content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def synth(**kwargs):
"""return ricker wavelet synthetic data"""
# defaults
if 'pol' not in kwargs: kwargs['pol'] = 0.
if 'delta' not in kwargs: kwargs['delta'] = 1.
if 'split' not in kwargs: kwargs['split'] = []
if 'noise' not in kwargs: kwargs['noise'] = 0.001
if 'nsamps' not in kw... | 5,293,500 |
def set_need_appearances(pdf_writer, bool_val):
"""
Sets property _root_object["/AcroForm"]["/NeedAppearances"] of the given
PdfFileWriter instance to a Boolean value. Setting it to True can be
necessary to make the text fields' content visible in the file produced
by pdf_writer.
Args:
bool_val (bool): the Boo... | 5,293,501 |
def gstruc_add(tstr):
""" Add to the GSTRUC tracking structure."""
# data: large list of data, one element per position (with padding)
# count: the number of elements in DATA we're using currently, also
# the index of the next one to start with.
# x/y: the x/y position for the gauss... | 5,293,502 |
def tmp_config_file(dict_: dict) -> str:
"""
Dumps dict into a yaml file that is saved in a randomly named file. Used to as config file to create
ObservatoryConfig instance.
:param dict_: config dict
:return: path of temporary file
"""
content = yaml.safe_dump(dict_).replace("'!", "!").repla... | 5,293,503 |
def get_bootstrap_assets(self, platform=None):
"""
:param self:
:param platform: optional, defaults to current build's platform
:return: Asset type requested for the supplied platform in bootstrap.cfg
"""
if platform is None:
platform = self.env['PLATFORM']
bootstrap_cfg = self.engin... | 5,293,504 |
def calc_checksum(packet):
"""
Calculates the checksum of a given packet.
This function is only for use in environments where 16-bit words are used.
:param packet: A list with 16-bit numbers as Integers.
:return: The checksum of the packet as Integer
"""
# validate the input
try:
... | 5,293,505 |
def interpolate_with_degree(nodes, values, deg, use_mp=False):
"""Compute a rational function which interpolates the given nodes/values
with given degree `m` of the numerator and `n` of the denominator.
Args:
nodes (array): the interpolation nodes
values (array): the values at the interpola... | 5,293,506 |
def preprocess_input(title, overview, vectorizer):
"""
Extract TF-IDF features from a single title and overview input.
:param title: Str. Movie title.
:param overview: Str. Movie plot.
:param vectorizer: Fitted sklearn.feature_extraction.text.TfidfVectorizer object.
:return: Tf-IDF features matr... | 5,293,507 |
def _generate_image_info(im, params):
""""generate url and tokens for image"""
image = ee.Image(im)
if "sld_style" in params:
m = image.sldStyle(params.get("sld_style"))
del params["sld_style"]
elif "palette" in params:
m = image.visualize(
**{
"min":... | 5,293,508 |
def forced_attribute_type(name: str, type_accessor: typing.Callable[[], typing.Type], may_subclass=False, source_source=None):
"""
Forced a certain data type on an object attribute
Not validated, but allows optimisations to happen!
Can speed up calls by a lot
"""
def annotation(target: typing.... | 5,293,509 |
def _setup_fig(ncols, nrows, figsize_width, figsize_height):
"""
Parameters:
-----------
ncols
Number of columns in the figure.
type: int
nrows
Number of rows in the figure.
type: int
figsize_width
Scaler adjustment of figure width
default: 1
... | 5,293,510 |
def unconfirmed():
"""Catch users with unconfirmed emails."""
if current_user.is_anonymous or current_user.confirmed:
return redirect(url_for('main.index'))
return render_template('account/unconfirmed.html') | 5,293,511 |
def local_str(arg):
"""
Преобразует arg в unicode, а затем в строку с кодировкой для вывода на текущем терминале
"""
import sys
e = sys.stdout.encoding
if not e:
e='cp1251'
return unicode(arg).encode(e, 'ignore') | 5,293,512 |
def computeAlleleFrequency (f_C, f_T):
"""3
f_C = minor allele count
f_T = major allele count
minor_allele_frequency = f_C/ (f_C+f_T)
7"""
minor_allele_frequency = f_C/(f_C+f_T)
return minor_allele_frequency | 5,293,513 |
def adjust_learning_rate(optimizer, gamma, step):
"""Sets the learning rate to the initial LR decayed by 10 at every specified step
# Adapted from PyTorch Imagenet example:
# https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
global lr
lr = lr * (gamma ** (step))
for param_... | 5,293,514 |
def test_user_level_overrides_base_level():
"""Test that user level overrides base level in configuration."""
base_config_file = os.path.join(os.path.dirname(__file__), "rsc", "config.yaml")
user_config_file = os.path.join(
os.path.dirname(__file__), "rsc", "user-override.yaml"
)
config = C... | 5,293,515 |
def handle_detected_heads(np_img_set, position_server):
"""Read data in from global detected_heads_queue if any and does something
with it based on inputs."""
global prev_head_data
queue_mutex.acquire()
global detected_heads_queue # Do I need global here?
if len(detected_heads_queue) == 0: # Dra... | 5,293,516 |
def update_m(obj, ia, rcut=9.0, pbc=None):
"""
retrieve local structure around atom `ia
for periodic systems (or very large system)
"""
zs, coords, c = obj
v1, v2, v3 = c
vs = ssd.norm(c, axis=0)
nns = []
for i,vi in enumerate(vs):
n1_doulbe = rcut/li
n1 = int(n1_dou... | 5,293,517 |
def analyze(input):
""" I analyze the input audio file.
"""
analyzed = {}
rate, snd = wavfile.read(input)
snd = snd / (2. ** 15)
entire_chan = snd[:, 0]
analyzed['duration'] = snd.shape[0] / rate
entire_nb_samples = len(entire_chan)
nb_samples = entire_nb_samples / NB_POINTS
#... | 5,293,518 |
def crext_TruncatedHMAC():
"""Create a Truncated HMAC extension."""
return ExtensionType.truncated_hmac.value + lenprefix(b"") | 5,293,519 |
def microcycle_days(weekly_training_days, weeks):
"""generates indexes of training days during the weeks"""
training_day_indexes = []
for w in range(weeks):
for d in weekly_training_days:
training_day_indexes.append(w * 7 + d.value)
return training_day_indexes | 5,293,520 |
def reduced_supercell_vectors(ab, n):
"""
Returns all possible reduced in-plane lattice vectors and
transition matrices for the given starting unit cell lattice
vectors(ab) and the supercell size n
"""
uv_list = []
tm_list = []
for r_tm in get_trans_matrices(n):
uv = get_uv(ab, r... | 5,293,521 |
def make_polygon_from_coords(coords: List[float]):
"""
Creates a `Polygon` instance using the passed in coordinates:
`[x1 y1 x2 y2 ... xn yn]`.
It raises a `ValueError` if the coordinates list does't have
an even number of entries.
:param coords: list of the coordinates of the vertices
:re... | 5,293,522 |
def rainbow(strip, wait_ms=20):
"""Draw rainbow that fades across all pixels at once."""
if (menu.screensaver_is_running == True):
menu.screensaver_is_running = False
time.sleep(1)
fastColorWipe(ledstrip.strip, True)
menu.t = threading.currentThread()
j = 0
menu.screensaver_i... | 5,293,523 |
def test_inspect_semi_structured_datatypes(engine_testaccount):
"""
Inspects semi-structured data type columns
"""
table_name = "test_variant2"
metadata = MetaData()
test_variant = Table(
table_name,
metadata,
Column('id', Integer, primary_key=True),
Column('va', ... | 5,293,524 |
def conf(repo):
"""Configures the config file for the nordb. Give the username option your postgres username so the program can use your postgres-databased."""
usernameUtilities.confUser() | 5,293,525 |
def fibonacciMemoization(n: int):
"""
:param n: range numbers to be visited in fibonacci series
:return: nth value in the fibonacci sequence
"""
global fibb_memo
if n in fibb_memo:
return fibb_memo[n]
if n <= 2:
return 1
fibb_memo[n] = fibonacciMemoization(n - 1) + fi... | 5,293,526 |
def broken_paired_reader(screed_iter, min_length=None,
force_single=False, require_paired=False):
"""Read pairs from a stream.
A generator that yields singletons and pairs from a stream of FASTA/FASTQ
records (yielded by 'screed_iter'). Yields (n, is_pair, r1, r2) where
'r2' i... | 5,293,527 |
def scatter(data, **kwargs):
"""I dont like this. Viewing code should not reside in model logic."""
fig, ax = plt.subplots(1, 1, figsize=(6, 5))
ax.scatter(*data.cpu().numpy().T[:2], **kwargs)
plt.close()
return fig | 5,293,528 |
def build_training_model_component():
"""
Build training model component
Returns:
training_model_component: training model component
"""
model_training_stage = []
rfor = RandomForestClassifier(featuresCol=FEATURES, labelCol=TARGET, seed=RANDOM_SEED)
model_training_stage.append(rfor)
... | 5,293,529 |
def cka(k_x: torch.Tensor, k_y: torch.Tensor, centered: bool = False, unbiased: bool = True) -> torch.Tensor:
"""Compute Centered Kernel Alignment (CKA).
:param k_x: n by n values of kernel applied to all pairs of x data
:param k_y: n by n values of kernel on y data
:param centered: whether or not at l... | 5,293,530 |
def _run_dag_and_wait():
"""Run and wait for the DAG to finish.
Returns:
state: The end state of the DAG.
"""
artifacts_path = os.path.join(prow.get_gcs_output(), "artifacts")
logging.info("Artifacts will be saved to: %s", artifacts_path)
conf = {
"PULL_NUMBER": os.getenv("PULL_NUMBER", ""),
"... | 5,293,531 |
def columns(table, missing=None):
"""
Construct a :class:`dict` mapping field names to lists of values. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]]
>>> cols = etl.columns(table)
>>> cols['foo']
['a', 'b', 'b']
>>> cols... | 5,293,532 |
def get_output_encoding():
""" Get the output encoding used for output to management commands.
:return: ``sys.stdout.encoding``
"""
return sys.stdin.encoding or sys.getdefaultencoding() or DEFAULT_ENCODING | 5,293,533 |
def _project_vertices(v, w, h, cam_r, cam_t):
"""projects vertices onto image plane"""
V = ch.array(v)
U = ProjectPoints(v=V, f=[w * 2, w * 2], c=[w / 2., h / 2.], # camera intrinsics
k=ch.zeros(5), t=cam_t, rt=cam_r)
return U | 5,293,534 |
def check_overlapping(features):
"""Check for elements of `features` with overlapping ranges. In the
case of overlap, print an informative error message and return
names and positions of overlapping features.
"""
features = features[:]
overlapping = []
for i in range(len(features)-1):
... | 5,293,535 |
def predict(x, P, F=1, Q=0, u=0, B=1, alpha=1.):
""" Predict next position using the Kalman filter state propagation
equations.
Parameters
----------
x : numpy.array
State estimate vector
P : numpy.array
Covariance matrix
F : numpy.array()
State Transition matrix
... | 5,293,536 |
def update_hosts(hosts_list=None, user='root'):
"""
@param_post{hosts_list}
@param_post{user} (optional, default: @val{root})
"""
if user is None:
missing_parameter('user')
if hosts_list is None:
missing_parameter('host_list')
try:
f = open("/etc/hosts", "r")
... | 5,293,537 |
def get_file_to_load():
"""Open a popup window to select a file to load"""
return sg.popup_get_file(
'Select a file to open',
EVENT_OPEN,
initial_folder=USER_HOME,
no_window=True,
default_extension=EDITOR_EXTENSION,
) | 5,293,538 |
def validate_bag(bag, environ=None):
"""
Pass the :py:class:`bag <tiddlyweb.model.bag.Bag>` to each of
the functions in ``BAG_VALIDATORS``, in order, either changing
the content of the bags's attributes, or if some aspect of the
bag can not be accepted raising :py:class:`InvalidBagError`.
``BAG... | 5,293,539 |
def renew(alias, sub_nas, args):
"""
:param alias:
:param sub_nas:
\n:param args [expiration, type]:
\n:returns new expiration if success or False if failed:
\nif sub_nas defined passes call to sub_nas otherwise
we try to renew alias
"""
# handle sub_nas first
nargs = len(args)
... | 5,293,540 |
def create_train_op(total_loss,
optimizer,
global_step=_USE_GLOBAL_STEP,
update_ops=None,
variables_to_train=None,
transform_grads_fn=None,
summarize_gradients=False,
gate_gradient... | 5,293,541 |
async def trade(exchanges: list, market_name, amount):
"""
When there is a price disparity for a cryptocurrency market on two separate exchanges, buys the currency on the
exchange with the lowest asking price and short sells on the exchange with the highest bid price. This ensures
market neutrality and ... | 5,293,542 |
def generate_sample_sheet(sample_list_file,
barcode_dict_file,
sample_sheet_template,
platform,
output_dir,
warnings=False):
"""
Create a sample sheet to be used by bcl2fasq file fro... | 5,293,543 |
def does_asyncio(func):
"""Simple decorator for running a test inside an asyncio event loop."""
def wrapper(*args, **kwargs):
get_event_loop().run_until_complete(func(*args, **kwargs))
return wrapper | 5,293,544 |
def correct_baseline(raw_data, mode, smoothing=True, transform=False,
**kwargs):
"""
Calculate baseline data for raw_data with generate_baseline(...).
Takes the same arguments like generate_baseline, for details see
docstring of generate_baseline.
"""
return raw_data - gene... | 5,293,545 |
def article(*args, **kwargs):
"""
The HTML <article> element represents a self-contained composition
in a document, page, application, or site, which is intended to be
independently distributable or reusable (e.g., in
syndication). This could be a forum post, a magazine or newspaper
article, a b... | 5,293,546 |
def validate(business: Business, cod: Dict) -> Error:
"""Validate the Change of Directors filing."""
if not business or not cod:
return Error(HTTPStatus.BAD_REQUEST, [{'error': babel('A valid business and filing are required.')}])
msg = []
msg_directors_addresses = validate_directors_addresses(... | 5,293,547 |
def index():
"""
Basic index view, listing online users.
"""
msg = 'Online: %s' % ', '.join(get_online_users())
return make_response(msg) | 5,293,548 |
def updateLastRun():
"""
Call to DB - update last run time
"""
swDB = switchdb.DB()
print("Updating last run time in DB...")
swDB.updateLastRun()
swDB.close() | 5,293,549 |
def show():
""" Shows all the figure windows that have been created thus far, and
creates a GUI main loop. This function is useful in scripts to show plots
and keep their windows open, and has no effect when used from the
interpreter prompt.
"""
from traits.etsconfig.api import ETSConfig
fr... | 5,293,550 |
def pixel2wave (pix, c, model='linear') :
"""
Inverse function for a given pixel(wave) model.
Converts a pixel position pix into a wavelength w using one of several invertable models:
'linear','quadratic','cubic' w(pix) = invert_polynomial(pix,c) because pix(w) = c[0]+c[1]*w+...
'exp' w(pix) = -ln[(pix-c2)... | 5,293,551 |
def compute_level(id, tree):
"""
compute the level of an id in a tree
"""
topic = tree[id]
level = 0
while (id != 0):
level += 1
id = topic['parent']
topic = tree[id]
return(level) | 5,293,552 |
def is_db_weather(weather_path):
"""True, if the ``weather_path`` is one of the pre-installed weather files that came with the CEA"""
weather_name = get_db_weather_name(weather_path)
if weather_name in LOCATOR.get_weather_names():
# could still be a custom weather file...
db_weather_path = L... | 5,293,553 |
def test_xarray(
dask_client, # pylint: disable=redefined-outer-name,unused-argument
):
"""Test xarray creation."""
ds = create_test_dataset()
xr1 = ds.to_xarray()
assert isinstance(xr1, xarray.Dataset)
xr2 = dataset.Dataset.from_xarray(xr1).to_xarray()
assert xr1 == xr2 | 5,293,554 |
def ReadDirectoryFromFile(file_name, hub_map):
"""directory_tools.ReadDirectory
INPUTS:
- file_name -- name of the file containing the MemberHub directory dump
- hub_map -- dictionary that maps hub names to hub IDs
OUTPUTS:
- directory -- list of families read from the MemberHub directory dump... | 5,293,555 |
def flatten(sequence: Sequence[Any], depth: Optional[int] = -1, **kwargs) -> Union[List[Any], Any]:
"""
Receives values, whether arrays of values, regardless of their shape and flatness
:param sequence: Is sequence of values.
:param depth: allows you to control a max depth, for example if you send a
... | 5,293,556 |
def change_four_variables_in_expr(latex_dict: dict) -> str:
"""
>>> latex_dict = {}
>>> latex_dict['input'] = [{'LHS': parse_latex(''), 'RHS': parse_latex('')}]
>>> latex_dict['feed'] = [parse_latex('')]
>>> latex_dict['output'] = [{'LHS': parse_latex(''), 'RHS': parse_latex('')}]
>>> change_fou... | 5,293,557 |
def polyglot_1st_pronoun(s):
"""Get first pronoun from the sentence.
Parameters
----------
:param s: string
Sentence
Returns
-------
:returns: string
first pronoun
"""
pronouns = polyglot_pronouns(s)
return pronouns[0] | 5,293,558 |
def test_attributes_from_environment_variables():
"""Test that the LSF environment takes the attributes from the environment variables."""
env = LSFEnvironment()
assert env.creates_processes_externally
assert env.main_address == "10.10.10.0"
assert env.main_port == 10234
assert env.world_size() ... | 5,293,559 |
def filter_by_pvalue_strand_lag(ratios, pcutoff, pvalues, output, no_correction, name, singlestrand):
"""Filter DPs by strang lag and pvalue"""
if not singlestrand:
zscore_ratios = zscore(ratios)
ratios_pass = np.where(np.bitwise_and(zscore_ratios > -2, zscore_ratios < 2) == True, True, False)
... | 5,293,560 |
def write_user_playlist(username, text_file=None):
""" Write user playlists to text_file """
links = get_playlists(username=username)
playlist = internals.input_link(links)
return write_playlist(playlist, text_file) | 5,293,561 |
def is_float(db_type):
"""Return True if the database type is a float supported type, False otherwise.
"""
return db_type in ACCEPTED_FLOAT_DB_TYPES | 5,293,562 |
def generate_papernot():
"""
Train the second/distilled model using uncertaity array
:return: distilled model
"""
sigmas = np.load(PROJ_PATH + 'mnist_papernot/sigmas.npz')['sigmas']
start = time()
model_papernot = train_papernot(sigmas)
end = time()
print("Papernot training costs {}s... | 5,293,563 |
def inverse_stft_window_fn(frame_step,
forward_window_fn=window_ops.hann_window,
name=None):
"""Generates a window function that can be used in `inverse_stft`.
Constructs a window that is equal to the forward window with a further
pointwise amplitude cor... | 5,293,564 |
def check_readiness(register: Register):
"""
Helper to raise an exception if the register is not ready to be used.
"""
if not register.is_ready():
msg = "The given RSF does not have enough information to be used in \
this command."
raise CommandError(msg) | 5,293,565 |
def Vegas(integrand, ndim, userdata=NULL,
epsrel=EPSREL, epsabs=EPSABS, flags=0, ncomp=1, seed=None,
mineval=MINEVAL, maxeval=MAXEVAL, nstart=NSTART,
nincrease=NINCREASE, nbatch=NBATCH,
gridno=GRIDNO, statefile=NULL, nvec=1):
"""
*nstart*: the number of integrand evaluations per iteration to start... | 5,293,566 |
def human_annotations(human_file):
"""
Generates JSON from TSV files
"""
zipped_rows = get_rows_from_file(human_file, '\r')
# Too many processes causes the http requests causes the remote to respond with error
pool = mp.Pool(processes=1)
annotations = pool.map(human_single_annotation, zipped... | 5,293,567 |
def eval_gather_inds(len_, num_samples=7):
""" get the gather indices """
inds = torch.arange(0, num_samples, dtype=torch.long)
mul = math.ceil(len_ / num_samples)
output = inds.repeat(mul)[:len_]
return output | 5,293,568 |
def from_bin(bin_):
"""
Convert a string-representation of binary into a list
of integers.
:param str bin_: String representation of binary data (ex: "10110111")
:return: iterator over integers
"""
for chunk in _chunks(bin_, 8):
yield int(chunk, 2) | 5,293,569 |
def vap_lapserate(temp,pres,dvap=None,chkvals=False,chktol=_CHKTOL,
dvap0=None,chkbnd=False,mathargs=None):
"""Calculate water vapour adiabatic lapse rate.
Calculate the adiabatic lapse rate of water vapour at temperature
and pressure.
:arg float temp: Temperature in K.
:arg float pres... | 5,293,570 |
def none_or_valid_float_value_as_string(str_to_check):
"""
Unless a string is "none", tries to convert it to a float and back to check
that it represents a valid float value. Throws ValueError if type
conversion fails. This function is only needed because the MATLAB scripts
take some arguments eithe... | 5,293,571 |
def hunkify_lines(lines, context=3):
"""
Return a list of line hunks given a list of lines `lines`. The number of
context lines can be control with `context` which will return line hunks
surrounded with `context` lines before and after the code change.
"""
# Find contiguous line changes
rang... | 5,293,572 |
def _from_node_reqs_to_dask_resources(
node_reqs: NodeRequirements,
) -> Dict[str, Union[int, float]]:
"""Dask resources are set such as {"CPU": X.X, "GPU": Y.Y, "RAM": INT}"""
dask_resources = node_reqs.dict(exclude_unset=True, by_alias=True)
logger.debug("transformed to dask resources: %s", dask_resou... | 5,293,573 |
def check_time_signatures(time_signatures):
"""Check time signatures."""
assert len(time_signatures) == 1
assert time_signatures[0].numerator == 3
assert time_signatures[0].denominator == 8 | 5,293,574 |
def init_policy(states, Q):
"""
Define initial target policy of off-policy MC method
Parameters
----------
states : list of tuples
States consist of positions and velocity of agent
Q : dict
Dictionary with q values of each action in each state
Returns
-------
pi : d... | 5,293,575 |
def gaussianFWHM(x, fwhm, norm = 'area'):
"""
Calculate a Gaussian function.
Parameters
----------
x : array_like
Input array
fwhm : scalar
The full-width at half-maximum value.
norm : {'area', 'amplitude'}
The normalization convention. The default is 'area'. See... | 5,293,576 |
def S_moving_average_filter(_data_list, _smoothing=1):
"""
Returns moving average data without data lag.
Use the smoothing factor to get required overall smoothing where the smoothing factor is greater than zero.
"""
ma_data = []
ds = len(_data_list)
s = _smoothing
mas = int((ds... | 5,293,577 |
def StripKey(key):
"""Returns key with header, footer and all newlines removed."""
key = key.strip()
key_lines = key.split(b'\n')
if (not key_lines[0].startswith(b'-----')
or not key_lines[-1].startswith(b'-----')):
raise OpenSSLException(
'The following key does not appear to be in PEM format... | 5,293,578 |
def get_expanse_certificate_context(data):
"""
provide custom context information about certificate with data from Expanse API
"""
return {
"SearchTerm": data['search'],
"CommonName": data['commonName'],
"FirstObserved": data['firstObserved'],
"LastObserved": data['lastOb... | 5,293,579 |
def find_polygon_divisions(line_pts, polygon_pts, angle):
"""
Esta función primero genera una recta, con un ángulo definido por angle, en cada
punto contenido dentro de line_pts. Luego, para cada recta generada, encuentra la intersección
con cada mitad del polígono definido en polygon_pts. R... | 5,293,580 |
def factorial(x: i32) -> i32:
"""
Computes the factorial of `x`.
"""
if x < 0:
return 0
result: i32
result = 1
i: i32
for i in range(1, x+1):
result *= i
return result | 5,293,581 |
def parseargs(): # pragma: no cover
"""Sets up command-line arguments and parser
Parameters:
Returns: parser
Raises:
"""
parser = argparse.ArgumentParser(description='Metrics BeeGFS-Sqlite to elastic')
parser.add_argument("-f", "--cfgfile", help='Specify the config file (./sqlite2elastic.in... | 5,293,582 |
def convert_time(time_str):
"""Convert iso string to date time object
:param time_str: String time to convert
"""
try:
dt = datetime.strptime(time_str, "%Y-%m-%dT%H:%Mz")
return dt
except Exception:
return time_str | 5,293,583 |
def get_common_words():
"""Finds all common words in Redis"""
redis_connection = get_redis_connection()
words = redis_connection.keys(get_word_key("*"))
return set([word[2:].decode('utf-8') for word in words]) | 5,293,584 |
def pixel_neighbours_from_east(x=0, y=0, xlim=(-1, 1), ylim=(-1, 1),
clockwise=False):
"""
Returns coordinates neighbouring a single pixel in order from Easterly.
Pixels defined relative to (0,0):
(-1, 1) (0, 1) (1, 1)
... | 5,293,585 |
def run_wikifier(input_folder_path: str, wikifier_columns_df: pd.DataFrame, template_output_path: str):
"""
run wikifier on all table files(csv, xlsx, xls) and add the new wikifier results to "wikifier.csv" file
:param input_folder_path:
:param wikifier_columns_df:
:param template_output_path:
:... | 5,293,586 |
def main( arguments ):
"""! @brief run everything """
input_file = arguments[ arguments.index('--in')+1 ]
info_file = arguments[ arguments.index('--info')+1 ]
output_folder = arguments[ arguments.index('--out')+1 ]
offset = 33
window_size = 200
step = 100
if not os.path.exists( output_folder ):
os.makedirs... | 5,293,587 |
def complex_to_amp_phase(lookup_table):
"""
This constructs the function to convert from complex64 or 128 to AMP8I_PHS8I format data.
Parameters
----------
lookup_table : numpy.ndarray
Returns
-------
callable
"""
_validate_lookup(lookup_table)
def converter(data):
... | 5,293,588 |
def suck_out_formats(reporters):
"""Builds a dictionary mapping edition keys to their cite_format if any.
The dictionary takes the form of:
{
'T.C. Summary Opinion': '{reporter} {volume}-{page}',
'T.C. Memo.': '{reporter} {volume}-{page}'
...
}
In other ... | 5,293,589 |
def tsne_embeddings(X,
include_svd=True, n_svd_components=50,
tsne_params=dict()):
"""
Computes t-SNE embeddings of the tf-idf vectors. By default it first performs
a dimensionaly reduction using truncated SVD, as recommended in the scikit-learn
documentation. This indeed seems to give better re... | 5,293,590 |
def get_expected_return(
rewards: tf.Tensor,
gamma: float,
standardize: bool = True) -> tf.Tensor:
"""Compute expected returns per timestep."""
n = tf.shape(rewards)[0]
returns = tf.TensorArray(dtype=tf.float32, size=n)
# Start from the end of `rewards` and accumulate reward sums
# int... | 5,293,591 |
def main():
"""ansible-deploy endpoint function"""
start_ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
global logger
log_dir = os.getcwd()
logger = set_logging(log_dir, LOGNAME, start_ts)
if len(sys.argv) < 2:
logger.error("To fee arguments")
sys.exit(2)
subcommand... | 5,293,592 |
def check_response_body(response, expected_body):
"""
Checks that the response body is the expected one.
:param response: Response to be checked.
:param expected_body: Expected body of the response.
"""
resp = str(response.read())
#print "\n\n\n respuesta: "+ resp+ "\n\n\n"
#print "\n ... | 5,293,593 |
def update_structure(structure):
"""Update a defined structure"""
DB.session.merge(structure)
DB.session.commit() | 5,293,594 |
def cast_bytes(data, encoding='utf8'):
"""
Cast str, int, float to bytes.
"""
if isinstance(data, str) is True:
return data.encode(encoding)
elif isinstance(data, int) is True:
return str(data).encode(encoding)
elif isinstance(data, float) is True:
return str(data).enco... | 5,293,595 |
def main(argv):
"""
Creates a parquet file with tissue data.
:param list argv: the list elements should be:
[1]: Parquet file path with raw sample data
[2]: Output file
"""
raw_model_parquet_path = argv[1]
output_path = argv[2]
spark = SparkSession.bu... | 5,293,596 |
def anchormap(refs: Dict[Any, Any] = {}) -> Sequence[Tuple[Location, Location]]:
"""
Return all lexical references
Performs compilation up to and including the type resolution, but doesn't start executing
:param refs: Datastructure used to pass on mocking information to the compiler. Supported options... | 5,293,597 |
def deep_access_list(x, keylist, key_value_eq=None):
"""
>>> deep_access_list({"a":2}, ["a"])
2
>>> deep_access_list({"a":[{"a":2, "b":5}, {"a":1, "b":6}]}, ["a", "a"])
3.0
>>> deep_access_list({"a":[{"a":"cat1", "b":"cat2"}, {"a":"cat3", "b":"cat2"}]}, ["a", "a"], "cat1")
1.0
>>> deep_a... | 5,293,598 |
def test_pack_callback_data():
"""Tests the function can pack action and parameters to a single callback_data string"""
callback_data = util.pack_callback_data("ACTION", params=["1", "2"], separator="::")
assert callback_data == "ACTION::1::2" | 5,293,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.