code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _parse_welcome(client, command, actor, args):
"""Parse a WELCOME and update user state, then dispatch a WELCOME event."""
_, _, hostmask = args.rpartition(' ')
client.user.update_from_hostmask(hostmask)
client.dispatch_event("WELCOME", hostmask) | Parse a WELCOME and update user state, then dispatch a WELCOME event. |
def _set_ownership(self):
"""
set ownership of the directory: user and group
:return: None
"""
if self.owner or self.group:
args = (
self.path,
self.owner if self.owner else -1,
self.group if self.group else -1,
... | set ownership of the directory: user and group
:return: None |
def abu_chart(self, cycle, mass_range=None ,ilabel=True,
imlabel=True, imlabel_fontsize=8, imagic=False,
boxstable=True, lbound=(-12, 0),
plotaxis=[0, 0, 0, 0], show=True, color_map='jet',
ifig=None,data_provided=False,thedata=None,
... | Plots an abundance chart
Parameters
----------
cycle : string, integer or list
The cycle we are looking in. If it is a list of cycles,
this method will then do a plot for each of these cycles
and save them all to a file.
mass_range : list, optional
... |
def linkage_group_ordering(linkage_records):
"""Convert degenerate linkage records into ordered info_frags-like records
for comparison purposes.
Simple example:
>>> linkage_records = [
... ['linkage_group_1', 31842, 94039, 'sctg_207'],
... ['linkage_group_1', 95303, 95303, 'sctg_20... | Convert degenerate linkage records into ordered info_frags-like records
for comparison purposes.
Simple example:
>>> linkage_records = [
... ['linkage_group_1', 31842, 94039, 'sctg_207'],
... ['linkage_group_1', 95303, 95303, 'sctg_207'],
... ['linkage_group_2', 15892, 25865, '... |
def _language_to_voice_code(self, language):
"""
Translate a language value to a voice code.
If you want to mock support for a language
by using a voice for a similar language,
please add it to the ``LANGUAGE_TO_VOICE_CODE`` dictionary.
:param language: the requested la... | Translate a language value to a voice code.
If you want to mock support for a language
by using a voice for a similar language,
please add it to the ``LANGUAGE_TO_VOICE_CODE`` dictionary.
:param language: the requested language
:type language: :class:`~aeneas.language.Language... |
def get_memory_usage(self):
"""
Get data about the virtual memory usage of the holder.
:returns: Memory usage data
:rtype: dict
Example:
>>> holder.get_memory_usage()
>>> {
>>> 'nb_arrays': 12, # The holder contains the v... | Get data about the virtual memory usage of the holder.
:returns: Memory usage data
:rtype: dict
Example:
>>> holder.get_memory_usage()
>>> {
>>> 'nb_arrays': 12, # The holder contains the variable values for 12 different periods
... |
def dict_value_hint(key, mapper=None):
"""Returns a function that takes a dictionary and returns value of
particular key. The returned value can be optionally processed by `mapper`
function.
To be used as a type hint in :class:`OneOf`.
"""
if mapper is None:
mapper = identity
def h... | Returns a function that takes a dictionary and returns value of
particular key. The returned value can be optionally processed by `mapper`
function.
To be used as a type hint in :class:`OneOf`. |
def check_missing_references(client):
"""Find missing references."""
from renku.models.refs import LinkReference
missing = [
ref for ref in LinkReference.iter_items(client)
if not ref.reference.exists()
]
if not missing:
return True
click.secho(
WARNING + 'Ther... | Find missing references. |
def sel_entries(self):
"""Generator which returns all SEL entries."""
ENTIRE_RECORD = 0xff
rsp = self.send_message_with_name('GetSelInfo')
if rsp.entries == 0:
return
reservation_id = self.get_sel_reservation_id()
next_record_id = 0
while True:
... | Generator which returns all SEL entries. |
def options(self, request, *args, **kwargs):
"""
Implements a OPTIONS HTTP method function returning all allowed HTTP
methods.
"""
allow = []
for method in self.http_method_names:
if hasattr(self, method):
allow.append(method.upper())
r... | Implements a OPTIONS HTTP method function returning all allowed HTTP
methods. |
def location(self):
"""
Returns a ``string`` constant to indicate whether the game was played
at the team's home venue, the opponent's venue, or at a neutral site.
"""
if self._location == '':
return HOME
if self._location == 'N':
return NEUTRAL
... | Returns a ``string`` constant to indicate whether the game was played
at the team's home venue, the opponent's venue, or at a neutral site. |
def save(self, path):
"""Dump the class data in the format of a .netrc file."""
rep = ""
for host in self.hosts.keys():
attrs = self.hosts[host]
rep = rep + "machine " + host + "\n\tlogin " \
+ six.text_type(attrs[0]) + "\n"
if attrs[1]:
... | Dump the class data in the format of a .netrc file. |
def write_taxon_info(taxon, include_anc, output):
"""Writes out data from `taxon` to the `output` stream to demonstrate
the attributes of a taxon object.
(currently some lines are commented out until the web-services call returns more info. See:
https://github.com/OpenTreeOfLife/taxomachine/issues/8... | Writes out data from `taxon` to the `output` stream to demonstrate
the attributes of a taxon object.
(currently some lines are commented out until the web-services call returns more info. See:
https://github.com/OpenTreeOfLife/taxomachine/issues/85
).
If `include_anc` is True, then ancestor info... |
def cached(fun):
"""
memoizing decorator for linkage functions.
Parameters have been hardcoded (no ``*args``, ``**kwargs`` magic), because,
the way this is coded (interchangingly using sets and frozensets) is true
for this specific case. For other cases that is not necessarily guaranteed.
"""
... | memoizing decorator for linkage functions.
Parameters have been hardcoded (no ``*args``, ``**kwargs`` magic), because,
the way this is coded (interchangingly using sets and frozensets) is true
for this specific case. For other cases that is not necessarily guaranteed. |
def from_requirement(cls, req, changes=None):
""" Create an instance from :class:`pkg_resources.Requirement` instance """
return cls(req.project_name, req.specs and ''.join(req.specs[0]) or '', changes=changes) | Create an instance from :class:`pkg_resources.Requirement` instance |
def toggle_show_cd_only(self, checked):
"""Toggle show current directory only mode"""
self.parent_widget.sig_option_changed.emit('show_cd_only', checked)
self.show_cd_only = checked
if checked:
if self.__last_folder is not None:
self.set_current_folder(s... | Toggle show current directory only mode |
def __add_bank(self, account_id, **kwargs):
"""Call documentation: `/account/add_bank
<https://www.wepay.com/developer/reference/account-2011-01-15#add_bank>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token... | Call documentation: `/account/add_bank
<https://www.wepay.com/developer/reference/account-2011-01-15#add_bank>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
... |
def any_ends_with(self, string_list, pattern):
"""Returns true iff one of the strings in string_list ends in
pattern."""
try:
s_base = basestring
except:
s_base = str
is_string = isinstance(pattern, s_base)
if not is_string:
return Fal... | Returns true iff one of the strings in string_list ends in
pattern. |
def incr_obj(obj, **attrs):
"""Increments context variables
"""
for name, value in attrs.iteritems():
v = getattr(obj, name, None)
if not hasattr(obj, name) or v is None:
v = 0
setattr(obj, name, v + value) | Increments context variables |
def _merge_wf_inputs(new, out, wf_outputs, to_ignore, parallel, nested_inputs):
"""Merge inputs for a sub-workflow, adding any not present inputs in out.
Skips inputs that are internally generated or generated and ignored, keeping
only as inputs those that we do not generate internally.
"""
interna... | Merge inputs for a sub-workflow, adding any not present inputs in out.
Skips inputs that are internally generated or generated and ignored, keeping
only as inputs those that we do not generate internally. |
def update(self, device_json=None, info_json=None, settings_json=None,
avatar_json=None):
"""Update the internal device json data."""
if device_json:
UTILS.update(self._device_json, device_json)
if avatar_json:
UTILS.update(self._avatar_json, avatar_json)
... | Update the internal device json data. |
def gammaVectorRDD(sc, shape, scale, numRows, numCols, numPartitions=None, seed=None):
"""
Generates an RDD comprised of vectors containing i.i.d. samples drawn
from the Gamma distribution.
:param sc: SparkContext used to create the RDD.
:param shape: Shape (> 0) of the Gamma di... | Generates an RDD comprised of vectors containing i.i.d. samples drawn
from the Gamma distribution.
:param sc: SparkContext used to create the RDD.
:param shape: Shape (> 0) of the Gamma distribution
:param scale: Scale (> 0) of the Gamma distribution
:param numRows: Number of Ve... |
def validate_realms(self, client_key, token, request, uri=None,
realms=None):
"""Check if the token has permission on those realms."""
log.debug('Validate realms %r for %r', realms, client_key)
if request.access_token:
tok = request.access_token
else:
... | Check if the token has permission on those realms. |
def build(self, builder):
"""
Build this element
:param builder:
:return:
"""
builder.start(self.__class__.__name__)
builder.data(self.country_code)
builder.end(self.__class__.__name__) | Build this element
:param builder:
:return: |
def reboot(name, call=None):
'''
Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
if call != 'action':
raise SaltCloudException(
'The reboot action must be called with -a or ... | Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name |
def _system_path(self, subdir, basename=''):
'''
Gets the full path to the 'subdir/basename' file in the system binwalk directory.
@subdir - Subdirectory inside the system binwalk directory.
@basename - File name inside the subdirectory.
Returns the full path to the 'subdir/b... | Gets the full path to the 'subdir/basename' file in the system binwalk directory.
@subdir - Subdirectory inside the system binwalk directory.
@basename - File name inside the subdirectory.
Returns the full path to the 'subdir/basename' file. |
def _is_cp_helper(self, choi, atol, rtol):
"""Test if a channel is completely-positive (CP)"""
if atol is None:
atol = self._atol
if rtol is None:
rtol = self._rtol
return is_positive_semidefinite_matrix(choi, rtol=rtol, atol=atol) | Test if a channel is completely-positive (CP) |
def stream_list(self, id, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Stream events for the current user, restricted to accounts on the given
list.
"""
id = self.__unpack_... | Stream events for the current user, restricted to accounts on the given
list. |
def dimensioned_streams(dmap):
"""
Given a DynamicMap return all streams that have any dimensioned
parameters i.e parameters also listed in the key dimensions.
"""
dimensioned = []
for stream in dmap.streams:
stream_params = stream_parameters([stream])
if set([str(k) for k in dma... | Given a DynamicMap return all streams that have any dimensioned
parameters i.e parameters also listed in the key dimensions. |
def List(self, listName, exclude_hidden_fields=False):
"""Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files.
"""
return _List(self._session, lis... | Sharepoint Lists Web Service
Microsoft Developer Network:
The Lists Web service provides methods for working
with SharePoint lists, content types, list items, and files. |
def plot_chmap(cube, kidid, ax=None, **kwargs):
"""Plot an intensity map.
Args:
cube (xarray.DataArray): Cube which the spectrum information is included.
kidid (int): Kidid.
ax (matplotlib.axes): Axis the figure is plotted on.
kwargs (optional): Plot options passed to ax.imshow(... | Plot an intensity map.
Args:
cube (xarray.DataArray): Cube which the spectrum information is included.
kidid (int): Kidid.
ax (matplotlib.axes): Axis the figure is plotted on.
kwargs (optional): Plot options passed to ax.imshow(). |
def curtailment(network, carrier='solar', filename=None):
"""
Plot curtailment of selected carrier
Parameters
----------
network : PyPSA network container
Holds topology of grid including results from powerflow analysis
carrier: str
Plot curtailemt of this carrier
filename:... | Plot curtailment of selected carrier
Parameters
----------
network : PyPSA network container
Holds topology of grid including results from powerflow analysis
carrier: str
Plot curtailemt of this carrier
filename: str or None
Save figure in this direction
Returns
... |
def on_click(self, button, **kwargs):
"""
Maps a click event with its associated callback.
Currently implemented events are:
============ ================ =========
Event Callback setting Button ID
============ ================ =========
Left click ... | Maps a click event with its associated callback.
Currently implemented events are:
============ ================ =========
Event Callback setting Button ID
============ ================ =========
Left click on_leftclick 1
Middle click on_middleclic... |
def get_template_id(self, template_id_short):
"""
获得模板ID
详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html
:param template_id_short: 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式
:return: 返回的 JSON 数据包
"""
return self.request.post(
url='ht... | 获得模板ID
详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html
:param template_id_short: 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式
:return: 返回的 JSON 数据包 |
def p_objectitem_0(self, p):
'''
objectitem : objectkey EQUAL number
| objectkey EQUAL BOOL
| objectkey EQUAL STRING
| objectkey EQUAL object
| objectkey EQUAL list
'''
if DEBUG:
self.print_p(p)
... | objectitem : objectkey EQUAL number
| objectkey EQUAL BOOL
| objectkey EQUAL STRING
| objectkey EQUAL object
| objectkey EQUAL list |
def apply_boundary_conditions_to_cm(external_indices, cm):
"""Remove connections to or from external nodes."""
cm = cm.copy()
cm[external_indices, :] = 0 # Zero-out row
cm[:, external_indices] = 0 # Zero-out columnt
return cm | Remove connections to or from external nodes. |
def act(self, action):
"""
Take one action for one step
"""
# FIXME: Hack to change in return type
action = int(action)
assert isinstance(action, int)
assert action < self.actions_num, "%r (%s) invalid"%(action, type(action))
# Reset buttons
for k... | Take one action for one step |
def translate_output_properties(res: 'Resource', output: Any) -> Any:
"""
Recursively rewrite keys of objects returned by the engine to conform with a naming
convention specified by the resource's implementation of `translate_output_property`.
If output is a `dict`, every key is translated using `trans... | Recursively rewrite keys of objects returned by the engine to conform with a naming
convention specified by the resource's implementation of `translate_output_property`.
If output is a `dict`, every key is translated using `translate_output_property` while every value is transformed
by recursing.
If o... |
def create_single_dialog_train_example(context_dialog_path, candidate_dialog_paths, rng, positive_probability,
minimum_context_length=2, max_context_length=20):
"""
Creates a single example for training set.
:param context_dialog_path:
:param candidate_dialog_paths... | Creates a single example for training set.
:param context_dialog_path:
:param candidate_dialog_paths:
:param rng:
:param positive_probability:
:return: |
def linkify_s_by_sd(self, services):
"""Add dependency in service objects
:return: None
"""
for servicedep in self:
# Only used for debugging purpose when loops are detected
setattr(servicedep, "service_description_string", "undefined")
setattr(servic... | Add dependency in service objects
:return: None |
def _discover_refs(self, remote=False):
"""Get the current list of local or remote refs."""
if remote:
cmd_refs = ['git', 'ls-remote', '-h', '-t', '--exit-code', 'origin']
sep = '\t'
ignored_error_codes = [2]
else:
# Check first whether the local ... | Get the current list of local or remote refs. |
def callable(self, addr, concrete_only=False, perform_merge=True, base_state=None, toc=None, cc=None):
"""
A Callable is a representation of a function in the binary that can be interacted with like a native python
function.
:param addr: The address of the function to use
... | A Callable is a representation of a function in the binary that can be interacted with like a native python
function.
:param addr: The address of the function to use
:param concrete_only: Throw an exception if the execution splits into multiple states
:param perform_merge: ... |
def _parse_raw_data(self):
"""
Parses the incoming data and determines if it is valid. Valid
data gets placed into self._messages
:return: None
"""
if self._START_OF_FRAME in self._raw and self._END_OF_FRAME in self._raw:
while self._raw[0] != self._START_OF... | Parses the incoming data and determines if it is valid. Valid
data gets placed into self._messages
:return: None |
def update(name,
password=None,
fullname=None,
description=None,
home=None,
homedrive=None,
logonscript=None,
profile=None,
expiration_date=None,
expired=None,
account_disabled=None,
unlock_account=N... | Updates settings for the windows user. Name is the only required parameter.
Settings will only be changed if the parameter is passed a value.
.. versionadded:: 2015.8.0
Args:
name (str): The user name to update.
password (str, optional): New user password in plain text.
fullname ... |
def new_section(self, name, params=None):
"""Return a new section"""
self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self)
# Set the default arguments
s = self.sections[name.lower()]
if name.lower() in self.decl_sections:
s.args = self.de... | Return a new section |
def get_request_payment(self, bucket):
"""
Get the request payment configuration on a bucket.
@param bucket: The name of the bucket.
@return: A C{Deferred} that will fire with the name of the payer.
"""
details = self._details(
method=b"GET",
url_... | Get the request payment configuration on a bucket.
@param bucket: The name of the bucket.
@return: A C{Deferred} that will fire with the name of the payer. |
def code(self):
"""
code
"""
def uniq(seq):
"""
@type seq: str
@return: None
"""
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and not seen_add(x)]
# noinspection PyTy... | code |
def turbulent_Sieder_Tate(Re, Pr, mu=None, mu_w=None):
r'''Calculates internal convection Nusselt number for turbulent flows
in pipe according to [1]_ and supposedly [2]_.
.. math::
Nu = 0.027Re^{4/5}Pr^{1/3}\left(\frac{\mu}{\mu_s}\right)^{0.14}
Parameters
----------
Re : float
... | r'''Calculates internal convection Nusselt number for turbulent flows
in pipe according to [1]_ and supposedly [2]_.
.. math::
Nu = 0.027Re^{4/5}Pr^{1/3}\left(\frac{\mu}{\mu_s}\right)^{0.14}
Parameters
----------
Re : float
Reynolds number, [-]
Pr : float
Prandtl number... |
def __delete(self, subscription_plan_id, **kwargs):
"""Call documentation: `/subscription_plan/delete
<https://www.wepay.com/developer/reference/subscription_plan#delete>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
`... | Call documentation: `/subscription_plan/delete
<https://www.wepay.com/developer/reference/subscription_plan#delete>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorizati... |
def build_vcf_deletion(x, genome_2bit):
"""Provide representation of deletion from BedPE breakpoints.
"""
base1 = genome_2bit[x.chrom1].get(x.start1, x.start1 + 1).upper()
id1 = "hydra{0}".format(x.name)
return VcfLine(x.chrom1, x.start1, id1, base1, "<DEL>",
_vcf_single_end_info(... | Provide representation of deletion from BedPE breakpoints. |
def hoverMoveEvent(self, event):
"""
Prompts the tool tip for this node based on the inputed event.
:param event | <QHoverEvent>
"""
# process the parent event
super(XNode, self).hoverMoveEvent(event)
self._hovered = True
# ... | Prompts the tool tip for this node based on the inputed event.
:param event | <QHoverEvent> |
def _remove_by_pk(self, key, flush=True):
"""Retrieve value from store.
:param key: Key
"""
try:
del self.store[key]
except Exception as error:
pass
if flush:
self.flush() | Retrieve value from store.
:param key: Key |
def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
context = super(SpecialMixin, self).get_serializer_context()
context['election_date'] = self.kwargs['date']
return context | Adds ``election_day`` to serializer context. |
def _init_map(self):
"""Have to call these all separately because they are "end" classes,
with no super() in them. Non-cooperative."""
ItemTextsFormRecord._init_map(self)
ItemFilesFormRecord._init_map(self)
edXBaseFormRecord._init_map(self)
IRTItemFormRecord._init_map(sel... | Have to call these all separately because they are "end" classes,
with no super() in them. Non-cooperative. |
def partial_match(self, path, filter_path):
'''Partially match a path and a filter_path with wildcards.
This function will return True if this path partially match a filter path.
This is used for walking through directories with multiple level wildcard.
'''
if not path or not filter_path:
... | Partially match a path and a filter_path with wildcards.
This function will return True if this path partially match a filter path.
This is used for walking through directories with multiple level wildcard. |
def xpath(self, expression):
"""Executes an xpath expression using the correct namespaces"""
global namespaces
return self.tree.xpath(expression, namespaces=namespaces) | Executes an xpath expression using the correct namespaces |
def is_executable(exe_name):
"""Check if Input is Executable
This methid checks if the input executable exists.
Parameters
----------
exe_name : str
Executable name
Returns
-------
Bool result of test
Raises
------
TypeError
For invalid input type
"""... | Check if Input is Executable
This methid checks if the input executable exists.
Parameters
----------
exe_name : str
Executable name
Returns
-------
Bool result of test
Raises
------
TypeError
For invalid input type |
def _set_data(self):
"""
This method will be called to set Series data
"""
if getattr(self, 'data', False) and not getattr(self, '_x', False) and not getattr(self, '_y', False):
_x = XVariable()
_y = YVariable()
_x.contribute_to_class(self, 'X', self.d... | This method will be called to set Series data |
def save_to_file(self, filename: str) -> ConfigFile:
"""
This converts the NetworkedConfigFile into a normal ConfigFile object.
This requires the normal class hooks to be provided.
"""
newclass = ConfigFile(fd=filename, load_hook=self.normal_class_hook[0],
... | This converts the NetworkedConfigFile into a normal ConfigFile object.
This requires the normal class hooks to be provided. |
def get_view(self, table):
"""Returns the SQL query for a view, or None if it doesn't exist or is not a view.
:param table: The table containing the view.
:type table: BQTable
"""
request = self.client.tables().get(projectId=table.project_id,
... | Returns the SQL query for a view, or None if it doesn't exist or is not a view.
:param table: The table containing the view.
:type table: BQTable |
def get_http_info(self, request):
"""
Determine how to retrieve actual data by using request.mimetype.
"""
if self.is_json_type(request.mimetype):
retriever = self.get_json_data
else:
retriever = self.get_form_data
return self.get_http_info_with_re... | Determine how to retrieve actual data by using request.mimetype. |
def tplds(self):
"""
:return: dictionary {id: object} of all current tplds.
:rtype: dict of (int, xenamanager.xena_port.XenaTpld)
"""
# As TPLDs are dynamic we must re-read them each time from the port.
self.parent.del_objects_by_type('tpld')
for tpld in self.get... | :return: dictionary {id: object} of all current tplds.
:rtype: dict of (int, xenamanager.xena_port.XenaTpld) |
def error_wrapper(error, errorClass):
"""
We want to see all error messages from cloud services. Amazon's EC2 says
that their errors are accompanied either by a 400-series or 500-series HTTP
response code. As such, the first thing we want to do is check to see if
the error is in that range. If it is... | We want to see all error messages from cloud services. Amazon's EC2 says
that their errors are accompanied either by a 400-series or 500-series HTTP
response code. As such, the first thing we want to do is check to see if
the error is in that range. If it is, we then need to see if the error
message is ... |
def _addr_in_exec_memory_regions(self, addr):
"""
Test if the address belongs to an executable memory region.
:param int addr: The address to test
:return: True if the address belongs to an exectubale memory region, False otherwise
:rtype: bool
"""
for start, en... | Test if the address belongs to an executable memory region.
:param int addr: The address to test
:return: True if the address belongs to an exectubale memory region, False otherwise
:rtype: bool |
def send(self, command, _id=None, result={}, frames=[], threads=None,
error_messages=[], warning_messages=[], info_messages=[],
exception=None):
""" Build a message from parameters and send it to debugger.
:param command: The command sent to the debugger client.
... | Build a message from parameters and send it to debugger.
:param command: The command sent to the debugger client.
:type command: str
:param _id: Unique id of the sent message. Right now, it's always `None`
for messages by debugger to client.
:type _i... |
def crab_request(client, action, *args):
'''
Utility function that helps making requests to the CRAB service.
:param client: A :class:`suds.client.Client` for the CRAB service.
:param string action: Which method to call, eg. `ListGewesten`
:returns: Result of the SOAP call.
.. versionadded:: 0... | Utility function that helps making requests to the CRAB service.
:param client: A :class:`suds.client.Client` for the CRAB service.
:param string action: Which method to call, eg. `ListGewesten`
:returns: Result of the SOAP call.
.. versionadded:: 0.3.0 |
def hms_string(secs):
"""return hours,minutes and seconds string, e.g. 02:00:45"""
l = hms(secs)
def extend10(n):
if n < 10:
return '0' + str(n)
else:
return str(n)
return extend10(l[0]) + ':' + extend10(l[1]) + ':' + extend10(l[2]) | return hours,minutes and seconds string, e.g. 02:00:45 |
def display(url):
"""Display a file in ds9"""
import os
oscmd="curl --silent -g --fail --max-time 1800 --user jkavelaars '%s'" % (url)
logger.debug(oscmd)
os.system(oscmd+' | xpaset ds9 fits')
return | Display a file in ds9 |
def create(input_dataset, target, feature=None, validation_set='auto',
warm_start='auto', batch_size=256,
max_iterations=100, verbose=True):
"""
Create a :class:`DrawingClassifier` model.
Parameters
----------
dataset : SFrame
Input data. The columns named by the ``... | Create a :class:`DrawingClassifier` model.
Parameters
----------
dataset : SFrame
Input data. The columns named by the ``feature`` and ``target``
parameters will be extracted for training the drawing classifier.
target : string
Name of the column containing the target variable.... |
def sort(self):
"""
Return an iterable of nodes, toplogically sorted to correctly import
dependencies before leaf nodes.
"""
while self.nodes:
iterated = False
for node in self.leaf_nodes():
iterated = True
self.prune_node(n... | Return an iterable of nodes, toplogically sorted to correctly import
dependencies before leaf nodes. |
def describe_arguments(func):
"""
Analyze a function's signature and return a data structure suitable for
passing in as arguments to an argparse parser's add_argument() method."""
argspec = inspect.getargspec(func)
# we should probably raise an exception somewhere if func includes **kwargs
if a... | Analyze a function's signature and return a data structure suitable for
passing in as arguments to an argparse parser's add_argument() method. |
def approve(self, creator):
"""
Approve granular permission request setting a Permission entry as
approved=True for a specific action from an user on an object instance.
"""
self.approved = True
self.creator = creator
self.save() | Approve granular permission request setting a Permission entry as
approved=True for a specific action from an user on an object instance. |
def identical_blocks(self):
"""
:returns: A list of block matches which appear to be identical
"""
identical_blocks = []
for (block_a, block_b) in self._block_matches:
if self.blocks_probably_identical(block_a, block_b):
identical_blocks.append((block_... | :returns: A list of block matches which appear to be identical |
def call_decorator(cls, func):
"""class function that MUST be specified as decorator
to the `__call__` method overriden by sub-classes.
"""
@wraps(func)
def _wrap(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except Excep... | class function that MUST be specified as decorator
to the `__call__` method overriden by sub-classes. |
def hierarchical_key(self, s):
"""
Parse text as some kind of hierarchical key.
Return a subclass of :class:`Key <pycoin.key.Key>`, or None.
"""
s = parseable_str(s)
for f in [self.bip32_seed, self.bip32_prv, self.bip32_pub,
self.electrum_seed, self.elec... | Parse text as some kind of hierarchical key.
Return a subclass of :class:`Key <pycoin.key.Key>`, or None. |
def print_dataset_summary(self):
"""
Prints information about the the BIDS data and the files currently selected.
"""
print('--- DATASET INFORMATION ---')
print('--- Subjects ---')
if self.raw_data_exists:
if self.BIDS.get_subjects():
print('... | Prints information about the the BIDS data and the files currently selected. |
def try_lock(self, key, ttl=-1, timeout=0):
"""
Tries to acquire the lock for the specified key. When the lock is not available,
* If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately.
* If a timeout is provided, the current thread become... | Tries to acquire the lock for the specified key. When the lock is not available,
* If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately.
* If a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies
... |
def moma(self, wt_fluxes):
"""Minimize the redistribution of fluxes using Euclidean distance.
Minimizing the redistribution of fluxes using a quadratic objective
function. The distance is minimized by minimizing the sum of
(wild type - knockout)^2.
Args:
wt_fluxes: ... | Minimize the redistribution of fluxes using Euclidean distance.
Minimizing the redistribution of fluxes using a quadratic objective
function. The distance is minimized by minimizing the sum of
(wild type - knockout)^2.
Args:
wt_fluxes: Dictionary of all the wild type fluxes... |
def outer_id(self, value):
"""The outer_id property.
Args:
value (int). the property value.
"""
if value == self._defaults['outerId'] and 'outerId' in self._values:
del self._values['outerId']
else:
self._values['outerId'] = value | The outer_id property.
Args:
value (int). the property value. |
def _fill_scope_refs(name, scope):
"""Put referenced name in 'ref' dictionary of a scope.
Walks up the scope tree and adds the name to 'ref' of every scope
up in the tree until a scope that defines referenced name is reached.
"""
symbol = scope.resolve(name)
if symbol is... | Put referenced name in 'ref' dictionary of a scope.
Walks up the scope tree and adds the name to 'ref' of every scope
up in the tree until a scope that defines referenced name is reached. |
def aggregate(self, query):
"""
Issue an aggregation query
### Parameters
**query**: This can be either an `AggeregateRequest`, or a `Cursor`
An `AggregateResult` object is returned. You can access the rows from its
`rows` property, which will always yield the rows of ... | Issue an aggregation query
### Parameters
**query**: This can be either an `AggeregateRequest`, or a `Cursor`
An `AggregateResult` object is returned. You can access the rows from its
`rows` property, which will always yield the rows of the result |
def pretty_plot_two_axis(x, y1, y2, xlabel=None, y1label=None, y2label=None,
width=8, height=None, dpi=300):
"""
Variant of pretty_plot that does a dual axis plot. Adapted from matplotlib
examples. Makes it easier to create plots with different axes.
Args:
x (np.ndarray... | Variant of pretty_plot that does a dual axis plot. Adapted from matplotlib
examples. Makes it easier to create plots with different axes.
Args:
x (np.ndarray/list): Data for x-axis.
y1 (dict/np.ndarray/list): Data for y1 axis (left). If a dict, it will
be interpreted as a {label: se... |
def get_table_location(self, database_name, table_name):
"""
Get the physical location of the table
:param database_name: Name of hive database (schema) @table belongs to
:type database_name: str
:param table_name: Name of hive table
:type table_name: str
:return... | Get the physical location of the table
:param database_name: Name of hive database (schema) @table belongs to
:type database_name: str
:param table_name: Name of hive table
:type table_name: str
:return: str |
def serializeContainers(self):
"""Serializes the current view of open video grids (i.e. the view)
"""
""" each serialized container looks like this:
dic={# these are used when re-instantiating the view
"classname" : self.__class__.__name__,
"kwargs" : {}, # ... | Serializes the current view of open video grids (i.e. the view) |
def hashable(x):
"""
Return a hashable version of the given object x, with lists and
dictionaries converted to tuples. Allows mutable objects to be
used as a lookup key in cases where the object has not actually
been mutated. Lookup will fail (appropriately) in cases where some
part of the obje... | Return a hashable version of the given object x, with lists and
dictionaries converted to tuples. Allows mutable objects to be
used as a lookup key in cases where the object has not actually
been mutated. Lookup will fail (appropriately) in cases where some
part of the object has changed. Does not (cu... |
def replace(self, to_replace, value=_NoValue, subset=None):
"""Returns a new :class:`DataFrame` replacing a value with another value.
:func:`DataFrame.replace` and :func:`DataFrameNaFunctions.replace` are
aliases of each other.
Values to_replace and value must have the same type and can ... | Returns a new :class:`DataFrame` replacing a value with another value.
:func:`DataFrame.replace` and :func:`DataFrameNaFunctions.replace` are
aliases of each other.
Values to_replace and value must have the same type and can only be numerics, booleans,
or strings. Value can have None. Wh... |
def _os_bootstrap():
"""
Set up 'os' module replacement functions for use during import bootstrap.
"""
global _os_stat, _os_getcwd, _os_environ, _os_listdir
global _os_path_join, _os_path_dirname, _os_path_basename
global _os_sep
names = sys.builtin_module_names
join = dirname = envir... | Set up 'os' module replacement functions for use during import bootstrap. |
def addSignal(self, s):
"""
Adds a L{Signal} to the interface
"""
if s.nargs == -1:
s.nargs = len([a for a in marshal.genCompleteTypes(s.sig)])
self.signals[s.name] = s
self._xml = None | Adds a L{Signal} to the interface |
def _send(self, line):
"""
Write a line of data to the server.
Args:
line -- A single line of data to write to the socket.
"""
if not line.endswith('\r\n'):
if line.endswith('\n'):
logger.debug('Fixing bare LF before sending data to socket')
... | Write a line of data to the server.
Args:
line -- A single line of data to write to the socket. |
def save_weights(sess, output_path, conv_var_names=None, conv_transpose_var_names=None):
"""Save the weights of the trainable variables, each one in a different file in output_path."""
if not conv_var_names:
conv_var_names = []
if not conv_transpose_var_names:
conv_transpose_var_names = []
... | Save the weights of the trainable variables, each one in a different file in output_path. |
def _read_message(self):
""" Reads a single size-annotated message from the server """
size = int(self.buf.read_line().decode("utf-8"))
return self.buf.read(size).decode("utf-8") | Reads a single size-annotated message from the server |
def current_user(self):
"""Returns the username of the current user.
:rtype: str
"""
if not hasattr(self, '_serverInfo') or 'username' not in self._serverInfo:
url = self._get_url('serverInfo')
r = self._session.get(url, headers=self._options['headers'])
... | Returns the username of the current user.
:rtype: str |
def show_progress(self, message=None):
"""If we are in a progress scope, and no log messages have been
shown, write out another '.'"""
if self.in_progress_hanging:
if message is None:
sys.stdout.write('.')
sys.stdout.flush()
else:
... | If we are in a progress scope, and no log messages have been
shown, write out another '. |
def _get_tmaster_processes(self):
''' get the command to start the tmaster processes '''
retval = {}
tmaster_cmd_lst = [
self.tmaster_binary,
'--topology_name=%s' % self.topology_name,
'--topology_id=%s' % self.topology_id,
'--zkhostportlist=%s' % self.state_manager_connectio... | get the command to start the tmaster processes |
def put(self, targetId):
"""
stores a new target.
:param targetId: the target to store.
:return:
"""
json = request.get_json()
if 'hinge' in json:
logger.info('Storing target ' + targetId)
if self._targetController.storeFromHinge(targetId, ... | stores a new target.
:param targetId: the target to store.
:return: |
def build_skeleton(nodes, independencies):
"""Estimates a graph skeleton (UndirectedGraph) from a set of independencies
using (the first part of) the PC algorithm. The independencies can either be
provided as an instance of the `Independencies`-class or by passing a
decision function tha... | Estimates a graph skeleton (UndirectedGraph) from a set of independencies
using (the first part of) the PC algorithm. The independencies can either be
provided as an instance of the `Independencies`-class or by passing a
decision function that decides any conditional independency assertion.
... |
def resume_multiple(self, infohash_list):
"""
Resume multiple paused torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/resumeAll', data=data) | Resume multiple paused torrents.
:param infohash_list: Single or list() of infohashes. |
def check_password_confirm(self, form, trigger_action_group=None):
"""Checks that the password and the confirm password match in
the provided form. Won't do anything if any of the password fields
are not in the form.
"""
pwcol = self.options['password_column']
pwconfirmfi... | Checks that the password and the confirm password match in
the provided form. Won't do anything if any of the password fields
are not in the form. |
def write(self, _force=False, _exists_ok=False, **items):
"""
Creates a db file with the core schema.
:param force: If `True` an existing db file will be overwritten.
"""
if self.fname and self.fname.exists():
raise ValueError('db file already exists, use force=True ... | Creates a db file with the core schema.
:param force: If `True` an existing db file will be overwritten. |
def add_argument(self, *args, **kwargs):
"""Add an argument.
This method adds a new argument to the current parser. The function is
same as ``argparse.ArgumentParser.add_argument``. However, this method
tries to determine help messages for the adding argument from some
docstring... | Add an argument.
This method adds a new argument to the current parser. The function is
same as ``argparse.ArgumentParser.add_argument``. However, this method
tries to determine help messages for the adding argument from some
docstrings.
If the new arguments belong to some sub ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.