code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
server = _connect(host, port, db, password)
return server.expireat(key, timestamp) | Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000 |
def secret_hex(self, secret_hex):
if secret_hex is None:
raise ValueError("Invalid value for `secret_hex`, must not be `None`")
if secret_hex is not None and not re.search('^(0[xX])?[0-9a-fA-F]{32,64}$', secret_hex):
raise ValueError("Invalid value for `secret_hex`, must be a fol... | Sets the secret_hex of this PreSharedKey.
The secret of the pre-shared key in hexadecimal. It is not case sensitive; 4a is same as 4A, and it is allowed with or without 0x in the beginning. The minimum length of the secret is 128 bits and maximum 256 bits.
:param secret_hex: The secret_hex of this PreS... |
def parameterize_path(path, parameters):
if parameters is None:
parameters = {}
try:
return path.format(**parameters)
except KeyError as key_error:
raise PapermillMissingParameterException("Missing parameter {}".format(key_error)) | Format a path with a provided dictionary of parameters
Parameters
----------
path : string
Path with optional parameters, as a python format string
parameters : dict
Arbitrary keyword arguments to fill in the path |
def discrete_index(self, indices):
elements = []
for i in indices:
elements.append(self[i])
return elements | get elements by discrete indices
:param indices: list
discrete indices
:return: elements |
def del_cookie(self, name: str, *,
domain: Optional[str]=None,
path: str='/') -> None:
self._cookies.pop(name, None)
self.set_cookie(name, '', max_age=0,
expires="Thu, 01 Jan 1970 00:00:00 GMT",
domain=domain, path=pat... | Delete cookie.
Creates new empty expired cookie. |
def modules_and_args(modules=True, states=False, names_only=False):
dirs = []
module_dir = os.path.dirname(os.path.realpath(__file__))
state_dir = os.path.join(os.path.dirname(module_dir), 'states')
if modules:
dirs.append(module_dir)
if states:
dirs.append(state_dir)
ret = _mods... | Walk the Salt install tree and return a dictionary or a list
of the functions therein as well as their arguments.
:param modules: Walk the modules directory if True
:param states: Walk the states directory if True
:param names_only: Return only a list of the callable functions instead of a dictionary w... |
def common_items_ratio(pronac, dt):
segment_id = get_segment_id(str(pronac))
metrics = data.common_items_metrics.to_dict(orient='index')[segment_id]
ratio = common_items_percentage(pronac, segment_common_items(segment_id))
k = 1.5
threshold = metrics['mean'] - k * metrics['std']
uncommon_items =... | Calculates the common items on projects in a cultural segment,
calculates the uncommon items on projects in a cultural segment and
verify if a project is an outlier compared to the other projects
in his segment. |
def extend(self, elts):
elts = elts[:]
self._in_deque.append(elts)
event = self._event_for(elts)
self._event_deque.append(event)
return event | Adds elts to the tasks.
Args:
elts (Sequence): a iterable of elements that can be appended to the
task's bundle_field.
Returns:
Event: an event that can be used to wait on the response. |
def local_manager_rule(self):
adm_gid = self.local_manager_gid
if not adm_gid:
return None
config = self.root['settings']['ugm_localmanager'].attrs
return config[adm_gid] | Return rule for local manager. |
def vote_random(candidates, votes, n_winners):
rcands = list(candidates)
shuffle(rcands)
rcands = rcands[:min(n_winners, len(rcands))]
best = [(i, 0.0) for i in rcands]
return best | Select random winners from the candidates.
This voting method bypasses the given votes completely.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners |
def stop_all(self):
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.stop)
yield from pool.join() | Stop all nodes |
def load_extra(cls, filename):
try:
with open(filename, 'rb') as configuration_file:
cls.load_extra_data(configuration_file.read())
sys.stderr.write("Config successfully loaded from {0:s}\n".format(
filename))
return True
except IOError:
return False | Loads extra JSON configuration parameters from a file on the filesystem.
Args:
filename: str, the filename to open.
Returns:
bool: True if the extra configuration parameters were read. |
def forward(self):
if self._index >= len(self._history) - 1:
return None
self._index += 1
self._check_index()
return self.current_item | Go forward in history if possible.
Return the current item after going forward. |
def parse_args(self, ctx, args):
if args and args[0] in self.commands:
args.insert(0, '')
super(OptionalGroup, self).parse_args(ctx, args) | Check if the first argument is an existing command. |
def merge(dest, src, merge_lists=False, in_place=True):
if in_place:
merged = dest
else:
merged = copy.deepcopy(dest)
return dictupdate.update(merged, src, merge_lists=merge_lists) | defaults.merge
Allows deep merging of dicts in formulas.
merge_lists : False
If True, it will also merge lists instead of replace their items.
in_place : True
If True, it will merge into dest dict,
if not it will make a new copy from that dict and return it.
CLI Exampl... |
def limited_to(self, left: Set[TLeft], right: Set[TRight]) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':
return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 in left and n2 in right) | Returns the induced subgraph where only the nodes from the given sets are included. |
def samefile(path1, path2):
path1, path1_is_storage = format_and_is_storage(path1)
path2, path2_is_storage = format_and_is_storage(path2)
if not path1_is_storage and not path2_is_storage:
return os_path_samefile(path1, path2)
if not path1_is_storage or not path2_is_storage:
return False
... | Return True if both pathname arguments refer to the same file or directory.
Equivalent to "os.path.samefile".
Args:
path1 (path-like object): Path or URL.
path2 (path-like object): Path or URL.
Returns:
bool: True if same file or directory. |
def get_change_price(self, plan_old, plan_new, period):
if period is None or period < 1:
return None
plan_old_day_cost = self._calculate_day_cost(plan_old, period)
plan_new_day_cost = self._calculate_day_cost(plan_new, period)
if plan_new_day_cost <= plan_old_day_cost:
... | Calculates total price of plan change. Returns None if no payment is required. |
def truncated_normal_expval(mu, tau, a, b):
phia = np.exp(normal_like(a, mu, tau))
phib = np.exp(normal_like(b, mu, tau))
sigma = 1. / np.sqrt(tau)
Phia = utils.normcdf((a - mu) / sigma)
if b == np.inf:
Phib = 1.0
else:
Phib = utils.normcdf((b - mu) / sigma)
return (mu + (phi... | Expected value of the truncated normal distribution.
.. math::
E(X) =\mu + \frac{\sigma(\varphi_1-\varphi_2)}{T}
where
.. math::
T & =\Phi\left(\frac{B-\mu}{\sigma}\right)-\Phi
\left(\frac{A-\mu}{\sigma}\right)\text \\
\varphi_1 &=
\varphi\left(\frac{A-\mu}{\sigma}\rig... |
def print_evaluation(period=1, show_stdv=True):
def callback(env):
if env.rank != 0 or (not env.evaluation_result_list) or period is False or period == 0:
return
i = env.iteration
if i % period == 0 or i + 1 == env.begin_iteration or i + 1 == env.end_iteration:
msg = ... | Create a callback that print evaluation result.
We print the evaluation results every **period** iterations
and on the first and the last iterations.
Parameters
----------
period : int
The period to log the evaluation results
show_stdv : bool, optional
Whether show stdv if pr... |
def checkInstalledBrew(package, similar=True, speak=True, speakSimilar=True):
packages = subprocess.check_output(['brew', 'list']).split()
installed = package in packages
similar = []
if not installed:
similar = [pkg for pkg in packages if package in pkg]
if speak:
speakInstalledPack... | checks if a given package is installed on homebrew |
def stratified_kfold(df, n_folds):
sessions = pd.DataFrame.from_records(list(df.index.unique())).groupby(0).apply(lambda x: x[1].unique())
sessions.apply(lambda x: np.random.shuffle(x))
folds = []
for i in range(n_folds):
idx = sessions.apply(lambda x: pd.Series(x[i * (len(x) / n_folds):(i + 1) ... | Create stratified k-folds from an indexed dataframe |
def _get_stddevs(self, C, stddev_types, stddev_shape):
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(C["sigtot"] + np.zeros(stddev_shape))
... | Returns the standard deviations given in Table 2 |
def read_data(self, timeout=10.0):
start_time = time.time()
while True:
data = None
try:
data = self.stdout_reader.queue.get(timeout=timeout)
if data:
yield data
else:
break
except... | Read blocks of raw PCM data from the file. |
def parse_template_json(self, template_json):
assert template_json['type'] == self.DOCUMENT_TYPE, ''
self.template_id = template_json['templateId']
self.name = template_json.get('name')
self.creator = template_json.get('creator')
self.template = template_json['serviceAgreementTem... | Parse a template from a json.
:param template_json: json dict |
def create(self, name, plugin_name, plugin_version, flavor_id,
description=None, volumes_per_node=None, volumes_size=None,
node_processes=None, node_configs=None, floating_ip_pool=None,
security_groups=None, auto_security_group=None,
availability_zone=None, vo... | Create a Node Group Template. |
def validate_empty_attributes(fully_qualified_name: str, spec: Dict[str, Any],
*attributes: str) -> List[EmptyAttributeError]:
return [
EmptyAttributeError(fully_qualified_name, spec, attribute)
for attribute in attributes
if not spec.get(attribute, None)
] | Validates to ensure that a set of attributes do not contain empty values |
def remove_input(urls, preserves, verbose = False):
for path in map(url2path, urls):
if any(os.path.samefile(path, preserve) for preserve in preserves):
continue
if verbose:
print >>sys.stderr, "removing \"%s\" ..." % path
try:
os.remove(path)
except:
pass | Attempt to delete all files identified by the URLs in urls except
any that are the same as the files in the preserves list. |
def _diff_group_position(group):
old_start = group[0][0]
new_start = group[0][1]
old_length = new_length = 0
for old_line, new_line, line_or_conflict in group:
if isinstance(line_or_conflict, tuple):
old, new = line_or_conflict
old_length += len(old)
new_lengt... | Generate a unified diff position line for a diff group |
def assign(self, link_type, product, linked_product, data=None,
identifierType=None):
return bool(self.call('catalog_product_link.assign',
[link_type, product, linked_product, data, identifierType])) | Assign a product link
:param link_type: type of link, one of 'cross_sell', 'up_sell',
'related' or 'grouped'
:param product: ID or SKU of product
:param linked_product: ID or SKU of linked product
:param data: dictionary of link data, (position, qty, etc.)
... |
def __compress_attributes(self, dic):
result = {}
for k, v in dic.iteritems():
if isinstance(v, types.ListType) and len(v) == 1:
if k not in ('msExchMailboxSecurityDescriptor', 'msExchSafeSendersHash', 'msExchBlockedSendersHash',
'replicationSigna... | This will convert all attributes that are list with only one item string into simple string. It seems that LDAP always return lists, even when it doesn
t make sense.
:param dic:
:return: |
def get_new_broks(self):
for elt in self.all_my_hosts_and_services():
for brok in elt.broks:
self.add(brok)
elt.broks = []
for contact in self.contacts:
for brok in contact.broks:
self.add(brok)
contact.broks = [] | Iter over all hosts and services to add new broks in internal lists
:return: None |
def get_relationship_dicts(self):
if not self.relationships:
return None
for goid, goobj in self.go2obj.items():
for reltyp, relset in goobj.relationship.items():
relfwd_goids = set(o.id for o in relset)
print("CountRelativesInit RELLLLS", goid, go... | Given GO DAG relationships, return summaries per GO ID. |
def unpack(cls, msg, client, server, request_id):
flags, = _UNPACK_INT(msg[:4])
namespace, pos = _get_c_string(msg, 4)
docs = bson.decode_all(msg[pos:], CODEC_OPTIONS)
return cls(*docs, namespace=namespace, flags=flags, _client=client,
request_id=request_id, _server=se... | Parse message and return an `OpInsert`.
Takes the client message as bytes, the client and server socket objects,
and the client request id. |
def protocol(alias_name, default=None, allow_none=False):
warnings.warn('Will be removed in v1.0', DeprecationWarning, stacklevel=2)
try:
return _split_docker_link(alias_name)[0]
except KeyError as err:
if default or allow_none:
return default
else:
raise err | Get the protocol from the docker link alias or return the default.
Args:
alias_name: The docker link alias
default: The default value if the link isn't available
allow_none: If the return value can be `None` (i.e. optional)
Examples:
Assuming a Docker link was created with ``do... |
def _all_inner(self, fields, limit, order_by, offset):
response = self.session.get(self._get_table_url(),
params=self._get_formatted_query(fields, limit, order_by, offset))
yield self._get_content(response)
while 'next' in response.links:
self.url_... | Yields all records for the query and follows links if present on the response after validating
:return: List of records with content |
def debug_file(self):
self.switch_to_plugin()
current_editor = self.get_current_editor()
if current_editor is not None:
current_editor.sig_debug_start.emit()
self.run_file(debug=True) | Debug current script |
def publish(cls, message, client_filter=None):
with cls._lock:
for client in cls.subscribers:
if (not client_filter) or client_filter(client):
client.send(message) | Publish messages to subscribers.
Args:
message: The message to publish.
client_filter: A filter function to call passing in each client. Only
clients for whom the function returns True will have the
message sent to them. |
def read(self):
data = self.dev.read()
if len(data) == 0:
self.log.warning("READ : Nothing received")
return
if data == b'\x00':
self.log.warning("READ : Empty packet (Got \\x00)")
return
pkt = bytearray(data)
data = self.dev.read(p... | We have been called to read! As a consumer, continue to read for
the length of the packet and then pass to the callback. |
def raw(text):
new_string = ''
for char in text:
try:
new_string += escape_dict[char]
except KeyError:
new_string += char
return new_string | Returns a raw string representation of text |
def class_repr(value):
klass = value
if not isinstance(value, type):
klass = klass.__class__
return '.'.join([klass.__module__, klass.__name__]) | Returns a representation of the value class.
Arguments
---------
value
A class or a class instance
Returns
-------
str
The "module.name" representation of the value class.
Example
-------
>>> from datetime import date
>>> class_repr(date)
'datetime.date'
... |
def find_function(self, name):
deffunction = lib.EnvFindDeffunction(self._env, name.encode())
if deffunction == ffi.NULL:
raise LookupError("Function '%s' not found" % name)
return Function(self._env, deffunction) | Find the Function by its name. |
def communicate_through(self, file):
if self._communication is not None:
raise ValueError("Already communicating.")
self._communication = communication = Communication(
file, self._get_needle_positions,
self._machine, [self._on_message_received],
right_end... | Setup communication through a file.
:rtype: AYABInterface.communication.Communication |
def parse(html_string, wrapper=Parser, *args, **kwargs):
return Parser(lxml.html.fromstring(html_string), *args, **kwargs) | Parse html with wrapper |
def nl_object_alloc(ops):
new = nl_object()
nl_init_list_head(new.ce_list)
new.ce_ops = ops
if ops.oo_constructor:
ops.oo_constructor(new)
_LOGGER.debug('Allocated new object 0x%x', id(new))
return new | Allocate a new object of kind specified by the operations handle.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/object.c#L54
Positional arguments:
ops -- cache operations handle (nl_object_ops class instance).
Returns:
New nl_object class instance or None. |
def stop_recording():
global _recording
if not _recording:
raise ValueError('Must call "start_recording" before.')
recorded_events_queue, hooked = _recording
unhook(hooked)
return list(recorded_events_queue.queue) | Stops the global recording of events and returns a list of the events
captured. |
def wrap_threading_start(start_func):
def call(self):
self._opencensus_context = (
execution_context.get_opencensus_full_context()
)
return start_func(self)
return call | Wrap the start function from thread. Put the tracer informations in the
threading object. |
def bytes_array(self):
assert len(self.dimensions) == 2, \
'{}: cannot get value as bytes array!'.format(self.name)
l, n = self.dimensions
return [self.bytes[i*l:(i+1)*l] for i in range(n)] | Get the param as an array of raw byte strings. |
def tag(tagname, content='', attrs=None):
attrs_str = attrs and ' '.join(_generate_dom_attrs(attrs))
open_tag = tagname
if attrs_str:
open_tag += ' ' + attrs_str
if content is None:
return literal('<%s />' % open_tag)
content = ''.join(iterate(content, unless=(basestring, literal)))
... | Helper for programmatically building HTML tags.
Note that this barely does any escaping, and will happily spit out
dangerous user input if used as such.
:param tagname:
Tag name of the DOM element we want to return.
:param content:
Optional content of the DOM element. If `None`, then ... |
def position_input(obj, visible=False):
if not obj.generic_position.all():
ObjectPosition.objects.create(content_object=obj)
return {'obj': obj, 'visible': visible,
'object_position': obj.generic_position.all()[0]} | Template tag to return an input field for the position of the object. |
def list_databases(self):
lines = output_lines(self.exec_psql('\\list'))
return [line.split('|') for line in lines] | Runs the ``\\list`` command and returns a list of column values with
information about all databases. |
def random_stats(self, all_stats, race, ch_class):
stats = []
res = {}
for s in all_stats:
stats.append(s['stat'])
res[s['stat']] = 0
cur_stat = 0
for stat in stats:
for ndx, i in enumerate(self.classes.dat):
if i['name'] == ch_... | create random stats based on the characters class and race
This looks up the tables from CharacterCollection to get
base stats and applies a close random fit |
def _LogRecord_msg():
def _LogRecord_msgProperty(self):
return self.__msg
def _LogRecord_msgSetter(self, value):
self.__msg = to_unicode(value)
logging.LogRecord.msg = property(_LogRecord_msgProperty, _LogRecord_msgSetter) | Overrides logging.LogRecord.msg attribute to ensure variable content is stored as unicode. |
def with_pattern(pattern, regex_group_count=None):
def decorator(func):
func.pattern = pattern
func.regex_group_count = regex_group_count
return func
return decorator | Attach a regular expression pattern matcher to a custom type converter
function.
This annotates the type converter with the :attr:`pattern` attribute.
EXAMPLE:
>>> import parse
>>> @parse.with_pattern(r"\d+")
... def parse_number(text):
... return int(text)
is equi... |
def log_game_start(self, players, terrain, numbers, ports):
self.reset()
self._set_players(players)
self._logln('{} v{}'.format(__name__, __version__))
self._logln('timestamp: {0}'.format(self.timestamp_str()))
self._log_players(players)
self._log_board_terrain(terrain)
... | Begin a game.
Erase the log, set the timestamp, set the players, and write the log header.
The robber is assumed to start on the desert (or off-board).
:param players: iterable of catan.game.Player objects
:param terrain: list of 19 catan.board.Terrain objects.
:param numbers:... |
def read(path):
url = '{}/{}/{}'.format(settings.VAULT_BASE_URL.rstrip('/'),
settings.VAULT_BASE_SECRET_PATH.strip('/'),
path.lstrip('/'))
headers = {'X-Vault-Token': settings.VAULT_ACCESS_TOKEN}
resp = requests.get(url, headers=headers)
if resp.ok... | Read a secret from Vault REST endpoint |
def set(self, key, value, confidence=100):
if value is None:
return
if key in self.info:
old_confidence, old_value = self.info.get(key)
if old_confidence >= confidence:
return
self.info[key] = (confidence, value) | Defines the given value with the given confidence, unless the same
value is already defined with a higher confidence level. |
def savemat(file_name, mdict, appendmat=True, format='7.3',
oned_as='row', store_python_metadata=True,
action_for_matlab_incompatible='error',
marshaller_collection=None, truncate_existing=False,
truncate_invalid_matlab=False, **keywords):
if float(format) < 7.3:
... | Save a dictionary of python types to a MATLAB MAT file.
Saves the data provided in the dictionary `mdict` to a MATLAB MAT
file. `format` determines which kind/vesion of file to use. The
'7.3' version, which is HDF5 based, is handled by this package and
all types that this package can write are supporte... |
def write(self, file_or_filename):
if isinstance(file_or_filename, basestring):
file = None
try:
file = open(file_or_filename, "wb")
except Exception, detail:
logger.error("Error opening %s." % detail)
finally:
if fi... | Writes the case data to file. |
def copytree_hardlink(source, dest):
copy2 = shutil.copy2
try:
shutil.copy2 = os.link
shutil.copytree(source, dest)
finally:
shutil.copy2 = copy2 | Recursively copy a directory ala shutils.copytree, but hardlink files
instead of copying. Available on UNIX systems only. |
def info(ctx):
dev = ctx.obj['dev']
controller = ctx.obj['controller']
slot1, slot2 = controller.slot_status
click.echo('Slot 1: {}'.format(slot1 and 'programmed' or 'empty'))
click.echo('Slot 2: {}'.format(slot2 and 'programmed' or 'empty'))
if dev.is_fips:
click.echo('FIPS Approved Mod... | Display status of YubiKey Slots. |
def prepare_editable_requirement(
self,
req,
require_hashes,
use_user_site,
finder
):
assert req.editable, "cannot prepare a non-editable req as editable"
logger.info('Obtaining %s', req)
with indent_log():
if require_hashes:
... | Prepare an editable requirement |
def Handle_Search(self, msg):
search_term = msg['object']['searchTerm']
results = self.db.searchForItem(search_term)
reply = {"status": "OK",
"type": "search",
"object": {
"received search": msg['object']['searchTerm'],
... | Handle a search.
:param msg: the received search
:type msg: dict
:returns: The message to reply with
:rtype: str |
def _set_mtu_to_nics(self, conf):
for dom_name, dom_spec in conf.get('domains', {}).items():
for idx, nic in enumerate(dom_spec.get('nics', [])):
net = self._get_net(conf, dom_name, nic)
mtu = net.get('mtu', 1500)
if mtu != 1500:
ni... | For all the nics of all the domains in the conf that have MTU set,
save the MTU on the NIC definition.
Args:
conf (dict): Configuration spec to extract the domains from
Returns:
None |
def team_info():
teams = __get_league_object().find('teams').findall('team')
output = []
for team in teams:
info = {}
for x in team.attrib:
info[x] = team.attrib[x]
output.append(info)
return output | Returns a list of team information dictionaries |
def run(self, *args, **kw):
if self._runFunc is not None:
if 'mode' in kw: kw.pop('mode')
if '_save' in kw: kw.pop('_save')
return self._runFunc(self, *args, **kw)
else:
raise taskpars.NoExecError('No way to run task "'+self.__taskName+\
'"... | This may be overridden by a subclass. |
def _get_condition_json(self, index):
condition = self.condition_data[index]
condition_log = {
'name': condition[0],
'value': condition[1],
'type': condition[2],
'match': condition[3]
}
return json.dumps(condition_log) | Method to generate json for logging audience condition.
Args:
index: Index of the condition.
Returns:
String: Audience condition JSON. |
def iter_orgs(username, number=-1, etag=None):
return gh.iter_orgs(username, number, etag) if username else [] | List the organizations associated with ``username``.
:param str username: (required), login of the user
:param int number: (optional), number of orgs to return. Default: -1,
return all of the issues
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns:... |
def replace_file(from_file, to_file):
try:
os.remove(to_file)
except OSError:
pass
copy(from_file, to_file) | Replaces to_file with from_file |
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form_class = self.get_form_class()
form = self.get_form(form_class)
formsets = self.get_formsets(form, saving=True)
valid_formsets = True
for formset in formsets.values():
if not formset... | Method for handling POST requests.
Validates submitted form and
formsets. Saves if valid, re displays
page with errors if invalid. |
def pdb(self):
if self.embed_disabled:
self.warning_log("Pdb is disabled when runned from the grid runner because of the multithreading")
return False
if BROME_CONFIG['runner']['play_sound_on_pdb']:
say(BROME_CONFIG['runner']['sound_on_pdb'])
set_trace() | Start the python debugger
Calling pdb won't do anything in a multithread context |
def _confirm_constant(a):
a = np.asanyarray(a)
return np.isclose(a, 1.0).all(axis=0).any() | Confirm `a` has volumn vector of 1s. |
def approximant(self, index):
if 'approximant' not in self.table.fieldnames:
raise ValueError("approximant not found in input file and no "
"approximant was specified on initialization")
return self.table["approximant"][index] | Return the name of the approximant ot use at the given index |
def _try_lookup(table, value, default = ""):
try:
string = table[ value ]
except KeyError:
string = default
return string | try to get a string from the lookup table, return "" instead of key
error |
def connection_made(self, transport):
self.transport = transport
self.transport.write(self.method.message.encode())
self.time_out_handle = self.loop.call_later(
TIME_OUT_LIMIT, self.time_out) | Connect to device is successful.
Start configuring RTSP session.
Schedule time out handle in case device doesn't respond. |
def create_cell_renderer_text(self, tree_view, title="title", assign=0, editable=False):
renderer = Gtk.CellRendererText()
renderer.set_property('editable', editable)
column = Gtk.TreeViewColumn(title, renderer, text=assign)
tree_view.append_column(column) | Function creates a CellRendererText with title |
def set_interval(self, timer_id, interval):
return lib.ztimerset_set_interval(self._as_parameter_, timer_id, interval) | Set timer interval. Returns 0 if OK, -1 on failure.
This method is slow, canceling the timer and adding a new one yield better performance. |
def _process(self, resource=None, data={}):
_data = data or self._data
rsc_url = self.get_rsc_endpoint(resource)
if _data:
req = requests.post(rsc_url, data=json.dumps(_data),
headers=self.headers)
else:
req = requests.get(rsc_url, ... | Processes the current transaction
Sends an HTTP request to the PAYDUNYA API server |
def sample(self, data_1, data_2, sample_size=15000,
blocked_proportion=.5, original_length_1=None,
original_length_2=None):
self._checkData(data_1, data_2)
self.active_learner = self.ActiveLearner(self.data_model)
self.active_learner.sample_product(data_1, data_2,
... | Draws a random sample of combinations of records from
the first and second datasets, and initializes active
learning with this sample
Arguments:
data_1 -- Dictionary of records from first dataset, where the
keys are record_ids and the values are dictionaries... |
def put(self, *args, **kwargs):
self.inq.put((self._putcount, (args, kwargs)))
self._putcount += 1 | place a new item into the pool to be handled by the workers
all positional and keyword arguments will be passed in as the arguments
to the function run by the pool's workers |
def avg_time(self, source=None):
if source is None:
runtimes = []
for rec in self.source_stats.values():
runtimes.extend([r for r in rec.runtimes if r != 0])
return avg(runtimes)
else:
if callable(source):
return avg(self.so... | Returns the average time taken to scrape lyrics. If a string or a
function is passed as source, return the average time taken to scrape
lyrics from that source, otherwise return the total average. |
def random_seed_np_tf(seed):
if seed >= 0:
np.random.seed(seed)
tf.set_random_seed(seed)
return True
else:
return False | Seed numpy and tensorflow random number generators.
:param seed: seed parameter |
def beginningPage(R):
p = R['PG']
if p.startswith('suppl '):
p = p[6:]
return p.split(' ')[0].split('-')[0].replace(';', '') | As pages may not be given as numbers this is the most accurate this function can be |
async def request(self, method: base.String,
data: Optional[Dict] = None,
files: Optional[Dict] = None, **kwargs) -> Union[List, Dict, base.Boolean]:
return await api.make_request(self.session, self.__token, method, data, files,
p... | Make an request to Telegram Bot API
https://core.telegram.org/bots/api#making-requests
:param method: API method
:type method: :obj:`str`
:param data: request parameters
:type data: :obj:`dict`
:param files: files
:type files: :obj:`dict`
:return: result... |
def get_conversation_between(self, um_from_user, um_to_user):
messages = self.filter(Q(sender=um_from_user, recipients=um_to_user,
sender_deleted_at__isnull=True) |
Q(sender=um_to_user, recipients=um_from_user,
mess... | Returns a conversation between two users |
def vsepg(v1, v2, ndim):
v1 = stypes.toDoubleVector(v1)
v2 = stypes.toDoubleVector(v2)
ndim = ctypes.c_int(ndim)
return libspice.vsepg_c(v1, v2, ndim) | Find the separation angle in radians between two double
precision vectors of arbitrary dimension. This angle is defined
as zero if either vector is zero.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsepg_c.html
:param v1: First vector
:type v1: Array of floats
:param v2: Second ve... |
def read_dir_tree(self, file_hash):
json_d = self.read_index_object(file_hash, 'tree')
node = {'files' : json_d['files'], 'dirs' : {}}
for name, hsh in json_d['dirs'].iteritems(): node['dirs'][name] = self.read_dir_tree(hsh)
return node | Recursively read the directory structure beginning at hash |
def is_lossy(label):
val = getkey(from_=label, keyword='INST_CMPRS_TYPE').decode().strip()
if val == 'LOSSY':
return True
else:
return False | Check Label file for the compression type. |
def _get_anchor(module_to_name, fullname):
if not _anchor_re.match(fullname):
raise ValueError("'%s' is not a valid anchor" % fullname)
anchor = fullname
for module_name in module_to_name.values():
if fullname.startswith(module_name + "."):
rest = fullname[len(module_name)+1:]
if len(anchor) >... | Turn a full member name into an anchor.
Args:
module_to_name: Dictionary mapping modules to short names.
fullname: Fully qualified name of symbol.
Returns:
HTML anchor string. The longest module name prefix of fullname is
removed to make the anchor.
Raises:
ValueError: If fullname uses cha... |
def union(self, rdds):
first_jrdd_deserializer = rdds[0]._jrdd_deserializer
if any(x._jrdd_deserializer != first_jrdd_deserializer for x in rdds):
rdds = [x._reserialize() for x in rdds]
cls = SparkContext._jvm.org.apache.spark.api.java.JavaRDD
jrdds = SparkContext._gateway.n... | Build the union of a list of RDDs.
This supports unions() of RDDs with different serialized formats,
although this forces them to be reserialized using the default
serializer:
>>> path = os.path.join(tempdir, "union-text.txt")
>>> with open(path, "w") as testFile:
... ... |
def mark_time(times, msg=None):
tt = time.clock()
times.append(tt)
if (msg is not None) and (len(times) > 1):
print msg, times[-1] - times[-2] | Time measurement utility.
Measures times of execution between subsequent calls using
time.clock(). The time is printed if the msg argument is not None.
Examples
--------
>>> times = []
>>> mark_time(times)
... do something
>>> mark_time(times, 'elapsed')
elapsed 0.1
... do som... |
def _get_sorted_action_keys(self, keys_list):
action_list = []
for key in keys_list:
if key.startswith('action-'):
action_list.append(key)
action_list.sort()
return action_list | This function returns only the elements starting with 'action-' in
'keys_list'. The returned list is sorted by the index appended to
the end of each element |
async def generate_image(self, imgtype, face=None, hair=None):
if not isinstance(imgtype, str):
raise TypeError("type of 'imgtype' must be str.")
if face and not isinstance(face, str):
raise TypeError("type of 'face' must be str.")
if hair and not isinstance(hair, str):
... | Generate a basic image using the auto-image endpoint of weeb.sh.
This function is a coroutine.
Parameters:
imgtype: str - type of the generation to create, possible types are awooo, eyes, or won.
face: str - only used with awooo type, defines color of face
hair: str... |
def get_tx_identity_info(self, tx_ac):
rows = self._fetchall(self._queries['tx_identity_info'], [tx_ac])
if len(rows) == 0:
raise HGVSDataNotAvailableError(
"No transcript definition for (tx_ac={tx_ac})".format(tx_ac=tx_ac))
return rows[0] | returns features associated with a single transcript.
:param tx_ac: transcript accession with version (e.g., 'NM_199425.2')
:type tx_ac: str
# database output
-[ RECORD 1 ]--+-------------
tx_ac | NM_199425.2
alt_ac | NM_199425.2
alt_aln_method ... |
def add_item(self, item, **options):
export_item = {
"item": item.url,
}
export_item.update(options)
self.items.append(export_item)
return self | Add a layer or table item to the export.
:param Layer|Table item: The Layer or Table to add
:rtype: self |
def _calculate_duration(start_time, finish_time):
if not (start_time and finish_time):
return 0
start = datetime.datetime.fromtimestamp(start_time)
finish = datetime.datetime.fromtimestamp(finish_time)
duration = finish - start
decimals = float(("0." + str(duration.microseconds)))
return... | Calculates how long it took to execute the testcase. |
def task_path(cls, project, location, queue, task):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/queues/{queue}/tasks/{task}",
project=project,
location=location,
queue=queue,
task=task,
) | Return a fully-qualified task string. |
def _filehandle(self):
if self._fh and self._has_file_rolled():
try:
self._fh.close()
except Exception:
pass
self._fh = None
if not self._fh:
self._open_file(self.filename)
if not self.opened_before:
... | Return a filehandle to the file being tailed |
def copy(self, **params):
new_params = dict()
for name in ['owner', 'priority', 'key', 'final']:
new_params[name] = params.get(name, getattr(self, name))
return Route(**new_params) | Creates the new instance of the Route substituting the requested
parameters. |
def find_by(cls, **kwargs) -> 'Entity':
logger.debug(f'Lookup `{cls.__name__}` object with values '
f'{kwargs}')
results = cls.query.filter(**kwargs).limit(1).all()
if not results:
raise ObjectNotFoundError(
f'`{cls.__name__}` object with values {... | Find a specific entity record that matches one or more criteria.
:param kwargs: named arguments consisting of attr_name and attr_value pairs to search on |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.