Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
345,200 | def is_cached(file_name):
gml_file_path = join(join(expanduser(), OCTOGRID_DIRECTORY), file_name)
return isfile(gml_file_path) | Check if a given file is available in the cache or not |
345,201 | def is_timeout(self):
lapse = datetime.datetime.now() - self.init_time
return lapse > datetime.timedelta(seconds=self.timeout) | Check if the lapse between initialization and now is more than ``self.timeout``. |
345,202 | def command_health(self):
if len(self.args) == 1 and self.args[0] == "health":
PackageHealth(mode="").test()
elif (len(self.args) == 2 and self.args[0] == "health" and
self.args[1] == "--silent"):
PackageHealth(mode=self.args[1]).test()
else:
... | Check package health |
345,203 | def account_matching_address(self, address, return_default=False):
_, address = email.utils.parseaddr(address)
for account in self.get_accounts():
if account.matches_address(address):
return account
if return_default:
try:
return s... | returns :class:`Account` for a given email address (str)
:param str address: address to look up. A realname part will be ignored.
:param bool return_default: If True and no address can be found, then
the default account wil be returned.
:rtype: :class:`Account`
:raises ~alot... |
345,204 | def fem(ab, off, angle, zsrc, zrec, lsrc, lrec, depth, freq, etaH, etaV, zetaH,
zetaV, xdirect, isfullspace, ht, htarg, use_ne_eval, msrc, mrec,
loop_freq, loop_off, conv=True):
r
fEM = np.zeros((freq.size, off.size), dtype=complex)
kcount = 0
if ab in [36, ]:
... | r"""Return the electromagnetic frequency-domain response.
This function is called from one of the above modelling routines. No
input-check is carried out here. See the main description of :mod:`model`
for information regarding input and output parameters.
This function can be directly used if you are ... |
345,205 | def _cache_for_link(cache_dir, link):
key_parts = [link.url_without_fragment]
if link.hash_name is not None and link.hash is not None:
key_parts.append("=".join([link.hash_name, link.hash]))
key_url = "
hashed = hashlib.sha224(key_url.encode()).hexdigest()
pa... | Return a directory to store cached wheels in for link.
Because there are M wheels for any one sdist, we provide a directory
to cache them in, and then consult that directory when looking up
cache hits.
We only insert things into the cache if they have plausible version
numbers, so that we don't co... |
345,206 | def make_cfglbls(cfgdict_list, varied_dict):
import textwrap
wrapper = textwrap.TextWrapper(width=50)
cfglbl_list = []
for cfgdict_ in cfgdict_list:
cfgdict = cfgdict_.copy()
for key in six.iterkeys(cfgdict_):
try:
vals = varied_dict[key]
... | Show only the text in labels that mater from the cfgdict |
345,207 | def _serialize_item(item):
if isinstance(item, (list, tuple)):
return [_serialize_item(subitem) for subitem in item]
elif isinstance(item, dict):
return dict([(key, _serialize_item(value))
for (key, value) in iteritems(item)])
elif isinstance(item, string... | Internal function: serialize native types. |
345,208 | def get_hosted_service_properties(self, service_name, embed_detail=False):
s deployments.
service_name:
Name of the hosted service.
embed_detail:
When True, the management service returns properties for all
deployments of the service, as well as for the servi... | Retrieves system properties for the specified hosted service. These
properties include the service name and service type; the name of the
affinity group to which the service belongs, or its location if it is
not part of an affinity group; and optionally, information on the
service's depl... |
345,209 | def from_array(a, mode=None, info=None):
if info is None:
info = {}
else:
info = dict(info)
grayscale, alpha, bitdepth = parse_mode(mode)
if in info:
if bool(info[]) != grayscale:
raise Error("info[] should match mode.")
info[] = grayscale
... | Create a PNG :class:`Image` object from a 2- or 3-dimensional array.
One application of this function is easy PIL-style saving:
``png.from_array(pixels, 'L').save('foo.png')``.
.. note :
The use of the term *3-dimensional* is for marketing purposes
only. It doesn't actually work. Please bea... |
345,210 | def find_template(self, name=None, hv=None):
if len(self.templates) <= 0:
self.get_hypervisors()
if name is not None and hv is not None:
template_list = filter(
lambda x: name in x.descr and x.hypervisor == self.hypervisors[hv], self.templates
... | Return a list of templates that could have one or more elements.
Args:
name: name of the template to find.
hv: the ID of the hypervisor to search the template in
Returns:
A list of templates object. If hv is None will return all the
templates matching the ... |
345,211 | def serve_record(self, environ, coll=, url=):
if coll in self.warcserver.list_fixed_routes():
return WbResponse.text_response(.format(coll))
return self.serve_content(environ, coll, url, record=True) | Serve a URL's content from a WARC/ARC record in replay mode or from the live web in
live, proxy, and record mode.
:param dict environ: The WSGI environment dictionary for the request
:param str coll: The name of the collection the record is to be served from
:param str url: The URL for ... |
345,212 | def filenames_to_uniq(names,new_delim=):
.-ABAA.BBCC
name_words = []
maxlen = 0
for name in names:
name_words.append(name.replace(,).replace(,).strip().split())
name_words[-1].reverse()
if len(name_words[-1]) > maxlen:
maxlen = len(name_words[-1])
common = [False... | Given a set of file names, produce a list of names consisting of the
uniq parts of the names. This works from the end of the name. Chunks of
the name are split on '.' and '-'.
For example:
A.foo.bar.txt
B.foo.bar.txt
returns: ['A','B']
AA.BB.foo.txt
CC.foo.... |
345,213 | def _get_plural_legacy(amount, extra_variants):
absence = None
if isinstance(extra_variants, six.text_type):
extra_variants = split_values(extra_variants)
if len(extra_variants) == 4:
variants = extra_variants[:3]
absence = extra_variants[3]
else:
variants = extra_va... | Get proper case with value (legacy variant, without absence)
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects, 0-object variant).
0-object variant is similar to C{absence} in C{get_plur... |
345,214 | def _make_query_from_terms(self, terms, limit=None):
expanded_terms = self._expand_terms(terms)
terms_used = 0
if expanded_terms[]:
query_parts = ["SELECT vid, dataset_vid, ts_rank_cd(setweight(doc,), to_tsquery(:doc)) as score"]
if expanded_terms[] and... | Creates a query for partition from decomposed search terms.
Args:
terms (dict or unicode or string):
Returns:
tuple of (TextClause, dict): First element is FTS query, second is
parameters of the query. Element of the execution of the query is
tuple of th... |
345,215 | def close(self) -> None:
if self.session_id is not None:
self.client.delete_session(self.session_id)
self.client.close() | Kill the managed Spark session. |
345,216 | def get_access_token(self, verifier=None):
if self._access_token is None:
self._access_token, self._access_token_dict = self._get_access_token(verifier)
return self._access_token | Return the access token for this API. If we've not fetched it yet,
go out, request and memoize it. |
345,217 | def update_screen(self):
self.clock.tick(self.FPS)
pygame.display.update() | Refresh the screen. You don't need to override this except to update only small portins of the screen. |
345,218 | def _is_valid_netmask(self, netmask):
mask = netmask.split()
if len(mask) == 4:
try:
for x in mask:
if int(x) not in self._valid_mask_octets:
return False
except ValueError:
retu... | Verify that the netmask is valid.
Args:
netmask: A string, either a prefix or dotted decimal
netmask.
Returns:
A boolean, True if the prefix represents a valid IPv4
netmask. |
345,219 | def _preprocess_data_for_tabular_explain(self, df, categories):
df = df.copy()
for col in list(df.columns):
if col not in (self._categorical_columns + self._numeric_columns):
del df[col]
for col_name, col_categories in zip(self._categoric... | Get preprocessed training set in numpy array, and categorical names from raw training data.
LIME tabular explainer requires a training set to know the distribution of numeric and
categorical values. The training set has to be numpy arrays, with all categorical values
converted to indices. It al... |
345,220 | def _addsub_offset_array(self, other, op):
assert op in [operator.add, operator.sub]
if len(other) == 1:
return op(self, other[0])
warnings.warn("Adding/subtracting array of DateOffsets to "
"{cls} not vectorized"
.format(cls=type... | Add or subtract array-like of DateOffset objects
Parameters
----------
other : Index, np.ndarray
object-dtype containing pd.DateOffset objects
op : {operator.add, operator.sub}
Returns
-------
result : same class as self |
345,221 | def admin(self):
self._check_title(self.browser.title())
self.browser.select_form(nr=0)
prompted = []
user = self.ctx.config.get(, )
if not user:
user = click.prompt()
prompted.append()
password = self.ctx.config.get(, )
... | Provide admin login credentials |
345,222 | def list_nodes_full(conn=None, call=None):
if call == :
raise SaltCloudSystemExit(
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node[]] = node
return ret | Return a list of the VMs that are on the provider, with all fields |
345,223 | def is_ipv6_filter(ip, options=None):
_is_ipv6 = _is_ipv(ip, 6, options=options)
return isinstance(_is_ipv6, six.string_types) | Returns a bool telling if the value passed to it was a valid IPv6 address.
ip
The IP address.
net: False
Consider IP addresses followed by netmask.
options
CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. |
345,224 | def object_info(self, oname, detail_level=0):
content = dict(oname=oname, detail_level=detail_level)
msg = self.session.msg(, content)
self._queue_send(msg)
return msg[][] | Get metadata information about an object.
Parameters
----------
oname : str
A string specifying the object name.
detail_level : int, optional
The level of detail for the introspection (0-2)
Returns
-------
The msg_id of the message sent. |
345,225 | def load_filters(self):
for f in sorted(logdissect.filters.__filters__):
self.filter_modules[f] = \
__import__( + f, globals(), \
locals(), [logdissect]).FilterModule(args=self.filter_args) | Load filter module(s) |
345,226 | def get_object_nbytes(obj, fallback_type=None, follow_pointers=False, exclude_modules=True, listoverhead=False):
import utool as ut
import types
seen = set([])
def _object_nbytes(obj):
object_id = id(obj)
if object_id in seen:
return 0
if (obj is None or isinstan... | CommandLine:
python -m utool.util_dev --test-get_object_nbytes
python -m utool.util_dev --test-get_object_nbytes:1
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dev import * # NOQA
>>> import numpy as np
>>> import utool as ut
>>> obj = [np.empty(1, dtyp... |
345,227 | def is_valid_metric_name(metric_name):
reg = re.compile()
if reg.match(metric_name) and not metric_name.startswith():
return True
else:
return False | check the validity of metric_name in config; the metric_name will be used for creation of sub-dir, so only contains: alphabet, digits , '.', '-' and '_'
:param str metric_name: metric_name
:return: True if valid |
345,228 | def multiline_string_lines(source, include_docstrings=False):
line_numbers = set()
previous_token_type =
try:
for t in generate_tokens(source):
token_type = t[0]
start_row = t[2][0]
end_row = t[3][0]
if token_type == tokenize.STRING and start_ro... | Return line numbers that are within multiline strings.
The line numbers are indexed at 1.
Docstrings are ignored. |
345,229 | def list(self, channels=None, server=""):
self.send_items(, .join(always_iterable(channels)), server) | Send a LIST command. |
345,230 | def field2write_only(self, field, **kwargs):
attributes = {}
if field.load_only and self.openapi_version.major >= 3:
attributes["writeOnly"] = True
return attributes | Return the dictionary of OpenAPI field attributes for a load_only field.
:param Field field: A marshmallow field.
:rtype: dict |
345,231 | async def jsk_shutdown(self, ctx: commands.Context):
await ctx.send("Logging out now..")
await ctx.bot.logout() | Logs this bot out. |
345,232 | def strlib_unary_features(span):
if not span.sentence.is_structural():
return
yield f"TAG_{get_tag(span)}", DEF_VALUE
for attr in get_attributes(span):
yield f"HTML_ATTR_{attr}", DEF_VALUE
yield f"PARENT_TAG_{get_parent_tag(span)}", DEF_VALUE
prev_tags = get_prev_sibling_tag... | Structural-related features for a single span |
345,233 | def setActionStepLength(self, typeID, actionStepLength, resetActionOffset=True):
if actionStepLength < 0:
raise exceptions.TraCIException("Invalid value for actionStepLength. Given value must be non-negative.")
if not resetActionOffset:
actionStepLength*=-1
... | setActionStepLength(string, double, bool) -> None
Sets the action step length for vehicles of this type. If resetActionOffset == True (default), the
next action point is scheduled immediately for all vehicles of the type.
If resetActionOffset == False, the interval between the last and the ne... |
345,234 | def _change_resource_record_sets(self, change_set, comment=None):
body = xml_generators.change_resource_record_set_writer(
connection=self,
change_set=change_set,
comment=comment
)
root = self._send_request(
path= % change_set.hosted_zon... | Given a ChangeSet, POST it to the Route53 API.
.. note:: You probably shouldn't be using this method directly,
as there are convenience methods on the ResourceRecordSet
sub-classes.
:param change_set.ChangeSet change_set: The ChangeSet object to create
the XML doc f... |
345,235 | def _experience(self, previousState, action, previousAction, reward):
e = self.experimentation
if action == previousAction:
experience = reward * (1 - e)
else:
propensity = self.module.getValue(previousState, action)
experience = propensity * (e / (s... | This is an altered version of the experience function for used in
the standard Roth-Erev algorithm. Like in RELearner, propensities for
all actions are updated and similarity does not come into play. If the
actionIndex points to the action the reward is associated with (usually
the last... |
345,236 | def method(self, method):
self._request.method = method
self.add_matcher(matcher(, method)) | Defines the HTTP method to match.
Use ``*`` to match any method.
Arguments:
method (str): method value to match. E.g: ``GET``.
Returns:
self: current Mock instance. |
345,237 | def _init_auth(self, config):
self.auth_mode = self._get_param(, , config)
if self.auth_mode in [, , ]:
pass
elif self.auth_mode == :
auth_module = self._get_param(, , config)
auth = __import__(auth_module, globals(), locals(), [], 0)
... | Init authentication
@dict: configuration of ldapcherry |
345,238 | def _verifyDiscoveredServices(self, claimed_id, services,
to_match_endpoints):
failure_messages = []
for endpoint in services:
for to_match_endpoint in to_match_endpoints:
try:
self._verifyDisco... | See @L{_discoverAndVerify} |
345,239 | def open(filename, frame=):
data = BagOfPoints.load_data(filename)
return RgbCloud(data, frame) | Create a RgbCloud from data saved in a file.
Parameters
----------
filename : :obj:`str`
The file to load data from.
frame : :obj:`str`
The frame to apply to the created RgbCloud.
Returns
-------
:obj:`RgbCloud`
A RgdCloud cr... |
345,240 | def get(self, sid):
return AuthRegistrationsCredentialListMappingContext(
self._version,
account_sid=self._solution[],
domain_sid=self._solution[],
sid=sid,
) | Constructs a AuthRegistrationsCredentialListMappingContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingContext
... |
345,241 | def K(self, X, X2=None):
if X2 is None:
X2 = X
base = np.pi * (X[:, None, :] - X2[None, :, :]) / self.period
exp_dist = np.exp( -0.5* np.sum( np.square( np.sin( base ) / self.lengthscale ), axis = -1 ) )
return self.variance * exp_dist | Compute the covariance matrix between X and X2. |
345,242 | def unload_modules():
mods = set([])
for m in sys.modules:
if m.startswith():
mods.add(m)
pm = PluginManager.get()
for p in pm.get_all_plugins():
mods.add(p.__module__)
for m in mods:
del(sys.modules[m]) | Unload all modules of the jukebox package and all plugin modules
Python provides the ``reload`` command for reloading modules. The major drawback is, that if this module is loaded in any other module
the source code will not be resourced!
If you want to reload the code because you changed the source file, ... |
345,243 | def download(progress=True):
data_dir = external_data_dir(create=True)
print("Using data directory: %s" % data_dir)
s3 =
files = [
(s3, ),
(s3, ),
(s3, ),
(s3, ),
(s3, ),
(s3, ),
(s3, ),
(s3, ),
(s3, ),
(s3, ),
... | Download larger data sets for various Bokeh examples. |
345,244 | def ConvDiagonalGRU(units, kernel_size=(3, 3)):
def BuildConv():
return layers.Conv(filters=units, kernel_size=kernel_size, padding=)
return layers.GeneralGRUCell(
candidate_transform=BuildConv,
memory_transform=DiagonalGate,
gate_nonlinearity=layers.HardSigmoid,
candidate_nonlinear... | Build convolutional GRU with diagonal gating as in ImprovedNGPU. |
345,245 | def io_check(*args, func=None):
func = func or inspect.stack()[2][3]
for var in args:
if not isinstance(var, io.IOBase):
name = type(var).__name__
raise IOObjError(
f) | Check if arguments are file-like object. |
345,246 | def vprint(self, *args, **kwargs):
if self.verbose:
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
caller_name = calframe[1][3]
prefix = % (self.name.lower(), caller_name)
print(prefix, *args, **kwargs) | When verbose is set, acts like the normal print() function.
Otherwise, does nothing. |
345,247 | def _read_segment_lines(segment_lines):
segment_fields = {}
for field in SEGMENT_SPECS.index:
segment_fields[field] = [None] * len(segment_lines)
for i in range(len(segment_lines)):
(segment_fields[][i], segment_fields[][i]) = _rx_segment.findall(segment_lines[i])[0]
... | Extract fields from segment line strings into a dictionary |
345,248 | def _init_metadata(self, **kwargs):
osid_objects.OsidObjectForm._init_metadata(self, **kwargs)
self._url_default = self._mdata[][][0]
self._data_default = self._mdata[][][0]
self._accessibility_type_default = self._mdata[][][0] | Initialize form metadata |
345,249 | def _set_properties(self, resource):
resource = resource.copy()
self._additions = tuple(
[
ResourceRecordSet.from_api_repr(added_res, self.zone)
for added_res in resource.pop("additions", ())
]
)
self._deletions = tuple(
... | Helper method for :meth:`from_api_repr`, :meth:`create`, etc.
:type resource: dict
:param resource: change set representation returned from the API. |
345,250 | def assert_equals(self, actual_val, expected_val, failure_message=):
assertion = lambda: expected_val == actual_val
self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, expected_val)) | Calls smart_assert, but creates its own assertion closure using
the expected and provided values with the '==' operator |
345,251 | def services(services_file=):
svcportprotodesc
res = {}
with salt.utils.files.fopen(services_file, ) as svc_defs:
for svc_def in svc_defs.readlines():
svc_def = salt.utils.stringutils.to_unicode(svc_def.strip())
if not svc_def or svc_def.startswith():
continue... | Parse through system-known services
:return: {
'svc': [
{ 'port': port
'proto': proto,
'desc': comment
},
],
} |
345,252 | def is_filtered(self, process):
if self.filter is None:
return False
if self.filter_key is None:
return self._is_process_filtered(process, key=) or \
self._is_process_filtered(process, key=)
else:
... | Return True if the process item match the current filter
The proces item is a dict. |
345,253 | def add_method(cls):
def wrapper(f):
setattr(cls, f.__name__, f)
return f
return wrapper | Attach a method to a class. |
345,254 | def parse_private(data, password=None):
if not isinstance(data, byte_cls):
raise TypeError(pretty_message(
,
type_name(data)
))
if password is not None:
if not isinstance(password, byte_cls):
raise TypeError(pretty_message(
,
... | Loads a private key from a DER or PEM-formatted file. Supports RSA, DSA and
EC private keys. Works with the follow formats:
- RSAPrivateKey (PKCS#1)
- ECPrivateKey (SECG SEC1 V2)
- DSAPrivateKey (OpenSSL)
- PrivateKeyInfo (RSA/DSA/EC - PKCS#8)
- EncryptedPrivateKeyInfo (RSA/DSA/EC - PKCS#8... |
345,255 | def _canonical_int(self, interface):
if self.use_canonical_interface is True:
return napalm.base.helpers.canonical_interface_name(
interface, addl_name_map=None
)
else:
return interface | Expose the helper function within this class. |
345,256 | def transform_args(self,*args,**kwargs):
newargs = self._combineargs(*args, **kwargs)
return self._build_arg_list(**newargs) | Combine arguments and turn them into gromacs tool arguments. |
345,257 | def _active_mounts_openbsd(ret):
for line in __salt__[]().split():
comps = re.sub(r"\s+", " ", line).split()
parens = re.findall(r, line, re.DOTALL)
if len(parens) > 1:
nod = __salt__[](.format(comps[0]))
nod = .join(nod.split()).split(" ")
ret[comps[... | List active mounts on OpenBSD systems |
345,258 | def serialize(obj, **options):
try:
if in options:
return toml.dump(obj, options[], **options)
else:
return toml.dumps(obj, **options)
except Exception as error:
raise SerializationError(error) | Serialize Python data to TOML.
:param obj: the data structure to serialize.
:param options: options given to lower pytoml module. |
345,259 | def export(self, **kwargs):
filename = kwargs.pop(, )
filetype = kwargs.pop(, )
adjust_dynamics = kwargs.pop(, False)
samplerate = kwargs.pop(, None)
channels = kwargs.pop(, self.channels)
separate_tracks = kwargs.pop(, False)
min_length = kwargs... | Generate audio file from composition.
:param str. filename: Output filename (no extension)
:param str. filetype: Output file type (only .wav supported for now)
:param integer samplerate: Sample rate of output audio
:param integer channels: Channels in output audio, if different than ori... |
345,260 | def snapshot():
all_objects = gc.get_objects()
this_frame = inspect.currentframe()
selected_objects = []
for obj in all_objects:
if obj is not this_frame:
selected_objects.append(obj)
graph = ObjectGraph(selected_objects)
del this_frame, all_objects, selected_objects, ob... | Return the graph of all currently gc-tracked objects.
Excludes the returned :class:`~refcycle.object_graph.ObjectGraph` and
objects owned by it.
Note that a subsequent call to :func:`~refcycle.creators.snapshot` will
capture all of the objects owned by this snapshot. The
:meth:`~refcycle.object_g... |
345,261 | def serveMiniMonth(self, request, year=None, month=None):
if not request.is_ajax():
raise Http404("/mini/ is for ajax requests only")
today = timezone.localdate()
if year is None: year = today.year
if month is None: month = today.month
year = int(year)
... | Serve data for the MiniMonth template tag. |
345,262 | def to_dict(self):
ctx = Context()
ContextFlags = self.ContextFlags
ctx[] = ContextFlags
for key in self._others:
if key != :
ctx[key] = getattr(self, key)
else:
ctx[key] = tuple([ (x.Low + (x.High << 64)) for x in getattr(... | Convert a structure into a Python dictionary. |
345,263 | def control_number(endpoint):
def _control_number(self, key, value):
self[] = get_record_ref(int(value), endpoint)
return int(value)
return _control_number | Populate the ``control_number`` key.
Also populates the ``self`` key through side effects. |
345,264 | def parse_top_output(out):
lines = out.splitlines()
line_iter = iter(lines)
header_line = next(line_iter)
titles = header_line.split()
max_split = len(titles) - 1
return {
: titles,
: [line.split(None, max_split) for line in line_iter],
} | Parses the output of the Docker CLI 'docker top <container>'. Note that if 'ps' output columns are modified and
'args' (for the command) is anywhere but in the last column, this will not parse correctly. However, the Docker API
produces wrong output in this case as well.
Returns a dictionary with entries 'T... |
345,265 | def _set_vrf(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("vrf_name",vrf.vrf, yang_name="vrf", rest_name="vrf", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, extensions={u: {u: u, u: None, u... | Setter method for vrf, mapped from YANG variable /nas/server_ip/vrf (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_vrf is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_vrf() directly. |
345,266 | def get_equivalent_atoms(self, tolerance=0.3):
PA = self._get_point_group_analyzer(tolerance=tolerance)
eq = PA.get_equivalent_atoms()
self._convert_eq(eq)
return eq | Returns sets of equivalent atoms with symmetry operations
Args:
tolerance (float): Tolerance to generate the full set of symmetry
operations.
Returns:
dict: The returned dictionary has two possible keys:
``eq_sets``:
A dictionary of indi... |
345,267 | def _writable(method):
@wraps(method)
def wrapper(self, *args, **kwargs):
if self.bucket.locked or self.bucket.deleted:
raise InvalidOperationError()
return method(self, *args, **kwargs)
return wrapper | Check that record is in defined status.
:param method: Method to be decorated.
:returns: Function decorated. |
345,268 | def dict_to_dom(root_node, xml_dict):
if in list(xml_dict.keys()):
root_node.appendChild(
root_node.ownerDocument.createTextNode(
convert_to_str(xml_dict[])
)
)
for key, value in xml_dict.items():
if key == :
continue
... | Create a DOM node and optionally several subnodes from a dictionary.
:param root_node: DOM-Node set the dictionary is applied upon
:type root_node: xml.dom.Element
:param xml_dict: The dictionary containing the nodes to process
:type xml_dict: dict |
345,269 | def union(self, other_streamlet):
from heronpy.streamlet.impl.unionbolt import UnionStreamlet
union_streamlet = UnionStreamlet(self, other_streamlet)
self._add_child(union_streamlet)
other_streamlet._add_child(union_streamlet)
return union_streamlet | Returns a new Streamlet that consists of elements of both this and other_streamlet |
345,270 | def get_unit_name(self):
if not self.unit:
return None
name = sorted(self.unit.names, key=len)[-1]
return % name | Returns the name of the unit for this GPS scale
Note that this returns a simply-pluralised version of the name. |
345,271 | def normalized_messages(self, no_field_name=):
if isinstance(self.messages, dict):
return self.messages
if not self.field_names:
return {no_field_name: self.messages}
return dict((name, self.messages) for name in self.field_names) | Return all the error messages as a dictionary |
345,272 | def _blocks(self, name):
i = len(self)
while i >= 0:
i -= 1
if name in self[i][]:
for b in self[i][]:
r = b.raw()
if r and r == name:
return b
else:
for b in self[... | Inner wrapper to search for blocks by name. |
345,273 | def _parse_reactome_association_file(
self, file, limit=None, subject_prefix=None, object_prefix=None):
eco_map = Reactome.get_eco_map(Reactome.map_files[])
count = 0
with open(file, ) as tsvfile:
reader = csv.reader(tsvfile, delimiter="\t")
for row i... | Parse ensembl gene to reactome pathway file
:param file: file path (not handle)
:param limit: limit (int, optional) limit the number of rows processed
:return: None |
345,274 | def loadSettings(self):
self.settings.beginGroup()
geometry = self.settings.value().toByteArray()
self.settings.endGroup()
self.restoreGeometry(geometry) | Load window state from self.settings |
345,275 | def historical_pandas_yahoo(symbol, source=, start=None, end=None):
return DataReader(symbol, source, start=start, end=end) | Fetch from yahoo! finance historical quotes |
345,276 | def _decode_linode_plan_label(label):
sizes = avail_sizes()
if label not in sizes:
if in label:
raise SaltCloudException(
.format(label)
)
else:
plan = label.split()
if len(plan) != 2:
raise SaltCloudExceptio... | Attempts to decode a user-supplied Linode plan label
into the format in Linode API output
label
The label, or name, of the plan to decode.
Example:
`Linode 2048` will decode to `Linode 2GB` |
345,277 | def paginate_search_results(object_class, search_results, page_size, page):
paginator = Paginator(search_results[], page_size)
try:
page_number = paginator.validate_number(page)
except InvalidPage:
if page == :
page_number = paginator.num_pages
else:
... | Takes edx-search results and returns a Page object populated
with db objects for that page.
:param object_class: Model class to use when querying the db for objects.
:param search_results: edX-search results.
:param page_size: Number of results per page.
:param page: Page number.
:return: Pagin... |
345,278 | def get_file_extension(filepath):
_ext = os.path.splitext(filepath)[-1]
if _ext:
return _ext[1:] if _ext.startswith() else _ext
return | Copy if anyconfig.utils.get_file_extension is not available.
>>> get_file_extension("/a/b/c")
''
>>> get_file_extension("/a/b.txt")
'txt'
>>> get_file_extension("/a/b/c.tar.xz")
'xz' |
345,279 | def mark_received(self, visibility_timeout=None):
if visibility_timeout:
visibility_timeout = int(visibility_timeout)
else:
visibility_timeout = 0
if not self.approximate_first_receive_timestamp:
self.approximate_first_receive_timestamp = int(unix_ti... | When a message is received we will set the first receive timestamp,
tap the ``approximate_receive_count`` and the ``visible_at`` time. |
345,280 | def _parse(self, date_str, format=):
rv = pd.to_datetime(date_str, format=format)
if hasattr(rv, ):
rv = rv.to_pydatetime()
return rv | helper function for parsing FRED date string into datetime |
345,281 | def transaction_date(self, value):
if value:
self._transaction_date = parse(value).date() if isinstance(value, type_check) else value | Force the transaction_date to always be a date
:param value:
:return: |
345,282 | def _line_mode_cell_append(self, lines):
self._store(lines, self._buffer_raw, )
self.cell_magic_parts.append(lines)
last_block = self.cell_magic_parts[-1]
self._is_complete = last_blank(last_block) ... | Append new content for a cell magic in line mode. |
345,283 | def find_vcs_root(cls, path):
if cls.search_parents_for_root():
valid_dirs = walk_up_dirs(path)
else:
valid_dirs = [path]
for i, current_path in enumerate(valid_dirs):
if cls.is_valid_root(current_path):
return current_path, i
... | Try to find a version control root directory of this type for the
given path.
If successful, returns (vcs_root, levels_up), where vcs_root is the
path to the version control root directory it found, and levels_up is an
integer indicating how many parent directories it had to search thro... |
345,284 | async def power_off(
self, stop_mode: PowerStopMode = PowerStopMode.HARD,
comment: str = None, wait: bool = False, wait_interval: int = 5):
params = {"system_id": self.system_id, : stop_mode.value}
if comment is not None:
params["comment"] = comment
t... | Power off.
:param stop_mode: How to perform the power off.
:type stop_mode: `PowerStopMode`
:param comment: Reason machine was powered on.
:type comment: `str`
:param wait: If specified, wait until the machine is powered on.
:type wait: `bool`
:param wait_interva... |
345,285 | def solve_hessian_approx_uniform(X, cells, rhs):
dim = 2
mesh = MeshTri(X, cells)
row_idx = []
col_idx = []
val = []
cells = mesh.cells["nodes"].T
n = X.shape[0]
a = mesh.cell_volumes * (2 / (dim + 1))
for i in [0, 1, 2]:
row_idx += [cells[i]]
col_id... | As discussed above, the approximated Jacobian is
partial_i E = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|.
To get the Hessian, we have to form its derivative. As a simplifications,
let us assume again that |tau_j| is independent of the node positions. Then we get
partial_ii E = 2/(d+1) |... |
345,286 | def cli(config, configfile, verbose):
config.verbose = verbose
config.configfile = configfile
if not os.path.isfile(configfile):
state.write(configfile, {}) | A glorious command line tool to make your life with git, GitHub
and Bugzilla much easier. |
345,287 | def get_shape(self):
return tuple(int(c.pcdata) for c in self.getElementsByTagName(ligolw.Dim.tagName))[::-1] | Return a tuple of this array's dimensions. This is done by
querying the Dim children. Note that once it has been
created, it is also possible to examine an Array object's
.array attribute directly, and doing that is much faster. |
345,288 | def get_xy_rotation_and_scale(header):
def calc_from_cd(cd1_1, cd1_2, cd2_1, cd2_2):
det = cd1_1 * cd2_2 - cd1_2 * cd2_1
if det < 0:
sgn = -1
else:
sgn = 1
if (cd2_1 == 0.0) or (cd1_2 == 0.0):
... | CREDIT: See IDL code at
http://www.astro.washington.edu/docs/idl/cgi-bin/getpro/library32.html?GETROT |
345,289 | def _strip(text):
text = text.strip()
text = text.replace(, )
text = text.lower()
for joiner in TextTitle.JOINERS:
text = text.replace(joiner, )
for article in TextTitle.ARTICLES:
if text.startswith(article + ):
text = text[len(a... | Strip articles/whitespace and remove case. |
345,290 | def set_ip_info(self, is_dhcp, ip=, gate=, mask=,
dns1=, dns2=, callback=None):
params = {: is_dhcp,
: ip,
: gate,
: mask,
: dns1,
: dns2,
}
return self.ex... | isDHCP: 0(False), 1(True)
System will reboot automatically to take effect after call this CGI command. |
345,291 | def init(obj, resource_root, attrs=None):
str_attrs = { }
if attrs:
for k, v in attrs.iteritems():
if k not in (, ):
str_attrs[k] = v
BaseApiObject.__init__(obj, resource_root, **str_attrs) | Wraper around the real constructor to avoid issues with the 'self'
argument. Call like this, from a subclass's constructor:
- BaseApiObject.init(self, locals()) |
345,292 | def slugify(value):
value = Markup(value).striptags()
if type(value) == unicode:
value = unicode(unidecode(value))
value = unicodedata.normalize(, value).encode(, )
value = unicode(re.sub(, , value).strip().lower())
return re.sub(, , value) | Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
Took from django sources. |
345,293 | def approximate_entropy(self, x, m=None, r=None):
if m is None or r is None:
m = 2
r = 0.3
entropy = feature_calculators.approximate_entropy(x, m, r)
logging.debug("approximate entropy by tsfresh calculated")
return entropy | As in tsfresh \
`approximate_entropy <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L1601>`_
Implements a `vectorized approximate entropy algorithm <https://en.wikipedia.org/wiki/Approximate_entropy>`_
For short time-series this ... |
345,294 | def __parse_email_to_employer_stream(self, stream):
if not stream:
return
f = self.__parse_email_to_employer_line
for rol in self.__parse_stream(stream, f):
email = rol[0]
org = rol[1]
rol_date = rol[2]
if org not in self.__... | Parse email to employer stream.
The stream contains a list of email addresses and their employers.
Each line has an email address and a organization name separated by
tabs. Optionally, the date when the identity withdrew from the
organization can be included followed by a '<' character.... |
345,295 | def Serialize(self, writer):
writer.WriteVarInt(len(self.NetworkAddressesWithTime))
for address in self.NetworkAddressesWithTime:
address.Serialize(writer) | Serialize object.
Args:
writer (neo.IO.BinaryWriter): |
345,296 | def export_input_zip(ekey, dstore):
dest = dstore.export_path()
nbytes = dstore.get_attr(, )
zbytes = dstore[].value
zbytes += b * (nbytes - len(zbytes))
open(dest, ).write(zbytes)
return [dest] | Export the data in the `input_zip` dataset as a .zip file |
345,297 | def get_collection(self, **kwargs):
list_of_contents = []
self.refresh(**kwargs)
if in self.__dict__:
for item in self.items:
if not in item:
list_of_contents.append(item)
continue
... | Get an iterator of Python ``Resource`` objects that represent URIs.
The returned objects are Pythonic `Resource`s that map to the most
recently `refreshed` state of uris-resources published by the device.
In order to instantiate the correct types, the concrete subclass must
populate its... |
345,298 | def setCurrentDebugLine( self, lineno ):
self.markerDeleteAll(self._currentDebugMarker)
self.markerAdd(lineno, self._currentDebugMarker)
self.setCurrentLine(lineno) | Returns the line number for the documents debug line.
:param lineno | <int> |
345,299 | def handle_synonyms(in_file, ref_file, genome_build, work_dir, data):
if genome_build in GMAP and ref_file:
mappings = GMAP[genome_build]
contigs = set([c.name for c in ref.file_contigs(ref_file)])
out_file = os.path.join(work_dir, "%s-fixed_contigs%s" % utils.splitext_plus(os.path.base... | Potentially handle remapping synonymous chromosome names between builds.
Handles tab delimited file formats like BED and VCF where the contig
is in the first column. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.