Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
358,400 | def _get_info(self, host, port, unix_socket, auth):
client = self._client(host, port, unix_socket, auth)
if client is None:
return None
info = client.info()
del client
return info | Return info dict from specified Redis instance
:param str host: redis host
:param int port: redis port
:rtype: dict |
358,401 | def calculate_solidity(labels,indexes=None):
if indexes is not None:
indexes = np.array(indexes,dtype=np.int32)
areas = scind.sum(np.ones(labels.shape),labels,indexes)
convex_hull_areas = calculate_convex_hull_areas(labels, indexes)
return areas / convex_hull_areas | Calculate the area of each label divided by the area of its convex hull
labels - a label matrix
indexes - the indexes of the labels to measure |
358,402 | def requires_token_auth(resource):
@functools.wraps(resource)
def decorated(*args, **kwargs):
token = flask.request.headers.get()
user = check_token(token)
if not token or user is None:
log.warn(, token=token)
return auth_failed()
flask.g.u... | Flask decorator protecting ressources using token scheme |
358,403 | def parse_reports(self):
self.read_dups = dict()
for f in self.find_log_files():
if f[].startswith():
if f[] in self.read_dups:
log.debug("Duplicate sample name found! Overwriting: {}".format(f[]))
self.add_data_source(f, section=)
sel... | Find RSeQC read_duplication reports and parse their data |
358,404 | def addEdge(self, outVertex, inVertex, label):
n1 = outVertex.neoelement
n2 = inVertex.neoelement
edge = n1.relationships.create(label, n2)
return Edge(edge) | Creates a new edge
@params outVertex: Edge origin Vertex
@params inVertex: Edge target vertex
@params label: Edge label
@returns The created Edge object |
358,405 | def run_simple(hostname, port, application, use_reloader=False,
use_debugger=False, use_evalex=True,
extra_files=None, reloader_interval=1, threaded=False,
processes=1, request_handler=None, static_files=None,
passthrough_errors=False, ssl_context=None):
... | Start an application using wsgiref and with an optional reloader. This
wraps `wsgiref` to fix the wrong default reporting of the multithreaded
WSGI variable and adds optional multithreading and fork support.
This function has a command-line interface too::
python -m werkzeug.serving --help
.... |
358,406 | def decrypt(v, key=None, keyfile=None):
cipher = functions.get_cipher(key, keyfile)
return cipher.decrypt(v) | Encrypt an string |
358,407 | def render_revalidation_failure(self, step, form, **kwargs):
self.storage.current_step = step
return self.render(form, **kwargs) | Gets called when a form doesn't validate when rendering the done
view. By default, it changed the current step to failing forms step
and renders the form. |
358,408 | def unregister(self, recipe):
recipe = self.get_recipe_instance_from_class(recipe)
if recipe.slug in self._registry:
del self._registry[recipe.slug] | Unregisters a given recipe class. |
358,409 | def percent_value(self, percent):
if not isinstance(percent, Decimal):
raise TypeError(u"percent is not an instance of Decimal")
percent = Decimal(max(min(percent, 100), 0) / 100)
return self.begin + self.length * percent | Returns the time value at ``percent`` of this interval.
:param percent: the percent
:type percent: :class:`~aeneas.exacttiming.Decimal`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeValue` |
358,410 | def _named_stream(self, name, binary=False):
with self._store.save_stream(self._named_key(name), binary=binary) as s:
yield s | Create an indexed output stream i.e. 'test_00000001.name'
:param name: Identifier for the stream
:return: A context-managed stream-like object |
358,411 | def update_pypsa_load_timeseries(network, loads_to_update=None,
timesteps=None):
_update_pypsa_timeseries_by_type(
network, type=, components_to_update=loads_to_update,
timesteps=timesteps) | Updates load time series in pypsa representation.
This function overwrites p_set and q_set of loads_t attribute of
pypsa network.
Be aware that if you call this function with `timesteps` and thus overwrite
current time steps it may lead to inconsistencies in the pypsa network
since only load time s... |
358,412 | def delete(self):
self.manager.session.delete(self.uri)
self.manager._metrics_contexts.remove(self) | Delete this :term:`Metrics Context` resource.
Raises:
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError`
:exc:`~zhmcclient.AuthError`
:exc:`~zhmcclient.ConnectionError` |
358,413 | def publish(self, channel_id):
payload = {
"channel_id":channel_id,
}
response = config.SESSION.post(config.publish_channel_url(), data=json.dumps(payload))
response.raise_for_status() | publish: publishes tree to Kolibri
Args:
channel_id (str): channel's id on Kolibri Studio
Returns: None |
358,414 | def add_bboxes_to_image(image, bboxes, color=, width=1):
def expanded_bbox(bbox, n):
l = min(bbox[0][0], bbox[1][0])
r = max(bbox[0][0], bbox[1][0])
t = min(bbox[0][1], bbox[1][1])
b = max(bbox[0][1], bbox[1][1])
return ((l - n, t - n), (r + n, b + n))
from... | Draw rectangles on the image for the bounding boxes
Returns a PIL.Image
Arguments:
image -- input image
bboxes -- bounding boxes in the [((l, t), (r, b)), ...] format
Keyword arguments:
color -- color to draw the rectangles
width -- line width of the rectangles
Example:
image = Image... |
358,415 | def one_of(self, items):
return self._generate_test(
lambda value: value in items,
(, self._path, freeze(items))
) | Check if the value is contained in a list or generator.
>>> Query().f1.one_of(['value 1', 'value 2'])
:param items: The list of items to check with |
358,416 | def unwatch_source(self, source_id):
source_id = int(source_id)
self._watched_sources.remove(source_id)
return (yield from
self._send_cmd("WATCH S[%d] OFF" % (
source_id, ))) | Remove a souce from the watchlist. |
358,417 | def prepend_child(self, name):
return XMLElement(lib.lsl_prepend_child(self.e, str.encode(name))) | Prepend a child element with the specified name. |
358,418 | def _dict_of_funcs(self, funcs: list) -> pd.Series:
return {func.__name__: func for func in funcs} | Return a pd.Series of functions with index derived from the function name. |
358,419 | def reduce_l2(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {:})
return , new_attrs, inputs | Reduce input tensor by l2 normalization. |
358,420 | def rap(self,analytic=False,pot=None,**kwargs):
if analytic:
self._setupaA(pot=pot,type=)
(rperi,rap)= self._aA.calcRapRperi(self)
return rap
if not hasattr(self,):
raise AttributeError("Integrate the orbit first")
if not hasattr(self,):
... | NAME:
rap
PURPOSE:
return the apocenter radius
INPUT:
analytic - compute this analytically
pot - potential to use for analytical calculation
OUTPUT:
R_ap
HISTORY:
2010-09-20 - Written - Bovy (NYU) |
358,421 | def copy(self, **params):
new_params = dict()
for name in [, , , ]:
new_params[name] = params.get(name, getattr(self, name))
return Route(**new_params) | Creates the new instance of the Route substituting the requested
parameters. |
358,422 | def p_mp_createInstance(p):
inst = p[1]
if p.parser.verbose:
p.parser.log(
_format("Creating instance of {0!A}.", inst.classname))
try:
p.parser.handle.CreateInstance(inst)
except CIMError as ce:
if ce.status_code == CIM_ERR_ALREADY_EXISTS:
if p.parse... | mp_createInstance : instanceDeclaration |
358,423 | def getAMFRequest(self, requests):
envelope = remoting.Envelope(self.amf_version)
if self.logger:
self.logger.debug( % self.amf_version)
for request in requests:
service = request.service
args = list(request.args)
envelope[request.id] =... | Builds an AMF request {LEnvelope<pyamf.remoting.Envelope>} from a
supplied list of requests. |
358,424 | def getPageContent(url, session, max_content_bytes=MaxContentBytes):
check_robotstxt(url, session)
try:
page = urlopen(url, session, max_content_bytes=max_content_bytes)
except IOError:
page = urlopen(url, session, max_content_bytes=max_content_bytes)
data = page.text
tries... | Get text content of given URL. |
358,425 | def create_customer(self, full_name, email):
log.warning()
data = {: full_name, : email}
return self.post(, headers=self.experimental_headers, data=data) | Creating customer user
:param full_name: str
:param email: str
:return: New customer |
358,426 | def get_bond_master(interface):
if interface:
iface_path = % (interface)
if os.path.exists(iface_path):
if in os.path.realpath(iface_path):
return None
master = os.path.join(iface_path, )
if os.path.exists(master):
master = ... | Returns bond master if interface is bond slave otherwise None.
NOTE: the provided interface is expected to be physical |
358,427 | def _set_ssm_enable(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=ssm_enable.ssm_enable, is_container=, presence=True, yang_name="ssm-enable", rest_name="ssm-enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_... | Setter method for ssm_enable, mapped from YANG variable /routing_system/router/hide_pim_holder/pim/ssm_enable (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ssm_enable is considered as a private
method. Backends looking to populate this variable should
do so... |
358,428 | def calc_delay(remainingDrops):
global sameDelay, lastDelay
if remainingDrops > 1:
lastDelay = 5
sameDelay = 0
if remainingDrops > 2:
return 15 * 60
elif remainingDrops == 2:
return 10 * 60
else:
if lastDelay > 1:
if sameDela... | Calculate the idle delay
Minimum play time for cards to drop is ~20min again. Except for accounts
that requested a refund?
Re-check every 15 mintes if there are more than 1 card drops remaining.
If only one drop remains, check every 5 minutes |
358,429 | def save(obj, path=None, name=None, sep=_sep, deep=False, mode=,
strip=None, compressed=False, verb=True, return_pfe=False):
msg = "Arg obj must be a tofu subclass instance !"
assert issubclass(obj.__class__, ToFuObject), msg
msg = "Arg path must be None or a str (folder) !"
assert path is... | Save the ToFu object
ToFu provides built-in saving and loading functions for ToFu objects.
Specifying saving path ad name is optional (defaults recommended)
The mode refers to the file format
Good practices are:
- save all struct objects
Parameters
----------
obj : ToFuObjec... |
358,430 | def write_skycatalog(self,filename):
if self.all_radec is None:
return
ralist = self.all_radec[0]
declist = self.all_radec[1]
f = open(filename,)
f.write("
f.write("
f.write("
for i in range(len(ralist)):
f.write(%(ralist[i... | Write out the all_radec catalog for this image to a file. |
358,431 | def revoke_security_group_deprecated(self, group_name,
src_security_group_name=None,
src_security_group_owner_id=None,
ip_protocol=None,
from_port=None, to_... | NOTE: This method uses the old-style request parameters
that did not allow a port to be specified when
authorizing a group.
Remove an existing rule from an existing security group.
You need to pass in either src_security_group_name and
src_security_group_owner_id OR ... |
358,432 | async def read(cls, *, hostnames: typing.Sequence[str] = None):
params = {}
if hostnames:
params["hostname"] = [
normalize_hostname(hostname)
for hostname in hostnames
]
data = await cls._handler.read(**params)
return cls(m... | List nodes.
:param hostnames: Sequence of hostnames to only return.
:type hostnames: sequence of `str` |
358,433 | def knuth(data):
import scipy.optimize as optimize
def f(data):
from scipy.special import gammaln
m, M = np.min(data), np.max(data)
n = len(data)
def fff(x):
k = x[0]
if k <= 0:
return float... | References
----------
.. [1] K. Knuth, "Optimal Data-Based Binning for Histograms", 2006.
http://arxiv.org/pdf/physics/0605197v1.pdf |
358,434 | def root(self) -> "GameNode":
node = self
while node.parent:
node = node.parent
return node | Gets the root node, i.e., the game. |
358,435 | def face_ordering(mesh):
norms = mesh.edges_unique_length[
mesh.edges_unique_inverse].reshape((-1, 3))
small = norms.argmin(axis=1)
MLidx = np.column_stack((small + 1, small + 2)) % 3
MLidx += (np.arange(len(small)) * 3).reshape((-1, 1))
diff = np.subtract(*... | Triangles with three different length sides are
ordered in two ways:
[small edge, medium edge, large edge] (SML)
[small edge, large edge, medium edge] (SLM)
This function returns [-1, 0, 1], depending on whether
the triangle is SML or SLM, and 0 if M == L.
The reason this is useful as it as a... |
358,436 | def set_network_permission(network_id, usernames, read, write, share,**kwargs):
user_id = kwargs.get()
net_i = _get_network(network_id)
net_i.check_share_permission(user_id)
if read == :
write =
share =
for username in usernames:
user_i = _get_user(user... | Set permissions on a network to a list of users, identifed by
their usernames. The read flag ('Y' or 'N') sets read access, the write
flag sets write access. If the read flag is 'N', then there is
automatically no write access or share access. |
358,437 | async def _connect(self):
if self._poller:
self._poller.join()
self._driver.connect(self._port)
self._device_info = self._driver.get_device_info()
self._poller = Poller(self._driver)
self._poller.start() | Connect to the 'TempDeck' port
Planned change- will connect to the correct port in case of multiple
TempDecks |
358,438 | def get_ext(url):
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(parsed.path)
return ext.lstrip() | Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present. |
358,439 | def tracking_number(self, service: str = ) -> str:
service = service.lower()
if service not in (, , ):
raise ValueError()
services = {
: (
,
,
),
: (
,
,
),
... | Generate random tracking number.
Supported services: USPS, FedEx and UPS.
:param str service: Post service.
:return: Tracking number. |
358,440 | def wait_for_provision_state(baremetal_client, node_uuid, provision_state,
loops=10, sleep=1):
for _ in range(0, loops):
node = baremetal_client.node.get(node_uuid)
if node is None:
return True
if node.provision_stat... | Wait for a given Provisioning state in Ironic Discoverd
Updating the provisioning state is an async operation, we
need to wait for it to be completed.
:param baremetal_client: Instance of Ironic client
:type baremetal_client: ironicclient.v1.client.Client
:param node_uuid: The Ironic node UUID
... |
358,441 | def _search_type_in_type_comment(self, code):
for p in self.PEP0484_TYPE_COMMENT_PATTERNS:
match = p.search(code)
if match:
return [match.group(1)] | For more info see:
https://www.python.org/dev/peps/pep-0484/#type-comments
>>> AssignmentProvider()._search_type_in_type_comment('type: int')
['int'] |
358,442 | def get_coiledcoil_region(self, cc_number=0, cutoff=7.0, min_kihs=2):
g = self.filter_graph(self.graph, cutoff=cutoff, min_kihs=min_kihs)
ccs = sorted(networkx.connected_component_subgraphs(g, copy=True),
key=lambda x: len(x.nodes()), reverse=True)
cc = ... | Assembly containing only assigned regions (i.e. regions with contiguous KnobsIntoHoles. |
358,443 | def get_child_models(self):
child_models = []
for plugin in self.child_model_plugin_class.get_plugins():
child_models.append((plugin.model, plugin.model_admin))
if not child_models:
child_models.append((
self.child_model_admin.base_model,
... | Get child models from registered plugins. Fallback to the child model
admin and its base model if no plugins are registered. |
358,444 | def extrude_triangulation(vertices,
faces,
height,
**kwargs):
vertices = np.asanyarray(vertices, dtype=np.float64)
height = float(height)
faces = np.asanyarray(faces, dtype=np.int64)
if not util.is_shape(vertices, (-1, 2... | Turn a 2D triangulation into a watertight Trimesh.
Parameters
----------
vertices : (n, 2) float
2D vertices
faces : (m, 3) int
Triangle indexes of vertices
height : float
Distance to extrude triangulation
**kwargs:
passed to Trimesh
Returns
---------
mesh... |
358,445 | def list_by_x(prs, key):
if key == "type":
kfn = operator.methodcaller(key)
res = sorted(((k, sort_by_prio(g)) for k, g
in anyconfig.utils.groupby(prs, kfn)),
key=operator.itemgetter(0))
elif key == "extensions":
res = select_by_key(((p.ex... | :param key: Grouping key, "type" or "extensions"
:return:
A list of :class:`Processor` or its children classes grouped by
given 'item', [(cid, [:class:`Processor`)]] by default |
358,446 | def getArguments(parser):
"Provides additional validation of the arguments collected by argparse."
args = parser.parse_args()
if args.example:
args.example_image, args.example_header = load(args.example)
dimensions = args.example_image.ndim
else:
dimensions = len(args.shape)... | Provides additional validation of the arguments collected by argparse. |
358,447 | def extract_as_epilog(self, text, sections=None, overwrite=False,
append=True):
if sections is None:
sections = self.epilog_sections
if ((not self.epilog or overwrite or append) and sections):
epilog_parts = []
for sec in sections:
... | Extract epilog sections from the a docstring
Parameters
----------
text
The docstring to use
sections: list of str
The headers of the sections to extract. If None, the
:attr:`epilog_sections` attribute is used
overwrite: bool
If Tr... |
358,448 | def convert_to_single_placement_group(
self, resource_group_name, vm_scale_set_name, active_placement_group_id=None, custom_headers=None, raw=False, **operation_config):
parameters = models.VMScaleSetConvertToSinglePlacementGroupInput(active_placement_group_id=active_placement_group_id)
... | Converts SinglePlacementGroup property to false for a existing virtual
machine scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_scale_set_name: The name of the virtual machine scale set to
create or update.
... |
358,449 | def get_method_description(method):
try:
try:
line_no = inspect.getsourcelines(method)[1]
except IOError:
line_no = -1
return " ({file}:{line})".format(
method=method.__name__, file=inspect.getfile(method), line=line_no
)
... | Retrieves a description of the given method. If possible, the description
contains the source file name and line.
:param method: A method
:return: A description of the method (at least its name)
:raise AttributeError: Given object has no __name__ attribute |
358,450 | def write_newick(rootnode,
features=None,
format=1,
format_root_node=True,
is_leaf_fn=None,
dist_formatter=None,
support_formatter=None,
name_formatter=None):
newick = []
leaf = is_leaf_fn if is_leaf_fn else lambda n: not bool(n.children)
for postorder, node in rootnode.iter_prep... | Iteratively export a tree structure and returns its NHX
representation. |
358,451 | def __extract_file(self, path, fileinfo, destination):
if not in fileinfo:
self.__copy_extracted(path, destination)
return
self.asarfile.seek(
self.__absolute_offset(fileinfo[])
)
contents = self.asarfile.read(
self.__... | Extracts the specified file to the specified destination.
Args:
path (str):
Relative (to the root of the archive) path of the
file to extract.
fileinfo (dict):
Dictionary containing the offset and size of the file
(Extract... |
358,452 | def _update_checksum(self):
source_list = [int(octet) for octet in self.source.split(".")]
destination_list = [int(octet) for octet in
self.destination.split(".")]
source_upper = (source_list[0] << 8) + source_list[1]
source_lower = (source_list[2] <<... | Update the packet checksum to enable integrity check. |
358,453 | def calc_mass_from_z0(z0, w0):
T0 = 300
mFromEquipartition = Boltzmann*T0/(w0**2 * z0**2)
return mFromEquipartition | Calculates the mass of the particle using the equipartition
from the angular frequency of the z signal and the average
amplitude of the z signal in nms.
Parameters
----------
z0 : float
Physical average amplitude of motion in nms
w0 : float
Angular Frequency of z motion
Ret... |
358,454 | def _translate_name(name):
underscored = inflection.underscore(name)
dasherized = inflection.dasherize(underscored)
words = dasherized.split()
last_word = words.pop()
words.append(inflection.pluralize(last_word))
return .join(words) | Translate the class name to the API endpoint.
For example, Car would become cars, FastCar would become fast-cars.
Args:
name (string): Camel case name (singular)
Returns:
string: A pluraised, dasherized string. |
358,455 | def url(self):
return reverse( % URL_NAMESPACE, kwargs={
: self.module,
: type(self).__name__,
}) | The URL to access this preview. |
358,456 | def consumer(self, service, data, to_update, status):
service_consumer = default_provider.get_service(str(service.consumer.name.name))
kwargs = {: service.user}
getattr(service_consumer, )(service.consumer.token, **kwargs)
instance = getattr(service_consumer, )
... | call the consumer and handle the data
:param service:
:param data:
:param to_update:
:param status:
:return: status |
358,457 | def from_json_compatible(schema, dct):
"Load from json-encodable"
kwargs = {}
for key in dct:
field_type = schema._fields.get(key)
if field_type is None:
raise ParseError("Unexpected field encountered in line for record %s: %s" % (schema.__name__, key))
kwargs[key] = fie... | Load from json-encodable |
358,458 | def add_exp_key(self, key, value, ex):
"Expired in seconds"
return self.c.set(key, value, ex) | Expired in seconds |
358,459 | def _categoryToLabelList(self, category):
if category is None:
return []
labelList = []
labelNum = 0
while category > 0:
if category % 2 == 1:
labelList.append(self.saved_categories[labelNum])
labelNum += 1
category = category >> 1
return labelList | Converts a category number into a list of labels |
358,460 | def __merge_nearest_successors(self, node):
merging_result = False;
if (node.successors[0].type == cfnode_type.CFNODE_NONLEAF):
[nearest_child_node1, nearest_child_node2] = node.get_nearest_successors(self.__type_measurement);
if (l... | !
@brief Find nearest sucessors and merge them.
@param[in] node (non_leaf_node): Node whose two nearest successors should be merged.
@return (bool): True if merging has been successfully performed, otherwise False. |
358,461 | def simple_merge(kls, skeletons):
if len(skeletons) == 0:
return PrecomputedSkeleton()
if type(skeletons[0]) is np.ndarray:
skeletons = [ skeletons ]
ct = 0
edges = []
for skel in skeletons:
edge = skel.edges + ct
edges.append(edge)
ct += skel.vertices.shape[0]
... | Simple concatenation of skeletons into one object
without adding edges between them. |
358,462 | def run_script_api(module_name):
filename =
file_stream =
form = request.values.to_dict(flat=False)
if request.json:
form.update(request.json)
for x in form:
if type(form[x]) == list and len(form[x]) == 1:
form[x] = form[x][0]
for x in form:
form[x... | API handler. Take script input (from script_input above), run the run()
function, and return the results |
358,463 | def add_tag(context, id, name):
result = job.add_tag(context, id=id, name=name)
utils.format_output(result, context.format) | add_tag(context, id, name)
Attach a tag to a job.
>>> dcictl job-add-tag [OPTIONS]
:param string id: ID of the job to attach the tag on [required]
:param string tag_name: name of the tag to be attached [required] |
358,464 | def setup_step_out(self, frame):
self.frame_calling = None
self.frame_stop = None
self.frame_return = frame.f_back
self.frame_suspend = False
self.pending_stop = True
return | Setup debugger for a "stepOut" |
358,465 | def _group_tasks_by_jobid(tasks):
ret = collections.defaultdict(list)
for t in tasks:
ret[t.get_field()].append(t)
return ret | A defaultdict with, for each job, a list of its tasks. |
358,466 | def delete_ikepolicy(self, ikepolicy):
ikepolicy_id = self._find_ikepolicy_id(ikepolicy)
ret = self.network_conn.delete_ikepolicy(ikepolicy_id)
return ret if ret else True | Deletes the specified IKEPolicy |
358,467 | def record_manifest(self):
data = {}
data[] = self.install_required(type=SYSTEM, verbose=False, list_only=True)
data[].sort()
data[] = self.install_custom(list_only=True)
data[].sort()
data[] = self.get_repositories()
return data | Returns a dictionary representing a serialized state of the service. |
358,468 | def log_stack(self, signal, frame):
gen_log.warning(,
self._blocking_signal_threshold,
.join(traceback.format_stack(frame))) | Signal handler to log the stack trace of the current thread.
For use with `set_blocking_signal_threshold`. |
358,469 | def setValue(self, value):
if self.name in self._CUSTOM_INT_PARAMS:
value = int(value)
elif self.name in self._CUSTOM_FLOAT_PARAMS:
value = float(value)
elif self.name in self._CUSTOM_BOOL_PARAMS:
value = bool(value)
elif self.name in self._CU... | Cast some known data in custom parameters. |
358,470 | def _has_valid_abs_ref(self, i, construction_table):
c_table = construction_table
abs_refs = constants.absolute_refs
A = np.empty((3, 3))
row = c_table.index.get_loc(i)
if row > 2:
message = .format
raise ValueError(message(i=i))
for k in ... | Checks, if ``i`` uses valid absolute references.
Checks for each index from first to third row of the
``construction_table``, if the references are colinear.
This case has to be specially treated, because the references
are not only atoms (to fix internal degrees of freedom) but also po... |
358,471 | def command(self, *args, **kwargs):
def wrapper(func):
self.add_command(func, *args, **kwargs)
return func
return wrapper | Attach a command to the current :class:`CLI` object.
The function should accept an instance of an
:class:`argparse.ArgumentParser` and use it to define extra
arguments and options. These options will only affect the specified
command. |
358,472 | def extract_message_info():
base_path = BASE_PACKAGE.replace(, )
filename = os.path.join(base_path, )
with open(filename, ) as file:
types_found = False
for line in file:
stripped = line.lstrip().rstrip()
if stripped == :
types_fou... | Get information about all messages of interest. |
358,473 | def record_get_field_values(rec, tag, ind1=" ", ind2=" ", code="",
filter_subfield_code="",
filter_subfield_value="",
filter_subfield_mode="e"):
tmp = []
ind1, ind2 = _wash_indicators(ind1, ind2)
if filter_subfield_co... | Return the list of values for the specified field of the record.
List can be filtered. Use filter_subfield_code
and filter_subfield_value to search
only in fields that have these values inside them as a subfield.
filter_subfield_mode can have 3 different values:
'e' for exact search
's' for sub... |
358,474 | def parse_gene_list(path: str, graph: Graph, anno_type: str = "name") -> list:
genes = pd.read_csv(path, header=None)[0].tolist()
genes = [str(int(gene)) for gene in genes]
ind = []
if anno_type == "name":
ind = graph.vs.select(name_in=genes).indices
elif anno_type == "symbol... | Parse a list of genes and return them if they are in the network.
:param str path: The path of input file.
:param Graph graph: The graph with genes as nodes.
:param str anno_type: The type of annotation with two options:name-Entrez ID, symbol-HGNC symbol.
:return list: A list of genes, all of which are... |
358,475 | def record(self):
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError()
return struct.pack(, self.vd.extent_location(),
self.inode.extent_location(), self.orig_len,
self.csum) + b * 40 | A method to generate a string representing this boot info table.
Parameters:
None.
Returns:
A string representing this boot info table. |
358,476 | def prepare_new_dataset():
clean_dir = ev(
"OUTPUT_DIR",
"/tmp")
clean_file = ev(
"CLEANED_FILE",
"{}/cleaned_attack_scans.csv".format(
clean_dir))
fulldata_file = ev(
"FULLDATA_FILE",
"{}/fulldata_attack_scans.csv".format(
clean_d... | prepare_new_dataset |
358,477 | def validate_err_calc(val):
try:
val = validate_float(val)
except (ValueError, TypeError):
pass
else:
if val <= 100 and val >= 0:
return val
raise ValueError("Percentiles for the error calculation must lie "
"between 0 and 100, not %s... | Validation function for the
:attr:`psy_simple.plotter.FldmeanPlotter.err_calc` formatoption |
358,478 | def save_lastfile(self, tfi):
tf = models.TaskFile.objects.get(task=tfi.task, version=tfi.version, releasetype=tfi.releasetype,
descriptor=tfi.descriptor, typ=tfi.typ)
c = self.get_config()
c[] = tf.pk
c.write() | Save the taskfile in the config
:param tfi: the last selected taskfileinfo
:type tfi: class:`jukeboxcore.filesys.TaskFileInfo`
:returns: None
:rtype: None
:raises: None |
358,479 | def plot_irm(fignum, B, M, title):
rpars = {}
Mnorm = []
backfield = 0
X, Y = [], []
for k in range(len(B)):
if M[k] < 0:
break
if k <= 5:
kmin = 0
else:
kmin = k - 5
for k in range(kmin, k + 1):
X.append(B[k])
if B[k] < 0:
... | function to plot IRM backfield curves
Parameters
_________
fignum : matplotlib figure number
B : list or array of field values
M : list or array of magnetizations
title : string title for plot |
358,480 | def parse(self, timestr, default=None, ignoretz=False, tzinfos=None, **kwargs):
if default is None:
default = datetime.datetime.now().replace(hour=0, minute=0,
second=0, microsecond=0)
res, skipped_tokens = self._parse(timestr,... | Parse the date/time string into a :class:`datetime.datetime` object.
:param timestr:
Any date/time string using the supported formats.
:param default:
The default datetime object, if this is a datetime object and not
``None``, elements specified in ``timestr`` repla... |
358,481 | def WmiQueryFromClient(args):
query = args.query
base_object = args.base_object or r"winmgmts:\root\cimv2"
if not query.upper().startswith("SELECT "):
raise RuntimeError("Only SELECT WMI queries allowed.")
for response_dict in RunWMIQuery(query, baseobj=base_object):
yield response_dict | Run the WMI query and return the data. |
358,482 | def get_std_icon(name, size=None):
if not name.startswith():
name = + name
icon = QWidget().style().standardIcon(getattr(QStyle, name))
if size is None:
return icon
else:
return QIcon(icon.pixmap(size, size)) | Get standard platform icon
Call 'show_std_icons()' for details |
358,483 | def list_agents(self):
t = text_helper.Table(fields=("Agent ID", "Agent class", "State"),
lengths=(40, 25, 15))
return t.render((a._descriptor.doc_id, a.log_category,
a._get_machine_state().name)
for a in self._agen... | List agents hosted by the agency. |
358,484 | def scan_for_plugins(directory):
if not os.path.exists(os.path.expanduser(directory)):
raise FileNotFoundError("Unable to locate directory %s" % directory)
files_in_dir = get_files_recursive(directory)
plugins = {}
for file in files_in_dir:
plugins_in_mo... | Scan a directory for modules that contains plugin(s).
:param directory: Path of the folder/directory to scan.
:return: Dictionary of file (key) and plugins (value), where the key is the path of the module and value is a list of plugins inside that module.
:rtype: dict |
358,485 | def is_lti(self):
return self.is_linear() and all(filt.is_lti() for filt in self.callables) | Tests whether all filters in the list are linear time invariant (LTI).
CascadeFilter and ParallelFilter instances are also LTI if all filters
they group are LTI. |
358,486 | def evaluate_trace_request(data, tracer=tracer):
data = ast.literal_eval(data)
if isinstance(data, str):
modules = dict.fromkeys(map(lambda x: x.strip(), data.split(",")), (None, None))
elif isinstance(data, list):
modules = dict.fromkeys(data, (None, None))
elif isinstance(data, ... | Evaluate given string trace request.
Usage::
Umbra -t "{'umbra.engine' : ('.*', 0), 'umbra.preferences' : (r'.*', 0)}"
Umbra -t "['umbra.engine', 'umbra.preferences']"
Umbra -t "'umbra.engine, umbra.preferences"
:param data: Trace request.
:type data: unicode
:param tracer: Tr... |
358,487 | def api2_formula(req):
API_VERSION =
wsgihelpers.track(req.url.decode())
params = dict(req.GET)
data = dict()
try:
extensions_header = req.headers.get()
tax_benefit_system = model.get_cached_composed_reform(
reform_keys = extensions_header.split(),
tax... | A simple `GET`-, URL-based API to OpenFisca, making the assumption of computing formulas for a single person.
Combination
-----------
You can compute several formulas at once by combining the paths and joining them with `+`.
Example:
```
/salaire_super_brut+salaire_net_a_payer?salaire_de_base=1440
```
This will com... |
358,488 | def pseudos_with_symbols(self, symbols):
pseudos = self.select_symbols(symbols, ret_list=True)
found_symbols = [p.symbol for p in pseudos]
duplicated_elements = [s for s, o in collections.Counter(found_symbols).items() if o > 1]
if duplicated_elements:
raise ValueEr... | Return the pseudos with the given chemical symbols.
Raises:
ValueError if one of the symbols is not found or multiple occurences are present. |
358,489 | def fmt_angle(val, s1=" ", s2=" ", s3="", pre=3, trunc=False,
lower=None, upper=None, b=False, upper_trim=False):
x = deci2sexa(val, pre=pre, trunc=trunc, lower=lower, upper=upper,
upper_trim=upper_trim, b=b)
left_digits_plus_deci_point = 3 if pre > 0 else 2
p = "{3:0" ... | Return sexagesimal string of given angle in degrees or hours.
Parameters
----------
val : float
The angle (in degrees or hours) that is to be converted into a
sexagesimal string.
s1 : str
Character to be used between the first and second parts of the
the sexagesimal repr... |
358,490 | def to_vars_dict(self):
return {
: self._client_id,
: self._client_secret,
: self._network,
: self._project_id,
: self._zone,
} | Return local state which is relevant for the cluster setup process. |
358,491 | def update_reportnumbers(self):
report_037_fields = record_get_field_instances(self.record, )
for field in report_037_fields:
subs = field_get_subfields(field)
for val in subs.get("a", []):
if "arXiv" not in val:
record_delete_field(se... | Update reportnumbers. |
358,492 | def format_json(event, colored):
try:
if event.message.startswith("{"):
msg_dict = json.loads(event.message)
event.message = json.dumps(msg_dict, indent=2)
except Exception:
pass
return event | If the event message is a JSON string, then pretty print the JSON with 2 indents and sort the keys. This makes
it very easy to visually parse and search JSON data |
358,493 | def flatten(dictionary, parent_key=False, separator=):
items = []
for key, value in dictionary.items():
new_key = str(parent_key) + separator + key if parent_key else key
if isinstance(value, collections.MutableMapping):
items.extend(flatten(value, new_key, separator).it... | Turn a nested dictionary into a flattened dictionary
:param dictionary: The dictionary to flatten
:param parent_key: The string to prepend to dictionary's keys
:param separator: The string used to separate flattened keys
:return: A flattened dictionary |
358,494 | def remove_entry(self, entry = None):
if entry is None or type(entry) is not v1Entry:
raise KPError("Need an entry.")
elif entry in self.entries:
entry.group.entries.remove(entry)
self.entries.remove(entry)
self._num_entries -= 1
... | This method can remove entries.
The v1Entry-object entry is needed. |
358,495 | def getToC(doc, simple = True):
def recurse(olItem, liste, lvl):
while olItem:
if olItem.title:
title = olItem.title
else:
title = " "
if not olItem.isExternal:
if olItem.uri:
page = olIte... | Create a table of contents.
Args:
simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation. |
358,496 | def get_registered_loggers(hide_children=False, hide_reusables=False):
return [logger for logger in logging.Logger.manager.loggerDict.keys()
if not (hide_reusables and "reusables" in logger)
and not (hide_children and "." in logger)] | Find the names of all loggers currently registered
:param hide_children: only return top level logger names
:param hide_reusables: hide the reusables loggers
:return: list of logger names |
358,497 | def countdown(
seconds=None,
block=True,
interval=1,
daemon=True,
tick_callback=None,
finish_callback=None,
):
def default_tick_callback(s, seconds, *args):
flush_print(s, sep="", end=" ")
def default_finish_callback(seconds, start_time):
flush_print()
def cd(... | Run a countdown function to wait something, similar to threading.Timer,
but will show the detail tick by tick_callback.
::
from torequests.utils import countdown
countdown(3)
# 3 2 1
# countdown finished [3 seconds]: 2018-06-13 00:12:55 => 2018-06-13 00:12:58.
countd... |
358,498 | def hasAttribute(self, attr: str) -> bool:
if attr == :
return bool(self.classList)
return attr in self.attributes | Return True if this node has ``attr``. |
358,499 | def pipe(maxsize=0, *, loop=None) -> Pipe:
class QueueStream:
def __init__(self, maxsize=0, *, loop=None) -> None:
self._queue: asyncio.Queue = asyncio.Queue(maxsize, loop=loop)
self._eof = asyncio.locks.Event(loop=loop)
def _check_send(self, value: Any, *, eof: bool) ... | \
A bidirectional pipe of Python objects.
>>> async def example1():
... a, b = pipe()
... a.send_nowait('foo')
... print(await b.recv())
>>> asyncio.run(example1())
foo
>>> async def example2():
... a, b = pipe()
... await b.send(eof=True)
... await a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.