Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
369,500 | def lock_machine(self, session, lock_type):
if not isinstance(session, ISession):
raise TypeError("session can only be an instance of type ISession")
if not isinstance(lock_type, LockType):
raise TypeError("lock_type can only be an instance of type LockType")
sel... | Locks the machine for the given session to enable the caller
to make changes to the machine or start the VM or control
VM execution.
There are two ways to lock a machine for such uses:
If you want to make changes to the machine settings,
you must obtain... |
369,501 | def _open(self, archive):
try:
handle = unrarlib.RAROpenArchiveEx(ctypes.byref(archive))
except unrarlib.UnrarException:
raise BadRarFile("Invalid RAR file.")
return handle | Open RAR archive file. |
369,502 | def split_transfer_kwargs(kwargs, skip=None):
skip = make_list(skip) if skip else []
transfer_kwargs = {
name: kwargs.pop(name)
for name in ["cache", "prefer_cache", "retries", "retry_delay"]
if name in kwargs and name not in skip
}
return transfer_kwargs, kwargs | Takes keyword arguments *kwargs*, splits them into two separate dictionaries depending on their
content, and returns them in a tuple. The first one will contain arguments related to potential
file transfer operations (e.g. ``"cache"`` or ``"retries"``), while the second one will contain
all remaining argume... |
369,503 | def hrv_parameters(data, sample_rate, signal=False, in_seconds=False):
out_dict = {}
tachogram_data, tachogram_time = tachogram(data, sample_rate, signal=signal,
in_seconds=in_seconds, out_seconds=True)
tachogram_data_nn = remove_ectopy(tachog... | -----
Brief
-----
Function for extracting HRV parameters from time and frequency domains.
-----------
Description
-----------
ECG signals require specific processing due to their cyclic nature. For example, it is expected that in similar
conditions the RR peak interval to be similar, wh... |
369,504 | def set_module_options(self, module):
self.i3bar_module_options = {}
self.i3bar_gaps_module_options = {}
self.py3status_module_options = {}
fn = self._py3_wrapper.get_config_attribute
def make_quotes(options):
x = ["`{}`".format(x) for x in options]
... | Set universal module options to be interpreted by i3bar
https://i3wm.org/i3status/manpage.html#_universal_module_options |
369,505 | def create_buffer(self, ignore_unsupported=False):
bufferdict = OrderedDict()
for branch in self.iterbranches():
if not self.GetBranchStatus(branch.GetName()):
continue
if not BaseTree.branch_is_supported(branch):
log.warning(... | Create this tree's TreeBuffer |
369,506 | def present(name, mediatype, **kwargs):
s docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see modules docstring)
.. code-block:: yaml
make_new_mediatype:
zabbix_mediatype.present:
- name:
- mediatyp... | Creates new mediatype.
NOTE: This function accepts all standard mediatype properties: keyword argument names differ depending on your
zabbix version, see:
https://www.zabbix.com/documentation/3.0/manual/api/reference/host/object#host_inventory
:param name: name of the mediatype
:param _connection_u... |
369,507 | def _get_block(self):
b = self._fh.read(4)
if not b: raise StopIteration
block_size = struct.unpack(,b)[0]
return self._fh.read(block_size) | Just read a single block from your current location in _fh |
369,508 | def _process_comment(self, comment: praw.models.Comment):
self._func_comment(comment, *self._func_comment_args) | Process a reddit comment. Calls `func_comment(*func_comment_args)`.
:param comment: Comment to process |
369,509 | def register_pickle():
import cPickle
registry.register(, cPickle.dumps, cPickle.loads,
content_type=,
content_encoding=) | The fastest serialization method, but restricts
you to python clients. |
369,510 | def revoke_token(access_token):
response = requests.post(
get_revoke_token_url(),
data={
: access_token,
: settings.API_CLIENT_ID,
: settings.API_CLIENT_SECRET,
},
timeout=15
)
return response.status_code == 200 | Instructs the API to delete this access token and associated refresh token |
369,511 | def iter_paths(self, pathnames=None, mapfunc=None):
pathnames = pathnames or self._pathnames
if self.recursive and not pathnames:
pathnames = []
elif not pathnames:
yield []
if mapfunc is not None:
for mapped_paths in map(mapfunc, pathnames):... | Special iteration on paths. Yields couples of path and items. If a expanded path
doesn't match with any files a couple with path and `None` is returned.
:param pathnames: Iterable with a set of pathnames. If is `None` uses the all \
the stored pathnames.
:param mapfunc: A mapping functi... |
369,512 | def set_value(self, eid, val, idx=):
if eid in self.__element_ids:
elems = self.__element_ids[eid]
if type(val) in SEQ_TYPES:
idx = 0
if idx == :
for elem in elems:
self.__set_value(eid, elem, val, idx)
... | Set the content of an xml element marked with the matching eid attribute. |
369,513 | def search_users(self, user_name):
action_path =
if user_name:
action_path += .format(user_name)
res = self._make_ocs_request(
,
self.OCS_SERVICE_CLOUD,
action_path
)
if res.status_code == 200:
tree = ET.from... | Searches for users via provisioning API.
If you get back an error 999, then the provisioning API is not enabled.
:param user_name: name of user to be searched for
:returns: list of usernames that contain user_name as substring
:raises: HTTPResponseError in case an HTTP error status was... |
369,514 | def get_ssh_dir(config, username):
sshdir = config.get()
if not sshdir:
sshdir = os.path.expanduser()
if not os.path.isdir(sshdir):
pwentry = getpwnam(username)
sshdir = os.path.join(pwentry.pw_dir, )
if not os.path.isdir(sshdir):
sshdir =... | Get the users ssh dir |
369,515 | def get_tab_tip(self, filename, is_modified=None, is_readonly=None):
text = u"%s — %s"
text = self.__modified_readonly_title(text,
is_modified, is_readonly)
if self.tempfile_path is not None\
and filename == encoding.to_unic... | Return tab menu title |
369,516 | def match(self, url):
try:
urlSchemes = self._urlSchemes.itervalues()
except AttributeError:
urlSchemes = self._urlSchemes.values()
for urlScheme in urlSchemes:
if urlScheme.match(url):
return True
return False | Try to find if url matches against any of the schemes within this
endpoint.
Args:
url: The url to match against each scheme
Returns:
True if a matching scheme was found for the url, False otherwise |
369,517 | def store_sample(self, sample_bytes, filename, type_tag):
if len(filename) > 1000:
print % (sample_bytes[:100], filename[:100])
exit(1)
sample_info = {}
sample_info[] = hashlib.md5(sample_bytes).hexdigest()
if self.has_samp... | Store a sample into the datastore.
Args:
filename: Name of the file.
sample_bytes: Actual bytes of sample.
type_tag: Type of sample ('exe','pcap','pdf','json','swf', or ...)
Returns:
md5 digest of the sample. |
369,518 | def kill_given_tasks(self, task_ids, scale=False, force=None):
params = {: scale}
if force is not None:
params[] = force
data = json.dumps({"ids": task_ids})
response = self._do_request(
, , params=params, data=data)
return response == 200 | Kill a list of given tasks.
:param list[str] task_ids: tasks to kill
:param bool scale: if true, scale down the app by the number of tasks killed
:param bool force: if true, ignore any current running deployments
:return: True on success
:rtype: bool |
369,519 | def get_member(thing_obj, member_string):
mems = {x[0]: x[1] for x in inspect.getmembers(thing_obj)}
if member_string in mems:
return mems[member_string] | Get a member from an object by (string) name |
369,520 | def _as_rescale(self, get, targetbitdepth):
width,height,pixels,meta = get()
maxval = 2**meta[] - 1
targetmaxval = 2**targetbitdepth - 1
factor = float(targetmaxval) / float(maxval)
meta[] = targetbitdepth
def iterscale():
for row in pixels:
... | Helper used by :meth:`asRGB8` and :meth:`asRGBA8`. |
369,521 | async def handle_client_hello(self, client_addr, _: ClientHello):
self._logger.info("New client connected %s", client_addr)
self._registered_clients.add(client_addr)
await self.send_container_update_to_client([client_addr]) | Handle an ClientHello message. Send available containers to the client |
369,522 | def confirm_delete_view(self, request, object_id):
kwargs = {: self, : object_id}
view_class = self.confirm_delete_view_class
return view_class.as_view(**kwargs)(request) | Instantiates a class-based view to provide 'delete confirmation'
functionality for the assigned model, or redirect to Wagtail's delete
confirmation view if the assigned model extends 'Page'. The view class
used can be overridden by changing the 'confirm_delete_view_class'
attribute. |
369,523 | def get_resource_allocation(self):
if hasattr(self, ):
return ResourceAllocation(self.rest_client.make_request(self.resourceAllocation), self.rest_client) | Get the :py:class:`ResourceAllocation` element tance.
Returns:
ResourceAllocation: Resource allocation used to access information about the resource where this PE is running.
.. versionadded:: 1.9 |
369,524 | def check_df(
state, index, missing_msg=None, not_instance_msg=None, expand_msg=None
):
child = check_object(
state,
index,
missing_msg=missing_msg,
expand_msg=expand_msg,
typestr="pandas DataFrame",
)
is_instance(child, pd.DataFrame, not_instance_msg=not_ins... | Check whether a DataFrame was defined and it is the right type
``check_df()`` is a combo of ``check_object()`` and ``is_instance()`` that checks whether the specified object exists
and whether the specified object is pandas DataFrame.
You can continue checking the data frame with ``check_keys()`` func... |
369,525 | def unpack_rsp(cls, rsp_pb):
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
raw_position_list = rsp_pb.s2c.positionList
position_list = [{
"code": merge_trd_mkt_stock_str(rsp_pb.s2c.header.trdMarket, position.code),
... | Convert from PLS response to user response |
369,526 | def norm_coefs(self):
sum_coefs = self.sum_coefs
self.ar_coefs /= sum_coefs
self.ma_coefs /= sum_coefs | Multiply all coefficients by the same factor, so that their sum
becomes one. |
369,527 | def apply_shortcuts(self):
toberemoved = []
for index, (qobject, context, name,
add_sc_to_tip) in enumerate(self.shortcut_data):
keyseq = QKeySequence( get_shortcut(context, name) )
try:
if isinstance(qobject, QAction):
... | Apply shortcuts settings to all widgets/plugins |
369,528 | def to_dict(self):
d = {
: self.id,
: self.start,
: self.end,
: self.form
}
if self.lnk is not None:
cfrom, cto = self.lnk.data
d[] = cfrom
d[] = cto
if self.surface is not None:
... | Encode the token as a dictionary suitable for JSON serialization. |
369,529 | def tobinary(series, path, prefix=, overwrite=False, credentials=None):
from six import BytesIO
from thunder.utils import check_path
from thunder.writers import get_parallel_writer
if not overwrite:
check_path(path, credentials=credentials)
overwrite = True
def tobuffer(kv):
... | Writes out data to binary format.
Parameters
----------
series : Series
The data to write
path : string path or URI to directory to be created
Output files will be written underneath path.
Directory will be created as a result of this call.
prefix : str, optional, default ... |
369,530 | def build_encryption_materials_cache_key(partition, request):
if request.algorithm is None:
_algorithm_info = b"\x00"
else:
_algorithm_info = b"\x01" + request.algorithm.id_as_bytes()
hasher = _new_cache_key_hasher()
_partition_hash = _partition_name_hash(hasher=hasher.copy(), part... | Generates a cache key for an encrypt request.
:param bytes partition: Partition name for which to generate key
:param request: Request for which to generate key
:type request: aws_encryption_sdk.materials_managers.EncryptionMaterialsRequest
:returns: cache key
:rtype: bytes |
369,531 | def mod9710(iban):
remainder = iban
block = None
while len(remainder) > 2:
block = remainder[:9]
remainder = str(int(block) % 97) + remainder[len(block):]
return int(remainder) % 97 | Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064.
@method mod9710
@param {String} iban
@returns {Number} |
369,532 | def _evaluate(self,R,phi=0.,t=0.):
return 0.5*R*R*(1.+2./3.*R*numpy.sin(3.*phi)) | NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
2017-10-16 - Written - Bovy (UofT) |
369,533 | def _drain(writer, ion_event):
result_event = _WRITE_EVENT_HAS_PENDING_EMPTY
while result_event.type is WriteEventType.HAS_PENDING:
result_event = writer.send(ion_event)
ion_event = None
yield result_event | Drain the writer of its pending write events.
Args:
writer (Coroutine): A writer co-routine.
ion_event (amazon.ion.core.IonEvent): The first event to apply to the writer.
Yields:
DataEvent: Yields each pending data event. |
369,534 | def build_colormap(palette, info):
from trollimage.colormap import Colormap
if in palette.attrs:
palette_indices = palette.attrs[]
else:
palette_indices = range(len(palette))
sqpalette = np.asanyarray(palette).squeeze() / 255.0
tups = [(val, tu... | Create the colormap from the `raw_palette` and the valid_range. |
369,535 | def nvrtcAddNameExpression(self, prog, name_expression):
code = self._lib.nvrtcAddNameExpression(prog,
c_char_p(encode_str(name_expression)))
self._throw_on_error(code)
return | Notes the given name expression denoting a __global__ function or
function template instantiation. |
369,536 | def get_post_agg(mconf):
if mconf.get() == :
return JavascriptPostAggregator(
name=mconf.get(, ),
field_names=mconf.get(, []),
function=mconf.get(, ))
elif mconf.get() == :
return Quantile(
mconf.get(, ),
... | For a metric specified as `postagg` returns the
kind of post aggregation for pydruid. |
369,537 | def stripped_photo_to_jpg(stripped):
if len(stripped) < 3 or stripped[0] != 1:
return stripped
header = bytearray(b()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\... | Adds the JPG header and footer to a stripped image.
Ported from https://github.com/telegramdesktop/tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225 |
369,538 | def _conj(self, f):
def f_conj(x, **kwargs):
result = np.asarray(f(x, **kwargs),
dtype=self.scalar_out_dtype)
return result.conj()
if is_real_dtype(self.out_dtype):
return f
else:
return self.element(f_conj... | Function returning the complex conjugate of a result. |
369,539 | def simulate_experiment(self, modelparams, expparams, repeat=1):
self._sim_count += modelparams.shape[0] * expparams.shape[0] * repeat
assert(self.are_expparam_dtypes_consistent(expparams)) | Produces data according to the given model parameters and experimental
parameters, structured as a NumPy array.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
array of model parameter vectors describing the hypotheses under
which data should be simulated.
... |
369,540 | def update_items(portal_type=None, uid=None, endpoint=None, **kw):
req.disable_csrf_protection()
records = req.get_request_data()
obj = get_object_by_uid(uid)
if obj:
record = records[0]
obj = update_object_with_data(obj, record)
return make_items_for([ob... | update items
1. If the uid is given, the user wants to update the object with the data
given in request body
2. If no uid is given, the user wants to update a bunch of objects.
-> each record contains either an UID, path or parent_path + id |
369,541 | def get_pint_to_fortran_safe_units_mapping(inverse=False):
replacements = {"^": "super", "/": "per", " ": ""}
if inverse:
replacements = {v: k for k, v in replacements.items()}
replacements.pop("")
return replacements | Get the mappings from Pint to Fortran safe units.
Fortran can't handle special characters like "^" or "/" in names, but we need
these in Pint. Conversely, Pint stores variables with spaces by default e.g. "Mt
CO2 / yr" but we don't want these in the input files as Fortran is likely to think
the whitesp... |
369,542 | def simxEraseFile(clientID, fileName_serverSide, operationMode):
if (sys.version_info[0] == 3) and (type(fileName_serverSide) is str):
fileName_serverSide=fileName_serverSide.encode()
return c_EraseFile(clientID, fileName_serverSide, operationMode) | Please have a look at the function description/documentation in the V-REP user manual |
369,543 | def parse_analyzer_arguments(arguments):
rets = []
for argument in arguments:
args = argument.split(argument_splitter)
func_name = args[0]
func_args = {}
for arg in args[1:]:
key, value = parse_arg(arg)
func_args[key] = value
... | Parse string in format `function_1:param1=value:param2 function_2:param` into array of FunctionArguments |
369,544 | def update_resource(self, resource, underlined=None):
try:
pymodule = self.project.get_pymodule(resource)
modname = self._module_name(resource)
self._add_names(pymodule, modname, underlined)
except exceptions.ModuleSyntaxError:
pass | Update the cache for global names in `resource` |
369,545 | def trailing_input(self):
slices = []
for r, re_match in self._re_matches:
for group_name, group_index in r.groupindex.items():
if group_name == _INVALID_TRAILING_INPUT:
slices.append(re_match.regs[group_index])
... | Get the `MatchVariable` instance, representing trailing input, if there is any.
"Trailing input" is input at the end that does not match the grammar anymore, but
when this is removed from the end of the input, the input would be a valid string. |
369,546 | def upload_async(self, remote_path, local_path, callback=None):
target = (lambda: self.upload_sync(local_path=local_path, remote_path=remote_path, callback=callback))
threading.Thread(target=target).start() | Uploads resource to remote path on WebDAV server asynchronously.
In case resource is directory it will upload all nested files and directories.
:param remote_path: the path for uploading resources on WebDAV server. Can be file and directory.
:param local_path: the path to local resource for upl... |
369,547 | def annual_heating_design_day_996(self):
if bool(self._winter_des_day_dict) is True:
return DesignDay.from_ashrae_dict_heating(
self._winter_des_day_dict, self.location, False,
self._stand_press_at_elev)
else:
return None | A design day object representing the annual 99.6% heating design day. |
369,548 | def get_request_data():
method = request.method.lower()
if method in ["get", "delete"]:
return request.args
elif method in ["post", "put", "patch"]:
if request.mimetype == :
try:
return request.get_json()
except:
abort(400, "Invali... | Get request data based on request.method
If method is GET or DELETE, get data from request.args
If method is POST, PATCH or PUT, get data from request.form or request.json |
369,549 | def xstep_check(self, b):
r
if self.opt[]:
Zop = lambda x: sl.inner(self.Zf, x, axis=self.cri.axisM)
ZHop = lambda x: sl.inner(np.conj(self.Zf), x,
axis=self.cri.axisK)
ax = ZHop(Zop(self.Xf)) + self.Xf
self.xrrs = sl... | r"""Check the minimisation of the Augmented Lagrangian with
respect to :math:`\mathbf{x}` by method `xstep` defined in
derived classes. This method should be called at the end of any
`xstep` method. |
369,550 | def declare_base(erroName=True):
if erroName:
class Base(Exception):
def __str__(self):
if len(self.args):
return "%s: %s" % (self.__class__.__name__, self.args[0])
else:
return "%s: %s" % (self.__class__.__name__, self... | Create a Exception with default message.
:param errorName: boolean, True if you want the Exception name in the
error message body. |
369,551 | def replaceWith(self, el):
self.childs = el.childs
self.params = el.params
self.endtag = el.endtag
self.openertag = el.openertag
self._tagname = el.getTagName()
self._element = el.tagToString()
self._istag = el.isTag()
self._isendtag = el.isEndT... | Replace value in this element with values from `el`.
This useful when you don't want change all references to object.
Args:
el (obj): :class:`HTMLElement` instance. |
369,552 | async def sysinfo(dev: Device):
click.echo(await dev.get_system_info())
click.echo(await dev.get_interface_information()) | Print out system information (version, MAC addrs). |
369,553 | def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
url = urljoin(URLS[], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration ... | Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any o... |
369,554 | def fleets(self):
if self._fleets is None:
self._fleets = FleetList(self)
return self._fleets | :rtype: twilio.rest.preview.deployed_devices.fleet.FleetList |
369,555 | def get_account_details(self, session=None, lightweight=None):
params = clean_locals(locals())
method = % (self.URI, )
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.AccountDetails, elapsed_time, lightweight) | Returns the details relating your account, including your discount
rate and Betfair point balance.
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.AccountDetails |
369,556 | def isTemporal(inferenceType):
if InferenceType.__temporalInferenceTypes is None:
InferenceType.__temporalInferenceTypes = \
set([InferenceType.TemporalNextStep,
InferenceType.TemporalClassification,
... | Returns True if the inference type is 'temporal', i.e. requires a
temporal memory in the network. |
369,557 | def add_reviewer(self, doc, reviewer):
self.reset_reviews()
if validations.validate_reviewer(reviewer):
doc.add_review(review.Review(reviewer=reviewer))
return True
else:
raise SPDXValueError() | Adds a reviewer to the SPDX Document.
Reviwer is an entity created by an EntityBuilder.
Raises SPDXValueError if not a valid reviewer type. |
369,558 | def many_until(these, term):
results = []
while True:
stop, result = choice(_tag(True, term),
_tag(False, these))
if stop:
return results, result
else:
results.append(result) | Consumes as many of these as it can until it term is encountered.
Returns a tuple of the list of these results and the term result |
369,559 | async def fetching_data(self, *_):
try:
with async_timeout.timeout(10):
resp = await self._websession.get(self._api_url, params=self._urlparams)
if resp.status != 200:
_LOGGER.error(, self._api_url, resp.status)
return False
... | Get the latest data from met.no. |
369,560 | def delete_old_tickets(**kwargs):
sender = kwargs.get(, None)
now = datetime.now()
expire = datetime(now.year, now.month, now.day - 2)
sender.objects.filter(created__lt=expire).delete() | Delete tickets if they are over 2 days old
kwargs = ['raw', 'signal', 'instance', 'sender', 'created'] |
369,561 | def send_status_message(self, object_id, status):
try:
body = json.dumps({
: object_id,
: status
})
self.status_queue.send_message(
MessageBody=body,
MessageGroupId=,
MessageDeduplicatio... | Send a message to the `status_queue` to update a job's status.
Returns `True` if the message was sent, else `False`
Args:
object_id (`str`): ID of the job that was executed
status (:obj:`SchedulerStatus`): Status of the job
Returns:
`bool` |
369,562 | def create_class(self, data, options=None, **kwargs):
_type = kwargs.get("_type")
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
if _type:
LOGGER.debug("Forcing Go Type %s" % _type)
cls = obj_map[_type]
el... | Return instance of class based on Go data
Data keys handled here:
_type
Set the object class
consts, types, vars, funcs
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from godo... |
369,563 | def _update_tokens(self, write_token=True, override=None,
patch_skip=False):
next_token = next(self.tokens)
patch_value =
patch_tokens =
if self.pfile and write_token:
token = override if override else self.token
patch_value += ... | Update tokens to the next available values. |
369,564 | def _upsert_persons(cursor, person_ids, lookup_func):
person_ids = list(set(person_ids))
cursor.execute("SELECT personid from persons where personid = ANY (%s)",
(person_ids,))
existing_person_ids = [x[0] for x in cursor.fetchall()]
new_person_ids = [p for p in person_i... | Upsert's user info into the database.
The model contains the user info as part of the role values. |
369,565 | def filter(self, cls, recursive=False):
source = self.walk_preorder if recursive else self._children
return [
codeobj
for codeobj in source()
if isinstance(codeobj, cls)
] | Retrieves all descendants (including self) that are instances
of a given class.
Args:
cls (class): The class to use as a filter.
Kwargs:
recursive (bool): Whether to descend recursively down the tree. |
369,566 | def extract_labels(filename):
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2049:
raise ValueError(
%
(magic, filename))
num_items = _read32(bytestream)
buf = bytestream.read(num_items)
labels... | Extract the labels into a 1D uint8 numpy array [index]. |
369,567 | def doDup(self, WHAT={}, **params):
if hasattr(WHAT, ):
for key, value in WHAT._modified():
if WHAT.__new2old__.has_key(key):
self._addDBParam(WHAT.__new2old__[key].encode(), value)
else:
self._addDBParam(key, value)
self._addDBParam(, WHAT.RECORDID)
self._addDBParam(, WHAT.MODID)
eli... | This function will perform the command -dup. |
369,568 | def whoami(*args, **kwargs):
user = client.whoami()
if user:
print_user(user)
else:
print() | Prints information about the current user.
Assumes the user is already logged-in. |
369,569 | def write(self, pos, size, **kwargs):
if type(pos) is str:
raise TypeError("SimFileDescriptor.write takes an address and size. Did you mean write_data?")
if self.state.solver.symbolic(size):
try:
passed_max_size = self.state.so... | Writes some data, loaded from the state, into the file.
:param pos: The address to read the data to write from in memory
:param size: The requested size of the write
:return: The real length of the write |
369,570 | def update(self):
if self.hasproxy():
irD = IRData()
received = 0
data = self.proxy.getIRData()
irD.received = data.received
self.lock.acquire()
self.ir = irD
self.lock.release() | Updates LaserData. |
369,571 | def _vmomentsurfaceMCIntegrand(vz,vR,vT,R,z,df,sigmaR1,gamma,sigmaz1,mvT,n,m,o):
return vR**n*vT**m*vz**o*df(R,vR*sigmaR1,vT*sigmaR1*gamma,z,vz*sigmaz1,use_physical=False)*numpy.exp(vR**2./2.+(vT-mvT)**2./2.+vz**2./2.) | Internal function that is the integrand for the vmomentsurface mass integration |
369,572 | def f_get_from_runs(self, name, include_default_run=True, use_indices=False,
fast_access=False, with_links = True,
shortcuts=True, max_depth=None, auto_load=False):
result_dict = OrderedDict()
old_crun = self.v_crun
try:
if l... | Searches for all occurrences of `name` in each run.
Generates an ordered dictionary with the run names or indices as keys and
found items as values.
Example:
>>> traj.f_get_from_runs(self, 'deep.universal_answer', use_indices=True, fast_access=True)
OrderedDict([(0, 42), (1, 4... |
369,573 | def inspect(self, **kwargs):
what = kwargs.pop("what", "hist")
if what == "hist":
with self.open_hist() as hist:
return hist.plot(**kwargs) if hist else None
elif what == "scf":
relaxation = abiinspect.Relaxation.from_f... | Plot the evolution of the structural relaxation with matplotlib.
Args:
what: Either "hist" or "scf". The first option (default) extracts data
from the HIST file and plot the evolution of the structural
parameters, forces, pressures and energies.
The s... |
369,574 | def _handleInvalid(invalidDefault):
blah
try:
isInstantiatedException = bool( issubclass(invalidDefault.__class__, Exception) )
except:
isInstantiatedException = False
if isInstantiatedException:
raise invalidDefault
else:
try:
isExceptionType =... | _handleInvalid - Common code for raising / returning an invalid value
@param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None
and "val" is not in #possibleValues
If instantiated Excep... |
369,575 | def verify_signature(public_key, signature, hash, hash_algo):
hash_algo = _hash_algorithms[hash_algo]
try:
return get_publickey(public_key).verify(
signature,
hash,
padding.PKCS1v15(),
utils.Prehashed(hash_algo),
) is None
except InvalidSi... | Verify the given signature is correct for the given hash and public key.
Args:
public_key (str): PEM encoded public key
signature (bytes): signature to verify
hash (bytes): hash of data
hash_algo (str): hash algorithm used
Returns:
True if the signature is valid, False ... |
369,576 | def ParseOptions(cls, options, configuration_object):
if not isinstance(configuration_object, tools.CLITool):
raise errors.BadConfigObject(
)
profilers = cls._ParseStringOption(options, )
if not profilers:
profilers = set()
elif profilers.lower() != :
profilers = set(p... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is of the wrong type. |
369,577 | def list_product_versions(page_size=200, page_index=0, sort="", q=""):
content = list_product_versions_raw(page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | List all ProductVersions |
369,578 | def ip_v6_network_validator(v: Any) -> IPv6Network:
if isinstance(v, IPv6Network):
return v
with change_exception(errors.IPv6NetworkError, ValueError):
return IPv6Network(v) | Assume IPv6Network initialised with a default ``strict`` argument
See more:
https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network |
369,579 | def words_to_word_ids(data=None, word_to_id=None, unk_key=):
if data is None:
raise Exception("data : list of string or byte")
if word_to_id is None:
raise Exception("word_to_id : a dictionary")
word_ids = []
for word in data:
if word_to_i... | Convert a list of string (words) to IDs.
Parameters
----------
data : list of string or byte
The context in list format
word_to_id : a dictionary
that maps word to ID.
unk_key : str
Represent the unknown words.
Returns
--------
list of int
A list of IDs ... |
369,580 | def nf_io_to_process(ios, def_ios, scatter_ios=None):
scatter_names = {k: v for k, v in scatter_ios} if scatter_ios else {}
var_types = {}
for def_io in def_ios:
var_types[def_io["name"]] = nf_type(def_io["variable_type"])
out = []
for io in ios:
cur_id = io["id"]
if sca... | Convert CWL input/output into a nextflow process definition.
Needs to handle scattered/parallel variables. |
369,581 | def mimeData(self, indexes):
byte_stream = pickle.dumps([self.get_node(index) for index in indexes], pickle.HIGHEST_PROTOCOL)
mime_data = QMimeData()
mime_data.setData("application/x-umbragraphmodeldatalist", byte_stream)
return mime_data | Reimplements the :meth:`QAbstractItemModel.mimeData` method.
:param indexes: Indexes.
:type indexes: QModelIndexList
:return: MimeData.
:rtype: QMimeData |
369,582 | def _handle_app_result_build_failure(self,out,err,exit_status,result_paths):
try:
raise ApplicationError, \
\
% err.read()
except:
raise ApplicationError,\
| Catch the error when files are not produced |
369,583 | def beta_pdf(x, a, b):
bc = 1 / beta(a, b)
fc = x ** (a - 1)
sc = (1 - x) ** (b - 1)
return bc * fc * sc | Beta distirbution probability density function. |
369,584 | def output(self):
if len(self.files) < 1:
raise Exception()
return self.template.render(self.files) | Generates output from data array
:returns Pythoned file
:rtype str or unicode |
369,585 | def create(self, phone_number, sms_capability, account_sid=values.unset,
friendly_name=values.unset, unique_name=values.unset,
cc_emails=values.unset, sms_url=values.unset,
sms_method=values.unset, sms_fallback_url=values.unset,
sms_fallback_method=values.unse... | Create a new HostedNumberOrderInstance
:param unicode phone_number: An E164 formatted phone number.
:param bool sms_capability: Specify SMS capability to host.
:param unicode account_sid: Account Sid.
:param unicode friendly_name: A human readable description of this resource.
:... |
369,586 | def _read_function(schema):
def func(
filename=None,
data=None,
add_node_labels=True,
use_uids=True,
**kwargs):
return _read(
filename=filename,
data=data,
schema=schema,
add_node_labels=add_node_labels,
... | Add a write method for named schema to a class. |
369,587 | def check_libcloud_version(reqver=LIBCLOUD_MINIMAL_VERSION, why=None):
if not HAS_LIBCLOUD:
return False
if not isinstance(reqver, (list, tuple)):
raise RuntimeError(
reqver\
)
try:
import libcloud
except ImportError:
raise ImportError(
... | Compare different libcloud versions |
369,588 | def leaves_are_consistent(self):
self.log(u"Checking if leaves are consistent")
leaves = self.leaves()
if len(leaves) < 1:
self.log(u"Empty leaves => return True")
return True
min_time = min([l.interval.begin for l in leaves])
self.log([u" Min ti... | Return ``True`` if the sync map fragments
which are the leaves of the sync map tree
(except for HEAD and TAIL leaves)
are all consistent, that is,
their intervals do not overlap in forbidden ways.
:rtype: bool
.. versionadded:: 1.7.0 |
369,589 | def label_tree(n,lookup):
children
if len(n["children"]) == 0:
leaves = [lookup[n["node_id"]]]
else:
leaves = reduce(lambda ls, c: ls + label_tree(c,lookup), n["children"], [])
del n["node_id"]
n["name"] = name = "|||".join(sorted(map(str, leaves)))
return leaves | label tree will again recursively label the tree
:param n: the root node, usually d3['children'][0]
:param lookup: the node/id lookup |
369,590 | def merge_coords(objs, compat=, join=, priority_arg=None,
indexes=None):
_assert_compat_valid(compat)
coerced = coerce_pandas_values(objs)
aligned = deep_align(coerced, join=join, copy=False, indexes=indexes)
expanded = expand_variable_dicts(aligned)
priority_vars = _get_priori... | Merge coordinate variables.
See merge_core below for argument descriptions. This works similarly to
merge_core, except everything we don't worry about whether variables are
coordinates or not. |
369,591 | def run(self, parent=None):
self.gw = GuerillaMGMTWin(parent=parent)
self.gw.show() | Start the configeditor
:returns: None
:rtype: None
:raises: None |
369,592 | def _parse_string_el(el):
value = str(el)
el_type = el.attributes().get()
if el_type and el_type.value == :
value = base64.b64decode(value)
if not PY2:
value = value.decode(, errors=)
value = _uc(value)
return value | read a string element, maybe encoded in base64 |
369,593 | def find(cls, session, resource_id, include=None):
url = session._build_url(cls._resource_path(), resource_id)
params = build_request_include(include, None)
process = cls._mk_one(session, include=include)
return session.get(url, CB.json(200, process), params=params) | Retrieve a single resource.
This should only be called from sub-classes.
Args:
session(Session): The session to find the resource in
resource_id: The ``id`` for the resource to look up
Keyword Args:
include: Resource classes to include
Returns:
... |
369,594 | def compute(self, nodes):
result = defaultdict(list)
candidates = itertools.combinations(nodes.keys(), 2)
for candidate in candidates:
if (
len(set(nodes[candidate[0]]).intersection(nodes[candidate[1]]))
>= self.min_int... | Helper function to find edges of the overlapping clusters.
Parameters
----------
nodes:
A dictionary with entires `{node id}:{list of ids in node}`
Returns
-------
edges:
A 1-skeleton of the nerve (intersecting nodes)
simplicies:
... |
369,595 | def close(self):
if self.__delayed_connection_path and self.__connection is None:
self.__initialize_connection()
return
try:
self.check_connection()
except (SystemError, NullDatabaseConnectionError):
return
logger.debug("close c... | Commit and close the connection.
.. seealso:: :py:meth:`sqlite3.Connection.close` |
369,596 | def predict(self, features, batch_size = -1):
if isinstance(features, RDD):
return self.predict_distributed(features, batch_size)
else:
return self.predict_local(features, batch_size) | Model inference base on the given data.
:param features: it can be a ndarray or list of ndarray for locally inference
or RDD[Sample] for running in distributed fashion
:param batch_size: total batch size of prediction.
:return: ndarray or RDD[Sample] depend on the the ty... |
369,597 | def format_stack_frame_json(self):
stack_frame_json = {}
stack_frame_json[] = get_truncatable_str(
self.func_name)
stack_frame_json[] = get_truncatable_str(
self.original_func_name)
stack_frame_json[] = get_truncatable_str(self.file_name)
stack_fr... | Convert StackFrame object to json format. |
369,598 | def start(self):
if not hasattr(self,"thread") or not self.thread.isAlive():
self.thread = threading.Thread(target=self.__run)
self.status = RUNNING
self.reset()
self.thread.start()
else:
print("Clock already running!") | Starts the clock from 0.
Uses a separate thread to handle the timing functionalities. |
369,599 | def univprop(self):
self.ignore(whitespace)
if not self.nextstr():
self._raiseSyntaxError()
name = self.noms(varset)
if not name:
mesg =
self._raiseSyntaxError(mesg=mesg)
if not isUnivName(name):
self._raiseSyntaxError(... | .foo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.