Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
345,300 | def determine_inst(i_info, param_str, command):
qty_instances = len(i_info)
if not qty_instances:
print("No instances found with parameters: {}".format(param_str))
sys.exit(1)
if qty_instances > 1:
print("{} instances match these parameters:".format(qty_instances))
tar_... | Determine the instance-id of the target instance.
Inspect the number of instance-ids collected and take the
appropriate action: exit if no ids, return if single id,
and call user_picklist function if multiple ids exist.
Args:
i_info (dict): information and details for instances.
param_... |
345,301 | def count(self, *columns):
if not columns and self.distinct_:
columns = self.columns
if not columns:
columns = ["*"]
return int(self.aggregate("count", *columns)) | Retrieve the "count" result of the query
:param columns: The columns to get
:type columns: tuple
:return: The count
:rtype: int |
345,302 | def poll(self):
if self._subprocess is not None:
self._subprocess.poll()
time.sleep(self._beaver_config.get()) | Poll attached subprocess until it is available |
345,303 | def upload_profiler_report(url, filename, config):
try:
logger.debug("Uploading profiler report to IOpipe")
with open(filename, "rb") as data:
response = requests.put(url, data=data, timeout=config["network_timeout"])
response.raise_for_status()
except Exception as e:
... | Uploads a profiler report to IOpipe
:param url: The signed URL
:param filename: The profiler report file
:param config: The IOpipe config |
345,304 | def add_blueprint(self, blueprint, **options):
instance = werkzeug.utils.import_string(blueprint)
self._blueprints.append((instance, options)) | Specify a blueprint to be registered with the application.
Additional options will be passed to :meth:`~Flask.register_blueprint`
when the application is created.
.. code-block:: python
factory = Factory()
factory.add_blueprint('myapp.views:blueprint', url_prefix='/fo... |
345,305 | def remove_node(self, node):
pending = self.node2pending.pop(node)
if not pending:
return
crashitem = self.collection[pending.pop(0)]
self.pending.extend(pending)
for node in self.node2pending:
self.check_schedule(node)
return cr... | Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
``DSession.worker_errordown`` hooks.
... |
345,306 | def console_set_color_control(
con: int, fore: Tuple[int, int, int], back: Tuple[int, int, int]
) -> None:
lib.TCOD_console_set_color_control(con, fore, back) | Configure :any:`color controls`.
Args:
con (int): :any:`Color control` constant to modify.
fore (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
back (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color in... |
345,307 | def action_is_greedy(action, isoptional=False):
num_consumed_args = _num_consumed_args.get(action, 0)
if action.option_strings:
if not isoptional and not action_is_satisfied(action):
return True
return action.nargs == REMAINDER
else:
return action.nargs == REMAINDER... | Returns True if action will necessarily consume the next argument.
isoptional indicates whether the argument is an optional (starts with -). |
345,308 | def fillout_factor(b, component, solve_for=None, **kwargs):
hier = b.get_hierarchy()
if not len(hier.get_value()):
raise NotImplementedError("constraint for requiv_contact_max requires hierarchy")
component_ps = _get_system_ps(b, component)
parentorbit = hier.get_parent... | Create a constraint to determine the fillout factor of a contact envelope.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'requiv_max' should not be the derived/constrain... |
345,309 | def sell(self, no, price, value):
self.money += price*value
try:
self.store[no] += -value
except:
self.store[no] = -value
try:
self.avgprice[no][] += [price]
except:
try:
self.avgprice[no][] = [price]
except:
self.avgprice[no] = {}
self.avgp... | 賣 |
345,310 | def _assemble_complex(self, stmt):
complex_data, _ = _get_complex_node(stmt.members)
if complex_data is None:
logger.info(, stmt.members)
return
self.model.add_node_from_data(complex_data) | Example: complex(p(HGNC:MAPK14), p(HGNC:TAB1)) |
345,311 | def class_filter(classes, class_name):
result_classes = classes
if isinstance(class_name, list):
if set(class_name) <= set(classes):
result_classes = class_name
return result_classes | Filter classes by comparing two lists.
:param classes: matrix classes
:type classes: list
:param class_name: sub set of classes
:type class_name : list
:return: filtered classes as list |
345,312 | def get_locals(cls, session):
return cls.find(session,
where=(cls.local == True,)) | Get all local packages.
:param session: SQLAlchemy session
:type session: :class:`sqlalchemy.Session`
:return: package instances
:rtype: generator of :class:`pyshop.models.Package` |
345,313 | def parse_args():
usage = "Usage: create_concordance <infile> [<outfile>]"
description = "Simple Concordance Generator"
argparser = argparse.ArgumentParser(
usage=usage, description=description)
argparser.add_argument(
, type=argparse.FileType(),
help="File read in to creat... | Parses command line args using argparse library |
345,314 | def tzolkin_generator(number=None, name=None):
number = number or 13
name = name or "Ajaw"
if number > 13:
raise ValueError("Invalid day number")
if name not in TZOLKIN_NAMES:
raise ValueError("Invalid day name")
count = _tzolkin_count(number, name)
ranged = iterto... | For a given tzolkin name/number combination, return a generator
that gives cycle, starting with the input |
345,315 | def _pdf(self, xloc, cache, **kwargs):
floc = numpy.zeros(xloc.shape)
for dist in evaluation.sorted_dependencies(self, reverse=True):
if dist not in self.inverse_map:
continue
idx = self.inverse_map[dist]
xloc_ = xloc[idx].reshape(1, -1)
... | Example:
>>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal())
>>> print(numpy.around(dist.pdf([[-0.5, 0.5, 1.5], [-1, 0, 1]]), 4))
[0. 0.3989 0. ]
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy.Uniform())
>>> print(dist.... |
345,316 | def to_text(self):
message =
last_was_text = False
for m in self.message:
if last_was_text and not isinstance(m, Text):
message +=
message += m.to_text()
if isinstance(m, Text):
last_was_text = True
else... | Render a MessageElement queue as plain text.
:returns: Plain text representation of the message.
:rtype: str |
345,317 | def add_submenu(self, grid_lang, ass, row, column):
text = "Available subassistants:\n"
path = []
(menu, text) = self.generate_menu(ass, text, path=path)
menu.show_all()
if ass[0].description:
description = self.get_formatted_description(ass[0].descr... | The function is used for creating button with menu and submenu.
Also signal on tooltip and signal on clicked are specified
Button is add to the Gtk.Grid |
345,318 | def start(self, positionals=None):
bot.info( %(self.name))
self.speak()
self._start(positionals) | start the helper flow. We check helper system configurations to
determine components that should be collected for the submission.
This is where the client can also pass on any extra (positional)
arguments in a list from the user. |
345,319 | def load(self, path):
config = _Config.load(os.path.join(path, ))
config.save_dir = path
self._vocab = vocab = ParserVocabulary.load(config.save_vocab_path)
with mx.Context(mxnet_prefer_gpu()):
self._parser = BiaffineParser(vocab, config.word_dims, config.tag_dims,... | Load from disk
Parameters
----------
path : str
path to the directory which typically contains a config.pkl file and a model.bin file
Returns
-------
DepParser
parser itself |
345,320 | def declare_const(self, id_, lineno, type_, default_value):
if not self.check_is_undeclared(id_, lineno, scope=self.current_scope, show_error=False):
entry = self.get_entry(id_)
if entry.scope == SCOPE.parameter:
syntax_error(lineno,
... | Similar to the above. But declares a Constant. |
345,321 | def _bar(self, serie, parent, x0, x1, y, i, zero, secondary=False):
x, y = self.view((x0, y))
x1, _ = self.view((x1, y))
width = x1 - x
height = self.view.y(zero) - y
series_margin = width * self._series_margin
x += series_margin
width -= 2 * series_margi... | Internal bar drawing function |
345,322 | def _name_variation_has_only_initials(name):
def _is_initial(name_variation):
return len(name_variation) == 1 or u in name_variation
parsed_name = ParsedName.loads(name)
return all([_is_initial(name_part) for name_part in parsed_name]) | Detects whether the name variation consists only from initials. |
345,323 | def build_from_energy_dict(cls, ebin_name, input_dict):
psf_types = input_dict.pop()
output_list = []
for psf_type, val_dict in sorted(psf_types.items()):
fulldict = input_dict.copy()
fulldict.update(val_dict)
fulldict[] = psf_type
fulldic... | Build a list of components from a dictionary for a single energy range |
345,324 | def lookup_pokemon(field,value,pokemons=None):
if pokemons == None:
pokemons = catch_em_all()
catches = {}
for pid,data in pokemons.items():
if isinstance(data[field],list):
for entry in data[field]:
found = search_entry(entry,value)
... | lookup_pokemon will search a particular field (name) for a value. If no pokemons
data structure is provided, all will be used.
:param field: the field to look up.
:param pokemons: the pokemons data structure |
345,325 | def _node_has_variant(node: BaseEntity, variant: str) -> bool:
return VARIANTS in node and any(
variant_dict[KIND] == variant
for variant_dict in node[VARIANTS]
) | Return true if the node has at least one of the given variant.
:param variant: :data:`PMOD`, :data:`HGVS`, :data:`GMOD`, or :data:`FRAGMENT` |
345,326 | def classes(self):
defclass = lib.EnvGetNextDefclass(self._env, ffi.NULL)
while defclass != ffi.NULL:
yield Class(self._env, defclass)
defclass = lib.EnvGetNextDefclass(self._env, defclass) | Iterate over the defined Classes. |
345,327 | def upload(self, release, filename, content_type=None):
release = self.as_id(release)
name = os.path.basename(filename)
if not content_type:
content_type, _ = mimetypes.guess_type(name)
if not content_type:
raise ValueError()
inputs = {: name}
... | Upload a file to a release
:param filename: filename to upload
:param content_type: optional content type
:return: json object from github |
345,328 | def _defer_to_worker(deliver, worker, work, *args, **kwargs):
deferred = Deferred()
def wrapped_work():
try:
result = work(*args, **kwargs)
except BaseException:
f = Failure()
deliver(lambda: deferred.errback(f))
else:
deliver(lambda:... | Run a task in a worker, delivering the result as a ``Deferred`` in the
reactor thread. |
345,329 | def unmarshal(self, v):
if not isinstance(v, timedelta):
v = timedelta(seconds=v)
return v | Convert the value from parsed JSON structure to native python representation.
By default this will leave the value as-is since the JSON parsing routines
typically convert to native types. The exception may be date strings or other
more complex types, where subclasses will override this behavior... |
345,330 | def touch_empty_backreferences(app, what, name, obj, options, lines):
if not bool(app.config.sphinx_gallery_conf[]):
return
examples_path = os.path.join(app.srcdir,
app.config.sphinx_gallery_conf[
"backreferences_dir"],
... | Generate empty back-reference example files
This avoids inclusion errors/warnings if there are no gallery
examples for a class / module that is being parsed by autodoc |
345,331 | def create(self, data, fields=[], models={}):
if not fields: fields = self.fields
if not models and hasattr(self, ): models = self.models
for field in fields:
setattr(self,field,None)
if not data: return None
for k, v in data.iteritems():
if type(... | Create model attributes |
345,332 | def street_name(self):
pattern = self.random_element(self.street_name_formats)
return self.generator.parse(pattern) | :example 'Crist Parks' |
345,333 | def backward(self, gradient, image=None, strict=True):
assert self.has_gradient()
assert gradient.ndim == 1
if image is None:
image = self.__original_image
assert not strict or self.in_bounds(image)
self._total_gradient_calls += 1
gradient = self._... | Interface to model.backward for attacks.
Parameters
----------
gradient : `numpy.ndarray`
Gradient of some loss w.r.t. the logits.
image : `numpy.ndarray`
Single input with shape as expected by the model
(without the batch dimension).
Returns... |
345,334 | def __edges_between_two_vertices(self, vertex1, vertex2, keys=False):
for vertex in vertex1, vertex2:
if vertex not in self.bg:
raise ValueError("Supplied vertex ({vertex_name}) is not present in current BreakpointGraph"
"".format(vertex_name... | Iterates over edges between two supplied vertices in current :class:`BreakpointGraph`
Checks that both supplied vertices are present in current breakpoint graph and then yield all edges that are located between two supplied vertices.
If keys option is specified, then not just edges are yielded, but rat... |
345,335 | def filter_connection_params(queue_params):
CONNECTION_PARAMS = (, , ,
, , , ,
, , ,
, ,)
return dict((p,v) for (p,v) in queue_params.items() if p in CONNECTION_PARAMS) | Filters the queue params to keep only the connection related params. |
345,336 | def download_profile(self):
profile_file = os.path.join(self.output_path, )
size = 0
try:
stats = os.stat(profile_file)
size = stats.st_size
except FileNotFoundError:
pass
profile.write(decoded) | Download the profile from the database |
345,337 | def safe_indicator(self, indicator, errors=):
if indicator is not None:
try:
indicator = quote(self.s(str(indicator), errors=errors), safe=)
except KeyError:
indicator = quote(bytes(indicator), safe=)
return indicator | Indicator encode value for safe HTTP request.
Args:
indicator (string): Indicator to URL Encode
errors (string): The error handler type.
Returns:
(string): The urlencoded string |
345,338 | def execute(self):
default_locale = os.environ.get(, ).split()[0]
if default_locale not in AVAILABLE_LOCALES:
default_locale = DEFAULT_LOCALE
epilog = .format(.join(sorted(AVAILABLE_LOCALES)),
default_locale,
DEFAULT_LOCALE)
formatte... | Given the command-line arguments, this creates a parser appropriate
to that command, and runs it. |
345,339 | def set_metadata(self, container, metadata, clear=False, prefix=None):
if prefix is None:
prefix = CONTAINER_META_PREFIX
massaged = _massage_metakeys(metadata, prefix)
new_meta = {}
if clear:
curr_meta = self.api.get_container_metadata(container,... | Accepts a dictionary of metadata key/value pairs and updates the
specified container metadata with them.
If 'clear' is True, any existing metadata is deleted and only the
passed metadata is retained. Otherwise, the values passed here update
the container's metadata.
By default,... |
345,340 | def build_act(make_obs_ph, q_func, num_actions, scope="deepq", reuse=None):
with tf.variable_scope(scope, reuse=reuse):
observations_ph = make_obs_ph("observation")
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update... | Creates the act function:
Parameters
----------
make_obs_ph: str -> tf.placeholder or TfInput
a function that take a name and creates a placeholder of input with that name
q_func: (tf.Variable, int, str, bool) -> tf.Variable
the model that takes the following inputs:
observa... |
345,341 | def shutdown(self):
self.socket.shutdown()
if scoop:
if scoop.DEBUG:
from scoop import _debug
_debug.writeWorkerDebug(
scoop._control.debug_stats,
scoop._control.QueueLength,
) | Shutdown the ressources used by the queue |
345,342 | def login(self, username, password, application, application_url):
logger.debug(str((username, application, application_url)))
method = self._anaconda_client_api.authenticate
return self._create_worker(method, username, password, application,
applicati... | Login to anaconda cloud. |
345,343 | def patch_gevent_hub():
from gevent.hub import Hub
def patched_handle_error(self, context, etype, value, tb):
if isinstance(value, str):
value = etype(value)
not_error = issubclass(etype, self.NOT_ERROR)
system_error = issubclass(etype, self.SYSTEM_ERROR)
... | This patches the error handler in the gevent Hub object. |
345,344 | def weld_merge_join(arrays_self, weld_types_self, arrays_other, weld_types_other,
how, is_on_sorted, is_on_unique, readable_text):
assert is_on_unique
weld_obj_vec_of_struct_self = weld_arrays_to_vec_of_struct(arrays_self, weld_types_self)
weld_obj_vec_of_struct_other = weld_arrays... | Applies merge-join on the arrays returning indices from each to keep in the resulting
Parameters
----------
arrays_self : list of (numpy.ndarray or WeldObject)
Columns from the self DataFrame on which to join.
weld_types_self : list of WeldType
Corresponding Weld types.
arrays_other... |
345,345 | def scan_file(fullpath, relpath):
load_metafile.cache_clear()
meta = load_metafile(fullpath)
if not meta:
return True
category = meta.get(, utils.get_category(relpath))
values = {
: category,
: fullpath,
: meta.get(, )
}
logger.debug("setting cat... | scan a file and put it into the index |
345,346 | def enable_script(zap_helper, script_name):
with zap_error_handler():
console.debug(.format(script_name))
result = zap_helper.zap.script.enable(script_name)
if result != :
raise ZAPError(.format(result))
console.info(.format(script_name)) | Enable a script. |
345,347 | def resolve(self):
result = self._get_aws_variables()
for name, value in self.variables.items():
if name in self.shell_env_values:
value = self.shell_env_values[name]
if name in self.override_values:
... | Resolves the values from different sources and returns a dict of environment variables to use when running
the function locally.
:return dict: Dict where key is the variable name and value is the value of the variable. Both key and values
are strings |
345,348 | def __map_entity(self, entity: dal.AssetClass) -> AssetClass:
mapper = self.__get_mapper()
ac = mapper.map_entity(entity)
return ac | maps the entity onto the model object |
345,349 | def get_all_tags_no_auth(image_name, branch=None):
output = []
logging.debug( % image_name)
spec = % image_name
headers = {: ,
: }
try:
response = requests.get(API_URL + spec, headers=headers)
except RequestException, re:
raise DockerTagNamingExcep... | Try to get the tags without any authentication, this does work only for
public images.
GET /v1/repositories/<namespace>/<repository_name>/tags
:param image_name: The docker image name
:param branch: The branch to filter by
:return: A list of Version instances, latest first |
345,350 | def do_file_sub(self, srcpath, regexp, subst):
try:
path = self._get_dest_for_srcpath(srcpath)
self._log_debug("substituting scrpath " % srcpath)
self._log_debug("substituting for in "
% (subst, regexp, path))
if not path:
... | Apply a regexp substitution to a file archived by sosreport.
srcpath is the path in the archive where the file can be found. regexp
can be a regexp string or a compiled re object. subst is a string to
replace each occurance of regexp in the content of srcpath.
This function returns th... |
345,351 | def render_asset_html(self, path, tag_template):
url = os.path.join(settings.STATIC_URL, path)
return tag_template.format(url=url) | Render HTML tag for a given path.
Arguments:
path (string): Relative path from static directory.
tag_template (string): Template string for HTML tag.
Returns:
string: HTML tag with url from given path. |
345,352 | def parse_data(self, logfile):
for line in logfile:
stripped_line = line.strip()
parsed_line = Line(stripped_line)
if parsed_line.valid:
self._valid_lines.append(parsed_line)
else:
self._invalid_lines.append(stripped_line... | Parse data from data stream and replace object lines.
:param logfile: [required] Log file data stream.
:type logfile: str |
345,353 | def _run_job(self, job_n, job):
self.run_log.append({"job": job.as_dict(), "corrections": [],
"handler": None, "validator": None,
"max_errors": False, "max_errors_per_job": False,
"max_errors_per_handler": False,
... | Runs a single job.
Args:
job_n: job number (1 index)
job: Custodian job
Raises:
ValidationError: if a job fails validation
ReturnCodeError: if the process has a return code different from 0
NonRecoverableError: if an unrecoverable occurs
... |
345,354 | def _checkpath(self, path):
if path.startswith("/") or ".." in path or path.strip() != path:
raise NotFoundException() | Checks that a given path is valid. If it's not, raises NotFoundException |
345,355 | def press_event(self):
if self.mouse_event.press_event is None:
return None
ev = self.copy()
ev.mouse_event = self.mouse_event.press_event
return ev | The mouse press event that initiated a mouse drag, if any. |
345,356 | def _write(self, session, openFile, maskMap):
FIRST_VALUE_INDEX = 12
openFile.write()
if self.type == self.SCALAR_TYPE:
openFile.write(.format(self.objectType))
openFile.write()
elif self.type == self.VECTOR_TYPE:
openFile... | WMS Dataset File Write to File Method |
345,357 | def deletePerson(self, name):
self.organizer.deletePerson(self.organizer.personByName(name)) | Delete the person named C{name}
@param name: A person name.
@type name: C{unicode} |
345,358 | def provide(self, name):
rv = self[name]
return rv(self) if callable(rv) else rv | Gets the value registered with ``name`` and determines whether the
value is a provider or a configuration setting. The ``KeyError`` is
raised when the ``name`` is not found.
The registered value is interpreted as a provider if it's callable. The
provider is called with a single argument... |
345,359 | def _add(self, replace, section, name, *args):
if isinstance(name, (str, unicode)):
name = dns.name.from_text(name, None)
if isinstance(args[0], dns.rdataset.Rdataset):
for rds in args:
if replace:
self.delete(name, rds.rdtype)
... | Add records. The first argument is the replace mode. If
false, RRs are added to an existing RRset; if true, the RRset
is replaced with the specified contents. The second
argument is the section to add to. The third argument
is always a name. The other arguments can be:
... |
345,360 | def record_present(name, zone, type, data, profile):
zones = __salt__[](profile)
try:
matching_zone = [z for z in zones if z[] == zone][0]
except IndexError:
return state_result(False, , name)
records = __salt__[](matching_zone[], profile)
matching_records = [record for record i... | Ensures a record is present.
:param name: Record name without the domain name (e.g. www).
Note: If you want to create a record for a base domain
name, you should specify empty string ('') for this
argument.
:type name: ``str``
:param zone: Zone where the... |
345,361 | def user_auth(
self,
cloudflare_email=None,
cloudflare_pass=None,
unique_id=None
):
if not (cloudflare_email and cloudflare_pass) and not unique_id:
raise KeyError(
)
params = {: }
if cloudflare_email and cloudflare... | Get user_key based on either his email and password or unique_id.
:param cloudflare_email: email associated with user
:type cloudflare_email: str
:param cloudflare_pass: pass associated with user
:type cloudflare_pass: str
:param unique_id: unique id asso... |
345,362 | def delete_term(set_id, term_id, access_token):
api_call(, .format(set_id, term_id), access_token=access_token) | Delete the given term. |
345,363 | def verify_request(self):
if flask_request.method == :
params = flask_request.form.to_dict()
else:
params = flask_request.args.to_dict()
log.debug(params)
log.debug()
try:
verify_request_common(self._consumers(), flask_request.url,
... | Verify LTI request
:raises: LTIException is request validation failed |
345,364 | def _run(self, keep_successfull):
self._dlog("interpreting template")
try:
res = self._handle_node(se... | Interpret the parsed 010 AST
:returns: PfpDom |
345,365 | def publickey_unsafe(sk: bytes) -> bytes:
h = H(sk)
a = decodecoord(h)
A = scalarmult_B(a)
return encodepoint(A) | Not safe to use with secret keys or secret data.
See module docstring. This function should be used for testing only. |
345,366 | def _pixelsize(self, p):
xpixelsize = 1./float(p.xdensity)
ypixelsize = 1./float(p.ydensity)
return max([xpixelsize,ypixelsize]) | Calculate line width necessary to cover at least one pixel on all axes. |
345,367 | def is_active(feature):
if current_app:
feature_flagger = current_app.extensions.get(EXTENSION_NAME)
if feature_flagger:
return feature_flagger.check(feature)
else:
raise AssertionError("Oops. This application doesnre running outside the request context. Check your setup. Returning False".... | Check if a feature is active |
345,368 | def serialize(obj, no_dump=False):
if hasattr(obj, "serialize") and isinstance(obj.serialize, collections.Callable):
o_dict = {
: "%s.%s" % (obj.__class__.__module__, obj.__class__.__name__),
: obj.serialize()
}
elif isinstance(obj, dict):
o_dict = {}
... | Serialize an object.
Returns a dict containing an `_error` property if a MemoryError happens during the
object serialization. See #369.
:param obj: the object to serialize
:type obj: alignak.objects.item.Item | dict | list | str
:param no_dump: if True return dict, otherwise return a json
:typ... |
345,369 | def prompt_config(sch, defaults=None, path=None):
out = {}
for name, attr in sch.attributes():
fullpath = name
if path:
fullpath = .format(path, name)
if defaults is None:
defaults = {}
default = defaults.get(name)
if isinstance(attr, _schema.... | Utility function to recursively prompt for config values
Arguments:
- defaults<dict>: default values used for empty inputs
- path<str>: path to prepend to config keys (eg. "path.keyname") |
345,370 | def _is_known_unsigned_by_dtype(dt):
return {
tf.bool: True,
tf.uint8: True,
tf.uint16: True,
}.get(dt.base_dtype, False) | Helper returning True if dtype is known to be unsigned. |
345,371 | def get_pegasus_to_nice_fn(*args, **kwargs):
if args or kwargs:
warnings.warn("Deprecation warning: get_pegasus_to_nice_fn does not need / use parameters anymore")
def p2n0(u, w, k, z): return (0, w-1 if u else z, z if u else w, u, k-4 if u else k-4)
def p2n1(u, w, k, z): return (1, w-1 if u el... | Returns a coordinate translation function from the 4-term pegasus_index
coordinates to the 5-term "nice" coordinates.
Details on the returned function, pegasus_to_nice(u,w,k,z)
Inputs are 4-tuples of ints, return is a 5-tuple of ints. See
pegasus_graph for description of the pegasus_index and ... |
345,372 | def _load_json_url(self, url):
res = requests.get(url)
res.raise_for_status()
return res.json() | dict: Return the JSON at the local path or URL as a dict. |
345,373 | def vcmp_host(opt_vcmp_host, opt_username, opt_password, opt_port):
m = ManagementRoot(
opt_vcmp_host, opt_username, opt_password, port=opt_port)
return m | vcmp fixture |
345,374 | def parsecapp(self, other):
return self.bind(lambda res: other.parsecmap(lambda x: res(x))) | Returns a parser that applies the produced value of this parser to the produced value of `other`. |
345,375 | def random_shift(x, pad=(4, 4), mode=):
assert mode in .split()
assert x.get_shape().ndims == 3
xp = tf.pad(x, [[pad[0], pad[0]], [pad[1], pad[1]], [0, 0]], mode)
return tf.random_crop(xp, tf.shape(x)) | Pad a single image and then crop to the original size with a random
offset. |
345,376 | def argv(self, module, argv=sys.argv[1:]):
kwargs = {: False}
last_priority = {}
parser = argparse.ArgumentParser(add_help=False)
parser.short_to_long = {}
for m in self.list(attribute="CLI"):
... | Processes argv for any options specific to the specified module.
@module - The module to process argv for.
@argv - A list of command line arguments (excluding argv[0]).
Returns a dictionary of kwargs for the specified module. |
345,377 | def longest_increasing_subsequence(sequence):
length = len(sequence)
counts = [1 for _ in range(length)]
for i in range(1, length):
for j in range(0, i):
if sequence[i] > sequence[j]:
counts[i] = max(counts[i], counts[j] + 1)
print(counts)
return ... | Dynamic Programming Algorithm for
counting the length of longest increasing subsequence
type sequence: List[int] |
345,378 | def write_vcf(path, callset, rename=None, number=None, description=None,
fill=None, write_header=True):
names, callset = normalize_callset(callset)
with open(path, ) as vcf_file:
if write_header:
write_vcf_header(vcf_file, names, callset=callset, rename=rename,
... | Preliminary support for writing a VCF file. Currently does not support sample data.
Needs further work. |
345,379 | def _append_separations_to_results(
self):
self.log.info()
for row in self.results:
if "ra" not in row:
print row
exit(0)
calculator = separations(
log=self.log,
ra1=self.ra,
... | *append angular separations to results*
**Key Arguments:**
# -
**Return:**
- None
.. todo:: |
345,380 | def restore(self, name, value, pttl=0):
with self.pipe as pipe:
res = pipe.restore(self.redis_key(name), ttl=pttl, value=value)
f = Future()
def cb():
f.set(self.valueparse.decode(res.result))
pipe.on_execute(cb)
return f | Restore serialized dump of a key back into redis
:param name: the name of the key
:param value: the binary representation of the key.
:param pttl: milliseconds till key expires
:return: |
345,381 | def orthographic_syllabify(self, word):
p_vectors = [self.get_phonetic_feature_vector(c, self.lang) for c in word]
syllables = []
for i in range(len(word)):
v = p_vectors[i]
syllables.append(word[i])
if i + 1 < len(word) and (not self.is_valid(p_v... | Main syllablic function. |
345,382 | def set(self, block, name, value):
self._kvs.set(self._key(block, name), value) | Set the value of the field named `name` |
345,383 | def get_nln_constraint(self, name):
for c in self.nln_constraints:
if c.name == name:
return c
else:
raise ValueError | Returns the constraint set with the given name. |
345,384 | def lookup_cc_partner(nu_pid):
neutrino_type = math.fabs(nu_pid)
assert neutrino_type in [12, 14, 16]
cc_partner = neutrino_type - 1
cc_partner = math.copysign(
cc_partner, nu_pid)
cc_partner = int(cc_partner)
return cc_partner | Lookup the charge current partner
Takes as an input neutrino nu_pid is a PDG code, then returns
the charged lepton partner. So 12 (nu_e) returns 11. Keeps sign |
345,385 | def build_flat_msg(self,
id=None,
msg=None):
flat_msg = {}
if not id:
log.error("Please pass in an id")
return None
if not msg:
log.error("Please pass in a msg")
return None
for k in... | build_flat_msg
:param id: unique id for this message
:param msg: message dictionary to flatten |
345,386 | def handle_lines(self):
while "\r\n" in self.buffer:
line, self.buffer = self.buffer.split("\r\n", 1)
if valid_packet(line):
self.handle_raw_packet(line)
else:
log.warning(, line) | Assemble incoming data into per-line packets. |
345,387 | def _multi_deletion(model, entity, element_lists, method="fba",
solution=None, processes=None, **kwargs):
solver = sutil.interface_to_str(model.problem.__name__)
if method == "moma" and solver not in sutil.qp_solvers:
raise RuntimeError(
"Cannot use MOMA since is no... | Provide a common interface for single or multiple knockouts.
Parameters
----------
model : cobra.Model
The metabolic model to perform deletions in.
entity : 'gene' or 'reaction'
The entity to knockout (``cobra.Gene`` or ``cobra.Reaction``).
element_lists : list
List of itera... |
345,388 | def get_job_and_task_param(job_params, task_params, field):
return job_params.get(field, set()) | task_params.get(field, set()) | Returns a dict combining the field for job and task params. |
345,389 | def errno_from_exception(e: BaseException) -> Optional[int]:
if hasattr(e, "errno"):
return e.errno
elif e.args:
return e.args[0]
else:
return None | Provides the errno from an Exception object.
There are cases that the errno attribute was not set so we pull
the errno out of the args but if someone instantiates an Exception
without any args you will get a tuple error. So this function
abstracts all that behavior to give you a safe way to get the
... |
345,390 | def object_put(self, file, **kwargs):
body, headers = multipart.stream_files(file, self.chunk_size)
return self._client.request(, decoder=,
data=body, headers=headers, **kwargs) | Stores input as a DAG object and returns its key.
.. code-block:: python
>>> c.object_put(io.BytesIO(b'''
... {
... "Data": "another",
... "Links": [ {
... "Name": "some link",
... "Ha... |
345,391 | def view_entries(search_query=None):
if search_query:
expr = Entry.content.search(search_query)
else:
expr = None
query = Entry.query(expr, order_by=Entry.timestamp.desc())
for entry in query:
timestamp = entry.timestamp.strftime()
print(timestamp)
print( * ... | View previous entries |
345,392 | def get_root_path(import_name):
mod = sys.modules.get(import_name)
if mod is not None and hasattr(mod, ):
return os.path.dirname(os.path.abspath(mod.__file__))
loader = pkgutil.get_loader(import_name)
filepath = loader.get_filename(import_name)
else:
... | Returns the path to a package or cwd if that cannot be found. This
returns the path of a package or the folder that contains a module.
Not to be confused with the package path returned by :func:`find_package`. |
345,393 | def query_mongo(
database_name,
collection_name,
query={},
include_num_results="0",
skip=0,
sort=None,
limit=getattr(
settings,
,
200),
cast_strings_to_integers=False,
return_keys=()):
l = []
respon... | return a response_dict with a list of search results |
345,394 | def format(self, record):
return {
: int(float(record.created or time.time()) * 1000),
: record.msg or ,
: record.levelname or ,
} | Format log record for ThreatConnect API.
Example log event::
[{
"timestamp": 1478907537000,
"message": "Test Message",
"level": "DEBUG"
}] |
345,395 | def find_first_TP(self):
star_mass = self.get()
he_lumi = self.get()
h_lumi = self.get()
mx2_bot = self.get()*star_mass
try:
h1_boundary_mass = self.get()
he4_boundary_mass = self.get()
except:
... | Find first TP of the TPAGB phase and returns the model
number at its LHe maximum.
Parameters
---------- |
345,396 | def from_(self) -> Optional[Sequence[AddressHeader]]:
try:
return cast(Sequence[AddressHeader], self[b])
except KeyError:
return None | The ``From`` header. |
345,397 | def undefinedImageType(self):
if self._undefinedImageType is None:
ctx = SparkContext._active_spark_context
self._undefinedImageType = \
ctx._jvm.org.apache.spark.ml.image.ImageSchema.undefinedImageType()
return self._undefinedImageType | Returns the name of undefined image type for the invalid image.
.. versionadded:: 2.3.0 |
345,398 | def _modify_report(summary_path, out_dir):
summary_path = op.abspath(summary_path)
template = op.normpath(op.join(op.dirname(op.realpath(template_seqcluster.__file__)), "report.rmd"))
content = open(template).read()
out_content = string.Template(content).safe_substitute({: summary_path})
out_fi... | Read Rmd template and dump with project path. |
345,399 | def sql(self, stringname, *args, **kwargs):
if hasattr(self, ):
return getattr(self.alchemist, stringname)(*args, **kwargs)
else:
s = self.strings[stringname]
return self.connection.cursor().execute(
s.format(**kwargs) if kwargs else s, args
... | Wrapper for the various prewritten or compiled SQL calls.
First argument is the name of the query, either a key in
``sqlite.json`` or a method name in
``allegedb.alchemy.Alchemist``. The rest of the arguments are
parameters to the query. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.