content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _find_in_iterable_case_insensitive(iterable, name):
"""
Return the value matching ``name``, case insensitive, from an iterable.
"""
iterable = list(OrderedDict.fromkeys([k for k in iterable]))
iterupper = [k.upper() for k in iterable]
try:
match = iterable[iterupper.index(name.upper(... | 5,339,800 |
def RunInSeparateProcess(fn, *args):
"""Runs a function in a separate process.
Note: Only boolean return values are supported.
@type fn: callable
@param fn: Function to be called
@rtype: bool
@return: Function's result
"""
pid = os.fork()
if pid == 0:
# Child process
try:
# In case th... | 5,339,801 |
def predict_all_points(data, order, coefficients):
"""
:param data: input data to create least squares prediction of order(order) of
:param order: order for least squares prediction
:param coefficients: coefficients of LPC
:return: returns estimation of entire data set. Will be of length (len(data) ... | 5,339,802 |
def _unpack(msg, decode=True):
"""Unpack and decode a FETCHed message dictionary."""
if 'UID' in msg and 'BODY[]' in msg:
uid = msg['UID']
body = msg['BODY[]']
if decode:
idate = msg.get('INTERNALDATE', None)
flags = msg.get('FLAGS', ())
return (uid, IMAP4Message(body, uid, idate, flags))
else:
r... | 5,339,803 |
def video_in(filename=INPUTPATH):
"""reads (max.20sec!) video file and stores every frame as PNG image for processing
returns image name and image files (as np array?)"""
#create video capture object
cap = cv2.VideoCapture(filename)
name = filename.split('/')[-1].split('.')[0]
i=0
if (cap.is... | 5,339,804 |
def convert_all_timestamps(results: List[ResponseResult]) -> List[ResponseResult]:
"""Replace all date/time info with datetime objects, where possible"""
results = [convert_generic_timestamps(result) for result in results]
results = [convert_observation_timestamps(result) for result in results]
return r... | 5,339,805 |
def download_mnist(data_dir="/tmp/data", train=True):
"""Download MNIST dataset from a public S3 bucket
Args:
data_dir (str): directory to save the data
train (bool): download training set
Returns:
None
"""
if not os.path.exists(data_dir):
os.makedirs(data_dir)
... | 5,339,806 |
def init():
"""Sets up a project in current working directory with default settings.
It copies files from templates directory and pastes them in the current working dir.
The new project is set up with default settings.
"""
cfg = Path("manim.cfg")
if cfg.exists():
raise FileExistsError(... | 5,339,807 |
def convert(s):
""" Take full markdown string and swap all math spans with img.
"""
matches = find_inline_equations(s) + find_display_equations(s)
for match in matches:
full = match[0]
latex = match[1]
img = makeimg(latex)
s = s.replace(full, img)
... | 5,339,808 |
def file_parser(input_file: str = 'stocks.json') -> dict:
"""Reads the input file and loads the file as dictionary.
Args:
input_file: Takes the input file name as an argument.
Returns:
dict:
Returns a json blurb.
"""
if path.isfile(input_file):
with open(input_file)... | 5,339,809 |
def _amplify_ep(text):
"""
check for added emphasis resulting from exclamation points (up to 4 of them)
"""
ep_count = text.count("!")
if ep_count > 4:
ep_count = 4
# (empirically derived mean sentiment intensity rating increase for
# exclamation points)
ep_amplifier = ep... | 5,339,810 |
def inline_singleton_lists(dsk):
""" Inline lists that are only used once
>>> d = {'b': (list, 'a'),
... 'c': (f, 'b', 1)} # doctest: +SKIP
>>> inline_singleton_lists(d) # doctest: +SKIP
{'c': (f, (list, 'a'), 1)}
Pairs nicely with lazify afterwards
"""
dependencies = dict((... | 5,339,811 |
def vegasflowplus_sampler(*args, **kwargs):
"""Convenience wrapper for sampling random numbers
Parameters
----------
`integrand`: tf.function
`n_dim`: number of dimensions
`n_events`: number of events per iteration
`training_steps`: number of training_iterations
Returns... | 5,339,812 |
def test_sparse_rail_generator_deterministic():
"""Check that sparse_rail_generator runs deterministic over different python versions!"""
speed_ration_map = {1.: 1., # Fast passenger train
1. / 2.: 0., # Fast freight train
1. / 3.: 0., # Slow commuter train
... | 5,339,813 |
def remove_recalculated_sectors(df, prefix='', suffix=''):
"""Return df with Total gas (sum of all sectors) removed
"""
idx = recalculated_row_idx(df, prefix='', suffix='')
return df[~idx] | 5,339,814 |
def unparse_headers(hdrs):
"""Parse a dictionary of headers to a string.
Args:
hdrs: A dictionary of headers.
Returns:
The headers as a string that can be used in an NNTP POST.
"""
return "".join([unparse_header(n, v) for n, v in hdrs.items()]) + "\r\n" | 5,339,815 |
def initialize(file=None, logging_level='INFO'):
"""Read the configuration file containing the run's parameters.
This should be the first call, before using any of the other OGGM modules
for most (all?) OGGM simulations.
Parameters
----------
file : str
path to the configuration file (... | 5,339,816 |
def gl_set_visibility(gl_project_group, gl_visibility_level):
"""
Sets the visibility for a Gitlab project or group
:param gl_project_group: A Project or Group object
:param visibility ('public','internal','private')
"""
gl_project_group.visibility = gl_visibility_level
gl_project_group.save... | 5,339,817 |
def modify_natoms(row, BBTs, fg):
"""This function takes a row of a pandas data frame and calculates the new number of atoms
based on the atom difference indicated in itw functional groups
BBTs : list of instances of BBT class
fg : instance of the Parameters class (fg parameters)
returns : n_at... | 5,339,818 |
async def test_sample_url_max_attempts(mocker):
"""It should observe the max attempts, for sequential failures."""
mock_collect_trace = mocker.patch(
'lab.fetch_websites.collect_trace', autospec=True)
mock_collect_trace.side_effect = [
{'protocol': proto, 'status': status}
for proto,... | 5,339,819 |
def cmd_deposit_references(logger, session, references_json):
"""
Deposit/update a set of references into database given by DB_URL.
Input is a line separated JSON file, with one reference object per line.
"""
import_references(session, references_json)
logger.echo("References imported successfu... | 5,339,820 |
def install(url, force, skip_platform_check=False, skip_migration=False, skip_package_migration=False,
skip_setup_swap=False, swap_mem_size=None, total_mem_threshold=None, available_mem_threshold=None):
""" Install image from local binary or URL"""
bootloader = get_bootloader()
if url.startswit... | 5,339,821 |
def recreate_cursor(collection, cursor_id, retrieved, batch_size):
"""
Creates and returns a Cursor object based on an existing cursor in the
in the server. If cursor_id is invalid, the returned cursor will raise
OperationFailure on read. If batch_size is -1, then all remaining documents
on the curs... | 5,339,822 |
def incons(input_dictionary,m,b,use_boiling=True,use_equation=False):
"""It returns the coordinates X,Y and Z at a desired depth.
Parameters
----------
input_dictionary : dictionary
Contains the infomation of the layer under the keyword 'LAYER' and 'z_ref'. Also it contains the keyword 'INCONS_PARAM' with the s... | 5,339,823 |
def nut00b(date1, date2):
"""
Wrapper for ERFA function ``eraNut00b``.
Parameters
----------
date1 : double array
date2 : double array
Returns
-------
dpsi : double array
deps : double array
Notes
-----
The ERFA documentation is below.
- - - - - - - - - -
... | 5,339,824 |
def train_tree_default(
training_predictor_table, training_target_table,
validation_predictor_table, validation_target_table):
"""Trains decision tree with default params.
:param training_predictor_table: See doc for `utils.read_feature_file`.
:param training_target_table: Same.
:param ... | 5,339,825 |
def AddResourceArg(parser, verb):
"""Add a resource argument for an access zone.
NOTE: Must be used only if it's the only resource arg in the command.
Args:
parser: the parser for the command.
verb: str, the verb to describe the resource, such as 'to update'.
"""
concept_parsers.ConceptParser.ForRes... | 5,339,826 |
def add_mms_attachments(db, mms, backup_dir, thread_dir):
"""Add all attachment objects to MMS message"""
qry = db.execute(
"SELECT _id, ct, unique_id, voice_note, width, height, quote "
"FROM part WHERE mid=?",
(mms._id,),
)
for _id, ct, unique_id, voice_note, width, height, quo... | 5,339,827 |
def Join_Factors(*factor_data, merge_names=None, new_name=None, weight=None, style='SAST'):
"""合并因子,按照权重进行加总。只将非缺失的因子的权重重新归一合成。
Parameters:
===========
factor_data: dataframe or tuple of dataframes
merge_names: list
待合并因子名称,必须是data_frame中列的子集
new_name: str
合成因子名称
w... | 5,339,828 |
def _check_for_file_changes(filepath: Path, config: Config) -> bool:
"""Returns True if a file was modified in a working dir."""
# Run 'git add' to avoid false negatives, as 'git diff --staged' is used for
# detection. This is important when there are external factors that impact the
# committing proces... | 5,339,829 |
def wait_or_cancel(proc, title, message):
"""
Display status dialog while process is running and allow user to cancel
:param proc: subprocess object
:param title: title for status dialog
:param message: message for status dialog
:return: (process exit code, stdout output or None)
"""
pD... | 5,339,830 |
def assert_eventually_true(eval, timeout=None, delay=0.01):
"""
Checks if the passed function evaluates to true within the time limit specified by timeout
"""
t0 = time.time()
while (True):
if eval():
break
time.sleep(delay)
if timeout and time.time() - t0 > ti... | 5,339,831 |
def getg_PyInteractiveBody_one_in_two_out():
"""Return a graph that has a PyInteractiveBody with one input
and two outputs.
"""
@dl.Interactive(
[("num", dl.Int(dl.Size(32)))],
[('num_out', dl.Int(dl.Size(32))), ('val_out', dl.Bool())]
)
def interactive_func(node: dl.PythonNode):... | 5,339,832 |
def batch_norm_relu(inputs, is_training):
"""Performs a batch normalization followed by a ReLU."""
# We set fused=True for a performance boost.
inputs = tf.layers.batch_normalization(
inputs=inputs,
axis=FLAGS.input_layout.find('C'),
momentum=FLAGS.batch_norm_decay,
epsilon=FLAGS.batch_nor... | 5,339,833 |
def knn(points, p, k):
"""
Calculates the k nearest neighbours of a point.
:param points: list of points
:param p: reference point
:param k: amount of neighbours
:return: list of k neighbours
"""
return sorted(points, key=lambda x: distance(p, x))[:k] | 5,339,834 |
def ruleset_detail(request, slug):
"""
View for return the specific ruleset that user pass by using its slug in JSON format.
:param request: WSGI request from user
:return: Specific ruleset metadata in JSON format.
"""
# try to fetch ruleset from database
try:
ruleset = Ruleset.obje... | 5,339,835 |
def send_slack_notification(message):
"""
Send slack notification
Arguments:
message {string} -- Slack notification message
Returns:
response {Response} -- Http response object
"""
response = requests.post(
SLACK_WEBHOOK,
data=json.dumps(
{
... | 5,339,836 |
def options_handler():
"""Validates and parses script arguments.
Returns:
Namespace: Parsed arguments object.
"""
parser = argparse.ArgumentParser(description="Downloads XSOAR packs as zip and their latest docker images as tar.")
parser.add_argument('-p', '--packs',
... | 5,339,837 |
def method_detect(method: str):
"""Detects which method to use and returns its object"""
if method in POSTPROCESS_METHODS:
if method == "rtb-bnb":
return RemovingTooTransparentBordersHardAndBlurringHardBorders()
elif method == "rtb-bnb2":
return RemovingTooTransparentBord... | 5,339,838 |
def approve_pipelines_for_publishing(pipeline_ids): # noqa: E501
"""approve_pipelines_for_publishing
# noqa: E501
:param pipeline_ids: Array of pipeline IDs to be approved for publishing.
:type pipeline_ids: List[]
:rtype: None
"""
return util.invoke_controller_impl() | 5,339,839 |
def get_x(document_id, word2wid, corpus_termfrequency_vector):
"""
Get the feature vector of a document.
Parameters
----------
document_id : int
word2wid : dict
corpus_termfrequency_vector : list of int
Returns
-------
list of int
"""
word_list = list(reuters.words(docu... | 5,339,840 |
def csrf_protect(remainder, params):
"""
Perform CSRF protection checks. Performs checks to determine if submitted
form data matches the token in the cookie. It is assumed that the GET
request handler successfully set the token for the request and that the
form was instrumented with a CSRF token fie... | 5,339,841 |
def process_chain_of_trust(host: str, image: Image, req_delegations: list):
"""
Processes the whole chain of trust, provided by the notary server (`host`)
for any given `image`. The 'root', 'snapshot', 'timestamp', 'targets' and
potentially 'targets/releases' are requested in this order and afterwards
... | 5,339,842 |
def collect_js(
deps,
closure_library_base = None,
has_direct_srcs = False,
no_closure_library = False,
css = None):
"""Aggregates transitive JavaScript source files from unfurled deps."""
srcs = []
direct_srcs = []
ijs_files = []
infos = []
modules = []
... | 5,339,843 |
def test_get_region_order():
"""
Test the ordering of models given a chromosome, start and end parameter
"""
print("test_get_region_order")
hdf5_handle = coord('test', '')
results = hdf5_handle.get_resolutions()
hdf5_handle.set_resolution(int(results[0]))
region_ids = get_region_ids(hd... | 5,339,844 |
def send_control(uuid, type, data):
"""
Sends control data to the terminal, as for example resize events
"""
sp = sessions[uuid]
if type == 'resize':
import termios
import struct
import fcntl
winsize = struct.pack("HHHH", data['rows'], data['cols'], 0, 0)
fcn... | 5,339,845 |
def get_absolute_path(path):
"""
Returns absolute path.
"""
if path.startswith("/"):
return path
else:
return os.path.join(HOME_DIR, path) | 5,339,846 |
def read_mat1(name: str, group: h5py._hl.dataset.Dataset, geom_model: BDF) -> None:
"""
Dataset:
attrs : <Attributes of HDF5 object at 2553977821512>
chunks : (310,)
compression : 'gzip'
compression_opts : 1
dims : <Dimensions of HDF5 object at 2553977821512>
dtype : dtype([('MID', '... | 5,339,847 |
def polyfit(x, y, deg=1):
"""Perform linear/polynomial regression.
Usage: cat a.csv | ph polyfix x y
cat a.csv | ph polyfix x y --deg=1 # default
cat a.csv | ph polyfix x y --deg=2 # default
Outputs a column polyfit_{deg} containing the evaluated index.
"""
df = pipein()
... | 5,339,848 |
def get_prefix_by_xml_filename(xml_filename):
"""
Obtém o prefixo associado a um arquivo xml
Parameters
----------
xml_filename : str
Nome de arquivo xml
Returns
-------
str
Prefixo associado ao arquivo xml
"""
file, ext = os.path.splitext(xml_filename)
retu... | 5,339,849 |
def dgausscdf(x):
"""
Derivative of the cumulative distribution function for the normal distribution.
"""
return gausspdf(x) | 5,339,850 |
def LStatFile(path):
"""
LStat the file. Do not follow the symlink.
"""
d = None
error = None
try:
d=os.lstat(path)
except OSError as error:
print("Exception lstating file " + path + " Error Code: " + str(error.errno) + " Error: " +error.strerror, file=sys.stderr)
... | 5,339,851 |
def run(module):
"""Change OpVariable (of Function storage class) to registers."""
for function in module.functions:
process_function(module, function) | 5,339,852 |
def update_pod(pod):
"""
Called when a Pod update with type MODIFIED is received.
Compares if the labels have changed. If they have, updates
the Calico endpoint for this pod.
"""
# Get Kubernetes labels and metadata.
workload_id, namespace, name, labels = parse_pod(pod)
_log.debug("Upd... | 5,339,853 |
def model_datasets_to_rch(gwf, model_ds, print_input=False):
"""convert the recharge data in the model dataset to a recharge package
with time series.
Parameters
----------
gwf : flopy.mf6.modflow.mfgwf.ModflowGwf
groundwater flow model.
model_ds : xr.DataSet
dataset containing ... | 5,339,854 |
def create_events_to_group(
search_query: str,
valid_events: bool,
group: Group,
amount: int = 1,
venue: bool = False,
) -> List[Event]:
"""
Create random test events and save them to a group
Arguments:
search_query {str} -- use query param for the search request
valid_e... | 5,339,855 |
def alt_stubbed_receiver() -> PublicKey:
"""Arbitrary known public key to be used as reciever."""
return PublicKey("J3dxNj7nDRRqRRXuEMynDG57DkZK4jYRuv3Garmb1i98") | 5,339,856 |
def create_api_headers(token):
"""
Create the API header.
This is going to be sent along with the request for verification.
"""
auth_type = 'Basic ' + base64.b64encode(bytes(token + ":")).decode('ascii')
return {
'Authorization': auth_type,
'Accept': 'application/json',
... | 5,339,857 |
def bv2fif(dataf, corf, ch_order=None, aux=('VEOG', 'HEOG', 'ECG', 'EMG'),
preload='default', ref_ch='Fp1', dbs=False,
use_find_events='dbs', tmin=-2, tmax=2, baseline=(-0.5,-0.1),
detrend=1):
"""Function to convert .eeg, .vmrk and .vhdr BrainVision files to a
combined .fif ... | 5,339,858 |
def _combine(bundle, transaction_managed=False, rollback=False,
use_reversion=True):
"""
Returns one sreg and DHCP output for that SREG.
If rollback is True the sreg will be created and then rolleback, but before
the rollback all its HWAdapters will be polled for their DHCP output.
"""... | 5,339,859 |
def get_node_session(*args, **kwargs):
"""Creates a NodeSession instance using the provided connection data.
Args:
*args: Variable length argument list with the connection data used
to connect to the database. It can be a dictionary or a
connection string.
**kwargs... | 5,339,860 |
def load_aaz_command_table(loader, aaz_pkg_name, args):
""" This function is used in AzCommandsLoader.load_command_table.
It will load commands in module's aaz package.
"""
profile_pkg = _get_profile_pkg(aaz_pkg_name, loader.cli_ctx.cloud)
command_table = {}
command_group_table = {}
arg_str... | 5,339,861 |
def edit_role(payload, search_term):
"""Find and edit the role."""
role = Role.query.get(search_term)
# if edit request == stored value
if not role:
return response_builder(dict(status="fail",
message="Role does not exist."), 404)
try:
if payload... | 5,339,862 |
def use_redis_cache(key, ttl_sec, work_func):
"""Attemps to return value by key, otherwise caches and returns `work_func`"""
redis = redis_connection.get_redis()
cached_value = get_pickled_key(redis, key)
if cached_value:
return cached_value
to_cache = work_func()
pickle_and_set(redis, k... | 5,339,863 |
def counting_sort(array, low, high):
"""Razeni pocitanim (CountingSort). Seradte zadane pole 'array'
pricemz o poli vite, ze se v nem nachazeji pouze hodnoty v intervalu
od 'low' po 'high' (vcetne okraju intervalu). Vratte serazene pole.
"""
counts = [0 for i in range(high - low + 1)]
for elem i... | 5,339,864 |
async def wait_until(
wait_until_timestamp: pd.Timestamp,
get_wall_clock_time: hdateti.GetWallClockTime,
*,
tag: Optional[str] = None,
) -> None:
"""
Wait until the wall clock time is `timestamp`.
"""
if tag is None:
# Use the name of the function calling this function.
t... | 5,339,865 |
def normalize_archives_url(url):
"""
Normalize url.
will try to infer, find or guess the most useful archives URL, given a URL.
Return normalized URL, or the original URL if no improvement is found.
"""
# change new IETF mailarchive URLs to older, still available text .mail archives
new_ie... | 5,339,866 |
def logs():
"""
:return: The absolute path to the directory that contains Benchmark's log file.
"""
return os.path.join(benchmark_confdir(), "logs") | 5,339,867 |
def getIsolatesFromIndices(indices):
"""
Extracts the isolates from the indices of a df_X.
:param pandas.index indices:
cn.KEY_ISOLATE_DVH, cn.KEY_ISOLATE_MMP
:return dict: keyed by cn.KEY_ISOLATE_DVH, cn.KEY_ISOLATE_MMP
values correspond to rows element in the index
"""
keys = [n for n in indice... | 5,339,868 |
def save_group_geo_org(user_id, group_id, area_id, org_unit_id):
"""Method for attaching org units and sub-counties."""
try:
if org_unit_id:
geo_org_perm, ctd = CPOVCUserRoleGeoOrg.objects.update_or_create(
user_id=user_id, group_id=group_id, org_unit_id=org_unit_id,
... | 5,339,869 |
def tf_efficientnet_lite0(pretrained=False, **kwargs):
""" EfficientNet-Lite0 """
# NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet_lite(
'tf_efficientnet_lite0', channel_multipli... | 5,339,870 |
def ensuredir(dirpath):
"""
ensure @dirpath exists and return it again
raises OSError on other error than EEXIST
"""
try:
os.makedirs(dirpath, 0o700)
except FileExistsError:
pass
return dirpath | 5,339,871 |
def get_qualname(node: ast.AST) -> Optional[str]:
"""
If node represents a chain of attribute accesses, return is qualified name.
"""
parts = []
while True:
if isinstance(node, ast.Name):
parts.append(node.id)
break
elif isinstance(node, ast.Attribute):
... | 5,339,872 |
def roc_plot(FLAGS, y_test, y_score, target_names):
"""Plot Receiver Operating Characteristic curve
Args:
FLAGS (argument parser): input information
y_test (2D array): true label of test data
y_score (2D) array: prediction label of test data
target_names (1D array): array of enc... | 5,339,873 |
def traceUsage(addr, register, steps):
"""
Given a start address, a register which holds a value and the number of steps,
this function disassembles forward #steps instructions and traces the value of <register>
until it is used in a call instruction. It then returns the offset added to <register> and the addre... | 5,339,874 |
def index_folder(folder, images=[]):
"""
simple multi threaded recusive function to map folder
Args:
@param folder: folder str path to folder
@param images: images list containing absolute paths of directory images
Returns:
List with image paths
"""
print(f'Entering {fold... | 5,339,875 |
def array3d (surface):
"""pygame.surfarray.array3d (Surface): return array
Copy pixels into a 3d array.
Copy the pixels from a Surface into a 3D array. The bit depth of the
surface will control the size of the integer values, and will work
for any type of pixel format.
This function will temp... | 5,339,876 |
def masked_kl_div(input, target, mask):
"""Evaluate masked KL divergence between input activations and target distribution.
Parameters:
input (tensor) - NxD batch of D-dimensional activations (un-normalized log distribution).
target (tensor) - NxD normalized target distribution.
mask (t... | 5,339,877 |
def create_sample_data(input_seqs, sample_size):
"""
Takes a sample of size 'sample_size' from an input file
containing sequences and their associated expression levels,
and writes them to a separate file. The format of the first
2 lines of the resulting output file will be of the format:
"
... | 5,339,878 |
def find_peaks(ts, mindist=100):
"""
Find peaks in time series
:param ts:
:return:
"""
extreme_value = -np.inf
extreme_idx = 0
peakvalues = []
peaktimes = []
find_peak = True
idx = 0
for r in ts.iteritems():
# print(r)
if find_peak:
# look fo... | 5,339,879 |
def test_extract_legacy_bad_top_dir(tmpdir):
""" Test Extract Legacy Bad Top Dir """
src = tmpdir.mkdir("src")
boost = src.mkdir("boost")
boost.ensure("lib", "libboost.so", file=True)
res = qisys.archive.compress(boost.strpath)
dest = tmpdir.mkdir("dest").join("boost-1.55")
qitoolchain.qipac... | 5,339,880 |
def load_dataset(name, root, sample="default", **kwargs):
"""
Default dataset wrapper
:param name (string): Name of the dataset (Out of cifar10/100, imagenet, tinyimagenet, CUB200, STANFORD120, MIT67).
:param root (string): Path to download the dataset.
:param sample (string): Default (random) samp... | 5,339,881 |
def get_flanking_seq(genome, scaffold, start, end, flanking_length):
"""
Get flanking based on Blast hit
"""
for rec in SeqIO.parse(genome, "fasta"):
if rec.id == scaffold:
return str(
rec.seq[int(start) - int(flanking_length) : int(end) + int(flanking_length)]
... | 5,339,882 |
def d(vars):
"""List of variables starting with string "df" in reverse order. Usage: d(dir())
@vars list of variables output by dir() command
"""
list_of_dfs = [item for item in vars if (item.find('df') == 0 and item.find('_') == -1 and item != 'dfs')]
list_of_dfs.sort(key=lambda x:int(re.sub("[^0-... | 5,339,883 |
def write_to_bin(out_file, filename, article_tag, summary_tag, makevocab=False):
"""Reads the tokenized files corresponding to the urls listed in the url_file and writes them to a out_file."""
print "Making bin file for filename %s..." % filename
if makevocab:
vocab_counter = collections.Counter()
with o... | 5,339,884 |
def get_class_namespaces(cls: type) -> tuple[Namespace, Namespace]:
"""
Return the module a class is defined in and its internal dictionary
Returns:
globals, locals
"""
return inspect.getmodule(cls).__dict__, cls.__dict__ | {cls.__name__: cls} | 5,339,885 |
def fetch_and_save_latest_definitions(
base_api_url, cache, output_dir=None, save_to_db=False,
save_to_fstate=False, by_latest=True, retries=2, verbose=True):
"""
Fetch ClearlyDefined definitions and paginate through. Save these as blobs
to data_dir.
Fetch the most recently updated defi... | 5,339,886 |
def write_stream(path, sync=True, *args, **kwargs):
"""Creates a writer object (context manager) to write multiple dataframes into one file. Must be used as context manager.
Parameters
----------
path : str, filename or path to database table
sync : bool, default True
Set to `False` to run the writer in the bac... | 5,339,887 |
def diff(
df: DataFrame,
columns: Dict[str, str],
periods: int = 1,
axis: PandasAxis = PandasAxis.ROW,
) -> DataFrame:
"""
Calculate row-by-row or column-by-column difference for select columns.
:param df: DataFrame on which the diff will be based.
:param columns: columns on which to pe... | 5,339,888 |
def change(par, value):
"""
Set to change a parameter to another value.
Parameters
----------
par: str
Name of the parameter to change.
value: any
Value to be set to the parameter.
"""
if "CONFIG_CHANGED_PARS" not in globals():
global CONFIG_CHANGED_PARS
... | 5,339,889 |
def decodeTx(data: bytes) -> Transaction:
"""Function to convert base64 encoded data into a transaction object
Args:
data (bytes): the data to convert
Returns a transaction object
"""
data = base64.b64decode(data)
if data[:1] != tx_flag:
return None
timestamp = f... | 5,339,890 |
def create_package_from_datastep(table):
"""Create an importable model package from a score code table.
Parameters
----------
table : swat.CASTable
The CAS table containing the score code.
Returns
-------
BytesIO
A byte stream representing a ZIP archive which can be importe... | 5,339,891 |
def _test_diff(diff: list[float]) -> tuple[float, float, float]:
"""Последовательный тест на медианную разницу с учетом множественного тестирования.
Тестирование одностороннее, поэтому p-value нужно умножить на 2, но проводится 2 раза.
"""
_, upper = seq.median_conf_bound(diff, config.P_VALUE / populat... | 5,339,892 |
def ProcessFiles(merged_store, filenames, callback):
"""Fetch and process each file contained in 'filenames'."""
@gen.engine
def _ProcessOneFile(contents, day_stats):
"""Iterate over the contents of a processed file: one entry per line. Increment stats for specific entries."""
buf = cStringIO.StringIO(co... | 5,339,893 |
def get_repo_of_app_or_library(app_or_library_name):
""" This function takes an app or library name and will return the corresponding repo
for that app or library"""
specs = get_specs()
repo_name = specs.get_app_or_lib(app_or_library_name)['repo']
if not repo_name:
return None
return Rep... | 5,339,894 |
def get_index_price_change_by_ticker(fromdate: str, todate: str, market: str="KOSPI") -> DataFrame:
"""입력된 기간동안의 전체 지수 등락률
Args:
fromdate (str ): 조회 시작 일자 (YYMMDD)
todate (str ): 조회 종료 일자 (YYMMDD)
market (str, optional): 조회 시장 (KOSPI/KOSDAQ/RKX/테마)
Returns:
... | 5,339,895 |
def axpy(alpha, x, y, stream=None):
"""y <- alpha*x + y """
global _blas
if not isinstance(alpha, Number): raise ValueError('alpha is not a numeric type')
validate_argument_dtype(x, 'x')
validate_argument_dtype(y, 'y')
if not _blas: _blas = Blas()
_blas.stream = stream
dtype = promote(... | 5,339,896 |
def _unenroll_get_hook(app_context):
"""Add field to unenroll form offering data removal, if policy supports."""
removal_policy = _get_removal_policy(app_context)
return removal_policy.add_unenroll_additional_fields(app_context) | 5,339,897 |
def main():
"""Run experiment with multiple classifiers."""
data = get_data()
print("Got %i training samples and %i test samples." %
(len(data['train']['X']), len(data['test']['X'])))
# Get classifiers
classifiers = [
('Logistic Regression (C=1)', LogisticRegression(C=1)),
... | 5,339,898 |
def query_fetch_bom_df(search_key: str, size: int) -> Union[pd.DataFrame, None]:
"""Fetch and return bom dataframe of the article
Runs recursive query on database to fetch the bom.
"""
# Recursive query
raw_query = f"""WITH cte AS (
SELECT *
FROM [{DB_NAME}].[dbo].[{SQL_T_BOM}]
... | 5,339,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.