Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
367,300 | def determine_packages_to_sync(self):
logger.info("Resuming interrupted sync from local todo list.")
saved_todo = iter(open(self.todolist, encoding="utf-8"))
self.target_serial = int(next(saved_todo).strip())
for line in saved_todo:
... | Update the self.packages_to_sync to contain packages that need to be
synced. |
367,301 | def changed_fields(self, from_db=False):
if self.exist:
current_dict = self.clean_value()
db_data = self._initial_data
if from_db:
db_data = self.objects.data().get(self.key)[0]
set... | Args:
from_db (bool): Check changes against actual db data
Returns:
list: List of fields names which their values changed. |
367,302 | def to_internal_value(self, data):
if html.is_html_input(data):
data = html.parse_html_dict(data)
if not isinstance(data, dict):
self.fail(, input_type=type(data).__name__)
if not self.allow_empty and len(data.keys()) == 0:
message = self.error_messa... | Dicts of native values <- Dicts of primitive datatypes. |
367,303 | def add_flooded_field(self, shapefile_path):
layer = QgsVectorLayer(
shapefile_path, self.tr(), )
layer.startEditing()
flood_class_field = QgsField(, QVariant.Int)
layer.addAttribute(flood_class_field)
lay... | Create the layer from the local shp adding the flooded field.
.. versionadded:: 3.3
Use this method to add a calculated field to a shapefile. The shapefile
should have a field called 'count' containing the number of flood
reports for the field. The field values will be set to 0 if the ... |
367,304 | def get_log_form(self, *args, **kwargs):
if isinstance(args[-1], list) or in kwargs:
return self.get_log_form_for_create(*args, **kwargs)
else:
return self.get_log_form_for_update(*args, **kwargs) | Pass through to provider LogAdminSession.get_log_form_for_update |
367,305 | def setIcon(self, icon):
icon = QIcon(icon)
if icon.isNull():
self._icon = None
self._style = XNodeHotspot.Style.Invisible
else:
self._icon = icon
self._style = XNodeHotspot.Style.Icon | Sets the icon for this hotspot. If this method is called with a valid
icon, then the style will automatically switch to Icon, otherwise,
the style will be set to Invisible.
:param icon | <QIcon> || <str> || None |
367,306 | def overlap(self, value):
if value == 0:
self._element._remove_overlap()
return
self._element.get_or_add_overlap().val = value | Set the value of the ``<c:overlap>`` child element to *int_value*,
or remove the overlap element if *int_value* is 0. |
367,307 | def header(self, k, v, replace=True):
if replace:
self._headers[k] = [v]
else:
self._headers.setdefault(k, []).append(v)
return self | Sets header value. Replaces existing value if `replace` is True.
Otherwise create a list of existing values and `v`
:param k: Header key
:param v: Header value
:param replace: flag for setting mode.
:type k: str
:type v: str
:type replace: bool |
367,308 | def create_line_plot(df):
fig = Figure("/mg/line_plot/", "mg_line_plot")
fig.graphics.transition_on_update(True)
fig.graphics.animate_on_load()
fig.layout.set_size(width=450, height=200)
fig.layout.set_margin(left=40, right=40)
return LineChart(df, fig, "Date", ["value"],
init_param... | create a mg line plot
Args:
df (pandas.DataFrame): data to plot |
367,309 | def disconnect(self, output_port, input_port):
ConnectionClass = output_port.connection_class
self.connections.remove(ConnectionClass(output_port, input_port)) | Remove a connection between (two ports of) :class:`.Effect` instances.
For this, is necessary informs the output port origin and the input port destination::
>>> pedalboard.append(driver)
>>> pedalboard.append(reverb)
>>> driver_output = driver.outputs[0]
>>> rev... |
367,310 | def install(root=None, expose=None):
VendorImporter.install_vendored(prefix=import_prefix(), root=root, expose=expose) | Installs the default :class:`VendorImporter` for PEX vendored code.
Any distributions listed in ``expose`` will also be exposed for direct import; ie:
``install(expose=['setuptools'])`` would make both ``setuptools`` and ``wheel`` available for
import via ``from pex.third_party import setuptools, wheel``, but o... |
367,311 | def remove_counter(self, key, path, consistency_level):
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_remove_counter(key, path, consistency_level)
return d | Remove a counter at the specified location.
Note that counters have limited support for deletes: if you remove a counter, you must wait to issue any following update
until the delete has reached all the nodes and all of them have been fully compacted.
Parameters:
- key
- path
- consistency_l... |
367,312 | def create_script(create=None):
if connexion.request.is_json:
create = Create.from_dict(connexion.request.get_json())
if(not hasAccess()):
return redirectUnauthorized()
driver = LoadedDrivers.getDefaultDriver()
driver.saveScript(create.script.name, create.script.content)
r... | Create a new script
Create a new script # noqa: E501
:param Scripts: The data needed to create this script
:type Scripts: dict | bytes
:rtype: Response |
367,313 | def create(cls, name, nat=False, mobile_vpn_toplogy_mode=None,
vpn_profile=None):
vpn_profile = element_resolver(vpn_profile) or \
VPNProfile().href
json = {: mobile_vpn_toplogy_mode,
: name,
: nat,
: vpn_profil... | Create a new policy based VPN
:param name: name of vpn policy
:param bool nat: whether to apply NAT to the VPN (default False)
:param mobile_vpn_toplogy_mode: whether to allow remote vpn
:param VPNProfile vpn_profile: reference to VPN profile, or uses default
:rtype: PolicyVPN |
367,314 | def gsea_significance(enrichment_scores, enrichment_nulls):
np.seterr(divide=, invalid=)
es = np.array(enrichment_scores)
esnull = np.array(enrichment_nulls)
logging.debug("Start to compute pvals..................................")
enrichmentPVals = gsea_pval(es, esnull).tol... | Compute nominal pvals, normalized ES, and FDR q value.
For a given NES(S) = NES* >= 0. The FDR is the ratio of the percentage of all (S,pi) with
NES(S,pi) >= 0, whose NES(S,pi) >= NES*, divided by the percentage of
observed S wih NES(S) >= 0, whose NES(S) >= NES*, and similarly if NES(S) = NES*... |
367,315 | def _register_key(fingerprint, gpg):
for private_key in gpg.list_keys(True):
try:
if str(fingerprint) == private_key[]:
config["gpg_key_fingerprint"] = \
repr(private_key[])
except KeyError:
pass | Registers key in config |
367,316 | def file_md5sum(filename):
hash_md5 = hashlib.md5()
with open(filename, ) as f:
for chunk in iter(lambda: f.read(1024 * 4), b):
hash_md5.update(chunk)
return hash_md5.hexdigest() | :param filename: The filename of the file to process
:returns: The MD5 hash of the file |
367,317 | def scrollTextIntoView(self, text):
if self.vc is None:
raise ValueError()
for n in range(self.maxSearchSwipes):
for v in self.vc.views:
try:
print >> sys.stderr, " scrollTextIntoV... | Performs a forward scroll action on the scrollable layout element until the text you provided is visible,
or until swipe attempts have been exhausted. See setMaxSearchSwipes(int) |
367,318 | def check_version(url=VERSION_URL):
for line in get(url):
if in line:
return line.split()[-1].strip("\r\n') | Returns the version string for the latest SDK. |
367,319 | def processFlat(self):
self.config["hier"] = False
est_idxs, est_labels, F = self.process()
assert est_idxs[0] == 0 and est_idxs[-1] == F.shape[1] - 1
return self._postprocess(est_idxs, est_labels) | Main process.for flat segmentation.
Returns
-------
est_idxs : np.array(N)
Estimated times for the segment boundaries in frame indeces.
est_labels : np.array(N-1)
Estimated labels for the segments. |
367,320 | def send_calibrate_accelerometer(self, simple=False):
calibration_command = self.message_factory.command_long_encode(
self._handler.target_system, 0,
mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION,
0,
0,
0,
0,
... | Request accelerometer calibration.
:param simple: if True, perform simple accelerometer calibration |
367,321 | def transform(self, X, y=None):
if self.normalize:
X = normalize(X)
check_is_fitted(self, "cluster_centers_")
X = self._check_test_data(X)
return self._transform(X) | Transform X to a cluster-distance space.
In the new space, each dimension is the cosine distance to the cluster
centers. Note that even if X is sparse, the array returned by
`transform` will typically be dense.
Parameters
----------
X : {array-like, sparse matrix}, shap... |
367,322 | def insert_break(lines, break_pos=9):
def line_filter(line):
if len(line) == 0:
return True
return any(line.startswith(c) for c in "-*+")
if len(lines) <= break_pos:
return lines
newlines = [
i for i, line in enumerate(lines[break_pos:], start=break_pos)
... | Insert a <!--more--> tag for larger release notes.
Parameters
----------
lines : list of str
The content of the release note.
break_pos : int
Line number before which a break should approximately be inserted.
Returns
-------
list of str
The text with the inserted ta... |
367,323 | def ser2ber(q,n,d,t,ps):
lnps = len(ps)
ber = np.zeros(lnps)
for k in range(0,lnps):
ser = ps[k]
sum1 = 0
sum2 = 0
for i in range(t+1,d+1):
term = special.comb(n,i)*(ser**i)*((1-ser))**(n-i)
sum1 = sum1 + term
for i in range(d+1,n+1):... | Converts symbol error rate to bit error rate. Taken from Ziemer and
Tranter page 650. Necessary when comparing different types of block codes.
parameters
----------
q: size of the code alphabet for given modulation type (BPSK=2)
n: number of channel bits
d: distance (2e+1) where e is the ... |
367,324 | def get_step_index(self, step=None):
if step is None:
step = self.steps.current
return self.get_form_list().keyOrder.index(step) | Returns the index for the given `step` name. If no step is given,
the current step will be used to get the index. |
367,325 | def _SetupPaths():
sdk_path = _FindSdkPath()
if sdk_path:
sys.path.append(sdk_path)
try:
import dev_appserver
if hasattr(dev_appserver, ):
dev_appserver.fix_sys_path()
else:
logging.warning(_NO_FIX_SYS_PATH_WARNING)
except ImportError:
logging.warning(_IMPORT... | Sets up the sys.path with special directories for endpointscfg.py. |
367,326 | def update_mapping_meta(self, doc_type, values, indices=None):
indices = self._validate_indices(indices)
for index in indices:
mapping = self.mappings.get_doctype(index, doc_type)
if mapping is None:
continue
meta = mapping.get_meta()
... | Update mapping meta
:param doc_type: a doc type or a list of doctypes
:param values: the dict of meta
:param indices: a list of indices
:return: |
367,327 | def write_chunks(out, chunks):
out.write(png_signature)
for chunk in chunks:
write_chunk(out, *chunk) | Create a PNG file by writing out the chunks. |
367,328 | def install_napp(cls, mgr):
try:
LOG.info()
mgr.install_local()
LOG.info()
except FileNotFoundError:
LOG.info()
try:
mgr.install_remote()
LOG.info()
return
except HTTPError as... | Install a NApp.
Raises:
KytosException: If a NApp hasn't been found. |
367,329 | def change_key(self, key):
services = {}
for service_name in self.list_services():
services[service_name] = self.get_service(service_name)
orgs = {}
for org_name in self.list_orgs():
orgs[org_name] = self.get_org(org_name)
self.key = key
... | re-encrypt stored services and orgs with the new key |
367,330 | def get_protein_seq_for_transcript(self, transcript_id):
headers = {"content-type": "text/plain"}
self.attempt = 0
ext = "/sequence/id/{}?type=protein".format(transcript_id)
return self.ensembl_request(ext, headers) | obtain the sequence for a transcript from ensembl |
367,331 | def wsgi_server_target(self, wsgi_environment, response_start):
route_result = {}
request_method = wsgi_environment[]
path_info = wsgi_environment[]
if self.PATH_INFO_mode == :
path_info = path_info.encode().decode()
wsgi_environment[] = path_info
... | Searches route in self.routes and passes found target wsgi_environment,
response_start and route_result. explanation for route_result is in
Route class.
result from ranning this method is simply passed from target to carafe
calling fuctionality. see Carafe class for explanations to this... |
367,332 | def inherit_set(base, namespace, attr_name,
inherit=lambda i: True):
items = []
base_set = getattr(base, attr_name, set())
new_set = namespace.setdefault(attr_name, set())
for item in base_set:
if item in new_s... | Perform inheritance of sets. Returns a list of items that
were inherited, for post-processing.
:param base: The base class being considered; see
``iter_bases()``.
:param namespace: The dictionary of the new class being built.
:param attr_name: The name of the attri... |
367,333 | def send_request(self, worker_class_or_function, args, on_receive=None):
if not self.running:
try:
self.start(self.server_script, interpreter=self.interpreter,
args=self.args)
except AttributeError:
pass... | Requests some work to be done by the backend. You can get notified of
the work results by passing a callback (on_receive).
:param worker_class_or_function: Worker class or function
:param args: worker args, any Json serializable objects
:param on_receive: an optional callback executed w... |
367,334 | def find_words(text, suspect_words, excluded_words=[]):
text = text.lower()
suspect_found = [i for i in re.finditer(make_regex(suspect_words), text)]
if len(excluded_words) > 0:
excluded_found = [i for i in re.finditer(make_regex(excluded_words), text)]
if len(suspect_found) > len(exclu... | Check if a text has some of the suspect words (or words that starts with
one of the suspect words). You can set some words to be excluded of the
search, so you can remove false positives like 'important' be detected when
you search by 'import'. It will return True if the number of suspect words
found is... |
367,335 | def delete(filething):
t = OggFLAC(filething)
filething.fileobj.seek(0)
t.delete(filething) | delete(filething)
Arguments:
filething (filething)
Raises:
mutagen.MutagenError
Remove tags from a file. |
367,336 | async def variant(self, elem=None, elem_type=None, params=None, obj=None):
elem_type = elem_type if elem_type else elem.__class__
if hasattr(elem_type, ):
elem = elem_type() if elem is None else elem
return await elem.kv_serialize(self, elem=elem, elem_type=elem_type, p... | Loads/dumps variant type
:param elem:
:param elem_type:
:param params:
:param obj:
:return: |
367,337 | def count_seeds(usort):
with open(usort, ) as insort:
cmd1 = ["cut", "-f", "2"]
cmd2 = ["uniq"]
cmd3 = ["wc"]
proc1 = sps.Popen(cmd1, stdin=insort, stdout=sps.PIPE, close_fds=True)
proc2 = sps.Popen(cmd2, stdin=proc1.stdout, stdout=sps.PIPE, close_fds=True)
proc3... | uses bash commands to quickly count N seeds from utemp file |
367,338 | def write_config(self):
config_file = os.path.join(self.config_dir, )
with open(config_file, ) as file_descriptor:
self.config.write(file_descriptor) | Write the current configuration to the config file. |
367,339 | def get_include_files():
plugin_data_files = []
trust_stores_pem_path = path.join(root_path, , , , , )
for file in listdir(trust_stores_pem_path):
file = path.join(trust_stores_pem_path, file)
if path.isfile(file):
filename = path.basename(file)
plugin_data_fil... | Get the list of trust stores so they properly packaged when doing a cx_freeze build. |
367,340 | def r2_score(y_true, y_pred):
if y_pred.ndim == 1:
var_y_est = np.var(y_pred)
var_e = np.var(y_true - y_pred)
else:
var_y_est = np.var(y_pred.mean(0))
var_e = np.var(y_true - y_pred, 0)
r_squared = var_y_est / (var_y_est + var_e)
return pd.Series([np.mean(r_squared... | R² for Bayesian regression models. Only valid for linear models.
Parameters
----------
y_true: : array-like of shape = (n_samples) or (n_samples, n_outputs)
Ground truth (correct) target values.
y_pred : array-like of shape = (n_samples) or (n_samples, n_outputs)
Estimated target values... |
367,341 | def set_args(self, **kwargs):
try:
kwargs_items = kwargs.iteritems()
except AttributeError:
kwargs_items = kwargs.items()
for key, val in kwargs_items:
self.args[key] = val | Set more arguments to self.args
args:
**kwargs:
key and value represents dictionary key and value |
367,342 | def post_user_login(sender, request, user, **kwargs):
logger.debug("Running post-processing for user login.")
try:
with transaction.atomic():
profile, created = UserProfile.objects.get_or_create(user=user)
if created:
logger.info("Created missing pr... | Create a profile for the user, when missing.
Make sure that all neccessary user groups exist and have the right permissions.
We need that automatism for people not calling the configure tool,
admin rights for admins after the first login, and similar cases. |
367,343 | def contains(this, that, axis=semantics.axis_default):
this = as_index(this, axis=axis, lex_as_struct=True, base=True)
that = as_index(that, axis=axis, lex_as_struct=True)
left = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side=)
right = np.searchsorted(that._keys, this._keys, sort... | Returns bool for each element of `that`, indicating if it is contained in `this`
Parameters
----------
this : indexable key sequence
sequence of items to test against
that : indexable key sequence
sequence of items to test for
Returns
-------
ndarray, [that.size], bool
... |
367,344 | def available_tcp_port(reactor):
endpoint = serverFromString(reactor, )
port = yield endpoint.listen(NoOpProtocolFactory())
address = port.getHost()
yield port.stopListening()
defer.returnValue(address.port) | Returns a Deferred firing an available TCP port on localhost.
It does so by listening on port 0; then stopListening and fires the
assigned port number. |
367,345 | def prepend(self, _, child, name=None):
self._insert(child, prepend=True, name=name)
return self | Adds childs to this tag, starting from the first position. |
367,346 | def WhereIs(self, prog, path=None, pathext=None, reject=[]):
if path is None:
try:
path = self[][]
except KeyError:
pass
elif SCons.Util.is_String(path):
path = self.subst(path)
if pathext is None:
try:
... | Find prog in the path. |
367,347 | def register_hit_type(
self, title, description, reward, duration_hours, keywords, qualifications
):
reward = str(reward)
duration_secs = int(datetime.timedelta(hours=duration_hours).total_seconds())
hit_type = self.mturk.create_hit_type(
Title=title,
... | Register HIT Type for this HIT and return the type's ID, which
is required for creating a HIT. |
367,348 | def advance(parser):
prev_end = parser.token.end
parser.prev_end = prev_end
parser.token = parser.lexer.next_token(prev_end) | Moves the internal parser object to the next lexed token. |
367,349 | def get_key_auth_cb(key_filepath):
def auth_cb(ssh):
key = ssh_pki_import_privkey_file(key_filepath)
ssh.userauth_publickey(key)
return auth_cb | This is just a convenience function for key-based login. |
367,350 | def label_components(self, display = None):
component
if self.graph_type == DIRECTED_GRAPH:
raise Exception("label_components only works for ",
"undirected graphs")
self.num_components = 0
for n in self.get_node_list():
self.get_node(n)... | API: label_components(self, display=None)
Description:
This method labels the nodes of an undirected graph with component
numbers so that each node has the same label as all nodes in the
same component. It will display the algortihm if display argument is
provided.
Input:... |
367,351 | def state():
playingpausedstopped
server = getServer()
state = server.core.playback.get_state()
logging.debug(, state)
if state.upper() == :
print()
else:
track = server.core.playback.get_current_track()
logging.debug(, track)
logging.debug(, jsonrpclib.jsonclass... | Get The playback state: 'playing', 'paused', or 'stopped'.
If PLAYING or PAUSED, show information on current track.
Calls PlaybackController.get_state(), and if state is PLAYING or PAUSED, get
PlaybackController.get_current_track() and
PlaybackController.get_time_position() |
367,352 | def find(self, item, description=, event_type=):
if in item:
splited = item.split(, 1)
if splited[0] in self.TYPES:
description = item.split()[1]
event_type = item.split()[0]
else:
description = item
e... | Find regexp in activitylog
find record as if type are in description. |
367,353 | def htmlCtxtUseOptions(self, options):
ret = libxml2mod.htmlCtxtUseOptions(self._o, options)
return ret | Applies the options to the parser context |
367,354 | def update_metric(self, metric, labels, pre_sliced=False):
self.curr_execgrp.update_metric(metric, labels, pre_sliced) | Update metric with the current executor. |
367,355 | def send_signal(self, s):
self._get_signal_event(s)
pid = self.get_pid()
if not pid:
raise ValueError()
os.kill(pid, s) | Send a signal to the daemon process.
The signal must have been enabled using the ``signals``
parameter of :py:meth:`Service.__init__`. Otherwise, a
``ValueError`` is raised. |
367,356 | def cookie_attr_value_check(attr_name, attr_value):
attr_value.encode()
return WHTTPCookie.cookie_attr_value_compliance[attr_name].match(attr_value) is not None | Check cookie attribute value for validity. Return True if value is valid
:param attr_name: attribute name to check
:param attr_value: attribute value to check
:return: bool |
367,357 | def referenceLengths(self):
result = {}
with samfile(self.filename) as sam:
if self.referenceIds:
for referenceId in self.referenceIds:
tid = sam.get_tid(referenceId)
if tid == -1:
raise UnknownReference... | Get the lengths of wanted references.
@raise UnknownReference: If a reference id is not present in the
SAM/BAM file.
@return: A C{dict} of C{str} reference id to C{int} length with a key
for each reference id in C{self.referenceIds} or for all references
if C{self.re... |
367,358 | def search(self, CorpNum, JobID, TradeType, TradeUsage, Page, PerPage, Order, UserID=None):
if JobID == None or len(JobID) != 18:
raise PopbillException(-99999999, "작업아이디(jobID)가 올바르지 않습니다.")
uri = + JobID
uri += + .join(TradeType)
uri += + .join(TradeUsage)
... | 수집 결과 조회
args
CorpNum : 팝빌회원 사업자번호
JobID : 작업아이디
TradeType : 문서형태 배열, N-일반 현금영수증, C-취소 현금영수증
TradeUsage : 거래구분 배열, P-소등공제용, C-지출증빙용
Page : 페이지 번호
PerPage : 페이지당 목록 개수, 최대 1000개
Order : 정렬 방향, D-내림... |
367,359 | def parse_color(color):
r
if isinstance(color, basestring):
color = grapefruit.Color.NewFromHtml(color)
if isinstance(color, int):
(r, g, b) = xterm256.xterm_to_rgb(color)
elif hasattr(color, ):
(r, g, b) = [int(c * 255.0) for c in color.rgb]
else:
(r, g, b) = color
... | r"""Turns a color into an (r, g, b) tuple
>>> parse_color('white')
(255, 255, 255)
>>> parse_color('#ff0000')
(255, 0, 0)
>>> parse_color('#f00')
(255, 0, 0)
>>> parse_color((255, 0, 0))
(255, 0, 0)
>>> from fabulous import grapefruit
>>> parse_color(grapefruit.Color((0.0, 1.0, ... |
367,360 | def paste(xsel=False):
selection = "primary" if xsel else "clipboard"
try:
return subprocess.Popen(["xclip", "-selection", selection, "-o"], stdout=subprocess.PIPE).communicate()[0].decode("utf-8")
except OSError as why:
raise XclipNotFound | Returns system clipboard contents. |
367,361 | def connect(self, exe_path=None, **kwargs):
connect_path = exe_path or self._config.DEFAULT_EXE_PATH
if connect_path is None:
raise ValueError(
"参数 exe_path 未设置,请设置客户端对应的 exe 地址,类似 C:\\客户端安装目录\\xiadan.exe"
)
self._app = pywinauto.Application().co... | 直接连接登陆后的客户端
:param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe'
:return: |
367,362 | def _rm_get_repeat_coords_from_header(parts):
assert((parts[8] == "C" and len(parts) == 15) or (len(parts) == 14))
if len(parts) == 14:
s = int(parts[9])
e = int(parts[10]) + 1
else:
s = int(parts[12])
e = int(parts[11]) + 1
if (s >= e):
raise AlignmentIteratorError("invalid repeatmakser ... | extract the repeat coordinates of a repeat masker match from a header line.
An example header line is::
239 29.42 1.92 0.97 chr1 11 17 (41) C XX#YY (74) 104 1 m_b1s502i1 4
239 29.42 1.92 0.97 chr1 11 17 (41) XX#YY 1 104 (74) m_b1s502i1 4
if the match is to the reverse complement, the start and end coordi... |
367,363 | def loads(data, use_datetime=0):
p, u = getparser(use_datetime=use_datetime)
p.feed(data)
p.close()
return u.close(), u.getmethodname() | data -> unmarshalled data, method name
Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
If the XML-RPC packet represents a fault condition, this function
raises a Fault exception. |
367,364 | def to_bitarray(data, width=8):
if isinstance(data, list) or isinstance(data, bytearray):
data = combine_hex(data)
return [True if digit == else False for digit in bin(data)[2:].zfill(width)] | Convert data (list of integers, bytearray or integer) to bitarray |
367,365 | def _guess_x_simple(self, y_desired, y_dims=None, **kwargs):
_, indexes = self.fmodel.dataset.nn_y(y_desired, dims=y_dims, k = 10)
return [self.fmodel.get_x(i) for i in indexes] | Provide an initial guesses for a probable x from y |
367,366 | def _write_csv(self, datasets, filename):
with open(.join([self.output, filename]), mode=, encoding=self.encoding) as write_file:
writer = csv.writer(write_file, delimiter=)
for i, row in enumerate(datasets):
if i == 0:
wr... | Write CSV
:param datasets: Datasets
:param filename: File Name |
367,367 | def load_from_config(self, config):
self.site = config.get("id", False)
self.classification = config.get("class", False)
self.tags = config.get("tags", False)
self._load_key_value(
config.get("key_value_data", False)
)
self._load_data(
con... | Load model from passed configuration. |
367,368 | def pstdev(data, mu=None):
var = pvariance(data, mu)
try:
return var.sqrt()
except AttributeError:
return math.sqrt(var) | Return the square root of the population variance.
See ``pvariance`` for arguments and other details. |
367,369 | def smoothed_hazard_(self, bandwidth):
timeline = self.timeline
cumulative_hazard_name = self.cumulative_hazard_.columns[0]
hazard_name = "differenced-" + cumulative_hazard_name
hazard_ = self.cumulative_hazard_.diff().fillna(self.cumulative_hazard_.iloc[0])
C = (hazard_... | Parameters
-----------
bandwidth: float
the bandwith used in the Epanechnikov kernel.
Returns
-------
DataFrame:
a DataFrame of the smoothed hazard |
367,370 | def add_if_unique(self, name):
with self.lock:
if name not in self.names:
self.names.append(name)
return True
return False | Returns ``True`` on success.
Returns ``False`` if the name already exists in the namespace. |
367,371 | def send_single_value(self, channel: int, value: int) -> int:
SetSingleChannel = 1
n = self._send_control_message(SetSingleChannel, value_or_length=value, channel=channel, data_or_length=1)
return n | Send a single value to the uDMX
:param channel: DMX channel number, 1-512
:param value: Value to be sent to channel, 0-255
:return: number of bytes actually sent |
367,372 | def get_users(session, query):
response = make_get_request(session, , params_data=query)
json_data = response.json()
if response.status_code == 200:
return json_data[]
else:
raise UsersNotFoundException(
message=json_data[],
error_code=json_data[],
... | Get one or more users |
367,373 | def t_ID(self, t):
r
if t.value in self.reserved:
t.type = self.reserved[t.value]
return t | r"""[a-zA-Z_][a-zA-Z_0-9]* |
367,374 | def topil(self, **kwargs):
if self.has_preview():
return pil_io.convert_image_data_to_pil(self._record, **kwargs)
return None | Get PIL Image.
:return: :py:class:`PIL.Image`, or `None` if the composed image is not
available. |
367,375 | def to_julian_date(self):
year = np.asarray(self.year)
month = np.asarray(self.month)
day = np.asarray(self.day)
testarr = month < 3
year[testarr] -= 1
month[testarr] += 12
return (day +
np.fix((153 * month - 457) / 5) +
... | Convert Datetime Array to float64 ndarray of Julian Dates.
0 Julian date is noon January 1, 4713 BC.
http://en.wikipedia.org/wiki/Julian_day |
367,376 | def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated) | Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenien... |
367,377 | def filter_recordings(recordings):
new_recordings = []
for recording in recordings:
recording[] = json.loads(recording[])
tmp = json.loads(recording[])
recording[] = normalize_segmentation(tmp)
had_none = False
for stroke in recording[]:
for point in stro... | Remove all recordings which have points without time.
Parameters
----------
recordings : list of dicts
Each dictionary has the keys 'data' and 'segmentation'
Returns
-------
list of dicts :
Only recordings where all points have time values. |
367,378 | def current_frame(self):
if not self.__fps:
raise RuntimeError("fps not set so current frame number cannot be"
" calculated")
else:
return int(self.__fps * self.time) | The current frame number that should be displayed. |
367,379 | def trim_wav_ms(in_path: Path, out_path: Path,
start_time: int, end_time: int) -> None:
try:
trim_wav_sox(in_path, out_path, start_time, end_time)
except FileNotFoundError:
trim_wav_pydub(in_path, out_path, start_time, end_time)
except subprocess.CalledProcessE... | Extracts part of a WAV File.
First attempts to call sox. If sox is unavailable, it backs off to
pydub+ffmpeg.
Args:
in_path: A path to the source file to extract a portion of
out_path: A path describing the to-be-created WAV file.
start_time: The point in the source WAV file at whi... |
367,380 | def community_topic_posts(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/posts
api_path = "/api/v2/community/topics/{id}/posts.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/help_center/posts#list-posts |
367,381 | def addToDB(abbr = None, dbname = manualDBname):
dbLoc = os.path.normpath(os.path.dirname(__file__))
with dbm.dumb.open(dbLoc + + dbname) as db:
if isinstance(abbr, str):
db[abbr] = abbr
elif isinstance(abbr, dict):
try:
db.update(abbr)
e... | Adds _abbr_ to the database of journals. The database is kept separate from the one scraped from WOS, this supersedes it. The database by default is stored with the WOS one and the name is given by `metaknowledge.journalAbbreviations.manualDBname`. To create an empty database run **addToDB** without an _abbr_ argument.... |
367,382 | def render_diagram(root_task, out_base, max_param_len=20, horizontal=False, colored=False):
import re
import codecs
import subprocess
from ozelot import config
from ozelot.etl.tasks import get_task_name, get_task_param_string
lines = [u"digraph G {"]
if horizontal:
lines.... | Render a diagram of the ETL pipeline
All upstream tasks (i.e. requirements) of :attr:`root_task` are rendered.
Nodes are, by default, styled as simple rects. This style is augmented by any
:attr:`diagram_style` attributes of the tasks.
.. note:: This function requires the 'dot' executable from the Gr... |
367,383 | def _string_find(self, substr, start=None, end=None):
if end is not None:
raise NotImplementedError
return ops.StringFind(self, substr, start, end).to_expr() | Returns position (0 indexed) of first occurence of substring,
optionally after a particular position (0 indexed)
Parameters
----------
substr : string
start : int, default None
end : int, default None
Not currently implemented
Returns
-------
position : int, 0 indexed |
367,384 | def compute_checksum(line):
return sum((int(c) if c.isdigit() else c == ) for c in line[0:68]) % 10 | Compute the TLE checksum for the given line. |
367,385 | def maybe_call_closing_deferred(self):
if self._closing_deferred:
self._closing_deferred.callback(self)
self._closing_deferred = None | Used internally to callback on the _closing_deferred if it
exists. |
367,386 | def setModel(self, model):
check_class(model, BaseTreeModel)
super(ArgosTreeView, self).setModel(model) | Sets the model.
Checks that the model is a |
367,387 | def trans_new(name, transform, inverse, breaks=None,
minor_breaks=None, _format=None,
domain=(-np.inf, np.inf), doc=, **kwargs):
def _get(func):
if isinstance(func, (classmethod, staticmethod, MethodType)):
return func
else:
return staticmetho... | Create a transformation class object
Parameters
----------
name : str
Name of the transformation
transform : callable ``f(x)``
A function (preferably a `ufunc`) that computes
the transformation.
inverse : callable ``f(x)``
A function (preferably a `ufunc`) that compu... |
367,388 | def UrnStringToHuntId(urn):
if urn.startswith(AFF4_PREFIX):
urn = urn[len(AFF4_PREFIX):]
components = urn.split("/")
if len(components) != 2 or components[0] != "hunts":
raise ValueError("Invalid hunt URN: %s" % urn)
return components[-1] | Converts given URN string to a flow id string. |
367,389 | def lattice(self, lattice):
self._lattice = lattice
self._coords = self._lattice.get_cartesian_coords(self._frac_coords) | Sets Lattice associated with PeriodicSite |
367,390 | def decode_conjure_bean_type(cls, obj, conjure_type):
deserialized = {}
for (python_arg_name, field_definition) \
in conjure_type._fields().items():
field_identifier = field_definition.identifier
if field_identifier not in obj or obj[field_identifier] ... | Decodes json into a conjure bean type (a plain bean, not enum
or union).
Args:
obj: the json object to decode
conjure_type: a class object which is the bean type
we're decoding into
Returns:
A instance of a bean of type conjure_type. |
367,391 | def make_rawr_zip_payload(rawr_tile, date_time=None):
if date_time is None:
date_time = gmtime()[0:6]
buf = StringIO()
with zipfile.ZipFile(buf, mode=) as z:
for fmt_data in rawr_tile.all_formatted_data:
zip_info = zipfile.ZipInfo(fmt_data.name, date_time)
z.wri... | make a zip file from the rawr tile formatted data |
367,392 | def toc(self):
if not self.activated:
return []
for exe in self.exes:
for array in exe.arg_arrays:
array.wait_to_read()
for array in exe.aux_arrays:
array.wait_to_read()
for exe in self.exes:
for name, array... | End collecting for current batch and return results.
Call after computation of current batch.
Returns
-------
res : list of |
367,393 | def add_content(self, content, mime_type=None):
if isinstance(content, str):
content = Content(mime_type, content)
if content.mime_type == "text/plain":
self._contents = self._ensure_insert(content, self._contents)
else:
if self._contents:
... | Add content to the email
:param contents: Content to be added to the email
:type contents: Content
:param mime_type: Override the mime type
:type mime_type: MimeType, str |
367,394 | def lost_dimensions(point_fmt_in, point_fmt_out):
unpacked_dims_in = PointFormat(point_fmt_in).dtype
unpacked_dims_out = PointFormat(point_fmt_out).dtype
out_dims = unpacked_dims_out.fields
completely_lost = []
for dim_name in unpacked_dims_in.names:
if dim_name not in out_dims:
... | Returns a list of the names of the dimensions that will be lost
when converting from point_fmt_in to point_fmt_out |
367,395 | def rbd_exists(service, pool, rbd_img):
try:
out = check_output([, , ,
service, , pool])
if six.PY3:
out = out.decode()
except CalledProcessError:
return False
return rbd_img in out | Check to see if a RADOS block device exists. |
367,396 | def requires_to_requires_dist(requirement):
requires_dist = []
for op, ver in requirement.specs:
requires_dist.append(op + ver)
if not requires_dist:
return
return " (%s)" % .join(requires_dist) | Compose the version predicates for requirement in PEP 345 fashion. |
367,397 | async def _queue(self, ctx, page: int = 1):
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.queue:
return await ctx.send(s nothing in the queue! Why not queue something?`{index + 1}.` [**{track.title}**]({track.uri})\n**{len(player.queue)} tracks**\n\n{queue... | Shows the player's queue. |
367,398 | def pcmd(host, seq, progressive, lr, fb, vv, va):
p = 1 if progressive else 0
at(host, , seq, [p, float(lr), float(fb), float(vv), float(va)]) | Makes the drone move (translate/rotate).
Parameters:
seq -- sequence number
progressive -- True: enable progressive commands, False: disable (i.e.
enable hovering mode)
lr -- left-right tilt: float [-1..1] negative: left, positive: right
rb -- front-back tilt: float [-1..1] negative: forwar... |
367,399 | def dump_misspelling_list(self):
results = []
for bad_word in sorted(self._misspelling_dict.keys()):
for correction in self._misspelling_dict[bad_word]:
results.append([bad_word, correction])
return results | Returns a list of misspelled words and corrections. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.