content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def preprocess_data_for_clustering(df):
"""Prepare data in order to apply a clustering algorithm
Parameters
----------
df : pandas.DataFrame
Input data, *i.e.* city-related timeseries, supposed to have
`station_id`, `ts` and `nb_bikes` columns
Returns
-------
pandas.DataFrame
... | 144c701b3be12aed2a1488a08eb05c65c6d704c5 | 3,646,700 |
def chars(line):
"""Returns the chars in a TerminalBuffer line.
"""
return "".join(c for (c, _) in notVoids(line)) | 1ffad7e9d0cc800f8de579fa30aeb108a12bd8d2 | 3,646,701 |
def map_is_finite(query_points: tf.Tensor, observations: tf.Tensor) -> Dataset:
"""
:param query_points: A tensor.
:param observations: A tensor.
:return: A :class:`~trieste.data.Dataset` containing all the rows in ``query_points``,
along with the tensor result of mapping the elements of ``obser... | e22571a179acfb8261924eaf71dec40d17adc47d | 3,646,702 |
def docker_image_exists(args, image): # type: (EnvironmentConfig, str) -> bool
"""Return True if the image exists, otherwise False."""
try:
docker_command(args, ['image', 'inspect', image], capture=True)
except SubprocessError:
return False
return True | ba2eedacef0179b25d203f00cf42fb4f4e4f9b72 | 3,646,703 |
import os
import shutil
def remove_local(path):
"""Remove a local file or directory.
Arguments:
path (str): Absolute path to the file or directory.
Returns:
Boolean indicating result.
"""
if os.path.isfile(path):
# Regular file
remover = os.remove
elif os.pat... | 7267d37bab380b7a9dc103ee3002f9c454cf7bf2 | 3,646,704 |
def get_g2_fit_general_two_steps(
g2,
taus,
function="simple_exponential",
second_fit_range=[0, 20],
sequential_fit=False,
*argv,
**kwargs,
):
"""
Fit g2 in two steps,
i) Using the "function" to fit whole g2 to get baseline and beta (contrast)
ii) Then using the obtained bas... | d02fbf1796e00b8f490a97a7f7274bab1233a823 | 3,646,705 |
import doctest
def run_doctest(module, verbosity=None):
"""Run doctest on the given module. Return (#failures, #tests).
If optional argument verbosity is not specified (or is None), pass
test_support's belief about verbosity on to doctest. Else doctest's
usual behavior is used (it searches sys.argv... | cc50538cf8cf50959a4c67eb1c37010d2eab45a9 | 3,646,706 |
def rate_matrix_arrhenius_time_segmented(energies, barriers, segment_temperatures, segment_start_times, t_range):
"""
Compute the rate matrix for each time ``t`` in ``t_range``, where the bath temperature is a piecewise constant
function of time.
The bath temperature function, by which the rate matrice... | 78245c7452a41af91be5f57f0acc72cc67c2e2e0 | 3,646,707 |
def div_tensor(tensor, coords=(x, y, z), h_vec=(1, 1, 1)):
"""
Divergence of a (second order) tensor
Parameters
----------
tensor : Matrix (3, 3)
Tensor function function to compute the divergence from.
coords : Tuple (3), optional
Coordinates for the new reference system. This ... | 8159dfc8b330f9184c336ba4cecabe2fdf0d7d55 | 3,646,708 |
import ast
def convert_path_to_repr_exp(path, with_end=False):
"""
Generate a representative expression for the given path
"""
exp = ""
#print("Path: {}".format(path))
for i in range(len(path)):
if with_end == False and \
((i == 0) or (i == len(path)-1)):
con... | 68dd8ea13ecdef6f2c3947a1e9341ff5e10ccf78 | 3,646,709 |
def cluster_create(context, values):
"""Create a cluster from the values dictionary."""
return IMPL.cluster_create(context, values) | 593577a3d912a6a24e8f6d3b66d66e1d8f39a681 | 3,646,710 |
def compute_heading_error(est, gt):
"""
Args:
est: the estimated heading as sin, cos values
gt: the ground truth heading as sin, cos values
Returns:
MSE error and angle difference from dot product
"""
mse_error = np.mean((est-gt)**2)
dot_prod = np.sum(est * gt, axis=1)
... | b015a5b904994372c6ca207388ee3db0ef477f0a | 3,646,711 |
def _get_count_bid(soup: bs4.BeautifulSoup) -> int:
""" Return bidding count from `soup`.
Parameters
----------
soup : bs4.BeautifulSoup
Soup of a Yahoo Auction page.
Returns
-------
int
Count of total bidding.
"""
tags = soup.find_all('dt', text='入札件数')
if... | 066b1dcb519db10276dfce35ba04b04f5efdbe66 | 3,646,712 |
def _is_class(s):
"""Imports from a class/object like import DefaultJsonProtocol._"""
return s.startswith('import ') and len(s) > 7 and s[7].isupper() | deee946066b5b5fc548275dd2cce7ebc7023626d | 3,646,713 |
def evaluate(vsm, wordsim_dataset_path):
"""Extract Correlation, P-Value for specified vector space mapper."""
return evaluation.extract_correlation_coefficient(
score_data_path=wordsim_dataset_path, vsm=vsm
) | 2e12b16eee43aef50b5a6de7d0d9fc5b9c806536 | 3,646,714 |
def longest_substring_using_lists(s: str) -> int:
"""
find the longest substring without repeating characters
644 ms 14.3 MB
>>> longest_substring_using_lists("abac")
3
>>> longest_substring_using_lists("abcabcbb")
3
>>> longest_substring_using_lists("bbbbb")
1
>>> longest_subst... | 4292af29c59ea6210cde28745f91f1e9573b7104 | 3,646,715 |
def getuserobj(user_id=None):
"""
登录查询用户是否存在的专用接口函数
:param user_id: 用户id(username)
:return: if exit: return 用户对象
else return None
"""
dbobj = connectMysql.connectMysql()
if user_id is '' or user_id is None:
dbobj.close_db()
return None
else:
userdata ... | 78f5cd9edd72b1ee838fb4b7cde73b3c960be0df | 3,646,716 |
def _parse_track_df(df: pd.DataFrame, track_id: int, track_name: str, track_comment: str,
data_year: int) -> dict:
"""
parses track data
:param df: data representing a track
:param track_id: track id
:param track_name: track name
:param track_comment: track comment
:param... | a6ccd068829ebd0355d4d13ee327255c09615a16 | 3,646,717 |
from typing import Tuple
from typing import Mapping
def parse_tileset(
tileset: TileSet
) -> Tuple[Mapping[Axes, int], TileCollectionData]:
"""
Parse a :py:class:`slicedimage.TileSet` for formatting into an
:py:class:`starfish.imagestack.ImageStack`.
Parameters:
-----------
tileset : ... | d75b121e91d47424704de671c716d1fbf6b02e86 | 3,646,718 |
def pad_sents(sents, pad_token):
""" Pad list of sentences(SMILES) according to the longest sentence in the batch.
@param sents (list[list[str]]): list of SMILES, where each sentence
is represented as a list of tokens
@param pad_token (str): padding token
@returns sen... | 8f0eabfaaa18eafa84366a2f20ed2ddd633dacc6 | 3,646,719 |
def bicubic_interpolation_filter(sr):
"""Creates a bicubic interpolation filter."""
return _interpolation_filter(sr, cv2.INTER_CUBIC) | 772ee384b90ae6b1e9fe875374441b3d59f86326 | 3,646,720 |
def is_receive_waiting():
"""Check to see if a payload is waiting in the receive buffer"""
#extern RADIO_RESULT radio_is_receive_waiting(void);
res = radio_is_receive_waiting_fn()
# this is RADIO_RESULT_OK_TRUE or RADIO_RESULT_OK_FALSE
# so it is safe to evaluate it as a boolean number.
return (... | 8b2a8d1a003f89c3a9b8df7db0729e15a96fdfcc | 3,646,721 |
import typing
def residual_block(
x,
filters: int,
weight_decay: float,
*,
strides: typing.Union[int, typing.Tuple[int, int]],
dilation: typing.Union[int, typing.Tuple[int, int]],
groups: int,
base_width: int,
downsample,
use_basic_block: bool,
use_cbam: bool,
cbam_chan... | f2021a89e2d737e73bfef3fb7dc127c3bbb5d0b7 | 3,646,722 |
def vacancy_based_on_freq(service,duration,frequency,earliest,latest,local_timezone):
"""
Check vacant timeslot with the user inputed duration for the frequency/week the user inputed.
service: get authentication from Google
duration: the length of the new event (int)
frequency: number of days i... | ba3d7b688170a7e03d849070eaae69ed718257d6 | 3,646,723 |
import os
import importlib
def load_extensions():
"""
NOTE: This code is a copy of the code in econ_platform_core.extensions.__init__.py.
I will need to figure out how to make this function not use the current directory.
TODO: Merge this function with the one in econ_platform_core.
Imports all ... | 89c490d973d06621ac0c371a4204e4352462185b | 3,646,724 |
def byte_list_to_nbit_le_list(data, bitwidth, pad=0x00):
"""! @brief Convert a list of bytes to a list of n-bit integers (little endian)
If the length of the data list is not a multiple of `bitwidth` // 8, then the pad value is used
for the additional required bytes.
@param data List of bytes.... | b92bbc28cc2ffd59ae9ca2e459842d7f4b284d18 | 3,646,725 |
def admin_not_need_apply_check(func):
"""
admin用户不需要申请权限检查
"""
@wraps(func)
def wrapper(view, request, *args, **kwargs):
if request.user.username == ADMIN_USER:
raise error_codes.INVALID_ARGS.format(_("用户admin默认拥有任意权限, 无需申请"))
return func(view, request, *args, **kwargs)... | 9592d3a4691761be1f58c8a404d7cbef9bd01116 | 3,646,726 |
def parse_headers(header_list):
"""
Convert headers from our serialized dict with lists for keys to a
HTTPMessage
"""
header_string = b""
for key, values in header_list.items():
for v in values:
header_string += \
key.encode('utf-8') + b":" + v.encode('utf-8')... | 8a387a7a60044115c61838f1da853e4608e3840d | 3,646,727 |
def _rrv_add_ ( s , o ) :
"""Addition of RooRealVar and ``number''
>>> var = ...
>>> num = ...
>>> res = var + num
"""
if not isinstance ( o , val_types ) : return NotImplemented
if isinstance ( o , _RRV_ ) and not o.isConstant() : o = o.ve ()
elif hasattr ( o , '... | e3e41fe3ae53379f0b49a4a2aa14e3a401bae6b3 | 3,646,728 |
from haversine import haversine #import haversine function from library
def stations_by_distance(stations, p):
"""This module sorts stations by distance and returns a
list of (station, town, distance) tupules."""
list_station_dist = [] #initiates list to store stations and distance
#it... | 4a378090803b061b8ea9b17d6255038235c1b1ca | 3,646,729 |
import hashlib
def create_SHA_256_hash_of_file(file):
"""
Function that returns the SHA 256 hash of 'file'.\n
Logic taken from https://www.quickprogrammingtips.com/python/how-to-calculate-sha256-hash-of-a-file-in-python.html
"""
sha256_hash = hashlib.sha256()
with open(file, "rb") as f:
... | 14f62a49ea54f5fceb719c4df601fde165f5e55c | 3,646,730 |
def partition_average(partition):
"""Given a partition, calculates the expected number of words sharing the same hint"""
score = 0
total = 0
for hint in partition:
score += len(partition[hint])**2
total += len(partition[hint])
return score / total | 944f514e925a86f3be431bd4d56970d92d16f570 | 3,646,731 |
import queue
def set_params(config):
"""Configure parameters based on loaded configuration"""
params = {
'path': None,
'minio': None,
'minio_access_key': None,
'minio_secret_key': None,
'minio_secure': True,
'minio_ca_certs': None,
'minio_bucket': 'catal... | b1cc87d88b656cb6d57dcb0579276de8f0d744e8 | 3,646,732 |
def post_stop_watch():
"""
This method change watcher status to true and return -> "watching": false
"""
url = common.combine_url(
config.INGESTION_AGENT_URL,
config.INGESTION_WATCHER_STATUS,
config.INGESTION_STOP_WATCHER,
)
resp = base_requests.send_post_request(url)
... | 2b7634c78bf46c6365aac89f4be6908d8baf1bcf | 3,646,733 |
def combine_grad_fields(field1, field2):
"""
Combines two gradient fields by summing the gradiends in every point.
The absolute values of each pixel are not interesting.
Inputs:
- field1: np.array(N, M) of Pixels.
- field2: np.array(N, M) of Pixels.
Output:
- out_field: np.a... | 7cbe02280c33d9ed077a5b39f3df347c08c11417 | 3,646,734 |
import time
def start_queue_manager(hostname, portnr, auth_code, logger):
"""
Starts the queue manager process.
"""
p = Process(target=_queue_manager_target, args=(hostname, portnr, auth_code, logger))
p.start()
for i in range(10):
time.sleep(2)
if get_event_queue(hostname, por... | 428201417b76b896a3cdd6efe40b69a3cf297966 | 3,646,735 |
def edit_module_form(request, module_id):
"""
Only the instructor who is the creator of the course to which this module belongs can access this.
"""
course = Module.objects.get(moduleID=module_id).getCourse()
if request.user.role != 1 or (course.instructorID.userID != request.user.userID):
c... | ba1dc405c9249fb6227d0ed0d1cd0fc5b80caa78 | 3,646,736 |
def r2(y_true, y_pred):
"""
:math:`R^2` (coefficient of determination) regression score function.
Best possible score is 1.0, lower values are worse.
Args:
y_true ([np.array]): test samples
y_pred ([np.array]): predicted samples
Returns:
[float]: R2
"""
return r2_... | 3962c83a022cbab416a2914c0be749cf5b66d51e | 3,646,737 |
def passstore(config, name):
"""Get password file"""
return config.passroot / name | d0ca8c71650bd98dacd7d6ff9ed061aba3f2c43a | 3,646,738 |
import json
import sys
def _get(url, **fields):
"""Get a GroupMe API url using urllib3.
Can have arbitrary string parameters
which will be part of the GET query string."""
fields["token"] = login.get_login()
response = HTTP.request("GET", GROUPME_API + url, fields=fields)
# 2XX Success
if... | fcaa2153baf457a6370daa8eb3b35444c4677ca3 | 3,646,739 |
def coord_shell_array(nvt_run, func, li_atoms, species_dict, select_dict,
run_start, run_end):
"""
Args:
nvt_run: MDAnalysis Universe
func: One of the neighbor statistical method (num_of_neighbor_one_li,
num_of_neighbor_one_li_simple)
li_atoms: Atom grou... | 4a0b5f1417cb2184c866cf5ca5c138ed051f44a6 | 3,646,740 |
import os
from datetime import datetime
def get_events(number):
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the au... | a4a0ca917be06655a1aa77fddbdd8ccaf58424ba | 3,646,741 |
def plot_transactions_ts(transactional_df, frequency="M", aggregation="n_purchases", reg=False, black_friday_dates=None, plot_black_friday=False, plot_normal_only=False, **kwargs):
"""
plota a evolucao das compras no tempo
black_friday_dates:: list of datetime.date
"""
# preventing unwnated modific... | ba4764f91a37f4b88f63e52d7aa02660d8296d11 | 3,646,742 |
import time
def generate_token(public_id):
"""
Simple token generator returning encoded JWT
:param public_id: unique string user identification
:return JWT: authorization token for given public_id
"""
# if User.query.filter_by(public_id=public_id).one_or_none() is None:
# return jsonify(... | 88bbaabfeb8ba666daf532cae22f7486349a9a9d | 3,646,743 |
import logging
def get_user_permission_all_url_list(user_id):
"""
获取用户全部权限 url list
:param user_id: 用户id
:return:
"""
logging.info('get_user_permission_all_url_list')
try:
user_permission_list = db_get_user_permission_all_list(user_id)
permission_url_list = list()
f... | 7ad115dea2d791a46fa10b5ff8553a8485c8167f | 3,646,744 |
def plot_predicted_data(training_actual_df, predicted_df, date_col, actual_col,
pred_col=PredictionKeys.PREDICTION.value, prediction_percentiles=None,
title="", test_actual_df=None, is_visible=True,
figsize=None, path=None, fontsize=None,
... | 36e0fe88c664df1b93a7d96f217d4d2c94b96ad2 | 3,646,745 |
def CheckTreeIsOpen(input_api, output_api, url, closed, url_text):
"""Similar to the one in presubmit_canned_checks except it shows an helpful
status text instead.
"""
assert(input_api.is_committing)
try:
connection = input_api.urllib2.urlopen(url)
status = connection.read()
connection.close()
... | 540dd0ceb9c305907b0439b678a6444ca24c3f76 | 3,646,746 |
def tnr_ecma_st(signal, fs, prominence=True):
"""Computation of tone-to-noise ration according to ECMA-74, annex D.9
for a stationary signal.
The T-TNR value is calculated according to ECMA-TR/108
Parameters
----------
signal :numpy.array
A stationary signal in [Pa].
fs : intege... | 4dcb740899de5a9411fddb8ed41b0b1628a438f4 | 3,646,747 |
def pop_legacy_palette(kwds, *color_defaults):
"""
Older animations in BPA and other areas use all sorts of different names for
what we are now representing with palettes.
This function mutates a kwds dictionary to remove these legacy fields and
extract a palette from it, which it returns.
"""
... | 438ff6bb0f1300c614c724535d2215b2419fbb84 | 3,646,748 |
def trace_dot(X, Y):
"""Trace of np.dot(X, Y.T).
Parameters
----------
X : array-like
First matrix
Y : array-like
Second matrix
"""
return np.dot(X.ravel(), Y.ravel()) | 9c8d601144507cdbfb2d738af61a0016ea808d4a | 3,646,749 |
import gc
from datetime import datetime
async def handle_waste_view(ack, body, client, view):
"""Process input from waste form"""
logger.info("Processing waste input...")
logger.info(body)
raw_leaders = view['state']['values']['input_a']['leader_names']['selected_options']
leader_list = [" - " + n... | 101b85b947cc148176f2f4d067cb73c0386b56cd | 3,646,750 |
def random_superposition(dim: int) -> np.ndarray:
"""
Args:
dim: Specified size returns a 2^dim length array.
Returns:
Normalized random array.
"""
state_vector = np.random.standard_normal(dim).astype(complex)
state_vector += 1j * np.random.normal(dim)
state_vector /= np.lina... | f33867247a64c09571fcfc29c10e45e8e9921271 | 3,646,751 |
def predict(dag_model: Dag, test_data: Tensor) -> MultitaskMultivariateNormal:
"""
Can use this little helper function to predict from a Dag without
wrapping it in a DagGPyTorchModel.
"""
dag_model.eval()
with no_grad(), fast_pred_var():
return dag_model(test_data) | d4c0e2d48e2edf3f4e2b07b26024d92390efe4dc | 3,646,752 |
def edit_skill():
"""Edit a skill entry in the skills table for a certain user. """
id = request.form['id']
skill_level = request.form['skill_level']
skills.update({'skill_level': skill_level}, id=id)
return good_json_response('success') | 9b314aa51f990e1bbbd6bf75874e410e937fa595 | 3,646,753 |
def is_catalogue_link(link):
"""check whether the specified link points to a catalogue"""
return link['type'] == 'application/atom+xml' and 'rel' not in link | bc6e2e7f5c34f6ea198036cf1404fef8f7e7b214 | 3,646,754 |
def morlet_window(width: int, sigma: float) -> np.ndarray:
"""
Unadjusted Morlet window function.
Parameters
----------
width : integer (positive power of 2)
Window width to use - power of two as window of two corresponds to Nyquist rate.
sigma : float
Corresponds to the freque... | 2f0d6ff644a078b50bb510835a9bb2d2028ea143 | 3,646,755 |
def tfidfvec():
"""
中文特征值化
:return: None
"""
c1, c2, c3 = cutword()
print(c1, c2, c3)
tf = TfidfVectorizer()
data = tf.fit_transform([c1, c2, c3])
print(tf.get_feature_names())
print(data.toarray())
return None | 1a0fe0e4a28e6d963f49156476ed720df492718b | 3,646,756 |
import http
def resolve_guid(guid, suffix=None):
"""Resolve GUID to corresponding URL and return result of appropriate
view function. This effectively yields a redirect without changing the
displayed URL of the page.
:param guid: GUID value (not the object)
:param suffix: String to append to GUID... | 85a422f1c5709a44050595be4bf91ce1b937c0ef | 3,646,757 |
from typing import Any
def _is_array(obj: Any) -> bool:
"""Whether the object is a numpy array."""
return isinstance(obj, np.ndarray) | 4852e045fcef142c23a9370efbe3b5ffe7a9f8a3 | 3,646,758 |
def has_ao_1e_int_overlap(trexio_file) -> bool:
"""Check that ao_1e_int_overlap variable exists in the TREXIO file.
Parameter is a ~TREXIO File~ object that has been created by a call to ~open~ function.
Returns:
True if the variable exists, False otherwise
Raises:
- Exception from ... | 53b5ec13ff7c32af5692972d586921a4d5bc07ef | 3,646,759 |
from typing import Sequence
from typing import Set
async def get_non_existent_ids(collection, id_list: Sequence[str]) -> Set[str]:
"""
Return the IDs that are in `id_list`, but don't exist in the specified `collection`.
:param collection: the database collection to check
:param id_list: a list of doc... | b13c61f4528c36a9d78a3687ce84c39158399142 | 3,646,760 |
def create_source_fc(header):
"""
Creates :class:`parser.file_configuration_t` instance, configured to
contain path to C++ source file
:param header: path to C++ source file
:type header: str
:rtype: :class:`parser.file_configuration_t`
"""
return file_configuration_t(
data=he... | 29cd1112b9f59091b286f5222e62e9bec309bd36 | 3,646,761 |
def StorageFlatten(cache_line_size, create_bound_attribute=False):
"""Flatten the multi-dimensional read/write to 1D.
Parameters
----------
cache_line_size: int
The size of CPU cache line.
create_bound_attribute:
Whether to create bound attributes.
Returns
-------
fp... | cb535450d3a503632f66e015555148d211f3e6f9 | 3,646,762 |
def wrap(node):
"""Stringify the parse tree node and wrap it in parentheses if it might be
ambiguous.
"""
if isinstance(node, (IntNode, CallNode, SymbolNode)):
return str(node)
else:
return "(" + str(node) + ")" | 9ac5d9a7d5e6d6539231ba6897a44e2787d92809 | 3,646,763 |
def _ParseProjectNameMatch(project_name):
"""Process the passed project name and determine the best representation.
Args:
project_name: a string with the project name matched in a regex
Returns:
A minimal representation of the project name, None if no valid content.
"""
if not project_name:
retu... | cb9f92a26c7157a5125fbdb5dd8badd7ffd23055 | 3,646,764 |
from typing import OrderedDict
def assign_variables(assignment_expressions, df, locals_dict, df_alias=None, trace_rows=None):
"""
Evaluate a set of variable expressions from a spec in the context
of a given data table.
Expressions are evaluated using Python's eval function.
Python expressions hav... | b8e28bae70eaa56b49537011d3fd3079f640ab76 | 3,646,765 |
import io
import zipfile
def getCharts(dmldata: bytearray) -> list:
"""Get DrawingML object from clipboard"""
stream = io.BytesIO(dmldata)
with zipfile.ZipFile(stream, "r") as z:
with z.open("[Content_Types].xml") as f:
tree = ET.fromstring(f.read())
part_names = []
for... | 402bf7e45be03ccda31563c2fc10afe2d4d09077 | 3,646,766 |
def explore_validation_time_gap_threshold_segments(participant_list, time_gap_list = [100, 200, 300, 400, 500, 1000, 2000], prune_length = None,
auto_partition_low_quality_segments = False):
"""Explores different threshiold values for the invalid time gaps in the Segments ... | bd88f292a00986212ae36e383c4bb4e3cd94067c | 3,646,767 |
def convolve_design(X, hrf, opt=None):
"""convolve each column of a 2d design matrix with hrf
Args:
X ([2D design matrix]): time by cond, or list of onsets
hrf ([1D hrf function]): hrf
opt: if onset case, provides n_times and tr for
interpolation
Returns:
[conv... | 02f2473ff18a78759c87884cd0f7fc94db6e0e2d | 3,646,768 |
from typing import List
def relax_incr_dimensions(iet, **kwargs):
"""
Recast Iterations over IncrDimensions as ElementalFunctions; insert
ElementalCalls to iterate over the "main" and "remainder" regions induced
by the IncrDimensions.
"""
sregistry = kwargs['sregistry']
efuncs = []
ma... | 0d7af62309d427c6477329ed6b7a5dccab390a51 | 3,646,769 |
def _get_lspci_name(line):
"""Reads and returns a 'name' from a line of `lspci` output."""
hush = line.split('[')
return '['.join(hush[0:-1]).strip() | 92910d0f4d9dce1689ed22a963932fb85d8e2677 | 3,646,770 |
def dumps_bytes(obj):
"""
Serialize ``obj`` to JSON formatted ``bytes``.
"""
b = dumps(obj)
if isinstance(b, unicode):
b = b.encode("ascii")
return b | 5ee94b2bd5a8bcd2f8586578e6d86084a030d93a | 3,646,771 |
def get_child_right_position(position: int) -> int:
"""
heap helper function get the position of the right child of the current node
>>> get_child_right_position(0)
2
"""
return (2 * position) + 2 | 2a5128a89ac35fe846d296d6b92c608e50b80a45 | 3,646,772 |
from typing import List
from typing import Dict
def convert_paragraphs_to_s2orc(paragraphs: List, old_to_new: Dict) -> List[Dict]:
"""
Convert paragraphs into S2ORC format
"""
# TODO: temp code to process body text into S2ORC format. this includes getting rid of sub/superscript spans.
# als... | 922f6a238f63039e68b1a14342974d6b3d47ba8f | 3,646,773 |
def get_feature_set_details(shape_file_path):
""" This function gets the shape type of the shapefile and make a list
of fields to be added to output summary table based on that shape type """
try:
# Checking for geometry type
feat_desc = arcpy.Describe(shape_file_path)
arcpy.AddMes... | 9c4eddd9963751d195f4165ecc862d2753bb2067 | 3,646,774 |
def get_label_parts(label):
"""returns the parts of an absolute label as a list"""
return label[2:].replace(":", "/").split("/") | 44998aad262f04fdb4da9e7d96d2a2b3afb27502 | 3,646,775 |
import argparse
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Argparse Python script',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'-c',
'--cdhit',
help='Output file from CD-HIT (clu... | d961b0a81bd0e6db9687927c8b23f8cba5a3cfce | 3,646,776 |
import pandas
import numpy
def combined_spID(*species_identifiers):
"""Return a single column unique species identifier
Creates a unique species identifier based on one or more columns of a
data frame that represent the unique species ID.
Args:
species_identifiers: A tuple containing one or ... | d50abeccc6fb0235fd8a58dfadbd7c6bdb72825d | 3,646,777 |
import copy
def qr(A, prec=1e-10):
"""
computes a faster and economic qr decomposition similar to:
http://www.iaa.ncku.edu.tw/~dychiang/lab/program/mohr3d/source/Jama%5CQRDecomposition.html
"""
m = len(A)
if m <= 0:
return [], A
n = len(A[0])
Rdiag = [0] * n;
QR = copy.deep... | fe1ffa20b5ad44a76837bd816ca07c3388ebcb4d | 3,646,778 |
def split_range(r, n):
"""
Computes the indices of segments after splitting a range of r values
into n segments.
Parameters
----------
r : int
Size of the range vector.
n : int
The number of splits.
Returns
-------
segments : list
The list of lists of fi... | 34f570933a5eb8772dc4b2e80936887280ff47a4 | 3,646,779 |
def is_connected_to_mongo():
"""
Make sure user is connected to mongo; returns True if connected, False otherwise.
Check below url to make sure you are looking for the right port.
"""
maxSevSelDelay = 1 # how long to spend looking for mongo
try: # make sure this address is running
... | 2bf28835ae192d41836f2335ce5c1e152b0e0838 | 3,646,780 |
def _fill_three_digit_hex_color_code(*, hex_color_code: str) -> str:
"""
Fill 3 digits hexadecimal color code until it becomes 6 digits.
Parameters
----------
hex_color_code : str
One digit hexadecimal color code (not including '#').
e.g., 'aaa', 'fff'
Returns
-------
f... | d91df947fcc5f0718bbd9b3b4f69f1ad68ebeff4 | 3,646,781 |
import re
def normalize(text: str, convert_digits=True) -> str:
"""
Summary:
Arguments:
text [type:string]
Returns:
normalized text [type:string]
"""
# replacing all spaces,hyphens,... with white space
space_pattern = (
r"[\xad\ufeff\u200e\u200d\u200b\x7f\u202a\... | 43bddc9c78615ab4cc58a732c164ad81b6848dc1 | 3,646,782 |
def register_name_for(entity):
"""
gets the admin page register name for given entity class.
it raises an error if the given entity does not have an admin page.
:param type[pyrin.database.model.base.BaseEntity] entity: the entity class of
a... | c43ab1a1e08058435c6680886d0e7c1dd81b1bef | 3,646,783 |
def index():
"""Show all the posts, most recent first."""
db = get_db()
posts = db.execute(
# "SELECT p.id, title, body, created, author_id, username"
# " FROM post p"
# " JOIN user u ON p.author_id = u.id"
# " ORDER BY created DESC"
"SELECT *, l.author_id as love_a... | b40a302ef1278f3fb0227c40db4764c22f5f0cb8 | 3,646,784 |
import requests
def get_user_information(fbid, extra_fields=[]):
""" Gets user basic information: first_name, last_name, gender,
profile_pic, locale, timezone
:usage:
>>> # Set the user fbid you want the information
>>> fbid = "<user fbid>"
>>> # Call the function passing the fbid... | 7765fec33fc70a67c3249e6417d0f75acba0ba2e | 3,646,785 |
import re
def parseTeam(teamString):
"""Parse strings for data from official Pokemon Showdown format.
Keyword arguemnts:\n
teamString -- a team string, copied from pokepaste or pokemon showdown
"""
pokemonList = teamString.split('\n\n')
teamList = []
#print(pokemonList)
for pokemon i... | 70680cf1eca50a4738b8afc7ab12fcd86b48d01d | 3,646,786 |
import os
def url_scheme(url, path):
"""Treat local URLs as 'file://'."""
if not urlparse(url).scheme:
url = "file://" + os.path.join(path, url)
return url | dba51b0c0a3fbbbf32186a8820cfbd762485a3af | 3,646,787 |
def mix_style(style_codes,
content_codes,
num_layers=1,
mix_layers=None,
is_style_layerwise=True,
is_content_layerwise=True):
"""Mixes styles from style codes to those of content codes.
Each style code or content code consists of `num_layers` co... | 377a0638d84ed084a91eb6dfb20302e56ab85647 | 3,646,788 |
import logging
def train_many_models(extractor, param_grid, data_dir, output_dir=None,
**kwargs):
"""
Train many extractor models, then for the best-scoring model, write
train/test block-level classification performance as well as the model itself
to disk in ``output_dir``.
... | 783cb5a524a58023d79e88eff4b46a0e713ca8cc | 3,646,789 |
from datetime import datetime
import sys
import os
def analyze_iw(aoi, doi, dictionary, size, aoiId):
"""
Function that pre-processes sentinel-2 imagery and runs the LCC change detection algorithm
Parameters:
aoi(ee.Feature): area of interest with property 'landcover'
doi(ee.Date): da... | 4883daea5b3e05d4af5dafcb257c8555ae361a9a | 3,646,790 |
import collections
def _build_client_update(model: model_lib.Model,
use_experimental_simulation_loop: bool = False):
"""Creates client update logic for FedSGD.
Args:
model: A `tff.learning.Model` used to compute gradients.
use_experimental_simulation_loop: Controls the reduce loo... | 8ba68ebba2c6520e9c7a89975d16dc20debf52eb | 3,646,791 |
import ipaddress
def ipv4_addr_check():
"""Prompt user for IPv4 address, then validate. Re-prompt if invalid."""
while True:
try:
return ipaddress.IPv4Address(input('Enter valid IPv4 address: '))
except ValueError:
print('Bad value, try again.')
raise | e85681cdcedb605f47240b27e8e2bce077a39273 | 3,646,792 |
import os
import imp
def getPlugins():
"""
List the plugins located in the plugins folder.
"""
plugins = []
pluginList = os.listdir(PluginFolder)
for pluginName in pluginList:
location = os.path.join(PluginFolder, pluginName)
if not os.path.isdir(location) or not MainModule + ... | d88ca8c19a35ddf49fda37e41e1f8f3b01cf9974 | 3,646,793 |
def energybalance_erg(ratio,crew,erg,w0=4.3801,dt=0.03,doplot=1,doprint=0,theconst=1.0):
"""
calculates one stroke with ratio as input, using force profile in time domain
"""
# w0 = initial flywheel angular velo
# initialising output values
dv = 100.
vavg = 0.0
vend = 0.0
power = 0.0
#... | a742b88394f194afee3ef89bc4e878027fcac8b5 | 3,646,794 |
import os
import subprocess
def get_gpu_count():
"""get avaliable gpu count
Returns:
gpu_count: int
"""
gpu_count = 0
env_cuda_devices = os.environ.get('CUDA_VISIBLE_DEVICES', None)
if env_cuda_devices is not None:
assert isinstance(env_cuda_devices, str)
try:
... | fad511d32419daa1f2d9ac569ebd9201a9aa1de9 | 3,646,795 |
def get_EXP3_policy(Q, eta, G_previous):
"""
Obtain EXP-3 policy based on a given Q-function. Also, return updated
values of G, to be used in future calls to this function.
Inputs:
1) Q: a num_states x num_actions matrix, in which Q[s][a] specifies
the Q-function in state s... | 80e886142fff398801e4f767ed09392d7f8b398c | 3,646,796 |
def table_content(db, table):
"""
return a 2 dimentioanl array cont-aining all table values
========================================================
>>> table_content("sys", "host_ip")
[[1, 2, 3],
[2, 3, 4],
[3, 4, 5]]
========================================================
"""
... | 51b973f442131a157aa13ae0c0ed9f1d07a4115d | 3,646,797 |
def process_sort_params(sort_keys, sort_dirs, default_keys=None,
default_dir='asc'):
"""Process the sort parameters to include default keys.
Creates a list of sort keys and a list of sort directions. Adds the default
keys to the end of the list if they are not already included.
... | 1f11f5d7d4fbe5c1864ace120c1dbde7b6023acb | 3,646,798 |
def namify(idx):
"""
Helper function that pads a given file number and return it as per the dataset image name format.
"""
len_data = 6 #Ilsvr images are in the form of 000000.JPEG
len_ = len(str(idx))
need = len_data - len_
assert len_data >= len_, "Error! Image idx being fetched is incorr... | 069ff7a297f944e9e0e51e5e100276a54fa51618 | 3,646,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.