content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def compare_dirs_ignore_words(dir1, dir2, ignore_words, ignore_files=None):
"""Same as compare_dirs but ignores lines with words in ignore_words.
"""
return compare_dirs(
dir1,
dir2,
ignore=ignore_files,
function=lambda file1, file2:
compare_text_files_ignore_lines(fi... | 2794027a638a7f775ae559b250a500e28a218e4a | 3,655,500 |
def float_to_wazn(value):
"""Converts a float value to an integer in the WAZN notation.
The float format has a maxium of 6 decimal digits.
:param value: value to convert from float to WAZN notation
:returns: converted value in WAZN notation
"""
return int(Decimal(value) / MICRO_WAZN) | 6bf10dfbefe51b2a785c4d0504e446662487b485 | 3,655,501 |
import time
def timer(func):
""" Decorator to measure execution time """
def wrapper(*args, **kwargs):
start_time = time.time()
ret = func(*args, **kwargs)
elapsed = time.time() - start_time
print('{:s}: {:4f} sec'.format(func.__name__, elapsed))
return ret
retu... | 0f6a8a4dc8eff1aa49efaf5d26ac46e0cc483b3e | 3,655,502 |
import uuid
def _create_keyword_plan_campaign(client, customer_id, keyword_plan):
"""Adds a keyword plan campaign to the given keyword plan.
Args:
client: An initialized instance of GoogleAdsClient
customer_id: A str of the customer_id to use in requests.
keyword_plan: A str of the ke... | b6ce2ee2ec40e1192461c41941f18fe04f901344 | 3,655,503 |
def word2vec(sentences, year):
"""
Creates a word2vec model.
@param sentences: list of list of words in each sentence (title + abstract)
@return word2vec model
"""
print("Creating word2vec model")
model = Word2Vec(sentences, size=500, window=5, min_count=1, workers=4)
model.save(f"models... | 745bd15f4c0cea5b9417fd0562625426bd5cd293 | 3,655,504 |
def true_rjust(string, width, fillchar=' '):
""" Justify the string to the right, using printable length as the width. """
return fillchar * (width - true_len(string)) + string | 53a8cbfd049c21821b64e1a218c9af2a7b4c8b7d | 3,655,505 |
def threshold_generator_with_values(values, duration, num_classes):
"""
Args:
values: A Tensor with shape (-1,)
Values = strictly positive, float thresholds.
duration: An int.
num_classes: An int.
Returns:
thresh: A Tensor with shape
(len(list_values... | 58aa50e08beaba8f299af3ec9dfeb3de652e6471 | 3,655,506 |
def is_hermitian(mx, tol=1e-9):
"""
Test whether mx is a hermitian matrix.
Parameters
----------
mx : numpy array
Matrix to test.
tol : float, optional
Tolerance on absolute magitude of elements.
Returns
-------
bool
True if mx is hermitian, otherwise False... | 31e9a1faff21707b2fc44c7824bb05fc85967f00 | 3,655,507 |
def argmax(a, b, axis=1, init_value=-1, name="argmax"):
""" sort in axis with ascending order """
assert axis<len(a.shape) and len(a.shape)<=2, "invalid axis"
assert b.shape[axis] == 2, "shape mismatch"
size = a.shape[axis] # save max arg index
def argmax2d(A, B):
init = hcl.compute((2,... | 3626126cae255498cab854f8b898a7d0f730b20d | 3,655,508 |
def morphology(src, operation="open", kernel_shape=(3, 3), kernel_type="ones"):
"""Dynamic calls different morphological operations
("open", "close", "dilate" and "erode") with the given parameters
Arguments:
src (numpy.ndarray) : source image of shape (rows, cols)
operation (str, optional)... | f8258616f07b9dd0089d323d9237483c05b86c2e | 3,655,509 |
def msd(traj, mpp, fps, max_lagtime=100, detail=False, pos_columns=None):
"""Compute the mean displacement and mean squared displacement of one
trajectory over a range of time intervals.
Parameters
----------
traj : DataFrame with one trajectory, including columns frame, x, and y
mpp : microns ... | 4511eb3e0d69ab5581635ba93db6dedfd387eb84 | 3,655,510 |
import random
def build_rnd_graph(golden, rel, seed=None):
"""Build a random graph for testing."""
def add_word(word):
if word not in words:
words.add(word)
def add_edge(rel, word1, word2):
data.append((rel, word1, word2))
random.seed(seed)
m, _ = golden.shape
wo... | 46eacb5a51cf94ee27ed33757887afca4cc153ff | 3,655,511 |
from typing import Union
import pathlib
from typing import IO
from typing import AnyStr
import inspect
import pandas
def _make_parser_func(sep):
"""
Create a parser function from the given sep.
Parameters
----------
sep: str
The separator default to use for the parser.
Returns
--... | 318edb7e761e163c828878a1c186edc535d824a1 | 3,655,512 |
import glob
import os
def load_and_join(LC_DIR):
"""
load and join quarters together.
Takes a list of fits file names for a given star.
Returns the concatenated arrays of time, flux and flux_err
"""
fnames = sorted(glob.glob(os.path.join(LC_DIR, "*fits")))
hdulist = fits.open(fnames[0])
... | 39345f4439d516b19707c68f29ab71987a54ec56 | 3,655,513 |
def dcm_to_pil_image_gray(file_path):
"""Read a DICOM file and return it as a gray scale PIL image"""
ds = dcmread(file_path)
# Get the image after apply clahe
img_filtered = Image.fromarray(apply_clahe(ds.pixel_array).astype("uint8"))
# Normalize original image to the interval [0, 255]
img = cv... | c85b149dd1d02f24e60411ffb6d0dccfb1afd949 | 3,655,514 |
from typing import Any
def get_object_unique_name(obj: Any) -> str:
"""Return a unique string associated with the given object.
That string is constructed as follows: <object class name>_<object_hex_id>
"""
return f"{type(obj).__name__}_{hex(id(obj))}" | f817abf636673f7ef6704cbe0ff5a7a2b897a3f6 | 3,655,515 |
def create_voting_dict():
"""
Input: a list of strings. Each string represents the voting record of a senator.
The string consists of
- the senator's last name,
- a letter indicating the senator's party,
- a couple of letters indicating the senator's home ... | 4a662c110b88ae92ea548da6caa15b01b82f1cf2 | 3,655,516 |
def areFriends(profile1, profile2):
"""Checks wether profile1 is connected to profile2 and profile2 is connected to profile1"""
def check(p1, p2):
if p1.isServiceIdentity:
fsic = get_friend_serviceidentity_connection(p2.user, p1.user)
return fsic is not None and not fsic.deleted
... | 89eb04d0b8cce054e75d26d194d3f88f9b5970db | 3,655,517 |
def filter_dict(regex_dict, request_keys):
"""
filter regular expression dictionary by request_keys
:param regex_dict: a dictionary of regular expressions that
follows the following format:
{
"name": "sigma_aldrich",
"regexes": ... | fb503f0d4df0a7965c276907b7a9e43bd14f9cac | 3,655,518 |
import six
def calculate_partition_movement(prev_assignment, curr_assignment):
"""Calculate the partition movements from initial to current assignment.
Algorithm:
For each partition in initial assignment
# If replica set different in current assignment:
# Get Difference in ... | 180a47944523f0c814748d1918935e47d9a7ada4 | 3,655,519 |
from typing import List
from typing import Union
import torch
from typing import Sequence
def correct_crop_centers(
centers: List[Union[int, torch.Tensor]],
spatial_size: Union[Sequence[int], int],
label_spatial_shape: Sequence[int],
) -> List[int]:
"""
Utility to correct the crop center if the cr... | d8a28d464a4d0fcd8c1ad8ed0b790713aaa878e2 | 3,655,520 |
def contrast_normalize(data, centered=False):
"""Normalizes image data to have variance of 1
Parameters
----------
data : array-like
data to be normalized
centered : boolean
When False (the default), centers the data first
Returns
-------
data : array-like
norm... | e85e5488e0c69bcf0233c03f3595a336b3ad7921 | 3,655,521 |
def create_gdrive_folders(website_short_id: str) -> bool:
"""Create gdrive folder for website if it doesn't already exist"""
folder_created = False
service = get_drive_service()
base_query = "mimeType = 'application/vnd.google-apps.folder' and not trashed and "
query = f"{base_query}name = '{website... | 21928843c47bbc3b175b65a7268eb63e0bec1275 | 3,655,522 |
def filter_for_recognized_pumas(df):
"""Written for income restricted indicator but can be used for many other
indicators that have rows by puma but include some non-PUMA rows. Sometimes
we set nrows in read csv/excel but this approach is more flexible"""
return df[df["puma"].isin(get_all_NYC_PUMAs())] | fe3c608495603f74300dc79a4e50d185d87ca799 | 3,655,523 |
import pandas as pd
import os
def hotspots2006(path):
"""Hawaian island chain hotspot Argon-Argon ages
Ar-Ar Ages (millions of years) and distances (km) from Kilauea along the
trend of the chain of Hawaian volcanic islands and other seamounts that
are believed to have been created by a moving "hot spot".
... | fce88e988e62227c8247fd58575db1fafd35e73f | 3,655,524 |
def school_booking_cancel(request, pk_booking):
"""Render the school booking cancel page for a school representative.
:param request: httprequest received
:type request: HttpRequest
:param pk_booking: Primary Key of a Booking
:type pk_booking: int
:return: Return a HttpResponse whose content is... | 1b0e09119ba453efdf486e11a57d92c508a497ff | 3,655,525 |
def bandpass_filter(df, spiky_var):
"""Detect outliers according to a passband filter specific to each variable.
Parameters
----------
df: pandas DataFrame that contains the spiky variable
spiky_var: string that designate the spiky variable
Returns
-------
id_outlier: index of outliers... | a20e3861f04212fe8b3e44d278da9ed58d545d1c | 3,655,526 |
def load_energy():
"""Loads the energy file, skipping all useluss information and returns it as a dataframe"""
energy = pd.read_excel("Energy Indicators.xls", skiprows=17, header=0,
skip_footer=53-15, na_values="...", usecols=[2,3,4,5])
# Rename columns
energy.columns = ["Coun... | 10c9e638398d74eed57ccab414cac5577623c6cf | 3,655,527 |
import re
def list_list_to_string(list_lists,data_delimiter=None,row_formatter_string=None,line_begin=None,line_end=None):
"""Repeatedly calls list to string on each element of a list and string adds the result
. ie coverts a list of lists to a string. If line end is None the value defaults to "\n", for no se... | d1e69d21205fcc21e186a8dd160c1817fb1f0f68 | 3,655,528 |
import os
def get_env_loader(package, context):
"""This function returns a function object which extends a base environment
based on a set of environments to load."""
def load_env(base_env):
# Copy the base environment to extend
job_env = dict(base_env)
# Get the paths to the env ... | acc7e5bf5b23c885dfeed2af71e054205c5b1aa9 | 3,655,529 |
def sampen(L, m):
"""
"""
N = len(L)
r = (np.std(L) * .2)
B = 0.0
A = 0.0
# Split time series and save all templates of length m
xmi = np.array([L[i: i + m] for i in range(N - m)])
xmj = np.array([L[i: i + m] for i in range(N - m + 1)])
# Save all matches minus the self-match,... | 0a97e8dd8c4edbf2ec4cbbdff3241af7de3f2a66 | 3,655,530 |
from typing import Union
def total(score: Union[int, RevisedResult]) -> int:
"""
Return the total number of successes (negative for a botch).
If `score` is an integer (from a 1st/2nd ed. die from :func:`standard` or
:func:`special`) then it is returned unmodified.
If `score` is a :class:`Revised... | 849b757875ea461b0ea6bf4a63270e6f5fbac28c | 3,655,531 |
import torch
import os
def load_vgg16(model_dir, gpu_ids):
""" Use the model from https://github.com/abhiskk/fast-neural-style/blob/master/neural_style/utils.py """
# if not os.path.exists(model_dir):
# os.mkdir(model_dir)
# if not os.path.exists(os.path.join(model_dir, 'vgg16.weight')):
# ... | 7e6499c5ce8f81f693015916eeb8649263dc3039 | 3,655,532 |
def rbbox_overlaps_v3(bboxes1, bboxes2, mode='iou', is_aligned=False):
"""Calculate overlap between two set of bboxes.
Args:
bboxes1 (torch.Tensor): shape (B, m, 5) in <cx, cy, w, h, a> format
or empty.
bboxes2 (torch.Tensor): shape (B, n, 5) in <cx, cy, w, h, a> format
... | cdd414b02ac08c5a8bc494ed7319942e26bc5f02 | 3,655,533 |
import warnings
def get_target_compute_version(target=None):
"""Utility function to get compute capability of compilation target.
Looks for the arch in three different places, first in the target attributes, then the global
scope, and finally the GPU device (if it exists).
Parameters
----------
... | ad55cbb81fb74521175ea6fbdcba54cc14a409cb | 3,655,534 |
def get_poet_intro_by_id(uid):
"""
get poet intro by id
:param uid:
:return:
"""
return Poet.get_poet_by_id(uid) | d6fd84bd150ee8ce72becdb6b27b67d1c21c7a9b | 3,655,535 |
from datetime import datetime
def create_post():
"""Создать пост"""
user = get_user_from_request()
post = Post(
created_date=datetime.datetime.now(),
updated_date=datetime.datetime.now(),
creator=user,
)
json = request.get_json()
url = json["url"]
if Post.get_or_... | 7b8eaf74cda78198d08ca6eac66f1f13a12c4341 | 3,655,536 |
import async_timeout
async def fetch(session, url):
"""Method to fetch data from a url asynchronously
"""
async with async_timeout.timeout(30):
async with session.get(url) as response:
return await response.json() | d8ff22df047fece338dcfe4c6286766a563ff9aa | 3,655,537 |
def recurse_while(predicate, f, *args):
"""
Accumulate value by executing recursively function `f`.
The function `f` is executed with starting arguments. While the
predicate for the result is true, the result is fed into function `f`.
If predicate is never true then starting arguments are returned... | fd3313760c246336519a2e89281cc94a2bee6833 | 3,655,538 |
from typing import Optional
import ast
import sys
def unparse(node: Optional[ast.AST]) -> Optional[str]:
"""Unparse an AST to string."""
if node is None:
return None
elif isinstance(node, str):
return node
elif node.__class__ in OPERATORS:
return OPERATORS[node.__class__]
e... | b0fafc4c423af192cb4c15b1e063f7b1c8dfa568 | 3,655,539 |
import timeit
import logging
def construct_lookup_variables(train_pos_users, train_pos_items, num_users):
"""Lookup variables"""
index_bounds = None
sorted_train_pos_items = None
def index_segment(user):
lower, upper = index_bounds[user:user + 2]
items = sorted_train_pos_items[lower:u... | c3e1087cce5a38d681379f30d7c6dee8d1544e60 | 3,655,540 |
def total_allocation_constraint(weight, allocation: float, upper_bound: bool = True):
"""
Used for inequality constraint for the total allocation.
:param weight: np.array
:param allocation: float
:param upper_bound: bool if true the constraint is from above (sum of weights <= allocation) else from b... | b92c4bd18d1c6246ff202987c957a5098fd66ba1 | 3,655,541 |
def sigmoid(x):
""" computes sigmoid of x """
return 1.0/(1.0 + np.exp(-x)) | cd34b4ed9fe08607ea3fec1dce89bee7c34efeb0 | 3,655,542 |
def handle_error(err):
"""Catches errors with processing client requests and returns message"""
code = 500
error = 'Error processing the request'
if isinstance(err, HTTPError):
code = err.code
error = str(err.message)
return jsonify(error=error, code=code), code | d6f9051bab504852720f657d04bc6afa72794047 | 3,655,543 |
from pyunitwizard.kernel import default_form, default_parser
from pyunitwizard import convert as _convert, get_dimensionality as _get_dimensionality
from typing import Dict
def dimensionality(quantity_or_unit: str) -> Dict[str, int]:
""" Returns the dimensionality of the quantity or unit.
Parameters
... | 4c334c6283a57704036c414cfd52f79b875a93fc | 3,655,544 |
import re
def split_prec_rows(df):
"""Split precincts into two rows.
NOTE: Because this creates a copy of the row values, don't rely on total vote counts, just look at percentage.
"""
for idx in df.index:
# look for rows with precincts that need to be split
if re.search('\d{4}/\d{4}'... | 72ba424080b0ff3e04ecc5d248bc85b4f409167c | 3,655,545 |
def socfaker_elasticecsfields_host():
"""
Returns an ECS host dictionary
Returns:
dict: Returns a dictionary of ECS
host fields/properties
"""
if validate_request(request):
return jsonify(str(socfaker.products.elastic.document.fields.host)) | 41a2624eda28eae736398ece87aee2ee2028987c | 3,655,546 |
from textwrap import dedent
def _moog_writer(photosphere, filename, **kwargs):
"""
Writes an :class:`photospheres.photosphere` to file in a MOOG-friendly
format.
:param photosphere:
The photosphere.
:path filename:
The filename to write the photosphere to.
"""
def _get_x... | da5a952e15984aecd914ebcf9381900924fdeff1 | 3,655,547 |
def upcomingSplits(
symbol="",
exactDate="",
token="",
version="stable",
filter="",
format="json",
):
"""This will return all upcoming estimates, dividends, splits for a given symbol or the market. If market is passed for the symbol, IPOs will also be included.
https://iexcloud.io/docs/... | ae21f8c04bf7bf2eacd8b16aa62c9fae7750e042 | 3,655,548 |
def mu_model(u, X, U, k):
"""
Returns the utility of the kth player
Parameters
----------
u
X
U
k
Returns
-------
"""
M = X.T @ X
rewards = M @ u
penalties = u.T @ M @ U[:, :k] * U[:, :k]
return rewards - penalties.sum(axis=1) | 59bce1ce8617f0e11340d1c1ab18315fd81e6925 | 3,655,549 |
def tokenizer_init(model_name):
"""simple wrapper for auto tokenizer"""
tokenizer = AutoTokenizer.from_pretrained(model_name)
return tokenizer | c54accf802fcbcf1479ccb0745266a5182edb73b | 3,655,550 |
def insert_message(nick, message, textDirection):
"""
Insert record
"""
ins = STATE['messages_table'].insert().values(
nick=nick, message=message, textDirection=textDirection)
res = STATE['conn'].execute(ins)
ltr = 1 if textDirection == 'ltr' else 0
rtl = 1 if textDirection == 'rtl'... | 1163fab2342aa5e41b321055bbf75f4c23fbb031 | 3,655,551 |
from typing import Tuple
from typing import Dict
def process_metadata(metadata) -> Tuple[Dict[str, str], Dict[str, str]]:
""" Returns a tuple of valid and invalid metadata values. """
if not metadata:
return {}, {}
valid_values = {}
invalid_values = {}
for m in metadata:
key, valu... | fbd7affaa8743d6c45bb2a02067d737dac990eb4 | 3,655,552 |
def rightOfDeciSeperatorToDeci(a):
"""This function only convert value at the right side of decimal seperator to decimal"""
deciNum = 0
for i in range(len(a)):
deciNum += (int(a[i]))*2**-(i+1)
return deciNum | 14cfd187758836d329ac4778a30167ddece0f2a0 | 3,655,553 |
import torch
def conv(input, weight):
"""
Returns the convolution of input and weight tensors,
where input contains sequential data.
The convolution is along the sequence axis.
input is of size [batchSize, inputDim, seqLength]
"""
output = torch.nn.functional.conv1d(input... | e213be11c423ff63a1ebffda55331298fcf53443 | 3,655,554 |
import torch
def irr_repr(order, alpha, beta, gamma, dtype = None):
"""
irreducible representation of SO3
- compatible with compose and spherical_harmonics
"""
cast_ = cast_torch_tensor(lambda t: t)
dtype = default(dtype, torch.get_default_dtype())
alpha, beta, gamma = map(cast_, (alpha, b... | ff054a05c2d79a4dcfc903116cefdfce4fa56c8f | 3,655,555 |
from typing import List
from typing import Optional
def label_to_span(labels: List[str],
scheme: Optional[str] = 'BIO') -> dict:
"""
convert labels to spans
:param labels: a list of labels
:param scheme: labeling scheme, in ['BIO', 'BILOU'].
:return: labeled spans, a list of tupl... | 01e3a1f3d72f8ec0b1cfa2c982fc8095c06c09f8 | 3,655,556 |
from typing import Optional
def get_storage_account(account_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStorageAccountResult:
"""
The storage account.
:param str account... | c818e801d152f2b11bedac42bcefe322b94ab16e | 3,655,557 |
def format_and_add(graph, info, relation, name):
"""
input: graph and three stirngs
function formats the strings and adds to the graph
"""
info = info.replace(" ", "_")
name = name.replace(" ", "_")
inf = rdflib.URIRef(project_prefix + info)
rel = rdflib.URIRef(project_prefix + rela... | abbe87b923d4ac37262e391a7d9a878b65e4ff41 | 3,655,558 |
import os
def get_dataset(dir, batch_size, num_epochs, reshape_size, padding='SAME'):
"""Reads input data num_epochs times. AND Return the dataset
Args:
train: Selects between the training (True) and validation (False) data.
batch_size: Number of examples per returned batch.
num_epochs: Num... | cdb47a4a4fcbe01f53a878c95755a711906224b1 | 3,655,559 |
def to_log_space(p:float, bounds: BOUNDS_TYPE):
""" Interprets p as a point in a rectangle in R^2 or R^3 using Morton space-filling curve
:param bounds [ (low,high), (low,high), (low,high) ] defaults to unit cube
:param dim Dimension. Only used if bounds are not supplied.
Very ... | 2ab53687481100bda229456b8aa5fad4d8ef817d | 3,655,560 |
def rsi_tradingview(ohlc: pd.DataFrame, period: int = 14, round_rsi: bool = True):
""" Implements the RSI indicator as defined by TradingView on March 15, 2021.
The TradingView code is as follows:
//@version=4
study(title="Relative Strength Index", shorttitle="RSI", format=format.price, prec... | 5b9d96d5e174d6534c2d32a3ece83a5fb09b28ba | 3,655,561 |
def bin_by(x, y, nbins=30):
"""Bin x by y, given paired observations of x & y.
Returns the binned "x" values and the left edges of the bins."""
bins = np.linspace(y.min(), y.max(), nbins+1)
# To avoid extra bin for the max value
bins[-1] += 1
indicies = np.digitize(y, bins)
output = []
... | ff0f9e79f3561cabf2a6498e31a78836be38bfb3 | 3,655,562 |
def calc_stats_with_cumsum(df_tgt, list_tgt_status, dict_diff, calc_type=0):
""" Calculate statistics with cumulative sum of target status types. \n
"dict_diff" is dictionaly of name key and difference value. ex) {"perweek": 7, "per2week": 14} \n
calc_type=0: calculate for each simulation result. \n... | 2dcdd95b8723f250a24afae548b8fd4ce9b5f51c | 3,655,563 |
def _normalize_handler_method(method):
"""Transforms an HTTP method into a valid Python identifier."""
return method.lower().replace("-", "_") | aad23dba304ba39708e4415de40019479ccf0195 | 3,655,564 |
def getContentType(the_type):
"""
Get the content type based on the type name which is in settings
:param the_type:
:return:
"""
if the_type not in settings.XGDS_MAP_SERVER_JS_MAP:
return None
the_model_name = settings.XGDS_MAP_SERVER_JS_MAP[the_type]['model']
splits = the_model... | 25031eb0dce8fe7828f94bdbc99d5c574f0e5ea6 | 3,655,565 |
import scipy
import math
import numpy
def calculateGravityAcceleration(stateVec, epoch, useGeoid):
""" Calculate the acceleration due to gravtiy acting on the satellite at
a given state (3 positions and 3 velocities). Ignore satellite's mass,
i.e. use a restricted two-body problem.
Arguments
... | a2ea0ff1c8feb9f0a678911130e3ca6e96838b7c | 3,655,566 |
import math
def points_on_line(r0, r1, spacing):
"""
Coordinates of points spaced `spacing` apart between points `r0` and `r1`.
The dimensionality is inferred from the length of the tuples `r0` and `r1`,
while the specified `s... | eb2795cba55566823632c75b7a72f34731b5e36e | 3,655,567 |
def index() -> Response:
"""
Return application index.
"""
return APP.send_static_file("index.html") | 37d299ec548fe4f83d8f55f063e3bf9f5fb64c4e | 3,655,568 |
def compare_files(og_maxima,new_maxima, compare_file, until=100, divisor=1000):
"""
given input of the maxima of a graph, compare it to the maxima from data100.txt
maxima will be a series of x,y coordinates corresponding to the x,y values of a maximum from a file.
First see if there is a maxima with t... | 86fe2ffd02785d41284b8edfef44d0dc0e097c90 | 3,655,569 |
import _datetime
def parseDatetimetz(string, local=True):
"""Parse the given string using :func:`parse`.
Return a :class:`datetime.datetime` instance.
"""
y, mo, d, h, m, s, tz = parse(string, local)
s, micro = divmod(s, 1.0)
micro = round(micro * 1000000)
if tz:
offset = _tzoffse... | ce95f42f568b50ffcdc0084dc659a1d5fd0233ff | 3,655,570 |
def median_ratio_flux(spec, smask, ispec, iref, nsig=3., niter=5, **kwargs):
""" Calculate the median ratio between two spectra
Parameters
----------
spec
smask:
True = Good, False = Bad
ispec
iref
nsig
niter
kwargs
Returns
-------
med_scale : float
Medi... | 28872a548ce7569f17f155242aaf4377bf0c1b63 | 3,655,571 |
def get_tags_from_event():
"""List of tags
Arguments:
event {dict} -- Lambda event payload
Returns:
list -- List of AWS tags for use in a CFT
"""
return [
{
"Key": "OwnerContact",
"Value": request_event['OwnerContact']
}
] | e7a0f7da62a4904dbfb716c57b6811053aff3497 | 3,655,572 |
from typing import List
def _verify(symbol_table: SymbolTable, ontology: _hierarchy.Ontology) -> List[Error]:
"""Perform a battery of checks on the consistency of ``symbol_table``."""
errors = _verify_there_are_no_duplicate_symbol_names(symbol_table=symbol_table)
if len(errors) > 0:
return errors... | da9dd12f01107a0c0ea1a8b2df1aa2fb543391ab | 3,655,573 |
def gsl_eigen_symmv_alloc(*args, **kwargs):
"""gsl_eigen_symmv_alloc(size_t n) -> gsl_eigen_symmv_workspace"""
return _gslwrap.gsl_eigen_symmv_alloc(*args, **kwargs) | 54384bfa9787b9a337ad3b9e2d9ea211769238d4 | 3,655,574 |
def add_poll_answers(owner, option):
"""
Add poll answer object. Matching user and option is considered same.
:param owner: User object.
:param option: Chosen poll option.
:return: Poll answer object, Boolean (true, if created).
"""
'''
owner = models.ForeignKey(User, related_name='poll_... | ac667fbfb47aeb7d2450a3d698b0b678c3bdfdbc | 3,655,575 |
def calculate_rrfdi ( red_filename, nir_filename ):
"""
A function to calculate the Normalised Difference Vegetation Index
from red and near infrarred reflectances. The reflectance data ought to
be present on two different files, specified by the varaibles
`red_filename` and `nir_filename`. The file... | 3b8f4d7eadceb38b7f874bfe0a56827f7a8aab09 | 3,655,576 |
import sys
def retry_on_failure(retries=NO_RETRIES):
"""Decorator which runs a test function and retries N times before
actually failing.
"""
def logfun(exc):
print("%r, retrying" % exc, file=sys.stderr) # NOQA
return retry(exception=AssertionError, timeout=None, retries=retries,
... | cfd1427001036597e99cb27b3ce16b4edcfae8ba | 3,655,577 |
import argparse
def command_line():
"""Generate an Argument Parser object to control the command line options
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-w", "--webdir", dest="webdir",
help="make page and plots in DIR", metavar="DIR",
... | f1463f291cc99acc66cb1fb46d1be0a7ef60e9ca | 3,655,578 |
import re
def strip_price(header_list):
"""input a list of tag-type values and return list of strings with surrounding html characters removed"""
match_obs = []
regex = '\$(((\d+).\d+)|(\d+))'
string_list = []#['' for item in range(len(header_list))]
for item in range(len(header_list)):
... | 7b3d90416e44f8aa61ababc0e7b68f82ae754413 | 3,655,579 |
import functools
def module(input, output, version):
"""A decorator which turn a function into a module"""
def decorator(f):
class Wrapper(Module):
def __init__(self):
super().__init__(input, output, version)
@property
def name(self):
... | b7d5afcaa8fa52411024f84f979891d19ccf60c0 | 3,655,580 |
def compile_modules_to_ir(
result: BuildResult,
mapper: genops.Mapper,
compiler_options: CompilerOptions,
errors: Errors,
) -> ModuleIRs:
"""Compile a collection of modules into ModuleIRs.
The modules to compile are specified as part of mapper's group_map.
Returns the IR of the modules.
... | e2ea8a87a1ed2450e4c8ed99c7ca8a3142568f45 | 3,655,581 |
def minutes_to_restarttime(minutes) :
"""
converts an int meaning Minutes after midnight into a
restartTime string understood by the bos command
"""
if minutes == -1 :
return "never"
pod = "am"
if minutes > 12*60 :
pod = "pm"
minutes -= 12*60
time = "%d:%02d %s"... | 6d7807cebb7a474553dda8eadfd27e5ce7b2a657 | 3,655,582 |
import tqdm
def ccm_test(x, y,emb_dim = "auto", l_0 = "auto", l_1 = "auto", tau=1, n=10,mean_num = 10,max_dim = 10):
"""
estimate x from y to judge x->y cause
:param x:
:param y:
:param l_0:
:param l_1:
:param emb_dim:
:param tau:
:param n:
:return:
"""
if em... | c03a05e62df36910ea05e361c9683b60befc1b9c | 3,655,583 |
def make_indiv_spacing(subject, ave_subject, template_spacing, subjects_dir):
"""
Identifies the suiting grid space difference of a subject's volume
source space to a template's volume source space, before a planned
morphing takes place.
Parameters:
-----------
subject : str
Sub... | cbe5120093fdf78913c2386820d3388aca0724d1 | 3,655,584 |
def sqlpool_blob_auditing_policy_update(
cmd,
instance,
state=None,
storage_account=None,
storage_endpoint=None,
storage_account_access_key=None,
storage_account_subscription_id=None,
is_storage_secondary_key_in_use=None,
retention_days=None,
... | e99013545172eb03ad5dddeefdb0b36b7bb2edd7 | 3,655,585 |
from typing import Optional
import os
def from_system() -> Optional[Config]:
"""
Config-factory; producing a Config based on environment variables and when
environment variables aren't set, fall back to the ``cij_root`` helper.
"""
conf = Config()
# Setup configuration using environment vari... | 6fb093d33ab44851b8027642b26f0e116b17af56 | 3,655,586 |
def format_search_filter(model_fields):
"""
Creates an LDAP search filter for the given set of model
fields.
"""
ldap_fields = convert_model_fields_to_ldap_fields(model_fields);
ldap_fields["objectClass"] = settings.LDAP_AUTH_OBJECT_CLASS
search_filters = import_func(settings.LDAP_AUTH_FORMA... | b6c5c17b566c583a07ef5e9f3ec61cb868f6f8ab | 3,655,587 |
def multiprocess(func=None, pycsp_host='', pycsp_port=None):
""" @multiprocess(pycsp_host='', pycsp_port=None)
@multiprocess decorator for making a function into a CSP MultiProcess factory.
Each generated CSP process is implemented as a single OS process.
All objects and variables provided to multipro... | ec1d5c14a7eb60af0cd351c15c1ec0724e577fb0 | 3,655,588 |
def normalize_img(img):
"""
normalize image (caffe model definition compatible)
input: opencv numpy array image (h, w, c)
output: dnn input array (c, h, w)
"""
scale = 1.0
mean = [104,117,123]
img = img.astype(np.float32)
img = img * scale
img -= mean
img = np.transpose(img, ... | dac9ec8c942d70fb98f0b0989e9643f80dde5448 | 3,655,589 |
from typing import List
from typing import Any
def pages(lst: List[Any], n: int, title: str, *, fmt: str = "```%s```", sep: str = "\n") -> List[discord.Embed]:
# noinspection GrazieInspection
"""
Paginates a list into embeds to use with :class:disputils.BotEmbedPaginator
:param lst: the list t... | f8d9471f2d254b63754128a2e2762520f858edbd | 3,655,590 |
import re
def Substitute_Percent(sentence):
"""
Substitutes percents with special token
"""
sentence = re.sub(r'''(?<![^\s"'[(])[+-]?[.,;]?(\d+[.,;']?)+%(?![^\s.,;!?'")\]])''',
' @percent@ ', sentence)
return sentence | 61bc6970af09703ef018bfcc9378393241ae21ed | 3,655,591 |
def ready_df1(df):
"""
This function prepares the dataframe for EDA.
"""
df = remove_columns(df, columns=[ 'nitrogen_dioxide',
'nitrogen_dioxide_aqi',
'sulfur_dioxide',
'sulfur_dioxide_aqi',... | 3776c571d3eabb39ce27017ac1481e2bd469f68c | 3,655,592 |
def _wrap(func, args, flip=True):
"""Return partial function with flipped args if flip=True
:param function func: Any function
:param args args: Function arguments
:param bool flip: If true reverse order of arguments.
:return: Returns function
:rtype: function
"""
@wraps(func)
def ... | 9ac5a814840f821260d46df64b60cd6d71185dbb | 3,655,593 |
def compute_kkt_optimality(g, on_bound):
"""Compute the maximum violation of KKT conditions."""
g_kkt = g * on_bound
free_set = on_bound == 0
g_kkt[free_set] = np.abs(g[free_set])
return np.max(g_kkt) | 216cf110d64d1fd8ec89c0359ebaa9b4e4dcc773 | 3,655,594 |
def replace_cipd_revision(file_path, old_revision, new_revision):
"""Replaces cipd revision strings in file.
Args:
file_path: Path to file.
old_revision: Old cipd revision to be replaced.
new_revision: New cipd revision to use as replacement.
Returns:
Number of replaced occurrences.
Raises:
... | f429e74f0dd7180ab4bf90d662f8042b958b81f8 | 3,655,595 |
def spectral_derivs_plot(spec_der, contrast=0.1, ax=None, freq_range=None,
fft_step=None, fft_size=None):
"""
Plot the spectral derivatives of a song in a grey scale.
spec_der - The spectral derivatives of the song (computed with
`spectral_derivs`) or the song itself... | 5b683d8c49e9bad2fd1fa029af6bc5660bc0e936 | 3,655,596 |
from operator import add
from operator import sub
def scale_center(pnt, fac, center):
"""scale point in relation to a center"""
return add(scale(sub(pnt, center), fac), center) | f69ca54e25d5eb8008b8f08c40500f236005e093 | 3,655,597 |
def gopherize_feed(feed_url, timestamp=False, plug=True):
"""Return a gophermap string for the feed at feed_url."""
return gopherize_feed_object(feedparser.parse(feed_url), timestamp, plug) | aaf4d35044c873e7d0f1a43c4d001ebe5e30714b | 3,655,598 |
def first_sunday_of_month(datetime: pendulum.DateTime) -> pendulum.DateTime:
"""Get the first Sunday of the month based on a given datetime.
:param datetime: the datetime.
:return: the first Sunday of the month.
"""
return datetime.start_of("month").first_of("month", day_of_week=7) | 88c517d1d38785c0d8f9c0f79f3d34199dfceb1e | 3,655,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.