code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def prepare_metadata(devkit_archive, test_groundtruth_path):
"""Extract dataset metadata required for HDF5 file setup.
Parameters
----------
devkit_archive : str or file-like object
The filename or file-handle for the gzipped TAR archive
containing the ILSVRC2010 development kit.
te... | Extract dataset metadata required for HDF5 file setup.
Parameters
----------
devkit_archive : str or file-like object
The filename or file-handle for the gzipped TAR archive
containing the ILSVRC2010 development kit.
test_groundtruth_path : str or file-like object
The filename o... |
def configure_default_logger(
self,
log_freq='midnight',
log_total=30,
log_level='INFO',
log_format=ReportingFormats.DEFAULT.value,
custom_args=''
):
"""default logger that every Prosper script should use!!
Args:
lo... | default logger that every Prosper script should use!!
Args:
log_freq (str): TimedRotatingFileHandle_str -- https://docs.python.org/3/library/logging.handlers.html#timedrotatingfilehandler
log_total (int): how many log_freq periods between log rotations
log_level (str): minim... |
def flush(self):
"""Erases queue and set `end-of-queue` message."""
while not self._queue.empty():
self._queue.get()
self._queue.task_done()
self.close() | Erases queue and set `end-of-queue` message. |
def intersect(self, other):
"""Returns a new :class:`~pyinter.Interval` representing the intersection of this :class:`~pyinter.Interval`
with the other :class:`~pyinter.Interval`"""
if self.overlaps(other):
newlower_value = max(self.lower_value, other.lower_value)
new_upp... | Returns a new :class:`~pyinter.Interval` representing the intersection of this :class:`~pyinter.Interval`
with the other :class:`~pyinter.Interval` |
def perform_evaluation(self):
"""
Determine which parts lie along the given vector, and what length
:return: effects on the given parts (in order of the distance from
the start point)
:rtype: list(:class:`VectorEffect`)
"""
# Create effect vector (with m... | Determine which parts lie along the given vector, and what length
:return: effects on the given parts (in order of the distance from
the start point)
:rtype: list(:class:`VectorEffect`) |
def _process_docs(self, anexec, docblocks, parent, module, docsearch):
"""Associates the docstrings from the docblocks with their parameters."""
#The documentation for the parameters is stored outside of the executable
#We need to get hold of them from docblocks from the parent text
key ... | Associates the docstrings from the docblocks with their parameters. |
def _parse_retry_after(self, response):
"""Parse Retry-After header from response if it is set."""
value = response.headers.get('Retry-After')
if not value:
seconds = 0
elif re.match(r'^\s*[0-9]+\s*$', value):
seconds = int(value)
else:
date_t... | Parse Retry-After header from response if it is set. |
def index_item(self, item):
"""
Index an item into our `name_to_item` dictionary.
If an object holding the same item's name/key already exists in the index
then the conflict is managed by the `manage_conflict` method.
:param item: item to index
:type item: alignak.object... | Index an item into our `name_to_item` dictionary.
If an object holding the same item's name/key already exists in the index
then the conflict is managed by the `manage_conflict` method.
:param item: item to index
:type item: alignak.objects.item.Item
:return: item modified
... |
def seek_monotonic(self, monotonic, bootid=None):
"""Seek to a matching journal entry nearest to `monotonic` time.
Argument `monotonic` is a timestamp from boot in either seconds or a
datetime.timedelta instance. Argument `bootid` is a string or UUID
representing which boot the monotoni... | Seek to a matching journal entry nearest to `monotonic` time.
Argument `monotonic` is a timestamp from boot in either seconds or a
datetime.timedelta instance. Argument `bootid` is a string or UUID
representing which boot the monotonic time is reference to. Defaults to
current bootid. |
def _parse_game_date_and_location(self, boxscore):
"""
Retrieve the game's date and location.
The date and location of the game follow a more complicated parsing
scheme and should be handled differently from other tags. Both fields
are separated by a newline character ('\n') wit... | Retrieve the game's date and location.
The date and location of the game follow a more complicated parsing
scheme and should be handled differently from other tags. Both fields
are separated by a newline character ('\n') with the first line being
the date and the second being the locati... |
async def pause_writing(self):
"""Pause writing."""
self._restart_writer = False
if self._writer_task:
self._writer_task.remove_done_callback(self.restart_writing)
self._writer_task.cancel()
await self._writer_task
await asyncio.sleep(0, loop=self.... | Pause writing. |
def forget(self, *keys):
"""
Remove an item from the collection by key.
:param keys: The keys to remove
:type keys: tuple
:rtype: Collection
"""
keys = reversed(sorted(keys))
for key in keys:
del self[key]
return self | Remove an item from the collection by key.
:param keys: The keys to remove
:type keys: tuple
:rtype: Collection |
def spia_matrices_to_excel(spia_matrices: Mapping[str, pd.DataFrame], path: str) -> None:
"""Export a SPIA data dictionary into an Excel sheet at the given path.
.. note::
# The R import should add the values:
# ["nodes"] from the columns
# ["title"] from the name of the file
#... | Export a SPIA data dictionary into an Excel sheet at the given path.
.. note::
# The R import should add the values:
# ["nodes"] from the columns
# ["title"] from the name of the file
# ["NumberOfReactions"] set to "0" |
def generateIdentityKeyPair():
"""
Generate an identity key pair. Clients should only do this once,
at install time.
@return the generated IdentityKeyPair.
"""
keyPair = Curve.generateKeyPair()
publicKey = IdentityKey(keyPair.getPublicKey())
serialized = ... | Generate an identity key pair. Clients should only do this once,
at install time.
@return the generated IdentityKeyPair. |
def set_json(self, config_json):
"""Permanently set the JSON configuration
Unable to call twice."""
if self.configuration_dict is not None:
raise RuntimeError("Can only set configuration once", self.configuration_dict)
schema = fetch_config('ConfigurationSchema.json')
... | Permanently set the JSON configuration
Unable to call twice. |
def delete_database(self, name_or_obj):
"""
Deletes the specified database. If no database by that name
exists, no exception will be raised; instead, nothing at all
is done.
"""
name = utils.get_name(name_or_obj)
self._database_manager.delete(name) | Deletes the specified database. If no database by that name
exists, no exception will be raised; instead, nothing at all
is done. |
def addinputfile(self, project, inputtemplate, sourcefile, **kwargs):
"""Add/upload an input file to the CLAM service. Supports proper file upload streaming.
project - the ID of the project you want to add the file to.
inputtemplate - The input template you want to use to add this file (InputTe... | Add/upload an input file to the CLAM service. Supports proper file upload streaming.
project - the ID of the project you want to add the file to.
inputtemplate - The input template you want to use to add this file (InputTemplate instance)
sourcefile - The file you want to add: string containing... |
def _translate_src_oprnd(self, operand):
"""Translate source operand to a SMT expression.
"""
if isinstance(operand, ReilRegisterOperand):
return self._translate_src_register_oprnd(operand)
elif isinstance(operand, ReilImmediateOperand):
return smtsymbol.Constant(... | Translate source operand to a SMT expression. |
def scan(self, filetypes=None):
"""Iterates over the content of the disk and queries VirusTotal
to determine whether it's malicious or not.
filetypes is a list containing regular expression patterns.
If given, only the files which type will match with one or more of
the given pa... | Iterates over the content of the disk and queries VirusTotal
to determine whether it's malicious or not.
filetypes is a list containing regular expression patterns.
If given, only the files which type will match with one or more of
the given patterns will be queried against VirusTotal.
... |
def quick_search(self, name, platform=None, sort_by=None, desc=True):
"""
Quick search method that allows you to search for a game using only the
title and the platform
:param name: string
:param platform: int
:param sort_by: string
:param desc: bool
:ret... | Quick search method that allows you to search for a game using only the
title and the platform
:param name: string
:param platform: int
:param sort_by: string
:param desc: bool
:return: pybomb.clients.Response |
def progressbar(total, pos, msg=""):
"""
Given a total and a progress position, output a progress bar
to stderr. It is important to not output anything else while
using this, as it relies soley on the behavior of carriage
return (\\r).
Can also take an optioal message to add after the
progr... | Given a total and a progress position, output a progress bar
to stderr. It is important to not output anything else while
using this, as it relies soley on the behavior of carriage
return (\\r).
Can also take an optioal message to add after the
progressbar. It must not contain newlines.
The pr... |
def lower_case(f):
"""Decorator specifically for turning mssql AST into lowercase"""
# if it has already been wrapped, we return original
if hasattr(f, "lower_cased"):
return f
@wraps(f)
def wrapper(*args, **kwargs):
f.lower_cased = True
return f(*args, **kwargs).lower()
... | Decorator specifically for turning mssql AST into lowercase |
def parse(self):
"""
Return the list of string of all the decorators found
"""
self._parse(self.method)
return list(set([deco for deco in self.decos if deco])) | Return the list of string of all the decorators found |
def get_cfn_attribute(self, attribute_name):
'''
Implemented attributes:
* DNSName
* LoadBalancerName
Not implemented:
* CanonicalHostedZoneID
* LoadBalancerFullName
* SecurityGroups
This method is similar to models.py:FakeLoadBalancer.get_cfn_at... | Implemented attributes:
* DNSName
* LoadBalancerName
Not implemented:
* CanonicalHostedZoneID
* LoadBalancerFullName
* SecurityGroups
This method is similar to models.py:FakeLoadBalancer.get_cfn_attribute() |
def copy(src, trg, transform=None):
''' copy items with optional fields transformation
'''
source = open(src[0], src[1])
target = open(trg[0], trg[1], autocommit=1000)
for item in source.get():
item = dict(item)
if '_id' in item:
del item['_id']
if transform:
... | copy items with optional fields transformation |
def _add_skyline(self, rect):
"""
Arguments:
seg (Rectangle):
"""
skylineq = collections.deque([]) # Skyline after adding new one
for sky in self._skyline:
if sky.right <= rect.left or sky.left >= rect.right:
self._merge_skyline(sk... | Arguments:
seg (Rectangle): |
def on_response(self, ch, method, props, body):
"""
All RPC response will call this method, so change the isAccept to True in this method
所有的RPC请求回调都会调用该方法,在该方法内修改对应corr_id已经接受消息的isAccept值和返回结果
"""
logger.info("on response => {}".format(body))
corr_id = props.correlation... | All RPC response will call this method, so change the isAccept to True in this method
所有的RPC请求回调都会调用该方法,在该方法内修改对应corr_id已经接受消息的isAccept值和返回结果 |
def maxwellian(E: np.ndarray, E0: np.ndarray, Q0: np.ndarray) -> Tuple[np.ndarray, float]:
"""
input:
------
E: 1-D vector of energy bins [eV]
E0: characteristic energy (scalar or vector) [eV]
Q0: flux coefficient (scalar or vector) (to yield overall flux Q)
output:
-------
Phi: dif... | input:
------
E: 1-D vector of energy bins [eV]
E0: characteristic energy (scalar or vector) [eV]
Q0: flux coefficient (scalar or vector) (to yield overall flux Q)
output:
-------
Phi: differential number flux
Q: total flux
Tanaka 2006 Eqn. 1
http://odin.gi.alaska.edu/lumm/Pape... |
def default_pixmap(self, value):
"""
Setter for **self.__default_pixmap** attribute.
:param value: Attribute value.
:type value: QPixmap
"""
if value is not None:
assert type(value) is QPixmap, "'{0}' attribute: '{1}' type is not 'QPixmap'!".format(
... | Setter for **self.__default_pixmap** attribute.
:param value: Attribute value.
:type value: QPixmap |
def append(self, key, value):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists."""
self.__items.append((key, value))
try:
dict_getitem(self, key).append(value)
except KeyError:
dict_setitem(self, key, [value]) | Adds a (name, value) pair, doesn't overwrite the value if it already
exists. |
def influx_count_(self, measurement):
"""
Count the number of rows for a measurement
"""
try:
q = "select count(*) from " + measurement
self.start("Querying: count ...")
datalen = self.influx_cli.query(q)
self.end("Finished querying")
... | Count the number of rows for a measurement |
def with_columns(self, *labels_and_values):
"""Return a table with additional or replaced columns.
Args:
``labels_and_values``: An alternating list of labels and values or
a list of label-value pairs. If one of the labels is in
existing table, then every val... | Return a table with additional or replaced columns.
Args:
``labels_and_values``: An alternating list of labels and values or
a list of label-value pairs. If one of the labels is in
existing table, then every value in the corresponding column is
set t... |
def join_key_value(key, value, separator='='):
r"""
Join a key and value together into a single line suitable for adding to a
simple line-oriented ``.properties`` file. No trailing newline is added.
>>> join_key_value('possible separators', '= : space')
'possible\\ separators=\\= \\: space'
:... | r"""
Join a key and value together into a single line suitable for adding to a
simple line-oriented ``.properties`` file. No trailing newline is added.
>>> join_key_value('possible separators', '= : space')
'possible\\ separators=\\= \\: space'
:param key: the key
:type key: text string
:... |
def get_question(self, number: str=None) -> dict:
"""
取得課程中的所有題目資訊
"""
try:
# 取得資料
response = self.__session.get(
self.__url + '/HomeworkBoard', timeout=0.5, verify=False)
soup = BeautifulSoup(response.text, 'html.parser')
#... | 取得課程中的所有題目資訊 |
def _is_finished_dumping(directory):
"""Determine if the sequencing directory has all files.
The final checkpoint file will differ depending if we are a
single or paired end run.
"""
#if _is_finished_dumping_checkpoint(directory):
# return True
# Check final output files; handles both Hi... | Determine if the sequencing directory has all files.
The final checkpoint file will differ depending if we are a
single or paired end run. |
def fetchall(self):
"""Fetch all (remaining) rows of a query result, returning them as a sequence of sequences
(e.g. a list of tuples).
"""
if self._state == self._STATE_NONE:
raise Exception("No query yet")
if not self._data:
return []
else:
... | Fetch all (remaining) rows of a query result, returning them as a sequence of sequences
(e.g. a list of tuples). |
def remove_router_from_hosting_device(self, client, hosting_device_id,
router_id):
"""Remove a router from hosting_device."""
res_path = hostingdevice.HostingDevice.resource_path
return client.delete((res_path + DEVICE_L3_ROUTERS + "/%s") % (
... | Remove a router from hosting_device. |
def add_reads(self, reads):
"""
Create another VariantSequence with more supporting reads.
"""
if len(reads) == 0:
return self
new_reads = self.reads.union(reads)
if len(new_reads) > len(self.reads):
return VariantSequence(
prefix=s... | Create another VariantSequence with more supporting reads. |
def create_thumb(self):
"""Create the thumbnail for html output"""
thumbnail_figure = self.copy_thumbnail_figure()
if thumbnail_figure is not None:
if isinstance(thumbnail_figure, six.string_types):
pic = thumbnail_figure
else:
pic = self.p... | Create the thumbnail for html output |
def get_weather_forecast(self, latitude, longitude, start, end,
frequency=1, reading_type=None):
"""
Return the weather forecast for a given location for specific
datetime specified in UTC format.
::
results = ws.get_weather_forecast(lat, long, start, end)
... | Return the weather forecast for a given location for specific
datetime specified in UTC format.
::
results = ws.get_weather_forecast(lat, long, start, end)
for w in results['hits']:
print w['start_datetime_local']
print w['reading_type'], '=', w[... |
def evalall(self, loc=None, defaults=None):
"""Evaluates all option values in environment `loc`.
:See: `eval()`
"""
self.check()
if defaults is None:
defaults = cma_default_options
# TODO: this needs rather the parameter N instead of loc
if 'N' in lo... | Evaluates all option values in environment `loc`.
:See: `eval()` |
def aes_ecb_decrypt(self, key_handle, ciphertext):
"""
AES ECB decrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param ciphertext: Data to decrypt
... | AES ECB decrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param ciphertext: Data to decrypt
@type key_handle: integer or string
@type ciphertext: string
... |
def get_user_data_iobject(user=None,group=None,data_kind=DINGOS_USER_DATA_TYPE_NAME):
"""
Returns either stored settings of a given user or default settings.
This behavior reflects the need for views to have some settings at
hand when running. The settings are returned as dict object.
... | Returns either stored settings of a given user or default settings.
This behavior reflects the need for views to have some settings at
hand when running. The settings are returned as dict object. |
def get_sockinfo (host, port=None):
"""Return socket.getaddrinfo for given host and port."""
family, socktype = socket.AF_INET, socket.SOCK_STREAM
return socket.getaddrinfo(host, port, family, socktype) | Return socket.getaddrinfo for given host and port. |
def add_chain(self, group_name, component_map):
"""
Adds the component chain to ``group_name`` in the fast5.
These are added as attributes to the group.
:param group_name: The group name you wish to add chaining data to,
e.g. ``Test_000``
:param component_map: The se... | Adds the component chain to ``group_name`` in the fast5.
These are added as attributes to the group.
:param group_name: The group name you wish to add chaining data to,
e.g. ``Test_000``
:param component_map: The set of components and corresponding
group names or group p... |
def parse_variant_playlist(cls, session_, url, name_key="name",
name_prefix="", check_streams=False,
force_restart=False, name_fmt=None,
start_offset=0, duration=None,
**request_params):
"... | Attempts to parse a variant playlist and return its streams.
:param url: The URL of the variant playlist.
:param name_key: Prefer to use this key as stream name, valid keys are:
name, pixels, bitrate.
:param name_prefix: Add this prefix to the stream names.
:par... |
def write(self, filename=None, output="dict", attribute_indent=4):
"""
This method writes the dict into various output formats. This includes a dict,
json, and yaml
:param filename: the file in which the dict is written
:param output: is a string that is either "dict", "json", "y... | This method writes the dict into various output formats. This includes a dict,
json, and yaml
:param filename: the file in which the dict is written
:param output: is a string that is either "dict", "json", "yaml"
:param attribute_indent: character indentation of nested attributes in |
def jupytext_cli(args=None):
"""Entry point for the jupytext script"""
try:
jupytext(args)
except (ValueError, TypeError, IOError) as err:
sys.stderr.write('[jupytext] Error: ' + str(err) + '\n')
exit(1) | Entry point for the jupytext script |
def _shift_headings(self, content: str, shift: int) -> str:
'''Shift Markdown headings in a string by a given value. The shift can
be positive or negative.
:param content: Markdown content
:param shift: Heading shift
:returns: Markdown content with headings shifted by ``shift``... | Shift Markdown headings in a string by a given value. The shift can
be positive or negative.
:param content: Markdown content
:param shift: Heading shift
:returns: Markdown content with headings shifted by ``shift`` |
def from_elan(cls: Type[CorpusT], org_dir: Path, tgt_dir: Path,
feat_type: str = "fbank", label_type: str = "phonemes",
utterance_filter: Callable[[Utterance], bool] = None,
label_segmenter: Optional[LabelSegmenter] = None,
speakers: List[str] = No... | Construct a `Corpus` from ELAN files.
Args:
org_dir: A path to the directory containing the unpreprocessed
data.
tgt_dir: A path to the directory where the preprocessed data will
be stored.
feat_type: A string describing the input speech featu... |
def print_line(line):
"""
Print given line to stdout (i3bar).
"""
sys.__stdout__.write("{}\n".format(line))
sys.__stdout__.flush() | Print given line to stdout (i3bar). |
def add_remote_provider(self, provider, client, path):
"""Adds a remote configuration source.
Remote Providers are searched in the order they are added.
provider is a string value, "etcd", "consul" and "zookeeper" are
currently supported.
client is a client object
path is... | Adds a remote configuration source.
Remote Providers are searched in the order they are added.
provider is a string value, "etcd", "consul" and "zookeeper" are
currently supported.
client is a client object
path is the path in the k/v store to retrieve configuration
To re... |
def get_instance(self, payload):
"""
Build an instance of AuthCallsCredentialListMappingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialLis... | Build an instance of AuthCallsCredentialListMappingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance
:rtype: twilio.rest.api.v201... |
def bounding_box(self):
"""
The minimal bounding box (`~regions.BoundingBox`) enclosing the
exact rectangular region.
"""
w2 = self.width / 2.
h2 = self.height / 2.
cos_angle = np.cos(self.angle) # self.angle is a Quantity
sin_angle = np.sin(self.angle... | The minimal bounding box (`~regions.BoundingBox`) enclosing the
exact rectangular region. |
def _stream_search(self, query):
"""Helper method for iterating over Solr search results."""
for doc in self.solr.search(query, rows=100000000):
if self.unique_key != "_id":
doc["_id"] = doc.pop(self.unique_key)
yield doc | Helper method for iterating over Solr search results. |
def write_file(self, filename, distance=6, velocity=8, charge=3):
"""
Writes LammpsData to file.
Args:
filename (str): Filename.
distance (int): No. of significant figures to output for
box settings (bounds and tilt) and atomic coordinates.
... | Writes LammpsData to file.
Args:
filename (str): Filename.
distance (int): No. of significant figures to output for
box settings (bounds and tilt) and atomic coordinates.
Default to 6.
velocity (int): No. of significant figures to output for
... |
def visit_ImportFrom(self, node):
"""
Check validity of imported functions.
Check:
- no level specific value are provided.
- a module is provided
- module/submodule exists in MODULES
- imported function exists in the given ... | Check validity of imported functions.
Check:
- no level specific value are provided.
- a module is provided
- module/submodule exists in MODULES
- imported function exists in the given module/submodule |
def get_atom_sequence_to_rosetta_map(self):
'''Uses the Rosetta->ATOM injective map to construct an injective mapping from ATOM->Rosetta.
We do not extend the injection to include ATOM residues which have no corresponding Rosetta residue.
e.g. atom_sequence_to_rosetta_mapping[c].map.get(... | Uses the Rosetta->ATOM injective map to construct an injective mapping from ATOM->Rosetta.
We do not extend the injection to include ATOM residues which have no corresponding Rosetta residue.
e.g. atom_sequence_to_rosetta_mapping[c].map.get('A 45 ') will return None if there is no corresponding... |
def list_items(self, sort_key=None, reverse=False):
"""Return a list of cart items.
Parameters
----------
sort_key : func
A function to customize the list order, same as the 'key'
argument to the built-in :func:`sorted`.
reverse: bool
If set t... | Return a list of cart items.
Parameters
----------
sort_key : func
A function to customize the list order, same as the 'key'
argument to the built-in :func:`sorted`.
reverse: bool
If set to True, the sort order will be reversed.
Returns
... |
def get_event(self, param):
""" Returns an Event instance by it's id
:param param: an event_id or a Query instance
:return: event for the specified info
:rtype: Event
"""
if param is None:
return None
if isinstance(param, str):
url = self... | Returns an Event instance by it's id
:param param: an event_id or a Query instance
:return: event for the specified info
:rtype: Event |
def save(self, *args, **kwargs):
"""
Fill 'created' and 'modified' attributes on first create
"""
if self.created is None:
self.created = tz_now()
if self.modified is None:
self.modified = self.created
super(Thread, self).save... | Fill 'created' and 'modified' attributes on first create |
def json_get(serialized_object, field):
"""
This emulates the HSTORE `->` get value operation.
It get value from JSON serialized column by given key and return `null` if not present.
Key can be either an integer for array index access or a string for object field access.
:return: JSON serialized va... | This emulates the HSTORE `->` get value operation.
It get value from JSON serialized column by given key and return `null` if not present.
Key can be either an integer for array index access or a string for object field access.
:return: JSON serialized value of key in object |
def update(self, default_activity_sid=values.unset,
event_callback_url=values.unset, events_filter=values.unset,
friendly_name=values.unset, multi_task_enabled=values.unset,
timeout_activity_sid=values.unset,
prioritize_queue_order=values.unset):
"""
... | Update the WorkspaceInstance
:param unicode default_activity_sid: The ID of the Activity that will be used when new Workers are created in this Workspace.
:param unicode event_callback_url: The Workspace will publish events to this URL.
:param unicode events_filter: Use this parameter to receiv... |
def pretty(self):
"sort values and format output for viewing and comparing in test scenarios"
pretty_obj = OrderedDict()
for key, value in sorted(iteritems(self.__dict__)):
if value is None:
pretty_obj[key] = None
elif is_str_or_unicode(value):
... | sort values and format output for viewing and comparing in test scenarios |
def sonar_config(self, trigger_pin, echo_pin, cb=None, ping_interval=50, max_distance=200):
"""
Configure the pins,ping interval and maximum distance for an HC-SR04 type device.
Single pin configuration may be used. To do so, set both the trigger and echo pins to the same value.
Up to a ... | Configure the pins,ping interval and maximum distance for an HC-SR04 type device.
Single pin configuration may be used. To do so, set both the trigger and echo pins to the same value.
Up to a maximum of 6 SONAR devices is supported
If the maximum is exceeded a message is sent to the console and ... |
def histogram(data, bins=None, *args, **kwargs):
"""Facade function to create 1D histograms.
This proceeds in three steps:
1) Based on magical parameter bins, construct bins for the histogram
2) Calculate frequencies for the bins
3) Construct the histogram object itself
*Guiding principle:* pa... | Facade function to create 1D histograms.
This proceeds in three steps:
1) Based on magical parameter bins, construct bins for the histogram
2) Calculate frequencies for the bins
3) Construct the histogram object itself
*Guiding principle:* parameters understood by numpy.histogram should be
und... |
def MessageToJson(message, including_default_value_fields=False):
"""Converts protobuf message to JSON format.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serial... | Converts protobuf message to JSON format.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular mes... |
def run(self):
"""Runs until stopEvent is notified, and notify
observers of all reader insertion/removal.
"""
while not self.stopEvent.isSet():
try:
# no need to monitor if no observers
if 0 < self.observable.countObservers():
... | Runs until stopEvent is notified, and notify
observers of all reader insertion/removal. |
def fetcher_factory(conf):
"""Return initialized fetcher capable of processing given conf."""
global PROMOTERS
applicable = []
if not PROMOTERS:
PROMOTERS = load_promoters()
for promoter in PROMOTERS:
if promoter.is_applicable(conf):
applicable.append((promoter.PRIORITY, ... | Return initialized fetcher capable of processing given conf. |
def p_identlist(self, t):
'''identlist : IDENT
| NOT IDENT
| IDENT AND identlist
| NOT IDENT AND identlist
'''
if len(t)==5 :
#print(t[1],t[2],t[3],t[4])
t[0] = t[1]+t[2]+t[3]+t[4]
elif len(t)==4 :
#pri... | identlist : IDENT
| NOT IDENT
| IDENT AND identlist
| NOT IDENT AND identlist |
def strip_hidden(key_tuples, visibilities):
"""Filter each tuple according to visibility.
Args:
key_tuples: A sequence of tuples of equal length (i.e. rectangular)
visibilities: A sequence of booleans equal in length to the tuples contained in key_tuples.
Returns:
A sequence equal ... | Filter each tuple according to visibility.
Args:
key_tuples: A sequence of tuples of equal length (i.e. rectangular)
visibilities: A sequence of booleans equal in length to the tuples contained in key_tuples.
Returns:
A sequence equal in length to key_tuples where the items are tuples ... |
def _print_cline(self, buf, i, icol):
"""
Print clines after multirow-blocks are finished
"""
for cl in self.clinebuf:
if cl[0] == i:
buf.write('\\cline{{{cl:d}-{icol:d}}}\n'
.format(cl=cl[1], icol=icol))
# remove entries that... | Print clines after multirow-blocks are finished |
def dump(obj, fp, **user_kwargs):
"""Serialize ``obj`` as a JSON-formatted stream and write to ``fp`` (a
``.write()``-supporting file-like object.
"""
return json.dump(obj, fp, **_encoder_kwargs(user_kwargs)) | Serialize ``obj`` as a JSON-formatted stream and write to ``fp`` (a
``.write()``-supporting file-like object. |
def get(ctx, resource, id):
"""Gets all of the information (fields) for a given device model or
instance.
"""
session, api_url, project_id = build_client_from_context(ctx)
url = '/'.join([api_url, resource, id])
r = session.get(url)
if r.status_code != 200:
raise failed_request_excep... | Gets all of the information (fields) for a given device model or
instance. |
def ffill(self, dim, limit=None):
'''Fill NaN values by propogating values forward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, default None
... | Fill NaN values by propogating values forward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, default None
The maximum number of consecutive NaN values ... |
def share(self, fmto, **kwargs):
"""Share the settings of this formatoption with other data objects
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to share the attributes with
``**kwargs``
Any other keyword argument that shall... | Share the settings of this formatoption with other data objects
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to share the attributes with
``**kwargs``
Any other keyword argument that shall be passed to the update
method ... |
def isoratio_init(self,isos):
'''
This file returns the isotopic ratio of two isotopes specified
as iso1 and iso2. The isotopes are given as, e.g.,
['Fe',56,'Fe',58] or ['Fe-56','Fe-58'] (for compatibility)
-> list.
'''
if len(isos) == 2:
dumb = []
... | This file returns the isotopic ratio of two isotopes specified
as iso1 and iso2. The isotopes are given as, e.g.,
['Fe',56,'Fe',58] or ['Fe-56','Fe-58'] (for compatibility)
-> list. |
def calls(self, truncate=False):
"""
Show 10 most frequently called queries. Requires the pg_stat_statements
Postgres module to be installed.
Record(
query='BEGIN;',
exec_time=datetime.timedelta(0, 0, 288174),
prop_exec_time='0.0%',
ncalls... | Show 10 most frequently called queries. Requires the pg_stat_statements
Postgres module to be installed.
Record(
query='BEGIN;',
exec_time=datetime.timedelta(0, 0, 288174),
prop_exec_time='0.0%',
ncalls='845590',
sync_io_time=datetime.timedelt... |
def get_lr(self, score):
"""Compute a :float: likelihood ratio from a provided similarity score when compared
to two probability density functions which are computed and pre-loaded during init.
The numerator indicates the probability density that a particular similarity score
correspond... | Compute a :float: likelihood ratio from a provided similarity score when compared
to two probability density functions which are computed and pre-loaded during init.
The numerator indicates the probability density that a particular similarity score
corresponds to a 'good' addon donor, i.e. a cl... |
def checkbox_field(*args, **kwargs):
'''
Checkbox field
'''
checkbox_field = wtforms.BooleanField(*args, **kwargs)
checkbox_field.input_type = 'checkbox_field'
return checkbox_field | Checkbox field |
def __find_reports(self, report_type, usage_page, usage_id = 0):
"Find input report referencing HID usage control/data item"
if not self.is_opened():
raise HIDError("Device must be opened")
#
results = list()
if usage_page:
for report_id in self.rep... | Find input report referencing HID usage control/data item |
def set_shaders(self, vert, frag):
""" This function takes care of setting the shading code and
compiling+linking it into a working program object that is ready
to use.
"""
self._linked = False
# Create temporary shader objects
vert_handle = gl.glCreateShader(gl.G... | This function takes care of setting the shading code and
compiling+linking it into a working program object that is ready
to use. |
def isnumber(*args):
"""Checks if value is an integer, long integer or float.
NOTE: Treats booleans as numbers, where True=1 and False=0.
"""
return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args)) | Checks if value is an integer, long integer or float.
NOTE: Treats booleans as numbers, where True=1 and False=0. |
def _extend_word(self, word, length, prefix=0, end=False, flatten=False):
"""
Extend the given word with a random suffix up to length.
:param length: the length of the extended word; >= len(word);
:param prefix: if greater than 0, the maximum length of the prefix to
... | Extend the given word with a random suffix up to length.
:param length: the length of the extended word; >= len(word);
:param prefix: if greater than 0, the maximum length of the prefix to
consider to choose the next character;
:param end: if True, the generated word ends... |
def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
if self.limits != {}:
return self.limits
... | Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict |
def find_by_index(self, cls, index_name, value):
"""Required functionality."""
query_args = {
index_name + '__eq': DynamoMappings.map_index_val(value),
'index': gsi_name(index_name)
}
final_results = []
for db_result in self.get_class_table(cls).query_2(*... | Required functionality. |
def execute(self, query, args, consistency):
"""
Execute a CQL query against the server.
:param query: The CQL query to execute
:type query: str.
:param args: The arguments to substitute
:type args: dict.
:param consistency: The consistency level
:type ... | Execute a CQL query against the server.
:param query: The CQL query to execute
:type query: str.
:param args: The arguments to substitute
:type args: dict.
:param consistency: The consistency level
:type consistency: ConsistencyLevel
In order to avoid unpleasa... |
def send(self, msg, timeout=None, tries=None):
'''
Send a message to an IPC socket
If the socket is not currently connected, a connection will be established.
:param dict msg: The message to be sent
:param int timeout: Timeout when sending message (Currently unimplemented)
... | Send a message to an IPC socket
If the socket is not currently connected, a connection will be established.
:param dict msg: The message to be sent
:param int timeout: Timeout when sending message (Currently unimplemented) |
def get_queryset(self):
"""
This viewset provides a helper attribute to prefetch related models
based on the include specified in the URL.
__all__ can be used to specify a prefetch which should be done regardless of the include
.. code:: python
# When MyViewSet is ... | This viewset provides a helper attribute to prefetch related models
based on the include specified in the URL.
__all__ can be used to specify a prefetch which should be done regardless of the include
.. code:: python
# When MyViewSet is called with ?include=author it will prefetch... |
def is_dir_exists(dirpath):
# type: (AnyStr) -> bool
"""Check the existence of folder path."""
if dirpath is None or not os.path.exists(dirpath) or not os.path.isdir(dirpath):
return False
else:
return True | Check the existence of folder path. |
def proxify_routine(routine, impl=None):
"""Proxify a routine with input impl.
:param routine: routine to proxify.
:param impl: new impl to use. If None, use routine.
"""
# init impl
impl = routine if impl is None else impl
is_method = ismethod(routine)
if is_method:
function ... | Proxify a routine with input impl.
:param routine: routine to proxify.
:param impl: new impl to use. If None, use routine. |
def max(self, axis=None, dtype=None, out=None, keepdims=False):
"""Return the maximum of ``self``.
See Also
--------
numpy.amax
min
"""
return self.elem.__array_ufunc__(
np.maximum, 'reduce', self.elem,
axis=axis, dtype=dtype, out=(out,), ... | Return the maximum of ``self``.
See Also
--------
numpy.amax
min |
def match_relative_fit(imglist, reference_catalog):
"""Perform cross-matching and final fit using 2dHistogram matching
Parameters
----------
imglist : list
List of input image `~tweakwcs.tpwcs.FITSWCS` objects with metadata and source catalogs
reference_catalog : Table
Astropy Tabl... | Perform cross-matching and final fit using 2dHistogram matching
Parameters
----------
imglist : list
List of input image `~tweakwcs.tpwcs.FITSWCS` objects with metadata and source catalogs
reference_catalog : Table
Astropy Table of reference sources for this field
Returns
----... |
def save(self, expected_value=None, return_values=None):
"""
Commits pending updates to Amazon DynamoDB.
:type expected_value: dict
:param expected_value: A dictionary of name/value pairs that
you expect. This dictionary should have name/value pairs
where the na... | Commits pending updates to Amazon DynamoDB.
:type expected_value: dict
:param expected_value: A dictionary of name/value pairs that
you expect. This dictionary should have name/value pairs
where the name is the name of the attribute and the value is
either the value... |
def safe(self,x):
"""removes nans and infs from outputs."""
x[np.isinf(x)] = 1
x[np.isnan(x)] = 1
return x | removes nans and infs from outputs. |
def get_all_cpv_use(cp):
'''
.. versionadded:: 2015.8.0
Uses portage to determine final USE flags and settings for an emerge.
@type cp: string
@param cp: eg cat/pkg
@rtype: lists
@return use, use_expand_hidden, usemask, useforce
'''
cpv = _get_cpv(cp)
portage = _get_portage()
... | .. versionadded:: 2015.8.0
Uses portage to determine final USE flags and settings for an emerge.
@type cp: string
@param cp: eg cat/pkg
@rtype: lists
@return use, use_expand_hidden, usemask, useforce |
def _setup_environ(self):
"""
Apply changes from /etc/environment files before creating a
TemporaryEnvironment to snapshot environment state prior to module run.
"""
_pam_env_watcher.check()
_etc_env_watcher.check()
env = dict(self.extra_env or {})
if self... | Apply changes from /etc/environment files before creating a
TemporaryEnvironment to snapshot environment state prior to module run. |
def add_validate(subparsers):
"""Validate Spinnaker setup."""
validate_parser = subparsers.add_parser(
'validate', help=add_validate.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
validate_parser.set_defaults(func=validate_parser.print_help)
validate_subparsers = validate_pars... | Validate Spinnaker setup. |
def stop(self):
"""Stop watching the socket."""
if self.closed:
raise ConnectionClosed()
if self.read_watcher.active:
self.read_watcher.stop()
if self.write_watcher.active:
self.write_watcher.stop() | Stop watching the socket. |
def softmax_cross_entropy_with_logits(sentinel=None,
labels=None,
logits=None,
dim=-1):
"""
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning
"""
# Make sure t... | Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.