code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def template_statemgr_yaml(cl_args, zookeepers):
'''
Template statemgr.yaml
'''
statemgr_config_file_template = "%s/standalone/templates/statemgr.template.yaml" \
% cl_args["config_path"]
statemgr_config_file_actual = "%s/standalone/statemgr.yaml" % cl_args["config_path"]
... | Template statemgr.yaml |
def get_file_size(fileobj):
"""
Returns the size of a file-like object.
"""
currpos = fileobj.tell()
fileobj.seek(0, 2)
total_size = fileobj.tell()
fileobj.seek(currpos)
return total_size | Returns the size of a file-like object. |
def pool_context(*args, **kwargs):
""" Context manager for multiprocessing.Pool class (for compatibility with Python 2.7.x) """
pool = Pool(*args, **kwargs)
try:
yield pool
except Exception as e:
raise e
finally:
pool.terminate() | Context manager for multiprocessing.Pool class (for compatibility with Python 2.7.x) |
def dist_hamming(src, tar, diff_lens=True):
"""Return the normalized Hamming distance between two strings.
This is a wrapper for :py:meth:`Hamming.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
diff_lens : bool
... | Return the normalized Hamming distance between two strings.
This is a wrapper for :py:meth:`Hamming.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
diff_lens : bool
If True (default), this returns the Hamming di... |
def set_target(self, target: EventDispatcherBase) -> None:
"""
This method should be called by the event dispatcher that dispatches this event
to set its target property.
Args:
target (EventDispatcherBase): The event dispatcher that will dispatch this event.
... | This method should be called by the event dispatcher that dispatches this event
to set its target property.
Args:
target (EventDispatcherBase): The event dispatcher that will dispatch this event.
Raises:
PermissionError: If the target property of the event has al... |
def modify_conf(cfgfile, service_name, outfn):
"""Modify config file neutron and keystone to include enabler options."""
if not cfgfile or not outfn:
print('ERROR: There is no config file.')
sys.exit(0)
options = service_options[service_name]
with open(cfgfile, 'r') as cf:
line... | Modify config file neutron and keystone to include enabler options. |
def get_sample_times(self):
"""Return an Array containing the sample times.
"""
if self._epoch is None:
return Array(range(len(self))) * self._delta_t
else:
return Array(range(len(self))) * self._delta_t + float(self._epoch) | Return an Array containing the sample times. |
def run(self, data_dir=None):
"""
Note: this function will check the experiments directory for a
special file, scheduler.info, that details how often each
experiment should be run and the last time the experiment was
run. If the time since the experiment was run is shorter than
... | Note: this function will check the experiments directory for a
special file, scheduler.info, that details how often each
experiment should be run and the last time the experiment was
run. If the time since the experiment was run is shorter than
the scheduled interval in seconds, then the... |
def from_path(path: str, encoding: str = 'utf-8', **kwargs) -> BELGraph:
"""Load a BEL graph from a file resource. This function is a thin wrapper around :func:`from_lines`.
:param path: A file path
:param encoding: the encoding to use when reading this file. Is passed to :code:`codecs.open`. See the pytho... | Load a BEL graph from a file resource. This function is a thin wrapper around :func:`from_lines`.
:param path: A file path
:param encoding: the encoding to use when reading this file. Is passed to :code:`codecs.open`. See the python
`docs <https://docs.python.org/3/library/codecs.html#standard-encodings>`... |
def compute_bleu(reference_corpus, translation_corpus, max_order=4,
smooth=False):
"""Computes BLEU score of translated segments against one or more references.
Args:
reference_corpus: list of lists of references for each translation. Each
reference should be tokenized into a list of t... | Computes BLEU score of translated segments against one or more references.
Args:
reference_corpus: list of lists of references for each translation. Each
reference should be tokenized into a list of tokens.
translation_corpus: list of translations to score. Each translation
should be tokenize... |
def batch_means(x, f=lambda y: y, theta=.5, q=.95, burn=0):
"""
TODO: Use Bayesian CI.
Returns the half-width of the frequentist confidence interval
(q'th quantile) of the Monte Carlo estimate of E[f(x)].
:Parameters:
x : sequence
Sampled series. Must be a one-dimensional array... | TODO: Use Bayesian CI.
Returns the half-width of the frequentist confidence interval
(q'th quantile) of the Monte Carlo estimate of E[f(x)].
:Parameters:
x : sequence
Sampled series. Must be a one-dimensional array.
f : function
The MCSE of E[f(x)] will be computed.... |
def execute_api_request(self):
"""
Execute the request and return json data as a dict
:return: data dict
"""
if not self.auth.check_auth():
raise Exception('Authentification needed or API not available with your type of connection')
if self.auth.is_authentifie... | Execute the request and return json data as a dict
:return: data dict |
def reset_can(self, channel=Channel.CHANNEL_CH0, flags=ResetFlags.RESET_ALL):
"""
Resets a CAN channel of a device (hardware reset, empty buffer, and so on).
:param int channel: CAN channel, to be reset (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int flags: Flag... | Resets a CAN channel of a device (hardware reset, empty buffer, and so on).
:param int channel: CAN channel, to be reset (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int flags: Flags defines what should be reset (see enum :class:`ResetFlags`). |
def GET_getitemvalues(self) -> None:
"""Get the values of all |Variable| objects observed by the
current |GetItem| objects.
For |GetItem| objects observing time series,
|HydPyServer.GET_getitemvalues| returns only the values within
the current simulation period.
"""
... | Get the values of all |Variable| objects observed by the
current |GetItem| objects.
For |GetItem| objects observing time series,
|HydPyServer.GET_getitemvalues| returns only the values within
the current simulation period. |
def get_extrapolated_conductivity(temps, diffusivities, new_temp, structure,
species):
"""
Returns extrapolated mS/cm conductivity.
Args:
temps ([float]): A sequence of temperatures. units: K
diffusivities ([float]): A sequence of diffusivities (e.g.,
... | Returns extrapolated mS/cm conductivity.
Args:
temps ([float]): A sequence of temperatures. units: K
diffusivities ([float]): A sequence of diffusivities (e.g.,
from DiffusionAnalyzer.diffusivity). units: cm^2/s
new_temp (float): desired temperature. units: K
structure (... |
def update_meta_data_for_state_view(graphical_editor_view, state_v, affects_children=False, publish=True):
"""This method updates the meta data of a state view
:param graphical_editor_view: Graphical Editor view the change occurred in
:param state_v: The state view which has been changed/moved
:param a... | This method updates the meta data of a state view
:param graphical_editor_view: Graphical Editor view the change occurred in
:param state_v: The state view which has been changed/moved
:param affects_children: Whether the children of the state view have been resized or not
:param publish: Whether to pu... |
def read_pandas (self, format='table', **kwargs):
"""Read using :mod:`pandas`. The function ``pandas.read_FORMAT`` is called
where ``FORMAT`` is set from the argument *format*. *kwargs* are
passed to this function. Supported formats likely include
``clipboard``, ``csv``, ``excel``, ``fwf... | Read using :mod:`pandas`. The function ``pandas.read_FORMAT`` is called
where ``FORMAT`` is set from the argument *format*. *kwargs* are
passed to this function. Supported formats likely include
``clipboard``, ``csv``, ``excel``, ``fwf``, ``gbq``, ``html``,
``json``, ``msgpack``, ``pickl... |
def patch_wheel(in_wheel, patch_fname, out_wheel=None):
""" Apply ``-p1`` style patch in `patch_fname` to contents of `in_wheel`
If `out_wheel` is None (the default), overwrite the wheel `in_wheel`
in-place.
Parameters
----------
in_wheel : str
Filename of wheel to process
patch_fn... | Apply ``-p1`` style patch in `patch_fname` to contents of `in_wheel`
If `out_wheel` is None (the default), overwrite the wheel `in_wheel`
in-place.
Parameters
----------
in_wheel : str
Filename of wheel to process
patch_fname : str
Filename of patch file. Will be applied with ... |
def show_system_info_output_show_system_info_stack_mac(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_system_info = ET.Element("show_system_info")
config = show_system_info
output = ET.SubElement(show_system_info, "output")
show_sys... | Auto Generated Code |
def time_stops(self):
""" Valid time steps for this service as a list of datetime objects. """
if not self.supports_time:
return []
if self.service.calendar == 'standard':
units = self.service.time_interval_units
interval = self.service.time_interval
... | Valid time steps for this service as a list of datetime objects. |
def gene_id_of_associated_transcript(effect):
"""
Ensembl gene ID of transcript associated with effect, returns
None if effect does not have transcript.
"""
return apply_to_transcript_if_exists(
effect=effect,
fn=lambda t: t.gene_id,
default=None) | Ensembl gene ID of transcript associated with effect, returns
None if effect does not have transcript. |
def create_trace(
turn_activity: Activity,
name: str,
value: object = None,
value_type: str = None,
label: str = None,
) -> Activity:
"""Creates a trace activity based on this activity.
:param turn_activity:
:type turn_activity: Activity
:para... | Creates a trace activity based on this activity.
:param turn_activity:
:type turn_activity: Activity
:param name: The value to assign to the trace activity's <see cref="Activity.name"/> property.
:type name: str
:param value: The value to assign to the trace activity's <see cref... |
def or_(self, first_qe, *qes):
''' Add a $not expression to the query, negating the query expressions
given. The ``| operator`` on query expressions does the same thing
**Examples**: ``query.or_(SomeDocClass.age == 18, SomeDocClass.age == 17)`` becomes ``{'$or' : [{ 'age' : 18 }, { 'ag... | Add a $not expression to the query, negating the query expressions
given. The ``| operator`` on query expressions does the same thing
**Examples**: ``query.or_(SomeDocClass.age == 18, SomeDocClass.age == 17)`` becomes ``{'$or' : [{ 'age' : 18 }, { 'age' : 17 }]}``
:param query_exp... |
def claim_pep_node(self, node_namespace, *,
register_feature=True, notify=False):
"""
Claim node `node_namespace`.
:param node_namespace: the pubsub node whose events shall be
handled.
:param register_feature: Whether to publish the `node_namespace`
... | Claim node `node_namespace`.
:param node_namespace: the pubsub node whose events shall be
handled.
:param register_feature: Whether to publish the `node_namespace`
as feature.
:param notify: Whether to register the ``+notify`` feature to
receive notification ... |
def enable(profile='allprofiles'):
'''
.. versionadded:: 2015.5.0
Enable firewall profile
Args:
profile (Optional[str]): The name of the profile to enable. Default is
``allprofiles``. Valid options are:
- allprofiles
- domainprofile
- privatepro... | .. versionadded:: 2015.5.0
Enable firewall profile
Args:
profile (Optional[str]): The name of the profile to enable. Default is
``allprofiles``. Valid options are:
- allprofiles
- domainprofile
- privateprofile
- publicprofile
Returns:
... |
def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_message(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status")
config = logical_chassis_fwdl_status
output =... | Auto Generated Code |
def issue_funds(ctx, amount='uint256', rtgs_hash='bytes32', returns=STATUS):
"In the IOU fungible the supply is set by Issuer, who issue funds."
# allocate new issue as result of a new cash entry
ctx.accounts[ctx.msg_sender] += amount
ctx.issued_amounts[ctx.msg_sender] += amount
... | In the IOU fungible the supply is set by Issuer, who issue funds. |
def select_point(action, action_space, select_point_act, screen):
"""Select a unit at a point."""
select = spatial(action, action_space).unit_selection_point
screen.assign_to(select.selection_screen_coord)
select.type = select_point_act | Select a unit at a point. |
def patch(self, url, data=None, **kwargs):
""" Shorthand for self.oauth_request(url, 'patch')
:param str url: url to send patch oauth request to
:param dict data: patch data to update the service
:param kwargs: extra params to send to request api
:return: Response of the request... | Shorthand for self.oauth_request(url, 'patch')
:param str url: url to send patch oauth request to
:param dict data: patch data to update the service
:param kwargs: extra params to send to request api
:return: Response of the request
:rtype: requests.Response |
def dump_registers(cls, registers, arch = None):
"""
Dump the x86/x64 processor register values.
The output mimics that of the WinDBG debugger.
@type registers: dict( str S{->} int )
@param registers: Dictionary mapping register names to their values.
@type arch: str
... | Dump the x86/x64 processor register values.
The output mimics that of the WinDBG debugger.
@type registers: dict( str S{->} int )
@param registers: Dictionary mapping register names to their values.
@type arch: str
@param arch: Architecture of the machine whose registers were... |
def read_midc_raw_data_from_nrel(site, start, end):
"""Request and read MIDC data directly from the raw data api.
Parameters
----------
site: string
The MIDC station id.
start: datetime
Start date for requested data.
end: datetime
End date for requested data.
Return... | Request and read MIDC data directly from the raw data api.
Parameters
----------
site: string
The MIDC station id.
start: datetime
Start date for requested data.
end: datetime
End date for requested data.
Returns
-------
data:
Dataframe with DatetimeInde... |
def is_github_repo_owner_the_official_one(context, repo_owner):
"""Given a repo_owner, check if it matches the one configured to be the official one.
Args:
context (scriptworker.context.Context): the scriptworker context.
repo_owner (str): the repo_owner to verify
Raises:
scriptwor... | Given a repo_owner, check if it matches the one configured to be the official one.
Args:
context (scriptworker.context.Context): the scriptworker context.
repo_owner (str): the repo_owner to verify
Raises:
scriptworker.exceptions.ConfigError: when no official owner was defined
Ret... |
def Scale(self, factor):
"""Multiplies the xs by a factor.
factor: what to multiply by
"""
new = self.Copy()
new.xs = [x * factor for x in self.xs]
return new | Multiplies the xs by a factor.
factor: what to multiply by |
def login(self, email=None, password=None, user=None):
"""
Logs the user in and setups the header with the private token
:param email: Gitlab user Email
:param user: Gitlab username
:param password: Gitlab user password
:return: True if login successful
:raise: H... | Logs the user in and setups the header with the private token
:param email: Gitlab user Email
:param user: Gitlab username
:param password: Gitlab user password
:return: True if login successful
:raise: HttpError
:raise: ValueError |
def get_copyright_metadata(self):
"""Gets the metadata for the copyright.
return: (osid.Metadata) - metadata for the copyright
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template
... | Gets the metadata for the copyright.
return: (osid.Metadata) - metadata for the copyright
*compliance: mandatory -- This method must be implemented.* |
def download_file_by_name(url, target_folder, file_name, mkdir=False):
"""Download a file to a directory.
Args:
url: A string to a valid URL.
target_folder: Target folder for download (e.g. c:/ladybug)
file_name: File name (e.g. testPts.zip).
mkdir: Set to True to create the dir... | Download a file to a directory.
Args:
url: A string to a valid URL.
target_folder: Target folder for download (e.g. c:/ladybug)
file_name: File name (e.g. testPts.zip).
mkdir: Set to True to create the directory if doesn't exist (Default: False) |
def validate_properties_exist(self, classname, property_names):
"""Validate that the specified property names are indeed defined on the given class."""
schema_element = self.get_element_by_class_name(classname)
requested_properties = set(property_names)
available_properties = set(schema... | Validate that the specified property names are indeed defined on the given class. |
def _set_platform_specific_keyboard_shortcuts(self):
"""
QtDesigner does not support QKeySequence::StandardKey enum based default keyboard shortcuts.
This means that all default key combinations ("Save", "Quit", etc) have to be defined in code.
"""
self.action_new_phrase.setShort... | QtDesigner does not support QKeySequence::StandardKey enum based default keyboard shortcuts.
This means that all default key combinations ("Save", "Quit", etc) have to be defined in code. |
def hgetall(self, name):
"""
Returns all the fields and values in the Hash.
:param name: str the name of the redis key
:return: Future()
"""
with self.pipe as pipe:
f = Future()
res = pipe.hgetall(self.redis_key(name))
def cb():
... | Returns all the fields and values in the Hash.
:param name: str the name of the redis key
:return: Future() |
def _manual_lookup(self, facebook_id, facebook_id_string):
"""
People who we have not communicated with in a long time
will not appear in the look-ahead cache that Facebook keeps.
We must manually resolve them.
:param facebook_id: Profile ID of the user to lookup.
:retur... | People who we have not communicated with in a long time
will not appear in the look-ahead cache that Facebook keeps.
We must manually resolve them.
:param facebook_id: Profile ID of the user to lookup.
:return: |
def _cleanup(self):
"""Cleanup after extraction & analysis."""
self._expkg = None
self._extmp = None
self._flag_e = True
self._ifile.close() | Cleanup after extraction & analysis. |
def caldata(self, time):
''' Market open or not.
:param datetime time: 欲判斷的日期
:rtype: bool
:returns: True 為開市、False 為休市
'''
if time.date() in self.__ocdate['close']: # 判對是否為法定休市
return False
elif time.date() in self.__ocdate['open']: # 判... | Market open or not.
:param datetime time: 欲判斷的日期
:rtype: bool
:returns: True 為開市、False 為休市 |
def collect(self):
"""Collect the elements in an PRDD and concatenate the partition."""
# The order of the frame order appends is based on the implementation
# of reduce which calls our function with
# f(valueToBeAdded, accumulator) so we do our reduce implementation.
def append_... | Collect the elements in an PRDD and concatenate the partition. |
def OnMouseUp(self, event):
"""Generate a dropIndex.
Process: check self.IsInControl, check self.IsDrag, HitTest,
compare HitTest value
The mouse can end up in 5 different places:
Outside the Control
On itself
Above its starting point and on another item... | Generate a dropIndex.
Process: check self.IsInControl, check self.IsDrag, HitTest,
compare HitTest value
The mouse can end up in 5 different places:
Outside the Control
On itself
Above its starting point and on another item
Below its starting point and o... |
def do_shell(self, args):
"""Pass command to a system shell when line begins with '!'"""
if _debug: ConsoleCmd._debug("do_shell %r", args)
os.system(args) | Pass command to a system shell when line begins with '! |
def fanpower_watts(ddtt):
"""return fan power in bhp given the fan IDF object"""
from eppy.bunch_subclass import BadEPFieldError # here to prevent circular dependency
try:
fan_tot_eff = ddtt.Fan_Total_Efficiency # from V+ V8.7.0 onwards
except BadEPFieldError as e:
fan_tot_eff = ddtt.Fan... | return fan power in bhp given the fan IDF object |
def addattachments(message, template_path):
"""Add the attachments from the message from the commandline options."""
if 'attachment' not in message:
return message, 0
message = make_message_multipart(message)
attachment_filepaths = message.get_all('attachment', failobj=[])
template_parent_... | Add the attachments from the message from the commandline options. |
def protein_subsequences_around_mutations(effects, padding_around_mutation):
"""
From each effect get a mutant protein sequence and pull out a subsequence
around the mutation (based on the given padding). Returns a dictionary
of subsequences and a dictionary of subsequence start offsets.
"""
pro... | From each effect get a mutant protein sequence and pull out a subsequence
around the mutation (based on the given padding). Returns a dictionary
of subsequences and a dictionary of subsequence start offsets. |
def enterEvent(self, event):
"""
Reimplements the :meth:`QLabel.enterEvent` method.
:param event: QEvent.
:type event: QEvent
"""
if self.__checkable:
not self.__checked and self.setPixmap(self.__hover_pixmap)
else:
self.setPixmap(self.__... | Reimplements the :meth:`QLabel.enterEvent` method.
:param event: QEvent.
:type event: QEvent |
def flags(self, index):
"""Override Qt method"""
column = index.column()
if index.isValid():
if column in [C.COL_START, C.COL_END]:
# return Qt.ItemFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
return Qt.ItemFlags(Qt.ItemIsEnabled)
else:
... | Override Qt method |
def resolve_file_path_list(pathlist, workdir, prefix='',
randomize=False):
"""Resolve the path of each file name in the file ``pathlist`` and
write the updated paths to a new file.
"""
files = []
with open(pathlist, 'r') as f:
files = [line.strip() for line in f]
... | Resolve the path of each file name in the file ``pathlist`` and
write the updated paths to a new file. |
def fire_metric(metric_name, metric_value):
""" Fires a metric using the MetricsApiClient
"""
metric_value = float(metric_value)
metric = {metric_name: metric_value}
metric_client.fire_metrics(**metric)
return "Fired metric <{}> with value <{}>".format(metric_name, metric_value) | Fires a metric using the MetricsApiClient |
def EXP_gas(self, base, exponent):
"""Calculate extra gas fee"""
EXP_SUPPLEMENTAL_GAS = 10 # cost of EXP exponent per byte
def nbytes(e):
result = 0
for i in range(32):
result = Operators.ITEBV(512, Operators.EXTRACT(e, i * 8, 8) != 0, i + 1, result)
... | Calculate extra gas fee |
def _parse_alt_title(html_chunk):
"""
Parse title from alternative location if not found where it should be.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str: Book's title.
"""
title = html_chunk.find("img", fn=has_param("alt"))
i... | Parse title from alternative location if not found where it should be.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str: Book's title. |
def nice_number(number, thousands_separator=',', max_ndigits_after_dot=None):
"""Return nicely printed number NUMBER in language LN.
Return nicely printed number NUMBER in language LN using
given THOUSANDS_SEPARATOR character.
If max_ndigits_after_dot is specified and the number is float, the
numbe... | Return nicely printed number NUMBER in language LN.
Return nicely printed number NUMBER in language LN using
given THOUSANDS_SEPARATOR character.
If max_ndigits_after_dot is specified and the number is float, the
number is rounded by taking in consideration up to max_ndigits_after_dot
digit after t... |
def data_properties(data, mask=None, background=None):
"""
Calculate the morphological properties (and centroid) of a 2D array
(e.g. an image cutout of an object) using image moments.
Parameters
----------
data : array_like or `~astropy.units.Quantity`
The 2D array of the image.
ma... | Calculate the morphological properties (and centroid) of a 2D array
(e.g. an image cutout of an object) using image moments.
Parameters
----------
data : array_like or `~astropy.units.Quantity`
The 2D array of the image.
mask : array_like (bool), optional
A boolean mask, with the s... |
def set_video_crop(self, x1, y1, x2, y2):
"""
Args:
x1 (int): Top left x coordinate (px)
y1 (int): Top left y coordinate (px)
x2 (int): Bottom right x coordinate (px)
y2 (int): Bottom right y coordinate (px)
"""
crop = "%s %s %s %s" % (str(... | Args:
x1 (int): Top left x coordinate (px)
y1 (int): Top left y coordinate (px)
x2 (int): Bottom right x coordinate (px)
y2 (int): Bottom right y coordinate (px) |
def gaussian_gradient_magnitude(image, sigma = 5, voxelspacing = None, mask = slice(None)):
r"""
Computes the gradient magnitude (edge-detection) of the supplied image using gaussian
derivates and returns the intensity values.
Optionally a binary mask can be supplied to select the voxels for which ... | r"""
Computes the gradient magnitude (edge-detection) of the supplied image using gaussian
derivates and returns the intensity values.
Optionally a binary mask can be supplied to select the voxels for which the feature
should be extracted.
Parameters
----------
image : array_like o... |
def param_map_rc_encode(self, target_system, target_component, param_id, param_index, parameter_rc_channel_index, param_value0, scale, param_value_min, param_value_max):
'''
Bind a RC channel to a parameter. The parameter should change accoding
to the RC channel value.
... | Bind a RC channel to a parameter. The parameter should change accoding
to the RC channel value.
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
param_id : Onboard parameter id, terminated... |
def transmute_sites( self, old_site_label, new_site_label, n_sites_to_change ):
"""
Selects a random subset of sites with a specific label and gives them a different label.
Args:
old_site_label (String or List(String)): Site label(s) of the sites to be modified..
new_sit... | Selects a random subset of sites with a specific label and gives them a different label.
Args:
old_site_label (String or List(String)): Site label(s) of the sites to be modified..
new_site_label (String): Site label to be applied to the modified sites.
n_site... |
def predict(self, x, distributed=True):
"""
Use a model to do prediction.
# Arguments
x: Input data. A Numpy array or RDD of Sample.
distributed: Boolean. Whether to do prediction in distributed mode or local mode.
Default is True. In local mode, x must be a... | Use a model to do prediction.
# Arguments
x: Input data. A Numpy array or RDD of Sample.
distributed: Boolean. Whether to do prediction in distributed mode or local mode.
Default is True. In local mode, x must be a Numpy array. |
def make_graph(pkg):
"""Returns a dictionary of information about pkg & its recursive deps.
Given a string, which can be parsed as a requirement specifier, return a
dictionary where each key is the name of pkg or one of its recursive
dependencies, and each value is a dictionary returned by research_pac... | Returns a dictionary of information about pkg & its recursive deps.
Given a string, which can be parsed as a requirement specifier, return a
dictionary where each key is the name of pkg or one of its recursive
dependencies, and each value is a dictionary returned by research_package.
(No, it's not real... |
def start(self, ccallbacks=None):
"""Establish and maintain connections."""
self.__manage_g = gevent.spawn(self.__manage_connections, ccallbacks)
self.__ready_ev.wait() | Establish and maintain connections. |
def add_resolved_requirements(self, reqs, platforms=None):
"""Multi-platform dependency resolution for PEX files.
:param builder: Dump the requirements into this builder.
:param interpreter: The :class:`PythonInterpreter` to resolve requirements for.
:param reqs: A list of :class:`PythonRequirement` to... | Multi-platform dependency resolution for PEX files.
:param builder: Dump the requirements into this builder.
:param interpreter: The :class:`PythonInterpreter` to resolve requirements for.
:param reqs: A list of :class:`PythonRequirement` to resolve.
:param log: Use this logger.
:param platforms: A... |
def get_code(self, *args, **kwargs):
"""
get the python source code from callback
"""
# FIXME: Honestly should allow multiple commands
callback = self._commands[args[0]]
# TODO: syntax color would be nice
source = _inspect.getsourcelines(callback)[0]
"""
source_len = len(source)
... | get the python source code from callback |
def _check_table(self):
"""Ensure that an incorrect table doesn't exist
If a bad (old) table does exist, return False
"""
cursor = self._db.execute("PRAGMA table_info(%s)"%self.table)
lines = cursor.fetchall()
if not lines:
# table does not exist
... | Ensure that an incorrect table doesn't exist
If a bad (old) table does exist, return False |
def db_type(self, connection):
"""
The type of the field to insert into the database.
"""
conn_module = type(connection).__module__
if "mysql" in conn_module:
return "bigint AUTO_INCREMENT"
elif "postgres" in conn_module:
return "bigserial"
... | The type of the field to insert into the database. |
def build(self):
"""Only build and create Slackware package
"""
pkg_security([self.name])
self.error_uns()
if self.FAULT:
print("")
self.msg.template(78)
print("| Package {0} {1} {2} {3}".format(self.prgnam, self.red,
... | Only build and create Slackware package |
def detect_voice(self, prob_detect_voice=0.5):
"""
Returns self as a list of tuples:
[('v', voiced segment), ('u', unvoiced segment), (etc.)]
The overall order of the AudioSegment is preserved.
:param prob_detect_voice: The raw probability that any random 20ms window of the aud... | Returns self as a list of tuples:
[('v', voiced segment), ('u', unvoiced segment), (etc.)]
The overall order of the AudioSegment is preserved.
:param prob_detect_voice: The raw probability that any random 20ms window of the audio file
contains voice.
:... |
def redis_key(cls, key):
"""
Get the key we pass to redis.
If no namespace is declared, it will use the class name.
:param key: str the name of the redis key
:return: str
"""
keyspace = cls.keyspace
tpl = cls.keyspace_template
key = "%s" % key... | Get the key we pass to redis.
If no namespace is declared, it will use the class name.
:param key: str the name of the redis key
:return: str |
def previous(self, day_of_week=None):
"""
Modify to the previous occurrence of a given day of the week.
If no day_of_week is provided, modify to the previous occurrence
of the current day of the week. Use the supplied consts
to indicate the desired day_of_week, ex. pendulum.MOND... | Modify to the previous occurrence of a given day of the week.
If no day_of_week is provided, modify to the previous occurrence
of the current day of the week. Use the supplied consts
to indicate the desired day_of_week, ex. pendulum.MONDAY.
:param day_of_week: The previous day of week ... |
def cropped(self, t0, t1):
"""returns a cropped copy of this segment which starts at
self.point(t0) and ends at self.point(t1)."""
if abs(self.delta*(t1 - t0)) <= 180:
new_large_arc = 0
else:
new_large_arc = 1
return Arc(self.point(t0), radius=self.radius,... | returns a cropped copy of this segment which starts at
self.point(t0) and ends at self.point(t1). |
def add_name(self, tax_id, tax_name, source_name=None, source_id=None,
name_class='synonym', is_primary=False, is_classified=None,
execute=True, **ignored):
"""Add a record to the names table corresponding to
``tax_id``. Arguments are as follows:
- tax_id (str... | Add a record to the names table corresponding to
``tax_id``. Arguments are as follows:
- tax_id (string, required)
- tax_name (string, required)
*one* of the following are required:
- source_id (int or string coercable to int)
- source_name (string)
``source_i... |
def play(self, sgffile):
"Play a game"
global verbose
if verbose >= 1:
print "Setting boardsize and komi for black\n"
self.blackplayer.boardsize(self.size)
self.blackplayer.komi(self.komi)
if verbose >= 1:
print "Setting boardsize and komi for wh... | Play a game |
def apply_range_set(self, hist: Hist) -> None:
""" Apply the associated range set to the axis of a given hist.
Note:
The min and max values should be bins, not user ranges! For more, see the binning
explanation in ``apply_func_to_find_bin(...)``.
Args:
hist:... | Apply the associated range set to the axis of a given hist.
Note:
The min and max values should be bins, not user ranges! For more, see the binning
explanation in ``apply_func_to_find_bin(...)``.
Args:
hist: Histogram to which the axis range restriction should be ap... |
def _get_support_sound_mode(self):
"""
Get if sound mode is supported from device.
Method executes the method for the current receiver type.
"""
if self._receiver_type == AVR_X_2016.type:
return self._get_support_sound_mode_avr_2016()
else:
return... | Get if sound mode is supported from device.
Method executes the method for the current receiver type. |
def delete_lambda_deprecated(awsclient, function_name, s3_event_sources=[],
time_event_sources=[], delete_logs=False):
# FIXME: mutable default arguments!
"""Deprecated: please use delete_lambda!
:param awsclient:
:param function_name:
:param s3_event_sources:
:para... | Deprecated: please use delete_lambda!
:param awsclient:
:param function_name:
:param s3_event_sources:
:param time_event_sources:
:param delete_logs:
:return: exit_code |
def gblocks(self,
new_path = None,
seq_type = 'nucl' or 'prot'):
"""Apply the gblocks filtering algorithm to the alignment.
See http://molevol.cmima.csic.es/castresana/Gblocks/Gblocks_documentation.html
Need to rename all sequences, because it will complain with l... | Apply the gblocks filtering algorithm to the alignment.
See http://molevol.cmima.csic.es/castresana/Gblocks/Gblocks_documentation.html
Need to rename all sequences, because it will complain with long names. |
def next(self):
"""
Handles the iteration by pulling the next line out of the stream,
attempting to convert the response to JSON if necessary.
:returns: Data representing what was seen in the feed
"""
while True:
if not self._resp:
self._start... | Handles the iteration by pulling the next line out of the stream,
attempting to convert the response to JSON if necessary.
:returns: Data representing what was seen in the feed |
def getobjectsize(self, window_name, object_name=None):
"""
Get object size
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
... | Get object size
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
LDTP's name convention, or a Unix glob. Or menu heirarchy
@type... |
def revert(self, revision_id):
"""Revert the record to a specific revision.
#. Send a signal :data:`invenio_records.signals.before_record_revert`
with the current record as parameter.
#. Revert the record to the revision id passed as parameter.
#. Send a signal :data:`inven... | Revert the record to a specific revision.
#. Send a signal :data:`invenio_records.signals.before_record_revert`
with the current record as parameter.
#. Revert the record to the revision id passed as parameter.
#. Send a signal :data:`invenio_records.signals.after_record_revert`
... |
def potential_from_grid(self, grid):
"""
Calculate the potential at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
"""
poten... | Calculate the potential at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on. |
def add(self, labels, value):
"""Add adds a single observation to the summary."""
if type(value) not in (float, int):
raise TypeError("Summary only works with digits (int, float)")
# We have already a lock for data but not for the estimator
with mutex:
try:
... | Add adds a single observation to the summary. |
def solution_to_array(solution, events, slots):
"""Convert a schedule from solution to array form
Parameters
----------
solution : list or tuple
of tuples of event index and slot index for each scheduled item
events : list or tuple
of :py:class:`resources.Event` instances
slots ... | Convert a schedule from solution to array form
Parameters
----------
solution : list or tuple
of tuples of event index and slot index for each scheduled item
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` i... |
def amplification_type(self, channels=None):
"""
Get the amplification type used for the specified channel(s).
Each channel uses one of two amplification types: linear or
logarithmic. This function returns, for each channel, a tuple of
two numbers, in which the first number indi... | Get the amplification type used for the specified channel(s).
Each channel uses one of two amplification types: linear or
logarithmic. This function returns, for each channel, a tuple of
two numbers, in which the first number indicates the number of
decades covered by the logarithmic am... |
def get_stats_item(self, item):
"""Return the stats object for a specific item in JSON format.
Stats should be a list of dict (processlist, network...)
"""
if isinstance(self.stats, dict):
try:
return self._json_dumps({item: self.stats[item]})
exc... | Return the stats object for a specific item in JSON format.
Stats should be a list of dict (processlist, network...) |
def print_table(self, stream=sys.stdout, filter_function=None):
"""
A pretty ASCII printer for the periodic table, based on some filter_function.
Args:
stream: file-like object
filter_function:
A filtering function that take a Pseudo as input and returns ... | A pretty ASCII printer for the periodic table, based on some filter_function.
Args:
stream: file-like object
filter_function:
A filtering function that take a Pseudo as input and returns a boolean.
For example, setting filter_function = lambda p: p.Z_val ... |
def bfs(self, root = None, display = None):
'''
API: bfs(self, root = None, display = None)
Description:
Searches tree starting from node named root using breadth-first
strategy if root argument is provided. Starts search from root node
of the tree otherwise.
... | API: bfs(self, root = None, display = None)
Description:
Searches tree starting from node named root using breadth-first
strategy if root argument is provided. Starts search from root node
of the tree otherwise.
Pre:
Node indicated by root argument should ... |
def _mb_model(self, beta, mini_batch):
""" Creates the structure of the model (model matrices etc) for mini batch model
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for the latent variables
mini_batch : int
Mini batch si... | Creates the structure of the model (model matrices etc) for mini batch model
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for the latent variables
mini_batch : int
Mini batch size for the data sampling
Returns
-... |
def iter_node(node, name='', unknown=None,
# Runtime optimization
list=list, getattr=getattr, isinstance=isinstance,
enumerate=enumerate, missing=NonExistent):
"""Iterates over an object:
- If the object has a _fields attribute,
it gets attributes in the or... | Iterates over an object:
- If the object has a _fields attribute,
it gets attributes in the order of this
and returns name, value pairs.
- Otherwise, if the object is a list instance,
it returns name, value pairs for each item
in the list, where the name is passed int... |
def name(self):
"""The process name."""
name = self._platform_impl.get_process_name()
if os.name == 'posix':
# On UNIX the name gets truncated to the first 15 characters.
# If it matches the first part of the cmdline we return that
# one instead because it's u... | The process name. |
def create_api_handler(self):
""" Creates an api handler and sets it on self """
try:
self.github = github3.login(username=config.data['gh_user'],
password=config.data['gh_password'])
except KeyError as e:
raise config.NotConfigured(e)
... | Creates an api handler and sets it on self |
def _find_free_location(self, free_locations, required_sectors=1, preferred=None):
"""
Given a list of booleans, find a list of <required_sectors> consecutive True values.
If no such list is found, return length(free_locations).
Assumes first two values are always False.
"""
... | Given a list of booleans, find a list of <required_sectors> consecutive True values.
If no such list is found, return length(free_locations).
Assumes first two values are always False. |
def on_path(self, new):
""" Handle the file path changing.
"""
self.name = basename(new)
self.graph = self.editor_input.load() | Handle the file path changing. |
def rpc_call(self, request, method=None, **payload):
""" Call REST API with RPC force.
return object: a result
"""
if not method or self.separator not in method:
raise AssertionError("Wrong method name: {0}".format(method))
resource_name, method = method.split(self... | Call REST API with RPC force.
return object: a result |
def merge_dicts(*dict_list):
"""Extract all of the dictionaries from this list, then merge them together """
# if not isinstance(dict_list, list):
# raise TypeError("dict_list is not a list. Please try again")
# print(dict_list)
all_dicts = []
for ag in dict_list:
if isinstance(ag, d... | Extract all of the dictionaries from this list, then merge them together |
def copy_files(self):
""" Copy the LICENSE and CONTRIBUTING files to each folder repo
Generate covers if needed. Dump the metadata.
"""
files = [u'LICENSE', u'CONTRIBUTING.rst']
this_dir = dirname(abspath(__file__))
for _file in files:
sh.cp(
... | Copy the LICENSE and CONTRIBUTING files to each folder repo
Generate covers if needed. Dump the metadata. |
def decode_nibbles(value):
"""
The inverse of the Hex Prefix function
"""
nibbles_with_flag = bytes_to_nibbles(value)
flag = nibbles_with_flag[0]
needs_terminator = flag in {HP_FLAG_2, HP_FLAG_2 + 1}
is_odd_length = flag in {HP_FLAG_0 + 1, HP_FLAG_2 + 1}
if is_odd_length:
raw_n... | The inverse of the Hex Prefix function |
def notify_created(room, event, user):
"""Notifies about the creation of a chatroom.
:param room: the chatroom
:param event: the event
:param user: the user performing the action
"""
tpl = get_plugin_template_module('emails/created.txt', chatroom=room, event=event, user=user)
_send(event, t... | Notifies about the creation of a chatroom.
:param room: the chatroom
:param event: the event
:param user: the user performing the action |
def validate_deprecation_semver(version_string, version_description):
"""Validates that version_string is a valid semver.
If so, returns that semver. Raises an error otherwise.
:param str version_string: A pantsbuild.pants version which affects some deprecated entity.
:param str version_description: A string... | Validates that version_string is a valid semver.
If so, returns that semver. Raises an error otherwise.
:param str version_string: A pantsbuild.pants version which affects some deprecated entity.
:param str version_description: A string used in exception messages to describe what the
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.