content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def transformation_task(df):
"""Tranform original dataset.
:param_df: Input Dataframe.
:return: Transformed DataFrame.
"""
##Prepare dataframes
spark.sql('use xxx_usercrypto_db')
##create staging table
# spark.sql('drop table if exists stg_users')
# df.write.saveAsTable('stg_users')... | 6ffa8d7ae22b73ea39bc59483a2f7855c04d6ca6 | 48,600 |
def is_weight_node(node):
"""
Check if the node is weight type.
Args:
node (Node): The node object.
Returns:
bool, if the node is weight type.
"""
if node.type == NodeTypeEnum.PARAMETER.value:
full_name = node.full_name.lower()
weight_flag = False
if ful... | 283f90340bfa0feb81073a4113dfd645929ac4a2 | 48,601 |
def dict_to_qbody(d, prefix=''):
"""
Generates a string representing a query body from an AST dict.
:param d: AST dict
:param prefix: needed in case it will recurse
"""
if type(d) is not dict:
return ''
s = ''
iprefix = prefix + '\t'
args = ''
for k, v in d.items():
... | c297835a7f72be9f749e55c33441edadf22b6ee0 | 48,602 |
def has_setter(obj, attr):
"""True if an attribute has an associated setter.
Parameters
----------
obj : object
Any class instance.
attr : str
Name of the attribute to check.
"""
_check_is_attr_name(attr)
return True if has_property(obj, attr) and \
g... | 6414f935a8843164a343df5b17930d614afb330e | 48,603 |
import pydensecrf.densecrf as dcrf
from pydensecrf.utils import (
unary_from_labels, unary_from_softmax,
create_pairwise_bilateral, create_pairwise_gaussian)
def FC_CRF(pred, im, NLABELS, RESIZE_FACTOR= 5,
DELTA_COL= 5, DELTA_SIZE= 5, n_steps=10,
CERTAINTY= 0.7, mode= "multilabel"):
... | 5acf086e5bc4477a8d994291622cd887f1642d4b | 48,604 |
import math
def convert_to_samples(c, deg, boundary_condition='Mirror', in_place=False):
"""
Convert interpolation coefficients into samples
In the input array, the signals are considered along the first dimension
(1D computations).
"""
n = c.shape[0]
if n == 1:
return c
kerl... | c3f0d47d00495058075f4889f45b155fdd06ef07 | 48,605 |
from .signaltools import get_window
def firwin2(numtaps, freq, gain, nfreqs=None, window='hamming', nyq=1.0,
antisymmetric=False):
"""
FIR filter design using the window method.
From the given frequencies `freq` and corresponding gains `gain`,
this function constructs an FIR filter with l... | 7d5a34ec8d1272989f1785d06425d698893de8d0 | 48,606 |
def run_notebook_or_python(clname, path, params):
"""원격 노트북 인스턴스에서 노트북 또는 파이썬 파일 실행.
Returns:
tuple: (stdout, exit_code)
"""
info("run_notebook_or_python: {} - {}".format(clname, path))
check_cluster(clname)
clinfo = load_cluster_info(clname)
dask = 'type' in clinfo and clinfo['ty... | ac872e8bf8e26b4dcdf10894de00b2be97e02463 | 48,607 |
def remove_raw_object(cls):
"""
Decorator.
If a Record class is decorated, raw_object will be removed once all mark properties are cached.
"""
cls.remove_raw_object = True
return cls | 9aab8feb4201237864de5eae891a98ed3894d862 | 48,608 |
import os
def validate_experiment_file_existance(args):
"""Warn if experiment metadata files are missing
Parameters
----------
args : argparse.Namespace
parsed arguments as generated by argparse.parse_args
Returns
-------
bool
True if we have required arguments
"""
... | 39f09f91f681b693d170b548663d2714b2c5bda7 | 48,609 |
def change_user_password():
"""
User-friendly function to be used on first boot for changing user passwords
"""
usernames = get_nonroot_nonsystem_users()
if len(usernames) == 0:
logger.warning("Can't detect any users! Changing root password instead")
usernames = ["root"]
for name... | 5e734e66508ae4a96a5f463c202d61436f5e9430 | 48,610 |
def columnOfMatrix(matrix, i):
"""
Метод для получения i-го столбца матрицы
"""
return [row[i] for row in matrix] | 605c95e7cf90dca575bdcf8d4bc434b850131c21 | 48,611 |
import datasets
import time
def run_wall_clock_test(optimizer,
problem,
num_steps,
dataset=datasets.EMPTY_DATASET,
seed=None,
logdir=None,
batch_size=None):
"""Runs optim... | 3fceec7ebd2dcd4c3e7052035e7f177024378e3a | 48,612 |
def p_list_formatter(primer_list):
"""
Reformat the primer list (remove unnecessary characters from biopython2 output).
Args:
primer_list (list): list from list_from_gen output
Returns:
primer_dimers (list): list with unnecessary chars removed.
"""
reformat_p_list = []
primer... | 0b1585221a13c3560d511127af782875fcd71732 | 48,613 |
def fullpath(dataset):
"""
return absolute path to dataset
dataset is an array as returned by CURDATA()
"""
dat = dataset[:] # make a copy because I don't want to modify the original array
if len(dat) == 5: # for topspin 2-
dat[3] = join(normpath(dat[3]), 'data', dat[4], 'nmr')
f... | 5aa8ba5f2d2abca6a33e42af1d8017f72791dda0 | 48,614 |
def edit_meeting(request, club_name, meeting_id):
"""Edit details of meeting"""
current_club = Club.objects.get(club_name=club_name)
meeting = Meeting.objects.get(id=meeting_id)
form = MeetingForm(instance=meeting)
if request.method == 'POST':
form = MeetingForm(request.POST, instance=meetin... | dec2e6704e498ba093e5ca225d821bfee09b2a73 | 48,615 |
def parse_mulplt(path):
"""
Parses MULPLT.DEF file and returns list of lists like: [station, channel type (e.g. SH), channel (E, N or Z)].
"""
data = []
with open(path, "r") as f:
lines = f.readlines()
tag = "#DEFAULT CHANNEL"
for line in lines:
if line[:len(tag)... | c18bad56944c4c8617c0b8c98d5c01cde822de56 | 48,616 |
def status():
"""Status check for server"""
return "Running...\n" | 89b001639d8983cfb2d8705bfcdfdcc6fc8750a4 | 48,617 |
def parse(report_file: str, summary_file: str) -> dict:
"""
Check input file is an accepted file, then select the appropriate parsing method.
Args:
report_file (str): An Ariba report file of clusters which passed filtering.
summary_file (str): A summary file of the report
Returns:
... | 457620a773132eaca13c5b1437781037a7f610f9 | 48,618 |
import pickle
def load_sim(filename):
"""Load a saved simulation"""
with open(filename, "rb") as f:
sim = pickle.load(f)
return sim | 712ce4bc662ec04acc4364515cbc502d01712e8c | 48,619 |
def _repr_rule(iptc_rule, ipv6=False):
""" Return a string representation of an iptc_rule """
s = ''
if ipv6==False and iptc_rule.src != '0.0.0.0/0.0.0.0':
s += 'src {} '.format(iptc_rule.src)
elif ipv6==True and iptc_rule.src != '::/0':
s += 'src {} '.format(iptc_rule.src)
if ipv6==... | e01c3b27ec6ee831a7d88fc87e69e707639ef0b6 | 48,620 |
def CV_IS_SEQ_CLOSED(*args):
"""CV_IS_SEQ_CLOSED(CvSeq seq) -> int"""
return _cv.CV_IS_SEQ_CLOSED(*args) | 2551448332db2e0375cbb4afaaf59f9a398c6216 | 48,621 |
import os
def default_file(filename=''):
"""Discard any path components then search for file in system paths."""
filename = os.path.basename(filename)
if filename in ['..','.','',None]: # special cases
return None # check return value
ret = filename
# first try filename as provided in cwd... | 374cf638e7dfc683f66c64dc9c1c6c60cd6229d1 | 48,622 |
def add_padding_0_bits(bits_string: str, required_length: int) -> tuple:
"""
Adds 0 to bits string.
Returns tuple - (bits string with padding, number of added 0s)
"""
extra_0_bits_count = 0
while len(bits_string) < required_length:
bits_string += '0'
extra_0_bits_count += 1
r... | fd3eee071821d087b710c33a0beef72431836505 | 48,623 |
def get_sheet(filename):
"""
Open workbook and return first worksheet as object
Args:
filename: local file name
Returns:
Worksheet object
"""
wb = load_workbook(filename)
return wb.worksheets[0] | 34015122747021a6a6b815bef62f689818fb523d | 48,624 |
def object_clearance():
"""
Check for two Objects Clearance distance:
Quick measurements between parallel faces and similarly placed objects
Original code from: Bill 03/2015
Adapted to WF by : Rentlau_64 03/2015
"""
global verbose
msg = verbose
m_actDoc = get_ActiveDocument(info=m... | 16c52c178a3485ed10da5a221d8a501e74d06700 | 48,625 |
import json
def readlasfile(lasfile):
"""
Run a PDAL pipeline. Input is a JSON declaration to
deliver to PDAL. Output is a labelled numpy array.
Data are filtered to compute height above ground using nearest ground point neighbours (TIN method arriving soon) and sort by morton order. Any unused dimen... | 12aa456f0dd062b41a4b4cd719aa3a896020bd47 | 48,626 |
from ansible.inventory.manager import InventoryManager
from ansible.parsing.dataloader import DataLoader
import os
def ssh_to_host(hostname, remote_command=None):
"""Compose cmd string of ssh and execute
Uses Ansible to parse inventory file, gets ssh connection options
:param hostname: str. Hostname from... | ee19abe5c19d08119e82ba6a0b9043129b6dffa2 | 48,627 |
def avgpool_4x4(inputs, downsample=False):
"""
avgpool_4x4
"""
return avgpool_base(inputs, (4, 4), downsample) | 973d8b4066f1e8eea7dcf20baae6df24e4029044 | 48,628 |
def str_data(group, field, default=''):
"""
Retrieve value of field as a string, with default if field is missing.
"""
if field in group:
data = group[field][0]
if data.ndim > 0:
value = [_s(v) for v in data]
else:
value = _s(data)
return value
... | c6f4a886eb64fa2b44a151e3032de8a5381b46b1 | 48,629 |
def filter_attributes(func):
"""Filters and removes attributes from User Dictionary objects depending on test requirements."""
@wraps(func)
def filter_attributes_wrapper(*args, **kwargs):
# Get generated users.
users = func(*args, **kwargs)
# If only single user (dict), treat as a ... | 98c81d09e56e240c106cc4ee6cd5a3b158796396 | 48,630 |
def mask_source_centers(array, fwhm, y, x):
""" Creates a mask of ones with the size of the input frame and zeros at
the center of the sources (planets) with coordinates x, y.
Parameters
----------
array : array_like
Input frame.
fwhm : float
Size in pixels of the FWHM.
y, x... | 9b2627ab24a19d6b1921092d3bdd94ff8b0ef70b | 48,631 |
def IsInstance(type_):
"""Returns a function which can be used to check whether or not a value is of the given type."""
def Do(item):
return isinstance(item, type_)
return Do | 06f916e8658761a03619834692d78a44d145b514 | 48,632 |
from typing import Set
def random_proof_tree(rules_dict: RulesDict, root: int) -> Node:
"""Return random tree found by breadth first search."""
seen: Set[int] = set()
root_node = Node(root)
queue = deque([root_node])
while queue:
v = queue.popleft()
rule = choice(list(rules_dict[v.... | 8193a767b88607c018afc8f3099dddfb149f2fed | 48,633 |
def PCreate (name, uvData, err):
"""
Create the parameters and underlying structures of a set of images.
* name = Name to be given to object
* uvData = Python uv data from which the image mosaic will be derived
Most control parameters are in InfoList member
* err = Pyt... | 5bbe747a32f69c865a50082d3639d8da73cda265 | 48,634 |
import sys
def curret_platform() -> str:
"""Get current platform name by short string."""
if sys.platform.startswith('linux'):
return 'linux'
elif sys.platform.startswith('darwin'):
return 'mac'
elif sys.platform.startswith('win'):
if sys.maxsize > 2 ** 31 - 1:
retu... | 81520ae0a9046ff3c2beb44ed4bfd9419ad054b3 | 48,635 |
def active_subspace(df, weights):
"""
TODO: docs
"""
df, M, m = process_inputs(df)
# compute the matrix
C = np.dot(df.transpose(), df * weights)
return sorted_eigh(C) | 5befc4753cb80a6afb6a77719ed0bb2efba99305 | 48,636 |
def get_nq_report(complete_text):
"""
Given the complete submission text for an N-Q filing, parse the document
and return its respective ReportNQ DTO object.
"""
lines = complete_text.split('\n')
series_list = get_series_list(lines)
accepted_date = get_accepted_date(lines)
... | 2ba8ce963a2c13aa759a6427d4e4b7ea27a79924 | 48,637 |
def split_addresslines( lines ):
"""
Split up to 4 lines into appropiate fields (org, dept, street 1/2)
"""
data = {
'organisation': '',
'department': '',
'street_1': '',
'street_2': '',
}
if len(lines) == 0:
pass
elif len(lines) == 1:
data['s... | 481755042c10b54c9724c30c71ba6c9d29bdff91 | 48,638 |
import glob
from pathlib import Path
import importlib
def supported_format():
""" give supported formats """
if not bool(__supported_format__):
modules = glob.glob(join(dirname(__file__), "*.py"))
module_name = [Path(local_file) for local_file \
in modules if not '__init__... | e9f2ae9d7c68399386a444c81b063ec472d77ea1 | 48,639 |
def _make_edge_trace(graph_nx: nx.Graph, pos: dict) -> Scatter:
"""(HELPER) This function is a helper function to visualize_graph_with_attributes.
Return a trace containing lines which represent edges between nodes
given the position of nodes in pos.
"""
x_edges = []
y_edges = []
for edge... | f3e6502779f9b1efcf46ed3f169bf6708ee566c8 | 48,640 |
def import_tnmr(path):
"""
Import tnmr data and return dnpdata object
Args:
path (str) : Path to .jdf file
Returns:
tnmr_data (object) : dnpdata object containing tnmr data
"""
attrs = import_tnmr_pars(path)
values, coords, dims = import_tnmr_data(path)
tnmr_data = dn... | c10723983e5c4bc33adeee6b12f9265e6f04fb64 | 48,641 |
def focal_loss(
y_true,
y_pred,
alpha=[1-0.25, 0.25],
gamma=2.0,
from_logits=False
):
"""
Computes the multi-class focal loss, with class balancing parameter.
Parameters
----------
y_true : tensor
Targets of shape [num_targets,].
y_pre... | 1cf0907eb2d3c8d3c9be71e62e1140ec264f6d41 | 48,642 |
import aeneas.cdtw.cdtw
import aeneas.cmfcc.cmfcc
import aeneas.cew.cew
def can_run_c_extension(name=None):
"""
Determine whether the given Python C extension loads correctly.
If ``name`` is ``None``, tests all Python C extensions,
and return ``True`` if and only if all load correctly.
:param st... | b93b160e448d0d71b42fade1dbeefb63b7a53225 | 48,643 |
def _merge_surrogates(text):
"""Returns a copy of the text with all surrogate pairs merged"""
return _decode_surrogatepass(
text.encode("utf-16-le", _surrogatepass),
"utf-16-le") | 4d887b1352c23900c8ca5829c347c248ac10c3c8 | 48,644 |
import glob
import os
def findChessboards(imageDirectory):
"""
Calculates the object points and image points of chessboard images
:param imageDirectory: the directory to look through for chessboard images
:return: names of the files, the object points list, the image points list, resolution of the cam... | c724ae6e3287279793f428d929435fd25eebe206 | 48,645 |
def show_nums_to_user():
"""
093
Ask the user to enter five numbers. Sort them into order and present them to the user.
Ask them to select one of the numbers. Remove it from the original array and save it in a
new array.
:return: new array with one (popped) item.
"""
arr, trigger = [], 5... | 3b5a365dd729623ede7079d5d131ecc9f40897e7 | 48,646 |
from re import X
def player(board):
"""
Returns player who has the next turn on a board.
"""
if terminal(board):
return
elif board == initial_state():
return X
else:
no_of_X = 0
no_of_O = 0
for row in board:
no_of_X += row.count("X")
... | 542698f474894fcdfa60a440e653a52dae6dbab5 | 48,647 |
def seq_type(seq):
"""
Determines whether a sequence consists of 'N's only
(i.e., represents a gap)
"""
return 'gap' if set(seq.upper()) == {'N'} else 'bases' | 5555e5cd0ccdbf8f5e7b475c5c983ab54a17fb07 | 48,648 |
from typing import Tuple
def get_rows_and_columns(num_plots: int) -> Tuple[int, int]:
"""Get optimal number of rows and columns to display figures.
Parameters
----------
num_plots : int
Number of subplots
Returns
-------
rows : int
Optimal number of rows.
cols : int
... | c1c6f40423975459f08e71c764ffa2c1b81ce90d | 48,649 |
from typing import Union
import ast
def get_fixture_decorator(node: AnyFunctionDef) -> Union[ast.Call, ast.Attribute, None]:
"""
Returns a @pytest.fixture decorator applied to given function definition, if any.
Return value is either:
* ast.Call, if decorator is written as @pytest.fixture()
* ast... | 717e63c4f585e0a28fc08ad07b7892bf61d44b01 | 48,650 |
def do__AcmeV2_AcmeOrder__acme_server_sync(
ctx,
dbAcmeOrder=None,
authenticatedUser=None,
):
"""
:param ctx: (required) A :class:`lib.utils.ApiContext` instance
:param dbAcmeOrder: (required) A :class:`model.objects.AcmeOrder` object to refresh against the server
:param authenticatedUser: (... | 060af883b56ea44826a0d2de3c3a0874449a87f5 | 48,651 |
def static_equilibrium(topology, tmax=100, eta=1e-6, verbose=False, callback=None):
"""
Generate a form diagram in static equilibrium.
Parameters
----------
topology : :class:`compas_cem.diagrams.TopologyDiagram`
A topology diagram.
tmax : ``int``, optional
Maximum number of ite... | 3ae9f86fa47a83f965e1733211b5d2a32765a235 | 48,652 |
from random import shuffle
def chooselabelsubset(lst, n, method):
"""Chooses a subset of the given list, using the given method:
start: from the beginning
end: from the end
random: randomly
"""
# pick the the trainpos and trainneg sets
def randindexes(lst):
"""Ret... | bd922b22654b4bcaf6ed1bb8161b3c582f7f3427 | 48,653 |
import logging
def create_logger() -> logging.Logger:
""" Creates a logging object to be used for reports. """
# Gets a logger object with the name 'gol_logger' and sets the log level to INFO.
#
# Sets an absolute path log_path to the log file _Resources/gol.log, then runs
# logging.FileHandler t... | 48a161b1c4c5856568a87dedf37b06e6a6a5a6bb | 48,654 |
def s_quantifier(num, quantifier):
"""S quantifier."""
return quantifier_selector(num, quantifier, f'{quantifier}s') | 4453fdfb68a6affe6a1f05089b193264d3ae93ba | 48,655 |
def get_monitor_info_a(h_monitor):
"""
BOOL GetMonitorInfoA(
HMONITOR hMonitor,
LPMONITORINFO lpmi
);
"""
return __get_monitor_info(WINDLL.user32.GetMonitorInfoA, h_monitor) | aadfb1f9fe679c6d3ad9facc47c804245f7ea37e | 48,656 |
def textdeskew(image):
"""
Function that calculates a the rotation angle for documents that are
already properly scanned. Using the angle, it tries to deskew. Useful in
cases where there is no difference between foreground and background, and
the document is properly scanned.
"""
gray = cv2.cvtColor(image, cv... | 95d59ec6aca39627bdefa10f174f8b6e97c2c47c | 48,657 |
def group_arguments(seq, group=254):
"""
group the list into lists of 254 items each.
This is due to argument restrictions in python.
http://docs.djangoproject.com/en/dev/topics/http/urls/#patterns
"""
return (seq[pos:pos + group] for pos in range(0, len(seq), group)) | 066ffdd6984fe74f62a1838856124c98a726b623 | 48,658 |
from typing import List
from typing import Union
from typing import Dict
def get_reduction_mask(inputs: List[Union[Chord, Key]], kwargs: Dict = None) -> List[bool]:
"""
Return a boolean mask that will remove repeated inputs when applied to the given inputs list
as inputs[mask].
Parameters
-------... | c20a1c190f49e73126a1dd23cbdee850cb162958 | 48,659 |
import traceback
def generate_requirement_image(
learn_guide_project,
): # pylint: disable=too-many-statements
"""Generate a single requirement image"""
def make_line(
requirement_name, position=(0, 0), icon=None, hidden=False, triangle_icon=None
): # pylint: disable=too-many-branches
... | 92bc23d0baebf55be60b4e34b21535f1b8c9e905 | 48,660 |
from typing import Optional
import contextlib
import socket
def resolve(hostname: str) -> Optional[str]:
""" Get the IP address of a subdomain """
with contextlib.suppress(socket.gaierror):
return socket.gethostbyname(hostname) | cb4924f3120f97e558fabccbab1c30612e52dc2c | 48,661 |
from typing import List
from typing import Dict
def get_researcher_allowed_studies(request: ResearcherRequest) -> List[Dict]:
"""
Return a list of studies which the currently logged-in researcher is authorized to view and edit.
"""
kwargs = {}
if not request.session_researcher.site_admin:
... | 9c0d38b8f4786fbda56b092504e2fd17c277857e | 48,662 |
def fast_non_dominated_sort(values1, values2):
""" Function to carry out NSGA-II's fast non dominated sort """
S = [[] for i in range(0, len(values1))]
front = [[]]
n = [0 for i in range(0, len(values1))]
rank = [0 for i in range(0, len(values1))]
for p in range(0, len(values1)):
S[p] =... | ee7275aea0c2b0acadd6fb523fc24e5618165bfe | 48,663 |
def generate_list(n,idx_excl,n_rand):
"""
random_array = generate_list(n,idx_excl,n_rand)
Generates a list
Parameters
----------
n : INT, total number of samples
idx_excl : 2D array, start,stop index for each seizure
n_rand : INT, number of random samples
Returns
-------
1D... | e639df120d8c78c9bf777f1a569658ffec8d4a65 | 48,664 |
def _neighboring_points(o_index, i_index, e_len, f_len):
"""
A function that returns list of neighboring points in
an alignment matrix for a given alignment (pair of indexes)
"""
result = []
if o_index > 0:
result.append((o_index - 1, i_index))
if i_index > 0:
result.append(... | f7501e25b25a1be50f7eeaf7d32d46a5e55c8ee0 | 48,665 |
import io
import base64
import json
def pose_estimate(event, context):
"""Perform human pose estimation."""
try:
# Get image from the request
picture, filename = fetch_input_image(event)
image = load_image(picture)
print('Loading model')
model = Model(MODEL_PATH)
... | 4c7cc9670d94b62dcaf926b94ee980f7f33de550 | 48,666 |
import collections
def CreateAssocVarPairs(rappor_metrics):
"""Yield a list of pairs of variables that should be associated.
For now just do all (string x boolean) analysis.
"""
var_pairs = collections.defaultdict(list)
for metric, var_list in rappor_metrics.iteritems():
string_vars = []
boolean_v... | d9be4a5904bb3486d9761cef89299bbee67178b8 | 48,667 |
import copy
def function_tester(rng, func, ref_func, inputs,
func_args=[], func_kwargs={},
atol_f=1e-6, atol_b=1e-3, atol_accum=1e-6, dstep=1e-3, backward=None,
ctx=None, func_name=None, ref_grad=None, disable_half_test=False):
""" Automatic testing of f... | 381b5cf9937d50ede15ab4de5ffb5186bbd95b48 | 48,668 |
import sys
import turicreate as tc
import os
def show(x, y, xlabel="X", ylabel="Y", title=None):
"""
Plots the data in `x` on the X axis and the data in `y` on the Y axis
in a 2d visualization, and shows the resulting visualization.
Uses the following heuristic to choose the visualization:
* If `... | de9de989036a4f4fa5df834dcf59ed2c7da92b91 | 48,669 |
def read_text(unformatted_text: str) -> str:
"""Open text from the file or read it directly.
Arguments:
unformatted_text (str): path to a file OR inputed text
Returns:
str: reads and returns text as a string
"""
try:
with open(unformatted_text, "rt") as f:
# cre... | 180238bf545ee7daef56169cc64a9c6277599546 | 48,670 |
def regions(**kw_params):
"""
Get all available regions for the EC2 service.
You may pass any of the arguments accepted by the VPCConnection
object's constructor as keyword arguments and they will be
passed along to the VPCConnection object.
:rtype: list
:return: A list of :class:`boto.ec2.... | 7e099f76714d4ccfc557c24bccea6ac96d734828 | 48,671 |
def read_from_txt(txt_file: str = "untitled.txt") -> list:
"""Opens a text file to get all words, called from outside the class instantiation"""
with open(txt_file, "r") as words:
lines = words.readlines()
return [
line.split(".")[1].strip().upper() for line in lines
] | 4b5a195b77b8eb4028246e54b75cf0862628fcaa | 48,672 |
def extensionOP(extension):
"""
Get an extension's associated operator
:param extension: the extension
:return: the DAT source of extension or the internal parameters' comp or
None if undetermined
"""
eop = None
if isinstance(extension, ParCollection):
# assume internal parameters
eop = extension.stdswi... | 2203ced8580c2f6d51e892f8aae14c238b615e21 | 48,673 |
import tokenize
def _integerize(json_data, word_to_id, dataset):
"""Transform words into integers."""
sequences = np.full((len(json_data), MAX_TOKENS_SEQUENCE[dataset]),
word_to_id[PAD], np.int32)
sequence_lengths = np.zeros(shape=(len(json_data)), dtype=np.int32)
for i, sentence in enum... | 039336371843f0ffb809be94c6100ef659f63248 | 48,674 |
def plot_pq_all(mean_arr, std_arr, label_list, title='QP_accu',
metric='rmse', ax=None, colors=None, alpha=0.5):
"""Generate a summary QP plots with different methods.
Args:
mean_arr (np.ndarray): Mean performance of each method at a certain
quantile, (#methods, #quantiles).... | 42229b9a6a30b20e2847c19dab99f7f11dadb7bb | 48,675 |
import numpy
def rechannel(channels):
"""A data node to rechannel data.
Parameters
----------
channels : int or list
The channel mapping.
Receives
------
data : ndarray
The original signal.
Yields
------
data : ndarray
The rechanneled signal.
"""
... | 993863df43b0fe1a074617a59dc6dca97e2f3076 | 48,676 |
def prepare_traveler_from_raw_data(trips: list):
"""
Construct a traveler by combining a list of single trips
:param trips:
:return:
"""
traveler_chekins = []
for trip in trips:
traveler_chekins = traveler_chekins + generate_checkins(trip)
return sorted(traveler_chekins, key=lamb... | 2fb3e09da47e0c24790864e32b6ff0e232f1d795 | 48,677 |
def spglib_get_primitive(struct, **kwds):
"""Find primitive structure for given :class:`~pwtools.crys.Structure`.
If `struct` is irreducible (is already a primitive cell), we return None,
else a Structure.
Uses spglib.
Parameters
----------
struct : Structure
**kwds : keywords
... | 03a181f49ca4066e78bc7d93ae5cec1ca80a2ac3 | 48,678 |
import asyncio
async def async_query_for_ptr_with_proto(protocol, ips_to_lookup):
"""Send and receiver the PTR queries."""
time_outs = 0
query_for_ip = {}
for ip in ips_to_lookup:
req = async_generate_ptr_query(ip)
query_for_ip[ip] = req.id
try:
await asyncio.wait_f... | e7502b250f02c9345cc7af2c4a913a8f010fc10c | 48,679 |
def fft_shift_phasor_2d(shape, offset, grad=False):
"""Return phasor array used to shift an array (in real space) by
multiplication in fourier space.
Parameters
----------
shape : (int, int)
Length 2 iterable giving shape of array.
offset : (float, float)
Offset in array ele... | cb8e37bcc24f4a6925b1af4b4b6a2563a30b4600 | 48,680 |
def get_ar(bbox):
"""
:param bbox: top left, right down
:return: aspect ratio
"""
[x1, y1, x2, y2] = bbox
return (y2 - y1) / (x2 - x1) | d79eb51eafec917b1754558a9a87307734fd8ac4 | 48,681 |
def log_p_xi(meanLike, covarLike, xi):
"""
Calculate log-likelihood of a single xi, given its
mean/covar after collapsing P(A | X_{-i}, Z)
"""
D = float(xi.shape[1])
ll = -(D / 2) * np.log(covarLike)
ll -= (1 / (2 * covarLike)) * np.power(xi - meanLike, 2).sum()
return ll.item() | 88ce5ea31907a6b9d586912e7ba95a4f7d01b298 | 48,682 |
def get_statsTable(dType, dFreq, df, dates_as_index=True, ptiles=None):
"""
Construct detailed tables with summary statistics.
Parameters
___________
dType : str
Dataset type of the portfolios. Possible choices are:
* ``Returns``
* ``Factors``
* ``NumFir... | 6ca9e3c83177b676dc98db73b282688e8b26c606 | 48,683 |
def has_parameter(param_key_matcher, param_value_matcher):
"""Check values of the stacks parameters."""
return StackParameterMatcher(wrap_matcher(param_key_matcher), wrap_matcher(param_value_matcher)) | 1f1284bc80b27615d3bd7a6b5f6a658dbf5a7fc6 | 48,684 |
import glob
def get_run_files_from_formatter(run_id, formatter, **kwargs):
"""Get a set of files for a particular run
Parameters
----------
run_id : `str`
The number number we are reading
formatter : `FilenameFormat`
Object that constructs the file naem
kwargs
Passed t... | 1266babe827f230176241613b312eec1cc64adcc | 48,685 |
def create_assigment_rule(sbml_model: libsbml.Model,
assignee_id: str,
formula: str,
rule_id: str = None,
rule_name: str = None) -> libsbml.AssignmentRule:
"""Create SBML AssignmentRule
Arguments:
sb... | 62165da36f4f5117bd9f17305842588968dc44f4 | 48,686 |
def regula_falsi(f: Function, xi: float, xf: float, tol: float, iter: bool = False) -> float:
"""
Regula Falsi
============
Regula falsi method to find a root of a function
Parameters
----------
f : Function
Function
xi : float
First point
xf : float
Sec... | b33b5bfec8598b5f5afbff066b75d43ea135970d | 48,687 |
def SelectCard():
# Method Description:
"""Selects A Card Using A Terminal As UI"""
# Endless Loop Till User Enters A Valid Card Number
while(True):
# Prompt user to select card
i= int(input("Please choose a card: "))
# If the position entered is correct
if (i > 0) and (... | c48daf472b6c1b8577762324a4a992fb806c84d9 | 48,688 |
def temperature_salinity_timeseries(
temperature, salinity, colors, data_date, prediction, bloom_dates, titles,
):
"""Create a time series plot figure object showing temperature
on the left axis and salinity on the right.
"""
fig = matplotlib.figure.Figure(figsize=(15, 4.25), facecolor=colors['bg'])... | 398234b6c73c11127449f5d8caa99cf90c99f764 | 48,689 |
import pandas
def readCSVfile(fileName):
"""twitter_follower_yyyymmdd_hhMMss.csv を開く"""
lines = pandas.read_csv(fileName, encoding="utf8")
return lines | 421502f6ae7ac1a92e89044b5c78d4d95e238214 | 48,690 |
import tempfile
import os
def return_testvideo_path():
"""
returns Test video path
"""
path = "{}/Downloads/Test_videos/BigBuckBunny_4sec.mp4".format(
tempfile.gettempdir()
)
return os.path.abspath(path) | 86a5f32f18df6940f2a24227eaeb0baec2ea83d3 | 48,691 |
def validate_image_pull_credentials(image_pull_credentials):
"""
Validate ImagePullCredentialsType for Project
Property: Environment.ImagePullCredentialsType
"""
VALID_IMAGE_PULL_CREDENTIALS = ("CODEBUILD", "SERVICE_ROLE")
if image_pull_credentials not in VALID_IMAGE_PULL_CREDENTIALS:
... | f4953fefbca3ca5906ca58497152b25a07247c9a | 48,692 |
def dynamic_import_st(module, backend):
"""Import ST models dynamically.
Args:
module (str): module_name:class_name or alias in `predefined_st`
backend (str): NN backend. e.g., pytorch, chainer
Returns:
type: ST class
"""
model_class = dynamic_import(module, predefined_st.... | e83a0f75da0894aecac760d421c25107419e155f | 48,693 |
def num_bits(i):
"""Returns the number of bits in an unsigned integer."""
n = 0
while i:
n += 1
i &= i - 1
return n | 3eb664bd642717556af0b2c09314000d70209b44 | 48,694 |
import argparse
def get_args():
"""parse arguments
:returns: parsed arguments
"""
#Command line arguments parser. Described as in their 'help' sections.
parser = argparse.ArgumentParser(description="Replication of Zaremba et al. (2014).\
\n https://arxiv.org/abs/1409.2329")
parser.add... | 28ddf1b900eb1295b0da3d9ab4edbf76ec889cf0 | 48,695 |
def available_solvers():
"""Returns a list of all available solvers.
These can be used in :func:'optunity.make_solver'.
"""
return solver_registry.solver_names() | d90d1c6b0b2bf2af28ad696a91fb6d62d561ea6e | 48,696 |
import math
def coefficient_of_drag_adjusted(state, only_in_range=False):
"""
Calculate the coefficient of drag. The drag is calculated by a bilinear
interpolation from values spaced evenly through Mach values and log10
Reynolds numbers. These values were initially computed from one of the
other... | 95e2f0e553ce90cc2c0b8cf789551ff5cefa9a75 | 48,697 |
def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
domain=DOMAIN,
data={CONF_HOST: "192.168.1.123", CONF_MAC: "aabbccddeeff"},
) | 72d859c574605471e8e5a542eda38fdbeb5cc985 | 48,698 |
def placeholder(shape=None, ndim=None, dtype=None, sparse=False, name=None):
"""Instantiates a placeholder tensor and returns it.
# Arguments
shape: Shape of the placeholder
(integer tuple, may include `None` entries).
ndim: Number of axes of the tensor.
At least one of ... | a5d6cb761bca6b94fc64d20bfc0efe83a74cfd9b | 48,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.