code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def kv(d):
"""Equivalent to dict.items().
Usage::
>>> for key, node in DictTree.kv(d):
>>> print(key, DictTree.getattr(node, "population"))
MD 200000
VA 100000
"""
return ((key, value) for key, value in iteritems(d) ... | Equivalent to dict.items().
Usage::
>>> for key, node in DictTree.kv(d):
>>> print(key, DictTree.getattr(node, "population"))
MD 200000
VA 100000 |
def find_node(self, x: int, y: int) -> Optional["BSP"]:
"""Return the deepest node which contains these coordinates.
Returns:
Optional[BSP]: BSP object or None.
"""
if not self.contains(x, y):
return None
for child in self.children:
found = ch... | Return the deepest node which contains these coordinates.
Returns:
Optional[BSP]: BSP object or None. |
def _set_dns_server_global(self, v, load=False):
"""
Setter method for dns_server_global, mapped from YANG variable /ipv6/ipv6_global_cmds/nd_global/dns_server_global (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_dns_server_global is considered as a private
... | Setter method for dns_server_global, mapped from YANG variable /ipv6/ipv6_global_cmds/nd_global/dns_server_global (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_dns_server_global is considered as a private
method. Backends looking to populate this variable should
... |
def _subfeed(self, feedname):
""" Used for Inbox/Outbox major/minor/direct subfeeds """
url = self.url
if not url.endswith("/"):
url += "/"
return url + feedname | Used for Inbox/Outbox major/minor/direct subfeeds |
def listify(value):
"""
Wrap the given value into a list, with the below provisions:
* If the value is a list or a tuple, it's coerced into a new list.
* If the value is None, an empty list is returned.
* Otherwise, a single-element list is returned, containing the value.
:param value: A value... | Wrap the given value into a list, with the below provisions:
* If the value is a list or a tuple, it's coerced into a new list.
* If the value is None, an empty list is returned.
* Otherwise, a single-element list is returned, containing the value.
:param value: A value.
:return: a list!
:rtyp... |
def _message_generator(self):
"""Iterate over processed messages in the receive queue.
:rtype: generator[~uamqp.message.Message]
"""
self.open()
auto_complete = self.auto_complete
self.auto_complete = False
receiving = True
message = None
try:
... | Iterate over processed messages in the receive queue.
:rtype: generator[~uamqp.message.Message] |
def envget(var, default=None):
"""Get value of IRAF or OS environment variable."""
if 'pyraf' in sys.modules:
#ONLY if pyraf is already loaded, import iraf into the namespace
from pyraf import iraf
else:
# else set iraf to None so it knows to not use iraf's environment
iraf ... | Get value of IRAF or OS environment variable. |
def Nor(*xs, simplify=True):
"""Expression NOR (not OR) operator
If *simplify* is ``True``, return a simplified expression.
"""
xs = [Expression.box(x).node for x in xs]
y = exprnode.not_(exprnode.or_(*xs))
if simplify:
y = y.simplify()
return _expr(y) | Expression NOR (not OR) operator
If *simplify* is ``True``, return a simplified expression. |
def on_start(self):
"""
start requester
"""
LOGGER.debug("rabbitmq.Requester.on_start")
if not self.fire_and_forget:
self.channel.basic_consume(self.on_response, no_ack=True,
queue=self.callback_queue) | start requester |
def iter_merge(cls, timeseries_list):
"""Iterate through several time series in order, yielding (time, list)
tuples where list is the values of each individual TimeSeries
in the list at time t.
"""
# using return without an argument is the way to say "the
# iterator is e... | Iterate through several time series in order, yielding (time, list)
tuples where list is the values of each individual TimeSeries
in the list at time t. |
def fetch_new_release_category(self, category_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches new release categories by given ID.
:param category_id: the station ID.
:type category_id: str
:param terr: the current territory.
:return: API response.
:rtype: list
... | Fetches new release categories by given ID.
:param category_id: the station ID.
:type category_id: str
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#newreleasecategories-category_id` |
def write_grindstone(self):
"""
Writes self.gs to self.grindstone_path.
"""
with open(self.grindstone_path, 'w') as f:
# Write the JSON dump of the file
f.write(json.dumps(self.grindstone)) | Writes self.gs to self.grindstone_path. |
def save(self, commit=False):
"""Save the changes to the model.
If the model has not been persisted
then it adds the model to the declared session. Then it flushes the
object session and optionally commits it.
"""
if not has_identity(self):
# Object has not b... | Save the changes to the model.
If the model has not been persisted
then it adds the model to the declared session. Then it flushes the
object session and optionally commits it. |
def debug_toolbar_callback(request):
"""Show the debug toolbar to those with the Django staff permission, excluding the Eighth Period
office."""
if request.is_ajax():
return False
if not hasattr(request, 'user'):
return False
if not request.user.is_authenticated:
return Fal... | Show the debug toolbar to those with the Django staff permission, excluding the Eighth Period
office. |
def appendtext(self, window_name, object_name, data):
"""
Append string sequence.
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either fu... | Append string sequence.
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type ob... |
def format_date(format_string, localize=False, key=None):
"""
A pre-called helper to supply a date format string ahead of time, so that it can apply to each
date or datetime that this column represents. With Django >= 1.5, the ``localize=True`` keyword
argument can be given, or else can be supplied in ... | A pre-called helper to supply a date format string ahead of time, so that it can apply to each
date or datetime that this column represents. With Django >= 1.5, the ``localize=True`` keyword
argument can be given, or else can be supplied in the column's own declaration for the same
effect. (The date and d... |
def get_hw_family(self, version_text):
"""Return the HW family information from the device."""
family = None
if version_text is None:
return family
match = re.search(self.platform_re, version_text, re.MULTILINE)
if match:
self.platform_string = match.grou... | Return the HW family information from the device. |
def acpi_shutdown(self, acpi_shutdown):
"""
Sets either this QEMU VM can be ACPI shutdown.
:param acpi_shutdown: boolean
"""
if acpi_shutdown:
log.info('QEMU VM "{name}" [{id}] has enabled ACPI shutdown'.format(name=self._name, id=self._id))
else:
... | Sets either this QEMU VM can be ACPI shutdown.
:param acpi_shutdown: boolean |
def get_lines_from_file(filepath, encoding="UTF-8"):
"""Return an iterator over lines."""
try:
fd = codecs.open(filepath, 'r', encoding)
lines = fd.readlines()
except UnicodeDecodeError:
# Fall back to 'ISO-8859-1'
fd = codecs.open(filepath, 'r', 'ISO-8859-1')
lines =... | Return an iterator over lines. |
def name(self):
# type: () -> bytes
'''
Generate a string that contains all components of the symlink.
Parameters:
None
Returns:
String containing all components of the symlink.
'''
if not self._initialized:
raise pycdlibexception.Py... | Generate a string that contains all components of the symlink.
Parameters:
None
Returns:
String containing all components of the symlink. |
def load_tf_weights_in_gpt2(model, gpt2_checkpoint_path):
""" Load tf checkpoints in a pytorch model
"""
try:
import re
import numpy as np
import tensorflow as tf
except ImportError:
print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Pleas... | Load tf checkpoints in a pytorch model |
def _make_version(major, minor, micro, level, serial):
"""Generate version string from tuple (almost entirely from coveragepy)."""
level_dict = {"alpha": "a", "beta": "b", "candidate": "rc", "final": ""}
if level not in level_dict:
raise RuntimeError("Invalid release level")
version = "{0:d}.{1:... | Generate version string from tuple (almost entirely from coveragepy). |
def _download_file(self, url, filename, compress=False, timeout=30):
""" Download a file to the resources folder.
Download data from `url`, save as `filename`, and optionally compress with gzip.
Parameters
----------
url : str
URL to download data from
filen... | Download a file to the resources folder.
Download data from `url`, save as `filename`, and optionally compress with gzip.
Parameters
----------
url : str
URL to download data from
filename : str
name of file to save; if compress, ensure '.gz' is appended... |
def delete_project(self, project):
""" Called when project is deleted. """
pid = project.pid
# project deleted
ds_project = self.get_project(pid)
if ds_project is not None:
self._call(["delete", "account", "name=%s" % pid])
return | Called when project is deleted. |
def get_cache_model(name, dataset_name='wikitext-2', window=2000,
theta=0.6, lambdas=0.2, ctx=mx.cpu(), **kwargs):
r"""Returns a cache model using a pre-trained language model.
We implement the neural cache language model proposed in the following work::
@article{grave2016improving... | r"""Returns a cache model using a pre-trained language model.
We implement the neural cache language model proposed in the following work::
@article{grave2016improving,
title={Improving neural language models with a continuous cache},
author={Grave, Edouard and Joulin, Armand and Usunier, ... |
def _initialize_trunk_interfaces_to_none(self, switch_ip, replay=True):
"""Initialize all nexus interfaces to trunk allowed none."""
try:
# The following determines if the switch interfaces are
# in place. If so, make sure they have a basic trunk
# configuration app... | Initialize all nexus interfaces to trunk allowed none. |
def create_switch(apps, schema_editor):
"""Create the `role_based_access_control` switch if it does not already exist."""
Switch = apps.get_model('waffle', 'Switch')
Switch.objects.update_or_create(name=ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH, defaults={'active': False}) | Create the `role_based_access_control` switch if it does not already exist. |
def str_to_application_class(self, an_app_key):
"""a configman compatible str_to_* converter"""
try:
app_class = str_to_python_object(self.apps[an_app_key])
except KeyError:
app_class = str_to_python_object(an_app_key)
try:
self.application_defaults = ... | a configman compatible str_to_* converter |
def place_objects(self):
"""Places objects randomly until no collisions or max iterations hit."""
placed_objects = []
index = 0
# place objects by rejection sampling
for _, obj_mjcf in self.mujoco_objects.items():
horizontal_radius = obj_mjcf.get_horizontal_radius()
... | Places objects randomly until no collisions or max iterations hit. |
def show_inputs(client, workflow):
"""Show workflow inputs and exit."""
for input_ in workflow.inputs:
click.echo(
'{id}: {default}'.format(
id=input_.id,
default=_format_default(client, input_.default),
)
)
sys.exit(0) | Show workflow inputs and exit. |
def _iter_key_ranges(self):
"""Iterates over self._key_ranges, delegating to self._iter_key_range()."""
while True:
if self._current_key_range is None:
if self._key_ranges:
self._current_key_range = self._key_ranges.pop()
# The most recently popped key_range may be None, so con... | Iterates over self._key_ranges, delegating to self._iter_key_range(). |
def write(self, f):
""" Write namespace as INI file.
:param f: File object or path to file.
"""
if isinstance(f, str):
f = io.open(f, 'w', encoding='utf-8')
if not hasattr(f, 'read'):
raise AttributeError("Wrong type of file: {0}".format(type(f)))
... | Write namespace as INI file.
:param f: File object or path to file. |
def to_resolvers(sweepable: Sweepable) -> List[ParamResolver]:
"""Convert a Sweepable to a list of ParamResolvers."""
if isinstance(sweepable, ParamResolver):
return [sweepable]
elif isinstance(sweepable, Sweep):
return list(sweepable)
elif isinstance(sweepable, collections.Iterable):
... | Convert a Sweepable to a list of ParamResolvers. |
def records(rec_type=None, fields=None, clean=True):
'''
Return DMI records from SMBIOS
type
Return only records of type(s)
The SMBIOS specification defines the following DMI types:
==== ======================================
Type Information
==== ===============... | Return DMI records from SMBIOS
type
Return only records of type(s)
The SMBIOS specification defines the following DMI types:
==== ======================================
Type Information
==== ======================================
0 BIOS
1 System
... |
def create_cache_cluster(CacheClusterId=None, ReplicationGroupId=None, AZMode=None, PreferredAvailabilityZone=None, PreferredAvailabilityZones=None, NumCacheNodes=None, CacheNodeType=None, Engine=None, EngineVersion=None, CacheParameterGroupName=None, CacheSubnetGroupName=None, CacheSecurityGroupNames=None, SecurityGro... | Creates a cache cluster. All nodes in the cache cluster run the same protocol-compliant cache engine software, either Memcached or Redis.
See also: AWS API Documentation
:example: response = client.create_cache_cluster(
CacheClusterId='string',
ReplicationGroupId='string',
AZMo... |
def logexception(self, logger=None):
'''
calls exception method on a loger and prints the log to stdout
logger is set in the cfg
#Todo more details here on the cfg etc
:param logger:
:return:
'''
traceback.print_exc()
if logger:
logger... | calls exception method on a loger and prints the log to stdout
logger is set in the cfg
#Todo more details here on the cfg etc
:param logger:
:return: |
def trigger(self):
"""Triggers the device.
The trigger method sens a GET(group execute trigger) command byte to
the device.
"""
ibsta = self._lib.ibtrg(self._device)
self._check_status(ibsta) | Triggers the device.
The trigger method sens a GET(group execute trigger) command byte to
the device. |
def format_config(data, env):
"""
Format data with given env.
:param data: a string/integer/float/boolean/list/dict object.
:param env: a dictionary.
:return: return formatted data.
`format_config` will try to format strings contained env placeholder `{{ ENV_KEY }}`.
If `ENV_KEY` does not... | Format data with given env.
:param data: a string/integer/float/boolean/list/dict object.
:param env: a dictionary.
:return: return formatted data.
`format_config` will try to format strings contained env placeholder `{{ ENV_KEY }}`.
If `ENV_KEY` does not exist in env, then this function will trh... |
def start_task(cls, task_tag, skip_unresolved=False):
""" Start task from registry
:param task_tag: same as in :meth:`.WTaskDependencyRegistryStorage.start_task` method
:param skip_unresolved: same as in :meth:`.WTaskDependencyRegistryStorage.start_task` method
:return: None
"""
registry = cls.registry_sto... | Start task from registry
:param task_tag: same as in :meth:`.WTaskDependencyRegistryStorage.start_task` method
:param skip_unresolved: same as in :meth:`.WTaskDependencyRegistryStorage.start_task` method
:return: None |
def list_string_to_dict(string):
"""Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``."""
dictionary = {}
for idx, c in enumerate(string):
dictionary.update({c: idx})
return dictionary | Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``. |
def _w_within_shard(args: Dict[str, Any]):
"""Applies a W gate when the gate acts only within a shard."""
index = args['index']
half_turns = args['half_turns']
axis_half_turns = args['axis_half_turns']
state = _state_shard(args)
pm_vect = _pm_vects(args)[index]
num_shard_qubits = args['num_s... | Applies a W gate when the gate acts only within a shard. |
def clear(self, name):
"""
Clears (resets) a counter specified by its name.
:param name: a counter name to clear.
"""
self._lock.acquire()
try:
del self._cache[name]
finally:
self._lock.release() | Clears (resets) a counter specified by its name.
:param name: a counter name to clear. |
def autoencoder_autoregressive():
"""Autoregressive autoencoder model."""
hparams = autoencoder_basic()
hparams.add_hparam("autoregressive_forget_base", False)
hparams.add_hparam("autoregressive_mode", "none")
hparams.add_hparam("autoregressive_decode_steps", 0)
hparams.add_hparam("autoregressive_eval_pure_... | Autoregressive autoencoder model. |
def from_environment_variables(cls):
"""
Construct OneViewClient using environment variables.
Allowed variables: ONEVIEWSDK_IP (required), ONEVIEWSDK_USERNAME (required), ONEVIEWSDK_PASSWORD (required),
ONEVIEWSDK_AUTH_LOGIN_DOMAIN, ONEVIEWSDK_API_VERSION, ONEVIEWSDK_IMAGE_STREAMER_IP, ... | Construct OneViewClient using environment variables.
Allowed variables: ONEVIEWSDK_IP (required), ONEVIEWSDK_USERNAME (required), ONEVIEWSDK_PASSWORD (required),
ONEVIEWSDK_AUTH_LOGIN_DOMAIN, ONEVIEWSDK_API_VERSION, ONEVIEWSDK_IMAGE_STREAMER_IP, ONEVIEWSDK_SESSIONID, ONEVIEWSDK_SSL_CERTIFICATE,
... |
def get_int(bytearray_, byte_index):
"""
Get int value from bytearray.
int are represented in two bytes
"""
data = bytearray_[byte_index:byte_index + 2]
data[1] = data[1] & 0xff
data[0] = data[0] & 0xff
packed = struct.pack('2B', *data)
value = struct.unpack('>h', packed)[0]
ret... | Get int value from bytearray.
int are represented in two bytes |
def _setup_output(self, path, force):
'''Clear the way for an output to be placed at path'''
# Allow for special case of output being a pipe
if os.path.isdir(path) or os.path.isfile(path):
if force:
logging.warn("Deleting previous file/directory '%s'" % path)
... | Clear the way for an output to be placed at path |
def hide_routemap_holder_route_map_content_match_route_type_route_type_rmm(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET... | Auto Generated Code |
def tshark(*args, **kargs):
"""Sniff packets and print them calling pkt.summary(), a bit like text wireshark""" # noqa: E501
print("Capturing on '" + str(kargs.get('iface') if 'iface' in kargs else conf.iface) + "'") # noqa: E501
i = [0] # This should be a nonlocal variable, using a mutable object for Py... | Sniff packets and print them calling pkt.summary(), a bit like text wireshark |
def boot_settings(self):
"""Property to provide reference to bios boot instance
It is calculated once when the first time it is queried. On refresh,
this property gets reset.
"""
return BIOSBootSettings(
self._conn, utils.get_subresource_path_by(
self... | Property to provide reference to bios boot instance
It is calculated once when the first time it is queried. On refresh,
this property gets reset. |
def get_data_node(self, path: DataPath) -> Optional[DataNode]:
"""Return the data node addressed by a data path.
Args:
path: Data path.
Returns:
Data node if found in the schema, or ``None``.
Raises:
InvalidSchemaPath: If the schema path is invalid.... | Return the data node addressed by a data path.
Args:
path: Data path.
Returns:
Data node if found in the schema, or ``None``.
Raises:
InvalidSchemaPath: If the schema path is invalid. |
def update_stack(StackName=None, TemplateBody=None, TemplateURL=None, UsePreviousTemplate=None, StackPolicyDuringUpdateBody=None, StackPolicyDuringUpdateURL=None, Parameters=None, Capabilities=None, ResourceTypes=None, RoleARN=None, StackPolicyBody=None, StackPolicyURL=None, NotificationARNs=None, Tags=None, ClientRequ... | Updates a stack as specified in the template. After the call completes successfully, the stack update starts. You can check the status of the stack via the DescribeStacks action.
To get a copy of the template for an existing stack, you can use the GetTemplate action.
For more information about creating an upd... |
def getTWFiles(self):
"""Get data files with Twitter messages (tweets).
Each item is a list of pickle files on the ../data/tw/ directory
(probably with some hashtag or common theme).
Use social.tw.search and social.tw.stream to get tweets.
Tweets are excluded from packag... | Get data files with Twitter messages (tweets).
Each item is a list of pickle files on the ../data/tw/ directory
(probably with some hashtag or common theme).
Use social.tw.search and social.tw.stream to get tweets.
Tweets are excluded from package to ease sharing. |
def find_by_hash(self, hash=None, book=-1):
'''Search notes for a given (possibly abbreviated) hash'''
if hash:
self.fyi("nota.find_by_hash() with abbreviated hash %s; book=%s" % (hash, book))
try:
if book < 0:
rows = self.cur.execute("SELECT noteId, hash ... | Search notes for a given (possibly abbreviated) hash |
def _get_request_messages(self, request):
"""Parses the request as a json message.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: The parsed json object
:rtype: dict[str, object]
"""
data = request.get_data(as_... | Parses the request as a json message.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: The parsed json object
:rtype: dict[str, object] |
def registerContract(self, contract):
""" used for when callback receives a contract
that isn't found in local database """
if contract.m_exchange == "":
return
"""
if contract not in self.contracts.values():
contract_tuple = self.contract_to_tuple(contr... | used for when callback receives a contract
that isn't found in local database |
def download_signed_document(self, signature_id, document_id):
"""
Get the audit trail of concrete document
@signature_id: Id of signature
@document_id: Id of document
"""
connection = Connection(self.token)
connection.set_url(self.production, self.SIGNS_DOCUMENT... | Get the audit trail of concrete document
@signature_id: Id of signature
@document_id: Id of document |
def __getBio(self, web):
"""Scrap the bio from a GitHub profile.
:param web: parsed web.
:type web: BeautifulSoup node.
"""
bio = web.find_all("div", {"class": "user-profile-bio"})
if bio:
try:
bio = bio[0].text
if bio and Git... | Scrap the bio from a GitHub profile.
:param web: parsed web.
:type web: BeautifulSoup node. |
def replies(self):
""" returns a list of strings """
fs_reply_path = join(self.fs_replies_path, 'message_001.txt')
if exists(fs_reply_path):
return [load(open(fs_reply_path, 'r'))]
else:
return [] | returns a list of strings |
def _step1func(self, force, ipyclient):
""" hidden wrapped function to start step 1 """
## check input data files
sfiles = self.paramsdict["sorted_fastq_path"]
rfiles = self.paramsdict["raw_fastq_path"]
## do not allow both a sorted_fastq_path and a raw_fastq
if sfiles ... | hidden wrapped function to start step 1 |
def filter_children( self ):
"""Filter our children into regular and local children sets"""
real_children = []
for child in self.children:
if child.name == '<module>':
self.local_children.append( child )
else:
real_children.append( child )
... | Filter our children into regular and local children sets |
def _transition(self, nxt, cur=None, since=None):
'''
Register that a transition has taken place.
nxt is an identifier for the state being entered.
cur is an identifier for the state being left.
since is the time at which the previous state was entered.
'''
... | Register that a transition has taken place.
nxt is an identifier for the state being entered.
cur is an identifier for the state being left.
since is the time at which the previous state was entered. |
def response_complete(self):
"""
Signal that this particular entity has been fully processed. The exporter will not send it to this target again
under this particular export configuration (there is no guarantee another export configuration on the same
server won't send it, or that it won... | Signal that this particular entity has been fully processed. The exporter will not send it to this target again
under this particular export configuration (there is no guarantee another export configuration on the same
server won't send it, or that it won't be received from another server though, so you... |
def get_queryset(self, request):
"""
Annote the queryset with an 'is_active' property that's true iff that row is the most
recently added row for that particular set of KEY_FIELDS values.
Filter the queryset to show only is_active rows by default.
"""
if request.GET.get(S... | Annote the queryset with an 'is_active' property that's true iff that row is the most
recently added row for that particular set of KEY_FIELDS values.
Filter the queryset to show only is_active rows by default. |
def console_get_char_foreground(
con: tcod.console.Console, x: int, y: int
) -> Color:
"""Return the foreground color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`.
"""
return Color._new_fro... | Return the foreground color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`. |
def report_status(self):
"""Get status of player from mopidy core and send webhook.
"""
current_status = {
'current_track': self.core.playback.current_track.get(),
'state': self.core.playback.state.get(),
'time_position': self.core.playback.time_position.get()... | Get status of player from mopidy core and send webhook. |
def unmarshall_time(tyme):
"""Unmarshall a datetime dict."""
return datetime.datetime(day=tyme['day'],
month=tyme['month'],
year=tyme['year'],
hour=tyme['hour'],
minute=tyme['minute'],
... | Unmarshall a datetime dict. |
def nx_to_ontology(graph, source_node, output_path, base_iri):
"""Graph nodes are ID's, and have a 'label' in the node data with the right label
:param graph:
:param source_node:
:param str output_path:
:param base_iri:
"""
ontology = owlready.Ontology(base_iri)
parent_lookup = {
... | Graph nodes are ID's, and have a 'label' in the node data with the right label
:param graph:
:param source_node:
:param str output_path:
:param base_iri: |
def flow_orifice(Diam, Height, RatioVCOrifice):
"""Return the flow rate of the orifice."""
#Checking input validity
ut.check_range([Diam, ">0", "Diameter"],
[RatioVCOrifice, "0-1", "VC orifice ratio"])
if Height > 0:
return (RatioVCOrifice * area_circle(Diam).magnitude
... | Return the flow rate of the orifice. |
def ElemMatch(q, *conditions):
"""
The ElemMatch operator matches documents that contain an array field with at
least one element that matches all the specified query criteria.
"""
new_condition = {}
for condition in conditions:
deep_merge(condition.to_dict(), new_condition)
return ... | The ElemMatch operator matches documents that contain an array field with at
least one element that matches all the specified query criteria. |
def _item_to_row(iterator, resource):
"""Convert a JSON row to the native object.
.. note::
This assumes that the ``schema`` attribute has been
added to the iterator after being created, which
should be done by the caller.
:type iterator: :class:`~google.api_core.page_iterator.Ite... | Convert a JSON row to the native object.
.. note::
This assumes that the ``schema`` attribute has been
added to the iterator after being created, which
should be done by the caller.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that... |
def set_max_workers(self, nb):
"""
Set the maximum workers to create.
"""
self.count_lock.acquire()
self.max_workers = nb
if self.workers > self.max_workers:
self.kill(self.workers - self.max_workers)
self.count_lock.release() | Set the maximum workers to create. |
def using_transport(self, transport=None, path=None, logs=True):
""" change used transport
:param transport: from where will be this image copied
:param path in filesystem
:param logs enable/disable
:return: self
"""
if not transport:
return self
... | change used transport
:param transport: from where will be this image copied
:param path in filesystem
:param logs enable/disable
:return: self |
def comparator(objective):
"""
Higher order function creating a compare function for objectives.
Args:
objective (cipy.algorithms.core.Objective): The objective to create a
compare for.
Returns:
callable: Function accepting two objectives to compare.
Examples:
... | Higher order function creating a compare function for objectives.
Args:
objective (cipy.algorithms.core.Objective): The objective to create a
compare for.
Returns:
callable: Function accepting two objectives to compare.
Examples:
>>> a = Minimum(0.1)
>>> b = Mi... |
def _credit_card_type(self, card_type=None):
""" Returns a random credit card type instance. """
if card_type is None:
card_type = self.random_element(self.credit_card_types.keys())
elif isinstance(card_type, CreditCard):
return card_type
return self.credit_card_t... | Returns a random credit card type instance. |
def load_url(self):
'''读取分享文件列表'''
def on_load_url(filelist, error=None):
self.url_entry.props.secondary_icon_name = REFRESH_ICON
if timestamp != self.url_entry.timestamp:
logger.debug('SharePage.load_url, dirname not match, ignored')
return
... | 读取分享文件列表 |
def maybe_put_task(self):
"""Enqueue the next task, if there are any waiting."""
try:
task = next(self.tasks)
except StopIteration:
pass
else:
log.debug('Putting %s on queue', task)
self.task_queue.put(task) | Enqueue the next task, if there are any waiting. |
def process_raw(self, adsb_ts, adsb_msgs, commb_ts, commb_msgs, tnow=None):
"""process a chunk of adsb and commb messages recieved in the same
time period.
"""
if tnow is None:
tnow = time.time()
self.t = tnow
local_updated_acs_buffer = []
output_buf... | process a chunk of adsb and commb messages recieved in the same
time period. |
def save_ip_ranges(profile_name, prefixes, force_write, debug, output_format = 'json'):
"""
Creates/Modifies an ip-range-XXX.json file
:param profile_name:
:param prefixes:
:param force_write:
:param debug:
:return:
"""
filename = 'ip-ranges-%s.json' % profile_name
ip_ranges = ... | Creates/Modifies an ip-range-XXX.json file
:param profile_name:
:param prefixes:
:param force_write:
:param debug:
:return: |
def rar3_type(btype):
"""RAR3 type code as string."""
if btype < rf.RAR_BLOCK_MARK or btype > rf.RAR_BLOCK_ENDARC:
return "*UNKNOWN*"
return block_strs[btype - rf.RAR_BLOCK_MARK] | RAR3 type code as string. |
def get_volumes_for_instance(self, arg, device=None):
"""
Return all EC2 Volume objects attached to ``arg`` instance name or ID.
May specify ``device`` to limit to the (single) volume attached as that
device.
"""
instance = self.get(arg)
filters = {'attachment.in... | Return all EC2 Volume objects attached to ``arg`` instance name or ID.
May specify ``device`` to limit to the (single) volume attached as that
device. |
def encryption_iv(self):
"""
Returns the byte string of the initialization vector for the encryption
scheme. Only the PBES2 stores the IV in the params. For PBES1, the IV
is derived from the KDF and this property will return None.
:return:
A byte string or None
... | Returns the byte string of the initialization vector for the encryption
scheme. Only the PBES2 stores the IV in the params. For PBES1, the IV
is derived from the KDF and this property will return None.
:return:
A byte string or None |
def _ProcessAMCacheFileKey(self, am_entry, parser_mediator):
""""Parses an Amcache Root/File key for events.
Args:
am_entry (pyregf.key): amcache File key.
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
"""
... | Parses an Amcache Root/File key for events.
Args:
am_entry (pyregf.key): amcache File key.
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs. |
def add(self, node_spec):
"""Add a node to the net. Its parents must already be in the
net, and its variable must not."""
node = BayesNode(*node_spec)
assert node.variable not in self.vars
assert every(lambda parent: parent in self.vars, node.parents)
self.nodes.append(no... | Add a node to the net. Its parents must already be in the
net, and its variable must not. |
def _has_base(cls, base):
"""Helper for _issubclass, a.k.a pytypes.issubtype.
"""
if cls is base:
return True
elif cls is None:
return False
try:
for bs in cls.__bases__:
if _has_base(bs, base):
return True
except:
pass
return False | Helper for _issubclass, a.k.a pytypes.issubtype. |
def load_clients_file(filename):
"""
Load a list of base64 encoded shared secrets for numerical client ids.
Returns a dict.
Format of file is expected to be
# This is a comment. Blank lines are OK.
123,c2hhcmVkIHNlY3JldA==
456,MTIzNDU2Nzg5MDEyMw==
"""
res = {}
con... | Load a list of base64 encoded shared secrets for numerical client ids.
Returns a dict.
Format of file is expected to be
# This is a comment. Blank lines are OK.
123,c2hhcmVkIHNlY3JldA==
456,MTIzNDU2Nzg5MDEyMw== |
def scale_between(minval, maxval, numStops):
""" Scale a min and max value to equal interval domain with
numStops discrete values
"""
scale = []
if numStops < 2:
return [minval, maxval]
elif maxval < minval:
raise ValueError()
else:
domain = maxval - minval
... | Scale a min and max value to equal interval domain with
numStops discrete values |
def kernels_list(self, **kwargs): # noqa: E501
"""List kernels # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.kernels_list(async_req=True)
>>> result = thread.get()
... | List kernels # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.kernels_list(async_req=True)
>>> result = thread.get()
:param async_req bool
:param int page: Page numbe... |
def create_parameterized_CAG(input, output, filename="CAG_with_indicators_and_values.pdf"):
""" Create a CAG with mapped and parameterized indicators """
with open(input, "rb") as f:
G = pickle.load(f)
G.parameterize(year=2017, month=4)
G.get_timeseries_values_for_indicators()
with open(outp... | Create a CAG with mapped and parameterized indicators |
def set_stats(self, ids):
"""Compute stats for a set of results.
:param id: Result IDs as int list.
:return: :class:`results.SetStats <results.SetStats>` object
:rtype: results.SetStats
"""
schema = SetStatsSchema()
resp = self.service.post(self.base, params={'st... | Compute stats for a set of results.
:param id: Result IDs as int list.
:return: :class:`results.SetStats <results.SetStats>` object
:rtype: results.SetStats |
def job_not_running(self, jid, tgt, tgt_type, minions, is_finished):
'''
Return a future which will complete once jid (passed in) is no longer
running on tgt
'''
ping_pub_data = yield self.saltclients['local'](tgt,
'saltutil... | Return a future which will complete once jid (passed in) is no longer
running on tgt |
def from_pymatgen_molecule(cls, molecule):
"""Create an instance of the own class from a pymatgen molecule
Args:
molecule (:class:`pymatgen.core.structure.Molecule`):
Returns:
Cartesian:
"""
new = cls(atoms=[el.value for el in molecule.species],
... | Create an instance of the own class from a pymatgen molecule
Args:
molecule (:class:`pymatgen.core.structure.Molecule`):
Returns:
Cartesian: |
def create_ca_bundle_for_names(self, bundle_name, names):
"""Create a CA bundle to trust only certs defined in names
"""
records = [rec for name, rec
in self.store.store.items() if name in names]
return self.create_bundle(
bundle_name, names=[r['parent_ca'... | Create a CA bundle to trust only certs defined in names |
def subset(self, subset_id):
"""Returns information regarding the set"""
if subset_id in self.subsetcache:
return self.subsetcache[subset_id]
set_uri = self.get_set_uri(subset_id)
for row in self.graph.query("SELECT ?seturi ?setid ?setlabel ?setopen WHERE { ?seturi rdf:type s... | Returns information regarding the set |
def _decodeUserData(byteIter, userDataLen, dataCoding, udhPresent):
""" Decodes PDU user data (UDHI (if present) and message text) """
result = {}
if udhPresent:
# User Data Header is present
result['udh'] = []
udhLen = next(byteIter)
ieLenRead = 0
# Parse and store U... | Decodes PDU user data (UDHI (if present) and message text) |
def multiply_frequencies(signal, fs, frange, calibration_frequencies, attendB):
"""Given a vector of dB attenuations, adjust signal by
multiplication in the frequency domain"""
npts = len(signal)
padto = 1 << (npts - 1).bit_length()
X = np.fft.rfft(signal, n=padto)
npts = padto
f = np.... | Given a vector of dB attenuations, adjust signal by
multiplication in the frequency domain |
def _density_par_approx(self,dangle,tdisrupt,_return_array=False,
higherorder=False):
"""Compute the density as a function of parallel angle using the
spline representation + approximations"""
# First construct the breakpoints for this dangle
Oparb= (dangle-s... | Compute the density as a function of parallel angle using the
spline representation + approximations |
def to_blob(self, repo):
""":return: Blob using the information of this index entry"""
return Blob(repo, self.binsha, self.mode, self.path) | :return: Blob using the information of this index entry |
def on_api_error(self, error_status=None, message=None, event_origin=None):
"""
API error handling
"""
if message.meta["error"].find("Widget instance not found on server") > -1:
# widget is missing on the other side, try to re-attach
# then try again
... | API error handling |
def vendorize(vendor_requirements):
"""
This is the main entry point for vendorizing requirements. It expects
a list of tuples that should contain the name of the library and the
version.
For example, a library ``foo`` with version ``0.0.1`` would look like::
vendor_requirements = [
... | This is the main entry point for vendorizing requirements. It expects
a list of tuples that should contain the name of the library and the
version.
For example, a library ``foo`` with version ``0.0.1`` would look like::
vendor_requirements = [
('foo', '0.0.1'),
] |
def _check_list_len(row, length):
"""
Sanity check for csv parser
:param row
:param length
:return:None
"""
if len(row) != length:
raise Exception(
"row length does not match expected length of " +
str(length) + "\nrow: ... | Sanity check for csv parser
:param row
:param length
:return:None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.