code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def connect(self, callback=None, timeout=None):
if hasattr(self, '_connecting_future') and not self._connecting_future.done():
future = self._connecting_future
else:
if hasattr(self, '_connecting_future'):
self._connecting_future.exception()
future = t... | Connect to the IPC socket |
def _prep_sample_cnvs(cnv_file, data):
import pybedtools
sample_name = tz.get_in(["rgnames", "sample"], data)
def make_names(name):
return re.sub("[^\w.]", '.', name)
def matches_sample_name(feat):
return (feat.name == sample_name or feat.name == "X%s" % sample_name or
fe... | Convert a multiple sample CNV file into a single BED file for a sample.
Handles matching and fixing names where R converts numerical IDs (1234) into
strings by adding an X (X1234), and converts other characters into '.'s.
http://stat.ethz.ch/R-manual/R-devel/library/base/html/make.names.html |
def stem(self, form, tag):
key = (form, tag)
if key not in self.lemma_cache:
lemma = self.stemmer(*key).word()
self.lemma_cache[key] = lemma
return self.lemma_cache[key] | Returns the stem of word with specific form and part-of-speech
tag according to the Stanford lemmatizer. Lemmas are cached. |
def _map_purchase_request_to_func(self, purchase_request_type):
if purchase_request_type in self._intent_view_funcs:
view_func = self._intent_view_funcs[purchase_request_type]
else:
raise NotImplementedError('Request type "{}" not found and no default view specified.'.format(purc... | Provides appropriate parameters to the on_purchase functions. |
def get_default_vpc():
ec2 = get_ec2_resource()
for vpc in ec2.vpcs.all():
if vpc.is_default:
return vpc | Return default VPC or none if not present |
def from_key_bytes(cls, algorithm, key_bytes):
return cls(
algorithm=algorithm, key=serialization.load_der_public_key(data=key_bytes, backend=default_backend())
) | Creates a `Verifier` object based on the supplied algorithm and raw verification key.
:param algorithm: Algorithm on which to base verifier
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes encoded_point: Raw verification key
:returns: Instance of Verifier generated... |
def authenticate(self, request):
authenticators = self._meta.authenticators
if request.method == 'OPTIONS' and ADREST_ALLOW_OPTIONS:
self.auth = AnonimousAuthenticator(self)
return True
error_message = "Authorization required."
for authenticator in authenticators:... | Attempt to authenticate the request.
:param request: django.http.Request instance
:return bool: True if success else raises HTTP_401 |
def change_password(username, password, uid=None, host=None,
admin_username=None, admin_password=None,
module=None):
if len(password) > 20:
raise CommandExecutionError('Supplied password should be 20 characters or less')
if uid is None:
user = list_users(h... | Change user's password
CLI Example:
.. code-block:: bash
salt dell dracr.change_password [USERNAME] [PASSWORD] uid=[OPTIONAL]
host=<remote DRAC> admin_username=<DRAC user>
admin_password=<DRAC PW>
salt dell dracr.change_password diana secret
Note that if only a us... |
def seek(self, value, target="offset"):
if target not in (u'offset', u'id'):
raise ArgumentError("You must specify target as either offset or id", target=target)
if target == u'offset':
self._verify_offset(value)
self.offset = value
else:
self.offs... | Seek this stream to a specific offset or reading id.
There are two modes of use. You can seek to a specific reading id,
which means the walker will be positioned exactly at the reading
pointed to by the reading ID. If the reading id cannot be found
an exception will be raised. The re... |
def main():
setup_main_logger(console=True, file_logging=False)
params = argparse.ArgumentParser(description='Quick usage: python3 -m sockeye.init_embedding '
'-w embed-in-src.npy embed-in-tgt.npy '
'-i vocab-in-sr... | Commandline interface to initialize Sockeye embedding weights with pretrained word representations. |
def right_axis_label(self, label, position=None, rotation=-60, offset=0.08,
**kwargs):
if not position:
position = (2. / 5 + offset, 3. / 5, 0)
self._labels["right"] = (label, position, rotation, kwargs) | Sets the label on the right axis.
Parameters
----------
label: String
The axis label
position: 3-Tuple of floats, None
The position of the text label
rotation: float, -60
The angle of rotation of the label
offset: float,
Us... |
def ToDebugString(self):
text_parts = ['Path segment index\tWeight']
for path_segment_index, weight in self._weight_per_index.items():
text_parts.append('{0:d}\t\t\t{1:d}'.format(
path_segment_index, weight))
text_parts.append('')
text_parts.append('Weight\t\t\tPath segment index(es)')
... | Converts the path segment weights into a debug string. |
def has_started(self):
assessment_offered = self.get_assessment_offered()
if assessment_offered.has_start_time():
return DateTime.utcnow() >= assessment_offered.get_start_time()
else:
return True | Tests if this assessment has begun.
return: (boolean) - ``true`` if the assessment has begun,
``false`` otherwise
*compliance: mandatory -- This method must be implemented.* |
def dict_snake_to_camel_case(snake_dict, convert_keys=True, convert_subkeys=False):
converted = {}
for key, value in snake_dict.items():
if isinstance(value, dict):
new_value = dict_snake_to_camel_case(value, convert_keys=convert_subkeys,
conv... | Recursively convert a snake_cased dict into a camelCased dict
:param snake_dict: Dictionary to convert
:param convert_keys: Whether the key should be converted
:param convert_subkeys: Whether to also convert the subkeys, in case they are named properties of the dict
:return: |
def handleSync(self, msg: Any) -> Any:
if isinstance(msg, tuple) and len(
msg) == 2 and not hasattr(msg, '_field_types'):
return self.getFunc(msg[0])(*msg)
else:
return self.getFunc(msg)(msg) | Pass the message as an argument to the function defined in `routes`.
If the msg is a tuple, pass the values as multiple arguments to the function.
:param msg: tuple of object and callable |
def home_slug():
prefix = get_script_prefix()
slug = reverse("home")
if slug.startswith(prefix):
slug = '/' + slug[len(prefix):]
try:
return resolve(slug).kwargs["slug"]
except KeyError:
return slug | Returns the slug arg defined for the ``home`` urlpattern, which
is the definitive source of the ``url`` field defined for an
editable homepage object. |
def sky_dist(src1, src2):
if np.all(src1 == src2):
return 0
return gcd(src1.ra, src1.dec, src2.ra, src2.dec) | Great circle distance between two sources.
A check is made to determine if the two sources are the same object, in this case
the distance is zero.
Parameters
----------
src1, src2 : object
Two sources to check. Objects must have parameters (ra,dec) in degrees.
Returns
-------
d... |
def execute(self):
if not self.cmd.is_conn_available():
return
if self.cmd.connection.lowest_server_version >= SYSINFO_MIN_VERSION:
success, rows = self._sys_info()
self.cmd.exit_code = self.cmd.exit_code or int(not success)
if success:
for... | print system and cluster info |
def _create_worker(self, worker):
worker.sig_started.connect(self._start)
self._workers.append(worker) | Common worker setup. |
def get_token(self, code, headers=None, **kwargs):
self._check_configuration("site", "token_url", "redirect_uri",
"client_id", "client_secret")
url = "%s%s" % (self.site, quote(self.token_url))
data = {
'redirect_uri': self.redirect_uri,
... | Requests an access token |
def calculate_row_format(columns, keys=None):
row_format = ''
if keys is None:
keys = columns.keys()
else:
keys = [key for key in keys if key in columns]
for key in keys:
if len(row_format) > 0:
row_format += "|"
row_format += "%%(%s)-%ds" % (key, columns[key]... | Calculate row format.
Args:
columns (dict): the keys are the column name and the value the max length.
keys (list): optional list of keys to order columns as well as to filter for them.
Returns:
str: format for table row |
def rms(x):
try:
return (np.array(x) ** 2).mean() ** 0.5
except:
x = np.array(dropna(x))
invN = 1.0 / len(x)
return (sum(invN * (x_i ** 2) for x_i in x)) ** .5 | Root Mean Square"
Arguments:
x (seq of float): A sequence of numerical values
Returns:
The square root of the average of the squares of the values
math.sqrt(sum(x_i**2 for x_i in x) / len(x))
or
return (np.array(x) ** 2).mean() ** 0.5
>>> rms([0, 2, 4, 4])
3... |
def _repr(obj):
vals = ", ".join("{}={!r}".format(
name, getattr(obj, name)) for name in obj._attribs)
if vals:
t = "{}(name={}, {})".format(obj.__class__.__name__, obj.name, vals)
else:
t = "{}(name={})".format(obj.__class__.__name__, obj.name)
return t | Show the received object as precise as possible. |
def updateMesh(self, polydata):
self.poly = polydata
self.mapper.SetInputData(polydata)
self.mapper.Modified()
return self | Overwrite the polygonal mesh of the actor with a new one. |
def seek(self, offset, whence=0, mode='rw'):
try:
st = self._sndfile.seek(offset, whence, mode)
except IOError, e:
raise PyaudioIOError(str(e))
return st | similar to python seek function, taking only in account audio data.
:Parameters:
offset : int
the number of frames (eg two samples for stereo files) to move
relatively to position set by whence.
whence : int
only 0 (beginning), 1 (current)... |
def set_acl(self, role, users):
acl_updates = [{"user": user, "role": role} for user in users]
r = fapi.update_repository_method_acl(
self.namespace, self.name, self.snapshot_id,
acl_updates, self.api_url
)
fapi._check_response_code(r, 200) | Set permissions for this method.
Args:
role (str): Access level
one of {one of "OWNER", "READER", "WRITER", "NO ACCESS"}
users (list(str)): List of users to give role to |
def clean(self, list_article_candidates):
results = []
for article_candidate in list_article_candidates:
article_candidate.title = self.do_cleaning(article_candidate.title)
article_candidate.description = self.do_cleaning(article_candidate.description)
article_candida... | Iterates over each article_candidate and cleans every extracted data.
:param list_article_candidates: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A list, the list with the cleaned ArticleCandidate-Objects |
def delete(ctx, componentname):
col = ctx.obj['col']
if col.count({'name': componentname}) > 1:
log('More than one component configuration of this name! Try '
'one of the uuids as argument. Get a list with "config '
'list"')
return
log('Deleting component configuratio... | Delete an existing component configuration. This will trigger
the creation of its default configuration upon next restart. |
def alterar(
self,
id_interface,
nome,
protegida,
descricao,
id_ligacao_front,
id_ligacao_back,
tipo=None,
vlan=None):
if not is_valid_int_param(id_interface):
raise InvalidParameterError(
... | Edit an interface by its identifier.
Equipment identifier is not changed.
:param nome: Interface name.
:param protegida: Indication of protected ('0' or '1').
:param descricao: Interface description.
:param id_ligacao_front: Front end link interface identifier.
:param i... |
def float(cls, name, description=None, unit='', params=None,
default=None, initial_status=None):
return cls(cls.FLOAT, name, description, unit, params,
default, initial_status) | Instantiate a new float sensor object.
Parameters
----------
name : str
The name of the sensor.
description : str
A short description of the sensor.
units : str
The units of the sensor value. May be the empty string
if there are no... |
def norm(x, encoding="latin1"):
"Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular"
if not isinstance(x, basestring):
x = unicode(x)
elif isinstance(x, str):
x = x.decode(encoding, 'ignore')
return unicodedata.normalize('NFKD', x).encode('ASCII', 'ignore') | Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular |
def fetchExternalUpdates(self):
seeds = seeder.fetchDynamicProperties(
self.buildSpec['target'],
self.buildSpec['encoding']
)
for config in self.configs:
config.seedUI(seeds) | !Experimental!
Calls out to the client code requesting seed values to use in the UI
!Experimental! |
def _get_ids_from_hostname(self, hostname):
results = self.list_instances(hostname=hostname, mask="id")
return [result['id'] for result in results] | List VS ids which match the given hostname. |
def request_args(self):
kwargs = {}
kwargs.update(self.request.match_info.items())
kwargs.update(self.request.query.items())
return kwargs | Returns the arguments passed with the request in a dictionary.
Returns both URL resolved arguments and query string arguments. |
def iter_pages_builds(self, number=-1, etag=None):
url = self._build_url('pages', 'builds', base_url=self._api)
return self._iter(int(number), url, PagesBuild, etag=etag) | Iterate over pages builds of this repository.
:returns: generator of :class:`PagesBuild
<github3.repos.pages.PagesBuild>` |
def regret(self):
return (sum(self.pulls)*np.max(np.nan_to_num(self.wins/self.pulls)) -
sum(self.wins)) / sum(self.pulls) | Calculate expected regret, where expected regret is
maximum optimal reward - sum of collected rewards, i.e.
expected regret = T*max_k(mean_k) - sum_(t=1-->T) (reward_t)
Returns
-------
float |
def download(ui, repo, clname, **opts):
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
cl, vers, patch, err = DownloadCL(ui, repo, clname)
if err != "":
return err
ui.write(cl.EditorText() + "\n")
ui.write(patch + "\n")
return | download a change from the code review server
Download prints a description of the given change list
followed by its diff, downloaded from the code review server. |
def respond(request, code):
redirect = request.GET.get('next', request.POST.get('next'))
if redirect:
return HttpResponseRedirect(redirect)
return type('Response%d' % code, (HttpResponse, ), {'status_code': code})() | Responds to the request with the given response code.
If ``next`` is in the form, it will redirect instead. |
def write_csv(data, file_name, encoding='utf-8'):
name_extension = len(data) > 1
root, ext = os.path.splitext(file_name)
for i, sheet in enumerate(data):
fname = file_name if not name_extension else root+"_"+str(i)+ext
with open(fname, 'wb') as date_file:
csv_file = csv.writer(da... | Writes out to csv format.
Args:
data: 2D list of tables/worksheets.
file_name: Name of the output file. |
def update(self, obj_id, is_public=NotUpdated, is_protected=NotUpdated):
data = {}
self._copy_if_updated(data, is_public=is_public,
is_protected=is_protected)
return self._patch('/job-executions/%s' % obj_id, data) | Update a Job Execution. |
def get_attribute_option(self, attribute, option_name):
self.__validate_attribute_option_name(option_name)
attribute_key = self.__make_key(attribute)
return self.__attribute_options[attribute_key].get(option_name) | Returns the value of the given attribute option for the specified
attribute. |
def write_file(self, filename, distance=6, velocity=8, charge=3):
with open(filename, "w") as f:
f.write(self.get_string(distance=distance, velocity=velocity,
charge=charge)) | Writes LammpsData to file.
Args:
filename (str): Filename.
distance (int): No. of significant figures to output for
box settings (bounds and tilt) and atomic coordinates.
Default to 6.
velocity (int): No. of significant figures to output for
... |
def write(self, text):
'Uses curses to print in the fanciest way possible.'
if not self.no_color:
text = self.colorize_text(text)
else:
pattern = re.compile('\<\<[A-Z]*?\>\>')
text = pattern.sub('', text)
text += '\n'
self.buffer.write(text)
... | Uses curses to print in the fanciest way possible. |
def _jws_header(keyid, algorithm):
data = {
'typ': 'JWT',
'alg': algorithm.name,
'kid': keyid
}
datajson = json.dumps(data, sort_keys=True).encode('utf8')
return base64url_encode(datajson) | Produce a base64-encoded JWS header. |
def _parse_reassign_label(cls, args):
argparser = ArgumentParser(prog="cluster reassign_label")
argparser.add_argument("destination_cluster",
metavar="destination_cluster_id_label",
help="id/label of the cluster to move the label to")
argparser.add_argument("label... | Parse command line arguments for reassigning label. |
def get_summary_page_link(ifo, utc_time):
search_form = search_form_string
data = {'H1': data_h1_string, 'L1': data_l1_string}
if ifo not in data:
return ifo
else:
alog_utc = '%02d-%02d-%4d' % (utc_time[2], utc_time[1], utc_time[0])
ext = '%4d%02d%02d' % (utc_time[0], utc_time[1]... | Return a string that links to the summary page and aLOG for this ifo
Parameters
----------
ifo : string
The detector name
utc_time : sequence
First three elements must be strings giving year, month, day resp.
Returns
-------
return_string : string
String containing ... |
def postorder(self, skip_seed=False):
for node in self._tree.postorder_node_iter():
if skip_seed and node is self._tree.seed_node:
continue
yield node | Return a generator that yields the nodes of the tree in postorder.
If skip_seed=True then the root node is not included. |
def inserir(self, name):
brand_map = dict()
brand_map['name'] = name
code, xml = self.submit({'brand': brand_map}, 'POST', 'brand/')
return self.response(code, xml) | Inserts a new Brand and returns its identifier
:param name: Brand name. String with a minimum 3 and maximum of 100 characters
:return: Dictionary with the following structure:
::
{'marca': {'id': < id_brand >}}
:raise InvalidParameterError: Name is null and invalid.
... |
def make_retrigger_request(repo_name, request_id, auth, count=DEFAULT_COUNT_NUM,
priority=DEFAULT_PRIORITY, dry_run=True):
url = '{}/{}/request'.format(SELF_SERVE, repo_name)
payload = {'request_id': request_id}
if count != DEFAULT_COUNT_NUM or priority != DEFAULT_PRIORITY:
... | Retrigger a request using buildapi self-serve. Returns a request.
Buildapi documentation:
POST /self-serve/{branch}/request
Rebuild `request_id`, which must be passed in as a POST parameter.
`priority` and `count` are also accepted as optional
parameters. `count` defaults to 1, and represents the ... |
def do_hdr(self, line, hdrs_usr):
if self.hdr_ex is None:
self._init_hdr(line, hdrs_usr)
return True
elif self.hdr_ex in line:
self._init_hdr(line, hdrs_usr)
return True
return False | Initialize self.h2i. |
def trim(self):
for key, value in list(iteritems(self.counters)):
if value.empty():
del self.counters[key] | Clear not used counters |
def _onClassAttribute(self, name, line, pos, absPosition, level):
attributes = self.objectsStack[level].classAttributes
for item in attributes:
if item.name == name:
return
attributes.append(ClassAttribute(name, line, pos, absPosition)) | Memorizes a class attribute |
def make_filter(self, fieldname, query_func, expct_value):
def actual_filter(item):
value = getattr(item, fieldname)
if query_func in NULL_AFFECTED_FILTERS and value is None:
return False
if query_func == 'eq':
return value == expct_value
... | makes a filter that will be appliead to an object's property based
on query_func |
def create_assignment_group(self, course_id, group_weight=None, integration_data=None, name=None, position=None, rules=None, sis_source_id=None):
path = {}
data = {}
params = {}
path["course_id"] = course_id
if name is not None:
data["name"] = name
if p... | Create an Assignment Group.
Create a new assignment group for this course. |
async def unpack(self, ciphertext: bytes) -> (str, str, str):
LOGGER.debug('Wallet.unpack >>> ciphertext: %s', ciphertext)
if not ciphertext:
LOGGER.debug('Wallet.pack <!< No ciphertext to unpack')
raise AbsentMessage('No ciphertext to unpack')
try:
unpacked =... | Unpack a message. Return triple with cleartext, sender verification key, and recipient verification key.
Raise AbsentMessage for missing ciphertext, or WalletState if wallet is closed. Raise AbsentRecord
if wallet has no key to unpack ciphertext.
:param ciphertext: JWE-like formatted message as... |
def packet_write(self):
bytes_written = 0
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN, bytes_written
while len(self.out_packet) > 0:
pkt = self.out_packet[0]
write_length, status = nyamuk_net.write(self.sock, pkt.payload)
if write_leng... | Write packet to network. |
def eliminate_sequential_children(paths):
"helper for infer_columns. removes paths that are direct children of the n-1 or n-2 path"
return [p for i,p in enumerate(paths) if not ((i>0 and paths[i-1]==p[:-1]) or (i>1 and paths[i-2]==p[:-1]))] | helper for infer_columns. removes paths that are direct children of the n-1 or n-2 path |
def extract_col_name(string):
prefixes = ["presence_pass_", "value_pass_", "type_pass_"]
end = string.rfind("_")
for prefix in prefixes:
if string.startswith(prefix):
return prefix[:-6], string[len(prefix):end]
return string, string | Take a string and split it.
String will be a format like "presence_pass_azimuth",
where "azimuth" is the MagIC column name and "presence_pass"
is the validation.
Return "presence", "azimuth". |
def setattr(self, req, ino, attr, to_set, fi):
self.reply_err(req, errno.EROFS) | Set file attributes
Valid replies:
reply_attr
reply_err |
def from_desmond(cls, path, **kwargs):
dms = DesmondDMSFile(path)
pos = kwargs.pop('positions', dms.getPositions())
return cls(master=dms, topology=dms.getTopology(), positions=pos, path=path,
**kwargs) | Loads a topology from a Desmond DMS file located at `path`.
Arguments
---------
path : str
Path to a Desmond DMS file |
def proc_decorator(req_set):
def decorator(func):
@wraps(func)
def inner(self, *args, **kwargs):
proc = func.__name__.lower()
inner.proc_decorator = kwargs
self.logger.debug("processing proc:{}".format(func.__name__))
self.l... | Decorator that provides the wrapped function with an attribute 'actual_kwargs'
containing just those keyword arguments actually passed in to the function. |
def email_users(users, subject, text_body, html_body=None, sender=None, configuration=None, **kwargs):
if not users:
raise ValueError('No users supplied')
recipients = list()
for user in users:
recipients.append(user.data['email'])
if configuration is None:
... | Email a list of users
Args:
users (List[User]): List of users
subject (str): Email subject
text_body (str): Plain text email body
html_body (str): HTML email body
sender (Optional[str]): Email sender. Defaults to SMTP username.
configurati... |
def has_ops_before(self, ts):
spec = {'ts': {'$lt': ts}}
return bool(self.coll.find_one(spec)) | Determine if there are any ops before ts |
def get_font(self, font):
font = {'a': 0, 'b': 1}.get(font, font)
if not six.text_type(font) in self.fonts:
raise NotSupported(
'"{}" is not a valid font in the current profile'.format(font))
return font | Return the escpos index for `font`. Makes sure that
the requested `font` is valid. |
def add(x, y, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_add,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) | Return ``x`` + ``y``. |
def save(self, heads, console=True):
self._save_junit()
self._save_html_report(heads)
if console:
self._print_console_summary() | Create reports in different formats.
:param heads: html table extra values in title rows
:param console: Boolean, default is True. If set, also print out the console log. |
def has_value_of_type(self, var_type):
if self.has_value() and self.has_type(var_type):
return True
return False | Does the variable both have the given type and
have a variable value we can use? |
def call(self, method, *args, **kw):
if args and kw:
raise ValueError("JSON-RPC method calls allow only either named or positional arguments.")
if not method:
raise ValueError("JSON-RPC method call requires a method name.")
request = self._data_serializer.assemble_request... | In context of a batch we return the request's ID
else we return the actual json |
def naive_grouped_rowwise_apply(data,
group_labels,
func,
func_args=(),
out=None):
if out is None:
out = np.empty_like(data)
for (row, label_row, out_row) in zip(data, group_la... | Simple implementation of grouped row-wise function application.
Parameters
----------
data : ndarray[ndim=2]
Input array over which to apply a grouped function.
group_labels : ndarray[ndim=2, dtype=int64]
Labels to use to bucket inputs from array.
Should be the same shape as arr... |
def create_key(self, master_secret=b""):
master_secret = deserialize.bytes_str(master_secret)
bip32node = control.create_wallet(self.testnet,
master_secret=master_secret)
return bip32node.wif() | Create new private key and return in wif format.
@param: master_secret Create from master secret, otherwise random. |
def extract_forward_and_reverse_complement(
self, forward_reads_to_extract, reverse_reads_to_extract, database_fasta_file,
output_file):
self.extract(forward_reads_to_extract, database_fasta_file, output_file)
cmd_rev = "fxtract -XH -f /dev/stdin '%s'" % database_fasta_file
... | As per extract except also reverse complement the sequences. |
def _from_dict(cls, _dict):
args = {}
if 'name' in _dict:
args['name'] = _dict.get('name')
else:
raise ValueError(
'Required property \'name\' not present in ClassifierResult JSON'
)
if 'classifier_id' in _dict:
args['classi... | Initialize a ClassifierResult object from a json dictionary. |
def conditional_probability_alive(self, frequency, recency, T):
r, alpha, a, b = self._unload_params("r", "alpha", "a", "b")
log_div = (r + frequency) * np.log((alpha + T) / (alpha + recency)) + np.log(
a / (b + np.maximum(frequency, 1) - 1)
)
return np.atleast_1d(np.where(fr... | Compute conditional probability alive.
Compute the probability that a customer with history
(frequency, recency, T) is currently alive.
From http://www.brucehardie.com/notes/021/palive_for_BGNBD.pdf
Parameters
----------
frequency: array or scalar
historica... |
def get_curl_command_line(self, method, url, **kwargs):
if kwargs.get("query"):
url = "{}?{}".format(url, d1_common.url.urlencode(kwargs["query"]))
curl_list = ["curl"]
if method.lower() == "head":
curl_list.append("--head")
else:
curl_list.append("-X ... | Get request as cURL command line for debugging. |
def percent_pareto_interactions(records, percentage=0.8):
if len(records) == 0:
return None
user_count = Counter(r.correspondent_id for r in records)
target = int(math.ceil(sum(user_count.values()) * percentage))
user_sort = sorted(user_count.keys(), key=lambda x: user_count[x])
while target... | The percentage of user's contacts that account for 80% of its interactions. |
def _create_rubber_bands_action(self):
icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg')
self.action_toggle_rubberbands = QAction(
QIcon(icon),
self.tr('Toggle Scenario Outlines'), self.iface.mainWindow())
message = self.tr('Toggle rubber bands showing scen... | Create action for toggling rubber bands. |
def render_value_for_node(node_id):
value = None
result = []
try:
result = db.execute(text(fetch_query_string('select_node_from_id.sql')), node_id=node_id).fetchall()
except DatabaseError as err:
current_app.logger.error("DatabaseError: %s", err)
if result:
kw = dict(zip(resu... | Wrap render_node for usage in operate scripts. Returns without template
rendered. |
def hardware_version(self):
res = self.rpc(0x00, 0x02, result_type=(0, True))
binary_version = res['buffer']
ver = ""
for x in binary_version:
if x != 0:
ver += chr(x)
return ver | Return the embedded hardware version string for this tile.
The hardware version is an up to 10 byte user readable string that is
meant to encode any necessary information about the specific hardware
that this tile is running on. For example, if you have multiple
assembly variants of a ... |
def _calcidxs(func):
timegrids = hydpy.pub.get('timegrids')
if timegrids is None:
raise RuntimeError(
'An Indexer object has been asked for an %s array. Such an '
'array has neither been determined yet nor can it be '
'determined automatically... | Return the required indexes based on the given lambda function
and the |Timegrids| object handled by module |pub|. Raise a
|RuntimeError| if the latter is not available. |
def verbose(self):
enabled = self.lib.iperf_get_verbose(self._test)
if enabled:
self._verbose = True
else:
self._verbose = False
return self._verbose | Toggles verbose output for the iperf3 instance
:rtype: bool |
def score_n1(matrix, matrix_size):
score = 0
for i in range(matrix_size):
prev_bit_row, prev_bit_col = -1, -1
row_counter, col_counter = 0, 0
for j in range(matrix_size):
bit = matrix[i][j]
if bit == prev_bit_row:
row_counter += 1
else:... | \
Implements the penalty score feature 1.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
============================================ ======================== ======
Feature Evaluation condition Points
=====... |
def _jitter(c, magnitude:uniform):
"Replace pixels by random neighbors at `magnitude`."
c.flow.add_((torch.rand_like(c.flow)-0.5)*magnitude*2)
return c | Replace pixels by random neighbors at `magnitude`. |
def _create_user(self, email, password, is_superuser, **extra_fields):
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(
email=email,
password=password,
... | Create new user |
def get_appliance_event_after_time(self, location_id, since, per_page=None, page=None, min_power=None):
url = "https://api.neur.io/v1/appliances/events"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = {
"locationId": location_id,
"since": since
}
... | Get appliance events by location Id after defined time.
Args:
location_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
since (string): ISO 8601 start time for getting the events that are created or updated after it.
Maxiumim value allowe... |
def get_term(self,term_id):
if term_id in self.idx:
return Cterm(self.idx[term_id],self.type)
else:
return None | Returns the term object for the supplied identifier
@type term_id: string
@param term_id: term identifier |
def remove_prohibited_element(tag_name, document_element):
elements = document_element.getElementsByTagName(tag_name)
for element in elements:
p = element.parentNode
p.removeChild(element) | To fit the Evernote DTD need, drop this tag name |
def Process(
self, parser_mediator, cache=None, database=None, **unused_kwargs):
if cache is None:
raise ValueError('Missing cache value.')
if database is None:
raise ValueError('Missing database value.')
super(SQLitePlugin, self).Process(parser_mediator)
for query, callback_method in ... | Determine if this is the right plugin for this database.
This function takes a SQLiteDatabase object and compares the list
of required tables against the available tables in the database.
If all the tables defined in REQUIRED_TABLES are present in the
database then this plugin is considered to be the c... |
def initialize_from_bucket(self):
tmp_dir = tempfile.mkdtemp("tfds")
data_files = gcs_utils.gcs_dataset_info_files(self.full_name)
if not data_files:
return
logging.info("Loading info from GCS for %s", self.full_name)
for fname in data_files:
out_fname = os.path.join(tmp_dir, os.path.bas... | Initialize DatasetInfo from GCS bucket info files. |
def _handle_response(response):
if not str(response.status_code).startswith('2'):
raise KucoinAPIException(response)
try:
res = response.json()
if 'code' in res and res['code'] != "200000":
raise KucoinAPIException(response)
if 'success' in... | Internal helper for handling API responses from the Quoine server.
Raises the appropriate exceptions when necessary; otherwise, returns the
response. |
def reset(self):
self.indchar = None
self.comments = {}
self.refs = []
self.set_skips([])
self.docstring = ""
self.ichain_count = 0
self.tre_store_count = 0
self.case_check_count = 0
self.stmt_lambdas = []
if self.strict:
self.u... | Resets references. |
def heptad_register(self):
base_reg = 'abcdefg'
exp_base = base_reg * (self.cc_len//7+2)
ave_ca_layers = self.calc_average_parameters(self.ca_layers)[0][:-1]
reg_fit = fit_heptad_register(ave_ca_layers)
hep_pos = reg_fit[0][0]
return exp_base[hep_pos:hep_pos+self.cc_len],... | Returns the calculated register of the coiled coil and the fit quality. |
def set_exception(self, exception):
was_handled = self._finish(self.errbacks, exception)
if not was_handled:
traceback.print_exception(
type(exception), exception, exception.__traceback__) | Signal unsuccessful completion. |
def save_veto_definer(cp, out_dir, tags=None):
if tags is None:
tags = []
make_analysis_dir(out_dir)
veto_def_url = cp.get_opt_tags("workflow-segments",
"segments-veto-definer-url", tags)
veto_def_base_name = os.path.basename(veto_def_url)
veto_def_new_path =... | Retrieve the veto definer file and save it locally
Parameters
-----------
cp : ConfigParser instance
out_dir : path
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options. |
def print_label(self, package_num=None):
if package_num:
packages = [
self.shipment.response.CompletedShipmentDetail.CompletedPackageDetails[package_num]
]
else:
packages = self.shipment.response.CompletedShipmentDetail.CompletedPackageDetails
... | Prints all of a shipment's labels, or optionally just one.
@type package_num: L{int}
@param package_num: 0-based index of the package to print. This is
only useful for shipments with more than one package. |
def execute_cross_join(op, left, right, **kwargs):
key = "cross_join_{}".format(ibis.util.guid())
join_key = {key: True}
new_left = left.assign(**join_key)
new_right = right.assign(**join_key)
result = pd.merge(
new_left,
new_right,
how='inner',
on=key,
copy=F... | Execute a cross join in pandas.
Notes
-----
We create a dummy column of all :data:`True` instances and use that as the
join key. This results in the desired Cartesian product behavior guaranteed
by cross join. |
def charge_transfer_to_string(self):
ch = self.charge_transfer
chts = ['\nCharge Transfer\n\nabsorbing atom']
for i in range(len(ch)):
for atom, v2 in ch[str(i)].items():
a = ['\n', atom, '\n', 's ', str(v2['s']), '\n',
'p ', str(v2['p']), '\n... | returns shrage transfer as string |
def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs):
if grouper is None:
self._set_binner()
grouper = self.grouper
obj = self._selected_obj
grouped = groupby(obj, by=None, grouper=grouper, axis=self.axis)
try:
if isinstance(obj, ABCDat... | Re-evaluate the obj with a groupby aggregation. |
def prog(text):
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor.prog = text
return func
return decorator | Decorator used to specify the program name for the console script
help message.
:param text: The text to use for the program name. |
def get_relationships_for_idents(self, cid, idents):
keys = [(cid, ident,) for ident in idents]
key_ranges = zip(keys, keys)
mapping = {}
for k, v in self.kvl.scan(self.TABLE, *key_ranges):
label = self._label_from_kvlayer(k, v)
ident = label.other(cid)
... | Get relationships between ``idents`` and a ``cid``.
Returns a dictionary mapping the identifiers in ``idents``
to either None, if no relationship label is found between
the identifier and ``cid``, or a RelationshipType classifying
the strength of the relationship between the identifier ... |
def compose_item_handle(tokens):
if len(tokens) < 1:
raise CoconutInternalException("invalid function composition tokens", tokens)
elif len(tokens) == 1:
return tokens[0]
else:
return "_coconut_forward_compose(" + ", ".join(reversed(tokens)) + ")" | Process function composition. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.