Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
17,000 | def search_value(self, xpath, default=None, single_value=True):
matches = [match.value for match in parse(xpath).find(self.retval)]
if len(matches) == 0:
return default
return matches[0] if single_value is True else matches | Try to find a value in the result
:param str xpath: a xpath filter see https://github.com/kennknowles/python-jsonpath-rw#jsonpath-syntax
:param any default: default value if not found
:param bool single_value: is the result is multivalued
:return: the value found or None |
17,001 | def visit_Call(self, node):
node = self.generic_visit(node)
if isinstance(node.func, ast.Attribute):
if node.func.attr in methods:
obj = lhs = node.func.value
while isinstance(obj, ast.Attrib... | Transform call site to have normal function call.
Examples
--------
For methods:
>> a = [1, 2, 3]
>> a.append(1)
Becomes
>> __list__.append(a, 1)
For functions:
>> __builtin__.dict.fromkeys([1, 2, 3])
Becomes
>> __builtin__.... |
17,002 | def removeXmlElement(name, directory, file_pattern, logger=None):
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, file_pattern):
filepath = os.path.join(path, filename)
remove_xml_element_file(name, filepath) | Recursively walk a directory and remove XML elements |
17,003 | def get_exchange_group_info(self, symprec=1e-2, angle_tolerance=5.0):
structure = self.get_structure_with_spin()
return structure.get_space_group_info(
symprec=symprec, angle_tolerance=angle_tolerance
) | Returns the information on the symmetry of the Hamiltonian
describing the exchange energy of the system, taking into
account relative direction of magnetic moments but not their
absolute direction.
This is not strictly accurate (e.g. some/many atoms will
have zero magnetic momen... |
17,004 | def _validate_slices_form_uniform_grid(slice_datasets):
invariant_properties = [
,
,
,
,
,
,
,
,
,
,
]
for property_name in invariant_properties:
_slice_attribute_equal(slice_datasets, property_name)
_validate... | Perform various data checks to ensure that the list of slices form a
evenly-spaced grid of data.
Some of these checks are probably not required if the data follows the
DICOM specification, however it seems pertinent to check anyway. |
17,005 | def CWDE(cpu):
bit = Operators.EXTRACT(cpu.AX, 15, 1)
cpu.EAX = Operators.SEXTEND(cpu.AX, 16, 32)
cpu.EDX = Operators.SEXTEND(bit, 1, 32) | Converts word to doubleword.
::
DX = sign-extend of AX.
:param cpu: current CPU. |
17,006 | def make_multisig_segwit_wallet( m, n ):
pks = []
for i in xrange(0, n):
pk = BitcoinPrivateKey(compressed=True).to_wif()
pks.append(pk)
return make_multisig_segwit_info(m, pks) | Create a bundle of information
that can be used to generate an
m-of-n multisig witness script. |
17,007 | def diff(candidate, running, *models):
*
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
first = _get_root_object(models)
first.load_dict(candidate)
second = _get_root_object(models)
second.load_dict(running)
return napalm_yang.utils.diff(first, seco... | Returns the difference between two configuration entities structured
according to the YANG model.
.. note::
This function is recommended to be used mostly as a state helper.
candidate
First model to compare.
running
Second model to compare.
models
A list of models... |
17,008 | def read_stb(library, session):
status = ViUInt16()
ret = library.viReadSTB(session, byref(status))
return status.value, ret | Reads a status byte of the service request.
Corresponds to viReadSTB function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:return: Service request status byte, return value of the library call.
:rtype: int, :class... |
17,009 | def transform(self, X):
msg = " should be a 1-dimensional array with length ."
if not dask.is_dask_collection(X):
return super(HashingVectorizer, self).transform(X)
if isinstance(X, db.Bag):
bag2 = X.map_partitions(_transform, estimator=self)
objs =... | Transform a sequence of documents to a document-term matrix.
Transformation is done in parallel, and correctly handles dask
collections.
Parameters
----------
X : dask.Bag of raw text documents, length = n_samples
Samples. Each sample must be a text document (either... |
17,010 | def get_runs_by_id(self, config_id):
d = self.data[config_id]
runs = []
for b in d.results.keys():
try:
err_logs = d.exceptions.get(b, None)
if d.results[b] is None:
r = Run(config_id, b, None, None , d.time_stamps[b], err_logs)
else:
r = Run(config_id, b, d.results[b][], d.results[b... | returns a list of runs for a given config id
The runs are sorted by ascending budget, so '-1' will give
the longest run for this config. |
17,011 | def target_query(plugin, port, location):
return ((r.row[PLUGIN_NAME_KEY] == plugin) &
(r.row[PORT_FIELD] == port) &
(r.row[LOCATION_FIELD] == location)) | prepared ReQL for target |
17,012 | def _verify_signed_jwt_with_certs(
jwt, time_now, cache,
cert_uri=_DEFAULT_CERT_URI):
segments = jwt.split()
if len(segments) != 3:
raise _AppIdentityError(
)
signed = % (segments[0], segments[1])
signature = _urlsafe_b64decode(segments[2])
lsign... | Verify a JWT against public certs.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
The PyCrypto library included with Google App Engine is severely limited and
so you have to use it very carefully to verify JWT signatures. The first
issue is that the library can't read X.509 files, so we mak... |
17,013 | def dump(destination, xs, model=None, properties=False, indent=True, **kwargs):
text = dumps(
xs, model=model, properties=properties, indent=indent, **kwargs
)
if hasattr(destination, ):
print(text, file=destination)
else:
with open(destination, ) as fh:
print(te... | Serialize Xmrs (or subclass) objects to PENMAN and write to a file.
Args:
destination: filename or file object
xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize
model: Xmrs subclass used to get triples
properties: if `True`, encode variable properties
... |
17,014 | def addChild(self,item):
if not isinstance(item,Node):
item = Node(item)
if item in self.children:
return item
self.children.append(item)
item.parents.add(self)
return item | When you add a child to a Node, you are adding yourself as a parent to the child
You cannot have the same node as a child more than once.
If you add a Node, it is used. If you add a non-node, a new child Node is created. Thus: You cannot
add a child as an item which is a Node. (You can, however, construct s... |
17,015 | def length(self):
return sum([shot.length for shot in self.shots if not shot.is_splay]) | Total surveyed cave length, not including splays. |
17,016 | def iter(self, match="*", count=1000):
replace_this = self.key_prefix+":"
for key in self._client.scan_iter(
match="{}:{}".format(self.key_prefix, match), count=count):
yield self._decode(key).replace(replace_this, "", 1) | Iterates the set of keys in :prop:key_prefix in :prop:_client
@match: #str pattern to match after the :prop:key_prefix
@count: the user specified the amount of work that should be done
at every call in order to retrieve elements from the collection
-> yields redis ke... |
17,017 | def _prepare_data_payload(data):
if not data: return None
res = {}
for key, value in viewitems(data):
if value is None: continue
if isinstance(value, list):
value = stringify_list(value)
elif isinstance(value, dict):
... | Make a copy of the `data` object, preparing it to be sent to the server.
The data will be sent via x-www-form-urlencoded or multipart/form-data mechanisms. Both of them work with
plain lists of key/value pairs, so this method converts the data into such format. |
17,018 | def get_banks_by_assessment_taken(self, assessment_taken_id):
mgr = self._get_provider_manager(, local=True)
lookup_session = mgr.get_bank_lookup_session(proxy=self._proxy)
return lookup_session.get_banks_by_ids(
self.get_bank_ids_by_assessment_taken(assess... | Gets the list of ``Banks`` mapped to an ``AssessmentTaken``.
arg: assessment_taken_id (osid.id.Id): ``Id`` of an
``AssessmentTaken``
return: (osid.assessment.BankList) - list of banks
raise: NotFound - ``assessment_taken_id`` is not found
raise: NullArgument - ``ass... |
17,019 | def collect_phrases (sent, ranks, spacy_nlp):
tail = 0
last_idx = sent[0].idx - 1
phrase = []
while tail < len(sent):
w = sent[tail]
if (w.word_id > 0) and (w.root in ranks) and ((w.idx - last_idx) == 1):
rl = RankedLexeme(text=w.raw.lower(), rank=ranks[w.... | iterator for collecting the noun phrases |
17,020 | def mem(args, opts):
dbfile, read1file = args[:2]
readtype = opts.readtype
pl = readtype or "illumina"
pf = op.basename(read1file).split(".")[0]
rg = opts.rg or r"@RG\tID:{0}\tSM:sm\tLB:lb\tPL:{1}".format(pf, pl)
dbfile = check_index(dbfile)
args[0] = dbfile
samfile, _, unmapped = ... | %prog mem database.fasta read1.fq [read2.fq]
Wrapper for `bwa mem`. Output will be read1.sam. |
17,021 | def setmode(mode):
if hasattr(mode, ):
set_custom_pin_mappings(mode)
mode = CUSTOM
assert mode in [BCM, BOARD, SUNXI, CUSTOM]
global _mode
_mode = mode | You must call this method prior to using all other calls.
:param mode: the mode, one of :py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM`,
:py:attr:`GPIO.SUNXI`, or a `dict` or `object` representing a custom
pin mapping. |
17,022 | def placeholders(cls,dic):
keys = [str(x) for x in dic]
entete = ",".join(keys)
placeholders = ",".join(cls.named_style.format(x) for x in keys)
entete = f"({entete})"
placeholders = f"({placeholders})"
return entete, placeholders | Placeholders for fields names and value binds |
17,023 | def _function(self):
start_time = datetime.datetime.now()
if self.settings[] == :
stop_time = start_time + datetime.timedelta(seconds= self.settings[])
elif self.settings[] == :
if self.last_execution is None:
stop_time = start_time
... | Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click. |
17,024 | def requires_lock(function):
def new_lock_requiring_function(self, filename, *args, **kwargs):
if self.owns_lock(filename):
return function(self, filename, *args, **kwargs)
else:
raise RequiresLockException()
return new_lock_requiring_function | Decorator to check if the user owns the required lock.
The first argument must be the filename. |
17,025 | def set_window_pos_callback(window, cbfun):
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_pos_callback_repository:
previous_callback = _window_pos_callback_repository[window_addr]
else:
... | Sets the position callback for the specified window.
Wrapper for:
GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun); |
17,026 | def compute_gaussian_krnl(M):
g = signal.gaussian(M, M // 3., sym=True)
G = np.dot(g.reshape(-1, 1), g.reshape(1, -1))
G[M // 2:, :M // 2] = -G[M // 2:, :M // 2]
G[:M // 2, M // 2:] = -G[:M // 2, M // 2:]
return G | Creates a gaussian kernel following Foote's paper. |
17,027 | def getsockopt(self, level, optname, *args, **kwargs):
return self._sock.getsockopt(level, optname, *args, **kwargs) | get the value of a given socket option
the values for ``level`` and ``optname`` will usually come from
constants in the standard library ``socket`` module. consult the unix
manpage ``getsockopt(2)`` for more information.
:param level: the level of the requested socket option
:t... |
17,028 | def essl(lw):
w = np.exp(lw - lw.max())
return (w.sum())**2 / np.sum(w**2) | ESS (Effective sample size) computed from log-weights.
Parameters
----------
lw: (N,) ndarray
log-weights
Returns
-------
float
the ESS of weights w = exp(lw), i.e. the quantity
sum(w**2) / (sum(w))**2
Note
----
The ESS is a popular criterion to determ... |
17,029 | def dskmi2(vrtces, plates, finscl, corscl, worksz, voxpsz, voxlsz, makvtl, spxisz):
nv = ctypes.c_int(len(vrtces))
vrtces = stypes.toDoubleMatrix(vrtces)
np = ctypes.c_int(len(plates))
plates = stypes.toIntMatrix(plates)
finscl = ctypes.c_double(finscl)
corscl = ctypes.c_int(corscl)... | Make spatial index for a DSK type 2 segment. The index is returned
as a pair of arrays, one of type int and one of type
float. These arrays are suitable for use with the DSK type 2
writer dskw02.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskmi2_c.html
:param vrtces: Vertices
:typ... |
17,030 | def main():
listname = sys.argv[2]
hostname = sys.argv[1]
msg = email.message_from_file(f, Message.Message)
h = HyperArch.HyperArchive(mlist)
sequence = h.sequence
h.processUnixMailbox(f)
f.close()
archive = h.archive
msgno = % sequence
fil... | This is the mainline.
It first invokes the pipermail archiver to add the message to the archive,
then calls the function above to do whatever with the archived message
after it's URL and path are known. |
17,031 | def folderitem(self, obj, item, index):
cat = obj.getCategoryTitle()
cat_order = self.an_cats_order.get(cat)
if self.do_cats:
item["category"] = cat
if (cat, cat_order) not in self.categories:
self.categories.append((cat, cat_order))... | Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by
the template
:index: current ind... |
17,032 | def update_ff(self, ff, mol2=False, force_ff_assign=False):
aff = False
if force_ff_assign:
aff = True
elif not in self.tags:
aff = True
elif not self.tags[]:
aff = True
if aff:
self.assign_force_field(ff, mol2=mol2)
... | Manages assigning the force field parameters.
The aim of this method is to avoid unnecessary assignment of the
force field.
Parameters
----------
ff: BuffForceField
The force field to be used for scoring.
mol2: bool, optional
If true, mol2 style ... |
17,033 | def from_json_and_lambdas(cls, file: str, lambdas):
with open(file, "r") as f:
data = json.load(f)
return cls.from_dict(data, lambdas) | Builds a GrFN from a JSON object.
Args:
cls: The class variable for object creation.
file: Filename of a GrFN JSON file.
Returns:
type: A GroundedFunctionNetwork object. |
17,034 | def get_ec_names(ecfile, fasta_names):
df = pd.read_table(ecfile, header=None, names=["ec", "transcripts"])
transcript_groups = [x.split(",") for x in df["transcripts"]]
transcripts = []
for group in transcript_groups:
transcripts.append(":".join([fasta_names[int(x)] for x in group]))
r... | convert equivalence classes to their set of transcripts |
17,035 | def pprint(self, imports=None, prefix="\n ",unknown_value=,
qualify=False, separator=""):
r = Parameterized.pprint(self,imports,prefix,
unknown_value=unknown_value,
qualify=qualify,separator=separator)
classname... | Same as Parameterized.pprint, except that X.classname(Y
is replaced with X.classname.instance(Y |
17,036 | def assemble(experiments,
backend=None,
qobj_id=None, qobj_header=None,
shots=1024, memory=False, max_credits=None, seed_simulator=None,
default_qubit_los=None, default_meas_los=None,
schedule_los=None, meas_level=2, meas_return=,
memory_... | Assemble a list of circuits or pulse schedules into a Qobj.
This function serializes the payloads, which could be either circuits or schedules,
to create Qobj "experiments". It further annotates the experiment payload with
header and configurations.
Args:
experiments (QuantumCircuit or list[Qu... |
17,037 | def format_subpages(self, page, subpages):
if not subpages:
return None
try:
template = self.get_template()
except IOError:
return None
ret = etree.XML(template.render({: page,
: subpages}))
a... | Banana banana |
17,038 | def Q(self):
return np.array(list(self.center_frequencies)) \
/ np.array(list(self.bandwidths)) | The quality factor of the scale, or, the ratio of center frequencies
to bandwidths |
17,039 | def recursive_build_tree(self, intervals):
center = int(round(len(intervals) / 2))
left = intervals[:center]
right = intervals[center + 1:]
node = intervals[center]
if len(left) > 1:
left = self.recursive_build_tree(left)
elif len(left) == 1:
... | recursively builds a BST based on the elementary intervals.
each node is an array: [interval value, left descendent nodes, right descendent nodes, [ids]].
nodes with no descendents have a -1 value in left/right descendent positions.
for example, a node with two empty descendents:
[5... |
17,040 | def destroy(self, force=False):
try:
if not force:
self.join()
finally:
self._dbg(2, )
self.workqueue.destroy()
self.account_manager.reset()
self.completed = 0
self.total = 0
self.failed = 0
... | Like shutdown(), but also removes all accounts, hosts, etc., and
does not restart the queue. In other words, the queue can no longer
be used after calling this method.
:type force: bool
:param force: Whether to wait until all jobs were processed. |
17,041 | def lease(self, lease_time, num_tasks, group_by_tag=False, tag=None, client=None):
client = self._require_client(client)
if group_by_tag:
query_params = {"leaseSecs": lease_time, "numTasks": num_tasks, "groupByTag": group_by_tag, "tag": tag}
else:
query_params =... | Acquires a lease on the topmost N unowned tasks in the specified queue.
:type lease_time: int
:param lease_time: How long to lease this task, in seconds.
:type num_tasks: int
:param num_tasks: The number of tasks to lease.
:type group_by_tag: bool
:param group_by_tag: ... |
17,042 | def compare(args):
data = json.load(sys.stdin)
m = RiverManager(args.hosts)
if m.compare(args.name, data):
sys.exit(0)
else:
sys.exit(1) | Compare the extant river with the given name to the passed JSON. The
command will exit with a return code of 0 if the named river is configured
as specified, and 1 otherwise. |
17,043 | def adjustSizeConstraint(self):
widget = self.currentWidget()
if not widget:
return
offw = 4
offh = 4
minw = min(widget.minimumWidth() + offw, MAX_INT)
minh = min(widget.minimumHeight() + offh, MAX_I... | Adjusts the min/max size based on the current tab. |
17,044 | def delete_last_line(self, file_path=, date=str(datetime.date.today())):
deleted_line = False
if os.path.isfile(file_path):
with open(file_path, ) as file:
reader = csv.reader(file, delimiter=)
for row in reader:
if date == row[0]:... | The following code was modified from
http://stackoverflow.com/a/10289740 &
http://stackoverflow.com/a/17309010
It essentially will check if the total for the current date already
exists in total.csv. If it does, it just removes the last line.
This is so the script could be run mo... |
17,045 | def get(data_label=None, destination_dir="."):
try:
os.mkdir(destination_dir)
except:
pass
if data_label is None:
data_label=data_urls.keys()
if type(data_label) == str:
data_label = [data_label]
for label in data_label:
data_url = data_urls[la... | Download sample data by data label. Labels can be listed by sample_data.data_urls.keys()
:param data_label: label of data. If it is set to None, all data are downloaded
:param destination_dir: output dir for data
:return: |
17,046 | def are_domains_equal(domain1, domain2):
domain1 = domain1.encode("idna")
domain2 = domain2.encode("idna")
return domain1.lower() == domain2.lower() | Compare two International Domain Names.
:Parameters:
- `domain1`: domains name to compare
- `domain2`: domains name to compare
:Types:
- `domain1`: `unicode`
- `domain2`: `unicode`
:return: True `domain1` and `domain2` are equal as domain names. |
17,047 | def authorized(resp, remote):
if resp and in resp:
if resp[] == :
return redirect(url_for(,
remote_app=))
elif resp[] in [,
]:
raise OAuthResponseError(
, remote... | Authorized callback handler for GitHub.
:param resp: The response.
:param remote: The remote application. |
17,048 | def formatday(self, day, weekday):
super(MiniEventCalendar, self).formatday(day, weekday)
now = get_now()
self.day = day
if day == 0:
return
elif now.month == self.mo and now.year == self.yr and day == now.day:
if day in self.count:
... | Return a day as a table cell. |
17,049 | def load(self):
self._validate()
self._logger.logging_load()
self._csv_reader = csv.reader(
six.StringIO(self.source.strip()),
delimiter=self.delimiter,
quotechar=self.quotechar,
strict=True,
skipinitialspace=True,
)
... | Extract tabular data as |TableData| instances from a CSV text object.
|load_source_desc_text|
:return:
Loaded table data.
|load_table_name_desc|
=================== ========================================
Format specifier Value after the replacemen... |
17,050 | def objects_reachable_from(obj):
found = ObjectGraph.vertex_set()
to_process = [obj]
while to_process:
obj = to_process.pop()
found.add(obj)
for referent in gc.get_referents(obj):
if referent not in found:
to_process.append(referent)
return O... | Return graph of objects reachable from *obj* via ``gc.get_referrers``.
Returns an :class:`~refcycle.object_graph.ObjectGraph` object holding all
objects reachable from the given one by following the output of
``gc.get_referrers``. Note that unlike the
:func:`~refcycle.creators.snapshot` function, the ... |
17,051 | def buy_open_order_quantity(self):
return sum(order.unfilled_quantity for order in self.open_orders if
order.side == SIDE.BUY and order.position_effect == POSITION_EFFECT.OPEN) | [int] 买方向挂单量 |
17,052 | def emailclients(self, tag=None, fromdate=None, todate=None):
return self.call("GET", "/stats/outbound/opens/emailclients", tag=tag, fromdate=fromdate, todate=todate) | Gets an overview of the email clients used to open your emails.
This is only recorded when open tracking is enabled for that email. |
17,053 | def start(self, **kwargs):
return self.client.api.start(self.id, **kwargs) | Start this container. Similar to the ``docker start`` command, but
doesn't support attach options.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error. |
17,054 | def get_hacr_channels(db=None, gps=None, connection=None,
**conectkwargs):
if connection is None:
if gps is None:
gps = from_gps()
if db is None:
db = get_database_names(gps, gps)[0]
connection = connect(db=db, **conectkwargs)
... | Return the names of all channels present in the given HACR database |
17,055 | def get(self, cls, id_field, id_val):
cache_key, flag_key = self.get_keys(cls, id_field, id_val)
result = self.get_cached_or_set_flag(keys=(cache_key, flag_key))
if len(result) == 1:
result.append(None)
previous_flag, cached_data = result
... | Retrieve an object which `id_field` matches `id_val`. If it exists in
the cache, it will be fetched from Redis. If not, it will be fetched
via the `fetch` method and cached in Redis (unless the cache flag got
invalidated in the meantime). |
17,056 | def disconnect_container_from_network(container, network_id):
log.debug(
%s\%s\,
container, network_id
)
response = _client_wrapper(,
container,
network_id)
log.debug(
%s\%s\,
container, network_id
)
... | .. versionadded:: 2015.8.3
Disconnect container from network
container
Container name or ID
network_id
Network name or ID
CLI Examples:
.. code-block:: bash
salt myminion docker.disconnect_container_from_network web-1 mynet
salt myminion docker.disconnect_contai... |
17,057 | def format_property(name, value):
result = b
utf8_name = utf8_bytes_string(name)
result = b + utf8_name
if value is not None:
utf8_value = utf8_bytes_string(value)
result += b + ( % len(utf8_value)).encode() + b + utf8_value
return result | Format the name and value (both unicode) of a property as a string. |
17,058 | def get_astrom(official=,provisional=):
sql= "SELECT m.* FROM measure m "
sql+="LEFT JOIN object o ON m.provisional LIKE o.provisional "
if not official:
sql+="WHERE o.official IS NULL"
else:
sql+="WHERE o.official LIKE " % ( official, )
sql+=" AND m.provisional LIKE " % ( ... | Query the measure table for all measurements of a particular object.
Default is to return all the astrometry in the measure table,
sorted by mjdate |
17,059 | def get_realms_and_credentials(self, uri, http_method=, body=None,
headers=None):
request = self._create_request(uri, http_method=http_method, body=body,
headers=headers)
if not self.request_validator.verify_request_toke... | Fetch realms and credentials for the presented request token.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:returns:... |
17,060 | def _removeSegment(self, segment, preserveCurve, **kwargs):
segment = self.segments[segment]
for point in segment.points:
self.removePoint(point, preserveCurve) | segment will be a valid segment index.
preserveCurve will be a boolean.
Subclasses may override this method. |
17,061 | def try_utf8_decode(value):
if not value or not is_string(value):
return value
elif PYTHON3 and not isinstance(value, bytes):
return value
elif not PYTHON3 and not isinstance(value, unicode):
return value
try:
return value.decode()
except UnicodeDecodeError:
... | Try to decode an object.
:param value:
:return: |
17,062 | def read_bitpacked_deprecated(file_obj, byte_count, count, width, debug_logging):
raw_bytes = array.array(ARRAY_BYTE_STR, file_obj.read(byte_count)).tolist()
mask = _mask_for_bits(width)
index = 0
res = []
word = 0
bits_in_word = 0
while len(res) < count and index <= len(raw_bytes):
... | Read `count` values from `fo` using the deprecated bitpacking encoding. |
17,063 | def do_cspvarica(self, varfit=, random_state=None):
if self.data_ is None:
raise RuntimeError("CSPVARICA requires data to be set")
try:
sorted(self.cl_)
for c in self.cl_:
assert(c is not None)
except (TypeError, AssertionError):
... | Perform CSPVARICA
Perform CSPVARICA source decomposition and VAR model fitting.
Parameters
----------
varfit : string
Determines how to calculate the residuals for source decomposition.
'ensemble' (default) fits one model to the whole data set,
'clas... |
17,064 | def timezone(self):
if not self._timezone_group and not self._timezone_location:
return None
if self._timezone_location != "":
return "%s/%s" % (self._timezone_group, self._timezone_location)
else:
return self._timezone_group | The name of the time zone for the location.
A list of time zone names can be obtained from pytz. For example.
>>> from pytz import all_timezones
>>> for timezone in all_timezones:
... print(timezone) |
17,065 | def ancestral_states(self, n):
anc = np.empty(n, dtype=np.intc)
_weighted_choices(self.state_indices, self.freqs, anc)
return anc | Generate ancestral sequence states from the equilibrium frequencies |
17,066 | def asset_view_prj(self, ):
if not self.cur_asset:
return
prj = self.cur_asset.project
self.view_prj(prj) | View the project of the current asset
:returns: None
:rtype: None
:raises: None |
17,067 | def image_plane_pix_grid_from_regular_grid(self, regular_grid):
pixel_scale = regular_grid.mask.pixel_scale
pixel_scales = ((regular_grid.masked_shape_arcsec[0] + pixel_scale) / (self.shape[0]),
(regular_grid.masked_shape_arcsec[1] + pixel_scale) / (self.shape[1]))
... | Calculate the image-plane pixelization from a regular-grid of coordinates (and its mask).
See *grid_stacks.SparseToRegularGrid* for details on how this grid is calculated.
Parameters
-----------
regular_grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates at th... |
17,068 | def accept_ws(buf, pos):
match = re_ws.match(buf, pos)
if not match:
return None, pos
return buf[match.start(0):match.end(0)], match.end(0) | Skip whitespace at the current buffer position. |
17,069 | def should_recover(self):
return (self.checkpoint_freq > 0
and (self.num_failures < self.max_failures
or self.max_failures < 0)) | Returns whether the trial qualifies for restoring.
This is if a checkpoint frequency is set and has not failed more than
max_failures. This may return true even when there may not yet
be a checkpoint. |
17,070 | def use_pickle():
from . import serialize
serialize.pickle = serialize._stdlib_pickle
can_map[FunctionType] = _original_can_map[FunctionType] | Revert to using stdlib pickle.
Reverts custom serialization enabled by use_dill|cloudpickle. |
17,071 | def wind_series(self):
return [(timestamp, \
self._station_history.get_measurements()[timestamp][]) \
for timestamp in self._station_history.get_measurements()] | Returns the wind speed time series relative to the
meteostation, in the form of a list of tuples, each one containing the
couple timestamp-value
:returns: a list of tuples |
17,072 | def fromdict(dict):
seed = hb_decode(dict[])
index = dict[]
return Challenge(seed, index) | Takes a dictionary as an argument and returns a new Challenge
object from the dictionary.
:param dict: the dictionary to convert |
17,073 | def session_to_hour(timestamp):
t = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN)
return t.strftime(SYNERGY_HOURLY_PATTERN) | :param timestamp: as string in YYYYMMDDHHmmSS format
:return string in YYYYMMDDHH format |
17,074 | def _http_headers(self):
if not self.usertag:
return {}
creds = u.format(
self.usertag,
self.password or
)
token = base64.b64encode(creds.encode())
return {
: .format(token.decode())
} | Return dictionary of http headers necessary for making an http
connection to the endpoint of this Connection.
:return: Dictionary of headers |
17,075 | def CheckAccess(self, token):
namespace, _ = self.urn.Split(2)
if namespace != "ACL":
raise access_control.UnauthorizedAccess(
"Approval object has invalid urn %s." % self.urn,
subject=self.urn,
requested_access=token.requested_access)
user, subject_urn = self.Infe... | Enforce a dual approver policy for access. |
17,076 | def combine_sample_regions(*samples):
samples = utils.unpack_worlds(samples)
samples = cwlutils.unpack_tarballs(samples, samples[0])
global_analysis_file = os.path.join(samples[0]["dirs"]["work"], "analysis_blocks.bed")
if utils.file_exists(global_analysis_file) and not _needs_region_update(gl... | Create batch-level sets of callable regions for multi-sample calling.
Intersects all non-callable (nblock) regions from all samples in a batch,
producing a global set of callable regions. |
17,077 | def power_off(env, identifier, hard):
virtual_guest = env.client[]
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, )
if not (env.skip_confirmations or
formatting.confirm(
% vs_id)):
raise exceptions.C... | Power off an active virtual server. |
17,078 | def _convert(cls, record):
if not record:
return {}
converted_dict = {}
for field in cls.conversion:
key = field[0]
if len(field) >= 2 and field[1]:
converted_key = field[1]
else:
converted_key = key
... | Core method of the converter. Converts a single dictionary into another dictionary. |
17,079 | def on_redraw(self):
super(WidgetLayer,self).on_redraw()
if not self._initialized:
self.initialize()
self._initialized = True | Called when the Layer should be redrawn.
If a subclass uses the :py:meth:`initialize()` Method, it is very important to also call the Super Class Method to prevent crashes. |
17,080 | def Wp(self):
Wp = trapz_loglog(self._Ep * self._J, self._Ep) * u.GeV
return Wp.to("erg") | Total energy in protons |
17,081 | def skip(self, num_bytes):
if num_bytes is None:
self._offset = len(self._data)
else:
self._offset += num_bytes | Jump the ahead the specified bytes in the buffer. |
17,082 | def _add_child(self, child, logical_block_size, allow_duplicate, check_overflow):
t have any functionality that is not appropriate for both.
Parameters:
child - The child directory record object to add.
logical_block_size - The size of a logical block for this volume descript... | An internal method to add a child to this object. Note that this is called both
during parsing and when adding a new object to the system, so it
it shouldn't have any functionality that is not appropriate for both.
Parameters:
child - The child directory record object to add.
... |
17,083 | def prepare_inputseries(self, ramflag: bool = True) -> None:
for element in printtools.progressbar(self):
element.prepare_inputseries(ramflag) | Call method |Element.prepare_inputseries| of all handled
|Element| objects. |
17,084 | def lvdisplay(lvname=, quiet=False):
**
ret = {}
cmd = [, ]
if lvname:
cmd.append(lvname)
cmd_ret = __salt__[](cmd, python_shell=False,
ignore_retcode=quiet)
if cmd_ret[] != 0:
return {}
out = cmd_ret[].splitlines()
for line in out:... | Return information about the logical volume(s)
lvname
logical device name
quiet
if the logical volume is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvdisplay
salt '*' lvm.lvdisplay /dev/vg_myserver/root |
17,085 | def _process_field_queries(field_dictionary):
def field_item(field):
return {
"match": {
field: field_dictionary[field]
}
}
return [field_item(field) for field in field_dictionary] | We have a field_dictionary - we want to match the values for an elasticsearch "match" query
This is only potentially useful when trying to tune certain search operations |
17,086 | def assemble(asmcode, pc=0, fork=DEFAULT_FORK):
return b.join(x.bytes for x in assemble_all(asmcode, pc=pc, fork=fork)) | Assemble an EVM program
:param asmcode: an evm assembler program
:type asmcode: str
:param pc: program counter of the first instruction(optional)
:type pc: int
:param fork: fork name (optional)
:type fork: str
:return: the hex representation of the bytecode
... |
17,087 | def read_mail(window):
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
(retcode, capabilities) = mail.login(LOGIN_EMAIL, LOGIN_PASSWORD)
mail.list()
typ, data = mail.select()
n = 0
now = datetime.now()
search_string = .format(now.day, calendar.month_abbr[now.month], now.year)
(retcode, ... | Reads late emails from IMAP server and displays them in the Window
:param window: window to display emails in
:return: |
17,088 | def download_unzip(names=None, normalize_filenames=False, verbose=True):
r
names = [names] if isinstance(names, (str, basestring)) else names
file_paths = {}
for name in names:
created = create_big_url(name)
name = (created or name).lower().strip()
if name in BIG_URLS:
... | r""" Download CSV or HTML tables listed in `names`, unzip and to DATA_PATH/`names`.csv .txt etc
TODO: move to web or data_utils or futils
Also normalizes file name extensions (.bin.gz -> .w2v.bin.gz).
Uses table in data_info.csv (internal DATA_INFO) to determine URL or file path from dataset name.
Also... |
17,089 | def convert_to_string(data, headers, **_):
return (([utils.to_string(v) for v in row] for row in data),
[utils.to_string(h) for h in headers]) | Convert all *data* and *headers* to strings.
Binary data that cannot be decoded is converted to a hexadecimal
representation via :func:`binascii.hexlify`.
:param iterable data: An :term:`iterable` (e.g. list) of rows.
:param iterable headers: The column headers.
:return: The processed data and hea... |
17,090 | def add_actors(self, doc:Document, event: str, cameo_code: int) -> List[Document]:
actor1_cdr = {
"ActorName": doc.cdr_document[self.attribute("Actor1Name")],
"ActorCountryCode": doc.cdr_document[self.attribute("Actor1CountryCode")],
"ActorKnownGroupCode": d... | Each event has two actors. The relationship of the event to the actors depends
on the cameo code and is defined by the mapping.
Args:
doc: the document containing the evence
event: one of "event1", "event2", or "event3"
cameo_code:
Returns: the documents crea... |
17,091 | def createNotification(self, ulOverlayHandle, ulUserValue, type_, pchText, style):
fn = self.function_table.createNotification
pImage = NotificationBitmap_t()
pNotificationId = VRNotificationId()
result = fn(ulOverlayHandle, ulUserValue, type_, pchText, style, byref(pImage), by... | Create a notification and enqueue it to be shown to the user.
An overlay handle is required to create a notification, as otherwise it would be impossible for a user to act on it.
To create a two-line notification, use a line break ('\n') to split the text into two lines.
The pImage argument may ... |
17,092 | def is_ancestor_of_repository(self, id_, repository_id):
if self._catalog_session is not None:
return self._catalog_session.is_ancestor_of_catalog(id_=id_, catalog_id=repository_id)
return self._hierarchy_session.is_ancestor(id_=id_, ancestor_id=repository_id) | Tests if an ``Id`` is an ancestor of a repository.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the Id of a repository
return: (boolean) - ``true`` if this ``id`` is an ancestor of
``repository_id,`` ``false`` otherwise
raise: NotFound - ``rep... |
17,093 | def parse_personalities(personalities_line):
tokens = personalities_line.split()
assert tokens.pop(0) == "Personalities"
assert tokens.pop(0) == ":"
personalities = []
for token in tokens:
assert token.startswith() and token.endswith()
personalities.append(token.strip())
r... | Parse the "personalities" line of ``/proc/mdstat``.
Lines are expected to be like:
Personalities : [linear] [raid0] [raid1] [raid5] [raid4] [raid6]
If they do not have this format, an error will be raised since it
would be considered an unexpected parsing error.
Parameters
----------
... |
17,094 | def noise_despike(sig, win=3, nlim=24., maxiter=4):
if win % 2 != 1:
win += 1
kernel = np.ones(win) / win
over = np.ones(len(sig), dtype=bool)
npad = int((win - 1) / 2)
over[:npad] = False
over[-npad:] = False
nloops = 0
while any(over) and (nloops < ma... | Apply standard deviation filter to remove anomalous values.
Parameters
----------
win : int
The window used to calculate rolling statistics.
nlim : float
The number of standard deviations above the rolling
mean above which data are considered outliers.
Returns
-------
... |
17,095 | def from_dict(cls, serialized):
def field(name):
return serialized.get(name) or serialized.get(name.lower())
return Error(
code=field(),
message=field(),
info=ErrorInfo.from_dict(field()),
version=bakery.LATEST_VERSIO... | Create an error from a JSON-deserialized object
@param serialized the object holding the serialized error {dict} |
17,096 | def store_memory_object(self, mo, overwrite=True):
for p in self._containing_pages_mo(mo):
self._apply_object_to_page(p, mo, overwrite=overwrite)
self._update_range_mappings(mo.base, mo.object, mo.length) | This function optimizes a large store by storing a single reference to the :class:`SimMemoryObject` instead of
one for each byte.
:param memory_object: the memory object to store |
17,097 | def remove_shard(self, shard, drop_buffered_records=False):
try:
self.roots.remove(shard)
except ValueError:
pass
else:
self.active.extend(shard.children)
if drop_buffered_records:
heap = self.buffer.heap... | Remove a Shard from the Coordinator. Drops all buffered records from the Shard.
If the Shard is active or a root, it is removed and any children promoted to those roles.
:param shard: The shard to remove
:type shard: :class:`~bloop.stream.shard.Shard`
:param bool drop_buffered_record... |
17,098 | def _sigfigs(n, sigfigs=3):
n = float(n)
if n == 0 or math.isnan(n):
return n
return round(n, -int(math.floor(math.log10(abs(n))) - sigfigs + 1)) | helper function to round a number to significant figures |
17,099 | def p_referenceInitializer(p):
if p[1][0] == :
try:
p[0] = p.parser.aliases[p[1]]
except KeyError:
ce = CIMError(
CIM_ERR_FAILED,
_format("Unknown alias: {0!A}", p[1]))
ce.file_line = (p.parser.file, p.lexer.lineno)
... | referenceInitializer : objectHandle
| aliasIdentifier |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.