positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def bind_protocol(self, proto):
"""Tries to bind given protocol to this peer.
Should only be called by `proto` trying to bind.
Once bound this protocol instance will be used to communicate with
peer. If another protocol is already bound, connection collision
resolution takes pla... | Tries to bind given protocol to this peer.
Should only be called by `proto` trying to bind.
Once bound this protocol instance will be used to communicate with
peer. If another protocol is already bound, connection collision
resolution takes place. |
def get_beam(header):
"""
Create a :class:`AegeanTools.fits_image.Beam` object from a fits header.
BPA may be missing but will be assumed to be zero.
if BMAJ or BMIN are missing then return None instead of a beam object.
Parameters
----------
header : HDUHeader
The fits header.
... | Create a :class:`AegeanTools.fits_image.Beam` object from a fits header.
BPA may be missing but will be assumed to be zero.
if BMAJ or BMIN are missing then return None instead of a beam object.
Parameters
----------
header : HDUHeader
The fits header.
Returns
-------
beam : ... |
def get_collaborator_permission(self, collaborator):
"""
:calls: `GET /repos/:owner/:repo/collaborators/:username/permission <http://developer.github.com/v3/repos/collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:rtype: string
"""
assert... | :calls: `GET /repos/:owner/:repo/collaborators/:username/permission <http://developer.github.com/v3/repos/collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:rtype: string |
def parse_channels(self):
"""Creates an array of Channel objects from the project"""
channels = []
for channel in self._project_dict["channels"]:
channels.append(Channel(channel, self._is_sixteen_bit, self._ignore_list))
return channels | Creates an array of Channel objects from the project |
def _doIdRes(self, message, endpoint, return_to):
"""Handle id_res responses that are not cancellations of
immediate mode requests.
@param message: the response paramaters.
@param endpoint: the discovered endpoint object. May be None.
@raises ProtocolError: If the message conte... | Handle id_res responses that are not cancellations of
immediate mode requests.
@param message: the response paramaters.
@param endpoint: the discovered endpoint object. May be None.
@raises ProtocolError: If the message contents are not
well-formed according to the OpenID s... |
def login(self):
"""
Perform cookie based user login.
"""
resp = super(CookieSession, self).request(
'POST',
self._session_url,
data={'name': self._username, 'password': self._password},
)
resp.raise_for_status() | Perform cookie based user login. |
def output_folder(self, value):
"""Output folder path for the rendering.
:param value: output folder path
:type value: str
"""
self._output_folder = value
if not os.path.exists(self._output_folder):
os.makedirs(self._output_folder) | Output folder path for the rendering.
:param value: output folder path
:type value: str |
def handle_api_exceptions(self, method, *url_parts, **kwargs):
"""Call REST API and handle exceptions
Params:
method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE'
url_parts: like in rest_api_url() method
api_ver: like in rest_api_url() method
kwargs: othe... | Call REST API and handle exceptions
Params:
method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE'
url_parts: like in rest_api_url() method
api_ver: like in rest_api_url() method
kwargs: other parameters passed to requests.request,
but the only nota... |
def to_file(self, filepath=None):
"""Writes Torrent object into file, either
:param filepath:
"""
if filepath is None and self._filepath is None:
raise TorrentError('Unable to save torrent to file: no filepath supplied.')
if filepath is not None:
self._f... | Writes Torrent object into file, either
:param filepath: |
def restore_used_registers(self):
"""Pops all used working registers after function call"""
used = self.used_registers_stack.pop()
self.used_registers = used[:]
used.sort(reverse = True)
for reg in used:
self.newline_text("POP \t%s" % SharedData.REGISTERS[reg], ... | Pops all used working registers after function call |
def _to_spans(x):
"""Convert a Candidate, Mention, or Span to a list of spans."""
if isinstance(x, Candidate):
return [_to_span(m) for m in x]
elif isinstance(x, Mention):
return [x.context]
elif isinstance(x, TemporarySpanMention):
return [x]
else:
raise ValueError(f... | Convert a Candidate, Mention, or Span to a list of spans. |
def ptb_producer(raw_data, batch_size, num_steps, name=None):
"""Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_... | Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_steps: int, the number of unrolls.
name: the name of this opera... |
def prepare_hmet_lsm(self, lsm_data_var_map_array,
hmet_ascii_output_folder=None,
netcdf_file_path=None):
"""
Prepares HMET data for GSSHA simulation from land surface model data.
Parameters:
lsm_data_var_map_array(str): Array with c... | Prepares HMET data for GSSHA simulation from land surface model data.
Parameters:
lsm_data_var_map_array(str): Array with connections for LSM output and GSSHA input. See: :func:`~gsshapy.grid.GRIDtoGSSHA.`
hmet_ascii_output_folder(Optional[str]): Path to diretory to output HMET ASCII fi... |
def _help_menu(self):
"""F1"""
if self.help_menu is False:
self.focus_pos_saved = self.top.body.focus_position
help_men = "\n".join(["{} - {}".format(i, j.__name__.strip('_'))
for i, j in self.keys.items() if j.__name__ !=
... | F1 |
def run_validators(new_data, old_data):
"""
Run through all matching validators.
:param new_data: New lint data.
:param old_data: Old lint data (before review)
:return:
"""
#{'validator_name': (success, score, message)}
validation_data = {}
for file_type, lint_data in list(new_data.... | Run through all matching validators.
:param new_data: New lint data.
:param old_data: Old lint data (before review)
:return: |
def is_early_compact_l2a(self):
"""Check if product is early version of compact L2A product
:return: True if product is early version of compact L2A product and False otherwise
:rtype: bool
"""
return self.data_source is DataSource.SENTINEL2_L2A and self.safe_type is EsaSafeType... | Check if product is early version of compact L2A product
:return: True if product is early version of compact L2A product and False otherwise
:rtype: bool |
def export_chat_invite_link(chat_id, **kwargs):
"""
Use this method to generate a new invite link for a chat; any previously generated link is revoked.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
:param chat_id: Unique identifier for the targ... | Use this method to generate a new invite link for a chat; any previously generated link is revoked.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
:param chat_id: Unique identifier for the target chat or username of the target channel (in the format @ch... |
def get_metric_values_response(self):
"""
Get the faked metrics, for all metric groups and all resources that
have been prepared on the manager object of this context object, as a
string in the format needed for the "Get Metrics" operation response.
Returns:
"MetricsR... | Get the faked metrics, for all metric groups and all resources that
have been prepared on the manager object of this context object, as a
string in the format needed for the "Get Metrics" operation response.
Returns:
"MetricsResponse" string as described for the "Get Metrics"
... |
def mouseReleaseEvent(self, event):
"""
Overloads the mouse release event to apply the current changes.
:param event | <QEvent>
"""
super(XGanttViewItem, self).mouseReleaseEvent(event)
if not self.flags() & self.ItemIsMovable:
r... | Overloads the mouse release event to apply the current changes.
:param event | <QEvent> |
def set_axis_color(axis, color, alpha=None):
"""Sets the spine color of all sides of an axis (top, right, bottom, left)."""
for side in ('top', 'right', 'bottom', 'left'):
spine = axis.spines[side]
spine.set_color(color)
if alpha is not None:
spine.set_alpha(alpha) | Sets the spine color of all sides of an axis (top, right, bottom, left). |
def password(message: Text,
default: Text = "",
validate: Union[Type[Validator],
Callable[[Text], bool],
None] = None, # noqa
qmark: Text = DEFAULT_QUESTION_PREFIX,
style: Optional[Style] = None,
... | Question the user to enter a secret text not displayed in the prompt.
This question type can be used to prompt the user for information
that should not be shown in the command line. The typed text will be
replaced with `*`.
Args:
message: Question text
default: Defau... |
def append(key, val, convert=False, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 0.17.0
Append a value to a list in the grains config file. If the grain doesn't
exist, the grain key is added and the value is appended to the new grain
as a list item.
key
The grain key to be ap... | .. versionadded:: 0.17.0
Append a value to a list in the grains config file. If the grain doesn't
exist, the grain key is added and the value is appended to the new grain
as a list item.
key
The grain key to be appended to
val
The value to append to the grain key
convert
... |
def imagetransformer_base_10l_16h_big_dr01_imgnet():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_base_14l_8h_big_dr01()
# num_hidden_layers
hparams.num_decoder_layers = 10
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.batch_size ... | big 1d model for conditional image generation. |
def format_name(self):
'''
Format the function name
'''
if not hasattr(self.module, '__func_alias__'):
# Resume normal sphinx.ext.autodoc operation
return super(FunctionDocumenter, self).format_name()
if not self.objpath:
# Resume normal sphin... | Format the function name |
def _get_events_list(object_key: str) -> List[str]:
"""Get list of event ids for the object with the specified key.
Args:
object_key (str): Key of an object in the database.
"""
return DB.get_list(_keys.events_list(object_key)) | Get list of event ids for the object with the specified key.
Args:
object_key (str): Key of an object in the database. |
def volume(self, volume):
"""See `volume`."""
# max 100
volume = int(volume)
self._volume = max(0, min(volume, 100)) | See `volume`. |
def _add_discovery_config(self):
"""Add the Discovery configuration to our list of configs.
This should only be called with self._config_lock. The code here assumes
the lock is held.
"""
lookup_key = (discovery_service.DiscoveryService.API_CONFIG['name'],
discovery_service.Discov... | Add the Discovery configuration to our list of configs.
This should only be called with self._config_lock. The code here assumes
the lock is held. |
def _pick_colours(self, palette_name, selected=False):
"""
Pick the rendering colour for a widget based on the current state.
:param palette_name: The stem name for the widget - e.g. "button".
:param selected: Whether this item is selected or not.
:returns: A colour tuple (fg, a... | Pick the rendering colour for a widget based on the current state.
:param palette_name: The stem name for the widget - e.g. "button".
:param selected: Whether this item is selected or not.
:returns: A colour tuple (fg, attr, bg) to be used. |
def creation_time(self, timeformat='unix'):
"""Returns the UTC time of creation of this station
:param timeformat: the format for the time value. May be:
'*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted
string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for... | Returns the UTC time of creation of this station
:param timeformat: the format for the time value. May be:
'*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted
string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for
a ``datetime.datetime`` object
:ty... |
def update_host_mapping(host_id, interface, nexus_ip, new_ch_grp):
"""Change channel_group in host/interface mapping data base."""
LOG.debug("update_host_mapping called")
session = bc.get_writer_session()
mapping = _lookup_one_host_mapping(
session=session,
host_id=h... | Change channel_group in host/interface mapping data base. |
def add_latlon_metadata(lat_var, lon_var):
"""Adds latitude and longitude metadata"""
lat_var.long_name = 'latitude'
lat_var.standard_name = 'latitude'
lat_var.units = 'degrees_north'
lat_var.axis = 'Y'
lon_var.long_name = 'longitude'
lon_var.standard_name = 'longitude'
lon_var.units = ... | Adds latitude and longitude metadata |
def _model_error_corr(self, catchment1, catchment2):
"""
Return model error correlation between subject catchment and other catchment.
Methodology source: Kjeldsen & Jones, 2009, table 3
:param catchment1: catchment to calculate error correlation with
:type catchment1: :class:`... | Return model error correlation between subject catchment and other catchment.
Methodology source: Kjeldsen & Jones, 2009, table 3
:param catchment1: catchment to calculate error correlation with
:type catchment1: :class:`Catchment`
:param catchment2: catchment to calculate error correl... |
def __crawler_start(self):
"""Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:... | Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:
`__crawler_stop()` and `_... |
def letter_scales(counts):
"""Convert letter counts to frequencies, sorted increasing."""
try:
scale = 1.0 / sum(counts.values())
except ZeroDivisionError:
# This logo is all gaps, nothing can be done
return []
freqs = [(aa, cnt*scale) for aa, cnt in counts.iteritems() if cnt]
... | Convert letter counts to frequencies, sorted increasing. |
def reload(self):
"""
Reloads the limits configuration from the database.
If an error occurs loading the configuration, an error-level
log message will be emitted. Additionally, the error message
will be added to the set specified by the 'redis.errors_key'
configuration... | Reloads the limits configuration from the database.
If an error occurs loading the configuration, an error-level
log message will be emitted. Additionally, the error message
will be added to the set specified by the 'redis.errors_key'
configuration ('errors' by default) and sent to the... |
def commit(self, **params):
"""
Rebuild kevent operations by removing open files that no longer need to
be watched, and adding new files if they are not currently being watched.
This is done by comparing self.paths to self.paths_open.
"""
log = self._getparam('log', self._di... | Rebuild kevent operations by removing open files that no longer need to
be watched, and adding new files if they are not currently being watched.
This is done by comparing self.paths to self.paths_open. |
def cigar_iter(self, reverse):
"""self.cigar => [(length, type) ... ] iterate the cigar
:param reverse: whether to iterate in the reverse direction (right-to-left)
:type reverse: boolean
:return a list of pairs of the type [(length, M/D) ..]
"""
l = 0
P = self.... | self.cigar => [(length, type) ... ] iterate the cigar
:param reverse: whether to iterate in the reverse direction (right-to-left)
:type reverse: boolean
:return a list of pairs of the type [(length, M/D) ..] |
def get_real_stored_key(self, session_key):
"""Return the real key name in redis storage
@return string
"""
prefix = settings.SESSION_REDIS_PREFIX
if not prefix:
return session_key
return ':'.join([prefix, session_key]) | Return the real key name in redis storage
@return string |
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None, ciphers=None, ssl_context=None,
ca_cert_dir=None):
"""
All arguments except for server_hostname, ssl_context, and ca_cert_dir ... | All arguments except for server_hostname, ssl_context, and ca_cert_dir have
the same meaning as they do when using :func:`ssl.wrap_socket`.
:param server_hostname:
When SNI is supported, the expected hostname of the certificate
:param ssl_context:
A pre-made :class:`SSLContext` object. If n... |
async def mail(self, sender, options=None):
"""
Sends a SMTP 'MAIL' command. - Starts the mail transfer session.
For further details, please check out `RFC 5321 § 4.1.1.2`_ and
`§ 3.3`_.
Args:
sender (str): Sender mailbox (used as reverse-path).
options ... | Sends a SMTP 'MAIL' command. - Starts the mail transfer session.
For further details, please check out `RFC 5321 § 4.1.1.2`_ and
`§ 3.3`_.
Args:
sender (str): Sender mailbox (used as reverse-path).
options (list of str or None, optional): Additional options to send
... |
def cumulative_density_at_times(self, times, label=None):
"""
Return a Pandas series of the predicted cumulative density function (1-survival function) at specific times.
Parameters
-----------
times: iterable or float
values to return the survival function at.
... | Return a Pandas series of the predicted cumulative density function (1-survival function) at specific times.
Parameters
-----------
times: iterable or float
values to return the survival function at.
label: string, optional
Rename the series returned. Useful for plot... |
def fit_circle_check(points,
scale,
prior=None,
final=False,
verbose=False):
"""
Fit a circle, and reject the fit if:
* the radius is larger than tol.radius_min*scale or tol.radius_max*scale
* any segment spans more than... | Fit a circle, and reject the fit if:
* the radius is larger than tol.radius_min*scale or tol.radius_max*scale
* any segment spans more than tol.seg_angle
* any segment is longer than tol.seg_frac*scale
* the fit deviates by more than tol.radius_frac*radius
* the segments on the ends deviate from tan... |
def get_lattice_quanta(self, convert_to_muC_per_cm2=True, all_in_polar=True):
"""
Returns the dipole / polarization quanta along a, b, and c for
all structures.
"""
lattices = [s.lattice for s in self.structures]
volumes = np.array([s.lattice.volume for s in self.structur... | Returns the dipole / polarization quanta along a, b, and c for
all structures. |
def init():
"""Initialize Yass in the current directory """
yass_conf = os.path.join(CWD, "yass.yml")
if os.path.isfile(yass_conf):
print("::ALERT::")
print("It seems like Yass is already initialized here.")
print("If it's a mistake, delete 'yass.yml' in this directory")
else:
... | Initialize Yass in the current directory |
def _ploadf(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
"""
output = _pload(ins.quad[2], 5)
output.extend(_fpush())
return output | Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer. |
def info_post(node_id):
"""Create an info.
The node id must be specified in the url.
You must pass contents as an argument.
info_type is an additional optional argument.
If info_type is a custom subclass of Info it must be
added to the known_classes of the experiment class.
"""
# get t... | Create an info.
The node id must be specified in the url.
You must pass contents as an argument.
info_type is an additional optional argument.
If info_type is a custom subclass of Info it must be
added to the known_classes of the experiment class. |
def get_block_entity_data(self, pos_or_x, y=None, z=None):
"""
Access block entity data.
Returns:
BlockEntityData subclass instance or
None if no block entity data is stored for that location.
"""
if None not in (y, z): # x y z supplied
pos_o... | Access block entity data.
Returns:
BlockEntityData subclass instance or
None if no block entity data is stored for that location. |
def has(self, relation, operator=">=", count=1, boolean="and", extra=None):
"""
Add a relationship count condition to the query.
:param relation: The relation to count
:type relation: str
:param operator: The operator
:type operator: str
:param count: The count... | Add a relationship count condition to the query.
:param relation: The relation to count
:type relation: str
:param operator: The operator
:type operator: str
:param count: The count
:type count: int
:param boolean: The boolean value
:type boolean: str
... |
def get_plugin_modules(plugins):
"""
Get plugin modules from input strings
:param tuple plugins: a tuple of plugin names in str
"""
if not plugins:
raise MissingPluginNames("input plugin names are required")
modules = []
for plugin in plugins:
short_name = PLUGIN_MAPPING.ge... | Get plugin modules from input strings
:param tuple plugins: a tuple of plugin names in str |
def clipline(x1, y1, x2, y2, xmin, ymin, xmax, ymax):
'Liang-Barsky algorithm, returns [xn1,yn1,xn2,yn2] of clipped line within given area, or None'
dx = x2-x1
dy = y2-y1
pq = [
(-dx, x1-xmin), # left
( dx, xmax-x1), # right
(-dy, y1-ymin), # bottom
( dy, ymax-y1), # ... | Liang-Barsky algorithm, returns [xn1,yn1,xn2,yn2] of clipped line within given area, or None |
def run(self):
"""A bit bulky atm..."""
self.close_connection = False
try:
while True:
self.started_response = False
self.status = ""
self.outheaders = []
self.sent_headers = False
self.chunked_write = False
self.write_buffer = StringIO.Strin... | A bit bulky atm... |
def remote_route(self):
""" A list of all IPs that were involved in this request, starting with
the client IP and followed by zero or more proxies. This does only
work if all proxies support the ```X-Forwarded-For`` header. Note
that this information can be forged by maliciou... | A list of all IPs that were involved in this request, starting with
the client IP and followed by zero or more proxies. This does only
work if all proxies support the ```X-Forwarded-For`` header. Note
that this information can be forged by malicious clients. |
def get_course_fs(self, courseid):
"""
:param courseid:
:return: a FileSystemProvider pointing to the directory of the course
"""
if not id_checker(courseid):
raise InvalidNameException("Course with invalid name: " + courseid)
return self._filesystem.from_su... | :param courseid:
:return: a FileSystemProvider pointing to the directory of the course |
def create_geometry(self, input_geometry, upper_depth, lower_depth):
'''
If geometry is defined as a numpy array then create instance of
nhlib.geo.polygon.Polygon class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (polygo... | If geometry is defined as a numpy array then create instance of
nhlib.geo.polygon.Polygon class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (polygon) as either
i) instance of nhlib.geo.polygon.Polygon class
ii) n... |
def set_deferred_transfer(self, enable):
"""
Allow transfers to be delayed and buffered
By default deferred transfers are turned off. All reads and
writes will be completed by the time the function returns.
When enabled packets are buffered and sent all at once, which
... | Allow transfers to be delayed and buffered
By default deferred transfers are turned off. All reads and
writes will be completed by the time the function returns.
When enabled packets are buffered and sent all at once, which
increases speed. When memory is written to, the transfer
... |
def init(self, only_mount=None, skip_mount=None, swallow_exceptions=True):
"""Generator that mounts this volume and either yields itself or recursively generates its subvolumes.
More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by
:func:`mou... | Generator that mounts this volume and either yields itself or recursively generates its subvolumes.
More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by
:func:`mount`, followed by a call to :func:`detect_mountpoint`, after which ``self`` is yielded,... |
def get_total_spatial_integral(self, z=None):
"""
Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z).
"""
... | Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).
needs to be implemented in subclasses.
:return: an array of values of the integral (same dimension as z). |
def output_results(results, metric, options):
"""
Output the results to stdout.
TODO: add AMPQ support for efficiency
"""
formatter = options['Formatter']
context = metric.copy() # XXX might need to sanitize this
try:
context['dimension'] = list(metric['Dimensions'].values())[0]
... | Output the results to stdout.
TODO: add AMPQ support for efficiency |
def get_groups(self, username):
"""Get all groups of a user"""
username = ldap.filter.escape_filter_chars(self._byte_p2(username))
userdn = self._get_user(username, NO_ATTR)
searchfilter = self.group_filter_tmpl % {
'userdn': userdn,
'username': username
... | Get all groups of a user |
def get_ilo_firmware_version_as_major_minor(self):
"""Gets the ilo firmware version for server capabilities
Parse the get_host_health_data() to retreive the firmware
details.
:param data: the output returned by get_host_health_data()
:returns: String with the format "<major>.<m... | Gets the ilo firmware version for server capabilities
Parse the get_host_health_data() to retreive the firmware
details.
:param data: the output returned by get_host_health_data()
:returns: String with the format "<major>.<minor>" or None. |
def gated_linear_unit_layer(x, name=None):
"""Gated linear unit layer.
Paper: Language Modeling with Gated Convolutional Networks.
Link: https://arxiv.org/abs/1612.08083
x = Wx * sigmoid(W'x).
Args:
x: A tensor
name: A string
Returns:
A tensor of the same shape as x.
"""
with tf.variable_... | Gated linear unit layer.
Paper: Language Modeling with Gated Convolutional Networks.
Link: https://arxiv.org/abs/1612.08083
x = Wx * sigmoid(W'x).
Args:
x: A tensor
name: A string
Returns:
A tensor of the same shape as x. |
def make_src_pkg(dest_dir, spec, sources, env=None, template=None, saltenv='base', runas='root'):
'''
Create a source rpm from the given spec file and sources
CLI Example:
.. code-block:: bash
salt '*' pkgbuild.make_src_pkg /var/www/html/
https://raw.githubusercontent.com/salt... | Create a source rpm from the given spec file and sources
CLI Example:
.. code-block:: bash
salt '*' pkgbuild.make_src_pkg /var/www/html/
https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/rpm/python-libnacl.spec
https://pypi.python.org/packages/source/l/lib... |
def _compile_expression(self,
expr: Expression,
scope: Dict[str, TensorFluent],
batch_size: Optional[int] = None,
noise: Optional[List[tf.Tensor]] = None) -> TensorFluent:
'''Compile the expression `e... | Compile the expression `expr` into a TensorFluent
in the given `scope` with optional batch size.
Args:
expr (:obj:`rddl2tf.expr.Expression`): A RDDL expression.
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.
batch_size (Optional[size]): The ba... |
def str2url(str):
"""
Takes a UTF-8 string and replaces all characters with the equivalent in 7-bit
ASCII. It returns a plain ASCII string usable in URLs.
"""
try:
str = str.encode('utf-8')
except:
pass
mfrom = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîï"
to = "AAAAAAECEEEEIIIIDNOOOOOOUUUUYSaaaaaaaceee... | Takes a UTF-8 string and replaces all characters with the equivalent in 7-bit
ASCII. It returns a plain ASCII string usable in URLs. |
def putlogo(figure=None):
"""Puts the CREDO logo at the bottom right of the current figure (or
the figure given by the ``figure`` argument if supplied).
"""
ip = get_ipython()
if figure is None:
figure=plt.gcf()
curraxis= figure.gca()
logoaxis = figure.add_axes([0.89, 0.01, 0.1, 0.1]... | Puts the CREDO logo at the bottom right of the current figure (or
the figure given by the ``figure`` argument if supplied). |
def receive_verify_post(self, post_params):
"""
Returns true if the incoming request is an authenticated verify post.
"""
if isinstance(post_params, dict):
required_params = ['action', 'email', 'send_id', 'sig']
if not self.check_for_valid_postback_actions(requir... | Returns true if the incoming request is an authenticated verify post. |
def create_fixed_rate_shipping(cls, fixed_rate_shipping, **kwargs):
"""Create FixedRateShipping
Create a new FixedRateShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_fixed_rate... | Create FixedRateShipping
Create a new FixedRateShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_fixed_rate_shipping(fixed_rate_shipping, async=True)
>>> result = thread.get()
... |
def __get_sentence(counts, sentence_id=None):
"""Let's fetch a random sentence that we then need to substitute bits of...
@
:param counts:
:param sentence_id:
"""
# First of all we need a cursor and a query to retrieve our ID's
cursor = CONN.cursor()
check_query = "select sen_id from su... | Let's fetch a random sentence that we then need to substitute bits of...
@
:param counts:
:param sentence_id: |
def run(self):
"""Run the main loop. Returns exit code."""
self.exit_code = 1
self.mainloop = GLib.MainLoop()
try:
future = ensure_future(self._start_async_tasks())
future.callbacks.append(self.set_exit_code)
self.mainloop.run()
return self... | Run the main loop. Returns exit code. |
def attempt_reauthorization(blink):
"""Attempt to refresh auth token and links."""
_LOGGER.info("Auth token expired, attempting reauthorization.")
headers = blink.get_auth_token(is_retry=True)
return headers | Attempt to refresh auth token and links. |
def serialize(self):
"""
Generates the messaging-type-related part of the message dictionary.
"""
if self.response is not None:
return {'messaging_type': 'RESPONSE'}
if self.update is not None:
return {'messaging_type': 'UPDATE'}
if self.tag is ... | Generates the messaging-type-related part of the message dictionary. |
def statsHandler(serverName, path=''):
"""Renders a GET request, by showing this nodes stats and children."""
path = path.lstrip('/')
parts = path.split('/')
if not parts[0]:
parts = parts[1:]
statDict = util.lookup(scales.getStats(), parts)
if statDict is None:
abort(404, 'No stats found with path... | Renders a GET request, by showing this nodes stats and children. |
def dumps(xs, model=None, properties=False, indent=True, **kwargs):
"""
Serialize Xmrs (or subclass) objects to PENMAN notation
Args:
xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize
model: Xmrs subclass used to get triples
properties: if `True`, enco... | Serialize Xmrs (or subclass) objects to PENMAN notation
Args:
xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize
model: Xmrs subclass used to get triples
properties: if `True`, encode variable properties
indent: if `True`, adaptively indent; if `False` ... |
def pixdump( source, start=None, end=None, length=None, width=64, height=None, palette=None ):
"""Print the contents of a byte string as a 256 colour image.
source
The byte string to print.
start
Start offset to read from (default: start)
end
End offset to stop reading at (def... | Print the contents of a byte string as a 256 colour image.
source
The byte string to print.
start
Start offset to read from (default: start)
end
End offset to stop reading at (default: end)
length
Length to read in (optional replacement for end)
width
Wid... |
def pad_or_truncate(
audio_reference,
audio_estimates
):
"""Pad or truncate estimates by duration of references:
- If reference > estimates: add zeros at the and of the estimated signal
- If estimates > references: truncate estimates to duration of references
Parameters
----------
refer... | Pad or truncate estimates by duration of references:
- If reference > estimates: add zeros at the and of the estimated signal
- If estimates > references: truncate estimates to duration of references
Parameters
----------
references : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing... |
def add_scm_info(self):
"""Adds SCM-related info."""
scm = get_scm()
if scm:
revision = scm.commit_id
branch = scm.branch_name or revision
else:
revision, branch = 'none', 'none'
self.add_infos(('revision', revision), ('branch', branch)) | Adds SCM-related info. |
def _rectForce(x,pot,t=0.):
"""
NAME:
_rectForce
PURPOSE:
returns the force in the rectangular frame
INPUT:
x - current position
t - current time
pot - (list of) Potential instance(s)
OUTPUT:
force
HISTORY:
2011-02-02 - Written - Bovy (NYU)
""... | NAME:
_rectForce
PURPOSE:
returns the force in the rectangular frame
INPUT:
x - current position
t - current time
pot - (list of) Potential instance(s)
OUTPUT:
force
HISTORY:
2011-02-02 - Written - Bovy (NYU) |
def fragment(self, fragment_size, mask=False):
"""
Fragment the frame into a chain of fragment frames:
- An initial frame with non-zero opcode
- Zero or more frames with opcode = 0 and final = False
- A final frame with opcode = 0 and final = True
The first and last fram... | Fragment the frame into a chain of fragment frames:
- An initial frame with non-zero opcode
- Zero or more frames with opcode = 0 and final = False
- A final frame with opcode = 0 and final = True
The first and last frame may be the same frame, having a non-zero
opcode and final... |
def nl_socket_alloc(cb=None):
"""Allocate new Netlink socket. Does not yet actually open a socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L206
Also has code for generating local port once.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L123
Keyword arguments:
... | Allocate new Netlink socket. Does not yet actually open a socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L206
Also has code for generating local port once.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L123
Keyword arguments:
cb -- custom callback handler.
... |
def move_to(x, y):
""" Sets the mouse's location to the specified coordinates. """
for b in _button_state:
if _button_state[b]:
e = Quartz.CGEventCreateMouseEvent(
None,
_button_mapping[b][3], # Drag Event
(x, y),
_button_mappin... | Sets the mouse's location to the specified coordinates. |
def readable_mem(mem):
"""
:param mem: An integer number of bytes to convert to human-readable form.
:return: A human-readable string representation of the number.
"""
for suffix in ["", "K", "M", "G", "T"]:
if mem < 10000:
return "{}{}".format(int(mem), suffix)
mem /= 10... | :param mem: An integer number of bytes to convert to human-readable form.
:return: A human-readable string representation of the number. |
def get_activities_by_ids(self, activity_ids):
"""Gets an ``ActivityList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
activities specified in the ``Id`` list, in the order of the
list, including duplicates, or an error results if an ``I... | Gets an ``ActivityList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
activities specified in the ``Id`` list, in the order of the
list, including duplicates, or an error results if an ``Id`` in
the supplied list is not found or inaccessi... |
def update_asset(self, asset_form=None):
"""Updates an existing asset.
arg: asset_form (osid.repository.AssetForm): the form
containing the elements to be updated
raise: IllegalState - ``asset_form`` already used in anupdate
transaction
raise: Invali... | Updates an existing asset.
arg: asset_form (osid.repository.AssetForm): the form
containing the elements to be updated
raise: IllegalState - ``asset_form`` already used in anupdate
transaction
raise: InvalidArgument - the form contains an invalid value
... |
def module_description_list(head):
"""Convert a ModuleDescription linked list to a Python list (and release the former).
"""
r = []
if head:
item = head
while item:
item = item.contents
r.append((item.name, item.shortname, item.longname, item.help))
it... | Convert a ModuleDescription linked list to a Python list (and release the former). |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._year is not None:
return Fal... | :rtype: bool |
def delete_files():
""" Delete one or more files from the server """
session_token = request.headers['session_token']
repository = request.headers['repository']
#===
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: r... | Delete one or more files from the server |
def raise_errors(self, response):
"""The innermost part - report errors by exceptions"""
# Errors: 400, 403 permissions or REQUEST_LIMIT_EXCEEDED, 404, 405, 415, 500)
# TODO extract a case ID for Salesforce support from code 500 messages
# TODO disabled 'debug_verbs' temporarily, after ... | The innermost part - report errors by exceptions |
def num_throats(self, labels='all', mode='union'):
r"""
Return the number of throats of the specified labels
Parameters
----------
labels : list of strings, optional
The throat labels that should be included in the count.
If not supplied, all throats are ... | r"""
Return the number of throats of the specified labels
Parameters
----------
labels : list of strings, optional
The throat labels that should be included in the count.
If not supplied, all throats are counted.
mode : string, optional
Speci... |
def process_slo(self, keep_local_session=False, request_id=None, delete_session_cb=None):
"""
Process the SAML Logout Response / Logout Request sent by the IdP.
:param keep_local_session: When false will destroy the local session, otherwise will destroy it
:type keep_local_session: bool... | Process the SAML Logout Response / Logout Request sent by the IdP.
:param keep_local_session: When false will destroy the local session, otherwise will destroy it
:type keep_local_session: bool
:param request_id: The ID of the LogoutRequest sent by this SP to the IdP
:type request_id: ... |
def stock2one(stock):
"""
convert stockholm to single line format
"""
lines = {}
for line in stock:
line = line.strip()
if print_line(line) is True:
yield line
continue
if line.startswith('//'):
continue
ID, seq = line.rsplit(' ', 1... | convert stockholm to single line format |
def load_snippets_html(cls, src_path, violation_lines):
"""
Load snippets from the file at `src_path` and format
them as HTML.
See `load_snippets()` for details.
"""
snippet_list = cls.load_snippets(src_path, violation_lines)
return [snippet.html() for snippet in... | Load snippets from the file at `src_path` and format
them as HTML.
See `load_snippets()` for details. |
def lsf(self, astr_path=""):
"""
List only the "files" in the astr_path.
:param astr_path: path to list
:return: "files" in astr_path, empty list if no files
"""
d_files = self.ls(astr_path, nodes=False, data=True)
l_files = d_files.ke... | List only the "files" in the astr_path.
:param astr_path: path to list
:return: "files" in astr_path, empty list if no files |
def presence_handler(type_, from_):
"""
Deprecated alias of :func:`.dispatcher.presence_handler`.
.. deprecated:: 0.9
"""
import aioxmpp.dispatcher
return aioxmpp.dispatcher.presence_handler(type_, from_) | Deprecated alias of :func:`.dispatcher.presence_handler`.
.. deprecated:: 0.9 |
def update_number(self, number, payload_number_modification, **kwargs): # noqa: E501
"""Assign number # noqa: E501
With this API call you will be able to assign a specific number to a specific account (one of your members). # noqa: E501
This method makes a synchronous HTTP request by default... | Assign number # noqa: E501
With this API call you will be able to assign a specific number to a specific account (one of your members). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.u... |
def call(self, folders, additional_fields, shape):
"""
Takes a folder ID and returns the full information for that folder.
:param folders: a list of Folder objects
:param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects
:param sha... | Takes a folder ID and returns the full information for that folder.
:param folders: a list of Folder objects
:param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects
:param shape: The set of attributes to return
:return: XML elements for t... |
def get_exitcode_reactor():
"""
This is only neccesary until a fix like the one outlined here is
implemented for Twisted:
http://twistedmatrix.com/trac/ticket/2182
"""
from twisted.internet.main import installReactor
from twisted.internet.selectreactor import SelectReactor
class Exi... | This is only neccesary until a fix like the one outlined here is
implemented for Twisted:
http://twistedmatrix.com/trac/ticket/2182 |
def bounds(sceneid):
"""
Retrieve image bounds.
Attributes
----------
sceneid : str
CBERS sceneid.
Returns
-------
out : dict
dictionary with image bounds.
"""
scene_params = _cbers_parse_scene_id(sceneid)
cbers_address = "{}/{}".format(CBERS_BUCKET, scene_... | Retrieve image bounds.
Attributes
----------
sceneid : str
CBERS sceneid.
Returns
-------
out : dict
dictionary with image bounds. |
def enter_cli_mode(self):
"""Check if at shell prompt root@ and go into CLI."""
delay_factor = self.select_delay_factor(delay_factor=0)
count = 0
cur_prompt = ""
while count < 50:
self.write_channel(self.RETURN)
time.sleep(0.1 * delay_factor)
c... | Check if at shell prompt root@ and go into CLI. |
def congiguration(self):
"""Manage slpkg configuration file
"""
options = [
"-g",
"--config"
]
command = [
"print",
"edit",
"reset"
]
conf = Config()
if (len(self.args) == 2 and self.args[0] in op... | Manage slpkg configuration file |
def emit_map(self, m, _, cache):
"""Emits array as per default JSON spec."""
self.emit_array_start(None)
self.marshal(MAP_AS_ARR, False, cache)
for k, v in m.items():
self.marshal(k, True, cache)
self.marshal(v, False, cache)
self.emit_array_end() | Emits array as per default JSON spec. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.