code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def datapath(self):
path = self._fields['path']
if not path:
path = self.fetch('directory')
if path and not self._fields['is_multi_file']:
path = os.path.join(path, self._fields['name'])
return os.path.expanduser(fmt.to_unicode(path)) | Get an item's data path. |
def as_odict(self):
if hasattr(self, 'cust_odict'):
return self.cust_odict
if hasattr(self, 'attr_check'):
self.attr_check()
odc = odict()
for attr in self.attrorder:
odc[attr] = getattr(self, attr)
return odc | returns an odict version of the object, based on it's attributes |
def create_backend(self,
service_id,
version_number,
name,
address,
use_ssl=False,
port=80,
connect_timeout=1000,
first_byte_timeout=15000,
between_bytes_timeout=10000,
error_threshold=0,
max_conn=20,
weight=100,
auto_loadbalance=False,
shield=None,
request_condition=None,
healthcheck=None,
comment=None):
body = self._formdata({
"name": name,
"address": address,
"use_ssl": use_ssl,
"port": port,
"connect_timeout": connect_timeout,
"first_byte_timeout": first_byte_timeout,
"between_bytes_timeout": between_bytes_timeout,
"error_threshold": error_threshold,
"max_conn": max_conn,
"weight": weight,
"auto_loadbalance": auto_loadbalance,
"shield": shield,
"request_condition": request_condition,
"healthcheck": healthcheck,
"comment": comment,
}, FastlyBackend.FIELDS)
content = self._fetch("/service/%s/version/%d/backend" % (service_id, version_number), method="POST", body=body)
return FastlyBackend(self, content) | Create a backend for a particular service and version. |
def copy(self, src_fs, src_path, dst_fs, dst_path):
if self.queue is None:
copy_file_internal(src_fs, src_path, dst_fs, dst_path)
else:
src_file = src_fs.openbin(src_path, "r")
try:
dst_file = dst_fs.openbin(dst_path, "w")
except Exception:
src_file.close()
raise
task = _CopyTask(src_file, dst_file)
self.queue.put(task) | Copy a file from one fs to another. |
def runlist_view(name, **kwargs):
ctx = Context(**kwargs)
ctx.execute_action('runlist:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name
}) | Show configuration content for a specified runlist. |
def decode_token(self, token):
key = current_app.secret_key
if key is None:
if current_app.debug:
current_app.logger.debug("app.secret_key not set")
return None
try:
return jwt.decode(
token, key,
algorithms=[self.config["algorithm"]],
options={'require_exp': True}
)
except jwt.InvalidTokenError:
return None | Decode Authorization token, return None if token invalid |
def deserialize_number(s, fmt=SER_BINARY):
ret = gmpy.mpz(0)
if fmt == SER_BINARY:
if isinstance(s, six.text_type):
raise ValueError(
"Encode `s` to a bytestring yourself to" +
" prevent problems with different default encodings")
for c in s:
ret *= 256
ret += byte2int(c)
return ret
assert fmt == SER_COMPACT
if isinstance(s, six.text_type):
s = s.encode('ascii')
for c in s:
ret *= len(COMPACT_DIGITS)
ret += R_COMPACT_DIGITS[c]
return ret | Deserializes a number from a string `s' in format `fmt' |
def setup_observations(self):
obs_methods = [self.setup_water_budget_obs,self.setup_hyd,
self.setup_smp,self.setup_hob,self.setup_hds,
self.setup_sfr_obs]
obs_types = ["mflist water budget obs","hyd file",
"external obs-sim smp files","hob","hds","sfr"]
self.obs_dfs = {}
for obs_method, obs_type in zip(obs_methods,obs_types):
self.log("processing obs type {0}".format(obs_type))
obs_method()
self.log("processing obs type {0}".format(obs_type)) | main entry point for setting up observations |
def disk2ram(self):
values = self.series
self.deactivate_disk()
self.ramflag = True
self.__set_array(values)
self.update_fastaccess() | Move internal data from disk to RAM. |
def rpc_get_docstring(self, filename, source, offset):
return self._call_backend("rpc_get_docstring", None, filename,
get_source(source), offset) | Get the docstring for the symbol at the offset. |
def run(self):
install.run(self)
spath = os.path.join(self.install_scripts, 'pygubu')
for ext in ('.py', '.pyw'):
filename = spath + ext
if os.path.exists(filename):
os.remove(filename)
if platform.system() == 'Windows':
spath = os.path.join(self.install_scripts, 'pygubu-designer.bat')
if os.path.exists(spath):
os.remove(spath) | Run parent install, and then save the install dir in the script. |
def _serialize_object(self, response_data, request):
if self._is_doc_request(request):
return response_data
else:
return super(DocumentedResource, self)._serialize_object(
response_data, request) | Override to not serialize doc responses. |
def evaluate(molecules, ensemble_chunk, sort_order, options, output_queue=None):
results = {}
for ensemble in ensemble_chunk:
results[ensemble] = calculate_performance(molecules, ensemble, sort_order, options)
if output_queue is not None:
output_queue.put(results)
else:
return results | Evaluate VS performance of each ensemble in ensemble_chunk |
def flat_data(self):
def flat_field(value):
try:
value.flat_data()
return value
except AttributeError:
return value
modified_dict = self.__original_data__
modified_dict.update(self.__modified_data__)
self.__original_data__ = {k: flat_field(v)
for k, v in modified_dict.items()
if k not in self.__deleted_fields__}
self.clear_modified_data() | Pass all the data from modified_data to original_data |
def cost_min2(self, alpha):
n = self.V.dim()
ax = alpha[:n]
ay = alpha[n:]
q2, r2 = self.get_q2_r2(ax, ay)
Lax = self.L * ax
Lay = self.L * ay
out = [
0.5 * numpy.dot(Lax, Lax),
0.5 * numpy.dot(Lay, Lay),
0.5 * numpy.dot(q2 - 1, q2 - 1),
0.5 * numpy.dot(r2, r2),
]
if self.num_f_eval % 10000 == 0:
print("{:7d} {:e} {:e} {:e} {:e}".format(self.num_f_eval, *out))
self.num_f_eval += 1
return numpy.sum(out) | Residual formulation, Hessian is a low-rank update of the identity. |
def run(self):
while not self.wait(self.delay()):
try:
logger.info('Invoking callback %s', self.callback)
self.callback()
except StandardError:
logger.exception('Callback failed') | Run the callback periodically |
def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True):
if root is None:
root = {}
tcoords = dataset.GetPointData().GetTCoords()
if tcoords:
dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress)
root['pointData']['activeTCoords'] = len(root['pointData']['arrays'])
root['pointData']['arrays'].append({'data': dumped_array}) | dump vtkjs texture coordinates |
def _check_voSet(orb,kwargs,funcName):
if not orb._voSet and kwargs.get('vo',None) is None:
warnings.warn("Method %s(.) requires vo to be given at Orbit initialization or at method evaluation; using default vo which is %f km/s" % (funcName,orb._vo),
galpyWarning) | Function to check whether vo is set, because it's required for funcName |
def SetCoreGRRKnowledgeBaseValues(kb, client_obj):
client_schema = client_obj.Schema
kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.FQDN, ""))
if not kb.fqdn:
kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.HOSTNAME, ""))
versions = client_obj.Get(client_schema.OS_VERSION)
if versions and versions.versions:
try:
kb.os_major_version = versions.versions[0]
kb.os_minor_version = versions.versions[1]
except IndexError:
pass
client_os = client_obj.Get(client_schema.SYSTEM)
if client_os:
kb.os = utils.SmartUnicode(client_obj.Get(client_schema.SYSTEM)) | Set core values from GRR into the knowledgebase. |
def execute(self):
self.prepare_models()
self.prepare_worker()
if self.options.print_options:
self.print_options()
self.run() | Main method to call to run the worker |
def as_set(self, decode=False):
items = self.database.smembers(self.key)
return set(_decode(item) for item in items) if decode else items | Return a Python set containing all the items in the collection. |
def _panel_domains(self,n=2,min_panel_size=.15,spacing=0.08,top_margin=1,bottom_margin=0):
d={}
for _ in range(n+1,1,-1):
lower=round(bottom_margin+(min_panel_size+spacing)*(n+1-_),2)
d['yaxis{0}'.format(_)]=dict(domain=(lower,lower+min_panel_size))
top=d['yaxis2']['domain']
d['yaxis2']['domain']=(top[0],top_margin)
return d | Returns the panel domains for each axis |
def _update_keymap(self, first_keycode, count):
lastcode = first_keycode + count
for keysym, codes in self._keymap_syms.items():
i = 0
while i < len(codes):
code = codes[i][1]
if code >= first_keycode and code < lastcode:
del codes[i]
else:
i = i + 1
keysyms = self.get_keyboard_mapping(first_keycode, count)
self._keymap_codes[first_keycode:lastcode] = keysyms
code = first_keycode
for syms in keysyms:
index = 0
for sym in syms:
if sym != X.NoSymbol:
if sym in self._keymap_syms:
symcodes = self._keymap_syms[sym]
symcodes.append((index, code))
symcodes.sort()
else:
self._keymap_syms[sym] = [(index, code)]
index = index + 1
code = code + 1 | Internal function, called to refresh the keymap cache. |
def fetcher_factory(conf):
global PROMOTERS
applicable = []
if not PROMOTERS:
PROMOTERS = load_promoters()
for promoter in PROMOTERS:
if promoter.is_applicable(conf):
applicable.append((promoter.PRIORITY, promoter))
if applicable:
best_match = sorted(applicable, reverse=True)[0][1]
return best_match(conf)
else:
raise ConfigurationError(
'No fetcher is applicable for "{0}"'.format(conf['name'])
) | Return initialized fetcher capable of processing given conf. |
def memory_error():
warning_heading = m.Heading(
tr('Memory issue'), **WARNING_STYLE)
warning_message = tr(
'There is not enough free memory to run this analysis.')
suggestion_heading = m.Heading(
tr('Suggestion'), **SUGGESTION_STYLE)
suggestion = tr(
'Try zooming in to a smaller area or using a raster layer with a '
'coarser resolution to speed up execution and reduce memory '
'requirements. You could also try adding more RAM to your computer.')
message = m.Message()
message.add(warning_heading)
message.add(warning_message)
message.add(suggestion_heading)
message.add(suggestion)
send_static_message(dispatcher.Anonymous, message) | Display an error when there is not enough memory. |
def _empty_queue(self):
while True:
try:
self.queue.pop()
self.unused += 1
self.nqueue -= 1
except:
self.nqueue = 0
break | Dump all live point proposals currently on the queue. |
def to_json(self, value):
if not self.is_valid(value):
raise ex.SerializeException('Invalid value: {}'.format(value))
return value | Subclasses should override this method for JSON encoding. |
def update(self):
self.filename = self.parent.info.dataset.filename
self.chan = self.parent.info.dataset.header['chan_name']
for chan in self.chan:
self.idx_chan.addItem(chan) | Get info from dataset before opening dialog. |
def AuthorizeUser(self, user, subject):
user_set = self.authorized_users.setdefault(subject, set())
user_set.add(user) | Allow given user access to a given subject. |
def settings(request):
from waliki.settings import WALIKI_USE_MATHJAX
return {k: v for (k, v) in locals().items() if k.startswith('WALIKI')} | inject few waliki's settings to the context to be used in templates |
def do_add_item(self, args):
if args.food:
add_item = args.food
elif args.sport:
add_item = args.sport
elif args.other:
add_item = args.other
else:
add_item = 'no items'
self.poutput("You added {}".format(add_item)) | Add item command help |
def coerce(self, value, includes=None, errors=None, resources=None, default_locale='en-US', locale=None):
if includes is None:
includes = []
if errors is None:
errors = []
return self._coerce_block(
value,
includes=includes,
errors=errors,
resources=resources,
default_locale=default_locale,
locale=locale
) | Coerces Rich Text properly. |
def to_jd(year, month, day):
gyear = year + 78
leap = isleap(gyear)
start = gregorian.to_jd(gyear, 3, 22 - leap)
if leap:
Caitra = 31
else:
Caitra = 30
if month == 1:
jd = start + (day - 1)
else:
jd = start + Caitra
m = month - 2
m = min(m, 5)
jd += m * 31
if month >= 8:
m = month - 7
jd += m * 30
jd += day - 1
return jd | Obtain Julian day for Indian Civil date |
def signup_time_future(self):
now = datetime.datetime.now()
return (now.date() < self.date or (self.date == now.date() and self.signup_time > now.time())) | Is the signup time in the future? |
def spatialDomainNoGrid(self):
self.w = np.zeros(self.xw.shape)
if self.Debug:
print("w = ")
print(self.w.shape)
for i in range(len(self.q)):
if self.q[i] != 0:
dist = np.abs(self.xw - self.x[i])
self.w -= self.q[i] * self.coeff * np.exp(-dist/self.alpha) * \
( np.cos(dist/self.alpha) + np.sin(dist/self.alpha) ) | Superposition of analytical solutions without a gridded domain |
def _sync_filters(self, filters_json):
for filter_json in filters_json:
filter_id = filter_json['id']
self.filters[filter_id] = Filter(filter_json, self) | Populate the user's filters from a JSON encoded list. |
def cancel(self, *args, **kwargs):
super().cancel()
for future in self.traverse():
if not future.cancelled():
future.cancel() | Manually cancel all tasks assigned to this event loop. |
def as_point(row):
return Point(row[COLS.X], row[COLS.Y], row[COLS.Z],
row[COLS.R], int(row[COLS.TYPE])) | Create a Point from a data block row |
def cleanup_event_loop(self):
for task in asyncio.Task.all_tasks(loop=self.loop):
if self.debug:
warnings.warn('Cancelling task: %s' % task)
task._log_destroy_pending = False
task.cancel()
self.loop.close()
self.loop.set_exception_handler(self.loop_exception_handler_save)
self.loop_exception_handler_save = None
self.loop_policy = None
self.loop = None | Cleanup an event loop and close it down forever. |
def merge_dicts(*dicts, **kwargs):
result = {}
for d in dicts:
result.update(d)
result.update(kwargs)
return result | Merges dicts and kwargs into one dict |
def _request_eip(interface, vm_):
params = {'Action': 'AllocateAddress'}
params['Domain'] = interface.setdefault('domain', 'vpc')
eips = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
for eip in eips:
if 'allocationId' in eip:
return eip['allocationId']
return None | Request and return Elastic IP |
def delete_nve_member(self, nexus_host, nve_int_num, vni):
starttime = time.time()
path_snip = snipp.PATH_VNI_UPDATE % (nve_int_num, vni)
self.client.rest_delete(path_snip, nexus_host)
self.capture_and_print_timeshot(
starttime, "delete_nve",
switch=nexus_host) | Delete a member configuration on the NVE interface. |
def slides(self):
sldIdLst = self._element.get_or_add_sldIdLst()
self.part.rename_slide_parts([sldId.rId for sldId in sldIdLst])
return Slides(sldIdLst, self) | |Slides| object containing the slides in this presentation. |
def _createbound(obj):
try:
kls = obj._unboundreference_()
except AttributeError:
kls = type(obj)
unbound = _createunbound(kls)
def valueget():
return obj
for t in (BoundBitfieldNode, BoundStructureNode, BoundArrayNode):
if isinstance(unbound, t._unboundtype):
kls = t
break
else:
kls = BoundSimpleNode
child = kls(unbound, valueget)
return child | Create a new BoundNode representing a given object. |
def list_domains_by_service(self, service_id):
content = self._fetch("/service/%s/domain" % service_id, method="GET")
return map(lambda x: FastlyDomain(self, x), content) | List the domains within a service. |
def _fix_valid_indices(cls, valid_indices, insertion_index, dim):
indices = np.array(sorted(valid_indices[dim]))
slice_index = np.sum(indices <= insertion_index)
indices[slice_index:] += 1
indices = np.insert(indices, slice_index, insertion_index + 1)
valid_indices[dim] = indices.tolist()
return valid_indices | Add indices for H&S inserted elements. |
def _read_object(self, path):
if not os.path.exists(path):
return None
if os.path.isdir(path):
raise RuntimeError('%s is a directory, not a file.' % path)
with open(path) as f:
file_contents = f.read()
return file_contents | read in object from file at `path` |
def _replace_lines(fn, startswith, new_line):
new_lines = []
for line in open(fn):
if line.startswith(startswith):
new_lines.append(new_line)
else:
new_lines.append(line)
with open(fn, 'w') as f:
f.write('\n'.join(new_lines)) | Replace lines starting with starts_with in fn with new_line. |
def decls(self) -> List[z3.ExprRef]:
result = []
for internal_model in self.raw:
result.extend(internal_model.decls())
return result | Get the declarations for this model |
def search(self, searchTerm):
if type(searchTerm)==type(''):
searchTerm=SearchTerm(searchTerm)
if searchTerm not in self.featpaths:
matches = None
if searchTerm.type != None and searchTerm.type != self.classname():
matches = self._searchInChildren(searchTerm)
elif searchTerm.isAtomic():
matches = self._searchSingleTerm(searchTerm)
else:
matches = self._searchMultipleTerms(searchTerm)
if matches == True:
matches = [self]
if matches == False:
matches = []
self.featpaths[searchTerm] = matches
return self.featpaths[searchTerm] | Returns objects matching the query. |
def handle_response(self, content, target=None, single_result=True, raw=False):
response = content['response']
self.check_errors(response)
data = response.get('data')
if is_empty(data):
return data
elif is_paginated(data):
if 'count' in data and not data['count']:
return data['data']
data = data['data']
if raw:
return data
return self.init_all_objects(data, target=target, single_result=single_result) | Parses response, checks it. |
def build_dir_tree(self, files):
def helper(split_files):
this_dir = {'files' : {}, 'dirs' : {}}
dirs = defaultdict(list)
for fle in split_files:
index = fle[0]; fileinfo = fle[1]
if len(index) == 1:
fileinfo['path'] = index[0]
this_dir['files'][fileinfo['path']] = fileinfo
elif len(index) > 1:
dirs[index[0]].append((index[1:], fileinfo))
for name,info in dirs.iteritems():
this_dir['dirs'][name] = helper(info)
return this_dir
return helper([(name.split('/')[1:], file_info) for name, file_info in files.iteritems()]) | Convert a flat file dict into the tree format used for storage |
def parse(s):
stopwatch = StopWatch()
for line in s.splitlines():
if line.strip():
parts = line.split(None)
name = parts[0]
if name != "%":
rest = (float(v) for v in parts[2:])
stopwatch.times[parts[0]].merge(Stat.build(*rest))
return stopwatch | Parse the output below to create a new StopWatch. |
def walk(node, walker):
method_name = '_' + node.__class__.__name__
method = getattr(walker, method_name, None)
if method is not None:
if isinstance(node, _ast.ImportFrom) and node.module is None:
node.module = ''
return method(node)
for child in get_child_nodes(node):
walk(child, walker) | Walk the syntax tree |
def _find_glob_matches(in_files, metadata):
reg_files = copy.deepcopy(in_files)
glob_files = []
for glob_search in [x for x in metadata.keys() if "*" in x]:
cur = []
for fname in in_files:
if fnmatch.fnmatch(fname, "*/%s" % glob_search):
cur.append(fname)
reg_files.remove(fname)
assert cur, "Did not find file matches for %s" % glob_search
glob_files.append(cur)
return reg_files, glob_files | Group files that match by globs for merging, rather than by explicit pairs. |
def split(attrs, inputs, proto_obj):
split_list = attrs.get('split') if 'split' in attrs else []
new_attrs = translation_utils._fix_attribute_names(attrs,
{'split' : 'num_outputs'})
if 'axis' not in attrs:
new_attrs = translation_utils._add_extra_attributes(new_attrs, {'axis': 0})
if not split_list:
num_outputs = len(proto_obj.model_metadata.get('output_tensor_data'))
else:
if len(set(split_list)) == 1:
num_outputs = len(split_list)
else:
raise NotImplementedError("Operator {} in MXNet does not support variable splits."
"Tracking the issue to support variable split here: "
"https://github.com/apache/incubator-mxnet/issues/11594"
.format('split'))
new_attrs['num_outputs'] = num_outputs
return 'split', new_attrs, inputs | Splits an array along a particular axis into multiple sub-arrays. |
def jenkins(self):
job_name = self.format['jenkins_job_name'].format(**self.data)
job = {'name': job_name}
return job | Generate jenkins job details. |
def connected(self, client):
self.clients.add(client)
self._log_connected(client)
self._start_watching(client)
self.send_msg(client, WELCOME, (self.pickle_protocol, __version__),
pickle_protocol=0)
profiler = self.profiler
while True:
try:
profiler = profiler.profiler
except AttributeError:
break
self.send_msg(client, PROFILER, type(profiler))
if self._latest_result_data is not None:
try:
self._send(client, self._latest_result_data)
except socket.error as exc:
if exc.errno in (EBADF, EPIPE):
self.disconnected(client)
return
raise
if len(self.clients) == 1:
self._start_profiling() | Call this method when a client connected. |
def _bend_cos_low(a, b, deriv):
a = Vector3(6, deriv, a, (0, 1, 2))
b = Vector3(6, deriv, b, (3, 4, 5))
a /= a.norm()
b /= b.norm()
return dot(a, b).results() | Similar to bend_cos, but with relative vectors |
def invenio_query_factory(parser=None, walkers=None):
parser = parser or Main
walkers = walkers or [PypegConverter()]
walkers.append(ElasticSearchDSL())
def invenio_query(pattern):
query = pypeg2.parse(pattern, parser, whitespace="")
for walker in walkers:
query = query.accept(walker)
return query
return invenio_query | Create a parser returning Elastic Search DSL query instance. |
def json(func):
"Decorator to make JSON views simpler"
def wrapper(self, request, *args, **kwargs):
try:
response = {
"success": True,
"data": func(self, request, *args, **kwargs)
}
except GargoyleException, exc:
response = {
"success": False,
"data": exc.message
}
except Switch.DoesNotExist:
response = {
"success": False,
"data": "Switch cannot be found"
}
except ValidationError, e:
response = {
"success": False,
"data": u','.join(map(unicode, e.messages)),
}
except Exception:
if settings.DEBUG:
import traceback
traceback.print_exc()
raise
return HttpResponse(dumps(response), content_type="application/json")
wrapper = wraps(func)(wrapper)
return wrapper | Decorator to make JSON views simpler |
def reset_scan_stats(self):
self._scan_event_count = 0
self._v1_scan_count = 0
self._v1_scan_response_count = 0
self._v2_scan_count = 0
self._device_scan_counts = {}
self._last_reset_time = time.time() | Clears the scan event statistics and updates the last reset time |
def marker_index_document_id(self):
params = '%s:%s:%s' % (self.index, self.doc_type, self.update_id)
return hashlib.sha1(params.encode('utf-8')).hexdigest() | Generate an id for the indicator document. |
def accuracy_thresh_expand(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor:
"Compute accuracy after expanding `y_true` to the size of `y_pred`."
if sigmoid: y_pred = y_pred.sigmoid()
return ((y_pred>thresh)==y_true[:,None].expand_as(y_pred).byte()).float().mean() | Compute accuracy after expanding `y_true` to the size of `y_pred`. |
def check_config(config):
"basic checks that the configuration file is valid"
shortnames = [count['shortname'] for count in config['count']]
if len(shortnames) != len(set(shortnames)):
logger.error("error: duplicate `shortname' in count configuration.")
return False
return True | basic checks that the configuration file is valid |
def __safe_name(self, method_name):
safe_name = re.sub(r'[^\.a-zA-Z0-9_]', '', method_name)
safe_name = safe_name.lstrip('_')
return safe_name[0:1].lower() + safe_name[1:] | Restrict method name to a-zA-Z0-9_, first char lowercase. |
def add_task_to_job(self, job_or_job_name, task_command, task_name=None,
**kwargs):
if isinstance(job_or_job_name, Job):
job = job_or_job_name
else:
job = self.get_job(job_or_job_name)
if not job:
raise DagobahError('job %s does not exist' % job_or_job_name)
logger.debug('Adding task with command {0} to job {1}'.format(task_command, job.name))
if not job.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current " +
"state: %s"
% job.state.status)
job.add_task(task_command, task_name, **kwargs)
job.commit() | Add a task to a job owned by the Dagobah instance. |
def getL2Representations(self):
return [set(L2.getSelf()._pooler.getActiveCells()) for L2 in self.L2Regions] | Returns the active representation in L2. |
def run_file(self, path, all_errors_exit=True):
path = fixpath(path)
with self.handling_errors(all_errors_exit):
module_vars = run_file(path)
self.vars.update(module_vars)
self.store("from " + splitname(path)[1] + " import *") | Execute a Python file. |
def image_box(center, shape, box):
return tuple(slice_create(c, b, stop=s)
for c, s, b in zip(center, shape, box)) | Create a region of size box, around a center in a image of shape. |
def write_file(data, outfilename):
if not data:
return False
try:
with open(outfilename, 'w') as outfile:
for line in data:
if line:
outfile.write(line)
return True
except (OSError, IOError) as err:
sys.stderr.write('An error occurred while writing {0}:\n{1}'
.format(outfilename, str(err)))
return False | Write a single file to disk. |
def find_name():
name_file = read_file('__init__.py')
name_match = re.search(r'^__package_name__ = ["\']([^"\']*)["\']',
name_file, re.M)
if name_match:
return name_match.group(1)
raise RuntimeError('Unable to find name string.') | Only define name in one place |
def _merge_inplace(self, other):
if other is None:
yield
else:
priority_vars = OrderedDict(
kv for kv in self.variables.items() if kv[0] not in self.dims)
variables = merge_coords_for_inplace_math(
[self.variables, other.variables], priority_vars=priority_vars)
yield
self._update_coords(variables) | For use with in-place binary arithmetic. |
def auto_complete(self, term, state=None, postcode=None, max_results=None):
self._validate_state(state)
params = {"term": term, "state": state, "postcode": postcode,
"max_results": max_results or self.max_results}
return self._make_request('/address/autoComplete', params) | Gets a list of addresses that begin with the given term. |
def insert_child(self, child_pid):
self._check_child_limits(child_pid)
try:
with db.session.begin_nested():
if not isinstance(child_pid, PersistentIdentifier):
child_pid = resolve_pid(child_pid)
return PIDRelation.create(
self._resolved_pid, child_pid, self.relation_type.id, None
)
except IntegrityError:
raise PIDRelationConsistencyError("PID Relation already exists.") | Add the given PID to the list of children PIDs. |
def _tool_classpath(self, tool, products, scheduler):
classpath = self.tool_classpath_from_products(products,
self.versioned_tool_name(tool, self.version),
scope=self.options_scope)
classpath = tuple(fast_relpath(c, get_buildroot()) for c in classpath)
return self._memoized_scalac_classpath(classpath, scheduler) | Return the proper classpath based on products and scala version. |
def could_be(self, other):
if type(other) is not type(self):
return NotImplemented
if self == other:
return True
for attr in ['title', 'firstname', 'middlename', 'nickname', 'prefix', 'lastname', 'suffix']:
if attr not in self or attr not in other:
continue
puncmap = dict((ord(char), None) for char in string.punctuation)
s = self[attr].lower().translate(puncmap)
o = other[attr].lower().translate(puncmap)
if s == o:
continue
if attr in {'firstname', 'middlename', 'lastname'}:
if (({len(comp) for comp in s.split()} == {1} and [el[0] for el in o.split()] == s.split()) or
({len(comp) for comp in o.split()} == {1} and [el[0] for el in s.split()] == o.split())):
continue
return False
return True | Return True if the other PersonName is not explicitly inconsistent. |
def _all_keys(self):
file_keys = [self._filename_to_key(fn) for fn in self._all_filenames()]
if self._sync:
return set(file_keys)
else:
return set(file_keys + list(self._buffer)) | Return a list of all encoded key names. |
def overlap_summary(self):
olaps = self.compute_overlaps()
table = [["5%: ",np.percentile(olaps,5)],
["25%: ",np.percentile(olaps,25)],
["50%: ",np.percentile(olaps,50)],
["75%: ",np.percentile(olaps,75)],
["95%: ",np.percentile(olaps,95)],
[" " , " "],
["Min: ",np.min(olaps)],
["Mean: ",np.mean(olaps)],
["Max: ",np.max(olaps)]]
header = ["Percentile","Overlap"]
print tabulate(table,header,tablefmt="rst") | print summary of reconstruction overlaps |
def remove_node(self, node):
if _debug: Network._debug("remove_node %r", node)
self.nodes.remove(node)
node.lan = None | Remove a node from this network. |
def getEvent(self, dev_id, starttime, endtime):
path = 'device/%s/event?startTime=%s&endTime=%s' % \
(dev_id, starttime, endtime)
return self.rachio.get(path) | Retrieve events for a device entity. |
def filter_dup(lst, lists):
max_rank = len(lst) + 1
dct = to_ranked_dict(lst)
dicts = [to_ranked_dict(l) for l in lists]
return [word for word in lst if all(dct[word] < dct2.get(word, max_rank) for dct2 in dicts)] | filters lst to only include terms that don't have lower rank in another list |
def set(self, val):
msg = ExtendedSend(
address=self._address,
commandtuple=COMMAND_THERMOSTAT_SET_COOL_SETPOINT_0X6C_NONE,
cmd2=int(val * 2),
userdata=Userdata())
msg.set_checksum()
self._send_method(msg, self._set_cool_point_ack) | Set the cool set point. |
def _send_event(self, title, text, tags, event_type, aggregation_key, severity='info'):
event_dict = {
'timestamp': int(time()),
'source_type_name': self.SOURCE_TYPE_NAME,
'msg_title': title,
'event_type': event_type,
'alert_type': severity,
'msg_text': text,
'tags': tags,
'aggregation_key': aggregation_key,
}
self.event(event_dict) | Emit an event to the Datadog Event Stream. |
def _convert_agent_types(ind, to_string=False, **kwargs):
if to_string:
return serialize_distribution(ind, **kwargs)
return deserialize_distribution(ind, **kwargs) | Convenience method to allow specifying agents by class or class name. |
def _parse_result(self, ok, match, fh=None):
peek_match = None
try:
if fh is not None and self._try_peeking:
peek_match = self.yaml_block_start.match(fh.peek())
except StopIteration:
pass
if peek_match is None:
return Result(
ok,
number=match.group("number"),
description=match.group("description").strip(),
directive=Directive(match.group("directive")),
)
indent = peek_match.group("indent")
concat_yaml = self._extract_yaml_block(indent, fh)
return Result(
ok,
number=match.group("number"),
description=match.group("description").strip(),
directive=Directive(match.group("directive")),
raw_yaml_block=concat_yaml,
) | Parse a matching result line into a result instance. |
def threeprime_plot(self):
data = dict()
dict_to_add = dict()
for key in self.threepGtoAfreq_data:
pos = list(range(1,len(self.threepGtoAfreq_data.get(key))))
tmp = [i * 100.0 for i in self.threepGtoAfreq_data.get(key)]
tuples = list(zip(pos,tmp))
data = dict((x, y) for x, y in tuples)
dict_to_add[key] = data
config = {
'id': 'threeprime_misinc_plot',
'title': 'DamageProfiler: 3P G>A misincorporation plot',
'ylab': '% G to A substituted',
'xlab': 'Nucleotide position from 3\'',
'tt_label': '{point.y:.2f} % G>A misincorporations at nucleotide position {point.x}',
'ymin': 0,
'xmin': 1
}
return linegraph.plot(dict_to_add,config) | Generate a 3' G>A linegraph plot |
def placeFiles(ftp, path):
for name in os.listdir(path):
if name != "config.py" and name != "config.pyc" and name != "templates" and name != "content":
localpath = os.path.join(path, name)
if os.path.isfile(localpath):
print("STOR", name, localpath)
ftp.storbinary('STOR ' + name, open(localpath, 'rb'))
elif os.path.isdir(localpath):
print("MKD", name)
try:
ftp.mkd(name)
except error_perm as e:
if not e.args[0].startswith('550'):
raise
print("CWD", name)
ftp.cwd(name)
placeFiles(ftp, localpath)
print("CWD", "..")
ftp.cwd("..") | Upload the built files to FTP |
def put_field(self, field):
fpath = self.fields_json_path(field)
with InterProcessLock(fpath + self.LOCK_SUFFIX, logger=logger):
try:
with open(fpath, 'r') as f:
dct = json.load(f)
except IOError as e:
if e.errno == errno.ENOENT:
dct = {}
else:
raise
if field.array:
dct[field.name] = list(field.value)
else:
dct[field.name] = field.value
with open(fpath, 'w') as f:
json.dump(dct, f, indent=2) | Inserts or updates a field in the repository |
def ctrl_int_cmd(self, cmd):
cmd_url = 'ctrl-int/1/{}?[AUTH]&prompt-id=0'.format(cmd)
return self.daap.post(cmd_url) | Perform a "ctrl-int" command. |
def _check_all_metadata_found(metadata, items):
for name in metadata:
seen = False
for sample in items:
check_file = sample["files"][0] if sample.get("files") else sample["vrn_file"]
if isinstance(name, (tuple, list)):
if check_file.find(name[0]) > -1:
seen = True
elif check_file.find(name) > -1:
seen = True
elif "*" in name and fnmatch.fnmatch(check_file, "*/%s" % name):
seen = True
if not seen:
print("WARNING: sample not found %s" % str(name)) | Print warning if samples in CSV file are missing in folder |
def reset(self):
self.context = pyblish.api.Context()
self.plugins = pyblish.api.discover()
self.was_discovered.emit()
self.pair_generator = None
self.current_pair = (None, None)
self.current_error = None
self.processing = {
"nextOrder": None,
"ordersWithError": set()
}
self._load()
self._run(until=pyblish.api.CollectorOrder,
on_finished=self.was_reset.emit) | Discover plug-ins and run collection |
def make_module_to_builder_dict(datasets=None):
module_to_builder = collections.defaultdict(
lambda: collections.defaultdict(
lambda: collections.defaultdict(list)))
if datasets:
builders = [tfds.builder(name) for name in datasets]
else:
builders = [
tfds.builder(name)
for name in tfds.list_builders()
if name not in BUILDER_BLACKLIST
] + [tfds.builder("image_label_folder", dataset_name="image_label_folder")]
for builder in builders:
mod_name = builder.__class__.__module__
modules = mod_name.split(".")
if "testing" in modules:
continue
current_mod_ctr = module_to_builder
for mod in modules:
current_mod_ctr = current_mod_ctr[mod]
current_mod_ctr.append(builder)
module_to_builder = module_to_builder["tensorflow_datasets"]
return module_to_builder | Get all builders organized by module in nested dicts. |
def increment(self, gold_set, test_set):
"Add examples from sets."
self.gold += len(gold_set)
self.test += len(test_set)
self.correct += len(gold_set & test_set) | Add examples from sets. |
def engineering(value, precision=3, prefix=False, prefixes=SI):
display = decimal.Context(prec=precision)
value = decimal.Decimal(value).normalize(context=display)
string = value.to_eng_string()
if prefix:
prefixes = {e(exponent): prefix for exponent, prefix in prefixes.items()}
return replace(string, prefixes)
else:
return string | Convert a number to engineering notation. |
def negate_gate(wordlen, input='x', output='~x'):
neg = bitwise_negate(wordlen, input, "tmp")
inc = inc_gate(wordlen, "tmp", output)
return neg >> inc | Implements two's complement negation. |
def cause_repertoire(self, mechanism, purview):
return self.repertoire(Direction.CAUSE, mechanism, purview) | Return the cause repertoire. |
def _put_many(self, items):
for item in items:
if not isinstance(item, self._item_class):
raise RuntimeError('Items mismatch for %s and %s' % (self._item_class, type(item)))
self._put_one(item) | store items in sqlite database |
def check_drives(drivename, drivestatus):
return DISK_STATES[int(drivestatus)]["icingastatus"], "Drive '{}': {}".format(
drivename, DISK_STATES[int(drivestatus)]["result"]) | check the drive status |
def list_from_metadata(cls, url, metadata):
key = cls._get_key(url)
metadata = Metadata(**metadata)
ct = cls._get_create_time(key)
time_buckets = cls.get_time_buckets_from_metadata(metadata)
return [cls(url, metadata, t, ct, key.size) for t in time_buckets] | return a list of DatalakeRecords for the url and metadata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.