code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def post(self, url, data=None, **kwargs):
return requests.post(url, data=data, headers=self.add_headers(**kwargs)) | Encapsulte requests.post to use this class instance header |
def execute(self, conn, block_name, origin_site_name, transaction=False):
if not conn:
dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/Block/UpdateStatus. \
Expects db connection from upper layer.", self.logger.exception)
binds = {"block_name": block_name, "origin_site_name": origin_site_name, "mtime": dbsUtils().getTime(),
"myuser": dbsUtils().getCreateBy()}
self.dbi.processData(self.sql, binds, conn, transaction) | Update origin_site_name for a given block_name |
def maybe_encode_keys(self, keys):
ret = {}
for k, v in six.iteritems(keys):
if is_dynamo_value(v):
return keys
elif not is_null(v):
ret[k] = self.encode(v)
return ret | Same as encode_keys but a no-op if already in Dynamo format |
def addFormat(name, fn, opts):
fmtyielders[name] = fn
fmtopts[name] = opts | Add an additional ingest file format |
def _style(self, retval):
"Applies custom option tree to values return by the callback."
if self.id not in Store.custom_options():
return retval
spec = StoreOptions.tree_to_dict(Store.custom_options()[self.id])
return retval.opts(spec) | Applies custom option tree to values return by the callback. |
def parse_private_key(data, password):
if is_pem(data):
if b'ENCRYPTED' in data:
if password is None:
raise TypeError('No password provided for encrypted key.')
try:
return serialization.load_pem_private_key(
data, password, backend=default_backend())
except ValueError:
raise
except Exception:
pass
if is_pkcs12(data):
try:
p12 = crypto.load_pkcs12(data, password)
data = crypto.dump_privatekey(
crypto.FILETYPE_PEM, p12.get_privatekey())
return serialization.load_pem_private_key(
data, password=None, backend=default_backend())
except crypto.Error as e:
raise ValueError(e)
try:
return serialization.load_der_private_key(
data, password, backend=default_backend())
except Exception:
pass
raise ValueError('Could not parse private key.') | Identifies, decrypts and returns a cryptography private key object. |
def prepare_env(app, env, docname):
if not hasattr(env, 'needs_all_needs'):
env.needs_all_needs = {}
if not hasattr(env, 'needs_functions'):
env.needs_functions = {}
needs_functions = app.needs_functions
if needs_functions is None:
needs_functions = []
if not isinstance(needs_functions, list):
raise SphinxError('Config parameter needs_functions must be a list!')
for need_common_func in needs_common_functions:
register_func(env, need_common_func)
for needs_func in needs_functions:
register_func(env, needs_func)
app.config.needs_hide_options += ['hidden']
app.config.needs_extra_options['hidden'] = directives.unchanged
if not hasattr(env, 'needs_workflow'):
env.needs_workflow = {
'backlink_creation': False,
'dynamic_values_resolved': False
} | Prepares the sphinx environment to store sphinx-needs internal data. |
def install_cache(expire_after=12 * 3600, cache_post=False):
allowable_methods = ['GET']
if cache_post:
allowable_methods.append('POST')
requests_cache.install_cache(
expire_after=expire_after,
allowable_methods=allowable_methods) | Patches the requests library with requests_cache. |
def list_commands(self, ctx):
self.connect(ctx)
if not hasattr(ctx, "widget"):
return super(Engineer, self).list_commands(ctx)
return ctx.widget.engineer_list_commands() + super(Engineer, self).list_commands(ctx) | list all commands exposed to engineer |
def _expand_subsystems(self, scope_infos):
def subsys_deps(subsystem_client_cls):
for dep in subsystem_client_cls.subsystem_dependencies_iter():
if dep.scope != GLOBAL_SCOPE:
yield self._scope_to_info[dep.options_scope]
for x in subsys_deps(dep.subsystem_cls):
yield x
for scope_info in scope_infos:
yield scope_info
if scope_info.optionable_cls is not None:
if issubclass(scope_info.optionable_cls, GlobalOptionsRegistrar):
for scope, info in self._scope_to_info.items():
if info.category == ScopeInfo.SUBSYSTEM and enclosing_scope(scope) == GLOBAL_SCOPE:
yield info
for subsys_dep in subsys_deps(info.optionable_cls):
yield subsys_dep
elif issubclass(scope_info.optionable_cls, SubsystemClientMixin):
for subsys_dep in subsys_deps(scope_info.optionable_cls):
yield subsys_dep | Add all subsystems tied to a scope, right after that scope. |
def dmlc_opts(opts):
args = ['--num-workers', str(opts.num_workers),
'--num-servers', str(opts.num_servers),
'--cluster', opts.launcher,
'--host-file', opts.hostfile,
'--sync-dst-dir', opts.sync_dst_dir]
dopts = vars(opts)
for key in ['env_server', 'env_worker', 'env']:
for v in dopts[key]:
args.append('--' + key.replace("_","-"))
args.append(v)
args += opts.command
try:
from dmlc_tracker import opts
except ImportError:
print("Can't load dmlc_tracker package. Perhaps you need to run")
print(" git submodule update --init --recursive")
raise
dmlc_opts = opts.get_opts(args)
return dmlc_opts | convert from mxnet's opts to dmlc's opts |
def _createSlink(self, slinks):
for slink in slinks:
superLink = SuperLink(slinkNumber=slink['slinkNumber'],
numPipes=slink['numPipes'])
superLink.stormPipeNetworkFile = self
for node in slink['nodes']:
superNode = SuperNode(nodeNumber=node['nodeNumber'],
groundSurfaceElev=node['groundSurfaceElev'],
invertElev=node['invertElev'],
manholeSA=node['manholeSA'],
nodeInletCode=node['inletCode'],
cellI=node['cellI'],
cellJ=node['cellJ'],
weirSideLength=node['weirSideLength'],
orificeDiameter=node['orificeDiameter'])
superNode.superLink = superLink
for p in slink['pipes']:
pipe = Pipe(pipeNumber=p['pipeNumber'],
xSecType=p['xSecType'],
diameterOrHeight=p['diameterOrHeight'],
width=p['width'],
slope=p['slope'],
roughness=p['roughness'],
length=p['length'],
conductance=p['conductance'],
drainSpacing=p['drainSpacing'])
pipe.superLink = superLink | Create GSSHAPY SuperLink, Pipe, and SuperNode Objects Method |
def record_diff(old, new):
return '\n'.join(difflib.ndiff(
['%s: %s' % (k, v) for op in old for k, v in op.items()],
['%s: %s' % (k, v) for op in new for k, v in op.items()],
)) | Generate a human-readable diff of two performance records. |
def prepend(self, _, child, name=None):
self._insert(child, prepend=True, name=name)
return self | Adds childs to this tag, starting from the first position. |
def report(zap_helper, output, output_format):
if output_format == 'html':
zap_helper.html_report(output)
elif output_format == 'md':
zap_helper.md_report(output)
else:
zap_helper.xml_report(output)
console.info('Report saved to "{0}"'.format(output)) | Generate XML, MD or HTML report. |
def make_tmp_dir(suffix="", prefix="tmp", dir=None):
if dir is None:
return tempfile.mkdtemp(suffix, prefix, dir)
else:
while True:
rand_term = random.randint(1, 9999)
tmp_dir = os.path.join(dir, "%s%d%s" % (prefix, rand_term, suffix))
if tf.gfile.Exists(tmp_dir):
continue
tf.gfile.MakeDirs(tmp_dir)
break
return tmp_dir | Make a temporary directory. |
def instance_of(klass, arg):
if not isinstance(arg, klass):
raise com.IbisTypeError(
'Given argument with type {} is not an instance of {}'.format(
type(arg), klass
)
)
return arg | Require that a value has a particular Python type. |
def _get_vnet(self, adapter_number):
vnet = "ethernet{}.vnet".format(adapter_number)
if vnet not in self._vmx_pairs:
raise VMwareError("vnet {} not in VMX file".format(vnet))
return vnet | Return the vnet will use in ubridge |
def to_dict(self):
data = {}
if self.created_at:
data['created_at'] = self.created_at.strftime(
'%Y-%m-%dT%H:%M:%S%z')
if self.image_id:
data['image_id'] = self.image_id
if self.permalink_url:
data['permalink_url'] = self.permalink_url
if self.thumb_url:
data['thumb_url'] = self.thumb_url
if self.type:
data['type'] = self.type
if self.url:
data['url'] = self.url
return data | Return a dict representation of this instance |
def load_trie(filename):
trie = marisa_trie.BytesTrie()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
trie.load(filename)
return trie | Load a BytesTrie from the marisa_trie on-disk format. |
def read_projected_dos( self ):
pdos_list = []
for i in range( self.number_of_atoms ):
df = self.read_atomic_dos_as_df( i+1 )
pdos_list.append( df )
self.pdos = np.vstack( [ np.array( df ) for df in pdos_list ] ).reshape(
self.number_of_atoms, self.number_of_data_points, self.number_of_channels, self.ispin ) | Read the projected density of states data into |
def rescorer(self, rescorer):
clone = self._clone()
clone._rescorer=rescorer
return clone | Returns a new QuerySet with a set rescorer. |
def clear(*signals):
signals = signals if signals else receivers.keys()
for signal in signals:
receivers[signal].clear() | Clears all callbacks for a particular signal or signals |
def c(self):
if self._client is None:
self._parse_settings()
self._client = Rumetr(**self.settings)
return self._client | Caching client for not repeapting checks |
def next(self):
if self.iter_next():
self.data, self.label = self._read()
return {self.data_name : self.data[0][1],
self.label_name : self.label[0][1]}
else:
raise StopIteration | return one dict which contains "data" and "label" |
def merge_asset(self, other):
for asset in other.asset:
asset_name = asset.get("name")
asset_type = asset.tag
pattern = "./{}[@name='{}']".format(asset_type, asset_name)
if self.asset.find(pattern) is None:
self.asset.append(asset) | Useful for merging other files in a custom logic. |
def max_lv_count(self):
self.open()
count = lvm_vg_get_max_lv(self.handle)
self.close()
return count | Returns the maximum allowed logical volume count. |
def runner(parallel, config):
def run_parallel(fn_name, items):
items = [x for x in items if x is not None]
if len(items) == 0:
return []
items = diagnostics.track_parallel(items, fn_name)
fn, fn_name = (fn_name, fn_name.__name__) if callable(fn_name) else (get_fn(fn_name, parallel), fn_name)
logger.info("multiprocessing: %s" % fn_name)
if "wrapper" in parallel:
wrap_parallel = {k: v for k, v in parallel.items() if k in set(["fresources", "checkpointed"])}
items = [[fn_name] + parallel.get("wrapper_args", []) + [wrap_parallel] + list(x) for x in items]
return run_multicore(fn, items, config, parallel=parallel)
return run_parallel | Run functions, provided by string name, on multiple cores on the current machine. |
def run(self):
with self.output().open('w') as outfile:
print("data 0 200 10 50 60", file=outfile)
print("data 1 190 9 52 60", file=outfile)
print("data 2 200 10 52 60", file=outfile)
print("data 3 195 1 52 60", file=outfile) | The execution of this task will write 4 lines of data on this task's target output. |
def FilterFnTable(fn_table, symbol):
new_table = list()
for entry in fn_table:
if entry[0] != symbol:
new_table.append(entry)
return new_table | Remove a specific symbol from a fn_table. |
def last(self):
self.__file.seek(0, 2)
data = self.get(self.length - 1)
return data | Get the last object in file. |
def click(self, x, y):
return self.server.jsonrpc.click(x, y) | click at arbitrary coordinates. |
def mnest_basename(self):
if not hasattr(self, '_mnest_basename'):
s = self.labelstring
if s=='0_0':
s = 'single'
elif s=='0_0-0_1':
s = 'binary'
elif s=='0_0-0_1-0_2':
s = 'triple'
s = '{}-{}'.format(self.ic.name, s)
self._mnest_basename = os.path.join('chains', s+'-')
if os.path.isabs(self._mnest_basename):
return self._mnest_basename
else:
return os.path.join(self.directory, self._mnest_basename) | Full path to basename |
def _delete(self, **kwargs):
requests_params = self._handle_requests_params(kwargs)
delete_uri = self._meta_data['uri']
session = self._meta_data['bigip']._meta_data['icr_session']
response = session.delete(delete_uri, **requests_params)
if response.status_code == 200 or 201:
self.__dict__ = {'deleted': True} | Wrapped with delete, override that in a subclass to customize |
def find_all_models(models):
for model in models:
yield model
for parent in model._meta.parents.keys():
for parent_model in find_all_models((parent,)):
yield parent_model | Yield all models and their parents. |
def bind_objects(self, *objects):
self.control.bind_keys(objects)
self.objects += objects | Bind one or more objects |
def insertReadGroupSet(self, readGroupSet):
programsJson = json.dumps(
[protocol.toJsonDict(program) for program in
readGroupSet.getPrograms()])
statsJson = json.dumps(protocol.toJsonDict(readGroupSet.getStats()))
try:
models.Readgroupset.create(
id=readGroupSet.getId(),
datasetid=readGroupSet.getParentContainer().getId(),
referencesetid=readGroupSet.getReferenceSet().getId(),
name=readGroupSet.getLocalId(),
programs=programsJson,
stats=statsJson,
dataurl=readGroupSet.getDataUrl(),
indexfile=readGroupSet.getIndexFile(),
attributes=json.dumps(readGroupSet.getAttributes()))
for readGroup in readGroupSet.getReadGroups():
self.insertReadGroup(readGroup)
except Exception as e:
raise exceptions.RepoManagerException(e) | Inserts a the specified readGroupSet into this repository. |
def to_dict(self):
return {'field': self.output_tag,
'expression': self.search_expression,
'coll_id': self.id_collection,
'collection': self.collection.name
if self.collection else None} | Return a dict representation of KnwKBDDEF. |
def values(self, column_name, exclude_type=STRUCT):
column_name = unnest_path(column_name)
columns = self.columns
output = []
for path in self.query_path:
full_path = untype_path(concat_field(path, column_name))
for c in columns:
if c.jx_type in exclude_type:
continue
if untype_path(c.name) == full_path:
output.append(c)
if output:
return output
return [] | RETURN ALL COLUMNS THAT column_name REFERS TO |
def _updateable(self, obj):
if obj.latest_version is None or obj.is_editable:
return None
else:
return obj.latest_version != obj.current_version | Return True if there are available updates. |
def stop_func_accept_retry_state(stop_func):
if not six.callable(stop_func):
return stop_func
if func_takes_retry_state(stop_func):
return stop_func
@_utils.wraps(stop_func)
def wrapped_stop_func(retry_state):
warn_about_non_retry_state_deprecation(
'stop', stop_func, stacklevel=4)
return stop_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_stop_func | Wrap "stop" function to accept "retry_state" parameter. |
def find_actual_cause(self, mechanism, purviews=False):
return self.find_causal_link(Direction.CAUSE, mechanism, purviews) | Return the actual cause of a mechanism. |
def _ps_extract_pid(self, line):
this_pid = self.regex['pid'].sub(r'\g<1>', line)
this_parent = self.regex['parent'].sub(r'\g<1>', line)
return this_pid, this_parent | Extract PID and parent PID from an output line from the PS command |
def process_prologue(self):
for key in ['TCurr', 'TCHED', 'TCTRL', 'TLHED', 'TLTRL', 'TIPFS',
'TINFS', 'TISPC', 'TIECL', 'TIBBC', 'TISTR', 'TLRAN',
'TIIRT', 'TIVIT', 'TCLMT', 'TIONA']:
try:
self.prologue[key] = make_sgs_time(self.prologue[key])
except ValueError:
self.prologue.pop(key, None)
logger.debug("Invalid data for %s", key)
for key in ['SubSatLatitude', "SubSatLongitude", "ReferenceLongitude",
"ReferenceDistance", "ReferenceLatitude"]:
self.prologue[key] = make_gvar_float(self.prologue[key]) | Reprocess prologue to correct types. |
def publish(self, tag, message):
payload = self.build_payload(tag, message)
self.socket.send(payload) | Publish a message down the socket |
def configure_node(self, node):
node.slaveinput['cov_master_host'] = socket.gethostname()
node.slaveinput['cov_master_topdir'] = self.topdir
node.slaveinput['cov_master_rsync_roots'] = [str(root) for root in node.nodemanager.roots] | Slaves need to know if they are collocated and what files have moved. |
def schema_file(self):
path = os.getcwd() + '/' + self.lazy_folder
return path + self.schema_filename | Gets the full path to the file in which to load configuration schema. |
def read_boolean_option(self, section, option):
if self.has_option(section, option):
self.config[option] = self.getboolean(section, option) | Read a boolean option. |
def search(self,
q=None,
per_page=None,
page=None,
bbox=None,
sort_by="relavance",
sort_order="asc"):
url = self._url + "/datasets.json"
param_dict = {
"sort_by" : sort_by,
"f" : "json"
}
if q is not None:
param_dict['q'] = q
if per_page is not None:
param_dict['per_page'] = per_page
if page is not None:
param_dict['page'] = page
if bbox is not None:
param_dict['bbox'] = bbox
if sort_by is not None:
param_dict['sort_by'] = sort_by
if sort_order is not None:
param_dict['sort_order'] = sort_order
ds_data = self._get(url=url,
param_dict=param_dict,
securityHandler=self._securityHandler,
additional_headers=[],
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
return ds_data | searches the opendata site and returns the dataset results |
def _dict_to_name_value(data):
if isinstance(data, dict):
sorted_data = sorted(data.items(), key=lambda s: s[0])
result = []
for name, value in sorted_data:
if isinstance(value, dict):
result.append({name: _dict_to_name_value(value)})
else:
result.append({name: value})
else:
result = data
return result | Convert a dictionary to a list of dictionaries to facilitate ordering |
def cmd_rally_alt(self, args):
if (len(args) < 2):
print("Usage: rally alt RALLYNUM newAlt <newBreakAlt>")
return
if not self.have_list:
print("Please list rally points first")
return
idx = int(args[0])
if idx <= 0 or idx > self.rallyloader.rally_count():
print("Invalid rally point number %u" % idx)
return
new_alt = int(args[1])
new_break_alt = None
if (len(args) > 2):
new_break_alt = int(args[2])
self.rallyloader.set_alt(idx, new_alt, new_break_alt)
self.send_rally_point(idx-1)
self.fetch_rally_point(idx-1)
self.rallyloader.reindex() | handle rally alt change |
def makeService(self, options):
return NodeService(
port=options['port'],
host=options['host'],
broker_host=options['broker_host'],
broker_port=options['broker_port'],
debug=options['debug']
) | Construct a Node Server |
def update_cnt(uid, post_data):
entry = TabPostHist.update(
user_name=post_data['user_name'],
cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md']),
time_update=tools.timestamp(),
).where(TabPostHist.uid == uid)
entry.execute() | Update the content by ID. |
def _group_by(data, criteria):
if isinstance(criteria, str):
criteria_str = criteria
def criteria(x):
return x[criteria_str]
res = defaultdict(list)
for element in data:
key = criteria(element)
res[key].append(element)
return res | Group objects in data using a function or a key |
def toggleglobalsitepackages_cmd(argv):
quiet = argv == ['-q']
site = sitepackages_dir()
ngsp_file = site.parent / 'no-global-site-packages.txt'
if ngsp_file.exists():
ngsp_file.unlink()
if not quiet:
print('Enabled global site-packages')
else:
with ngsp_file.open('w'):
if not quiet:
print('Disabled global site-packages') | Toggle the current virtualenv between having and not having access to the global site-packages. |
def _update_Pxy(self):
scipy.copyto(self.Pxy_no_omega, self.Phi_x.transpose(),
where=CODON_SINGLEMUT)
self.Pxy_no_omega[0][CODON_TRANSITION] *= self.kappa
self.Pxy = self.Pxy_no_omega.copy()
self.Pxy[0][CODON_NONSYN] *= self.omega
_fill_diagonals(self.Pxy, self._diag_indices) | Update `Pxy` using current `omega`, `kappa`, and `Phi_x`. |
def mpirun(self):
cmd = self.attributes['mpirun']
if cmd and cmd[0] != 'mpirun':
cmd = ['mpirun']
return [str(e) for e in cmd] | Additional options passed as a list to the ``mpirun`` command |
def _linearly_scale(inputmatrix, inputmin, inputmax, outputmin, outputmax):
inputrange = inputmax - inputmin
outputrange = outputmax - outputmin
delta = outputrange/inputrange
inputmin = inputmin + 1.0 / delta / 2.0
outputmax = outputmax - 1
outputmatrix = (inputmatrix - inputmin) * delta + outputmin
err = IndexError('Input, %g, is out of range (%g, %g).' %
(inputmatrix, inputmax - inputrange, inputmax))
if outputmatrix > outputmax:
if np.around(outputmatrix - outputmax, 1) <= 0.5:
outputmatrix = outputmax
else:
raise err
elif outputmatrix < outputmin:
if np.around(outputmin - outputmatrix, 1) <= 0.5:
outputmatrix = outputmin
else:
raise err
return outputmatrix | linearly scale input to output, used by Linke turbidity lookup |
def prepare(c):
actions, state = status(c)
if not confirm("Take the above actions?"):
sys.exit("Aborting.")
if actions.changelog is Changelog.NEEDS_RELEASE:
cmd = "$EDITOR {0.packaging.changelog_file}".format(c)
c.run(cmd, pty=True, hide=False)
if actions.version == VersionFile.NEEDS_BUMP:
version_file = os.path.join(
_find_package(c),
c.packaging.get("version_module", "_version") + ".py",
)
cmd = "$EDITOR {0}".format(version_file)
c.run(cmd, pty=True, hide=False)
if actions.tag == Tag.NEEDS_CUTTING:
cmd = 'git status --porcelain | egrep -v "^\\?"'
if c.run(cmd, hide=True, warn=True).ok:
c.run(
'git commit -am "Cut {0}"'.format(state.expected_version),
hide=False,
)
c.run("git tag {0}".format(state.expected_version), hide=False) | Edit changelog & version, git commit, and git tag, to set up for release. |
def namespace_to_regex(namespace):
db_name, coll_name = namespace.split(".", 1)
db_regex = re.escape(db_name).replace(r"\*", "([^.]*)")
coll_regex = re.escape(coll_name).replace(r"\*", "(.*)")
return re.compile(r"\A" + db_regex + r"\." + coll_regex + r"\Z") | Create a RegexObject from a wildcard namespace. |
def value(self):
pos = self.file.tell()
self.file.seek(0)
val = self.file.read()
self.file.seek(pos)
return val.decode(self.charset) | Data decoded with the specified charset |
def sanitize_path(path):
storage_option = infer_storage_options(path)
protocol = storage_option['protocol']
if protocol in ('http', 'https'):
path = os.path.normpath(path.replace("{}://".format(protocol), ''))
elif protocol == 'file':
path = os.path.normpath(path)
path = path.replace(':', '')
return make_path_posix(path) | Utility for cleaning up paths. |
def utils(opts, whitelist=None, context=None, proxy=proxy):
return LazyLoader(
_module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'),
opts,
tag='utils',
whitelist=whitelist,
pack={'__context__': context, '__proxy__': proxy or {}},
) | Returns the utility modules |
def request(self, method, endpoint, payload=None, timeout=5):
url = self.api_url + endpoint
data = None
headers = {}
if payload is not None:
data = json.dumps(payload)
headers['Content-Type'] = 'application/json'
try:
if self.auth_token is not None:
headers[API_AUTH_HEADER] = self.auth_token
response = self.session.request(method, url, data=data,
headers=headers,
timeout=timeout)
if response.status_code != 401:
return response
_LOGGER.debug("Renewing auth token")
if not self.login(timeout=timeout):
return None
headers[API_AUTH_HEADER] = self.auth_token
return self.session.request(method, url, data=data,
headers=headers,
timeout=timeout)
except requests.exceptions.ConnectionError:
_LOGGER.warning("Unable to connect to %s", url)
except requests.exceptions.Timeout:
_LOGGER.warning("No response from %s", url)
return None | Send request to API. |
def _format_subtree(self, subtree):
subtree['children'] = list(subtree['children'].values())
for child in subtree['children']:
self._format_subtree(child)
return subtree | Recursively format all subtrees. |
def list_message_files (package, suffix=".mo"):
for fname in glob.glob("po/*" + suffix):
localename = os.path.splitext(os.path.basename(fname))[0]
domainname = "%s.mo" % package.lower()
yield (fname, os.path.join(
"share", "locale", localename, "LC_MESSAGES", domainname)) | Return list of all found message files and their installation paths. |
def _get_indent(self, node):
lineno = node.lineno
if lineno > len(self._lines):
return -1
wsindent = self._wsregexp.match(self._lines[lineno - 1])
return len(wsindent.group(1)) | Get node indentation level. |
def shape(self):
"Tuple indicating the number of rows and columns in the Layout."
num = len(self)
if num <= self._max_cols:
return (1, num)
nrows = num // self._max_cols
last_row_cols = num % self._max_cols
return nrows+(1 if last_row_cols else 0), min(num, self._max_cols) | Tuple indicating the number of rows and columns in the Layout. |
def echo(msg, *args, **kwargs):
file = kwargs.pop('file', None)
nl = kwargs.pop('nl', True)
err = kwargs.pop('err', False)
color = kwargs.pop('color', None)
msg = safe_unicode(msg).format(*args, **kwargs)
click.echo(msg, file=file, nl=nl, err=err, color=color) | Wraps click.echo, handles formatting and check encoding |
def modify(self, **patch):
if 'monitor' in patch:
value = self._format_monitor_parameter(patch['monitor'])
patch['monitor'] = value
return super(Pool, self)._modify(**patch) | Custom modify method to implement monitor parameter formatting. |
def create_subword_function(subword_function_name, **kwargs):
create_ = registry.get_create_func(SubwordFunction, 'token embedding')
return create_(subword_function_name, **kwargs) | Creates an instance of a subword function. |
def sign_envelope(envelope, key_file):
doc = etree.fromstring(envelope)
body = get_body(doc)
queue = SignQueue()
queue.push_and_mark(body)
security_node = ensure_security_header(doc, queue)
security_token_node = create_binary_security_token(key_file)
signature_node = Signature(
xmlsec.TransformExclC14N, xmlsec.TransformRsaSha1)
security_node.append(security_token_node)
security_node.append(signature_node)
queue.insert_references(signature_node)
key_info = create_key_info_node(security_token_node)
signature_node.append(key_info)
xmlsec.addIDs(doc, ['Id'])
dsigCtx = xmlsec.DSigCtx()
dsigCtx.signKey = xmlsec.Key.load(key_file, xmlsec.KeyDataFormatPem, None)
dsigCtx.sign(signature_node)
return etree.tostring(doc) | Sign the given soap request with the given key |
def warning (self, msg, pos=None):
self.log(msg, 'warning: ' + self.location(pos)) | Logs a warning message pertaining to the given SeqAtom. |
def apply_obfuscation(source):
global keyword_args
global imported_modules
tokens = token_utils.listified_tokenizer(source)
keyword_args = analyze.enumerate_keyword_args(tokens)
imported_modules = analyze.enumerate_imports(tokens)
variables = find_obfuscatables(tokens, obfuscatable_variable)
classes = find_obfuscatables(tokens, obfuscatable_class)
functions = find_obfuscatables(tokens, obfuscatable_function)
for variable in variables:
replace_obfuscatables(
tokens, obfuscate_variable, variable, name_generator)
for function in functions:
replace_obfuscatables(
tokens, obfuscate_function, function, name_generator)
for _class in classes:
replace_obfuscatables(tokens, obfuscate_class, _class, name_generator)
return token_utils.untokenize(tokens) | Returns 'source' all obfuscated. |
def SortBy(*qs):
sort = []
for q in qs:
if q._path.endswith('.desc'):
sort.append((q._path[:-5], DESCENDING))
else:
sort.append((q._path, ASCENDING))
return sort | Convert a list of Q objects into list of sort instructions |
def create(self):
params = {}
return self.send(
url=self._base_url + 'create',
method='POST',
json=params
) | Create a new reminder. |
def iterable(item):
if isinstance(item, collections.Iterable) and not isinstance(item, basestring):
return item
else:
return [item] | generate iterable from item, but leaves out strings |
def _make_load_template(self):
loader = self._make_loader()
def load_template(template_name):
return loader.load_name(template_name)
return load_template | Return a function that loads a template by name. |
def run(self):
for cls in self.get_test_classes():
self.logger.info('Running {cls.__name__} test...'.format(cls=cls))
test = cls(runner=self)
if test._run():
self.logger.passed('Test {cls.__name__} succeeded!'.format(cls=cls))
else:
self.logger.failed('Test {cls.__name__} failed!'.format(cls=cls))
self.has_passed = False
if self.has_passed:
self.logger.passed('Summary: All tests passed!')
else:
self.logger.failed('Summary: One or more tests failed!')
return self.has_passed | Runs all enabled tests. |
def bin_hex_type(arg):
if re.match(r'^[a-f0-9]{2}(:[a-f0-9]{2})+$', arg, re.I):
arg = arg.replace(':', '')
elif re.match(r'^(\\x[a-f0-9]{2})+$', arg, re.I):
arg = arg.replace('\\x', '')
try:
arg = binascii.a2b_hex(arg)
except (binascii.Error, TypeError):
raise argparse.ArgumentTypeError("{0} is invalid hex data".format(repr(arg)))
return arg | An argparse type representing binary data encoded in hex. |
def _cache_get_last_in_slice(url_dict, start_int, total_int, authn_subj_list):
key_str = _gen_cache_key_for_slice(url_dict, start_int, total_int, authn_subj_list)
try:
last_ts_tup = django.core.cache.cache.get(key_str)
except KeyError:
last_ts_tup = None
logging.debug('Cache get. key="{}" -> last_ts_tup={}'.format(key_str, last_ts_tup))
return last_ts_tup | Return None if cache entry does not exist. |
def _classname(self):
if self.__class__.__module__ in (None,):
return self.__class__.__name__
else:
return "%s.%s" % (self.__class__.__module__, self.__class__.__name__) | Return the fully qualified class name. |
def _parse_challenge(cls, response):
links = _parse_header_links(response)
try:
authzr_uri = links['up']['url']
except KeyError:
raise errors.ClientError('"up" link missing')
return (
response.json()
.addCallback(
lambda body: messages.ChallengeResource(
authzr_uri=authzr_uri,
body=messages.ChallengeBody.from_json(body)))
) | Parse a challenge resource. |
def blogroll(request, btype):
'View that handles the generation of blogrolls.'
response, site, cachekey = initview(request)
if response: return response[0]
template = loader.get_template('feedjack/{0}.xml'.format(btype))
ctx = dict()
fjlib.get_extra_context(site, ctx)
ctx = Context(ctx)
response = HttpResponse(
template.render(ctx), content_type='text/xml; charset=utf-8' )
patch_vary_headers(response, ['Host'])
fjcache.cache_set(site, cachekey, (response, ctx_get(ctx, 'last_modified')))
return response | View that handles the generation of blogrolls. |
def init0(self, dae):
self.p0 = matrix(self.p, (self.n, 1), 'd')
self.q0 = matrix(self.q, (self.n, 1), 'd') | Set initial p and q for power flow |
def print_dependencies(_run):
print('Dependencies:')
for dep in _run.experiment_info['dependencies']:
pack, _, version = dep.partition('==')
print(' {:<20} == {}'.format(pack, version))
print('\nSources:')
for source, digest in _run.experiment_info['sources']:
print(' {:<43} {}'.format(source, digest))
if _run.experiment_info['repositories']:
repos = _run.experiment_info['repositories']
print('\nVersion Control:')
for repo in repos:
mod = COLOR_DIRTY + 'M' if repo['dirty'] else ' '
print('{} {:<43} {}'.format(mod, repo['url'], repo['commit']) +
ENDC)
print('') | Print the detected source-files and dependencies. |
def create_slug(self):
name = self.slug_source
counter = 0
while True:
if counter == 0:
slug = slugify(name)
else:
slug = slugify('{0} {1}'.format(name, str(counter)))
try:
self.__class__.objects.exclude(pk=self.pk).get(slug=slug)
counter += 1
except ObjectDoesNotExist:
break
return slug | Creates slug, checks if slug is unique, and loop if not |
def create_entry_file(self, filename, script_map, enapps):
if len(script_map) == 0:
return
template = MakoTemplate(
)
content = template.render(
enapps=enapps,
script_map=script_map,
filename=filename,
).strip()
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
file_exists = os.path.exists(filename)
if file_exists and self.running_inline:
with open(filename, 'r') as fin:
if content == fin.read():
return False
if file_exists and not self.options.get('overwrite'):
raise CommandError('Refusing to destroy existing file: {} (use --overwrite option or remove the file)'.format(filename))
self.message('Creating {}'.format(os.path.relpath(filename, settings.BASE_DIR)), level=3)
with open(filename, 'w') as fout:
fout.write(content)
return True | Creates an entry file for the given script map |
def reply_ok(self):
return (self.mtype == self.REPLY and self.arguments and
self.arguments[0] == self.OK) | Return True if this is a reply and its first argument is 'ok'. |
def _update_offset_value(self, f, offset, size, value):
f.seek(offset, 0)
if (size == 8):
f.write(struct.pack('>q', value))
else:
f.write(struct.pack('>i', value)) | Writes "value" into location "offset" in file "f". |
def unblock_signals(self):
self.aggregation_layer_combo.blockSignals(False)
self.exposure_layer_combo.blockSignals(False)
self.hazard_layer_combo.blockSignals(False) | Let the combos listen for event changes again. |
def _populate_struct_type_attributes(self, env, data_type):
parent_type = None
extends = data_type._ast_node.extends
if extends:
parent_type = self._resolve_type(env, extends, True)
if isinstance(parent_type, Alias):
raise InvalidSpec(
'A struct cannot extend an alias. '
'Use the canonical name instead.',
data_type._ast_node.lineno, data_type._ast_node.path)
if isinstance(parent_type, Nullable):
raise InvalidSpec(
'A struct cannot extend a nullable type.',
data_type._ast_node.lineno, data_type._ast_node.path)
if not isinstance(parent_type, Struct):
raise InvalidSpec(
'A struct can only extend another struct: '
'%s is not a struct.' % quote(parent_type.name),
data_type._ast_node.lineno, data_type._ast_node.path)
api_type_fields = []
for stone_field in data_type._ast_node.fields:
api_type_field = self._create_struct_field(env, stone_field)
api_type_fields.append(api_type_field)
data_type.set_attributes(
data_type._ast_node.doc, api_type_fields, parent_type) | Converts a forward reference of a struct into a complete definition. |
def _normalize_django_header_name(header):
new_header = header.rpartition('HTTP_')[2]
new_header = '-'.join(
x.capitalize() for x in new_header.split('_'))
return new_header | Unmunge header names modified by Django. |
def kill(self, job_id):
check_jobid(job_id)
queue = self._get_queue()
if queue is None:
raise QueueDoesntExist
ret, output = self._call('%s %s' % (
shell_escape(queue / 'commands/kill'),
job_id),
False)
if ret == 3:
raise JobNotFound
elif ret != 0:
raise RemoteCommandFailure(command='commands/kill',
ret=ret) | Kills a job on the server. |
def properties(self) -> dict:
if isinstance(self._last_node, dict):
return self._last_node.keys()
else:
return {} | Returns the properties of the current node in the iteration. |
def updateQTableFromTerminatingState( self, reward ):
old_q = self.q_table[self.prev_s][self.prev_a]
new_q = old_q
self.q_table[self.prev_s][self.prev_a] = new_q | Change q_table to reflect what we have learnt, after reaching a terminal state. |
def command_msg(housecode, command):
house_byte = 0
if isinstance(housecode, str):
house_byte = insteonplm.utils.housecode_to_byte(housecode) << 4
elif isinstance(housecode, int) and housecode < 16:
house_byte = housecode << 4
else:
house_byte = housecode
return X10Received(house_byte + command, 0x80) | Create an X10 message to send the house code and a command code. |
async def run_executor():
parser = argparse.ArgumentParser(description="Run the specified executor.")
parser.add_argument('module', help="The module from which to instantiate the concrete executor.")
args = parser.parse_args()
module_name = '{}.run'.format(args.module)
class_name = 'FlowExecutor'
module = import_module(module_name, __package__)
executor = getattr(module, class_name)()
with open(ExecutorFiles.PROCESS_SCRIPT, 'rt') as script_file:
await executor.run(DATA['id'], script_file.read()) | Start the actual execution; instantiate the executor and run. |
def execute(self, requests, resp_generator, *args, **kwargs):
return [resp_generator(request) for request in requests] | Calls the resp_generator for all the requests in sequential order. |
def dealloc(subseqs):
print(' . dealloc')
lines = Lines()
lines.add(1, 'cpdef inline dealloc(self):')
for seq in subseqs:
lines.add(2, 'PyMem_Free(self.%s)' % seq.name)
return lines | Deallocate memory for 1-dimensional link sequences. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.