Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
10,500 | def put(self, endpoint, data, **kwargs):
return self.__request("PUT", endpoint, data, **kwargs) | PUT requests |
10,501 | def get_sigla(self, work):
return [os.path.splitext(os.path.basename(path))[0]
for path in glob.glob(os.path.join(self._path, work, ))] | Returns a list of all of the sigla for `work`.
:param work: name of work
:type work: `str`
:rtype: `list` of `str` |
10,502 | def run(self):
logger.info(, self)
ret = self.job_func()
self.last_run = datetime.datetime.now()
self._schedule_next_run()
return ret | Run the job and immediately reschedule it.
:return: The return value returned by the `job_func` |
10,503 | def multipart_complete(self, multipart):
multipart.complete()
db.session.commit()
version_id = str(uuid.uuid4())
return self.make_response(
data=multipart,
context={
: MultipartObject,
: multipart.bucket,
... | Complete a multipart upload.
:param multipart: A :class:`invenio_files_rest.models.MultipartObject`
instance.
:returns: A Flask response. |
10,504 | def set(self, handler, attr, name, path, cfg):
full_name = ("%s.%s" % (path, name)).strip(".")
if attr.default is None:
default = None
else:
try:
comp = vodka.component.Component(cfg)
default = handler.default(name, ins... | Obtain value for config variable, by prompting the user
for input and substituting a default value if needed.
Also does validation on user input |
10,505 | def _copy(self, filename, dir1, dir2):
if self._copyfiles:
rel_path = filename.replace(, ).split()
rel_dir = .join(rel_path[:-1])
filename = rel_path[-1]
dir2_root = dir2
dir1 = os.path.join(dir1, rel_dir)
dir2 = os.pa... | Private function for copying a file |
10,506 | async def process_request(self, path, headers):
path_portion, _, query_string = path.partition("?")
websockets.handshake.check_request(headers)
subprotocols = []
for header in headers.get_all("Sec-WebSocket-Protocol"):
subprotocols.extend([token.strip() for token i... | This hook is called to determine if the websocket should return
an HTTP response and close.
Our behavior here is to start the ASGI application, and then wait
for either `accept` or `close` in order to determine if we should
close the connection. |
10,507 | def backtrace_on_usr1 ():
import signal
try:
signal.signal (signal.SIGUSR1, _print_backtrace_signal_handler)
except Exception as e:
warn (, e) | Install a signal handler such that this program prints a Python traceback
upon receipt of SIGUSR1. This could be useful for checking that
long-running programs are behaving properly, or for discovering where an
infinite loop is occurring.
Note, however, that the Python interpreter does not invoke Pytho... |
10,508 | def _freq_parser(self, freq):
freq = freq.lower().strip()
try:
if "day" in freq:
freq = freq.replace("day", "")
return timedelta(days=int(freq))
elif "hour" in freq:
freq = freq.replace("hour", "")
return ti... | day, hour, min, sec, |
10,509 | def scrap(self,
url=None, scheme=None, timeout=None,
html_parser=None, cache_ext=None
):
if not url:
url = self.url
if not scheme:
scheme = self.scheme
if not timeout:
timeout = self.timeout
if not html_parser:
... | Scrap a url and parse the content according to scheme
:param url: Url to parse (default: self._url)
:type url: str
:param scheme: Scheme to apply to html (default: self._scheme)
:type scheme: dict
:param timeout: Timeout for http operation (default: self._timout)
:type t... |
10,510 | def untokenized_tfds_dataset(dataset_name=gin.REQUIRED,
text2self=gin.REQUIRED,
tfds_data_dir=gin.REQUIRED,
dataset_split=gin.REQUIRED,
batch_size=gin.REQUIRED,
sequence_lengt... | Reads a tensorflow_datasets dataset.
Returns a tf.data.Dataset containing single tokenized examples where each
feature ends in EOS=1.
Args:
dataset_name: a string
text2self: a boolean
tfds_data_dir: a boolean
dataset_split: a string
batch_size: an integer
sequence_length: an integer
... |
10,511 | def heterogzygote_counts(paired):
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(paired.tumor_data), "structural", "counts"))
key = "germline_het_pon"
het_bed = tz.get_in(["genome_resources", "variation", key], paired.tumor_data)
vr = bedutils.population_variant_regions([x for x in [pai... | Provide tumor/normal counts at population heterozyogte sites with CollectAllelicCounts. |
10,512 | def Ra(L: float, Ts: float, Tf: float, alpha: float, beta: float, nu: float
) -> float:
return g * beta * (Ts - Tinf) * L**3.0 / (nu * alpha) | Calculate the Ralleigh number.
:param L: [m] heat transfer surface characteristic length.
:param Ts: [K] heat transfer surface temperature.
:param Tf: [K] bulk fluid temperature.
:param alpha: [m2/s] fluid thermal diffusivity.
:param beta: [1/K] fluid coefficient of thermal expansion.
:param nu... |
10,513 | def create_secgroups(self):
utils.banner("Creating Security Group")
sgobj = securitygroup.SpinnakerSecurityGroup(
app=self.app, env=self.env, region=self.region, prop_path=self.json_path)
sgobj.create_security_group() | Create security groups as defined in the configs. |
10,514 | def list_targets_by_rule(client=None, **kwargs):
result = client.list_targets_by_rule(**kwargs)
if not result.get("Targets"):
result.update({"Targets": []})
return result | Rule='string' |
10,515 | def alwaysCalledWith(self, *args, **kwargs):
self.__get_func = SinonSpy.__get_directly
return self.alwaysCalledWithMatch(*args, **kwargs) | Determining whether args/kwargs are the ONLY args/kwargs called previously
Eg.
f(1, 2, 3)
f(1, 2, 3)
spy.alwaysCalledWith(1, 2) will return True, because they are the ONLY called args
f(1, 3)
spy.alwaysCalledWith(1) will return True, because 1 is the O... |
10,516 | def get_metric_index(self, metric_cls):
ds = self.class2ds[metric_cls.ds]
if self.index_dict[ds]:
index_name = self.index_dict[ds]
else:
index_name = self.ds2index[metric_cls.ds]
return index_name | Get the index name with the data for a metric class
:param metric_cls: a metric class
:return: the name of the index with the data for the metric |
10,517 | def find_recent(self, nrecent=4):
try:
rows = self.cur.execute("SELECT noteId FROM note WHERE book > 0 ORDER BY date DESC LIMIT %d;"%nrecent).fetchall()
except:
self.error("nota.find_recent() cannot look up note list")
noteIds = []
for r in rows:... | Find recent non-trashed notes |
10,518 | def as_spectrum(self, binned=True):
if binned:
wave, flux = self.binwave, self.binflux
else:
wave, flux = self.wave, self.flux
result = ArraySourceSpectrum(wave, flux,
self.waveunits,
self... | Reduce the observation to a simple spectrum object.
An observation is a complex object with some restrictions on its
capabilities. At times, it would be useful to work with the
simulated observation as a simple object that is easier to
manipulate and takes up less memory.
Param... |
10,519 | def get_relations(self, cursor, table_name):
def table2model(table_name):
return SfProtectName(table_name).title().replace(, ).replace(, )
global last_introspected_model, last_read_only, last_refs
global last_with_important_related_name
result = {}
... | Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based. |
10,520 | def allclose_up_to_global_phase(
a: np.ndarray,
b: np.ndarray,
*,
rtol: float = 1.e-5,
atol: float = 1.e-8,
equal_nan: bool = False
) -> bool:
a, b = transformations.match_global_phase(a, b)
return np.allclose(a=a, b=b, rtol=rtol, atol=atol, equal_nan=... | Determines if a ~= b * exp(i t) for some t.
Args:
a: A numpy array.
b: Another numpy array.
rtol: Relative error tolerance.
atol: Absolute error tolerance.
equal_nan: Whether or not NaN entries should be considered equal to
other NaN entries. |
10,521 | def exists_type(self, using=None, **kwargs):
return self._get_connection(using).indices.exists_type(index=self._name, **kwargs) | Check if a type/types exists in the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.exists_type`` unchanged. |
10,522 | def count(args):
counts = defaultdict(int)
for arg in args:
for item in arg:
counts[item] = counts[item] + 1
return counts | count occurences in a list of lists
>>> count([['a','b'],['a']])
defaultdict(int, {'a' : 2, 'b' : 1}) |
10,523 | def register_rpc(self, address, rpc_id, func):
if rpc_id < 0 or rpc_id > 0xFFFF:
raise RPCInvalidIDError("Invalid RPC ID: {}".format(rpc_id))
if address not in self._rpc_overlays:
self._rpc_overlays[address] = RPCDispatcher()
self._rpc_overlays[address].add_rp... | Register a single RPC handler with the given info.
This function can be used to directly register individual RPCs,
rather than delegating all RPCs at a given address to a virtual
Tile.
If calls to this function are mixed with calls to add_tile for
the same address, these RPCs w... |
10,524 | def goto(directory, create=False):
current = os.getcwd()
directory = os.path.abspath(directory)
if os.path.isdir(directory) or (create and mkdir(directory)):
logger.info("goto -> %s", directory)
os.chdir(directory)
try:
yield True
finally:
logge... | Context object for changing directory.
Args:
directory (str): Directory to go to.
create (bool): Create directory if it doesn't exists.
Usage::
>>> with goto(directory) as ok:
... if not ok:
... print 'Error'
... else:
... print ... |
10,525 | def do_execute(self):
result = None
cont = self.input.payload
serialization.write_all(
str(self.resolve_option("output")),
[cont.get("Model").jobject, cont.get("Header").jobject])
return result | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str |
10,526 | def localize_sql(self, sql: str) -> str:
if self.db_pythonlib in [PYTHONLIB_PYMYSQL, PYTHONLIB_MYSQLDB]:
sql = _PERCENT_REGEX.sub("%%", sql)
sql = _QUERY_VALUE_REGEX.sub("%s", s... | Translates ?-placeholder SQL to appropriate dialect.
For example, MySQLdb uses %s rather than ?. |
10,527 | async def register(self, check, *, token=None):
token_id = extract_attr(token, keys=["ID"])
params = {"token": token_id}
response = await self._api.put("/v1/agent/check/register",
params=params,
data=check)
... | Registers a new local check
Parameters:
check (Object): Check definition
token (ObjectID): Token ID
Returns:
bool: ``True`` on success
The register endpoint is used to add a new check to the local agent.
Checks may be of script, HTTP, TCP, or TTL typ... |
10,528 | def preprocess_mnist(sc, options):
train_data = get_mnist(sc, "train", options.dataPath)\
.map(lambda rec_tuple: (normalizer(rec_tuple[0], mnist.TRAIN_MEAN, mnist.TRAIN_STD),
rec_tuple[1]))\
.map(lambda t: Sample.from_ndarray(t[0], t[1]))
test_data = get_mnis... | Preprocess mnist dataset.
Normalize and transform into Sample of RDDs. |
10,529 | def push_group_with_content(self, content):
cairo.cairo_push_group_with_content(self._pointer, content)
self._check_status() | Temporarily redirects drawing to an intermediate surface
known as a group.
The redirection lasts until the group is completed
by a call to :meth:`pop_group` or :meth:`pop_group_to_source`.
These calls provide the result of any drawing
to the group as a pattern,
(either as... |
10,530 | def is_authoring_node(self, node):
for parent_node in foundations.walkers.nodes_walker(node, ascendants=True):
if parent_node is self.__default_project_node:
return True
return False | Returns if given Node is an authoring node.
:param node: Node.
:type node: ProjectNode or DirectoryNode or FileNode
:return: Is authoring node.
:rtype: bool |
10,531 | def on_connect_button__clicked(self, event):
hub_uri = self.plugin_uri.get_text()
ui_plugin_name = self.ui_plugin_name.get_text()
plugin = self.create_plugin(ui_plugin_name, hub_uri)
self.init_plugin(plugin)
self.connect_button.set_sensitive(False)
self.emit(, ... | Connect to Zero MQ plugin hub (`zmq_plugin.hub.Hub`) using the settings
from the text entry fields (e.g., hub URI, plugin name).
Emit `plugin-connected` signal with the new plugin instance after hub
connection has been established. |
10,532 | def source_channels(self):
source_channels = [v.coordinates.keys() for v in self.verts]
return set(itertools.chain(*source_channels)) | Returns a set describing the source channels on which the gate is defined. |
10,533 | def read(path, encoding="utf-8"):
try:
with io.open(path, encoding=encoding) as f:
return f.read()
except Exception as e:
logger.error("read: %s failed. Error: %s", path, e)
return "" | Read the content of the file.
Args:
path (str): Path to the file
encoding (str): File encoding. Default: utf-8
Returns:
str: File content or empty string if there was an error |
10,534 | def extract_wavs(utterances: List[Utterance], tgt_dir: Path,
lazy: bool) -> None:
tgt_dir.mkdir(parents=True, exist_ok=True)
for utter in utterances:
wav_fn = "{}.{}".format(utter.prefix, "wav")
out_wav_path = tgt_dir / wav_fn
if lazy and out_wav_path.is_file():
... | Extracts WAVs from the media files associated with a list of Utterance
objects and stores it in a target directory.
Args:
utterances: A list of Utterance objects, which include information
about the source media file, and the offset of the utterance in the
media_file.
tg... |
10,535 | def annotate_with_depth(in_file, items):
bam_file = None
if len(items) == 1:
bam_file = dd.get_align_bam(items[0])
else:
paired = vcfutils.get_paired(items)
if paired:
bam_file = paired.tumor_bam
if bam_file:
out_file = "%s-duphold.vcf.gz" % utils.splitex... | Annotate called VCF file with depth using duphold (https://github.com/brentp/duphold)
Currently annotates single sample and tumor samples in somatic analysis. |
10,536 | def render_template(self, template_file, target_file, template_vars = {}):
template_dir = str(self.__class__.__name__).lower()
template = self.jinja_env.get_template(os.path.join(template_dir, template_file))
file_path = os.path.join(self.work_root, target_file)
with open(file_p... | Render a Jinja2 template for the backend
The template file is expected in the directory templates/BACKEND_NAME. |
10,537 | def _wrap_attr(self, attrs, context=None):
for attr in attrs:
if isinstance(attr, UnboundMethod):
if _is_property(attr):
yield from attr.infer_call_result(self, context)
else:
yield BoundMethod(attr, self)
e... | wrap bound methods of attrs in a InstanceMethod proxies |
10,538 | def colname_gen(df,col_name = ):
if col_name not in df.keys():
yield col_name
id_number = 0
while True:
col_name = col_name + str(id_number)
if col_name in df.keys():
id_number+=1
else:
return col_name | Returns a column name that isn't in the specified DataFrame
Parameters:
df - DataFrame
DataFrame to analyze
col_name - string, default 'unnamed_col'
Column name to use as the base value for the generated column name |
10,539 | def MapFields(function, key=True):
@use_raw_input
def _MapFields(bag):
try:
factory = type(bag)._make
except AttributeError:
factory = type(bag)
if callable(key):
try:
fields = bag._fields
except AttributeError as e:
... | Transformation factory that maps `function` on the values of a row.
It can be applied either to
1. all columns (`key=True`),
2. no column (`key=False`), or
3. a subset of columns by passing a callable, which takes column name and returns `bool`
(same as the parameter `function` in `filter`).
:... |
10,540 | def filter_expr(cls_or_alias, **filters):
if isinstance(cls_or_alias, AliasedClass):
mapper, cls = cls_or_alias, inspect(cls_or_alias).mapper.class_
else:
mapper = cls = cls_or_alias
expressions = []
valid_attributes = cls.filterable_attributes
f... | forms expressions like [Product.age_from = 5,
Product.subject_ids.in_([1,2])]
from filters like {'age_from': 5, 'subject_ids__in': [1,2]}
Example 1:
db.query(Product).filter(
*Product.filter_expr(age_from = 5, subject_ids__in=[1, 2]))
... |
10,541 | def max_rigid_id(self):
try:
return max([particle.rigid_id for particle in self.particles()
if particle.rigid_id is not None])
except ValueError:
return | Returns the maximum rigid body ID contained in the Compound.
This is usually used by compound.root to determine the maximum
rigid_id in the containment hierarchy.
Returns
-------
int or None
The maximum rigid body ID contained in the Compound. If no
rigi... |
10,542 | def unsubscribe_all(self):
for channel in self.list_all():
channel.ensure_stopped()
self.connect_api.stop_notifications() | Unsubscribes all channels |
10,543 | def get_translation_args(self, args):
translation_args = []
for arg in args:
condition = self._get_linguist_condition(arg, transform=True)
if condition:
translation_args.append(condition)
return translation_args | Returns linguist args from model args. |
10,544 | def light(self):
sun = self.chart.getObject(const.SUN)
return light(self.obj, sun) | Returns if object is augmenting or diminishing its
light. |
10,545 | def install_signal_trap(signums = (signal.SIGTERM, signal.SIGTSTP), retval = 1):
signums = set(signums) - set(origactions)
def temporary_file_cleanup_on_signal(signum, frame):
with temporary_files_lock:
temporary_files.clear()
if callable(origactions[signum]):
return origactions[signum](signum, f... | Installs a signal handler to erase temporary scratch files when a
signal is received. This can be used to help ensure scratch files
are erased when jobs are evicted by Condor. signums is a squence
of the signals to trap, the default value is a list of the signals
used by Condor to kill and/or evict jobs.
The lo... |
10,546 | def edit(self, image_id, name=None, note=None, tag=None):
obj = {}
if name:
obj[] = name
if note:
obj[] = note
if obj:
self.vgbdtg.editObject(obj, id=image_id)
if tag:
self.vgbdtg.setTags(str(tag), id=image_id)
ret... | Edit image related details.
:param int image_id: The ID of the image
:param string name: Name of the Image.
:param string note: Note of the image.
:param string tag: Tags of the image to be updated to. |
10,547 | def _expected_condition_find_element(self, element):
from toolium.pageelements.page_element import PageElement
web_element = False
try:
if isinstance(element, PageElement):
element._web_element = None
element._find_web_element... | Tries to find the element, but does not thrown an exception if the element is not found
:param element: PageElement or element locator as a tuple (locator_type, locator_value) to be found
:returns: the web element if it has been found or False
:rtype: selenium.webdriver.remote.webelement.WebEle... |
10,548 | def delete_map(self, url, map=None, auth_map=None):
xml = None
if map is not None:
xml = dumps_networkapi(map)
response_code, content = self.delete(url, xml, , auth_map)
return response_code, content | Gera um XML a partir dos dados do dicionário e o envia através de uma requisição DELETE.
:param url: URL para enviar a requisição HTTP.
:param map: Dicionário com os dados do corpo da requisição HTTP.
:param auth_map: Dicionário com as informações para autenticação na networkAPI.
:retu... |
10,549 | def visit_importfrom(self, node):
try:
logging_name = self._from_imports[node.modname]
for module, as_name in node.names:
if module == logging_name:
self._logging_names.add(as_name or module)
except KeyError:
pass | Checks to see if a module uses a non-Python logging module. |
10,550 | def camera_status_encode(self, time_usec, target_system, cam_idx, img_idx, event_id, p1, p2, p3, p4):
return MAVLink_camera_status_message(time_usec, target_system, cam_idx, img_idx, event_id, p1, p2, p3, p4) | Camera Event
time_usec : Image timestamp (microseconds since UNIX epoch, according to camera clock) (uint64_t)
target_system : System ID (uint8_t)
cam_idx : Camera ID (uint8_t)
img_idx : Imag... |
10,551 | def launch_game(
players: List[Player],
launch_params: Dict[str, Any],
show_all: bool,
read_overwrite: bool,
wait_callback: Callable
) -> None:
if not players:
raise GameException("at least one player must be specified")
game_dir = launch_params["game_dir"]
... | :raises DockerException, ContainerException, RealtimeOutedException |
10,552 | def append_qs(url, query_string):
parsed_url = urlsplit(url)
parsed_qs = parse_qsl(parsed_url.query, True)
if isstr(query_string):
parsed_qs += parse_qsl(query_string)
elif isdict(query_string):
for item in list(query_string.items()):
if islist(item[1]):
... | Append query_string values to an existing URL and return it as a string.
query_string can be:
* an encoded string: 'test3=val1&test3=val2'
* a dict of strings: {'test3': 'val'}
* a dict of lists of strings: {'test3': ['val1', 'val2']}
* a list of tuples: [('test3', 'val1'), ('test3'... |
10,553 | def setProperty(self, name, value):
self._push(self._driver.setProperty, (name, value)) | Called by the engine to set a driver property value.
@param name: Name of the property
@type name: str
@param value: Property value
@type value: object |
10,554 | def sinter(self, keys, *args):
func = lambda left, right: left.intersection(right)
return self._apply_to_sets(func, "SINTER", keys, *args) | Emulate sinter. |
10,555 | def taskfileinfo_task_data(tfi, role):
task = tfi.task
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return task.name | Return the data for task
:param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the task
:rtype: depending on role
:raises: None |
10,556 | def get_variable_set(self, variable_set, data):
if data.get():
variable_set = []
elif data.get():
op, layer_ids = data[].split(, 1)
op = op.lower()
layer_ids = [int(x) for x in layer_ids.split()]
if op in (, ):
vari... | Filters the given variable set based on request parameters |
10,557 | def _construct_replset(self, basedir, portstart, name, num_nodes,
arbiter, extra=):
self.config_docs[name] = {: name, : []}
for i in num_nodes:
datapath = self._create_paths(basedir, % (name, i + 1))
self._construct_mongod(os.path.jo... | Construct command line strings for a replicaset.
Handles single set or sharded cluster. |
10,558 | def macro(name):
def wrapper(view, context, model, column):
if in name:
macro_import_name, macro_name = name.split()
m = getattr(context.get(macro_import_name), macro_name, None)
else:
m = context.resolve(name)
if not m:
return m
... | Replaces :func:`~flask_admin.model.template.macro`, adding support for using
macros imported from another file. For example:
.. code:: html+jinja
{# templates/admin/column_formatters.html #}
{% macro email(model, column) %}
{% set address = model[column] %}
<a href="mailto... |
10,559 | def deep_update_dict(origin_dict, override_dict):
if not override_dict:
return origin_dict
for key, val in override_dict.items():
if isinstance(val, dict):
tmp = deep_update_dict(origin_dict.get(key, {}), val)
origin_dict[key] = tmp
elif val is None:
... | update origin dict with override dict recursively
e.g. origin_dict = {'a': 1, 'b': {'c': 2, 'd': 4}}
override_dict = {'b': {'c': 3}}
return: {'a': 1, 'b': {'c': 3, 'd': 4}} |
10,560 | def show(movie):
for key, value in sorted(movie.iteritems(), cmp=metadata_sorter, key=lambda x: x[0]):
if isinstance(value, list):
if not value:
continue
other = value[1:]
value = value[0]
else:
other = []
printer.p(, key=k... | Show the movie metadata. |
10,561 | def replace(self, src: str) -> str:
if not self.readied:
self.ready()
src = self._dict_replace(self.simple_pre, src)
for regex, replace in self.regex_pre:
src = regex.sub(replace, src)
src = self._operators_replace(src)
... | Extends LaTeX syntax via regex preprocess
:param src: str
LaTeX string
:return: str
New LaTeX string |
10,562 | def to_internal_value(self, data):
if data is None:
return
if not isinstance(data, dict):
self.fail()
if not self.allow_empty and len(data) == 0:
self.fail()
result, errors = {}, {}
for lang_code, model_fields in data.items():
... | Deserialize data from translations fields.
For each received language, delegate validation logic to
the translation model serializer. |
10,563 | def run(self, args):
Mframe.adjust_relative(self.proc, self.name, args, self.signum)
return False | **down** [*count*]
Move the current frame down in the stack trace (to a newer frame). 0
is the most recent frame. If no count is given, move down 1.
See also:
---------
`up` and `frame`. |
10,564 | def get_repo(path=None, alias=None, create=False):
if create:
if not (path or alias):
raise TypeError("If create is specified, we need path and scm type")
return get_backend(alias)(path, create=True)
if path is None:
path = abspath(os.path.curdir)
try:
scm, p... | Returns ``Repository`` object of type linked with given ``alias`` at
the specified ``path``. If ``alias`` is not given it will try to guess it
using get_scm method |
10,565 | def sendcontrol(self, char):
\ag
char = char.lower()
a = ord(char)
if 97 <= a <= 122:
a = a - ord() + 1
byte = _byte(a)
return self._writeb(byte), byte
d = {: 0, : 0,
: 27, : 27,
: 28, : 28,
: 29, : 29,
... | Helper method that wraps send() with mnemonic access for sending control
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
Ctrl-G (ASCII 7, bell, '\a')::
child.sendcontrol('g')
See also, sendintr() and sendeof(). |
10,566 | def crab_factory(**kwargs):
if in kwargs:
wsdl = kwargs[]
del kwargs[]
else:
wsdl = "http://crab.agiv.be/wscrab/wscrab.svc?wsdl"
log.info(, wsdl)
c = Client(
wsdl,
**kwargs
)
return c | Factory that generates a CRAB client.
A few parameters will be handled by the factory, other parameters will
be passed on to the client.
:param wsdl: `Optional.` Allows overriding the default CRAB wsdl url.
:param proxy: `Optional.` A dictionary of proxy information that is passed
to the under... |
10,567 | async def prepare_decrypter(client, cdn_client, cdn_redirect):
cdn_aes = AESModeCTR(
key=cdn_redirect.encryption_key,
iv=cdn_redirect.encryption_iv[:12] + bytes(4)
)
decrypter = CdnDecrypter(
cdn_client, cdn_redirect.fi... | Prepares a new CDN decrypter.
:param client: a TelegramClient connected to the main servers.
:param cdn_client: a new client connected to the CDN.
:param cdn_redirect: the redirect file object that caused this call.
:return: (CdnDecrypter, first chunk file data) |
10,568 | def executable_path(conn, executable):
executable_path = conn.remote_module.which(executable)
if not executable_path:
raise ExecutableNotFound(executable, conn.hostname)
return executable_path | Remote validator that accepts a connection object to ensure that a certain
executable is available returning its full path if so.
Otherwise an exception with thorough details will be raised, informing the
user that the executable was not found. |
10,569 | def load_json_file(file, decoder=None):
if decoder is None:
decoder = DateTimeDecoder
if not hasattr(file, "read"):
with io.open(file, "r", encoding="utf-8") as f:
return json.load(f, object_hook=decoder.decode)
return json.load(file, object_hook=decoder.decode) | Load data from json file
:param file: Readable object or path to file
:type file: FileIO | str
:param decoder: Use custom json decoder
:type decoder: T <= DateTimeDecoder
:return: Json data
:rtype: None | int | float | str | list | dict |
10,570 | def did_you_mean(unknown_command, entry_points):
from difflib import SequenceMatcher
similarity = lambda x: SequenceMatcher(None, x, unknown_command).ratio()
did_you_mean = sorted(entry_points, key=similarity, reverse=True)
return did_you_mean[0] | Return the command with the name most similar to what the user typed. This
is used to suggest a correct command when the user types an illegal
command. |
10,571 | def init_db(self, db_path):
self.database = % db_path
self.storage = SREGISTRY_STORAGE
bot.debug("Database located at %s" % self.database)
self.engine = create_engine(self.database, convert_unicode=True)
self.session = scoped_session(sessionmaker(autocommit=False,
... | initialize the database, with the default database path or custom of
the format sqlite:////scif/data/expfactory.db
The custom path can be set with the environment variable SREGISTRY_DATABASE
when a user creates the client, we must initialize this db
the database should use the .singularity cache fo... |
10,572 | def do_i_raise_dependency(self, status, inherit_parents, hosts, services, timeperiods):
for stat in status:
if self.is_state(stat):
return True
if not inherit_parents:
return False
now = time.time()
fo... | Check if this object or one of its dependency state (chk dependencies) match the status
:param status: state list where dependency matters (notification failure criteria)
:type status: list
:param inherit_parents: recurse over parents
:type inherit_parents: bool
:param hosts: ho... |
10,573 | def load_header_chain( cls, chain_path ):
header_parser = BlockHeaderSerializer()
chain = []
height = 0
with open(chain_path, "rb") as f:
h = SPVClient.read_header_at( f )
h[] = height
height += 1
chain.append(h)
retur... | Load the header chain from disk.
Each chain element will be a dictionary with:
* |
10,574 | def from_string(url, default_protocol=):
if url is None:
raise TypeError( + type(url))
result = Url()
match = re.match(r, url)
if match:
result.protocol = match.group(1)
else:
result.protocol = default_protocol
... | Parses the given URL and returns an URL object. There are some
differences to Python's built-in URL parser:
- It is less strict, many more inputs are accepted. This is
necessary to allow for passing a simple hostname as a URL.
- You may specify a default protocol that is used when the... |
10,575 | def normalize_path_out(self, path):
if path.startswith(self._CWD):
normalized_path = path[len(self._CWD):]
else:
normalized_path = path
if self._CLIENT_CWD:
normalized_path = os.path.join(self._CLIENT_CWD, normalized_path)
_logger.p_d... | Normalizes path sent to client
:param path: path to normalize
:return: normalized path |
10,576 | def _reset(self):
self.hw.remote_at(
dest_addr=self.remote_addr,
command=,
parameter=)
self.deactivate()
self._set_send_samples(False) | reset: None -> None
Resets the remote XBee device to a standard configuration |
10,577 | def write(self, frame):
if not isinstance(frame, FrameBase):
raise PyVLXException("Frame not of type FrameBase", frame_type=type(frame))
PYVLXLOG.debug("SEND: %s", frame)
self.transport.write(slip_pack(bytes(frame))) | Write frame to Bus. |
10,578 | def p_line_label_asm(p):
p[0] = p[2]
__DEBUG__("Declaring (value %04Xh) in %i" % (NAMESPACE, p[1], MEMORY.org, p.lineno(1)))
MEMORY.declare_label(p[1], p.lineno(1)) | line : LABEL asms NEWLINE |
10,579 | def generate_security_data(self):
timestamp = int(time.time())
security_dict = {
: str(self.target_object._meta),
: str(self.target_object._get_pk_val()),
: str(timestamp),
: self.initial_security_hash(timestamp),
}
return security... | Generate a dict of security data for "initial" data. |
10,580 | def Vmg(self):
rhexane
return self.VolumeGasMixture(T=self.T, P=self.P, zs=self.zs, ws=self.ws) | r'''Gas-phase molar volume of the mixture at its current
temperature, pressure, and composition in units of [m^3/mol]. For
calculation of this property at other temperatures or pressures or
compositions, or specifying manually the method used to calculate it,
and more - see the object or... |
10,581 | def bleu_score(logits, labels):
predictions = tf.to_int32(tf.argmax(logits, axis=-1))
bleu = tf.py_func(compute_bleu, (labels, predictions), tf.float32)
return bleu, tf.constant(1.0) | Approximate BLEU score computation between labels and predictions.
An approximate BLEU scoring method since we do not glue word pieces or
decode the ids and tokenize the output. By default, we use ngram order of 4
and use brevity penalty. Also, this does not have beam search.
Args:
logits: Tensor of size ... |
10,582 | def plot_dives_pitch(depths, dive_mask, des, asc, pitch, pitch_lf):
import copy
import numpy
from . import plotutils
fig, (ax1, ax2) = plt.subplots(2,1, sharex=True)
des_ind = numpy.where(dive_mask & des)[0]
asc_ind = numpy.where(dive_mask & asc)[0]
ax1.title.set_text()
ax1 = pl... | Plot dives with phase and associated pitch angle with HF signal
Args
----
depths: ndarray
Depth values at each sensor sampling
dive_mask: ndarray
Boolean mask slicing dives from the tag data
des: ndarray
boolean mask for slicing descent phases of dives from tag dta
asc: ... |
10,583 | def optional_else(self, node, last):
if node.orelse:
min_first_max_last(node, node.orelse[-1])
if in self.operators:
position = (node.orelse[0].first_line, node.orelse[0].first_col)
_, efirst = self.operators[].find_previous(position)
... | Create op_pos for optional else |
10,584 | def predict(inputs_list, problem, request_fn):
assert isinstance(inputs_list, list)
fname = "inputs" if problem.has_inputs else "targets"
input_encoder = problem.feature_info[fname].encoder
input_ids_list = [
_encode(inputs, input_encoder, add_eos=problem.has_inputs)
for inputs in inputs_list
]... | Encodes inputs, makes request to deployed TF model, and decodes outputs. |
10,585 | def many_init(cls, *args, **kwargs):
list_kwargs = {: cls(*args, **kwargs)}
for key in kwargs.keys():
if key in MANY_RELATION_KWARGS:
list_kwargs[key] = kwargs[key]
return ManyRelatedField(**list_kwargs) | This method handles creating a parent `ManyRelatedField` instance
when the `many=True` keyword argument is passed.
Typically you won't need to override this method.
Note that we're over-cautious in passing most arguments to both parent
and child classes in order to try to cover the gen... |
10,586 | def _create_pure_shape(self, primitive_type, options, sizes, mass, precision):
lua_code = "simCreatePureShape({}, {}, {{{}, {}, {}}}, {}, {{{}, {}}})".format(
primitive_type, options, sizes[0], sizes[1], sizes[2], mass, precision[0], precision[1])
self._inject_lua_code(lua_code) | Create Pure Shape |
10,587 | def batch(batch_size, items):
"Batch items into groups of batch_size"
items = list(items)
if batch_size is None:
return [items]
MISSING = object()
padded_items = items + [MISSING] * (batch_size - 1)
groups = zip(*[padded_items[i::batch_size] for i in range(batch_size)])
return [[item... | Batch items into groups of batch_size |
10,588 | def get_icohp_dict_by_bondlengths(self, minbondlength=0.0, maxbondlength=8.0):
newicohp_dict = {}
for value in self._icohplist.values():
if value._length >= minbondlength and value._length <= maxbondlength:
newicohp_dict[value._label] = value
return newicohp_... | get a dict of IcohpValues corresponding to certaind bond lengths
Args:
minbondlength: defines the minimum of the bond lengths of the bonds
maxbondlength: defines the maximum of the bond lengths of the bonds
Returns:
dict of IcohpValues, the keys correspond to the val... |
10,589 | def wite_to_json(self, dir_path="", file_name=""):
data = {
"plot_data": self.record_thread.profile_data,
"method_exec_info": self.method_exec_info,
"search_file": self.search_file,
"source_file": self.source_file}
file_path = os... | 将性能数据写入文件. |
10,590 | def modify_document(self, doc):
if self._lifecycle_handler.failed:
return
if self._theme is not None:
doc.theme = self._theme
if self._template is not None:
doc.template = self._template
self._main_handler.modify_d... | Execute the configured ``main.py`` or ``main.ipynb`` to modify the
document.
This method will also search the app directory for any theme or
template files, and automatically configure the document with them
if they are found. |
10,591 | def getboolean_optional(self, section, option, default=False):
try:
return self.getboolean(section, option)
except (configparser.NoSectionError, configparser.NoOptionError):
return default | Get an option boolean value for a given section
If the section or the option are not found, the default value is returned
:param section: config section
:param option: config option
:param default: default value
:returns: boolean config value |
10,592 | def generate_fault_source_model(self):
source_model = []
model_weight = []
for iloc in range(0, self.get_number_mfd_models()):
model_mfd = EvenlyDiscretizedMFD(
self.mfd[0][iloc].min_mag,
self.mfd[0][iloc].bin_width,
self.mfd[0... | Creates a resulting `openquake.hmtk` fault source set.
:returns:
source_model - list of instances of either the :class:
`openquake.hmtk.sources.simple_fault_source.mtkSimpleFaultSource`
or :class:
`openquake.hmtk.sources.complex_fault_source.mtkComplexFaultSource... |
10,593 | def to_str(data):
if isinstance(data, bytes):
return codecs.decode(data, aws_encryption_sdk.internal.defaults.ENCODING)
return data | Takes an input str or bytes object and returns an equivalent str object.
:param data: Input data
:type data: str or bytes
:returns: Data normalized to str
:rtype: str |
10,594 | def _deserialize(cls, key, value, fields):
converter = cls._get_converter_for_field(key, None, fields)
return converter.deserialize(value) | Marshal incoming data into Python objects. |
10,595 | def create(self, comment, mentions=()):
data = {
"app": self.app_id,
"record": self.record_id,
"comment": {
"text": comment,
}
}
if len(mentions) > 0:
_mentions = []
for m in mentions:
... | create comment
:param comment:
:param mentions: list of pair of code and type("USER", "GROUP", and so on)
:return: |
10,596 | def get_vulnerability_chains(
current_node,
sink,
def_use,
chain=[]
):
for use in def_use[current_node]:
if use == sink:
yield chain
else:
vuln_chain = list(chain)
vuln_chain.append(use)
yield from get_vulnerability_chains(
... | Traverses the def-use graph to find all paths from source to sink that cause a vulnerability.
Args:
current_node()
sink()
def_use(dict):
chain(list(Node)): A path of nodes between source and sink. |
10,597 | def get_edge_values(self, feature=):
elist = []
for cidx in self._coords.edges[:, 1]:
node = self.treenode.search_nodes(idx=cidx)[0]
elist.append(
(node.__getattribute__(feature) if hasattr(node, feature) else "")
)
return elist | Returns edge values in the order they are plotted (see .get_edges()) |
10,598 | def _log_A_0(params, freq, recency, age):
r, alpha, s, beta = params
if alpha < beta:
min_of_alpha_beta, max_of_alpha_beta, t = (alpha, beta, r + freq)
else:
min_of_alpha_beta, max_of_alpha_beta, t = (beta, alpha, s + 1)
abs_alpha_beta = max_of_alpha_bet... | log_A_0. |
10,599 | def tangle(*args, **kwargs):
class_attrs = {
"_links": [],
"_dlinks": [],
"_derived": {}
}
for value in args:
if isinstance(value, function):
class_attrs[key] = traitlet_cls(*traitlet_args, **traitlet_kwargs)
new_class = type(
.for... | Shortcut to create a new, custom Tangle model. Use instead of directly
subclassing `Tangle`.
A new, custom Widget class is created, with each of `kwargs` as a traitlet.
Returns an instance of the new class with default values.
`kwargs` options
- primitive types (int, bool, float) will be created ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.