code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def file_list(load):
'''
Return a list of all files in a specified environment
'''
ret = set()
try:
for container in __opts__['azurefs']:
if container.get('saltenv', 'base') != load['saltenv']:
continue
container_list = _get_container_path(container) +... | Return a list of all files in a specified environment |
def reset_training_state(self, dones, batch_info):
""" A hook for a model to react when during training episode is finished """
for idx, done in enumerate(dones):
if done > 0.5:
self.processes[idx].reset() | A hook for a model to react when during training episode is finished |
def start(self):
"""
Connect to the Cytomine server and switch to job connection
Incurs dataflows
"""
run_by_ui = False
if not self.current_user.algo:
# If user connects as a human (CLI execution)
self._job = Job(self._project.id, self._software.i... | Connect to the Cytomine server and switch to job connection
Incurs dataflows |
def _get_channel(host, timeout):
"""
Create communication channel for given `host`.
Args:
host (str): Specified --host.
timeout (int): Set `timeout` for returned `channel`.
Returns:
Object: Pika channel object.
"""
connection = create_blocking_connection(host)
# re... | Create communication channel for given `host`.
Args:
host (str): Specified --host.
timeout (int): Set `timeout` for returned `channel`.
Returns:
Object: Pika channel object. |
def yield_to_ioloop(self):
"""Function that will allow Rejected to process IOLoop events while
in a tight-loop inside an asynchronous consumer.
.. code-block:: python
:caption: Example Usage
class Consumer(consumer.Consumer):
@gen.coroutine
... | Function that will allow Rejected to process IOLoop events while
in a tight-loop inside an asynchronous consumer.
.. code-block:: python
:caption: Example Usage
class Consumer(consumer.Consumer):
@gen.coroutine
def process(self):
... |
def page(self, enabled=values.unset, date_created_after=values.unset,
date_created_before=values.unset, friendly_name=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of CompositionHookInstance rec... | Retrieve a single page of CompositionHookInstance records from the API.
Request is executed immediately
:param bool enabled: Only show Composition Hooks enabled or disabled.
:param datetime date_created_after: Only show Composition Hooks created on or after this ISO8601 date-time with timezone.... |
def connect_patch_namespaced_pod_proxy(self, name, namespace, **kwargs):
"""
connect PATCH requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_namespaced_... | connect PATCH requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_namespaced_pod_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param ... |
def _get_default_field_names(self, declared_fields, model_info):
""" Return default field names for serializer. """
return (
[model_info.pk.name] +
list(declared_fields.keys()) +
list(model_info.fields.keys()) +
list(model_info.relations.keys())
) | Return default field names for serializer. |
def get_authuser_by_name(cls, request):
""" Get user by username
Used by Token-based auth. Is added as request method to populate
`request.user`.
"""
username = authenticated_userid(request)
if username:
return cls.get_item(username=username) | Get user by username
Used by Token-based auth. Is added as request method to populate
`request.user`. |
def main(argv=None):
"""Run roll() from a command line interface"""
args = docopt.docopt(__doc__, argv=argv, version=__version__)
verbose = bool(args['--verbose'])
f_roll = dice.roll
kwargs = {}
if args['--min']:
f_roll = dice.roll_min
elif args['--max']:
f_roll = dice.roll... | Run roll() from a command line interface |
def _set_error_handler_callbacks(self, app):
"""
Sets the error handler callbacks used by this extension
"""
@app.errorhandler(NoAuthorizationError)
def handle_auth_error(e):
return self._unauthorized_callback(str(e))
@app.errorhandler(CSRFError)
def ... | Sets the error handler callbacks used by this extension |
def promise_method(func):
"""
A decorator which ensures that once a method has been marked as resolved
(via Class.__resolved)) will then propagate the attribute (function) call
upstream.
"""
name = func.__name__
@wraps(func)
def wrapped(self, *args, **kwargs):
cls_name = type(se... | A decorator which ensures that once a method has been marked as resolved
(via Class.__resolved)) will then propagate the attribute (function) call
upstream. |
def open_report_template_path(self):
"""Open File dialog to choose the report template path."""
# noinspection PyCallByClass,PyTypeChecker
directory_name = QFileDialog.getExistingDirectory(
self,
self.tr('Templates directory'),
self.leReportTemplatePath.text()... | Open File dialog to choose the report template path. |
def set(self, key, value, time=0, compress_level=-1):
"""
Set a value for a key on server.
:param key: Key's name
:type key: str
:param value: A value to be stored on server.
:type value: object
:param time: Time in seconds that your key will expire.
:typ... | Set a value for a key on server.
:param key: Key's name
:type key: str
:param value: A value to be stored on server.
:type value: object
:param time: Time in seconds that your key will expire.
:type time: int
:param compress_level: How much to compress.
... |
def add_all(self, items, overflow_policy=OVERFLOW_POLICY_OVERWRITE):
"""
Adds all of the item in the specified collection to the tail of the Ringbuffer. An add_all is likely to
outperform multiple calls to add(object) due to better io utilization and a reduced number of executed
operatio... | Adds all of the item in the specified collection to the tail of the Ringbuffer. An add_all is likely to
outperform multiple calls to add(object) due to better io utilization and a reduced number of executed
operations. The items are added in the order of the Iterator of the collection.
If there... |
def get(self, using=None, **kwargs):
"""
The get index API allows to retrieve information about the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.get`` unchanged.
"""
return self._get_connection(using).indices.get(index=self._name, **k... | The get index API allows to retrieve information about the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.get`` unchanged. |
def find(*args, **kwargs):
"""
kwargs supported:
user: the username
start_at: start datetime object
end_at: end datetime object
limit: # of objects to fetch
"""
# default end_at to now and start to 1 day from now
end_at = kwargs.get('end_at', datetime.datetime.now())
... | kwargs supported:
user: the username
start_at: start datetime object
end_at: end datetime object
limit: # of objects to fetch |
def recursively_preempt_states(self):
""" Preempt the state and all of it child states.
"""
super(ContainerState, self).recursively_preempt_states()
# notify the transition condition variable to let the state instantaneously stop
self._transitions_cv.acquire()
self._trans... | Preempt the state and all of it child states. |
def set_running_mean(self, running_mean):
"""
Set the running mean of the layer.
Only use this method for a BatchNormalization layer.
:param running_mean: a Numpy array.
"""
callBigDlFunc(self.bigdl_type, "setRunningMean",
self.value, JTensor.from_nd... | Set the running mean of the layer.
Only use this method for a BatchNormalization layer.
:param running_mean: a Numpy array. |
def clear(self):
"""Clear all work items from the session.
This removes any associated results as well.
"""
with self._conn:
self._conn.execute('DELETE FROM results')
self._conn.execute('DELETE FROM work_items') | Clear all work items from the session.
This removes any associated results as well. |
def _create_sagemaker_model(self, instance_type, accelerator_type=None, tags=None):
"""Create a SageMaker Model Entity
Args:
instance_type (str): The EC2 instance type that this Model will be used for, this is only
used to determine if the image needs GPU support or not.
... | Create a SageMaker Model Entity
Args:
instance_type (str): The EC2 instance type that this Model will be used for, this is only
used to determine if the image needs GPU support or not.
accelerator_type (str): Type of Elastic Inference accelerator to attach to an endpoint... |
def H12(self):
"Information measure of correlation 1."
maxima = np.vstack((self.hx, self.hy)).max(0)
return (self.H9() - self.hxy1) / maxima | Information measure of correlation 1. |
def _scale_y_values(self, values, new_min, new_max, scale_old_from_zero=True):
'''
Take values and transmute them into a new range
'''
# Scale Y values - Create a scaled list of values to use for the visual graph
scaled_values = []
y_min_value = min(values)
if sca... | Take values and transmute them into a new range |
def acceptance_fractions(mean_acceptance_fractions, burn=None, ax=None):
"""
Plot the meana cceptance fractions for each MCMC step.
:param mean_acceptance_fractions:
The acceptance fractions at each MCMC step.
:type mean_acceptance_fractions:
:class:`numpy.array`
:param burn: [opt... | Plot the meana cceptance fractions for each MCMC step.
:param mean_acceptance_fractions:
The acceptance fractions at each MCMC step.
:type mean_acceptance_fractions:
:class:`numpy.array`
:param burn: [optional]
The burn-in point. If provided, a dashed vertical line will be shown a... |
def systemInformationType17():
"""SYSTEM INFORMATION TYPE 17 Section 9.1.43e"""
a = L2PseudoLength(l2pLength=0x01)
b = TpPd(pd=0x6)
c = MessageType(mesType=0x3e) # 00111110
d = Si17RestOctets()
packet = a / b / c / d
return packet | SYSTEM INFORMATION TYPE 17 Section 9.1.43e |
def _register_self(self, logfile, key=JobDetails.topkey, status=JobStatus.unknown):
"""Runs this link, captures output to logfile,
and records the job in self.jobs"""
fullkey = JobDetails.make_fullkey(self.full_linkname, key)
if fullkey in self.jobs:
job_details = self.jobs[f... | Runs this link, captures output to logfile,
and records the job in self.jobs |
def add_output(summary_output, long_output, helper):
"""
if the summary output is empty, we don't add it as summary, otherwise we would have empty spaces (e.g.: '. . . . .') in our summary report
"""
if summary_output != '':
helper.add_summary(summary_output)
helper.add_long_output(long_outp... | if the summary output is empty, we don't add it as summary, otherwise we would have empty spaces (e.g.: '. . . . .') in our summary report |
def build_system_error(cls, errors=None):
"""Utility method to build a HTTP 500 System Error response"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.SYSTEM_ERROR, errors) | Utility method to build a HTTP 500 System Error response |
def format_list(extracted_list):
"""Format a list of traceback entry tuples for printing.
Given a list of tuples as returned by extract_tb() or
extract_stack(), return a list of strings ready for printing.
Each string in the resulting list corresponds to the item with the
same index in the argument... | Format a list of traceback entry tuples for printing.
Given a list of tuples as returned by extract_tb() or
extract_stack(), return a list of strings ready for printing.
Each string in the resulting list corresponds to the item with the
same index in the argument list. Each string ends in a newline;
... |
def update_version_records(self):
"""
Update rash_info table if necessary.
"""
from .__init__ import __version__ as version
with self.connection(commit=True) as connection:
for vrec in self.get_version_records():
if (vrec.rash_version == version and
... | Update rash_info table if necessary. |
def connect(host="localhost", user=None, password="",
db=None, port=3306, unix_socket=None,
charset='', sql_mode=None,
read_default_file=None, conv=decoders, use_unicode=None,
client_flag=0, cursorclass=Cursor, init_command=None,
connect_timeout=None, read_def... | See connections.Connection.__init__() for information about
defaults. |
def get_index_line(self,lnum):
""" Take the 1-indexed line number and return its index information"""
if lnum < 1:
sys.stderr.write("ERROR: line number should be greater than zero\n")
sys.exit()
elif lnum > len(self._lines):
sys.stderr.write("ERROR: too far this line nuber is not in index\... | Take the 1-indexed line number and return its index information |
def patch(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a PUT request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Op... | Sends a PUT request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Optional arguments that ``request`` takes.
:return: response object |
def air_range(self) -> Union[int, float]:
""" Does not include upgrades """
if self._weapons:
weapon = next(
(weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}),
None,
)
if weapon:
... | Does not include upgrades |
def calc_chunklen(alph_len):
'''
computes the ideal conversion ratio for the given alphabet.
A ratio is considered ideal when the number of bits in one output
encoding chunk that don't add up to one input encoding chunk is minimal.
'''
binlen, enclen = min([
(i, i*8 / m... | computes the ideal conversion ratio for the given alphabet.
A ratio is considered ideal when the number of bits in one output
encoding chunk that don't add up to one input encoding chunk is minimal. |
def draw_flow(img, flow, step=16, dtype=uint8):
"""
draws flow vectors on image
this came from opencv/examples directory
another way: http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html
"""
maxval = iinfo(img.dtype).max
# scaleFact = 1. #arbit... | draws flow vectors on image
this came from opencv/examples directory
another way: http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html |
def get_prior(self, twig=None, **kwargs):
"""
[NOT IMPLEMENTED]
:raises NotImplementedError: because it isn't
"""
raise NotImplementedError
kwargs['context'] = 'prior'
return self.filter(twig=twig, **kwargs) | [NOT IMPLEMENTED]
:raises NotImplementedError: because it isn't |
def _load_from_socket(port, auth_secret):
"""
Load data from a given socket, this is a blocking method thus only return when the socket
connection has been closed.
"""
(sockfile, sock) = local_connect_and_auth(port, auth_secret)
# The barrier() call may block forever, so no timeout
sock.sett... | Load data from a given socket, this is a blocking method thus only return when the socket
connection has been closed. |
def estimate_intraday(returns, positions, transactions, EOD_hour=23):
"""
Intraday strategies will often not hold positions at the day end.
This attempts to find the point in the day that best represents
the activity of the strategy on that day, and effectively resamples
the end-of-day positions wit... | Intraday strategies will often not hold positions at the day end.
This attempts to find the point in the day that best represents
the activity of the strategy on that day, and effectively resamples
the end-of-day positions with the positions at this point of day.
The point of day is found by detecting w... |
def object_to_id(self, obj):
"""
Searches elasticsearch for objects with the same username, password, optional domain, host_ip and service_id.
"""
# Not sure yet if this is advisable... Older passwords can be overwritten...
search = Credential.search()
search = search... | Searches elasticsearch for objects with the same username, password, optional domain, host_ip and service_id. |
def get_consensus_at(self, block_id):
"""
Get the consensus hash at a given block.
Return the consensus hash if we have one for this block.
Return None if we don't
"""
query = 'SELECT consensus_hash FROM snapshots WHERE block_id = ?;'
args = (block_id,)
c... | Get the consensus hash at a given block.
Return the consensus hash if we have one for this block.
Return None if we don't |
def is_readable(path=None):
"""
Test if the supplied filesystem path can be read
:param path: A filesystem path
:return: True if the path is a file that can be read. Otherwise, False
"""
if os.path.isfile(path) and os.access(path, os.R_OK):
return True
return False | Test if the supplied filesystem path can be read
:param path: A filesystem path
:return: True if the path is a file that can be read. Otherwise, False |
def update_link(self):
"""
redirects all links to self (the new linked object)
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links()
to_be_changed = list()
if name in l:
for wal in l[name]:
... | redirects all links to self (the new linked object) |
def _warcprox_opts(self, args):
'''
Takes args as produced by the argument parser built by
_build_arg_parser and builds warcprox arguments object suitable to pass
to warcprox.main.init_controller. Copies some arguments, renames some,
populates some with defaults appropriate for b... | Takes args as produced by the argument parser built by
_build_arg_parser and builds warcprox arguments object suitable to pass
to warcprox.main.init_controller. Copies some arguments, renames some,
populates some with defaults appropriate for brozzler-easy, etc. |
def winddir_text(pts):
"Convert wind direction from 0..15 to compass point text"
global _winddir_text_array
if pts is None:
return None
if not isinstance(pts, int):
pts = int(pts + 0.5) % 16
if not _winddir_text_array:
_ = pywws.localisation.translation.ugettext
_wind... | Convert wind direction from 0..15 to compass point text |
def quotes(self, security, start, end):
"""
Get historical prices for the given ticker security.
Date format is 'YYYYMMDD'
Returns a nested list.
"""
try:
url = 'http://www.google.com/finance/historical?q=%s&startdate=%s&enddate=%s&output=csv' % (secu... | Get historical prices for the given ticker security.
Date format is 'YYYYMMDD'
Returns a nested list. |
def set_formatter(name, func):
"""Replace the formatter function used by the trace decorator to
handle formatting a specific kind of argument. There are several
kinds of arguments that trace discriminates between:
* instance argument - the object bound to an instance method.
* class argument - the... | Replace the formatter function used by the trace decorator to
handle formatting a specific kind of argument. There are several
kinds of arguments that trace discriminates between:
* instance argument - the object bound to an instance method.
* class argument - the class object bound to a class method.... |
def read_original_textlc(lcpath):
'''
Read .epdlc, and .tfalc light curves and return a corresponding labelled
dict (if LC from <2012) or astropy table (if >=2012). Each has different
keys that can be accessed via .keys()
Input:
lcpath: path (string) to light curve data, which is a textfile wit... | Read .epdlc, and .tfalc light curves and return a corresponding labelled
dict (if LC from <2012) or astropy table (if >=2012). Each has different
keys that can be accessed via .keys()
Input:
lcpath: path (string) to light curve data, which is a textfile with HAT
LC data.
Example:
dat = rea... |
def is_type(msg_type, msg):
"""
Return message's type is or not
"""
for prop in MessageType.FIELDS[msg_type]["must"]:
if msg.get(prop, False) is False:
return False
for prop in MessageType.FIELDS[msg_type]["prohibit"]:
if msg.get(prop, Fals... | Return message's type is or not |
def generate_output_list(self, source, key, val, line='2', hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output RDAP list results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required)... | The function for generating CLI output RDAP list results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required).
key (:obj:`str`): The event key 'events' or 'events_actor'
(required).
val (:obj:`dict`): The event dictiona... |
def _doElegant(self):
""" perform elegant tracking
"""
cmdlist = ['bash', self.sim_script, self.elegant_file, self.sim_path, self.sim_exec]
subprocess.call(cmdlist) | perform elegant tracking |
def simxGetLastErrors(clientID, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
errors =[]
errorCnt = ct.c_int()
errorStrings = ct.POINTER(ct.c_char)()
ret = c_GetLastErrors(clientID, ct.byref(errorCnt), ct.byref(errorStrings), op... | Please have a look at the function description/documentation in the V-REP user manual |
def appendImport(self, statement):
'''append additional import statement(s).
import_stament -- tuple or list or str
'''
if type(statement) in (list,tuple):
self.extras += statement
else:
self.extras.append(statement) | append additional import statement(s).
import_stament -- tuple or list or str |
def _utc_float(self):
"""Return UTC as a floating point Julian date."""
tai = self.tai
leap_dates = self.ts.leap_dates
leap_offsets = self.ts.leap_offsets
leap_reverse_dates = leap_dates + leap_offsets / DAY_S
i = searchsorted(leap_reverse_dates, tai, 'right')
ret... | Return UTC as a floating point Julian date. |
async def load(self,
file_path,
locale=None,
key: int = 0,
pos: int = 1,
neg: Optional[ColRanges] = None):
"""
Start the loading/watching process
"""
if neg is None:
neg: ColRanges... | Start the loading/watching process |
def bump(ctx, verbose=False, pypi=False):
"""Bump a development version."""
cfg = config.load()
scm = scm_provider(cfg.project_root, commit=False, ctx=ctx)
# Check for uncommitted changes
if not scm.workdir_is_clean():
notify.warning("You have uncommitted changes, will create a time-stamped... | Bump a development version. |
def get_directed_graph_paths(element, arrow_length):
"""
Computes paths for a directed path which include an arrow to
indicate the directionality of each edge.
"""
edgepaths = element._split_edgepaths
edges = edgepaths.split(datatype='array', dimensions=edgepaths.kdims)
arrows = []
for e... | Computes paths for a directed path which include an arrow to
indicate the directionality of each edge. |
def error(self, *args):
"""Log an error. By default this will also raise an exception."""
if _canShortcutLogging(self.logCategory, ERROR):
return
errorObject(self.logObjectName(), self.logCategory,
*self.logFunction(*args)) | Log an error. By default this will also raise an exception. |
def on_ready_to_stop(self):
"""Invoked when the consumer is ready to stop."""
# Set the state to shutting down if it wasn't set as that during loop
self.set_state(self.STATE_SHUTTING_DOWN)
# Reset any signal handlers
signal.signal(signal.SIGABRT, signal.SIG_IGN)
signal.... | Invoked when the consumer is ready to stop. |
def get_namespace_view(self):
"""
Return the namespace view
This is a dictionary with the following structure
{'a': {'color': '#800000', 'size': 1, 'type': 'str', 'view': '1'}}
Here:
* 'a' is the variable name
* 'color' is the color used to show it
* 's... | Return the namespace view
This is a dictionary with the following structure
{'a': {'color': '#800000', 'size': 1, 'type': 'str', 'view': '1'}}
Here:
* 'a' is the variable name
* 'color' is the color used to show it
* 'size' and 'type' are self-evident
* and'vie... |
def _make_links_from(self, body):
'''Creates linked navigators from a HAL response body'''
ld = utils.CurieDict(self._core.default_curie, {})
for rel, link in body.get('_links', {}).items():
if rel != 'curies':
if isinstance(link, list):
ld[rel] = ... | Creates linked navigators from a HAL response body |
def _set_fabric_priority(self, v, load=False):
"""
Setter method for fabric_priority, mapped from YANG variable /cee_map/remap/fabric_priority (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fabric_priority is considered as a private
method. Backends look... | Setter method for fabric_priority, mapped from YANG variable /cee_map/remap/fabric_priority (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fabric_priority is considered as a private
method. Backends looking to populate this variable should
do so via calling ... |
def py_run(command_options="", return_std=False, stdout=None, stderr=None):
"""Run pylint from python
``command_options`` is a string containing ``pylint`` command line options;
``return_std`` (boolean) indicates return of created standard output
and error (see below);
``stdout`` and ``stderr`` are... | Run pylint from python
``command_options`` is a string containing ``pylint`` command line options;
``return_std`` (boolean) indicates return of created standard output
and error (see below);
``stdout`` and ``stderr`` are 'file-like' objects in which standard output
could be written.
Calling ag... |
def _filter_records(self, records, rtype=None, name=None, content=None, identifier=None): # pylint: disable=too-many-arguments,no-self-use
"""
Filter dns entries based on type, name or content.
"""
if not records:
return []
if identifier is not None:
LOGG... | Filter dns entries based on type, name or content. |
def dump_weights(tf_save_dir, outfile, options):
"""
Dump the trained weights from a model to a HDF5 file.
"""
def _get_outname(tf_name):
outname = re.sub(':0$', '', tf_name)
outname = outname.lstrip('lm/')
outname = re.sub('/rnn/', '/RNN/', outname)
outname = re.sub('/m... | Dump the trained weights from a model to a HDF5 file. |
def save(self, obj):
"""
save an object
:param obj: the object
:return: the saved object
"""
if obj not in self.session:
self.session.add(obj)
else:
obj = self.session.merge(obj)
self.session.flush()
self.session.refresh(ob... | save an object
:param obj: the object
:return: the saved object |
def product_requests_button(page, page_perms, is_parent=False):
"""Renders a 'requests' button on the page index showing the number
of times the product has been requested.
Attempts to only show such a button for valid product/variant pages
"""
# Is this page the 'product' model?
# It is genera... | Renders a 'requests' button on the page index showing the number
of times the product has been requested.
Attempts to only show such a button for valid product/variant pages |
def getTransfer(self, iso_packets=0):
"""
Get an USBTransfer instance for asynchronous use.
iso_packets: the number of isochronous transfer descriptors to
allocate.
"""
result = USBTransfer(
self.__handle, iso_packets,
self.__inflight_add, self._... | Get an USBTransfer instance for asynchronous use.
iso_packets: the number of isochronous transfer descriptors to
allocate. |
async def parse_tag_results(soup):
"""
Parse a page of tag or trait results. Same format.
:param soup: BS4 Class Object
:return: A list of tags, Nothing else really useful there
"""
soup = soup.find_all('td', class_='tc3')
tags = []
for item in soup:
tags.append(item.a.string)
... | Parse a page of tag or trait results. Same format.
:param soup: BS4 Class Object
:return: A list of tags, Nothing else really useful there |
def rpc_get_definition(self, filename, source, offset):
"""Get the location of the definition for the symbol at the offset.
"""
return self._call_backend("rpc_get_definition", None, filename,
get_source(source), offset) | Get the location of the definition for the symbol at the offset. |
def get_all_entities(self, membership_cache=None, entities_by_kind=None, return_models=False, is_active=True):
"""
Returns a list of all entity ids in this group or optionally returns a queryset for all entity models.
In order to reduce queries for multiple group lookups, it is expected that the... | Returns a list of all entity ids in this group or optionally returns a queryset for all entity models.
In order to reduce queries for multiple group lookups, it is expected that the membership_cache and
entities_by_kind are built outside of this method and passed in as arguments.
:param membersh... |
def _parse_author(self):
r"""Parse the author from TeX source.
Sets the ``_authors`` attribute.
Goal is to parse::
\author{
A.~Author,
B.~Author,
and
C.~Author}
Into::
['A. Author', 'B. Author', 'C. Author']
"... | r"""Parse the author from TeX source.
Sets the ``_authors`` attribute.
Goal is to parse::
\author{
A.~Author,
B.~Author,
and
C.~Author}
Into::
['A. Author', 'B. Author', 'C. Author'] |
def save_config_variables(self):
"""Save the configuration variables in non-volatile memory. This method
should be used in conjuction with *write_config_variables*.
:rtype: boolean
:Example:
>>> alpha.save_config_variables()
True
"""
command = 0x43
... | Save the configuration variables in non-volatile memory. This method
should be used in conjuction with *write_config_variables*.
:rtype: boolean
:Example:
>>> alpha.save_config_variables()
True |
def zip_process(**kwargs):
"""
Process zip operations.
:param kwargs:
:return:
"""
str_localPath = ""
str_zipFileName = ""
str_action = "zip"
str_arcroot = ""
for k,v in kwargs.items():
if k == 'path': str_localPath = v
if k == 'action':... | Process zip operations.
:param kwargs:
:return: |
def enrich(self, column):
""" This method adds a new column depending on the extension
of the file.
:param column: column where the file path is found
:type column: string
:return: returns the original dataframe with a new column named as
'filetype' that contai... | This method adds a new column depending on the extension
of the file.
:param column: column where the file path is found
:type column: string
:return: returns the original dataframe with a new column named as
'filetype' that contains information about its extension
... |
def find_transport_reactions(model):
"""
Return a list of all transport reactions.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
Notes
-----
A transport reaction is defined as follows:
1. It contains metabolites from at least 2 compartme... | Return a list of all transport reactions.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
Notes
-----
A transport reaction is defined as follows:
1. It contains metabolites from at least 2 compartments and
2. at least 1 metabolite undergoes no... |
def findentry(self, item):
"""A caseless way of checking if an item is in the list or not.
It returns None or the entry."""
if not isinstance(item, str):
raise TypeError(
'Members of this object must be strings. '
'You supplied \"%s\"' % type(item))
... | A caseless way of checking if an item is in the list or not.
It returns None or the entry. |
def new_thing(self, name, **stats):
"""Create a new thing, located here, and return it."""
return self.character.new_thing(
name, self.name, **stats
) | Create a new thing, located here, and return it. |
def get(block_id):
"""Processing block detail resource."""
_url = get_root_url()
try:
block = DB.get_block_details([block_id]).__next__()
response = block
response['links'] = {
'self': '{}'.format(request.url),
'list': '{}/processing-blocks'.format(_url),
... | Processing block detail resource. |
def length(self, t0=0, t1=1, error=None, min_depth=None):
"""returns the length of the line segment between t0 and t1."""
return abs(self.end - self.start)*(t1-t0) | returns the length of the line segment between t0 and t1. |
def from_layer(cls, font, layerName=None, copy=False, skipExportGlyphs=None):
"""Return a mapping of glyph names to glyph objects from `font`."""
if layerName is not None:
layer = font.layers[layerName]
else:
layer = font.layers.defaultLayer
if copy:
... | Return a mapping of glyph names to glyph objects from `font`. |
def authenticate(self, token_value):
"""Check that the password is valid.
This allows for revoking of a user's preview rights by changing the
valid passwords.
"""
try:
backend_path, user_id = token_value.split(':', 1)
except (ValueError, AttributeError):
... | Check that the password is valid.
This allows for revoking of a user's preview rights by changing the
valid passwords. |
def dataset_archive(dataset, signature, data_home=None, ext=".zip"):
"""
Checks to see if the dataset archive file exists in the data home directory,
found with ``get_data_home``. By specifying the signature, this function
also checks to see if the archive is the latest version by comparing the
sha2... | Checks to see if the dataset archive file exists in the data home directory,
found with ``get_data_home``. By specifying the signature, this function
also checks to see if the archive is the latest version by comparing the
sha256sum of the local archive with the specified signature.
Parameters
----... |
def register_actions(self, shortcut_manager):
"""Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
shortcut_manager.add_callback_for... | Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions. |
def _symlink_local_src(self, gopath, go_local_src, required_links):
"""Creates symlinks from the given gopath to the source files of the given local package.
Also duplicates directory structure leading to source files of package within
gopath, in order to provide isolation to the package.
Adds the sym... | Creates symlinks from the given gopath to the source files of the given local package.
Also duplicates directory structure leading to source files of package within
gopath, in order to provide isolation to the package.
Adds the symlinks to the source files to required_links. |
def gf_poly_mul_simple(p, q): # simple equivalent way of multiplying two polynomials without precomputation, but thus it's slower
'''Multiply two polynomials, inside Galois Field'''
# Pre-allocate the result array
r = bytearray(len(p) + len(q) - 1)
# Compute the polynomial multiplication (just like the ... | Multiply two polynomials, inside Galois Field |
def kwargs(self):
"""Returns a dict of the kwargs for this Struct which were not interpreted by the baseclass.
This excludes fields like `extends`, `merges`, and `abstract`, which are consumed by
SerializableFactory.create and Validatable.validate.
"""
return {k: v for k, v in self._kwargs.items() ... | Returns a dict of the kwargs for this Struct which were not interpreted by the baseclass.
This excludes fields like `extends`, `merges`, and `abstract`, which are consumed by
SerializableFactory.create and Validatable.validate. |
def ToTsvExcel(self, columns_order=None, order_by=()):
"""Returns a file in tab-separated-format readable by MS Excel.
Returns a file in UTF-16 little endian encoding, with tabs separating the
values.
Args:
columns_order: Delegated to ToCsv.
order_by: Delegated to ToCsv.
Returns:
... | Returns a file in tab-separated-format readable by MS Excel.
Returns a file in UTF-16 little endian encoding, with tabs separating the
values.
Args:
columns_order: Delegated to ToCsv.
order_by: Delegated to ToCsv.
Returns:
A tab-separated little endian UTF16 file representing the ta... |
def process_notes(notes, ref_data):
'''Add reference information to the bottom of a notes file
`:ref:` tags are removed and the actual reference data is appended
'''
ref_keys = ref_data.keys()
found_refs = set()
for k in ref_keys:
if k in notes:
found_refs.add(k)
# Th... | Add reference information to the bottom of a notes file
`:ref:` tags are removed and the actual reference data is appended |
def escape(s):
"""Convert the characters &, <, >, ' and " in string s to HTML-safe
sequences. Use this if you need to display text that might contain
such characters in HTML. Marks return value as markup string.
"""
if hasattr(s, '__html__'):
return s.__html__()
if isinstance(s, six.bi... | Convert the characters &, <, >, ' and " in string s to HTML-safe
sequences. Use this if you need to display text that might contain
such characters in HTML. Marks return value as markup string. |
def from_object(obj):
"""
Convert an object representing a contact information to an instance
`Contact`.
@param obj: an object containg the following attributes:
* `name`: an item of the enumeration `ContactName` representing the
type of this contact informat... | Convert an object representing a contact information to an instance
`Contact`.
@param obj: an object containg the following attributes:
* `name`: an item of the enumeration `ContactName` representing the
type of this contact information.
* `value`: value of this... |
def virtual_machines_list_available_sizes(name, resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Lists all available virtual machine sizes to which the specified virtual
machine can be resized.
:param name: The name of the virtual machine.
:param resou... | .. versionadded:: 2019.2.0
Lists all available virtual machine sizes to which the specified virtual
machine can be resized.
:param name: The name of the virtual machine.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash... |
def _create_ucsm_host_to_service_profile_mapping(self):
"""Reads list of Service profiles and finds associated Server."""
ucsm_ips = list(CONF.ml2_cisco_ucsm.ucsms)
for ucsm_ip in ucsm_ips:
with self.ucsm_connect_disconnect(ucsm_ip) as handle:
try:
... | Reads list of Service profiles and finds associated Server. |
def _update_valid_moves(self):
'''
Updates self.valid_moves according to the latest game state.
Assumes that the board and all hands are non-empty.
'''
left_end = self.board.left_end()
right_end = self.board.right_end()
moves = []
for d in self.hands[self... | Updates self.valid_moves according to the latest game state.
Assumes that the board and all hands are non-empty. |
def upload_files(selected_file, selected_host, only_link, file_name):
"""
Uploads selected file to the host, thanks to the fact that
every pomf.se based site has pretty much the same architecture.
"""
try:
answer = requests.post(
url=selected_host[0]+"upload.php",
fil... | Uploads selected file to the host, thanks to the fact that
every pomf.se based site has pretty much the same architecture. |
async def read_frame(self) -> DataFrame:
"""Read a single frame from the local buffer.
If no frames are available but the stream is still open, waits until
more frames arrive. Otherwise, raises StreamConsumedError.
When a stream is closed, a single `None` is added to the data frame
... | Read a single frame from the local buffer.
If no frames are available but the stream is still open, waits until
more frames arrive. Otherwise, raises StreamConsumedError.
When a stream is closed, a single `None` is added to the data frame
Queue to wake up any waiting `read_frame` corou... |
def canGoBack(self):
"""
Returns whether or not this wizard can move forward.
:return <bool>
"""
try:
backId = self._navigation.index(self.currentId())-1
if backId >= 0:
self._navigation[backId]
else:
return... | Returns whether or not this wizard can move forward.
:return <bool> |
def upsert(self, *fields):
"""
Update or Insert this document depending on whether it exists or not.
The presense of an `_id` value in the document is used to determine if
the document exists.
NOTE: This method is not the same as specifying the `upsert` flag when
calling... | Update or Insert this document depending on whether it exists or not.
The presense of an `_id` value in the document is used to determine if
the document exists.
NOTE: This method is not the same as specifying the `upsert` flag when
calling MongoDB. When called for a document with an `_... |
def load_config(path=None, defaults=None):
"""
Loads and parses an INI style configuration file using Python's built-in
ConfigParser module.
If path is specified, load it.
If ``defaults`` (a list of strings) is given, try to load each entry as a
file, without throwing any error if the operatio... | Loads and parses an INI style configuration file using Python's built-in
ConfigParser module.
If path is specified, load it.
If ``defaults`` (a list of strings) is given, try to load each entry as a
file, without throwing any error if the operation fails.
If ``defaults`` is not given, the followi... |
def dms2dd(degrees, minutes, seconds):
"""
Convert latitude/longitude of a location that is in degrees, minutes, seconds to decimal degrees
Parameters
----------
degrees : degrees of latitude/longitude
minutes : minutes of latitude/longitude
seconds : seconds of latitude/longitude
Retu... | Convert latitude/longitude of a location that is in degrees, minutes, seconds to decimal degrees
Parameters
----------
degrees : degrees of latitude/longitude
minutes : minutes of latitude/longitude
seconds : seconds of latitude/longitude
Returns
-------
degrees : decimal degrees of lo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.