code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def randomdate(year: int) -> datetime.date:
if calendar.isleap(year):
doy = random.randrange(366)
else:
doy = random.randrange(365)
return datetime.date(year, 1, 1) + datetime.timedelta(days=doy) | gives random date in year |
def perform(self):
if self._driver.w3c:
self.w3c_actions.perform()
else:
for action in self._actions:
action() | Performs all stored actions. |
def disttar_suffix(env, sources):
env_dict = env.Dictionary()
if env_dict.has_key("DISTTAR_FORMAT") and env_dict["DISTTAR_FORMAT"] in ["gz", "bz2"]:
return ".tar." + env_dict["DISTTAR_FORMAT"]
else:
return ".tar" | tar archive suffix generator |
def add_state(self):
sid = len(self.states)
self.states.append(DFAState(sid))
return sid | Adds a new state |
def update(self, prob):
chunk_activated = prob > 1.0 - self.sensitivity
if chunk_activated or self.activation < 0:
self.activation += 1
has_activated = self.activation > self.trigger_level
if has_activated or chunk_activated and self.activation < 0:
self.activation = -(8 * 2048) // self.chunk_size
if has_activated:
return True
elif self.activation > 0:
self.activation -= 1
return False | Returns whether the new prediction caused an activation |
def copy(self, src_url, dst_url):
src_bucket, src_key = _parse_url(src_url)
dst_bucket, dst_key = _parse_url(dst_url)
if not dst_bucket:
dst_bucket = src_bucket
params = {
'copy_source': '/'.join((src_bucket, src_key)),
'bucket': dst_bucket,
'key': dst_key,
}
return self.call("CopyObject", **params) | Copy an S3 object to another S3 location. |
def matches_input(self, optimized_str):
if all([keyword in optimized_str for keyword in self['keywords']]):
logger.debug('Matched template %s', self['template_name'])
return True | See if string matches keywords set in template file |
def img2img_transformer_base():
hparams = image_transformer2d_base()
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
hparams.learning_rate = 0.2
hparams.layer_prepostprocess_dropout = 0.1
hparams.learning_rate_warmup_steps = 12000
hparams.filter_size = 2048
hparams.num_encoder_layers = 4
hparams.num_decoder_layers = 8
hparams.block_length = 256
hparams.block_width = 256
hparams.dec_attention_type = cia.AttentionType.LOCAL_1D
hparams.block_raster_scan = False
return hparams | Base params for local1d attention. |
def _instantiate(self, module, class_name,
args=None, kwargs=None, static=None):
if args is None:
args = []
if kwargs is None:
kwargs = {}
if static is None:
static = False
_check_type('args', args, list)
_check_type('kwargs', kwargs, dict)
if static and class_name is None:
return module
if static and class_name is not None:
return getattr(module, class_name)
service_obj = getattr(module, class_name)
args = self._replace_scalars_in_args(args)
kwargs = self._replace_scalars_in_kwargs(kwargs)
args = self._replace_services_in_args(args)
kwargs = self._replace_services_in_kwargs(kwargs)
return service_obj(*args, **kwargs) | Instantiates a class if provided |
def add_to_gui(self, content):
if not self.rewrite_config:
raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.")
if not self.gui_file:
self.gui_path, self.gui_file = self.__get_gui_handle(self.root_dir)
self.gui_file.write(content + '\n') | add content to the gui script. |
def _assert_all_loadable_terms_specialized_to(self, domain):
for term in self.graph.node:
if isinstance(term, LoadableTerm):
assert term.domain is domain | Make sure that we've specialized all loadable terms in the graph. |
def pricing(sort='cost', **kwargs):
for name, provider in env.providers.items():
print name
provider.pricing(sort, **kwargs)
print | Print pricing tables for all enabled providers |
async def _retrieve_messages_before_strategy(self, retrieve):
before = self.before.id if self.before else None
data = await self.logs_from(self.channel.id, retrieve, before=before)
if len(data):
if self.limit is not None:
self.limit -= retrieve
self.before = Object(id=int(data[-1]['id']))
return data | Retrieve messages using before parameter. |
def all_valid(formsets):
valid = True
for formset in formsets:
if not formset.is_valid():
valid = False
return valid | Returns true if every formset in formsets is valid. |
def delete_resource(self, resource_id):
uri = self._get_resource_uri(guid=resource_id)
return self.service._delete(uri) | Remove a specific resource by its identifier. |
def child(self, name, data, source=None):
try:
if isinstance(data, dict):
self.children[name].update(data)
else:
self.children[name].grow(data)
except KeyError:
self.children[name] = Tree(data, name, parent=self)
if source is not None:
self.children[name].sources.append(source) | Create or update child with given data |
def prepare_to_generate(self, data_dir, tmp_dir):
self.get_or_create_vocab(data_dir, tmp_dir)
self.train_text_filepaths(tmp_dir)
self.dev_text_filepaths(tmp_dir) | Make sure that the data is prepared and the vocab is generated. |
def install():
sudo("apt-get update -y -q")
apt("nginx libjpeg-dev python-dev python-setuptools git-core "
"postgresql libpq-dev memcached supervisor python-pip")
run("mkdir -p /home/%s/logs" % env.user)
sudo("pip install -U pip virtualenv virtualenvwrapper mercurial")
run("mkdir -p %s" % env.venv_home)
run("echo 'export WORKON_HOME=%s' >> /home/%s/.bashrc" % (env.venv_home,
env.user))
run("echo 'source /usr/local/bin/virtualenvwrapper.sh' >> "
"/home/%s/.bashrc" % env.user)
print(green("Successfully set up git, mercurial, pip, virtualenv, "
"supervisor, memcached.", bold=True)) | Installs the base system and Python requirements for the entire server. |
def _series_sis(self):
pages = self.pages._getlist(validate=False)
page = pages[0]
lenpages = len(pages)
md = self.sis_metadata
if 'shape' in md and 'axes' in md:
shape = md['shape'] + page.shape
axes = md['axes'] + page.axes
elif lenpages == 1:
shape = page.shape
axes = page.axes
else:
shape = (lenpages,) + page.shape
axes = 'I' + page.axes
self.is_uniform = True
return [TiffPageSeries(pages, shape, page.dtype, axes, kind='SIS')] | Return image series in Olympus SIS file. |
def xinfo_consumers(self, stream, group_name):
fut = self.execute(b'XINFO', b'CONSUMERS', stream, group_name)
return wait_convert(fut, parse_lists_to_dicts) | Retrieve consumers of a consumer group |
def GetNotificationShard(self, queue):
queue_name = str(queue)
QueueManager.notification_shard_counters.setdefault(queue_name, 0)
QueueManager.notification_shard_counters[queue_name] += 1
notification_shard_index = (
QueueManager.notification_shard_counters[queue_name] %
self.num_notification_shards)
if notification_shard_index > 0:
return queue.Add(str(notification_shard_index))
else:
return queue | Gets a single shard for a given queue. |
def insert(self, index, key, value):
if key in self.keyOrder:
n = self.keyOrder.index(key)
del self.keyOrder[n]
if n < index:
index -= 1
self.keyOrder.insert(index, key)
super(SortedDict, self).__setitem__(key, value) | Inserts the key, value pair before the item with the given index. |
def print_whats_next(profile):
what_next = [
"{{autogreen}}Congratulations!{{/autogreen}} You are logged in "
"to the MAAS server at {{autoblue}}{profile.url}{{/autoblue}} "
"with the profile name {{autoblue}}{profile.name}{{/autoblue}}.",
"For help with the available commands, try:",
" maas help",
]
for message in what_next:
message = message.format(profile=profile)
print(colorized(message))
print() | Explain what to do next. |
def heating_remaining(self):
try:
if self.side == 'left':
timerem = self.device.device_data['leftHeatingDuration']
elif self.side == 'right':
timerem = self.device.device_data['rightHeatingDuration']
return timerem
except TypeError:
return None | Return seconds of heat time remaining. |
def power_source_str(self):
if DeviceInfo.ATTR_POWER_SOURCE not in self.raw:
return None
return DeviceInfo.VALUE_POWER_SOURCES.get(self.power_source, 'Unknown') | String representation of current power source. |
def autocmd(name, pattern='*', sync=False, allow_nested=False, eval=None):
def dec(f):
f._nvim_rpc_method_name = 'autocmd:{}:{}'.format(name, pattern)
f._nvim_rpc_sync = sync
f._nvim_bind = True
f._nvim_prefix_plugin_path = True
opts = {
'pattern': pattern
}
if eval:
opts['eval'] = eval
if not sync and allow_nested:
rpc_sync = "urgent"
else:
rpc_sync = sync
f._nvim_rpc_spec = {
'type': 'autocmd',
'name': name,
'sync': rpc_sync,
'opts': opts
}
return f
return dec | Tag a function or plugin method as a Nvim autocommand handler. |
def fmt_routes(bottle_app):
routes = [(r.method, r.rule) for r in bottle_app.routes]
if not routes:
return
string = 'Routes:\n'
string += fmt_pairs(routes, sort_key=operator.itemgetter(1))
return string | Return a pretty formatted string of the list of routes. |
def raw(self):
if self._raw is None:
self._raw = HttpStream(self)
return self._raw | A raw asynchronous Http response |
def disconnect(self):
self._logger.info("iface '%s' disconnects", self.name())
self._wifi_ctrl.disconnect(self._raw_obj) | Disconnect from the specified AP. |
def reportPrettyData(root, worker, job, job_types, options):
out_str = "Batch System: %s\n" % root.batch_system
out_str += ("Default Cores: %s Default Memory: %s\n"
"Max Cores: %s\n" % (
reportNumber(get(root, "default_cores"), options),
reportMemory(get(root, "default_memory"), options, isBytes=True),
reportNumber(get(root, "max_cores"), options),
))
out_str += ("Total Clock: %s Total Runtime: %s\n" % (
reportTime(get(root, "total_clock"), options),
reportTime(get(root, "total_run_time"), options),
))
job_types = sortJobs(job_types, options)
columnWidths = computeColumnWidths(job_types, worker, job, options)
out_str += "Worker\n"
out_str += sprintTag("worker", worker, options, columnWidths=columnWidths)
out_str += "Job\n"
out_str += sprintTag("job", job, options, columnWidths=columnWidths)
for t in job_types:
out_str += " %s\n" % t.name
out_str += sprintTag(t.name, t, options, columnWidths=columnWidths)
return out_str | print the important bits out. |
def to_json_object(self):
obj_dict = dict(namespace_start=self.namespace_start,
namespace_end=self.namespace_end)
if self.app is not None:
obj_dict['app'] = self.app
return obj_dict | Returns a dict representation that can be serialized to JSON. |
def _setup_pailgun(self):
def runner_factory(sock, arguments, environment):
return self._runner_class.create(
sock,
arguments,
environment,
self.services,
self._scheduler_service,
)
@contextmanager
def lifecycle_lock():
with self.services.lifecycle_lock:
yield
return PailgunServer(self._bind_addr, runner_factory, lifecycle_lock, self._request_complete_callback) | Sets up a PailgunServer instance. |
def list_users(self, limit=None, marker=None):
return self._user_manager.list(limit=limit, marker=marker) | Returns a list of the names of all users for this instance. |
def _hincrby(self, hashkey, attribute, command, type_, increment):
redis_hash = self._get_hash(hashkey, command, create=True)
attribute = self._encode(attribute)
previous_value = type_(redis_hash.get(attribute, '0'))
redis_hash[attribute] = self._encode(previous_value + increment)
return type_(redis_hash[attribute]) | Shared hincrby and hincrbyfloat routine |
def _create_project_ssh_key_pair(project, public_key, ssh_user):
key_parts = public_key.split(" ")
assert len(key_parts) == 2, key_parts
assert key_parts[0] == "ssh-rsa", key_parts
new_ssh_meta = "{ssh_user}:ssh-rsa {key_value} {ssh_user}".format(
ssh_user=ssh_user, key_value=key_parts[1])
common_instance_metadata = project["commonInstanceMetadata"]
items = common_instance_metadata.get("items", [])
ssh_keys_i = next(
(i for i, item in enumerate(items) if item["key"] == "ssh-keys"), None)
if ssh_keys_i is None:
items.append({"key": "ssh-keys", "value": new_ssh_meta})
else:
ssh_keys = items[ssh_keys_i]
ssh_keys["value"] += "\n" + new_ssh_meta
items[ssh_keys_i] = ssh_keys
common_instance_metadata["items"] = items
operation = compute.projects().setCommonInstanceMetadata(
project=project["name"], body=common_instance_metadata).execute()
response = wait_for_compute_global_operation(project["name"], operation)
return response | Inserts an ssh-key into project commonInstanceMetadata |
def from_dict(doc):
if 'path' in doc:
path = doc['path']
else:
path = None
return ModelOutputFile(
doc['filename'],
doc['mimeType'],
path=path
) | Create a model output file object from a dictionary. |
def to_native(self, obj):
ret = super(UserSerializer, self).to_native(obj)
del ret['password']
return ret | Remove password field when serializing an object |
def process_queues(self, forced=False):
with self.lock:
if (not forced and not self.must_process) or not self.queues_enabled:
return
self.must_process = False
ARBITRATOR.awaken() | Process queues if any have data queued |
def _convert_string_name(self, k):
k = String(k, "iso-8859-1")
klower = k.lower().replace('_', '-')
bits = klower.split('-')
return "-".join((bit.title() for bit in bits)) | converts things like FOO_BAR to Foo-Bar which is the normal form |
def within_n_mads(n, series):
mad_score = (series - series.mean()) / series.mad()
return (mad_score.abs() <= n).all() | Return true if all values in sequence are within n MADs |
def publish_string(self, rest, outfile, styles=''):
html = self.convert_string(rest)
html = self.strip_xml_header(html)
html = self.apply_styles(html, styles)
self.write_file(html, outfile)
return outfile | Render a reST string as HTML. |
def encodeQueryElement(element):
return urllib.parse.quote(
(
element.encode('utf-8')
if isinstance(element, str)
else str(element)
if isinstance(element, int)
else element
),
safe=d1_common.const.URL_QUERYELEMENT_SAFE_CHARS,
) | Encode a URL query element according to RFC3986. |
def clean_sample_data(samples):
out = []
for data in (utils.to_single_data(x) for x in samples):
if "dirs" in data:
data["dirs"] = {"work": data["dirs"]["work"], "galaxy": data["dirs"]["galaxy"],
"fastq": data["dirs"].get("fastq")}
data["config"] = {"algorithm": data["config"]["algorithm"],
"resources": data["config"]["resources"]}
for remove_attr in ["config_file", "algorithm"]:
data.pop(remove_attr, None)
out.append([data])
return out | Clean unnecessary information from sample data, reducing size for message passing. |
def jarManifest(target, source, env, for_signature):
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
return src
return '' | Look in sources for a manifest file, if any. |
def tmp_chdir(new_path):
prev_cwd = os.getcwd()
os.chdir(new_path)
try:
yield
finally:
os.chdir(prev_cwd) | Change directory temporarily and return when done. |
def update_dscp_marking_rule(self, rule, policy, body=None):
return self.put(self.qos_dscp_marking_rule_path %
(policy, rule), body=body) | Updates a DSCP marking rule. |
def readable_time_delta(seconds):
days = seconds // 86400
seconds -= days * 86400
hours = seconds // 3600
seconds -= hours * 3600
minutes = seconds // 60
m_suffix = 's' if minutes != 1 else ''
h_suffix = 's' if hours != 1 else ''
d_suffix = 's' if days != 1 else ''
retval = u'{0} minute{1}'.format(minutes, m_suffix)
if hours != 0:
retval = u'{0} hour{1} and {2}'.format(hours, h_suffix, retval)
if days != 0:
retval = u'{0} day{1}, {2}'.format(days, d_suffix, retval)
return retval | Convert a number of seconds into readable days, hours, and minutes |
def ProcessMessage(self, message):
self.ProcessResponse(message.source.Basename(), message.payload) | Processes a stats response from the client. |
def astensor(array: TensorLike) -> BKTensor:
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor | Covert numpy array to tensorflow tensor |
def until_any_child_in_state(self, state, timeout=None):
return until_any(*[r.until_state(state) for r in dict.values(self.children)],
timeout=timeout) | Return a tornado Future; resolves when any client is in specified state |
def _readXputMaps(self, mapCards, directory, session, spatial=False, spatialReferenceID=4236, replaceParamFile=None):
if self.mapType in self.MAP_TYPES_SUPPORTED:
for card in self.projectCards:
if (card.name in mapCards) and self._noneOrNumValue(card.value):
filename = card.value.strip('"')
self._invokeRead(fileIO=RasterMapFile,
directory=directory,
filename=filename,
session=session,
spatial=spatial,
spatialReferenceID=spatialReferenceID,
replaceParamFile=replaceParamFile)
else:
for card in self.projectCards:
if (card.name in mapCards) and self._noneOrNumValue(card.value):
filename = card.value.strip('"')
fileExtension = filename.split('.')[1]
if fileExtension in self.ALWAYS_READ_AND_WRITE_MAPS:
self._invokeRead(fileIO=RasterMapFile,
directory=directory,
filename=filename,
session=session,
spatial=spatial,
spatialReferenceID=spatialReferenceID,
replaceParamFile=replaceParamFile)
log.warning('Could not read map files. '
'MAP_TYPE {0} not supported.'.format(self.mapType)) | GSSHA Project Read Map Files from File Method |
def runSearchVariants(self, request):
return self.runSearchRequest(
request, protocol.SearchVariantsRequest,
protocol.SearchVariantsResponse,
self.variantsGenerator) | Runs the specified SearchVariantRequest. |
def rcauchy(alpha, beta, size=None):
return alpha + beta * np.tan(pi * random_number(size) - pi / 2.0) | Returns Cauchy random variates. |
def main(argv=sys.argv, stream=sys.stderr):
args = parse_args(argv)
suite = build_suite(args)
runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)
result = runner.run(suite)
return get_status(result) | Entry point for ``tappy`` command. |
def gene_names(self):
for record in SeqIO.parse(self.targets, 'fasta'):
self.genes.append(record.id) | Extract the names of the user-supplied targets |
def _handle_list(reclist):
ret = []
for item in reclist:
recs = _handle_resource_setting(item)
ret += [resource for resource in recs if resource.access_controller]
return ret | Return list of resources that have access_controller defined. |
def entries(self):
def add(x, y):
return x + y
try:
return reduce(add, list(self.cache.values()))
except:
return [] | Returns a list of all entries |
def _context_json(name):
from renku.models import provenance
cls = getattr(provenance, name)
return {
'@context': cls._jsonld_context,
'@type': cls._jsonld_type,
} | Return JSON-LD string for given context name. |
def response_doc(self):
try:
return self.__dict__['response_doc']
except KeyError:
self.__dict__['response_doc'] = ElementTree.fromstring(
self.response_xml
)
return self.__dict__['response_doc'] | The XML document received from the service. |
def do_upgrade():
op.alter_column(
table_name='knwKBRVAL',
column_name='id_knwKB',
type_=db.MediumInteger(8, unsigned=True),
existing_nullable=False,
existing_server_default='0'
) | Carry out the upgrade. |
def create_index(self, index=None, settings=None, es=None):
if index is None:
index = self.index
if es is None:
es = self.es
try:
alias = index
index = generate_index_name(alias)
args = {'index': index}
if settings:
args['body'] = settings
es.indices.create(**args)
es.indices.put_alias(index, alias)
logger.info('created index alias=%s index=%s' % (alias, index))
except elasticsearch.TransportError:
pass | Create new index and ignore if it exists already. |
async def _get_response(self, msg):
try:
protocol = await self._get_protocol()
pr = protocol.request(msg)
r = await pr.response
return pr, r
except ConstructionRenderableError as e:
raise ClientError("There was an error with the request.", e)
except RequestTimedOut as e:
await self._reset_protocol(e)
raise RequestTimeout('Request timed out.', e)
except (OSError, socket.gaierror, Error) as e:
await self._reset_protocol(e)
raise ServerError("There was an error with the request.", e)
except asyncio.CancelledError as e:
await self._reset_protocol(e)
raise e | Perform the request, get the response. |
def prt_error_summary(self, fout_err):
errcnts = []
if self.ignored:
errcnts.append(" {N:9,} IGNORED associations\n".format(N=len(self.ignored)))
if self.illegal_lines:
for err_name, errors in self.illegal_lines.items():
errcnts.append(" {N:9,} {ERROR}\n".format(N=len(errors), ERROR=err_name))
fout_log = self._wrlog_details_illegal_gaf(fout_err, errcnts)
sys.stdout.write(" WROTE GAF ERROR LOG: {LOG}:\n".format(LOG=fout_log))
for err_cnt in errcnts:
sys.stdout.write(err_cnt) | Print a summary about the GAF file that was read. |
def create(cls, paramCount):
return Particle(numpy.array([[]]*paramCount),
numpy.array([[]]*paramCount),
-numpy.Inf) | Creates a new particle without position, velocity and -inf as fitness |
def projC(gamma, q):
return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10)) | return the KL projection on the column constrints |
def _interval(dates):
interval = (dates[1] - dates[0]).days
last = dates[0]
for dat in dates[1:]:
if (dat - last).days != interval:
return 0
last = dat
return interval | Return the distance between all dates and 0 if they are different |
def _approx_eq_(self, other: Any, atol: float) -> bool:
if not isinstance(other, LinearDict):
return NotImplemented
all_vs = set(self.keys()) | set(other.keys())
return all(abs(self[v] - other[v]) < atol for v in all_vs) | Checks whether two linear combinations are approximately equal. |
def write_and_quit_all(editor):
eb = editor.window_arrangement.active_editor_buffer
if eb.location is None:
editor.show_message(_NO_FILE_NAME)
else:
eb.write()
quit(editor, all_=True, force=False) | Write current buffer and quit all. |
def parse(resp) -> DataFrameType:
statements = []
for statement in resp['results']:
series = {}
for s in statement.get('series', []):
series[_get_name(s)] = _drop_zero_index(_serializer(s))
statements.append(series)
if len(statements) == 1:
series: dict = statements[0]
if len(series) == 1:
return list(series.values())[0]
else:
return series
return statements | Makes a dictionary of DataFrames from a response object |
def _loadDB(self):
if not self._validID():
raise NotFound, self._getID()
(sql, fields) = self._prepareSQL("SELECT")
curs = self.cursor()
curs.execute(sql, self._getID())
result = curs.fetchone()
if not result:
curs.close()
raise NotFound, self._getID()
self._loadFromRow(result, fields, curs)
curs.close()
self._updated = time.time() | Connect to the database to load myself |
def _execute(self,
command,
args,
env_vars=None,
shim=None
):
main_args = [command] + args
logger.debug("calling pip %s", ' '.join(main_args))
rc, out, err = self._wrapped_pip.main(main_args, env_vars=env_vars,
shim=shim)
return rc, out, err | Execute a pip command with the given arguments. |
def as_dict(self):
data = get_dict_for_attrs(self, ['id', 'raw_id', 'short_id',
'revision', 'date', 'message'])
data['author'] = {'name': self.author_name, 'email': self.author_email}
data['added'] = [node.path for node in self.added]
data['changed'] = [node.path for node in self.changed]
data['removed'] = [node.path for node in self.removed]
return data | Returns dictionary with changeset's attributes and their values. |
def install(self):
remote_path = os.path.join(self.venv, 'requirements.txt')
put(self.requirements, remote_path)
run('{pip} install -r {requirements}'.format(
pip=self.pip(), requirements=remote_path)) | Use pip to install the requirements file. |
def on_epoch_end(self, epoch:int, **kwargs:Any)->None:
"Compare the value monitored to its best score and maybe save the model."
if self.every=="epoch": self.learn.save(f'{self.name}_{epoch}')
else:
current = self.get_monitor_value()
if current is not None and self.operator(current, self.best):
print(f'Better model found at epoch {epoch} with {self.monitor} value: {current}.')
self.best = current
self.learn.save(f'{self.name}') | Compare the value monitored to its best score and maybe save the model. |
def dictapply(d, fn):
for k, v in d.items():
if isinstance(v, dict):
v = dictapply(v, fn)
else:
d[k] = fn(v)
return d | apply a function to all non-dict values in a dictionary |
def itervalues(self):
"Returns an iterator over the values of ConfigMap."
return chain(self._pb.StringMap.values(),
self._pb.IntMap.values(),
self._pb.FloatMap.values(),
self._pb.BoolMap.values()) | Returns an iterator over the values of ConfigMap. |
def get(self, tags):
value = tags.get(self.name, '')
for name in self.alternate_tags:
value = value or tags.get(name, '')
value = value or self.default
return value | Find an adequate value for this field from a dict of tags. |
def to_glyphs_master_user_data(self, ufo, master):
target_user_data = master.userData
for key, value in ufo.lib.items():
if _user_data_has_no_special_meaning(key):
target_user_data[key] = value
if ufo.data.fileNames:
from glyphsLib.types import BinaryData
ufo_data = {}
for os_filename in ufo.data.fileNames:
filename = posixpath.join(*os_filename.split(os.path.sep))
ufo_data[filename] = BinaryData(ufo.data[os_filename])
master.userData[UFO_DATA_KEY] = ufo_data | Set the GSFontMaster userData from the UFO master-specific lib data. |
def filter_slaves(self, slaves):
"Remove slaves that are in an ODOWN or SDOWN state"
slaves_alive = []
for slave in slaves:
if slave['is_odown'] or slave['is_sdown']:
continue
slaves_alive.append((slave['ip'], slave['port']))
return slaves_alive | Remove slaves that are in an ODOWN or SDOWN state |
def _set_django_attributes(span, request):
django_user = getattr(request, 'user', None)
if django_user is None:
return
user_id = django_user.pk
try:
user_name = django_user.get_username()
except AttributeError:
return
if user_id is not None:
span.add_attribute('django.user.id', str(user_id))
if user_name is not None:
span.add_attribute('django.user.name', str(user_name)) | Set the django related attributes. |
def _do_mstep(self, X, responsibilities, params, min_covar=0):
weights = responsibilities.sum(axis=0)
weighted_X_sum = np.dot(responsibilities.T, X)
inverse_weights = 1.0 / (weights[:, np.newaxis] + 10 * EPS)
if 'w' in params:
self.weights_ = (weights / (weights.sum() + 10 * EPS) + EPS)
if 'm' in params:
self.means_ = weighted_X_sum * inverse_weights
if 'c' in params:
covar_mstep_func = _covar_mstep_funcs[self.covariance_type]
self.covars_ = covar_mstep_func(
self, X, responsibilities, weighted_X_sum, inverse_weights,
min_covar)
return weights | Perform the Mstep of the EM algorithm and return the class weihgts. |
def value_to_string(self, obj):
try:
return force_unicode(self.__get__(obj))
except TypeError:
return str(self.__get__(obj)) | This descriptor acts as a Field, as far as the serializer is concerned. |
def importobj(modpath, attrname):
module = __import__(modpath, None, None, ['__doc__'])
if not attrname:
return module
retval = module
names = attrname.split(".")
for x in names:
retval = getattr(retval, x)
return retval | imports a module, then resolves the attrname on it |
def cmd_accelcal(self, args):
mav = self.master
mav.mav.command_long_send(mav.target_system, mav.target_component,
mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
0, 0, 0, 0, 1, 0, 0)
self.accelcal_count = 0
self.accelcal_wait_enter = False | do a full 3D accel calibration |
def load_class_by_name(name: str):
mod_path, _, cls_name = name.rpartition('.')
mod = importlib.import_module(mod_path)
cls = getattr(mod, cls_name)
return cls | Given a dotted path, returns the class |
def update_contents(self, contents, mime_type):
import hashlib
import time
new_size = len(contents)
self.mime_type = mime_type
if mime_type == 'text/plain':
self.contents = contents.encode('utf-8')
else:
self.contents = contents
old_hash = self.hash
self.hash = hashlib.md5(self.contents).hexdigest()
if self.size and (old_hash != self.hash):
self.modified = int(time.time())
self.size = new_size | Update the contents and set the hash and modification time |
def escape(value):
if isinstance(value, (tuple, list)):
return "(" + ", ".join([escape(arg) for arg in value]) + ")"
else:
typ = by_python_type.get(value.__class__)
if typ is None:
raise InterfaceError(
"Unsupported python input: %s (%s)" % (value, value.__class__)
)
return typ.to_sql(value) | Escape a single value. |
def _render_template(config_file):
dirname, filename = os.path.split(config_file)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(dirname))
template = env.get_template(filename)
return template.render(__grains__) | Render config template, substituting grains where found. |
def started(generator_function):
@wraps(generator_function)
def wrapper(*args, **kwargs):
g = generator_function(*args, **kwargs)
next(g)
return g
return wrapper | starts a generator when created |
def write_training_data(self, features, targets):
assert len(features) == len(targets)
data = dict(zip(features, targets))
with open(os.path.join(self.repopath, 'training.pkl'), 'w') as fp:
pickle.dump(data, fp) | Writes data dictionary to filename |
def add_row(self):
tbl = self._tbl
tr = tbl.add_tr()
for gridCol in tbl.tblGrid.gridCol_lst:
tc = tr.add_tc()
tc.width = gridCol.w
return _Row(tr, self) | Return a |_Row| instance, newly added bottom-most to the table. |
def exclusion_path(cls, project, exclusion):
return google.api_core.path_template.expand(
"projects/{project}/exclusions/{exclusion}",
project=project,
exclusion=exclusion,
) | Return a fully-qualified exclusion string. |
def _filter_schemas(schemas, schema_tables, exclude_table_columns):
return [_filter_schema(s, schema_tables, exclude_table_columns)
for s in schemas] | Wrapper method for _filter_schema to filter multiple schemas. |
def focus_parent(self):
mid = self.get_selected_mid()
newpos = self._tree.parent_position(mid)
if newpos is not None:
newpos = self._sanitize_position((newpos,))
self.body.set_focus(newpos) | move focus to parent of currently focussed message |
def convert_using_api(from_currency, to_currency):
convert_str = from_currency + '_' + to_currency
options = {'compact': 'ultra', 'q': convert_str}
api_url = 'https://free.currencyconverterapi.com/api/v5/convert'
result = requests.get(api_url, params=options).json()
return result[convert_str] | convert from from_currency to to_currency by requesting API |
def _check_doc(self, root):
if (root.tag != 'ISO_4217' or
root[0].tag != 'CcyTbl' or
root[0][0].tag != 'CcyNtry' or
not root.attrib['Pblshd'] or
len(root[0]) < 270):
raise TypeError("%s: XML %s appears to be invalid" % (self.name, self._cached_currency_file))
return datetime.strptime(root.attrib['Pblshd'], '%Y-%m-%d').date() | Validates the xml tree and returns the published date |
def look_at(self, x, y, z):
for camera in self.cameras:
camera.look_at(x, y, z) | Converges the two cameras to look at the specific point |
def generate_big_urls_glove(bigurls=None):
bigurls = bigurls or {}
for num_dim in (50, 100, 200, 300):
for suffixes, num_words in zip(
('sm -sm _sm -small _small'.split(),
'med -med _med -medium _medium'.split(),
'lg -lg _lg -large _large'.split()),
(6, 42, 840)
):
for suf in suffixes[:-1]:
name = 'glove' + suf + str(num_dim)
dirname = 'glove.{num_words}B'.format(num_words=num_words)
filename = dirname + '.{num_dim}d.w2v.txt'.format(num_dim=num_dim)
bigurl_tuple = BIG_URLS['glove' + suffixes[-1]]
bigurls[name] = list(bigurl_tuple[:2])
bigurls[name].append(os.path.join(dirname, filename))
bigurls[name].append(load_glove)
bigurls[name] = tuple(bigurls[name])
return bigurls | Generate a dictionary of URLs for various combinations of GloVe training set sizes and dimensionality |
def mode(self, mode):
_LOGGER.debug("Setting new mode: %s", mode)
if self.mode == Mode.Boost and mode != Mode.Boost:
self.boost = False
if mode == Mode.Boost:
self.boost = True
return
elif mode == Mode.Away:
end = datetime.now() + self._away_duration
return self.set_away(end, self._away_temp)
elif mode == Mode.Closed:
return self.set_mode(0x40 | int(EQ3BT_OFF_TEMP * 2))
elif mode == Mode.Open:
return self.set_mode(0x40 | int(EQ3BT_ON_TEMP * 2))
if mode == Mode.Manual:
temperature = max(min(self._target_temperature, self.max_temp),
self.min_temp)
return self.set_mode(0x40 | int(temperature * 2))
else:
return self.set_mode(0) | Set the operation mode. |
def on_view_not_found(
self,
environ: Dict[str, Any],
start_response: Callable) -> Iterable[bytes]:
raise NotImplementedError() | called when view is not found |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.