Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
350,800 | def process_prefix(self, prefix: str) -> Union[Namespace, None]:
if self.namespaces.get(prefix):
return self.namespaces[prefix]
iri: str = common_namespaces.get(prefix)
if iri:
return self.add_namespace(prefix, iri) | Add namespace to graph if it has a local match
This allows qnames to be used without adding their respected namespaces if they are in
the common_namespaces local dict. This is is to save a butt-ton of time trying to see what
the ontology has as far as uris go.
Args: prefix: prefix of t... |
350,801 | def _get_msg_class(code):
msg_classes = {}
msg_classes = _add_msg_class(msg_classes,
MESSAGE_STANDARD_MESSAGE_RECEIVED_0X50,
StandardReceive)
msg_classes = _add_msg_class(msg_classes,
MESSAGE_EXTENDED_MES... | Get the message class based on the message code. |
350,802 | def angle(x0, y0, x1, y1):
return degrees(atan2(y1-y0, x1-x0)) | Returns the angle between two points. |
350,803 | def create_postgresql_pg8000(self, **kwargs):
return self._ce(
self._ccs(self.DialectAndDriver.psql_pg8000), **kwargs
) | :rtype: Engine |
350,804 | def kill_processes(self):
LOGGER.critical()
processes = self.active_processes(False)
while processes:
for proc in self.active_processes(False):
if int(proc.pid) != int(os.getpid()):
LOGGER.warning(, proc.name, proc.pid)
... | Gets called on shutdown by the timer when too much time has gone by,
calling the terminate method instead of nicely asking for the consumers
to stop. |
350,805 | def make_fields_unique(self, fields):
for i in range(0, len(fields)):
for j in range(i+1, len(fields)):
if fields[i] == fields[j]:
fields[j] += "'" | iterates over the row and make each field unique |
350,806 | def _casual_timedelta_string(meeting):
now = datetime.datetime.utcnow()
mdate = meeting[]
mtime = meeting[]
dt_string = "%s %s" % (mdate, mtime)
meeting_dt = datetime.datetime.strptime(dt_string, "%Y-%m-%d %H:%M:%S")
relative_td = dateutil.relativedelta.relativedelta(meeting_dt, now)
... | Return a casual timedelta string.
If a meeting starts in 2 hours, 15 minutes, and 32 seconds from now, then
return just "in 2 hours".
If a meeting starts in 7 minutes and 40 seconds from now, return just "in 7
minutes".
If a meeting starts 56 seconds from now, just return "right now". |
350,807 | def _init_ns2nt(rcntobj):
go2dcnt = rcntobj.go2dcnt
ntobj = cx.namedtuple("NtD1", "D1 dcnt goobj")
d0s = rcntobj.depth2goobjs[0]
ns_nt = [(o.namespace, ntobj(D1="", dcnt=go2dcnt[o.id], goobj=o)) for o in d0s]
return cx.OrderedDict(ns_nt) | Save depth-00 GO terms ordered using descendants cnt. |
350,808 | def sqlite3_backup(src_path, dest_path):
sqlite3_path = sqlite3_find_tool()
if sqlite3_path is None:
log.error("Failed to find sqlite3 tool")
return False
sqlite3_cmd = [sqlite3_path, .format(src_path), .format(dest_path)]
rc = None
backoff = 1.0
out = None
err =... | Back up a sqlite3 database, while ensuring
that no ongoing queries are being executed.
Return True on success
Return False on error. |
350,809 | def get_name_from_name_consensus_hash( self, name_consensus_hash, sender_script_pubkey, block_id ):
import virtualchain_hooks
cur = self.db.cursor()
names = namedb_get_names_by_sender( cur, sender_script_pubkey, self.lastblock )
if names is None:
log.error(... | Find the name.ns_id from hash( name.ns_id, consensus_hash ), given the sender and
block_id, and assuming that name.ns_id is already registered.
There are only a small number of values this hash can take, so test all of them to
see if the hash matches one of them.
This is used for name ... |
350,810 | def deb_packages(attrs=None, where=None):
*
if __grains__[] == :
return _osquery_cmd(table=, attrs=attrs, where=where)
return {: False, : } | Return deb_packages information from osquery
CLI Example:
.. code-block:: bash
salt '*' osquery.deb_packages |
350,811 | def download_urls(self):
urls = {
tfds.Split.TRAIN: ["train_clean100"],
tfds.Split.VALIDATION: ["dev_clean"],
tfds.Split.TEST: ["test_clean"],
}
if self.data in ["all", "clean360"]:
urls[tfds.Split.TRAIN].append("train_clean360")
if self.data == "all":
urls[tfds.... | Returns download urls for this config. |
350,812 | def parse(gctx_file_path, convert_neg_666=True, rid=None, cid=None,
ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False):
full_path = os.path.expanduser(gctx_file_path)
if not os.path.exists(full_path):
err_msg = "The given path to the gctx file can... | Primary method of script. Reads in path to a gctx file and parses into GCToo object.
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to numpy.nan or not
(see Note belo... |
350,813 | def add_group_shape(self, shapes=[]):
grpSp = self._element.add_grpSp()
for shape in shapes:
grpSp.insert_element_before(shape._element, )
if shapes:
grpSp.recalculate_extents()
return self._shape_factory(grpSp) | Return a |GroupShape| object newly appended to this shape tree.
The group shape is empty and must be populated with shapes using
methods on its shape tree, available on its `.shapes` property. The
position and extents of the group shape are determined by the shapes
it contains; its posi... |
350,814 | def network_define(name, bridge, forward, **kwargs):
*
conn = __get_conn(**kwargs)
vport = kwargs.get(, None)
tag = kwargs.get(, None)
autostart = kwargs.get(, True)
starting = kwargs.get(, True)
net_xml = _gen_net_xml(
name,
bridge,
forward,
vport,
ta... | Create libvirt network.
:param name: Network name
:param bridge: Bridge name
:param forward: Forward mode(bridge, router, nat)
:param vport: Virtualport type
:param tag: Vlan tag
:param autostart: Network autostart (default True)
:param start: Network start (default True)
:param connect... |
350,815 | def filter_fixtures(all_fixtures: Iterable[Any],
fixtures_base_dir: str,
mark_fn: Callable[[str, str], bool]=None,
ignore_fn: Callable[..., bool]=None) -> Any:
import pytest
for fixture_data in all_fixtures:
fixture_path = fixture_data[... | Helper function for filtering test fixtures.
- `fixtures_base_dir` should be the base directory that the fixtures were collected from.
- `mark_fn` should be a function which either returns `None` or a `pytest.mark` object.
- `ignore_fn` should be a function which returns `True` for any fixture
which... |
350,816 | def real_time_statistics(self):
if self._real_time_statistics is None:
self._real_time_statistics = WorkspaceRealTimeStatisticsList(
self._version,
workspace_sid=self._solution[],
)
return self._real_time_statistics | Access the real_time_statistics
:returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList
:rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList |
350,817 | def stdout_result(cmd, expected_errors=(), shell=True, sudo=False, quiet=False):
which = operations.sudo if sudo else operations.run
with hide():
result = which(cmd, shell=shell, quiet=quiet, warn_only=True)
if result.return_code == 0:
return result
if result.return_code not in exp... | Runs a command and returns the result, that would be written to `stdout`, as a string. The output itself can
be suppressed.
:param cmd: Command to run.
:type cmd: unicode
:param expected_errors: If the return code is non-zero, but found in this tuple, it will be ignored. ``None`` is
returned in t... |
350,818 | def patch_thread(threading=True, _threading_local=True, Queue=True, Event=False):
monkey.patch_module()
if threading:
monkey.patch_module()
threading = __import__()
if Event:
from gevent.event import Event
threading.Event = Event
if Queue:
... | Replace the standard :mod:`thread` module to make it greenlet-based.
If *threading* is true (the default), also patch ``threading``.
If *_threading_local* is true (the default), also patch ``_threading_local.local``. |
350,819 | def experiments_get(self, resource_url):
obj_dir, obj_json, is_active, cache_id = self.get_object(resource_url)
experiment = ExperimentHandle(obj_json, self)
if not cache_id in self.cache:
self.cache_add(resource_url, cache_id)
... | Get handle for experiment resource at given Url.
Parameters
----------
resource_url : string
Url for experiment resource at SCO-API
Returns
-------
scoserv.ExperimentHandle
Handle for local copy of experiment resource |
350,820 | def raise_event(self, event_name, **kwargs):
handlers = list(self._event_handlers[event_name])
logger.debug(, event_name, handlers)
for func in handlers:
func(self, **kwargs) | Raise an event. Calls each handler in turn with kwargs
:param event_name: The name of the event to raise
:type event_name: str
:param kwargs: Kwargs to be passed to all event handlers |
350,821 | def parse_mode(mode, default_bitdepth=None):
if mode == :
return (grayscale, alpha, bitdepth) | Parse PIL-style mode and return tuple (grayscale, alpha, bitdeph) |
350,822 | def exec_command(
self,
command,
bufsize=-1,
timeout=None,
get_pty=False,
environment=None,
):
chan = self._transport.open_session(timeout=timeout)
if get_pty:
chan.get_pty()
chan.settimeout(timeout)
if environment:... | Execute a command on the SSH server. A new `.Channel` is opened and
the requested command is executed. The command's input and output
streams are returned as Python ``file``-like objects representing
stdin, stdout, and stderr.
:param str command: the command to execute
:param ... |
350,823 | def add_cms_link(self):
intnote = record_get_field_values(self.record, ,
filter_subfield_code="a",
filter_subfield_value=)
if intnote:
val_088 = record_get_field_values(self.record,
... | Special handling if record is a CMS NOTE. |
350,824 | def main():
cleanup_and_exit = sys.exit
exit_code = 0
main_pdfCropMargins.main_crop()
except (KeyboardInterrupt, EOFError):
print("\nGot a KeyboardInterrupt, cleaning up and exiting...\n",
file=sys.stderr)
except SystemExit:
exit_code = sys.exc... | Run main, catching any exceptions and cleaning up the temp directories. |
350,825 | def mk_derived_attribute(metaclass, o_dbattr):
o_attr = one(o_dbattr).O_BATTR[107].O_ATTR[106]()
o_obj = one(o_attr).O_OBJ[102]()
action = o_dbattr.Action_Semantics_internal
label = % (o_obj.Name, o_attr.Name)
fget = functools.partial(interpret.run_derived_attribute, metaclass,
... | Create a python property that interprets that action of a BridgePoint derived
attribute. |
350,826 | def search_definition(self, module, keyword, arg):
r = module.search_one(keyword, arg)
if r is not None:
return r
for i in module.search():
modulename = i.arg
m = self.ctx.search_module(i.pos, modulename)
if m is not None:
... | Search for a defintion with `keyword` `name`
Search the module and its submodules. |
350,827 | def get_object_from_classbased_instance(
instance, queryset, request, *args, **kwargs):
from django.views.generic.edit import BaseCreateView
instance.request = request
instance.args = args
instance.kwargs = kwargs
if hasattr(instance, ) and not queryset:
que... | Get object from an instance of classbased generic view
Parameters
----------
instance : instance
An instance of classbased generic view
queryset : instance
A queryset instance
request : instance
A instance of HttpRequest
Returns
-------
instance
An insta... |
350,828 | def is_clique(self, nodes):
for node1, node2 in itertools.combinations(nodes, 2):
if not self.has_edge(node1, node2):
return False
return True | Check if the given nodes form a clique.
Parameters
----------
nodes: list, array-like
List of nodes to check if they are a part of any clique.
Examples
--------
>>> from pgmpy.base import UndirectedGraph
>>> G = UndirectedGraph(ebunch=[('A', 'B'), ('... |
350,829 | def nside_to_pixel_area(nside):
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
npix = 12 * nside * nside
pixel_area = 4 * math.pi / npix * u.sr
return pixel_area | Find the area of HEALPix pixels given the pixel dimensions of one of
the 12 'top-level' HEALPix tiles.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
pixel_area : :class:`~astropy.units.Quantity`
... |
350,830 | def computePMF_states(self, u_n, bin_n, nbins):
for i in range(nbins):
if np.sum(bin_n == i) == 0:
raise ParameterError(
"At least one bin in provided bin_n argument has no samples. All bins must have samples for free energies to be fi... | Compute the free energy of occupying a number of bins.
This implementation defines each bin as a separate thermodynamic state.
Parameters
----------
u_n : np.ndarray, float, shape=(K, N)
u_n[n] is the reduced potential energy of snapshot n for which the PMF is to be compute... |
350,831 | def merge_pars(params, user_inputs, spec_pars, client=False, getenv=True,
getshell=True):
context = params.copy()
for par in spec_pars:
val = user_inputs.get(par.name, par.default)
if val is not None:
if isinstance(val, six.string_types):
val = exp... | Produce open arguments by merging various inputs
This function is called in the context of a catalog entry, when finalising
the arguments for instantiating the corresponding data source.
The three sets of inputs to be considered are:
- the arguments section of the original spec (params)
- UserPara... |
350,832 | def root(self, cls=None, level=0):
if cls is None:
if self.parent is None:
return self, level
else:
if isinstance(self, cls):
if not isinstance(self.parent, cls):
return self, level
if self.parent is None:
... | Returns the top-most HubComponent in the hierarchy.
If `cls` is not None, then return the top-most attribute HubComponent
that is an instance of class `cls`.
For a fully-constructed track hub (and `cls=None`), this should return
a a Hub object for every component in the hierarchy. |
350,833 | def get_allowed(allow, disallow):
if allow is None and disallow is None:
return SUMO_VEHICLE_CLASSES
elif disallow is None:
return allow.split()
else:
disallow = disallow.split()
return tuple([c for c in SUMO_VEHICLE_CLASSES if c not in disallow]) | Normalize the given string attributes as a list of all allowed vClasses. |
350,834 | def make_filename(traj):
explored_parameters = traj.f_get_explored_parameters()
filename =
for param in explored_parameters.values():
short_name = param.v_name
val = param.f_get()
filename += % (short_name, str(val))
return filename[:-2] + | Function to create generic filenames based on what has been explored |
350,835 | def _is_converted_class(java_class):
if not java_class:
return False
return (
JAVA_MAPS_PATTERN.match(java_class) is not None
or JAVA_LISTS_PATTERN.match(java_class) is not None
or JAVA_SETS_PATTERN.match(java_class) is not None
) | Checks if the given Java class is one we *might* have set up |
350,836 | def _run_sequence(self, sequence):
self._check_pause()
self._pre_test()
session_data = self.target.get_session_data()
self._test_info()
resp = None
for edge in sequence:
if edge.callback:
edge.callback(self, edge, resp)
ses... | Run a single sequence |
350,837 | def command(name=None):
def decorator(f):
_commands.append((name, f))
return f
return decorator | A decorator to register a subcommand with the global `Subcommands` instance. |
350,838 | def sinh(x, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_sinh,
(BigFloat._implicit_convert(x),),
context,
) | Return the hyperbolic sine of x. |
350,839 | def _build_cmd(self, args: Union[list, tuple]) -> str:
cmd = [self.path]
cmd.extend(args)
return cmd | Build command. |
350,840 | def hex_to_name(hex_value, spec=):
if spec not in SUPPORTED_SPECIFICATIONS:
raise TypeError(" is not a supported specification for color name lookups; supported specifications are: %s." % (spec,
... | Convert a hexadecimal color value to its corresponding normalized
color name, if any such name exists.
The optional keyword argument ``spec`` determines which
specification's list of color names will be used; valid values are
``html4``, ``css2``, ``css21`` and ``css3``, and the default is
``css3``.... |
350,841 | def _handle_typename(self, node, scope, ctxt, stream):
self._dlog("handling typename")
return self._handle_node(node.type, scope, ctxt, stream) | TODO: Docstring for _handle_typename
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO |
350,842 | def get_app():
from bottle import default_app
default_app.push()
for module in ("mongo_orchestration.apps.servers",
"mongo_orchestration.apps.replica_sets",
"mongo_orchestration.apps.sharded_clusters"):
__import__(module)
app = default_app.pop()
ret... | return bottle app that includes all sub-apps |
350,843 | def _get_course_content_from_ecommerce(course_id, site_code=None):
api = get_ecommerce_client(site_code=site_code)
try:
api_response = api.courses(course_id).get()
except Exception:
logger.exception(
,
course_id,
exc_info=True
)
retu... | Get course information using the Ecommerce course api.
In case of error returns empty response.
Arguments:
course_id (str): course key of the course
site_code (str): site code
Returns:
course information from Ecommerce |
350,844 | def start_worker(node_ip_address,
object_store_name,
raylet_name,
redis_address,
worker_path,
temp_dir,
stdout_file=None,
stderr_file=None):
command = [
sys.executable, "-u", worker_pa... | This method starts a worker process.
Args:
node_ip_address (str): The IP address of the node that this worker is
running on.
object_store_name (str): The socket name of the object store.
raylet_name (str): The socket name of the raylet server.
redis_address (str): The ad... |
350,845 | def init(self, id):
reserve = to_millis(TimeUnit.HOUR) << (FlakeIdGenerator._BITS_NODE_ID + FlakeIdGenerator._BITS_SEQUENCE)
return self.new_id().continue_with(lambda f: f.result() >= (id + reserve)) | This method does nothing and will simply tell if the next ID
will be larger than the given ID.
You don't need to call this method on cluster restart - uniqueness is preserved thanks to the
timestamp component of the ID.
This method exists to make :class:`~hazelcast.proxy.FlakeIdGenerator... |
350,846 | def unlock(self, passphrase, encrypted_seed=None):
wallet = self.resource
if not encrypted_seed:
encrypted_seed = wallet.primary_private_seed
try:
if encrypted_seed[]:
primary_seed = NaclPassphraseBox.decrypt(
passphrase, encry... | Unlock the Wallet by decrypting the primary_private_seed with the
supplied passphrase. Once unlocked, the private seed is accessible in
memory and calls to `account.pay` will succeed. This is a necessary step
for creating transactions.
Args:
passphrase (str): The passphrase th... |
350,847 | def clean_text(value, topic=False):
for x in PROFANITY_REPLACEMENTS:
value = value.replace(x[0], x[1])
for bbset in BBCODE_REPLACEMENTS:
p = re.compile(bbset[0], re.DOTALL)
value = p.sub(bbset[1], value)
bleached = bleach.clean(value, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTR... | Replaces "profane" words with more suitable ones.
Uses bleach to strip all but whitelisted html.
Converts bbcode to Markdown |
350,848 | def setLoggerLevel(self, logger, level):
if logger == :
_log = logging.getLogger()
else:
_log = logging.getLogger(logger)
_log.setLevel(level)
if level == logging.NOTSET:
self._loggerLevels.pop(logger, None)
... | Sets the level to log the inputed logger at.
:param logger | <str>
level | <int> |
350,849 | def set_data_dir(directory=None, create=False, save=False):
if directory is None:
directory = _data_path
if _data_path is None:
raise IOError(
)
if not op.isdir(directory):
if not create:
raise IOError(
% d... | Set vispy data download directory
Parameters
----------
directory : str | None
The directory to use.
create : bool
If True, create directory if it doesn't exist.
save : bool
If True, save the configuration to the vispy config. |
350,850 | def scale_from_matrix(matrix):
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
M33 = M[:3, :3]
factor = numpy.trace(M33) - 2.0
try:
w, V = numpy.linalg.eig(M33)
i = numpy.where(abs(numpy.real(w) - factor) < 1e-8)[0][0]
direction = numpy.real(V[:, i]).squeez... | Return scaling factor, origin and direction from scaling matrix.
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S0 = scale_matrix(factor, origin)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_m... |
350,851 | def _report_options(p):
_default_options(p, blacklist=[, , ])
p.add_argument(
, type=float, default=1,
help="Number of days of history to consider")
p.add_argument(
, type=argparse.FileType(),
help="Store raw json of collected records to given file path")
p.add_argum... | Add options specific to the report subcommand. |
350,852 | def _build_or_update_workflow(json_spec, args):
try:
if args.mode == :
json_spec = _get_validated_json(json_spec, args)
workflow_id = _build_regular_workflow(json_spec)
elif args.mode == :
existing_workflow = dxpy.executable_builder.... | Creates or updates a workflow on the platform.
Returns the workflow ID, or None if the workflow cannot be created. |
350,853 | def _claskey(obj, style):
i = id(obj)
k = _claskeys.get(i, None)
if not k:
_claskeys[i] = k = _Claskey(obj, style)
return k | Wrap an old- or new-style class object. |
350,854 | def ram_sdp_rf(clk, we, addrw, addrr, di, do):
memL = [Signal(intbv(0)[len(di):]) for _ in range(2**len(addrr))]
@always(clk.posedge)
def write():
if we:
memL[int(addrw)].next = di
do.next = memL[int(addrr)]
return write | RAM: Simple-Dual-Port, Read-First |
350,855 | def allButDOI(self):
extraTags = [, , , , ]
s = self.ID()
extras = []
for tag in extraTags:
if getattr(self, tag, False):
extras.append(str(getattr(self, tag)))
if len(extras) > 0:
return "{0}, {1}".format(s, .join(extras))
... | Returns a string of the normalized values from the Citation excluding the DOI number. Equivalent to getting the ID with [ID()](#metaknowledge.citation.Citation.ID) then appending the extra values from [Extra()](#metaknowledge.citation.Citation.Extra) and then removing the substring containing the DOI number.
#... |
350,856 | def _got_request_exception(self, sender, exception, **extra):
extra = self.summary_extra()
extra[] = 500
self.summary_logger.error(str(exception), extra=extra)
g._has_exception = True | The signal handler for the got_request_exception signal. |
350,857 | def convolve_array_1d_with_psf(self, padded_array_1d, psf):
padded_array_2d = mapping_util.map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape(
array_1d=padded_array_1d, shape=self.mask.shape)
blurred_padded_array_2d = psf.convolve(array=padded_array_2d)
retur... | Convolve a 1d padded array of values (e.g. intensities before PSF blurring) with a PSF, and then trim \
the convolved array to its original 2D shape.
Parameters
-----------
padded_array_1d: ndarray
A 1D array of values which were computed using the *PaddedRegularGrid*.
... |
350,858 | def cmd_tool(args=None):
if in local_host:
header_loc =
else:
raise IOError()
p = OptionParser()
p.set_usage()
opts, args = p.parse_args(sys.argv[1:])
file1 = args[0]
file2 = args[1]
make_batch_script()
headersize1 = find_header_size... | Command line tool to make a md5sum comparison of two .fil files. |
350,859 | def clean_except_files(self):
if self.is_finalized:
self.warn("Can---- Cleaning -------- Done Cleaning ----')
return True | Clean everything except the build source files |
350,860 | def ansi_cmd(cmd, *args):
try:
obj = getattr(ANSI, str(.format(cmd)))
except AttributeError:
raise ValueError(
"incorrect command: {!r}".format(cmd))
if isinstance(obj, type("")):
return obj
else:
return obj(*args) | Get ANSI command code by name. |
350,861 | def read(calc_id, username=None):
if isinstance(calc_id, str) or calc_id < 0 and not username:
return datastore.read(calc_id)
job = logs.dbcmd(, calc_id, username)
if job:
return datastore.read(job.ds_calc_dir + )
else:
return datastore.read(calc_i... | :param calc_id: a calculation ID
:param username: if given, restrict the search to the user's calculations
:returns: the associated DataStore instance |
350,862 | async def request(self, route, **kwargs):
if isinstance(route, tuple):
method, url = route
else:
method = route.method
url = route.url
if self.bearer_info is None:
self.bearer_info = bearer_info = await self.get_bearer_info()
... | Make a request to the spotify API with the current bearer credentials.
Parameters
----------
route : Union[tuple[str, str], Route]
A tuple of the method and url or a :class:`Route` object.
kwargs : Any
keyword arguments to pass into :class:`aiohttp.ClientSession.... |
350,863 | def resolve_labels(model_label):
labels = {}
labels[] = model_label.split()[0]
labels[] = model_label.split()[-1]
labels[] = % (labels[], labels[])
return labels | Seperate model_label into parts.
Returns dictionary with app, model and app_model strings. |
350,864 | def get_combined_status(self):
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/status"
)
return github.CommitCombinedStatus.CommitCombinedStatus(self._requester, headers, data, completed=True) | :calls: `GET /repos/:owner/:repo/commits/:ref/status/ <http://developer.github.com/v3/repos/statuses>`_
:rtype: :class:`github.CommitCombinedStatus.CommitCombinedStatus` |
350,865 | def get_all(cls):
api = Client.instance().api
data = api.database.get()
database_names = data[]
databases = []
for name in database_names:
db = Database(name=name, api=api)
databases.append(db)
return databases | Returns an array with all databases
:returns Database list |
350,866 | def subscribe(request):
email = request.POST.get()
next = request.POST.get(, request.GET.get(, ))
valid = False
if not email:
messages.error(request, u)
else:
try:
validate_email(email)
valid = True
except ValidationError:
me... | Takes POST data (``email`` and optional ``next`` fields), submitting the ``email`` field to
the newsletter provider for subscription to a mailing list, and redirecting the user to the value
of ``next`` (this can also be provided in the querystring), or the homepage if no follow-on URL is
supplied, with a me... |
350,867 | def _setup_file_logger(cls, session: AppSession, args):
if not (args.output_file or args.append_output):
return
logger = logging.getLogger()
formatter = logging.Formatter(
)
if args.output_file:
filename = args.output_file
mode ... | Set up the file message logger.
A file log handler and with a formatter is added to the root logger. |
350,868 | def push_organization_to_ckan(portal_url, apikey, organization, parent=None):
portal = RemoteCKAN(portal_url, apikey=apikey)
if parent:
organization[] = [{: parent}]
try:
pushed_org = portal.call_action(,
data_dict=organization)
pushed_org... | Toma una organización y la crea en el portal de destino.
Args:
portal_url (str): La URL del portal CKAN de destino.
apikey (str): La apikey de un usuario con los permisos que le
permitan crear la organización.
organization(dict): Datos de la organización a cre... |
350,869 | def fromblast(args):
from jcvi.formats.blast import sort
from jcvi.utils.range import range_distance
p = OptionParser(fromblast.__doc__)
p.add_option("--clique", default=False, action="store_true",
help="Populate clique instead of linear path [default: %default]")
p.add_option... | %prog fromblast blastfile subject.fasta
Generate path from BLAST file. If multiple subjects map to the same query,
an edge is constructed between them (with the link provided by the query).
The BLAST file MUST be filtered, chained, supermapped. |
350,870 | def pending(self, partitions=None):
if partitions is None:
partitions = self.offsets.keys()
total = 0
reqs = []
for partition in partitions:
reqs.append(OffsetRequestPayload(self.topic, partition, -1, 1))
resps = self.client.send_offset_request... | Gets the pending message count
Keyword Arguments:
partitions (list): list of partitions to check for, default is to check all |
350,871 | def delete_document(self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
if not in self._inner_api_calls:
self._in... | Deletes the specified document.
Operation <response: ``google.protobuf.Empty``,
metadata: [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata]>
Example:
>>> import dialogflow_v2beta1
>>>
>>> client = dialogflow_v2beta1.Doc... |
350,872 | async def sort(self, name, start=None, num=None, by=None, get=None, desc=False, alpha=False, store=None, groups=None):
if (start is None and num is not None) or \
(start is not None and num is None):
raise RedisError("RedisError: ``start`` and ``num`` must both be specified"... | Sort and return the list, set or sorted set at ``name``.
:start: and :num:
allow for paging through the sorted data
:by:
allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
:get:
... |
350,873 | def get(self, timeout=None):
if timeout:
if self._conn1.poll(timeout):
return (True, self._conn1.recv())
else:
return (False, None)
return self._conn1.recv() | Return the next available item from the tube.
Blocks if tube is empty, until a producer for the tube puts an item on it. |
350,874 | def format_files(src: str, dest: str, **fmt_vars: str) -> None:
assert os.path.exists(src)
assert os.path.exists(dest)
for filename in os.listdir(src):
if filename.endswith(EXCLUDED_EXTENSIONS):
continue
elif not os.path.isfile(os.path.join(src, filename)):
... | Copies all files inside src into dest while formatting the contents
of the files into the output.
For example, a file with the following contents:
{foo} bar {baz}
and the vars {'foo': 'herp', 'baz': 'derp'}
will end up in the output as
herp bar derp
:param text src: Source directory.
... |
350,875 | def findTypeParent(element, tag):
p = element
while True:
p = p.getparent()
if p.tag == tag:
return p
return None | Finds fist parent of element of the given type
@param object element: etree element
@param string the tag parent to search for
@return object element: the found parent or None when not found |
350,876 | def validate(self, tracking_number):
"Return True if this is a valid USPS tracking number."
tracking_num = tracking_number[:-1].replace(, )
odd_total = 0
even_total = 0
for ii, digit in enumerate(tracking_num):
if ii % 2:
odd_total += int(digit)
... | Return True if this is a valid USPS tracking number. |
350,877 | def combine_inputs_with_outputs(nb_source, nb_outputs, fmt=None):
output_code_cells = [cell for cell in nb_outputs.cells if cell.cell_type == ]
output_other_cells = [cell for cell in nb_outputs.cells if cell.cell_type != ]
fmt = long_form_one_format(fmt)
text_repr = nb_source.metadata.get(, {}).g... | Copy outputs of the second notebook into
the first one, for cells that have matching inputs |
350,878 | def draw_dynamics_set(dynamics, xtitle = None, ytitle = None, xlim = None, ylim = None, xlabels = False, ylabels = False):
number_dynamics = len(dynamics);
if (number_dynamics == 1):
draw_dynamics(dynamics[0][0], dynamics[0][1], xtitle, ytitle, xlim, ylim, xlabels, ylabels);
retur... | !
@brief Draw lists of dynamics of neurons (oscillators) in the network.
@param[in] dynamics (list): List of network outputs that are represented by values of output of oscillators (used by y axis).
@param[in] xtitle (string): Title for Y.
@param[in] ytitle (string): Title for X.
@param[i... |
350,879 | def greenlet_manage(self):
while True:
try:
self.manage()
except Exception as e:
log.error("When reporting: %s" % e)
finally:
time.sleep(self.config["report_interval"]) | This greenlet always runs in background to update current status
in MongoDB every N seconds. |
350,880 | def members(self):
resp = self._rtm_client.get()
if resp.is_fail():
raise RTMServiceError(
,
resp
)
return resp.data[] | Gets members of current team
Returns:
list of User
Throws:
RTMServiceError when request failed |
350,881 | def camelise(text, capital_first=True):
def camelcase():
if not capital_first:
yield str.lower
while True:
yield str.capitalize
if istype(text, ):
text = text.encode()
c = camelcase()
return "".join(next(c)(x) if x else for x in text.split("_")) | Convert lower_underscore to CamelCase. |
350,882 | async def retry_get(config, url, *args, **kwargs):
return await _retry_do(config.session.get, url, *args,
**_make_headers(config, kwargs)) | aiohttp wrapper for GET |
350,883 | def write_int(fo, datum, schema=None):
datum = (datum << 1) ^ (datum >> 63)
while (datum & ~0x7F) != 0:
fo.write(pack(, (datum & 0x7f) | 0x80))
datum >>= 7
fo.write(pack(, datum)) | int and long values are written using variable-length, zig-zag coding. |
350,884 | def _ReadSources(self, artifact_definition_values, artifact_definition, name):
sources = artifact_definition_values.get()
if not sources:
raise errors.FormatError(
.format(name))
for source in sources:
type_indicator = source.get(, None)
if not type_indicator:
raise... | Reads the artifact definition sources.
Args:
artifact_definition_values (dict[str, object]): artifact definition
values.
artifact_definition (ArtifactDefinition): an artifact definition.
name (str): name of the artifact definition.
Raises:
FormatError: if the type indicator i... |
350,885 | def dependent(self, dep_type, node):
self._dependents[dep_type] = self._dependents.get(dep_type, []) + [node]
return self | Registers a node as dependent on this node
:param dep_type: The dependency type
:type dep_type: str
:param node: The node to be registered as a dependent
:type node: corenlp_xml.dependencies.DependencyNode
:return: self, provides fluent interface
:rtype: corenlp_xml.dep... |
350,886 | def _copy_calibration(self, calibration):
for key, item in calibration.__dict__.items():
self.__dict__[key] = item | Copy another ``StereoCalibration`` object's values. |
350,887 | def _start_new_warc_file(self, meta=False):
if self._params.max_size and not meta and self._params.appending:
while True:
self._warc_filename = self._generate_warc_filename()
if os.path.exists(self._warc_filename):
_logger.debug(, self._w... | Create and set as current WARC file. |
350,888 | def get_backend_instance(self, backend: BackendDefinitionType) -> BaseBackend:
if backend is NOT_SET:
backend = self.get_setting("backend", "arca.CurrentEnvironmentBackend")
if isinstance(backend, str):
backend = load_class(backend)
if callable(backend):
... | Returns a backend instance, either from the argument or from the settings.
:raise ArcaMisconfigured: If the instance is not a subclass of :class:`BaseBackend` |
350,889 | def grab_bulbs(host, token=None):
xml = grab_xml(host, token)
bulbs = {}
for room in xml:
for device in room[]:
bulbs[int(device[])] = device
return bulbs | Grab XML, then add all bulbs to a dict. Removes room functionality |
350,890 | def get_url(self, **kwargs):
return build(
self._request.path,
self._request.GET,
self._meta.prefix,
**kwargs ) | Return an url, relative to the request associated with this
table. Any keywords arguments provided added to the query
string, replacing existing values. |
350,891 | def resolve(self, name):
for scope in reversed(self.scopes):
try:
return structured.resolve(scope, name)
except (KeyError, AttributeError):
continue
raise AttributeError(name) | Call IStructured.resolve across all scopes and return first hit. |
350,892 | def point_mutation(self, random_state):
program = copy(self.program)
mutate = np.where(random_state.uniform(size=len(program)) <
self.p_point_replace)[0]
for node in mutate:
if isinstance(program[node], _Function):
arity =... | Perform the point mutation operation on the program.
Point mutation selects random nodes from the embedded program to be
replaced. Terminals are replaced by other terminals and functions are
replaced by other functions that require the same number of arguments
as the original node. The ... |
350,893 | async def SetFilesystemInfo(self, filesystems):
_params = dict()
msg = dict(type=,
request=,
version=3,
params=_params)
_params[] = filesystems
reply = await self.rpc(msg)
return reply | filesystems : typing.Sequence[~Filesystem]
Returns -> typing.Sequence[~ErrorResult] |
350,894 | def strip(self):
result = []
for k, v in self.items():
if isinstance(v, tuple):
if v > (_EPSILON, ) * len(v) or v < (-_EPSILON, ) * len(v):
result.append((k, v))
elif v > _EPSILON or v < -_EPSILON:
result.append((k, v))... | Remove coordinates that are zero, the opposite of expand().
::
>>> l = Location(pop=1, snap=0)
>>> l.strip()
<Location pop:1 > |
350,895 | def find_plugins(self,
plugin_env, full_env=None, installer=None, fallback=True
):
plugin_projects = list(plugin_env)
plugin_projects.sort()
error_info = {}
distributions = {}
if full_env is None:
env = Environment(self.entries)
e... | Find all activatable distributions in `plugin_env`
Example usage::
distributions, errors = working_set.find_plugins(
Environment(plugin_dirlist)
)
map(working_set.add, distributions) # add plugins+libs to sys.path
print 'Could not load', errors ... |
350,896 | def parse_extends(self):
for _selectors, rules in self.parts.items():
if in _selectors:
selectors, _, parent = _selectors.partition()
parents = parent.split()
del self.parts[_selectors]
for parent in... | For each part, create the inheritance parts from the ' extends ' |
350,897 | def format_and_annualise(self, raw_cov_array):
assets = self.X.columns
return (
pd.DataFrame(raw_cov_array, index=assets, columns=assets) * self.frequency
) | Helper method which annualises the output of shrinkage calculations,
and formats the result into a dataframe
:param raw_cov_array: raw covariance matrix of daily returns
:type raw_cov_array: np.ndarray
:return: annualised covariance matrix
:rtype: pd.DataFrame |
350,898 | def only_published(cls, at=None):
if isinstance(at, timedelta):
at = utcnow() + at
else:
at = at or utcnow()
pub, ret = cls.published, cls.retracted
publication = (-pub) | (pub == None) | (pub <= at)
retraction = (-ret) | (ret == None) | (ret > at)
return publication & retraction | Produce a query fragment suitable for selecting documents public.
Now (no arguments), at a specific time (datetime argument), or relative to now (timedelta). |
350,899 | def item_meta(item_name, name, value, scheme=None):
_annotate("item_meta", item_name, name, value, scheme=scheme) | Adds meta information to an already defined item
of the model being defined.
@param item_name: name of the model item the meta data should be added to.
@type item_name: str or unicode
@param name: name of the meta data class
@type name: str or unicode
@param value: metadata value
@type value... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.