content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from IPython import get_ipython
import os
def in_notebook():
"""Simple checker function to see if we're currently in a notebook."""
if os.environ.get('MPLBACKEND', None) is not None:
return True
try:
try:
if 'IPKernelApp' not in get_ipython().config:
return Fal... | 260552ef1ca3c167f33a40a9770eb2eaa50ab704 | 62,000 |
def build_timeline(entries):
"""
Marks notes as evidence in the timeline
:param entries: notes from the incident
:return: Results
"""
results = {}
# Parse each comment for file names
filename_to_occurred = {}
for note in entries:
occurred = get_occurred(note)
for fi... | 0870c8a20cb024308f63d2e35826daecfae80144 | 62,001 |
import re
def get_clarifications_copa(ex, nlp, comet_model):
"""
Generate clarifications for the COPA dataset
:param ex: a dictionary with the COPA instance
:param nlp: Spacy NLP
:param comet_model: the COMET model objects
:return: a list of (question, answer) tuples
"""
category_to_pr... | cc145eeccb5b57e883d49c8977b3a8080673c779 | 62,002 |
import requests
def bond_china_close_return(
symbol: str = "政策性金融债(进出口行)",
period: str = "1",
start_date: str = "20210621",
end_date: str = "20210721",
) -> pd.DataFrame:
"""
收盘收益率曲线历史数据
http://www.chinamoney.com.cn/chinese/bkcurvclosedyhis/?bondType=CYCC000&reference=1
:param symbol: ... | dd0f2398b770437866500e5defcb11218d6c5515 | 62,003 |
from typing import Union
from typing import Tuple
from pathlib import Path
import requests
def load_data() -> Union[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]:
"""Download, extract & Load uci har smartphone dataset.
The value will be split into train and test by :meth:`train_test_split`. U... | 948dfca8a6b64baaabad1d22780588ab07f8d7b4 | 62,004 |
from typing import List
import logging
def get_config_parameter_multiline(config: ConfigParser,
section: str,
param: str,
default: List[str],
loglevel: int = logging.DEBUG) -> Li... | bcd9dfcb1895bbeac252f758a3005564a369b09c | 62,005 |
def load_data(validation=False):
"""
Input data for PSSM top model
"""
if validation:
clinvar_path = 'data/clinvar/clinvar_val.tsv'
else:
clinvar_path = 'data/clinvar/clinvar_train.tsv'
clinvar = pd.read_csv(clinvar_path, sep="\t")
pn_path = 'data/proteinnet/casp12/clinvar'
... | da55983125a2056e9d9559046b4e7a6dbbb07b80 | 62,006 |
def data_from_dataframe(dataframe):
"""Convert a dataframe object to a list of dictionaries
:param fp: File pointer object
:return: tuple of table headers and data
"""
fields = dataframe.keys()
header = header_population(fields)
data = [data.to_dict() for _, data in dataframe.iterrows()]
... | b200161a1f9612c5ffd340e3949584642e7db26f | 62,007 |
import json
def fetch_objects(url):
""" Fetches the object information before download """
response = urlopen(url)
html = response.read()
objects = json.loads(html)
return objects["objects"] | c5e042fcebde62856963a67f307f30dac862c586 | 62,008 |
def add_movie(request):
"""
Create new movie with multiple locations and multiple timings
"""
try:
jsonBody = json.loads(request.body)
for key, value in jsonBody.iteritems():
if not value:
raise CustomApiException('Please provide '+ key, status.HTTP_400_BAD_REQUEST)
for each_location in jsonBody['l... | 2cd68bc83d78d213497706bf0760e7e3cb8e90f3 | 62,009 |
def coprocess(func, args=(), logfile=None, env=None, callback=None,
async=False):
"""Works like fork(), but connects the childs stdio to a pty. Returns a
file-like object connected to the master end of the child pty.
"""
pm = get_procmanager()
cp = pm.coprocess(func, args, logfile, env... | 48dc8745ce4825237cb180f6749529924490ecc6 | 62,010 |
def get_track_terms(track_fn):
"""Returns list of track terms"""
with open(track_fn, 'rb') as fin:
terms = fin.readlines()
terms = filter(None, [term.strip().lower().translate(None, ' ') for term in terms])
# remove duplicates
terms = list(set(terms))
return terms | 7a5370bf326aa220a44c4f03f9748ed26b4a2710 | 62,011 |
def urls_cidades(request, format=None):
"""
URLs de cidades disponíveis para acesso.
Formato da URL: /api/ongs/{estado}/{cidade}/
"""
return Response(utils.get_urls_cidades(request=request, format=format)) | 12cf210032a6285130e1e0328cbf639da049bc13 | 62,012 |
def compute_distribution_clusters_parallel(columns: list,
threshold: float,
pool: Pool,
tmp_folder_path: str,
quantiles: int = 256):
"""
Alg... | be0721132718a4bb7318f23675b6e417189736c5 | 62,013 |
def fixbackslash(value):
"""Replace backslashes '\' in encoded polylines for Google Maps overlay."""
return value.replace('\\','\\\\') | 20a1e6132c379049e949f50e413c66cf5e67e7dc | 62,014 |
def _filter_tuples(diced_str, to_remove):
"""
Returns *diced_str* with all of the tuples containing any elements of the
*to_remove* iterable filtered out. This is used to drop search terms from
the diced_str once they've been matched. For example:
# start with the output of the _dice doctest
>>... | 625ca421e3b1ec3dd9f5187fe994ee095eff8d30 | 62,015 |
def generate(props, count=50, filename=None, randomstate=np.random):
"""
LEGACY generate function, please use generate_from_model, if a
filename is specified used a MarkovMode.
"""
# Legacy, if a filename was specified it used to mean a MarkovModel
if filename:
return generate_from_mode... | 3149277b32efb6f9a24cb9d37a037f12d3a50026 | 62,016 |
import socket
def get_ipmi_address(node):
"""Get the BMC address defined in node.driver_info dictionary
Possible names of BMC address value examined in order of list
['ipmi_address'] + CONF.ipmi_address_fields. The value could
be an IP address or a hostname. DNS lookup performed for the
first non... | 57176678b7580ef8e46d76cfc43b88eeb01b4892 | 62,017 |
def _exists(name: str):
"""
Checks if a docker instance exists.
:param name: Instance name.
:returns: True if exists. False otherwise.
"""
cs = client.containers.list(filters={'name': name}, all=True)
return len(cs) > 0 | 0ec261e3510ddff603ef250bf5b5c5430a52d2f7 | 62,018 |
def op_lag_fire(
dataset,
model,
split_ratio,
lag_range=[
2,
168],
step_range=[
1,
25],
wind_range: list = [
0.5,
20],
shift_range: list = [
-72,
72],
roll_range: list = [
24,
240],damp_surface='s... | 0ee06c1f8d1bc30e9d5d81fd24ca6eca51dca35c | 62,019 |
import math
def all_frequency_based_dissim_for_modes(mode, metamodes):
"""
My own frequency-based dissimilarity function for clustering of modes
"""
list_dissim = []
# mode.freq[i] is a set of frequencies for all values of attribute i in the original cluster of this mode
# metamode.freq[i]
... | fc113cf8fc5ff8d35a4d66c8f26790fbae50c5c6 | 62,020 |
def get_spc_run_path(run_prefix, spc_info):
""" create species run path
"""
spc_run_fs = autofile.fs.species(run_prefix)
spc_run_fs.leaf.create(spc_info)
spc_run_path = spc_run_fs.leaf.path(spc_info)
return spc_run_path | 7d17575c30a02a56758d7fbeb89a040468ca2e58 | 62,021 |
def print_xm_info(xm_dict, name_re):
"""Print a dictionary of xmethods."""
def get_status_string(m):
if not m.enabled:
return " [disabled]"
else:
return ""
if not xm_dict:
return
for locus_str in xm_dict:
if not xm_dict[locus_str]:
conti... | e2564a5fcb7dc435c3ba1fa71fe82532d2b5083e | 62,022 |
def format_multitask_preds(preds):
"""
Input format: list of dicts (one per task, named with task_name), each having a
'predictions' list containing dictionaries that represent predictions for each sample.
Prediction score is represented by the field {task_name}_score in each of those dicts.
... | 470b23f6a5cc6b8e48ce0becfafd62104e016de8 | 62,023 |
def filter_queryset_metadata_dimension_time(queryset, time_min: str, time_max: str):
""" Filters a given REST framework queryset by a time_min and time_max boundary.
Only keeps the element which can be found in this temporal span.
Args:
queryset: A queryset containing elements
time_min (st... | f76dff18985e5664cbf6a3e7798fec8ec1dcd991 | 62,024 |
def CDLENGULFING(df):
"""
函数名:CDLENGULFING
名称:Engulfing Pattern 吞噬模式
简介:两日K线模式,分多头吞噬和空头吞噬,以多头吞噬为例,第一日为阴线,第二日阳线,第一日的开盘价和收盘价在第二日开盘价收盘价之内,但不能完全相同。
python API
integer=CDLENGULFING(open, high, low, close)
:return:
"""
open = df['open']
high = df['high']
low = df['low']
close... | 425bff3b4f22955be62d1cdbaf625af87d6c5f1f | 62,025 |
def bot():
"""Respond with the output of the webhook handler."""
payload = request.form['payload']
signature = request.headers['SIGNATURE']
return webhook_handler(payload, signature) | 77c78d2c20821532096cc6a0bb3f4d54f11a3840 | 62,026 |
def msp(items):
"""Yield the permutations of `items`
items is either a list of integers representing the actual items or a list of hashable items.
The output are the unique permutations of the items.
Parameters
----------
items : sequence
Yields
-------
list
permutation of... | a91f2b80997b73cf7dbcbec88a923f855e117c26 | 62,027 |
def get_emissions(scenario_id, emission_dir=None, exclude_emissions=EXCLUDE_EMISSION):
"""Gets an emission file
Parameters:
----------
* scenario_id
* emission_dir
* exclude_emissions
Return:
------
* df pandas.DataFrame
Updates:
-------
* 2019-11-29:Add Column Filter ... | c3f4791b3e0bd97c7e24af0703fc3d370aa1b7e2 | 62,028 |
def createMatrixData(matrix):
"""
Converts the given matrix to an MObject.
:type matrix: om.MMatrix
:rtype: om.MObject
"""
# Check for redundancy
#
if isinstance(matrix, om.MObject):
return matrix
# Create new matrix data object
#
fnMatrixData = om.MFnMatrixData()... | dbc73059cb99459d2d579e79953e172e306bdebe | 62,029 |
import os
def credentials(*args, **kwargs):
"""Override default credentials with contents of .ssh/config,
Only done if credentials are properly defined
"""
if env.ssh_config:
credentials = env.ssh_config.lookup(env.host)
# translate from ssh params to fabric params
if 'identit... | 100ec4cd558ec211d450def820b2cc5d158403c5 | 62,030 |
def _NormalizeGitPath(path):
"""Given a |path| in a GIT repository (relative to its root), normalizes it so
it will match only that exact path in a sparse checkout.
"""
path = path.strip()
if not path.startswith('/'):
path = '/' + path
if not path.endswith('/'):
path += '/'
return path | f2781ac304d4c15e835fa174d4aa816ea920045f | 62,031 |
def calculate_rhs(flcond, normals):
"""
Calculate the RHS vector.
Parameters
----------
flcond : FlightConditions
Definition of the flight conditions.
normals : np.ndarray, shape (m, n, 3)
Array containing the normal vectors of all wing panels.
Returns
-------
rhs :... | 38fb90e42cb54f14b1c9f2fe1c397d3a68e7226f | 62,032 |
def send(to: str, subject: str, body: str):
"""Sends email
"""
from_email = Email(SENDER_EMAIL)
to_email = To(to)
content = Content("text/plain", body)
mail = Mail(from_email, to_email, subject, content)
response = sg.client.mail.send.post(request_body=mail.get())
return response | 100e6ed40c3b863e280c2259ef24d1033060e54f | 62,033 |
def broadcasted_matmul(A, B):
""" Matmul with fast broadcasting
Args:
A - [n, m]
B - [..., m, k]
Returns:
AB - [..., n, k]
"""
# [n, batch_size, k]
AB = tf.tensordot(A, B, axes=[[-1], [-2]])
# [batch_size, n, k]
rankAB = tf.rank(AB)
return tf.transpose(AB, perm=tf... | 75995f0f681dff203b7ce80dd9d8b03be8af3601 | 62,034 |
def is_scope_owner(scope, account, session=None):
""" check to see if account owns the scope.
:param scope: the scope to check.
:param account: the account to check.
:param session: The database session in use.
:returns: True or false
"""
return True if session.query(models.Scope).filter_b... | 5c7194e8f79bcc959c29b318916234f3d11a4fe9 | 62,035 |
def unpack(t, n):
"""Iterates over a promised sequence, the sequence should support random
access by :meth:`object.__getitem__`. Also the length of the sequence
should be known beforehand.
:param t: a sequence.
:param n: the length of the sequence.
:return: an unpackable generator for the eleme... | 4601cc51b2ae1015a31e8dc525756d8f590c2d8b | 62,036 |
def get_latest_post():
""" Laziness function to return the latest post. """
post_record = app.config['MDB'].posts.find_one(
{'published': True, 'published_on': {'$exists': True}},
sort=[('published_on', -1)]
)
return Post(_id=post_record['_id']) | 8053efa33491e93c1c1c07b736de66f5e21dbbe6 | 62,037 |
import re
def parse_value(expr):
"""Parse text into Python expression.
Args:
expr: String to be converted to Python expression (e.g. a list).
Returns:
Parsed Python expression.
"""
try:
return eval(expr)
except:
return eval(re.sub(r"\s+", ",", expr))
else... | f033e35b77bb3839dc6ccc05e1f96898a1a93c0c | 62,038 |
from typing import List
def pkg_asset_download_urls(url) -> List[str]:
"""
Example URL for release assets:
tarball: https://github.com/ICGC-TCGA-PanCancer/awesome-wfpkgs2/releases/download/fastqc-wf.0.2.0/fastqc-wf.0.2.0.tar.gz
json: https://github.com/ICGC-TCGA-PanCancer/awesome-wfpkgs2/release... | 2e66629efa07c00473f8bfb86f2db816211d24ed | 62,039 |
from colorednoise import powerlaw_psd_gaussian
def create_synthetic_noise_dataset(cfg):
"""
Creates a NoiseDataset instance of sounds with synthetic noise.
"""
betas = np.linspace(cfg['data.mix_synthetic_noise.min_beta'],
cfg['data.mix_synthetic_noise.max_beta'],
... | 5ff012efec4fb203ac74efd54c0a92cfc042c8c5 | 62,040 |
def _grid_out_property(field_name, docstring):
"""Create a GridOut property."""
def getter(self):
self._ensure_file()
# Protect against PHP-237
if field_name == 'length':
return self._file.get(field_name, 0)
return self._file.get(field_name, None)
docstring += "... | 71bb15738528142d4e410811ba021884ed5bb5ef | 62,041 |
import json
def loads_enumerated_strategy(s):
"""Return `networkx.DiGraph` for strategy in `s`.
@type s: JSON `str`
"""
dout = json.loads(s)
g = nx.DiGraph()
dvars = dout['variables']
for stru, d in dout['nodes'].iteritems():
u = int(stru)
state = dict(zip(dvars, d['state'... | 3ca32ca5a38c6e8810506b15555ffaca77b9b69f | 62,042 |
def _get_db_subnet_group_arn(region: str, current_aws_account_id: str, db_subnet_group_name: str) -> str:
"""
Return an ARN for the DB subnet group name by concatenating the account name and region.
This is done to avoid another AWS API call since the describe_db_instances boto call does not return the DB s... | 4e04501adf0d006f6915f84b36a1c592879c54de | 62,043 |
import base64
def inchi2svg(inchi):
"""
Converts InChI to SVG vector graphic. This method accepts urlsafe_base64 encoded string containing single or
multiple InChIs. Size is the optional size of image in pixels (default value is 200 px).
Legend is optional label in the bottom of image.
cURL examples:
curl -X... | d0e7be785a3993cc238bef848d57998973b0f66a | 62,044 |
def create_stack_list(input_list):
"""
:param input_list: list (of page visits), duplicates are possible
:return: stack list: loops have been removed, consecutive duplicates also have been removed
"""
# print('#################')
# print(input_list)
stack_list = []
list_of_backward_jump... | d82d4b3825d2d034eb4aad4c39f8c0876fb82c86 | 62,045 |
from array import array
def getSimFeaturesFromFvals(fvals1, fvals2, meths):
"""Returns similarity features computed from the features for two objects.
'meths' is a list of (meth, weight), where meth is one of the following
methods for combining values 'a' and 'b' from the two input feature vectors:
... | 240a35aa2c14e6740ab7bfae6909ebeffa290520 | 62,046 |
from typing import Optional
import functools
def build_training_process(
model_fn: ModelFn,
*, # Callers pass below args by name.
loss_fn: LossFn,
metrics_fn: Optional[MetricsFn] = None,
server_optimizer_fn: OptimizerFn = functools.partial(
tf.keras.optimizers.SGD, 1.0),
client_optimi... | 3d34414b701796a80bde8a988098968a5205ade6 | 62,047 |
def get_system_uptime(device):
"""Return system uptime
Args:
device (obj): Device object
Returns:
str: Returns system uptime in seconds
"""
try:
out = device.parse('show system uptime')
except SchemaEmptyParserError:
return None
seconds = out.get('system-... | e5e2c58d9c28c94d437383ab38f501cccbd8c259 | 62,048 |
import os
import json
def init_config(config, save=True):
"""
Extract all config params (CAPITAL letters) from global or local namespace
save a serializable version to disk
make sure all config paths exist
:param config: dictionary, e.g.> locals() or globals() or any manual defined dict
:para... | 1c58cc370ca4f02733fef022345c804ea3427ddd | 62,049 |
def issue_statuses(metric, last_measurement) -> list[dict]:
"""Return the metric's issue statuses."""
last_issue_statuses = last_measurement.get("issue_status", [])
return [status for status in last_issue_statuses if status["issue_id"] in metric.get("issue_ids", [])] | 23d2434727fa1b7a2e06fb621347270efd0627fc | 62,050 |
def TriStrip(p):
"""for backward compatibility only - TriStrip is no longer a type
please use the triStrip() method of the Polygon type instead"""
return p.triStrip() | 6e1f3019acfc1c18deba69d11f3d27ead9d07ca6 | 62,051 |
from cimpyorm.api import load
import os
def load_test_db():
"""
Returns a session and a model for a database that's only supposed to be read from
:return: session, m
"""
path = os.path.join(get_path("DATASETROOT"), "FullGrid", "StaticTest.db")
if not os.path.isfile(path):
pytest.skip("... | b8342f517b97ff8a21021cb180d8ae0304f7d0c6 | 62,052 |
import time
import os
import sys
def run():
"""
Initialize and run the MCMC sampler.
"""
global _loglkwargs
start_time = time.time()
args = parse_args()
config = ConfigParser()
if not os.path.exists(args.config_file):
raise FileNotFoundError(f'No config file found at {args.con... | f8a69a580a17e42d4d6fe83547a7c2063a6ff391 | 62,053 |
def change_value(x):
"""Change tags from number to word."""
value = tags_to_name.get(x)
if value is not None:
return value
return x | 0ad571a8244156439484ffa8b033ebf05302bd15 | 62,054 |
def heroUnit(
headline="",
tagline="",
buttonStyle="primary",
buttonText="",
buttonHref="#"
):
"""
*Generate a heroUnit - TBS style*
**Key Arguments:**
- ``headline`` -- the headline text
- ``tagline`` -- the tagline text for below the headline
... | 42826a5d63023b1a87062205255f80a2c85dd0f6 | 62,055 |
def _get_warmup_factor_at_iter(method: str, iter: int, warmup_iters: int,
warmup_factor: float) -> float:
"""
Return the learning rate warmup factor at a specific iteration.
See :paper:`ImageNet in 1h` for more details.
Args:
method (str): warmup method; either "co... | 5b9798cece3ad3f657dcaddbf795501b187f37de | 62,056 |
def direction_finder(direction, exchange):
"""
Uses the 'src' attribute of an "img" tag to find the
direction of flow. In the data source small arrow images
are used to show flow direction.
"""
if direction == "/uflujpot.nsf/f90.gif":
# flow from Argentina
return 1
elif dire... | 076f80729e34c472a8a12aac15007ed3b2a82eea | 62,057 |
from typing import Optional
from typing import List
def get_tests_action(
file_set_producer: Optional[IFileSetProducer],
commands: Optional[List[str]] = None,
stage_name: Optional[str] = "Tests",
) -> ShellStep:
"""
Return shell script action that runs tests.
Parameters
----------
sco... | 6cea2aeabb59633b10867b1220aec4159be2bd45 | 62,058 |
import os
from src.praxxis.sqlite import sqlite_scene
def get_current_scene_db(scene_root, history_db):
"""calls the function to get the location of the history db"""
scene = sqlite_scene.get_current_scene(history_db)
return os.path.join(scene_root, scene, "%s.db" %(scene)) | 311d40334345d9bf7487bc436a99c4bbfa5bdbbc | 62,059 |
import types
import traceback
import os
import tempfile
from datetime import datetime
def reply_to_ticket(ticket_id, content, user_id=None):
"""Create a structured reply to a ticket.
:param int ticket_id: The ticket to reply to.
:param content: ``str``, ``dict``, or iterator of ``(title, content``) p... | eac8f9d77b38090d88417e71b12c8deae9e02a1d | 62,060 |
def skip_format_url(format_, url):
"""
Checks whether a give format/url should be skipped and not downloaded.
@param format_: Filename format (extension).
@type format_: str (e.g. html, txt, zip, pdf)
@param url: URL.
@type url: str
@return: True if format/url should be skipped, False oth... | 284e086c1f5350370d415cde64557eccfc3eb6e4 | 62,061 |
def brighten(color, brightness):
"""
Adds or subtracts value to a color.
"""
h, s, v = rgb_to_hsv(*map(down_scale, color))
return tuple(map(up_scale, hsv_to_rgb(h, s, v + down_scale(brightness)))) | 5f4b4ca1f17b6bb78e6e47c1e50c6cd433277525 | 62,062 |
import os
def get_es_url() -> str:
"""
拼接 es url
:return:
"""
es_url = os.getenv("ES_URL") # 普通安装升级时从 evnFrom ConfigMap 获取
if es_url == "":
es_url = os.getenv("PIPELINE_ES_URL") # 集成时从流水线变量获取
# 如果获取不到 ES_URL 立即退出
if es_url == "":
print("Quota Migration: can not find E... | 65509c23302405598a94315b63d395407d8e769e | 62,063 |
import copy
def swf(wf: dict, data: dict = {}) -> dict:
"""
Calls the dynamic workflow and returns the result
Params:
- wf: the workflow, based on the serverlessworkflow specification, to be executed
- data: the initial workflow data
"""
return execute_swf(wf=wf, data=copy.deepcopy(data)) | 32d207317079a220d8cc762bfea4c3e04b240486 | 62,064 |
def normalize_tf_graph(graph_output, new_graph=True, verbose=False):
"""Use grappler to normalize a graph.
Arguments
---------
graph_output: Tensor
A tensor we want to consider as "output" of a `FuncGraph`.
Returns
-------
The simplified graph.
"""
train_op = graph_output.gra... | fdc9fb782ecab34bfe0cbf6092b9040a22771441 | 62,065 |
def MvNormalLogp():
"""Compute the log pdf of a multivariate normal distribution.
This should be used in MvNormal.logp once Theano#5908 is released.
Parameters
----------
cov : tt.matrix
The covariance matrix.
delta : tt.matrix
Array of deviations from the mean.
"""
cov... | 4b13a04ec82c7b7b914b0c68b0e4e53365792789 | 62,066 |
def createZero4() -> Mat4:
"""
Create a 4x4 zero matrix
"""
return Mat4() | b670ce4fbd12d39dbb5bf234246b0ab2ab230884 | 62,067 |
def ppfBeta(p, q, r, a, b):
"""Returns the evaluation of the percent point function (inverse cumulative
distribution) evaluated at the probability p for a Beta distribution.
Usage:\n ppfBeta(p, q, r, a, b)"""
width = b-a
return stats.beta.ppf(p, q, r, loc=a, scale=width) | 89a446dc56aba086f1522485b8264c48c3b3d1c8 | 62,068 |
def is_valid_msisdn(msisdn):
"""A very basic msisdn validation check"""
return msisdn[0] == "+" and len(msisdn) == 12 | 5a8865182f0ff21eafcd836e5ccc9497bd097f93 | 62,069 |
def which_fib(lst, n):
"""
Returning the index of n in the sequence lst starting from 1
"""
return lst.index(n) + 1 | 5019442188151a9feb0bccbbcff1b4fcacb3a5c1 | 62,070 |
from typing import Tuple
from typing import Any
def subplots(*args, **kwargs) -> Tuple[Any, Any]:
"""Direct wrapper around |subplots|.
"""
return plt.subplots(*args, **kwargs) | 75ba1f4726e00a8399ae2d8b09a47cb8e00876b8 | 62,071 |
import torch
def get_normalized_adj(A):
"""
Returns a tensor, the degree normalized adjacency matrix.
"""
alpha = 0.8
D = np.array(np.sum(A, axis=1)).reshape((-1,))
D[D <= 10e-5] = 10e-5 # Prevent infs
diag = np.reciprocal(np.sqrt(D))
A_wave = np.multiply(np.multiply(diag.reshape((-... | 6293f1f3550fa93a9eeae57dbf13d00a3f9f8a0a | 62,072 |
def simple_dividers(a):
"""
:param a: число от 1 до 1000
:return: список простых делителей числа
"""
d_list = dividers_list(a)
smpl_div_list = []
l = len(d_list)
for i in range(l):
if is_prime(d_list[i]):
smpl_div_list.append(d_list[i])
return smpl_div_list | fd15382cf63e3be85bf540e3269d767bd12645ae | 62,073 |
def PosOpenBracket(text):
"""Returns the position of the right most open bracket in text.
Brackets inside strings are ignored. In case of no open bracket
the returned value is -1
@param text: The line preceding the new line to be indented.
@return res: The position of right most open bracket.
@n... | 664079f284e18478065a12ef62ed76ad60a4601a | 62,074 |
def get_details(app='groupproject', env='dev', region='us-east-1'):
"""Extract details for Application.
Args:
app (str): Application Name
env (str): Environment/account to get details from
Returns:
collections.namedtuple with _group_, _policy_, _profile_, _role_,
_user_... | 5d358b2e3135b7d9ec7c48f92e3350f3f567f87c | 62,075 |
def add_4_side_contrast_mtr(x):
"""Add the contrast of the 4 sides of each pixel value for each rgb channel.
Thus, for each rgb channel, 4 new channels is created s.t. for pixle (r,c):
1) absolute difference between (r,c) and (r-1,c)
2) absolute difference between (r,c) and (r+1,c)
3) ab... | 4e6c5f51f92f8bd21083eb1297033fdafada5eb7 | 62,076 |
def js_roots(n, p1, q1, mu=False):
"""Gauss-Jacobi (shifted) quadrature
Computes the sample points and weights for Gauss-Jacobi (shifted)
quadrature. The sample points are the roots of the `n`th degree shifted
Jacobi polynomial, :math:`G^{p,q}_n(x)`. These sample points and weights
correctly integ... | 3dc29658311aeeb9a0c6662ad4e3098ee831be37 | 62,077 |
import json
def verify_self_signed_jwks(sjwt):
"""
Verify the signature of a signed JWT containing a JWKS.
The JWT is signed by one of the keys in the JWKS.
In the JWT the JWKS is stored using this format ::
'jwks': {
'keys': [ ]
}
:param sjwt: Signed Jason Web T... | 40c6c72673f01ad26fa8fa92e46705d54d3a820f | 62,078 |
import warnings
def deprecated(func):
"""A decorator used to mark functions as deprecated.
Emit a warning when the decorated function is called.
"""
@wraps(func)
def wrapper(*args, **kwargs):
"""Emit a warning, then call ``func``."""
old_name = func.__name__
if old_name =... | 8d3602a322addd3253323d0cfe0ff839ba0b1b5f | 62,079 |
from re import U
def subtract_background(spec, backp, backm):
# type: (ReflData, ReflData, ReflData) -> (np.ndarray, np.ndarray)
"""
Subtract back+ and back- from spec.
if *offset* is 'auto', guess alignment.
Interpolates background measurements to align with the specular. If a
different in... | 8623dcc8cff5c53049c681e72b95522343f9dee8 | 62,080 |
def forwardscan(session, target, nd_period=None, lead_time=None, **kwargs):
"""Forward scan observation.
Call to `scan` method described in this module
Parameters
----------
session: `CaptureSession`
target: katpoint.Target
nd_period: float
noisediode period
lead_time: float
... | 79c0e75e66986504d3f6b3ae9bc6de3709782a3d | 62,081 |
def floyd_warshall(g):
"""Return new graph - transitive closure of g
"""
closure = deepcopy(g)
vertices = list(closure.vertices())
n = len(verts)
for k in range(n):
for i in range(n):
# does edge (i,k) exist in partial closure?
if i!=k and closure.get_edge(verts[i... | 965ebb596a18ab5f4a84e1388bc091582c999125 | 62,082 |
import re
def rlogv(filename):
"""
Return the head revision of an rcs file
(needed, as rlog -v is a FreeBSD extension)
@type filename: bytes
@rtype: bytes or None
"""
assert isinstance(filename, bytes)
logger.debug("rlogv: looking up revision for %r" % filename)
with open(filename... | 8515379219b638458a571121d5bc8206a6e45d72 | 62,083 |
import torch
def load_learning_policy(
optimizer: torch.optim.Optimizer,
learning_policy_type: str,
**kwargs: "other hyper-parameters for learning scheduler"
) -> "learning policy":
"""
default: (100, 105), 110 epochs suggested
null:
STD: (82, 123), 164 epochs suggested
STD-wrn: (60, 1... | 0f2b13e6b2f4f6322d987a68f7dc6a648c5ea34e | 62,084 |
from os import environ
from . import __version__
import daemonocle
import logging
import sys
def main():
"""
Run the main CLI program.
Initializes the stack, parses command line arguments, and fires requested
logic.
"""
plugins = DefaultPluginManager()
plugins.load_plugins()
parser, ... | 9126b928b082cabaf454e661f871e62747c72167 | 62,085 |
import io
import zipfile
from typing import Dict
import requests
def get_file_content(cb: BaseAPI, file_found_object: Dict, compressed=True):
"""Return the file content as a byte string.
Args:
cb: Carbon Black Cloud API object
file_found_object: Details about the files that were found to
... | 8866ad031d585cf9261d7a6cd91f046685fa0685 | 62,086 |
def view_groups(request, *args, **kwargs):
"""View, add, or delete view groups
:param request:
:param args:
:param kwargs:
:return:
"""
page = Page.objects.get(slug=kwargs['slug']).get_content_model()
if request.method == 'POST':
try:
page.add_view_group(Grou... | e10e785de3ff30a41e146d84fe6cef9e1e2c3ffe | 62,087 |
import requests
def __re_any(subreddit):
"""
Gets the most read entries of the Ask Reddit/TIL/IAmA subreddits from the last 24 hours
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Ask Reddit page
"""
posts = []
base_url = f'https://www.reddit.com/r/... | a1eb7111d5f8af1db337f402de1ec35845b29cd7 | 62,088 |
def decode_oh(onehots, postagstype=None):
"""
Convert one-hot representations to POS tags.
"""
postags = list()
if postagstype is None:
postagstype = PosTagsType()
for onehot in onehots:
if onehot >= postagstype.feature_length:
postags.append('UNKNOWN')
else:
... | 5a28abac7050a622d20c1b931091cea6ef4680ec | 62,089 |
from typing import Union
from typing import Any
import time
def get_token(session_: SessionMixin, scope:Union[str,list[str]]) -> tuple[dict[str, Any], bool]:
"""Check if token is currently valid and returns new token if there is no token or it is expired."""
token_valid = False
token_info = session_.get("... | 8d65761b14308b85e9316f2ebf11f890b0347b75 | 62,090 |
def pack_facet_info_numba(active_facets, c_to_f, f_to_c):
"""
Given a list of external facets get the owning cell and local facet
index
"""
facet_info = np.zeros((len(active_facets), 2), dtype=np.int64)
c_to_f_pos, c_to_f_offs = c_to_f
f_to_c_pos, f_to_c_offs = f_to_c
for j, facet in en... | ef0c1be9d16855323d9e79dcaf90e8811760c79f | 62,091 |
def load_text_validation_min(value):
"""load text_validation_min"""
return value | 777ef7221cd6f0153964fc1fe1d277bc514ed41c | 62,092 |
def build_lines_data(lines) -> bytes:
"""
Builds the byte string from given lines to send to the server
:param lines:
:return bytes:
"""
result = []
for line in lines:
result.append(f"{(len(line) + 5 ):04x}".encode())
result.append(line)
result.append(b"\n")
resul... | f5fd900c606b2e44454bbc15cab61e2b34809fab | 62,093 |
def find_folder_on_path(path, target='.git', **kwargs):
"""
Given a path, find the repo root. The root is considered the top-level
folder containing the '.git' folder. This method will traverse up the
tree, searching each level.
If not `.git` folder is found, None is returned. Otherwise the parent... | 317a061210bca432d128a82a8cc7e27b6aa4feee | 62,094 |
def magnitude(v: Vector) -> float:
"""Returns the magnitude (or length) of v"""
return sqrt(sum_of_squares(v)) | 9dda8c202eaae8cd9b6c848d3e7d3bd454363580 | 62,095 |
def var_order(bdd):
"""Return `dict` that maps each variable to a level.
@rtype: `dict(str: int)`
"""
return {var: bdd.level_of_var(var) for var in bdd.vars} | d9f526be705918bfff43d105750ce97d29e15e52 | 62,096 |
def yes_add_customer_event_form_data():
"""gives valid data for a test"""
return {
"title": "event test",
"description": "a short description",
"event_start": "2022-03-09T10:45",
"event_end": "2022-03-09T10:45",
} | 8601f8a91ef0bc0f3a9c3cd399e11449c1193a9f | 62,097 |
def ignore_headers(headers_to_sign):
"""
Ignore headers.
"""
# Excerpts from @lsegal -
# https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258
#
# User-Agent:
#
# This is ignored from signing because signing this causes problems
# with generating pre-sign... | ccc74d4310df7d5aee510ab846b434d1cc92c6b4 | 62,098 |
def get_camera_serial_and_firmware(console_text):
"""
Scraps console text for serial and firmware information of all connected realsense devices.
Args:
console_text (str): input console text contaning all connected device information
Returns:
Array[dic]: Array item for each connect dev... | 9426522f3815d7e73c12b5081c6308733836528d | 62,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.