content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def new_vk_group(update: Update, context: CallbackContext):
"""Добавляет группу ВК, если включен соответствующий режим."""
with models.session_scope() as session:
chat: models.Chat = session.query(models.Chat).get(update.effective_chat.id)
if chat.state != models.ChatState.VK_CONFIG:
... | 33,900 |
def to_short_site_cname(user, site):
"""
订阅源显示名称,最多 10 个汉字,支持用户自定义名称
"""
if isinstance(site, dict):
site_id = site['id']
site_cname = site['cname']
else:
site_id = site.id
site_cname = site.cname
if user:
cname = get_user_site_cname(user.oauth_id, site_id... | 33,901 |
def load_roed_data(full_output=False):
""" Load master table with all labels """
mtab = load_master_table()
df1 = table.Table.read("roed14_stars.fits").to_pandas()
def renamer(x):
""" match master table Star with Name """
x = x.strip()
if x.startswith("BD") or x.startswith("CD"):... | 33,902 |
def calculate_distance(p1, p2):
"""
Calculate distance between two points
param p1: tuple (x,y) point1
param p2: tuple (x,y) point2
return: distance between two points
"""
x1, y1 = p1
x2, y2 = p2
d = math.sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))
return d | 33,903 |
def get_multi_user_timeline(data: dict) -> None:
"""
:param data: the full output of get_user_timeline, {uid: {table: df}}
"""
uid2name = {u: data[u]['users']["display_name"][0] for u in data}
table_date = {t: d for t, d in zip(table_name, date_str)}
qid = []
qid2t = {}
raw = []
for ... | 33,904 |
def statistics(request, network):
""" some nice statistics for the whole pool """
# some basic statistics
days = 1
current_height, all_blocks, pool_blocks, pool_blocks_percent, bbp_mined = get_basic_statistics(network, days)
miners_count = get_miner_count(network, days)
graph_days ... | 33,905 |
def sim_log(dlevel, env, caller, action, affected):
"""
Parameters
----------
dlevel= int -- debug level
env= simpy.Environment
caller= string -- name of the sim component acting
action= string
affected= any -- whatever component being acted on/with e.g., packet
"""
if DEBUG_LEVEL <= dlevel:
pri... | 33,906 |
def klSigmode(self):
"""查找模式"""
if self.mode == 'deal':
self.canvas.updateSig(self.signalsOpen)
self.mode = 'dealOpen'
else:
self.canvas.updateSig(self.signals)
self.mode = 'deal' | 33,907 |
def save_sig(sig, conf):
"""
save the signature into the database path under user_defined
"""
filename = "{}/{}.pasta".format(conf["config"]["penne_folders"]["user_defined"].format(HOME), random_string())
log.info("saving signature to user defined database under: {}".format(filename))
with open(... | 33,908 |
def package_load_instructions(inst_distributions):
"""Load instructions, displayed in the package notes"""
per_package_inst = ''
for dist in inst_distributions:
if dist.type == 'zip':
per_package_inst += dedent(
"""
# Loading the ZIP Package
... | 33,909 |
def specialize_transform(graph, args):
"""Specialize on provided non-None args.
Parameters that are specialized on are removed.
"""
mng = graph.manager
graph = transformable_clone(graph, relation=f'sp')
mng.add_graph(graph)
for p, arg in zip(graph.parameters, args):
if arg is not No... | 33,910 |
def Multiplication(k):
"""
Generate a function that performs a polynomial multiplication and return coefficients up to degree k
"""
assert isinstance(k, int) and k > 0
def isum(factors):
init = next(factors)
return reduce(operator.iadd, factors, init)
def mul_function(x1, x2):
... | 33,911 |
def safe_divide(a, b):
"""
Avoid divide by zero
http://stackoverflow.com/questions/26248654/numpy-return-0-with-divide-by-zero
"""
with np.errstate(divide='ignore', invalid='ignore'):
c = np.true_divide(a, b)
c[c == np.inf] = 0
c = np.nan_to_num(c)
return c | 33,912 |
def report_and_plot():
"""
Scenario: do some reporting, or fine-tuning of analysis --> finding the right parameters
:return:
"""
analyzer = get_default_tk(context)
analyzer.load_analysis()
analyzer.frames[89].report() | 33,913 |
def plot_lc(data=None, model=None, bands=None, zp=25., zpsys='ab', pulls=True,
xfigsize=None, yfigsize=None, figtext=None, model_label=None,
errors=None, ncol=2, figtextsize=1., show_model_params=True,
tighten_ylim=False, fname=None, **kwargs):
"""Plot light curve data or model l... | 33,914 |
def read_image(filepath, gray=False):
"""
read image
:param filepath:
:param gray:
:return:
"""
if gray:
return cv2.cvtColor(cv2.imread(filepath), cv2.COLOR_BGR2GRAY)
else:
return cv2.cvtColor(cv2.imread(filepath), cv2.COLOR_BGR2RGB) | 33,915 |
def mixin_hub_pull_parser(parser):
"""Add the arguments for hub pull to the parser
:param parser: the parser configure
"""
def hub_uri(uri: str) -> str:
from ...hubble.helper import parse_hub_uri
parse_hub_uri(uri)
return uri
parser.add_argument(
'uri',
typ... | 33,916 |
def status(ctx, branch, repo):
"""Return the status of the given branch of each project in each CI."""
ctx.obj = Config()
if ctx.invoked_subcommand is None:
ctx.invoke(travis, branch=branch, repo=repo)
ctx.invoke(circle, branch=branch, repo=repo)
ctx.invoke(appveyor, branch=branch, ... | 33,917 |
def load_config() -> Tuple[List, List]:
"""Get configuration from config file.
Returns repo_paths and bare_repo_dicts.
"""
if config_file.exists():
with open(config_file, "r") as ymlfile:
config = yaml.load(ymlfile, Loader=yaml.Loader)
repo_paths = flatten_list(
... | 33,918 |
def deindented_source(src):
"""De-indent source if all lines indented.
This is necessary before parsing with ast.parse to avoid "unexpected
indent" syntax errors if the function is not module-scope in its
original implementation (e.g., staticmethods encapsulated in classes).
Parameters
-------... | 33,919 |
def test_read_csv_file_handle(all_parsers, io_class, encoding):
"""
Test whether read_csv does not close user-provided file handles.
GH 36980
"""
parser = all_parsers
expected = DataFrame({"a": [1], "b": [2]})
content = "a,b\n1,2"
handle = io_class(content.encode("utf-8") if io_class =... | 33,920 |
def test_parquet_conversion(datadir_mgr):
"""Test parquet-to-TSV conversion."""
with datadir_mgr.in_tmp_dir(
inpathlist=[TSV_TEST_FILE],
save_outputs=False,
):
args = ["-q", "-e", SUBCOMMAND, "-w", TSV_TEST_FILE]
print(f"azulejo {' '.join(args)}")
try:
azu... | 33,921 |
def home():
"""Render the home page."""
form = SearchForm()
search_results = None
if form.validate_on_submit():
search_term = form.username.data
cur = conn.cursor()
cur.execute(f"SELECT * FROM student WHERE name = '{search_term}';")
search_results = cur.fetchall()
... | 33,922 |
def capacity():
"""
Returns the raw capacity of the filesystem
Returns:
filesystem capacity (int)
"""
return hdfs.capacity() | 33,923 |
async def deploy(current_user: User = Depends(auth.get_current_user)):
""" This function is used to deploy the model of the currently trained chatbot """
response = mongo_processor.deploy_model(bot=current_user.get_bot(), user=current_user.get_user())
return {"message": response} | 33,924 |
def test_logic():
""" Test logic on known input """
# -------- TRIANGULAR --------
# Input
input_2d = np.random.normal(size=(1000, 20))
labels = np.random.randint(low=0, high=2, size=1000)
# Create model
model = tf.keras.Sequential([tf.keras.layers.Input(shape=(20,)),
... | 33,925 |
def find_rocks(img,rgb_thresh=(100, 100, 60)):
""" Find rock in given image frame"""
color_select = np.zeros_like(img[:,:,0])
# Require that each pixel be above all three threshold values in RGB
# above_thresh will now contain a boolean array with "True"
# where threshold was met
above_thresh = ... | 33,926 |
def assert_same_structure_up_to(shallow_nest, deep_nest):
"""(C++)
Asserts that ``deep_nest`` has same structure as ``shallow_nest`` up the
depths of ``shallow_nest``. Every sub-nest of each of ``nests`` beyond the
depth of the corresponding sub-nest in ``shallow_nest`` will be treated as a
leaf.
... | 33,927 |
def test_ba_validation_right_size_valid_number_8_digits_and_second_digit_different_6_7_9():
"""Test if a valid number is really valid with 8 digits"""
valid_number = '74694200'
assert ba.start(valid_number) == True | 33,928 |
def maybe_start_with_home_prefix(p: Path) -> Path:
"""
If the input path starts with the home directory path string, then return
a path that starts with the home directory and points to the same location.
Otherwise, return the path unchanged.
"""
try:
return Path("~", p.relative_to(Path.... | 33,929 |
def parse_nrc_lexicon():
"""Extract National Resource Council Canada emotion lexicon from http://saifmohammad.com/WebPages/lexicons.html
Returns:
{str: [str]} A defaultdict of emotion to list of associated words
"""
emotion2words = defaultdict(list)
with open(NRC_LEXICON) as lexicon_file:
... | 33,930 |
def rouge_2_fscore(predictions, labels, **unused_kwargs):
"""ROUGE-2 F1 score computation between labels and predictions.
This is an approximate ROUGE scoring method since we do not glue word pieces
or decode the ids and tokenize the output.
Args:
predictions: tensor, model predictions
labels: tensor,... | 33,931 |
def clear_log():
"""clear log file"""
if MODE == "debug":
log_line = f"start {str(datetime.today())} \n\n"
with open("temp/log.txt", "w", encoding="latin-1") as myfile:
myfile.write(log_line)
return () | 33,932 |
def enhancedFeatureExtractorDigit(datum):
"""
Your feature extraction playground.
You should return a util.Counter() of features
for this datum (datum is of type samples.Datum).
## DESCRIBE YOUR ENHANCED FEATURES HERE...
##
"""
features = basicFeatureExtractorDigit(datum)
"*** YOUR CODE HERE ***"... | 33,933 |
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer ... | 33,934 |
def wipe_cache():
"""
if path is absolute, just remove the directory
if the path is relative, recursively look from current directory down
looking for matching paths. This can take a long time looking for
:return:
"""
cache_name = os.path.expanduser(CONFIG.get('jit', 'COMPILE_PATH'))
if... | 33,935 |
def tested_function(x):
"""
Testovana funkce
Da se sem napsat vselijaka cunarna
"""
freq = 1
damp_fac = 0.1
val = np.sin(freq * x)
damp = np.exp(-1 * damp_fac * abs(x))
return val * damp | 33,936 |
def populatePlaylists():
"""Populates the playlist tables with dummy data.
"""
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
user1 = User(email="kaan@kaan.ca", password="1234")
user2 = User(email="ryan@ryan.ca", password="1234")
user3 = User(ema... | 33,937 |
def parse_nkpts(xml_file):
"""
Extract the number of kpoints used in the given xml file
"""
from masci_tools.util.xml.xml_getters import get_nkpts
xmltree, schema_dict = _load_xml_file(xml_file)
nkpts = get_nkpts(xmltree, schema_dict)
echo.echo_info(f'Number of k-points: {nkpts}') | 33,938 |
def parse_line(line):
"""
Parses a (non-comment) line of a GFF3 file. The attribute field is parsed into a dict.
:param line: line to parse as string
:return: dict with for each column (key) the corresponding value
"""
parts = line.strip().split('\t')
output = {}
if len(parts) != len(... | 33,939 |
def get_time_string(place: str = "Europe/Moscow"):
"""
Get time data from worldtimeapi.org and return simple string
Parameters
----------
place : str
Location, i.e. 'Europe/Moscow'.
Returns
-------
string
Time in format '%Y-%m-%d %H:%M:%S'
Examples
--------
... | 33,940 |
def new_worker_qthread(
Worker: Type[WorkerProtocol],
*args,
_start_thread: bool = False,
_connect: Dict[str, Callable] = None,
**kwargs,
):
"""This is a convenience function to start a worker in a Qthread.
In most cases, the @thread_worker decorator is sufficient and preferable.
But th... | 33,941 |
def contains(filename, value=None, fnvalue=None):
""" If a string is contained within a yaml (and is not a comment or key), return where we found it """
if filename in ALL_STRINGS:
for el in ALL_STRINGS[filename]:
if (value and value in el[0]) or (fnvalue and fnmatch.fnmatch(el[0], fnvalue))... | 33,942 |
def plot_with_overview(
ds,
tn,
forcing_vars=["dqdt_adv", "dtdt_adv"],
domain_var="q",
overview_window_width=4,
):
"""
Produce a forcing plot with timestep `tn` highlighted together with
overview plots of domain data variable `domain_var`. The width over the
overview plot is set with... | 33,943 |
def output_all_in_folder_to_csv(folder_name:str, output_folder:str, db_connection: db.engine.base.Connection):
"""
# TODO incorporate the file output regex so folders are only outputtted if they match
# then match all folders to regex and run this function rather than init_from_script function
Running ... | 33,944 |
def log_result(repository):
"""Catch results given by subprocesses."""
logger.info('Received %s from worker.', repository.name)
RESULTS.append(repository) | 33,945 |
def optimize(nn_last_layer, correct_label, learning_rate, num_classes):
"""
Build the TensorFLow loss and optimizer operations.
:param nn_last_layer: TF Tensor of the last layer in the neural network
:param correct_label: TF Placeholder for the correct label image
:param learning_rate: TF Placeholde... | 33,946 |
def addbatchinfo_32PCAs(fam, individuals_annotation, evec_file, eval_file, new_evec_file, new_eval_file):
""" add batch information to final evec file """
try:
fh1 = file(fam, "r")
except IOError, e:
print e
sys.exit(1)
id2fid = {}
line = fh1.readline().rstrip('\n')
while lin... | 33,947 |
def expanded_indexer(key, ndim):
"""Given a key for indexing an ndarray, return an equivalent key which is a
tuple with length equal to the number of dimensions.
The expansion is done by replacing all `Ellipsis` items with the right
number of full slices and then padding the key with full slices so tha... | 33,948 |
def __put_buttons_in_buttonframe(choices):
"""Put the buttons in the buttons frame"""
global __widgetTexts, __firstWidget, buttonsFrame
__firstWidget = None
__widgetTexts = {}
i = 0
for buttonText in choices:
tempButton = tk.Button(buttonsFrame, takefocus=1, text=buttonText)
_... | 33,949 |
def downsample(
data, sampling_freq=None, target=None, target_type="samples", method="mean"
):
"""Downsample pandas to a new target frequency or number of samples
using averaging.
Args:
data: (pd.DataFrame, pd.Series) data to downsample
sampling_freq: (float) Sampling frequency of data... | 33,950 |
def available_commands(mod, ending="_command"):
"""Just returns the available commands, rather than the whole long list."""
commands = []
for key in mod.__dict__:
if key.endswith(ending):
commands.append(key.split(ending)[0])
return commands | 33,951 |
def retrieve_browse(browse_location, config):
""" Retrieve browse image and get the local path to it.
If location is a URL perform download.
"""
# if file_name is a URL download browse first and store it locally
validate = URLValidator()
try:
validate(browse_location)
input_filen... | 33,952 |
def add_suffix(input_dict, suffix):
"""Add suffix to dict keys."""
return dict((k + suffix, v) for k,v in input_dict.items()) | 33,953 |
def ModelPrediction(
df_train,
forecast_length: int,
transformation_dict: dict,
model_str: str,
parameter_dict: dict,
frequency: str = 'infer',
prediction_interval: float = 0.9,
no_negatives: bool = False,
constraint: float = None,
future_regressor_train=[],
future_regressor_... | 33,954 |
def new_config(logger, arg):
"""
Method that turns the pycom to an access point for the user to connect and update the configurations.
The device automatically reboots and applies modifications upon successful configuration.
Takes an extra dummy argument required by the threading library.
:param log... | 33,955 |
def make_year_key(year):
"""A key generator for sorting years."""
if year is None:
return (LATEST_YEAR, 12)
year = str(year)
if len(year) == 4:
return (int(year), 12)
if len(year) == 6:
return (int(year[:4]), int(year[4:]))
raise ValueError('invalid year %s' % year) | 33,956 |
def test_example(default_rules_collection):
"""example.yml is expected to have 15 match errors inside."""
result = Runner(default_rules_collection, 'examples/example.yml', [], [], []).run()
assert len(result) == 16 | 33,957 |
def test_field_name(test_page):
"""Fields should report their intended class name, not 'Performer'."""
with pytest.raises(TypeError) as e:
test_page.button[0]
assert 'Button' in str(e.value)
with pytest.raises(TypeError) as e:
test_page.input_area.input[0]
assert 'Input'... | 33,958 |
def set_stereo_from_geometry(gra, geo, geo_idx_dct=None):
""" set graph stereo from a geometry
(coordinate distances need not match connectivity -- what matters is the
relative positions at stereo sites)
"""
gra = without_stereo_parities(gra)
last_gra = None
atm_keys = sorted(atom_keys(gra... | 33,959 |
def multiply_MPOs(op0, op1):
"""Multiply two MPOs (composition along physical dimension)."""
# number of lattice sites must agree
assert op0.nsites == op1.nsites
L = op0.nsites
# physical quantum numbers must agree
assert np.array_equal(op0.qd, op1.qd)
# initialize with dummy tensors and bo... | 33,960 |
def build_list_of_dicts(val):
"""
Converts a value that can be presented as a list of dict.
In case top level item is not a list, it is wrapped with a list
Valid values examples:
- Valid dict: {"k": "v", "k2","v2"}
- List of dict: [{"k": "v"}, {"k2","v2"}]
- JSON decodable stri... | 33,961 |
def add_borders_to_DataArray_U_points(da_u, da_v):
"""
A routine that adds a column to the "right" of the 'u' point
DataArray da_u so that every tracer point in the tile
will have a 'u' point to the "west" and "east"
After appending the border the length of da_u in x
will be +1 (one new colu... | 33,962 |
def arg(prevs, newarg):
""" Joins arguments to list """
retval = prevs
if not isinstance(retval, list):
retval = [retval]
return retval + [newarg] | 33,963 |
def print_data(uniprot_ids):
"""
For each protein possessing the N-glycosylation motif, prints given access ID followed
by a list of locations in the protein string where the motif can be found.
Args:
uniprot_ids (list): list of UniProt Protein Database access IDs.
Returns:
None
... | 33,964 |
def quote_plus(s, safe='', encoding=None, errors=None):
"""Quote the query fragment of a URL; replacing ' ' with '+'"""
if ' ' in s:
s = quote(s, safe + ' ', encoding, errors)
return s.replace(' ', '+')
return quote(s, safe, encoding, errors) | 33,965 |
def mod(x, y):
"""Implement `mod`."""
return x % y | 33,966 |
def _lower_batch_matmul(op: relay.Call, inputs: List[te.Tensor]) -> te.Tensor:
"""Lower a batch_matmul using cuBLAS."""
return cublas.batch_matmul(
inputs[0],
inputs[1],
transa=op.attrs["transpose_a"],
transb=op.attrs["transpose_b"],
dtype=op.checked_type.dtype,
) | 33,967 |
def cross_entropy_loss(inputs, labels, rescale_loss=1):
""" cross entropy loss with a mask """
criterion = mx.gluon.loss.SoftmaxCrossEntropyLoss(weight=rescale_loss)
loss = criterion(inputs, labels)
mask = S.var('mask')
loss = loss * S.reshape(mask, shape=(-1,))
return S.make_loss(loss.mean()) | 33,968 |
def as_wrapping_formatters(objs, fields, field_labels, formatters, no_wrap=None, no_wrap_fields=[]):
"""This function is the entry point for building the "best guess"
word wrapping formatters. A best guess formatter guesses what the best
columns widths should be for the table celldata. It does this ... | 33,969 |
def classification_metrics(n_classes: int = 2):
"""Function to set up the classification metrics"""
logger.info(f"Setting up metrics for: {n_classes}")
metrics_dict_train = torch.nn.ModuleDict(
{
"accuracy": Accuracy(),
"recall": Recall(),
"precision": Precision()... | 33,970 |
def ping(device,
address,
ttl=None,
timeout=None,
tos=None,
dscp=None,
size=None,
count=None,
source=None,
rapid=False,
do_not_fragment=False,
validate=False,
vrf=None,
command=None,
output=None... | 33,971 |
def log_prov_es(job, prov_es_info, prov_es_file):
"""Log PROV-ES document. Create temp PROV-ES document to populate
attributes that only the worker has access to (e.g. PID)."""
# create PROV-ES doc to generate attributes that only verdi know
ps_id = "hysds:%s" % get_uuid(job["job_id"])
bundle_id = ... | 33,972 |
def createHub(target, genomes, opts):
"""Main method that organizes the creation of the meta-compartive hub."""
# Create the necessary hub files
if not os.path.isdir(opts.hubDir):
os.makedirs(opts.hubDir)
writeHubFile(os.path.join(opts.hubDir, 'hub.txt'),
hubName="_vs_".join(opt... | 33,973 |
def find_host(connection, sd_name):
"""
Check if we can preform a transfer using the local host and return a host
instance. Return None if we cannot use this host.
Using the local host for an image transfer allows optimizing the connection
using unix socket. This speeds up the transfer significantl... | 33,974 |
def _subSquare(vectors, var, full=False):
"""
given a series of vectors, this function calculates:
(variances,vectors)=numpy.linalg.eigh(vectors.H*vectors)
it's a seperate function because if there are less vectors
than dimensions the process can be accelerated, it just takes some dancing
... | 33,975 |
def to_pickle(data):
"""
This prepares data on arbitrary form to be pickled. It handles any nested
structure and returns data on a form that is safe to pickle (including
having converted any database models to their internal representation).
We also convert any Saver*-type objects back to their norm... | 33,976 |
def remove_source_identifier_from_subscription(SubscriptionName=None, SourceIdentifier=None):
"""
Removes a source identifier from an existing event notification subscription.
See also: AWS API Documentation
Exceptions
:example: response = client.remove_source_identifier_from_subscription(... | 33,977 |
def spot_silver_benchmark_sge() -> pd.DataFrame:
"""
上海黄金交易所-数据资讯-上海银基准价-历史数据
https://www.sge.com.cn/sjzx/mrhq
:return: 历史数据
:rtype: pandas.DataFrame
"""
url = "https://www.sge.com.cn/graph/DayilyShsilverJzj"
payload = {}
r = requests.post(url, data=payload)
data_json = r.json()
... | 33,978 |
def requires_all_permissions(permission, login_url=None, raise_exception=False):
"""
Decorator for views that defines what permissions are required, and also
adds the required permissions as a property to that view function.
The permissions added to the view function can then be used by the sidebar
... | 33,979 |
def hasTable(cur, table):
"""checks to make sure this sql database has a specific table"""
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='table_name'")
rows = cur.fetchall()
if table in rows:
return True
else:
return False | 33,980 |
def _check_wkt_load(x):
"""Check if an object is a loaded polygon or not. If not, load it."""
if isinstance(x, str):
try:
x = loads(x)
except WKTReadingError:
warn('{} is not a WKT-formatted string.'.format(x))
return x | 33,981 |
def _yielddefer(function, *args, **kwargs):
"""
Called if a function decorated with :func:`yieldefer` is invoked.
"""
try:
retval = function(*args, **kwargs)
except:
return defer.fail()
if isinstance(retval, defer.Deferred):
return retval
if not (hasattr(ret... | 33,982 |
def dimension_parameters(time_series, nr_steps=100, literature_value=None,
plot=False, r_minmin=None, r_maxmax=None,
shortness_weight=0.5, literature_weight=1.):
""" Estimates parameters r_min and r_max for calculation of correlation
dimension using the algorith... | 33,983 |
def ensure_port_cleanup(
bound_addresses, maxtries=30, sleeptime=2): # pragma: no cover
"""
This makes sure any open ports are closed.
Does this by connecting to them until they give connection
refused. Servers should call like::
ensure_port_cleanup([80, 443])
"""
atexit.register(... | 33,984 |
def GetAllCmdOutput(args, cwd=None, quiet=False):
"""Open a subprocess to execute a program and returns its output.
Args:
args: A string or a sequence of program arguments. The program to execute is
the string or the first item in the args sequence.
cwd: If not None, the subprocess's current director... | 33,985 |
def seir_model_with_soc_dist(init_vals, params, t):
"""
SEIR infection model with social distancing.
rho = social distancing factor.
"""
S_0, E_0, I_0, R_0 = init_vals
S, E, I, R = [S_0], [E_0], [I_0], [R_0]
alpha, beta, gamma, rho = params
dt = t[1] - t[0]
for _ in t[1:]:
... | 33,986 |
def greeq(data, transmit=None, receive=None, opt=None, **kwopt):
"""Fit a non-linear relaxometry model to multi-echo Gradient-Echo data.
Parameters
----------
data : sequence[GradientEchoMulti]
Observed GRE data.
transmit : sequence[PrecomputedFieldMap], optional
Map(s) of the trans... | 33,987 |
def _add_aliases_to_namespace(namespace, *exprs):
"""
Given a sequence of sympy expressions,
find all aliases in each expression and add them to the namespace.
"""
for expr in exprs:
if hasattr(expr, 'alias') and isinstance(expr, sympy.FunctionClass):
if namespace.has_key(str(ex... | 33,988 |
def rotICA(V, kmax=6, learnrate=.0001, iterations=10000):
""" ICA rotation (using basicICA) with default parameters and normalization of
outputs.
:Example:
>>> Vica, W = rotICA(V, kmax=6, learnrate=.0001, iterations=10000)
"""
V1 = V[:, :kmax].T
[W, changes_s] = basicICA(V1, learnrate, i... | 33,989 |
def getipbyhost(hostname):
""" return the IP address for a hostname
"""
return socket.gethostbyname(hostname) | 33,990 |
def reduce_mem_usage(df) -> pd.DataFrame:
"""DataFrameのメモリ使用量を節約するための関数.
Arguments:
df {DataFrame} -- 対象のDataFrame
Returns:
[DataFrame] -- メモリ節約後のDataFrame
"""
numerics = [
'int8', 'int16', 'int32', 'int64', 'float16', 'float32', 'float64'
]
start_mem = df.memory_u... | 33,991 |
def poke_jenkins_hook(ui, repo, node, **kwargs):
"""Filter out the incoming heads and start a Jenkins job for them.
:param ui: Mercurial ui object
:param repo: Mercurial repository object
:param node: Mercurial node object (eg commit)
"""
jenkins_base_url = ui.config('poke_jenkins', 'jenkins_ba... | 33,992 |
def unquote_specific_tokens(tokens: List[str], tokens_to_unquote: List[str]) -> None:
"""
Unquote specific tokens in a list
:param tokens: token list being edited
:param tokens_to_unquote: the tokens, which if present in tokens, to unquote
"""
for i, token in enumerate(tokens):
unquoted... | 33,993 |
def cfg_from_file(filename):
"""
Load a config file and merge it into the default options.
"""
import yaml
with open(filename, 'r') as f:
yaml_cfg = edict(yaml.load(f))
_merge_a_into_b(yaml_cfg, root) | 33,994 |
def findparam(
parameters: _TYPE_FINDITER_PARAMETERS,
selector: _TYPE_FINDITER_SELECTOR
) -> typing.Iterator[_T_PARAM]:
"""
Return an iterator yielding those parameters (of type
:class:`inspect.Parameter` or :class:`~forge.FParameter`) that are
mached by the selector.
:paramref:... | 33,995 |
def test_extract_position_null_case(null_input):
"""Reads in a log that's None"""
# NoneType Input
assert e4.extract_position(null_input) == None | 33,996 |
def reset_syspath():
"""
Return a function to remove given path from sys.path.
This is to use at the end (after all assertions) of test which
use ``setup_project.setup_project`` to add base directory to sys.path
and avoid clash with next tests doing the same.
"""
def reset_func(path):
... | 33,997 |
def free_display():
"""Stop virtual display (if it is up)"""
from .. import config
config.stop_display() | 33,998 |
def FSA(profile_exp, profile_sm, diffsys, time, Xlim=[], n=[400, 500], w=None, f=None, alpha=0.3, name=''):
"""
Forward Simulation Analysis
Extract diffusion coefficients based on a diffusion profile.
Please do not close any plot window during the FSA process.
This is the final step of FSA.
Pa... | 33,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.