Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
360,000 | def devices():
*
out = __salt__[]("blkid -o export")
salt.utils.fsutils._verify_run(out)
return salt.utils.fsutils._blkid_output(out[], fs_type=) | Get known BTRFS formatted devices on the system.
CLI Example:
.. code-block:: bash
salt '*' btrfs.devices |
360,001 | def handle_read(self):
with self._lock:
logger.debug("handle_read()")
if self._socket is None:
return
while True:
try:
sock, address = self._socket.accept()
except socket.error, err:
... | Accept any incoming connections. |
360,002 | def push(self):
tx = Tx(self.tx_project_slug)
if self.options.resources:
articles = [
self.desk.articles().by_id(r.strip())
for r in self.options.resources.split()
]
else:
articles = self.desk.articles()
for ... | Push tutorials to Transifex. |
360,003 | def load_module_stages(self, mod):
if isinstance(mod, basestring):
mod = __import__(mod, globals=globals(), locals=locals(),
fromlist=[], level=0)
if not hasattr(mod, ):
raise ImportError(mod)
self.update(mod.Stages) | Add external stages from the Python module `mod`.
If `mod` is a string, then it will be interpreted as the name
of a module; otherwise it is an actual module object. The
module should exist somewhere in :data:`sys.path`. The module
must contain a `Stages` dictionary, which is a map fr... |
360,004 | def handle_nested_relation(self, line: str, position: int, tokens: ParseResults):
if not self.allow_nested:
raise NestedRelationWarning(self.get_line_number(), line, position)
self._handle_relation_harness(line, position, {
SUBJECT: tokens[SUBJECT],
RELATION... | Handle nested statements.
If :code:`allow_nested` is False, raises a ``NestedRelationWarning``.
:raises: NestedRelationWarning |
360,005 | def farray(self):
bandwidths = 2 * pi ** (1/2.) * self.frequencies / self.q
return self.frequencies - bandwidths / 2. | Array of frequencies for the lower-edge of each frequency bin
:type: `numpy.ndarray` |
360,006 | def parse_planar_fault_geometry(node):
assert "planarSurface" in node.tag
geometry = {"strike": node.attrib["strike"],
"dip": node.attrib["dip"]}
upper_depth = numpy.inf
lower_depth = 0.0
tags = get_taglist(node)
corner_points = []
for locn in ["topLeft", "topRight", "bo... | Parses a planar fault geometry node returning both the attributes and
parameters in a dictionary |
360,007 | def replace_spaces(s, replacer):
def replace(m):
if m.start() == 0:
side =
elif m.end() == len(s):
side =
else:
side =
return replacer(len(m.group()), side)
return re.sub(r, replace, s) | >>> replace_spaces('ab', lambda n, l: '_' * n)
'ab'
>>> replace_spaces('a b', lambda n, l: '_' * n)
'a_b'
>>> replace_spaces(' ab', lambda n, l: '_' * n)
'_ab'
>>> replace_spaces(' a b ', lambda n, s: s * n)
'leftleftacenterbright'
>>> replace_spaces(' a b ', lambda n, _: '0 0' * n)
... |
360,008 | def log_used_nonce(self, username, iat, nonce):
key = self.create_nonce_key(username, iat)
used = cache.get(key, [])
used.append(nonce)
cache.set(key, set(used), token.TIMESTAMP_TOLERANCE * 2) | Log a nonce as being used, and therefore henceforth invalid.
:param username: Username as a string.
:param iat: Unix timestamp float or integer of when the nonce was used.
:param nonce: Nonce value. |
360,009 | def _read_channel(channel, stream, start, duration):
channel_type = lalframe.FrStreamGetTimeSeriesType(channel, stream)
read_func = _fr_type_map[channel_type][0]
d_type = _fr_type_map[channel_type][1]
data = read_func(stream, channel, start, duration, 0)
return TimeSeries(data.data.data, delta_... | Get channel using lalframe |
360,010 | def instance():
start_time = time.time()
print(_green("Started..."))
env.host_string = _create_ec2_instance()
print(_green("Waiting 30 seconds for server to boot..."))
time.sleep(30)
for item in tasks.configure_instance:
try:
print(_yellow(item[]))
... | Creates an EC2 instance from an Ubuntu AMI and configures it as a Django server
with nginx + gunicorn |
360,011 | def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth):
depth = random.randrange(min_depth, max_depth + 1)
expr = random_expr(depth, vlist, ops)
sample = str(expr)
target = format_sympy_expr(sympy.simplify(sample))
return sample, target | Randomly generate an algebra simplify dataset sample.
Given an input expression, produce the simplified expression.
Args:
vlist: Variable list. List of chars that can be used in the expression.
ops: List of ExprOp instances. The allowed operators for the expression.
min_depth: Expression trees will no... |
360,012 | def pipe(value, *functions, funcs=None):
if funcs:
functions = funcs
for function in functions:
value = function(value)
return value | pipe(value, f, g, h) == h(g(f(value))) |
360,013 | def localization_diff(localizable_file, translated_file, excluded_strings_file, output_translation_file):
old_translated_file_dictionary = generate_localization_key_to_entry_dictionary_from_file(translated_file)
if excluded_strings_file is not None and os.path.isfile(excluded_strings_file):
exclude... | Generates a strings file representing the strings that were yet to be translated.
Args:
localizable_file (str): The path to the localization strings file, meaning the file that represents the strings
that require translation.
translated_file (str): The path to the translated strings fil... |
360,014 | def process_keystroke(self, inp, idx, offset):
if inp.lower() in (u, u):
return (-1, -1)
self._process_keystroke_commands(inp)
idx, offset = self._process_keystroke_movement(inp, idx, offset)
return idx, offset | Process keystroke ``inp``, adjusting screen parameters.
:param inp: return value of Terminal.inkey().
:type inp: blessed.keyboard.Keystroke
:param idx: page index.
:type idx: int
:param offset: scrolling region offset of current page.
:type offset: int
:returns: ... |
360,015 | def IsNTFS(self):
tsk_fs_type = self.GetFsType()
return tsk_fs_type in [
pytsk3.TSK_FS_TYPE_NTFS, pytsk3.TSK_FS_TYPE_NTFS_DETECT] | Determines if the file system is NTFS.
Returns:
bool: True if the file system is NTFS. |
360,016 | def s_connect(self, server, port, r_server=None):
with self.lock:
if not r_server:
self.send( % (server, port), error_check=True)
else:
self.send( % (server, port, \
r_server), error_check=True) | Link a server.
Required arguments:
* server - Server to link with.
* port - Port to use.
Optional arguments:
* r_server=None - Link r_server with server. |
360,017 | def cleanup(self):
if not self.persist:
self.hide()
self.clear()
self._serial_interface.cleanup() | Attempt to switch the device off or put into low power mode (this
helps prolong the life of the device), clear the screen and close
resources associated with the underlying serial interface.
If :py:attr:`persist` is ``True``, the device will not be switched off.
This is a managed funct... |
360,018 | def timefun(fun):
@wraps(fun)
def measure_time(*args, **kwargs):
t1 = timer()
result = fun(*args, **kwargs)
t2 = timer()
print("@timefun:" + fun.__name__ + " took " + str(t2 - t1) + " seconds")
return result
return measure_time | Timing decorator
Timers require you to do some digging. Start wrapping a few of the higher level
functions and confirm where the bottleneck is, then drill down into that function,
repeating as you go. When you find the disproportionately slow bit of code, fix it,
and work your way back out confirming t... |
360,019 | def read(self, n):
if self._EOF:
return ""
while self._seg_index <= self._last_seg_index:
result = self._read_from_seg(n)
if result != "":
return result
else:
self._next_seg()
self._EOF = True
return "" | Read data from file segs.
Args:
n: max bytes to read. Must be positive.
Returns:
some bytes. May be smaller than n bytes. "" when no more data is left. |
360,020 | def report_usage_to_host(host_ip, vmid):
cpu_usage = 0.0
os_mem_usage = 0.0
task_mem_usage = 0.0
io_usage = 0.0
cpu_usage = get_cpu_usage()
os_mem_usage = get_os_mem_usage()
task_mem_usage = get_task_mem_usage()
io_usage = get_io_usage()
usage = str(vmid.strip())++str(cpu_usage)++str(os_mem_usage)++str(t... | cmd = '/bin/ssh -n -q -o StrictHostKeyChecking=no root@host_ip \"/bin/nohup /bin/python /var/lib/virtdc/vmonere/host/vmonere_listener.py '+usage+' &\"'
cmd = cmd.replace("host_ip",str(host_ip).strip()) |
360,021 | def read_dataset_schema(schema_path: str) -> Dict[str, List[TableColumn]]:
schema: Dict[str, List[TableColumn]] = defaultdict(list)
for i, line in enumerate(open(schema_path, "r")):
if i == 0:
header = [x.strip() for x in line.split(",")]
elif line[0] == "-":
continu... | Reads a schema from the text2sql data, returning a dictionary
mapping table names to their columns and respective types.
This handles columns in an arbitrary order and also allows
either ``{Table, Field}`` or ``{Table, Field} Name`` as headers,
because both appear in the data. It also uppercases table a... |
360,022 | def find_db_instance(self, name, running=True):
found = None
for i in self.provider.reddwarf_client.instances.list():
if i.name == name:
if not running:
found = i
if i.status == :
found = i
if found:
... | Searches for a db instance named :attr:`name`.
:param str name: The name of the target db instance
:param bool running: A flag to only look for instances that are
actually *running*.
:rtype: :class:`dict` |
360,023 | def save(file_name, content):
with open(file_name, "w", encoding="utf-8") as output_file:
output_file.write(content)
return output_file.name | Save content to a file |
360,024 | def _scan_smaller(self, seq, threshold=):
ll = self.ll
matches = []
endpoints = []
scores = []
w = self.width
oseq = seq
seq = seq.upper()
for offset in range(self.width-len(seq)+1):
maximum = 0
... | m._scan_smaller(seq, threshold='') -- Internal utility function for performing sequence scans
The sequence is smaller than the PSSM. Are there
good matches to regions of the PSSM? |
360,025 | def edit(self, name=None, description=None, start_date=None, due_date=None, assignees=None, status=None):
update_dict = {: self.id}
if name:
if isinstance(name, (str, text_type)):
update_dict.update({: name})
self.name = name
else:
... | Edit the details of an activity.
:param name: (optionally) edit the name of the activity
:type name: basestring or None
:param description: (optionally) edit the description of the activity
:type description: basestring or None
:param start_date: (optionally) edit the start date... |
360,026 | def _is_finished(self, as_of):
if self.is_one_off():
last_billing_cycle = self.get_billing_cycles()[self.total_billing_cycles - 1]
return last_billing_cycle.date_range.upper <= as_of
else:
return False | Have the specified number of billing cycles been completed?
If so, we should not be enacting this RecurringCost. |
360,027 | def nom_diam_pipe(self):
ID = pc.diam_circle(self.area_pipe_min)
return pipe.ND_SDR_available(ID, self.sdr) | The nominal diameter of the LFOM pipe |
360,028 | def mangle_name(name):
import re
try:
return re.sub(, , re.sub(, , name).lower()).rstrip()
except TypeError:
raise TypeError(
+ str(type(name))) | Mangles a column name to a standard form, remoing illegal
characters.
:param name:
:return: |
360,029 | def get_problem_name(base_name, was_reversed=False, was_copy=False):
if any(base_name.endswith(suffix) for suffix in ("_rev", "_copy")):
raise ValueError("`base_name` cannot end in or ")
name = base_name
if was_copy:
name = "%s_copy" % name
if was_reversed:
name = "%s_rev" % name
return name | Construct a problem name from base and reversed/copy options.
Inverse of `parse_problem_name`.
Args:
base_name: base problem name. Should not end in "_rev" or "_copy"
was_reversed: if the problem is to be reversed
was_copy: if the problem is to be copied
Returns:
string name consistent with use... |
360,030 | def categories(self, value):
if value is not None:
assert type(value) is dict, " attribute: type is not !".format("categories", value)
for key, element in value.iteritems():
assert type(key) is dict, " attribute: type is not !".format("categories", key)
... | Setter for **self.__categories** attribute.
:param value: Attribute value.
:type value: dict |
360,031 | def get_agents(self, addr=True, agent_cls=None, as_coro=False):
async def slave_task(mgr_addr, addr=True, agent_cls=None):
r_manager = await self.env.connect(mgr_addr, timeout=TIMEOUT)
return await r_manager.get_agents(addr=addr, agent_cls=agent_cls)
tasks = create_task... | Get agents from the slave environments.
:param bool addr:
If ``True``, returns only addresses of the agents, otherwise
returns a :class:`Proxy` object for each agent.
:param agent_cls:
If specified, returns only agents that are members of that
particular... |
360,032 | def pretty_print(input_word, anagrams, by_length=False):
scores = {}
if by_length:
noun = "tiles"
for word, score in anagrams:
try:
scores[len(word)].append("{0} ({1:d})".format(word, score))
except KeyError:
scores[len(word)] = ["{0}... | Prints the anagram results sorted by score to stdout.
Args:
input_word: the base word we searched on
anagrams: generator of (word, score) from anagrams_in_word
by_length: a boolean to declare printing by length instead of score |
360,033 | def html(self):
formatter = HtmlFormatter(
cssclass=self.DIV_CSS_CLASS,
linenos=True,
linenostart=self._start_line,
hl_lines=self._shift_lines(
self._violation_lines,
self._start_line
),
lineanchors=... | Return an HTML representation of the snippet. |
360,034 | def get_view_mode_id(self, view_mode):
thumbnail
view_mode_ids = VIEW_MODES.get(view_mode.lower())
if view_mode_ids:
return view_mode_ids.get(xbmc.getSkinDir())
return None | Attempts to return a view_mode_id for a given view_mode
taking into account the current skin. If not view_mode_id can
be found, None is returned. 'thumbnail' is currently the only
suppported view_mode. |
360,035 | def stop_webserver(server):
if server == :
with settings(warn_only=True):
if env.verbosity:
print env.host,"STOPPING apache2"
a = sudo("/etc/init.d/apache2 stop")
if env.verbosity:
print ,a
elif server == :
with settin... | Stop server |
360,036 | def addinputfile(project, filename, credentials=None):
printdebug( )
user, oauth_access_token = parsecredentials(credentials)
response = Project.create(project, user)
if response is not None:
return response
postdata = flask.request.values
if fil... | Add a new input file, this invokes the actual uploader |
360,037 | def _disable_access_key(self, force_disable_self=False):
client = self.client
if self.validate is True:
return
else:
try:
client.update_access_key(
UserName=self._search_user_for_key(),
AccessKeyId=self.acce... | This function first checks to see if the key is already disabled\
if not then it goes to disabling |
360,038 | def setup_file_list(self, filter_text, current_path):
short_paths = shorten_paths(self.paths, self.save_status)
paths = self.paths
icons = self.icons
results = []
trying_for_line_number = in filter_text
if trying_for_line_number:
filter_tex... | Setup list widget content for file list display. |
360,039 | def _CanProcessKeyWithPlugin(self, registry_key, plugin):
for registry_key_filter in plugin.FILTERS:
if getattr(registry_key_filter, , []):
continue
if registry_key_filter.Match(registry_key):
return True
return False | Determines if a plugin can process a Windows Registry key or its values.
Args:
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
plugin (WindowsRegistryPlugin): Windows Registry plugin.
Returns:
bool: True if the Registry key can be processed with the plugin. |
360,040 | def xml_import(self,
filepath="",
xml_content=None,
markings=None,
identifier_ns_uri=None,
**kwargs):
if in kwargs and kwargs[]:
if isinstance(kwargs[],basestring):
... | Import a STIX or CybOX xml from file <filepath> or a string passed as ``xml_content``
You can furhter provide:
- a list of InfoObjects as markings with which all generated Information Objects
will be associated (e.g., in order to provide provenance function)
- a default identif... |
360,041 | def flow_pipeline(diameters, lengths, k_minors, target_headloss,
nu=con.WATER_NU, pipe_rough=mats.PVC_PIPE_ROUGH):
n = diameters.size
flow = pc.flow_pipe(diameters[0], target_headloss, lengths[0], nu, pipe_rough, k_minors[0])
err = 1.0
while abs(err) >... | This function takes a single pipeline with multiple sections, each potentially with different diameters,
lengths and minor loss coefficients and determines the flow rate for a given headloss.
:param diameters: list of diameters, where the i_th diameter corresponds to the i_th pipe section
:type diameters: ... |
360,042 | def fnmatch_pathname_to_regex(pattern):
i, n = 0, len(pattern)
nonsep = .join([, os.sep, ])
res = []
while i < n:
c = pattern[i]
i = i + 1
if c == :
try:
if pattern[i] == :
i = i + 1
res.append()
if pattern[i] == :
i = i + 1
res.append(.join([os.sep, ]))
else:
res.... | Implements fnmatch style-behavior, as though with FNM_PATHNAME flagged;
the path seperator will not match shell-style '*' and '.' wildcards. |
360,043 | def _call_to(self, from_node, to_func, ret_node, stmt_idx=None, ins_addr=None, return_to_outside=False):
self._register_nodes(True, from_node)
if to_func.is_syscall:
self.transition_graph.add_edge(from_node, to_func, type=, stmt_idx=stmt_idx, ins_addr=ins_addr)
else:
... | Registers an edge between the caller basic block and callee function.
:param from_addr: The basic block that control flow leaves during the transition.
:type from_addr: angr.knowledge.CodeNode
:param to_func: The function that we are calling
:type to_func: Function
... |
360,044 | def get_version(
here_path,
default_version=DEFAULT_VERSION,
):
if in here_path:
return _version_from_file(here_path)
if os.environ.get():
if not TEST_MODE:
return os.environ.get().replace(, )
else:
warnings.warn(
... | tries to resolve version number
Args:
here_path (str): path to project local dir
default_version (str): what version to return if all else fails
Returns:
str: semantic_version information for library |
360,045 | def compute_srcprob(self,xmlfile=None, overwrite=False):
for i,c in enumerate(self.components):
c._diffrsp_app(xmlfile=xmlfile)
c._srcprob_app(xmlfile = xmlfile, overwrite = overwrite) | Run the gtsrcprob app with the current model or a user provided xmlfile |
360,046 | def has_custom_image(user_context, app_id):
possible_paths = _valid_custom_image_paths(user_context, app_id)
return any(map(os.path.exists, possible_paths)) | Returns True if there exists a custom image for app_id. |
360,047 | def send_mail_template(subject, template, addr_from, addr_to, context=None,
attachments=None, fail_silently=None, addr_bcc=None,
headers=None):
if context is None:
context = {}
if attachments is None:
attachments = []
if fail_silently is Non... | Send email rendering text and html versions for the specified
template name using the context dictionary passed in. |
360,048 | def action(self, column=None, value=None, **kwargs):
return self._resolve_call(, column, value, **kwargs) | The underlying GICS table provides codes and descriptions
identifying the current status or disposition of a grant project.
>>> GICS().action('action_code', 'A') |
360,049 | def pretty_render(data, format=, indent=0):
if format == :
return render_json(data)
elif format == :
return render_html(data)
elif format == :
return render_xml(data)
else:
return dict_to_plaintext(data, indent=indent) | Render a dict based on a format |
360,050 | def filelist_prune(self, at_data, *args, **kwargs):
b_status = True
l_file = []
str_path = at_data[0]
al_file = at_data[1]
if len(self.str_extension):
al_file = [x for x in al_file if self.str_extension in x]
if len(al_file):
... | Given a list of files, possibly prune list by
extension. |
360,051 | def get_url(cls, ticket):
url =
if isinstance(ticket, dict):
ticket = ticket[]
ticket = six.moves.urllib.parse.quote(ticket)
return url.format(ticket=ticket) | 通过ticket换取二维码地址
详情请参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542
:param ticket: 二维码 ticket 。可以通过 :func:`create` 获取到
:return: 返回的二维码地址
使用示例::
from wechatpy import WeChatClient
client = WeChatClient('appid', 'secret')
u... |
360,052 | def decorate(self, output_tree, output_tax, unique_names):
logging.info("Decorating tree")
encountered_taxonomies = {}
tc = TaxonomyCleaner()
for node in self.tree.preorder_internal_node_iter(exclude_seed_node=True):
max_tax_string_length = 0
for tip in ... | Decorate a tree with taxonomy. This code does not allow inconsistent
taxonomy within a clade. If one sequence in a clade has a different
annotation to the rest, it will split the clade. Paraphyletic group
names are distinguished if unique_names = True using a simple tally of
each group (... |
360,053 | def parse_info(response):
s INFO command into a Python dict.
In doing so, convert byte data into unicode.utf-8,=,=:')
if len(keyvalue) == 2:
key, value = keyvalue
try:
data[key] = int(value)
except ValueError:
data[key] = get_value(... | Parse the response of Redis's INFO command into a Python dict.
In doing so, convert byte data into unicode. |
360,054 | def transcode(self, source, destinations, **kwargs):
return self.protocol.execute(, source=source,
destinations=destinations, **kwargs) | Changes the compression characteristics of an audio and/or video
stream. Allows you to change the resolution of a source stream, change
the bitrate of a stream, change a VP8 or MPEG2 stream into H.264 and
much more. Allow users to create overlays on the final stream as well
as crop strea... |
360,055 | def velocity(adata, var_names=None, basis=None, groupby=None, groups=None, mode=None, fits=, layers=,
color=None, color_map=, colorbar=False, perc=[2,98], use_raw=False, size=None, alpha=.5,
fontsize=None, figsize=None, dpi=None, show=True, save=None, ax=None, ncols=None, **kwargs):
b... | Phase and velocity plot for set of genes.
The phase plot shows spliced against unspliced expressions with steady-state fit.
Further the embedding is shown colored by velocity and expression.
Arguments
---------
adata: :class:`~anndata.AnnData`
Annotated data matrix.
var_names: `str` or... |
360,056 | def rho(self):
rdecane
return phase_select_property(phase=self.phase, s=self.rhos, l=self.rhol, g=self.rhog) | r'''Mass density of the chemical at its current phase and
temperature and pressure, in units of [kg/m^3].
Utilizes the object oriented interfaces
:obj:`thermo.volume.VolumeSolid`,
:obj:`thermo.volume.VolumeLiquid`,
and :obj:`thermo.volume.VolumeGas` to perform the
actual... |
360,057 | def update_session(self, alias, headers=None, cookies=None):
session = self._cache.switch(alias)
session.headers = merge_setting(headers, session.headers)
session.cookies = merge_cookies(session.cookies, cookies) | Update Session Headers: update a HTTP Session Headers
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of headers merge into session |
360,058 | def get_thread_id_for_variable_reference(self, variable_reference):
t evaluate variable references values on any thread, only in the suspended
thread (the main reason for this is that in UI frameworks inspecting a UI object
from a different thread can potentially crash the application).
... | We can't evaluate variable references values on any thread, only in the suspended
thread (the main reason for this is that in UI frameworks inspecting a UI object
from a different thread can potentially crash the application).
:param int variable_reference:
The variable reference (c... |
360,059 | def filter_broker_list(brokers, filter_by):
filter_by_set = set(filter_by)
return [(id, host) for id, host in brokers if id in filter_by_set] | Returns sorted list, a subset of elements from brokers in the form [(id, host)].
Passing empty list for filter_by will return empty list.
:param brokers: list of brokers to filter, assumes the data is in so`rted order
:type brokers: list of (id, host)
:param filter_by: the list of ids of brokers to kee... |
360,060 | def _do_scale_fit(freqs, signal, model, w=None):
scalefac = np.empty(model.shape[0])
scalemodel = np.empty((model.shape[0], np.real(model).shape[1]))
scalesignal = np.empty((signal.shape[0], np.real(signal).shape[1]))
for ii, xx in enumerate(signal):
scalesignal[ii] = np.real(xx)
scalef... | Perform a round of fitting to deal with over or under-estimation.
Scales curve on y-axis but preserves shape.
Parameters
----------
freqs : array
signal : array
The signal that the model is being fit to
model : array
The model being scaled
w : array
weighting function
Returns... |
360,061 | def getReqId(self) -> int:
if not self.isReady():
raise ConnectionError()
newId = self._reqIdSeq
self._reqIdSeq += 1
return newId | Get new request ID. |
360,062 | def _prepare_wsdl_objects(self):
self.CarrierCode =
self.RoutingCode =
self.Address = self.client.factory.create()
self.ShipDateTime = datetime.datetime.now().isoformat() | Create the data structure and get it ready for the WSDL request. |
360,063 | def _add_gradient_scalar(self, name:str, scalar_value)->None:
"Writes a single scalar value for a gradient statistic to Tensorboard."
tag = self.name + + name
self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=self.iteration) | Writes a single scalar value for a gradient statistic to Tensorboard. |
360,064 | def _parse_bands(lines, n_start):
kpoints = []
labels = []
bands_s1 = []
bands_s2 = []
known_kpoints = {}
pattern = re.compile(".*?Nr.*?Spin.*?K-Point.*?", re.DOTALL)
selected_lines = lines[n_start:]
for current_line, line in enumerate(selected_l... | Parse band structure from cp2k output |
360,065 | def create(self, id, fd, filename=):
schema = AttachmentSchema(exclude=(, , , , , ))
resp = self.service.post(self._base(id),
files={: (filename, fd)})
return self.service.decode(schema, resp) | Add an attachment to a device.
:param id: Device ID as an int.
:param fd: File-like object to upload.
:param filename: (optional) Name to use for new attachment as a string.
:return: :class:`attachments.Attachment <attachments.Attachment>` object
:rtype: attachments.Attachment |
360,066 | def add_all_exchange_reactions(model, compartment, allow_duplicates=False):
all_reactions = {}
if not allow_duplicates:
for rxnid in model.database.reactions:
rx = model.database.get_reaction(rxnid)
all_reactions[rx] = rxnid
added = set()
added_co... | Add all exchange reactions to database and to model.
Args:
model: :class:`psamm.metabolicmodel.MetabolicModel`. |
360,067 | def _pop_translated_data(self):
translated_data = {}
for meta in self.Meta.model._parler_meta:
translations = self.validated_data.pop(meta.rel_name, {})
if translations:
translated_data[meta.rel_name] = translations
return translated_data | Separate data of translated fields from other data. |
360,068 | def load(self, callables_fname):
r
_validate_fname(callables_fname)
if not os.path.exists(callables_fname):
raise OSError("File {0} could not be found".format(callables_fname))
with open(callables_fname, "r") as fobj:
fdict = json.load(fobj)
if sy... | r"""
Load traced modules information from a `JSON <http://www.json.org/>`_ file.
The loaded module information is merged with any existing module information
:param callables_fname: File name
:type callables_fname: :ref:`FileNameExists`
:raises:
* OSError (File *[fna... |
360,069 | def build_combined_label(sl, idxs, sep=, label_format=None):
if label_format:
return label_format % tuple([get_shortstr(str(sl[n])) for n in idxs])
else:
return sep.join([get_shortstr(str(sl[n])) for n in idxs]) | Generate a combined label from a list of indexes
into sl, by joining them with `sep` (str).
:param sl: Strings to combine
:type sl: dict of str
:param idxs: Indexes into sl
:type idxs: list of sl keys
:param sep:
:return: `str` of combined label |
360,070 | def remove_item(name, system_wide=False):
desktop_env = system.get_name()
if desktop_env == :
import winreg
if system_wide:
startup_dir = os.path.join(winreg.ExpandEnvironmentStrings(), )
else:
startup_dir = os.path.join(directories.get_config_dir()[0], )
for startup_file in os.path.listdir(start... | Removes a program from startup.
Removes a program from startup.
Args:
name (str) : The name of the program (as known to the system) to remove. See :func:``list_items``.
system_wide (bool): Remove it from system-wide startup.
Note:
``system_wide`` requires superuser/admin privileges. |
360,071 | def sun_utc(self, date, latitude, longitude, observer_elevation=0):
dawn = self.dawn_utc(date, latitude, longitude, observer_elevation=observer_elevation)
sunrise = self.sunrise_utc(date, latitude, longitude, observer_elevation=observer_elevation)
noon = self.solar_noon_utc(date, longi... | Calculate all the info for the sun at once.
All times are returned in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param... |
360,072 | def validate_resource(self, value):
def do_backoff(*args, **kwargs):
attempts = 0
while True:
try:
self._test_connection(*args, **kwargs)
break
except ValidationError:
wait_... | Validate the network resource with exponential backoff |
360,073 | def make_otp_response(vres, client_key):
if client_key is not None:
sig = make_signature(vres, client_key)
vres[] = sig
pairs = [x + "=" + .join(vres[x]) for x in sorted(vres.keys())]
return .join(pairs) | Create validation response (signed, if a client key is supplied). |
360,074 | def guid(self):
iden = hashlib.md5()
props = {: self.size}
for name, item in self.hashes:
iden.update(item.digest())
props[name] = item.hexdigest()
return iden.hexdigest(), props | Use elements from this hash set to create a unique
(re)identifier. |
360,075 | def add_corpus(self, name, description):
corpora_url = self.base_url + self.CORPORA_PAGE
data = {: name, : description}
result = self.session.post(corpora_url, data=data)
if result.status_code == 201:
return Corpus(session=self.session, **result.json())
else:... | Add a corpus to your account |
360,076 | def sort_by_distance_percentage(cls, consumer_offsets_metadata):
sorted_offsets = sorted(
list(consumer_offsets_metadata.items()),
key=lambda topic_offsets1: sum(
[cls.percentage_distance(o.highmark, o.current) for o in topic_offsets1[1]]
)
)
... | Receives a dict of (topic_name: ConsumerPartitionOffset) and returns an
similar dict where the topics are sorted by average offset distance
in percentage. |
360,077 | def get_internet_gateway(vpc, **conn):
result = {}
ig_result = describe_internet_gateways(Filters=[{"Name": "attachment.vpc-id", "Values": [vpc["id"]]}], **conn)
if ig_result:
result.update({
"State": ig_result[0]["Attachments"][0]["State"],
"Id": ig_result[0][... | Gets the Internet Gateway details about a VPC |
360,078 | def delete_cookies():
cookies = dict(request.args.items())
r = app.make_response(redirect(url_for("view_cookies")))
for key, value in cookies.items():
r.delete_cookie(key=key)
return r | Deletes cookie(s) as provided by the query string and redirects to cookie list.
---
tags:
- Cookies
parameters:
- in: query
name: freeform
explode: true
allowEmptyValue: true
schema:
type: object
additionalProperties:
type: string
... |
360,079 | def _check_index(self, key: Union[slice, int]) -> (int, int):
ss, se = self._span
if isinstance(key, int):
if key < 0:
key += se - ss
if key < 0:
raise IndexError()
elif key >= se - ss:
raise IndexError(... | Return adjusted start and stop index as tuple.
Used in __setitem__ and __delitem__. |
360,080 | def balance_of(self, b58_address: str) -> int:
func = InvokeFunction()
Oep4.__b58_address_check(b58_address)
address = Address.b58decode(b58_address).to_bytes()
func.set_params_value(address)
result = self.__sdk.get_network().send_neo_vm_transaction_pre_exec(self.__hex_c... | This interface is used to call the BalanceOf method in ope4
that query the ope4 token balance of the given base58 encode address.
:param b58_address: the base58 encode address.
:return: the oep4 token balance of the base58 encode address. |
360,081 | def with_slots(cls):
def _compare(self, other):
for slot in self.__class__._slots_:
attr = operator.attrgetter(slot)
source = attr(self)
target = attr(other)
if isinstance(source, numpy.ndarray):
eq = numpy.array_equal(source, target)
... | Decorator for a class with _slots_. It automatically defines
the methods __eq__, __ne__, assert_equal. |
360,082 | def create_path(path, is_dir=False):
path = norm_path(path)
path_check = path
if not is_dir:
path_check = os.path.dirname(path)
does_path_exists = os.path.exists(path_check)
if does_path_exists:
return path
try:
os.makedirs(path_check)
except OSError:
... | Check if path exists, if not create it
:param path: path or file to create directory for
:param is_dir: pass True if we are passing in a directory, default = False
:return: os safe path from `path` |
360,083 | def starting_at(self, datetime_or_str):
if isinstance(datetime_or_str, str):
self._starting_at = parse(datetime_or_str)
elif isinstance(datetime_or_str, datetime.datetime):
self._starting_at = datetime_or_str
else:
raise ValueError()
return se... | Set the starting time for the cron job. If not specified, the starting time will always
be the beginning of the interval that is current when the cron is started.
:param datetime_or_str: a datetime object or a string that dateutil.parser can understand
:return: self |
360,084 | def make_tensor_value_info(
name,
elem_type,
shape,
doc_string="",
shape_denotation=None,
):
value_info_proto = ValueInfoProto()
value_info_proto.name = name
if doc_string:
value_info_proto.doc_string = doc_string
tensor_type_proto = valu... | Makes a ValueInfoProto based on the data type and shape. |
360,085 | def _proc_node_stmt(self, toks):
opts = toks[1]
dummy_node = Node("dummy")
for key, value in opts.iteritems():
trait = dummy_node.trait(key)
if trait is not None:
if trait.is_trait_type( Float ):
opts[key] = float( val... | Return (ADD_NODE, node_name, options) |
360,086 | def read_from_endpoint(self, endpoint, timeout=15):
return self.event_handler.wait_for_event((_EventType.Watch, endpoint), timeout=timeout) | Blocking read from an endpoint. Will block until a message is received, or it times out. Also see
:meth:`get_endpoint_queue` if you are considering calling this in a loop.
.. warning::
Avoid calling this method from an endpoint callback; doing so is likely to lead to deadlock.
.. no... |
360,087 | def neurons(self):
self.cursor.execute()
sel = self.cursor.fetchall()
return np.array(sel).flatten() | Return list of neuron indices.
Parameters
----------
None
Returns
-------
list
list of neuron indices
See also
--------
sqlite3.connect.cursor |
360,088 | def tab_should_insert_whitespace():
b = get_app().current_buffer
before_cursor = b.document.current_line_before_cursor
return bool(b.text and (not before_cursor or before_cursor.isspace())) | When the 'tab' key is pressed with only whitespace character before the
cursor, do autocompletion. Otherwise, insert indentation.
Except for the first character at the first line. Then always do a
completion. It doesn't make sense to start the first line with
indentation. |
360,089 | def add_node(self, node):
self.nodes.append(node)
try:
if node.node_id != b"$stats":
self.node_ids.append(node.node_id)
except NotImplementedError:
raise
except Exception:
print("ERROR: getting Node") | add a node class of HomieNode to this device |
360,090 | def extract_agg_losses(dstore, what):
loss_type, tags = get_loss_type_tags(what)
if not loss_type:
raise ValueError()
l = dstore[].lti[loss_type]
if in dstore:
stats = None
losses = dstore[][:, :, l][]
elif in dstore:
stats = dstore[].attrs[]
losses... | Aggregate losses of the given loss type and tags. Use it as
/extract/agg_losses/structural?taxonomy=RC&zipcode=20126
/extract/agg_losses/structural?taxonomy=RC&zipcode=*
:returns:
an array of shape (T, R) if one of the tag names has a `*` value
an array of shape (R,), being R the number of ... |
360,091 | def process_key(processor, fn):
def f(*aa, **kw):
k = fn(*aa, **kw)
if isinstance(k, (tuple, list)):
return (processor(k[0]),) + tuple(k[1:])
else:
return processor(k)
return f | :param processor:
a function to process the key returned by the supplied key function
:param fn:
a key function
:return:
a function that wraps around the supplied key function to further
process the key before returning. |
360,092 | def create_service(self, service_type, plan_name, service_name, params,
async=False, **kwargs):
if self.space.has_service_with_name(service_name):
logging.warning("Service already exists with that name.")
return self.get_instance(service_name)
if self.space.... | Create a service instance. |
360,093 | def letter_scales(counts):
try:
scale = 1.0 / sum(counts.values())
except ZeroDivisionError:
return []
freqs = [(aa, cnt*scale) for aa, cnt in counts.iteritems() if cnt]
freqs.sort(key=lambda pair: pair[1])
return freqs | Convert letter counts to frequencies, sorted increasing. |
360,094 | def get_redirect_url(request):
next_ = request.GET.get(REDIRECT_FIELD_NAME)
if not next_:
redirect_url = resolve_url(django_settings.CAS_REDIRECT_URL)
if django_settings.CAS_IGNORE_REFERER:
next_ = redirect_url
else:
next_ = request.META.get(, redirect_url)
... | Redirects to referring page, or CAS_REDIRECT_URL if no referrer is
set. |
360,095 | def _get_fields_for_model(model):
fields = []
for name in model._sa_class_manager:
prop = getattr(model, name)
if isinstance(prop.property, RelationshipProperty):
for pk in prop.property.mapper.primary_key:
fields.append(.format(name, pk.name))
else:
... | Gets all of the fields on the model.
:param DeclarativeModel model: A SQLAlchemy ORM Model
:return: A tuple of the fields on the Model corresponding
to the columns on the Model.
:rtype: tuple |
360,096 | def draw_edges(self):
for i, (start, end) in enumerate(self.graph.edges()):
start_theta = node_theta(self.nodes, start)
end_theta = node_theta(self.nodes, end)
verts = [
get_cartesian(self.plot_radius, start_theta),
(0, 0),
... | Renders edges to the figure. |
360,097 | def _is_valid_inherit_element(self, element):
tag_name = element.get_tag_name()
return (
(tag_name in AccessibleCSSImplementation.VALID_INHERIT_TAGS)
and (not element.has_attribute(CommonFunctions.DATA_IGNORE))
) | Check that the children of element can be manipulated to apply the CSS
properties.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:return: True if the children of element can be manipulated to apply
the CSS properties or Fal... |
360,098 | def peer_retrieve_by_prefix(prefix, relation_name=, delimiter=,
inc_list=None, exc_list=None):
inc_list = inc_list if inc_list else []
exc_list = exc_list if exc_list else []
peerdb_settings = peer_retrieve(, relation_name=relation_name)
matched = {}
if peerdb_settin... | Retrieve k/v pairs given a prefix and filter using {inc,exc}_list |
360,099 | def _normalize_attrs(attrs, null=None):
if attrs:
items = sorted((_normalize_name(k), _normalize_value(v, null)) for (k, v) in attrs.items())
if null is None:
return OrderedDict((k, v) for (k, v) in items if v is not None)
else:
return OrderedDict(items)
else:
return {} | Returns an OrderedDict of attirbutes with the keys normalized by _normalize_name and the values
normalized by _normalize_value. The value of :null: is passed to _normalize_value. However, if
:null: is None, any values that are None are left out of the returned dict.
An OrderedDict is returned so that the attribu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.