content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_inside_lambda():
"""
>>> obj = test_inside_lambda()()
>>> next(obj)
1
>>> next(obj)
2
>>> next(obj)
Traceback (most recent call last):
StopIteration
"""
return lambda:((yield 1), (yield 2)) | 5,285,700 |
def check_version_format(version):
"""
Checks if a version number is well formed, eg:
YYYY-MM-DDTHH:mm:ss
"""
try:
datetime.datetime.strptime(version, "%Y-%m-%dT%H:%M:%S")
return True
except Exception:
raise HTTPError(406,
"Bad version format, ... | 5,285,701 |
def buy():
"""Buy shares of stock"""
transaction = "BUY"
# if requested via post
if request.method == "POST":
# saving the user input values
name = request.form.get("symbol")
if not name:
return apology("Please enter a 4 letter ticker symbol", 400)
quant_tex... | 5,285,702 |
def get_properties_node(character_node):
"""
Returns HIKProperty2State node of the given HumanIk Character node
:param character_node: str
:return: str
"""
if not is_character_definition(character_node):
raise Exception(
'Invalid character definition node! Object "{}" does n... | 5,285,703 |
def isnetid(s):
"""
Returns True if s is a valid Cornell netid.
Cornell network ids consist of 2 or 3 lower-case initials followed by a
sequence of digits.
Examples:
isnetid('wmw2') returns True
isnetid('2wmw') returns False
isnetid('ww2345') returns True
isnetid('w2345') r... | 5,285,704 |
def delete_column(idf, list_of_cols, print_impact=False):
"""
:param idf: Input Dataframe
:param list_of_cols: List of columns to delete e.g., ["col1","col2"].
Alternatively, columns can be specified in a string format,
where different column names are separ... | 5,285,705 |
def generate_sql_verification_data(sql_results_instance):
"""Generates the verification text for a given result sql.
Keyword arguments:
sql_results_instance -- the sql results returned from athena
show_columns -- boolean for whether to show column names or not in the results
"""
results_string ... | 5,285,706 |
def test_get_config_missing(fxtr_setup_logger_environment):
"""Test: get_config() - missing."""
cfg.glob.logger.debug(cfg.glob.LOGGER_START)
# -------------------------------------------------------------------------
cfg.glob.setup = cfg.setup.Setup()
assert len(cfg.glob.setup._config) == CONFIG_P... | 5,285,707 |
def filter_paths(paths, excluded_paths):
"""Filter out path matching one of excluded_paths glob
Args:
paths: path to filter.
excluded_paths: List for glob of modules to exclude.
Returns: An iterable of paths Python modules (i.e. *py files).
"""
excluded = set(Path(f) for excluded_p... | 5,285,708 |
def molobj_add_conformer(molobj, coordinates):
""" Append coordinates as a new conformer to molobj """
conf = Chem.Conformer(len(coordinates))
for i, coordinate in enumerate(coordinates):
conf.SetAtomPosition(i, coordinate)
molobj.AddConformer(conf, assignId=True) | 5,285,709 |
def test_get_specific_application_normal(client):
"""test proper infromation is returned from the API to a normal user
target_url: /applications/<id>
"""
lottery_id = 1
application_id = make_application(
client, test_user['secret_id'], lottery_id)
resp = as_user_get(client,
... | 5,285,710 |
def ec2_resource(aws_credentials):
"""
Create mocked EC2 service resource.
"""
with mock_ec2():
yield boto3.resource('ec2') | 5,285,711 |
def get_user_data(username):
"""Returns user data."""
user = User.query(User.username_lower == username.lower()).get()
if user:
user.data["metadata"]["last_updated"]=user.last_updated
return jsonify(data=user.data) if user else jsonify(error=404) | 5,285,712 |
def copy_spheno_files_output(model_name, output_dir, spheno_oob_path, sarah_spheno_path):
"""
Creates a copy of SPheno output in the
Outputs/... folder.
Then create another one, for the patched version.
"""
dirs = [output_dir + "/SPheno", output_dir+"/SPheno_patched"]
for newdir in dirs:
... | 5,285,713 |
def filter_roidb(roidb):
"""
Remove roidb entries that have no usable RoIs.
"""
def is_valid(entry):
# Valid images have:
# (1) At least one foreground RoI OR
# (2) At least one background RoI
overlaps = entry['max_overlaps']
# find boxes with sufficient over... | 5,285,714 |
def _extract_keywords(tweets):
"""...
Args:
tweets: List of tweets.
"""
neg, neu, pos = {}, {}, {}
for tweet in tweets:
for word in tokenizer.tokenize(RE_RUS_LETTERS.sub(u"", tweet["text"].lower())):
keyword = morph.parse(word)[0].normal_form
if keyword in ... | 5,285,715 |
def read_captcha(path):
"""
读取验证码图片
:param path: 原始验证码存放路径
:return: image_array, image_label:存放读取的iamge list和label list
"""
image_array = []
image_label = []
file_list = os.listdir(path)#获取captcha文件
for file in file_list:
image = Image.open(path + '/' + file)#打开图片
fil... | 5,285,716 |
def getDiscriminatorModels() -> Tuple[torch.nn.Module, torch.nn.Module]:
"""
Prepares the CycleGAN discriminator models based on the given configuration.
Returns
-------
Tuple[torch.nn.Module, torch.nn.Module]
clean discriminator, distorted discriminator
"""
cleanDiscriminator = di... | 5,285,717 |
def merge_runs_by_tag(runs, tags):
"""
Collect the (step, value) tuples corresponding to individual tags for all runs.
Therefore the result might look like this:
<tagA>
+ step:
- <run-1-steps>
- <run-2-steps>
+ value:
- <run-1-values>
- <run-2-values>
.... | 5,285,718 |
def compute(formula, key, amount=1):
"""Function that computes the amount of fuel needed to create the
component KEY. Uses the formula input to follow the process chain."""
# If you reach FUEL, just return how much <fuel> you need
if key == "FUEL":
return amount
# Count how many <key> comp... | 5,285,719 |
def moment(array,substract_one_in_variance_n=True):
"""
Calculate the first four statistical moments of a 1D array
:param array:
:param substract_one_in_variance_n:
:return: array with: m0 (mean) m1 (variance) m2 (skewness) m3 (kurtosis)
"""
a1 = numpy.array(array)
m0 = a1.mean()
tm... | 5,285,720 |
def test_empty_selection_sort():
"""Test empty selection sort."""
assert selection_sort([]) == [] | 5,285,721 |
def best(z, i, down, values):
""" find best number (first possible downwards or upwards) that leads to z == zero at end"""
for digit in (range(9, 0, -1) if down else range(1, 10, 1)):
z_after = run(z, digit, i, values)
if i == 13: # at the end of the number, z must be zero
if z_afte... | 5,285,722 |
def Gbk_presel(best_gain: List[int], cand1: int, cand2: int, gcode0: int) -> Tuple[int, int]:
"""
# (i) [0] Q9 : unquantized pitch gain
# (i) [1] Q2 : unquantized code gain
# (o) : index of best 1st stage vector
# (o) : index of best 2nd stage vector
# (i) Q4 : presearch for gain codebook... | 5,285,723 |
def getCommandString(commandCode):
"""Returns a readable string representation of a message code
"""
return struct.pack('<L', commandCode) | 5,285,724 |
def funcs_for_external(external_fp_fn,
summary_path,
rd_path):
"""
If requesting an external method to get and compare
fingerprints, then use this function to get a dictionary
of pickle paths for each smiles, and the external
fingerprinting function.
... | 5,285,725 |
def from_graph(graph: nx.Graph,
prob: Union[float, int] = 0.1,
rng: Optional[np.random.Generator] = None) -> nx.Graph:
"""Generates mutated graph with the given mutation probability.
Parameters
----------
graph
The graph to be mutated.
prob
Edge mutatio... | 5,285,726 |
def get_preprocessed_data_set(data_path):
"""Preprocess the data set and return it. Because a list of targets and the paths
to the images are needed later, the class ImageFolderWithTargetListAndPaths
is used. Preprocessing follows standard ResNet-preprocessing.
Args:
data_path: path to folder... | 5,285,727 |
def MS_par(slices):
"""
K-modes in parallel
"""
s,k = slices
l,C_s,C_out = bound.get_shared_arrays('l_s','C_s','C_out')
X = bound.SHARED_VARS['X_s']
tmp=np.asarray(np.where(l==k))
if tmp.size !=1:
tmp = tmp.squeeze()
else:
tmp = tmp[0]
C_out[[k],:] = MS(X,s,t... | 5,285,728 |
def test_no_database_uri_set_without_testing_env_var(env, monkeypatch):
"""Package does not work without DATABASE_URI set in the environment."""
monkeypatch.setattr(configuration.ProductionConfig, 'DATABASE_URI', None)
monkeypatch.setattr(configuration.TestingConfig, 'DATABASE_URI', None)
monkeypatch.d... | 5,285,729 |
def parse_meta_staff_elem(
staff_elem: Element, resolution: int, measure_indices: List[int]
) -> Tuple[List[Tempo], List[KeySignature], List[TimeSignature], List[Beat]]:
"""Return data parsed from a meta staff element.
This function only parses the tempos, key and time signatures. Use
`parse_staff_elem... | 5,285,730 |
def get_row_audio(syllable_df, wav_loc, hparams):
""" load audio and grab individual syllables
TODO: for large sparse WAV files, the audio should be loaded only for the syllable
"""
# load audio
rate, data = prepare_wav(wav_loc, hparams)
data = data.astype('float32')
# get audio for ea... | 5,285,731 |
def main(test: bool = False) -> None:
"""
Main function.
:param test: Indicate function is being tested
:return: None
"""
menu.mainloop(surface, disable_loop=test) | 5,285,732 |
def perform_import(val, setting_name):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if val is None:
return None
elif isinstance(val, string_types):
return import_from_string(val, setting_name)
elif isinstance(val, (li... | 5,285,733 |
def main(time_series: str, config: dict = {}, train: bool = True, test: bool = True):
"""_summary_
Parameters
----------
time_series : str
_description_
config : dict, optional
_description_, by default {}
"""
# Get train files
train_files = list_files(time_series, confi... | 5,285,734 |
def get_root_url(g, website_url):
"""Given website url, get its root node."""
return (
g.V(website_url)
.hasLabel("website")
.in_("links_to")
) | 5,285,735 |
def prepare_test_data(*test_data):
"""Generator to prepare data for DDT
:param test_data: tuples with name of the test, input value and expected
output value
:return: named list with input value and expected output value
"""
for td in test_data:
_test_name, _input, _e... | 5,285,736 |
def send_message(hass, message, title=None, data=None):
"""Send a notification message."""
info = {ATTR_MESSAGE: message}
if title is not None:
info[ATTR_TITLE] = title
if data is not None:
info[ATTR_DATA] = data
hass.services.call(DOMAIN, SERVICE_NOTIFY, info) | 5,285,737 |
def can_see_staff_link(user):
"""
Return True if the user should see the staff view.
Example usage: {{ user|can_see_staff_link }}
"""
return should_see_staff_view(user) | 5,285,738 |
def mutUniformBounded(individual, low, up, indpb):
"""Mutate an individual by replacing attributes, with probability *indpb*,
by a integer uniformly drawn between *low* and *up* inclusively.
:param individual: :term:`Sequence <sequence>` individual to be mutated.
:param low: The lower bound or a :term:`... | 5,285,739 |
def authenticated_only(*args, **kwargs):
"""Return a permission allowing access to admin and authenticated users.
:returns: a permission allowing only super-admin.
"""
return StrictDynamicPermission(AuthenticatedNeed) | 5,285,740 |
def set_console_log_level(console_output_level: int):
""" Set console output to the desired level and register it with openml logger if needed. """
global console_handler
_set_level_register_and_store(cast(logging.Handler, console_handler), console_output_level) | 5,285,741 |
def initialize():
"""Forces the initialization for underlying database back-end module"""
return IMPL.initialize() | 5,285,742 |
def _not_blank(error_msg):
"""Returns a non-blank validation rule with custom error message."""
return validate.Length(min=1, error=error_msg) | 5,285,743 |
def _AdjustColHeadings(colHeadings, maxColLabelLen):
""" *For Internal Use*
removes illegal characters from column headings
and truncates those which are too long.
"""
for i in xrange(len(colHeadings)):
# replace unallowed characters and strip extra white space
colHeadings[i] = colHeadings[i... | 5,285,744 |
def authenticated_user(client, account):
"""Create an authenticated user for a test"""
# user = G(User, email='test@gmail.com')
account.email = 'test@gmail.com'
account.set_password('my_password123')
account.save()
client.login(email='test@gmail.com', password='my_password123')
return accoun... | 5,285,745 |
def calcENM(atoms, select=None, model='anm', trim='trim', gamma=1.0,
title=None, n_modes=None, **kwargs):
"""Returns an :class:`.ANM` or :class:`.GNM` instance and *atoms* used for the
calculations. The model can be trimmed, sliced, or reduced based on
the selection.
:arg atoms: atoms on... | 5,285,746 |
def Create_GIF(filename, path, num_images, duration = 66, loop = None):
"""
Temporary files must have the same name with a number indicating frame number
example: "filename_0.png"
Parameters
----------
filename : TYPE
Name of temporary files to stitch together.
path : TYPE
... | 5,285,747 |
def is_affine_st(A: Affine, tol: float = 1e-10) -> bool:
"""
Check if transfrom is pure scale and translation.
:return: ``True`` if Affine transform has scale and translation components only
:return: ``False`` if there is non-zero rotation or skew
"""
(_, wx, _, wy, _, _, *_) = A
return ab... | 5,285,748 |
def build(path):
"""Build an inference engine from a serialized model.
Args:
path: model or path to a saved onnx/trt checkpoint
"""
logging.info("Deserializing the TensorRT engine from {}".format(path))
with open(path, "rb") as f, trt.Logger() as logger, trt.Runtime(logger) as runtime:
... | 5,285,749 |
def transient_indices_periodic(T1,N):
"""Computes indices for transient handling of periodic signals.
Computes the indices to be used with a vector u of length N that contains
(several realizations of) a periodic signal, such that u[indices] has T1[0]
transient samples prepended to each realization. Th... | 5,285,750 |
def make_soup(root, n_p, n_s, verbose=False):
"""
Make a new word from a root, containing n_prefixes and n_suffixes
Also adds a random ending (grammatical form)
"""
soup = root[:-1]
ending = root[-1]
assert ending in {'i', 'o', 'e'}
added_affixes = []
meanings = []
for p in xrang... | 5,285,751 |
def build(conf, name='Enc_Anatomy'):
"""
Build a UNet based encoder to extract anatomical information from the image.
"""
spatial_encoder = UNet(conf)
spatial_encoder.input = Input(shape=conf.input_shape)
l1_down = spatial_encoder.unet_downsample(spatial_encoder.input, spatial_encoder.normalise)... | 5,285,752 |
def images_generator(X, y, batch_size):
"""
A generator for the images. Loads a 'batch_size' of images form disk
and returns it. Used for batch-training.
As an example, if the batch size is 64:
- The first call will return data[0:64]
- The second call will return data[... | 5,285,753 |
def prepare_values(y_true, y_pred):
"""Converts the input values to numpy.ndarray.
Parameters
----------
y_true : torch.tensor
Either a CPU or GPU tensor.
y_pred : torch.tensor
Either a CPU or GPU tensor.
Returns
-------
y_true, y_pred : numpy.ndarray
Numpy.ndar... | 5,285,754 |
def initialize_with_key(shared_key, cache_capacity=_CACHE_CAPACITY,
cache_timeout=_CACHE_TIMEOUT):
"""
Initializes module with the specified shared key as well as nonce cache.
This module can handle authenticating 5,000 requests/second, if you need to
authenticate more requests ... | 5,285,755 |
def pyagent(sweep_id, function, entity=None, project=None, count=None):
"""Generic agent entrypoint, used for CLI or jupyter.
Arguments:
sweep_id (dict): Sweep ID generated by CLI or sweep API
function (func, optional): A function to call instead of the "program"
entity (str, optional):... | 5,285,756 |
def expand_qt_container_rows(self, object_name):
"""
function used for expanding qt container rows with expandable children
param self: The script object calling this function
param object_name: qt object name as a string
returns: none
"""
children = self.asset_editor_row_container.findChi... | 5,285,757 |
def timing(f):
"""
Decorator function to add time elapsed
"""
@wraps(f)
def wrapper(*args, **kwargs):
start = time()
result = f(*args, **kwargs)
end = time()
time_elapsed = round(end - start, 2)
if isinstance(result, tuple):
return (*result, time_... | 5,285,758 |
def solve(env:Program):
"""
Solve the program!
"""
# emit the generated program
program = GeneratedMain()
program.window_title = "Goes Nowhere, Does Nothing"
program.window_width = 512
program.window_height = 512
dependencies:List[str] = []
if len([t for t in env.textures.value... | 5,285,759 |
def hg(args):
"""Run a Mercurial command and return its output.
All errors are deemed fatal and the system will quit."""
full_command = ['hg']
full_command.extend(args)
try:
output = check_output(full_command, env=os.environ, universal_newlines=True, shell=True, stderr=subprocess.STDOUT)
... | 5,285,760 |
def accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""
Calculate accuracy of given predictions
Parameters
----------
y_true: ndarray of shape (n_samples, )
True response values
y_pred: ndarray of shape (n_samples, )
Predicted response values
Returns
-------
... | 5,285,761 |
def breakeven_revenue(
cost_upfront,
carboncost=50, carbontons=0, wacc=7, lifetime=30,
degradationrate=0.5, cost_om=15, cost_om_units='$',
inflationrate=2.5, taxrate=40,
taxrate_federal=None, taxrate_state=None,
schedule='macrs', period=5, itc=0,
maxiter=1000, xtol='default',
ab=(-10... | 5,285,762 |
def get_mesh_pts(N, img_size):
"""
Algorithm is as follows:
First I will place approx 4*sqrt(N) equispaced points around the boundary
of the square and then distributed the remaining N-4*sqrt(N) points uniformly
at random inside the square. Then, I call the Delaunay algorithm to make the
triangu... | 5,285,763 |
def set_environment_config_vars():
""" Set GNIPPY env variables. """
os.environ["GNIPPY_URL"] = test_powertrack_url
os.environ["GNIPPY_RULES_URL"] = test_rules_url
os.environ["GNIPPY_AUTH_USERNAME"] = test_username
os.environ["GNIPPY_AUTH_PASSWORD"] = test_password | 5,285,764 |
def _create_cell_list(hparams, mode):
"""Create a list of RNN cells."""
# Multi-GPU
cell_list = []
for i in range(hparams.num_layers):
# last layers use residual connection
if i >= hparams.num_layers - hparams.num_residual_layers:
residual_connection = True
else:
residual_connection ... | 5,285,765 |
def lvl_profiles(z_axis, sigma_grid, tau_grid, sig_lvls):
"""Represent sigma and spice profiles as discrete points"""
all_profiles = []
num_profs = sigma_grid.shape[-1]
for i in range(num_profs):
z_lvl = np.interp(sig_lvls, sigma_grid[:, i], z_axis,
left=np.nan, right=... | 5,285,766 |
def get_pydot_attributes(index, dot):
"""Helper function to get attributes from pydot graph given index"""
return dot.get_subgraphs()[index].get_nodes()[0].get_attributes() | 5,285,767 |
def parse_taxon(file_name):
"""
:param file_name:
:return:
"""
res = set()
with open(file_name, 'r') as IN:
for line in IN:
res.add(line.strip())
return res | 5,285,768 |
def ldns_update_upcount(*args):
"""LDNS buffer."""
return _ldns.ldns_update_upcount(*args) | 5,285,769 |
def walk_test_targets(
path=None, # type: t.Optional[str]
module_path=None, # type: t.Optional[str]
extensions=None, # type: t.Optional[t.Tuple[str, ...]]
prefix=None, # type: t.Optional[str]
extra_dirs=None, # type: t.Optional[t.Tuple[str, ...]]
include_symlinks=Fal... | 5,285,770 |
def mate(ind1, ind2, indpb):
"""
Executes a uniform crossover that modify in place the two
individuals. The attributes are swapped according to the
*indpb* probability.
"""
out_success, in_success = True, True
if ind1.out_enabled and random.random() < indpb:
out_success = do_mate(ind... | 5,285,771 |
def time_convert(ens, cls_to, **kwds):
""" Time conversion function """
t0 = time.time()
ens_out = ens.convert_to(cls_to, **kwds)
t1 = time.time()
print("Convert %s to %s with %i pdfs in %.2f s" % (type(ens.gen_obj), cls_to, ens.frozen.npdf, t1-t0))
return ens_out | 5,285,772 |
def ph_calc_phwater(ref, light, therm, ea434, eb434, ea578, eb578, ind_slp, ind_off, psal=35.0):
"""
Description:
OOI Level 2 pH of seawater core data product, which is calculated using
data from the Sunburst SAMI-II pH instrument (PHSEN). This document is
intended to be used by OOI pro... | 5,285,773 |
def install_user():
""" returns current user
"""
user = os.getenv('USER', None)
if user is None:
raise Exception("Unable to determine current user.")
return user | 5,285,774 |
def Dominates(x, y):
"""Check if x dominates y.
:param x: a sample
:type x: array
:param y: a sample
:type y: array
"""
return np.all(x <= y) & np.any(x < y) | 5,285,775 |
def predict(path=None,img=None):
"""
图片文字方向预测
"""
ROTATE = [0,270,180,90]
if path is not None:
im = Image.open(path).convert('RGB')
elif img is not None:
im = Image.fromarray(img).convert('RGB')
w,h = im.size
thesh = 0.05
xmin,ymin,xmax,ymax = int(thesh*w),int(thesh*h),... | 5,285,776 |
def get_classic_generated_events(access_token, calendar_id):
"""Gets a list of classic generated events
Args:
access_token (string): User's access token to make the request
calendar_id (string): ID of the specific calendar that the event exists on
Returns:
List: list of events that... | 5,285,777 |
def test_multiple_els_simple(multiple_intersections):
"""Test sounding with multiple ELs.
If which='top', return lowest-pressure EL.
If which='bottom', return the highest-pressure EL.
If which='all', return all ELs
"""
levels, temperatures, dewpoints = multiple_intersections
el_pressure_to... | 5,285,778 |
def sumProb(N: int, p: float) -> float:
"""
Biến ngẫu nhiên nhị thức chỉ có hữu hạn symbol, tổng xác suất của tất cả các symbol này bằng 1.
Do đó hàm sumProb cho phép kiểm tra tổng xác suất của biến ngẫu nhiên nhị thức bằng 1.
Chứng minh toán học có trong file explanation.pdf
Parameters:
- N (... | 5,285,779 |
def set_gpu_from_theano():
"""
This set the GPU used by PyCUDA to the same as the one used by Theano.
"""
# Transfer the theano gpu binding to pycuda, for consistency
if config.device.startswith("gpu") and len(config.device) > 3:
os.environ["CUDA_DEVICE"] = theano.config.device[3:]
elif ... | 5,285,780 |
def server_cli(work_dir, host, port):
"""Run the server side of porfavor.
Warning: not to be used on production.
"""
app.config["UPLOAD_FOLDER"] = work_dir
app.run(host=host, port=port) | 5,285,781 |
def get_asset_name_and_format_from_string(title_text) -> []:
"""Checks input string for name and format
:param [] title_text: input string formatted by lines
:return: [name, asset_format]
"""
if (
title_text[0].lower() == "NEW".lower()
and title_text[1].lower() == "FREE".lower()
... | 5,285,782 |
def average_color(color: list):
"""複数サンプルした時に平均色を求めたい"""
c = color
avg_color = [c[i : i + 4] for i in range(0, len(c), 4)]
avg_color = np.array(avg_color)
avg = np.average(avg_color, axis=0)
return avg | 5,285,783 |
def vectorize_sentence(sentence: List[str], model, empty_strategy):
"""
Given a text transform it in a list of vectors using Word Embeddings techniques
:param sentence: string containing a sentence
:param model: word embedding model
:param empty_strategy: which strategy to use for handling missing v... | 5,285,784 |
def test_qamats_gadol_eim_qria():
"""`qamats` before `eim-qria` is `qamats-gadol` (qamats-gadol-eim-qria)"""
word = r"נָא" # na (qamats)
parts = ["nun", "qamats-gadol", "eim-qria-alef"]
assert parts == Parser().parse(word).flat() | 5,285,785 |
def operate_crontab(operate):
"""
操作crontab
:param operate: add , del
:return:
"""
try:
# 从系统命令中,获取定时任务
p = subprocess.Popen(["crontab", "-l"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
ret... | 5,285,786 |
def frac_diff(dataframe, d, thres=0.01):
"""
Perform Standard Fracdiff - Expanding Window
:param dataframe:
:param d:
:param thres:
:return:
"""
# Get the weights for the longgest series
def get_weights(d, size):
w = [1.]
for k in range(1, size):
w_ = ... | 5,285,787 |
def register(ref_img, in_img, ref_weights=None, in_weights=None, cmd=None):
"""Find the 4D affine transform that registers in_img to ref_img
Args:
ref_img -- (type: ndarray) reference image
in_img -- (type: ndarray) input image to be registered
ref_weights -- (type: ndarray, def... | 5,285,788 |
def test_fk_id_in_filter(query):
"""
Test in filter on an foreign key relationship.
"""
john_doe = Reporter.objects.create(
first_name="John", last_name="Doe", email="john@doe.com"
)
jean_bon = Reporter.objects.create(
first_name="Jean", last_name="Bon", email="jean@bon.com"
... | 5,285,789 |
def sort_loops_based_on_weights_and_date(params: dict) -> List[WeightedLoop]:
"""
:param params: dict of params
:return: list of sorted, signed, and weighted loops
"""
signed_weighted_loops = __find_signed_closed_loops(params)
# sort based on weights and dates
signed_weighted_loops.sort(key=... | 5,285,790 |
def get_alpha2_to_continents_from_wiki():
"""Get Country Codes to Continents from Wikipedia.
"""
data = {}
for continent, countries in get_continents_to_countries_from_wiki().items():
for country_name in countries:
pprint(pycountry.countries.get(name=country_name).alpha_2)
... | 5,285,791 |
def make_email_lists(items):
"""Make an HTML and plain text list of items, to be used in emails.
"""
if not items or len(items) == 0:
return "", ""
htm = ["<li>{}</li>".format(html.escape(i if i else "\'blank\'")) for i in items]
htm = "<ul>{}</ul>".format("".join(htm))
text = [f" - {... | 5,285,792 |
def RemoveDuplicatedVertices(vertices, faces, vnorms = None):
"""Remove duplicated vertices and re-index the polygonal faces such that
they share vertices
"""
vl = {}
vrl = {}
nvert = 0
vertList = []
normList = []
for i,v in enumerate(vertices):
key = '%f%f%f'%tuple(v)
... | 5,285,793 |
def setup_logging(verbosity=0):
"""Configure progressbar sys.stderr wrapper which is required to play nice
with logging and not have strange formatting artifacts.
"""
progressbar.streams.wrap_stderr() | 5,285,794 |
def is_network_rate_error(exc):
"""
:param exc: Exception
Exception thrown when requesting network resource
:return: bool
True iff exception tells you abused APIs
"""
keys = ["429", "Connection refused"]
for key in keys:
if key in str(exc):
return True
re... | 5,285,795 |
def ema(data, n, nans=-1):
""" Computes the exponential MA for each row of the input.
:param data: pandas dataframe.
:param n: MA period.
:return: a new dataframe with the MA values.
"""
if type(data) == pd.Series:
data = data.to_frame()
ma = data.ewm(span=n, adjust=False).mea... | 5,285,796 |
def listV(t,v):
"""
This function is not very 'smart'
This function creates a vsipl double or integer vector and copies a list into VSIPL.
It will only copy into vectors of type double (real or complex) or of type int.
That is to say vectors of type vsip_vview_d, vsip_cvview_d, and vsip_... | 5,285,797 |
def _to_tensor(x, dtype):
"""Convert the input `x` to a tensor of type `dtype`.
# Arguments
x: An object to be converted (numpy array, list, tensors).
dtype: The destination type.
# Returns
A tensor.
"""
x = tf.convert_to_tensor(x)
if x.dtype != dtype:
x = tf.cast... | 5,285,798 |
def show_object_details(object_id, article_indexes, pred_df=None, topk=10):
"""
Shows associated papers for an object id according to predicted article_indexes
# U expands categorical variables, so it has a dimension larger than dext.objects_df
:param object_id:
:param article_indexes:
:... | 5,285,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.