content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import io def bytes_to_PCM_16bits(bytes, start=0, end=None): """ Transform audio file to a format readable by scipy, ie. uncompressed PCM 16-bits. Support transformation from any format supported by ffmpeg. """ try: audiofile = AudioSegment.from_file(bytes) except Exception as e: ...
cac297a610b90a3459542def406cd62f58dd86bd
35,700
import os def backup_exists(filename): """ Return True if backup exists and no_dupes is set """ path = cfg.nzb_backup_dir.get_path() return path and os.path.exists(os.path.join(path, filename + ".gz"))
d962239452d1b3906601ad4d419cd406d0bfc611
35,701
import keras from keras.datasets import cifar10 from keras.utils import np_utils def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000): """ Preprocess CIFAR10 dataset :return: """ global keras if keras is None: # These values are specific to CIFAR10 img_rows = 32 img_cols ...
1a23e78aa1cb873f18b31df616f467cea8db3f5e
35,702
def create_log_group_arn(logs_client, hosted_zone_test_name): """Return ARN of a newly created CloudWatch log group.""" log_group_name = f"/aws/route53/{hosted_zone_test_name}" response = logs_client.create_log_group(logGroupName=log_group_name) assert response["ResponseMetadata"]["HTTPStatusCode"] == 2...
79113cc7c9ac844c4d38cd1780b38d14a112b40d
35,703
def _make_filetags(attributes, default_filetag = None): """Helper function for rendering RPM spec file tags, like ``` %attr(0755, root, root) %dir ``` """ template = "%attr({mode}, {user}, {group}) {supplied_filetag}" mode = attributes.get("mode", "-") user = attributes.get("user", "-"...
56898ec1fc974721150b7e1055be3ab3782754a2
35,704
from typing import Union def button_callback(update: Update, context: CallbackContext) -> Union[None, str]: """Обработчик запросов обратного вызова""" query = update.callback_query query.answer() message = query.data.split() return callbacks[message[0]](update=update, context=context, query=query,...
0c9e04f29fd931288cdb0d4cab0c732b03fd8fa0
35,705
def has_banking_permission(data): """ CHecks to see if the user hs the correct permission. Based on Castorr91's Gamble""" if not Parent.HasPermission(data.User, CESettings.BankingPermissions, CESettings.BankingPermissionInfo): message = CESettings.PermissionResp.format(data.UserName, CESettings.Banking...
39dcb62c36e2f89a51503902db183a4c128128e6
35,706
from datetime import datetime def calc_temps(start='start_date'): """min, max, avg temp for start range""" start_date = datetime.strptime('2016-08-01', '%Y-%m-%d').date() start_results = session.query(func.max(Measurements.tobs), \ func.min(Measurements.tobs),\ ...
78aaa7721c7f0d83843d85af55d2262faad69cdc
35,707
def reindex(tensor, shape, displacement=.5): """ Re-color the given tensor, by sampling along one axis at a specified frequency. .. image:: images/reindex.jpg :width: 1024 :height: 256 :alt: Noisemaker example output (CC0) :param Tensor tensor: An image tensor. :param list[int...
a9aa0e323b7e2ee4f06e4f6a44fecb0c57e1acb7
35,708
def test_dal_getitem_access(): """ Verify `__getitem__` is identical to `__getattr__` """ expected = "foo" class SampleService(Service): def sample_method(self): return expected dm = _BaseDataManager() dm.register_services(sample=SampleService()) with dm.context()...
8202385241a8ec7f4c4634b644dd8f459f5642cf
35,709
def seq_to_matrix(seq, letter_to_index=None): """Convert a list of characters to an N by 4 integer matrix Parameters ---------- seq : list list of characters A,C,G,T,-,=; heterozygous locus is separated by semiconlon. '-' is filler for heterozygous indels; '=' is homozygous deletions ...
f43e406bc8efecc0b00ec7a22b57ebee4e16efc2
35,710
def m(id, part = None): """ Provide any measure (that we know of) about this design. This acts as a central registry for measures to not clutter the global namespace. "m" for "measure". Most numbers can be adjusted, allowing customization beyond the rather simple parameters in the OpenSCAD Customi...
0c88b195ac37e3357861392b4cb67757a2bec363
35,711
def plot( title: str, body_system: Body_System, x_start: float = -1, x_end: float = 1, y_start: float = -1, y_end: float = 1,) -> None: """ Utility function to plot how the given body-system evolves over time. No doctest provided since this function does not have a return value....
33cdeee3be9625c82643d3cefa75a5d554b0f54e
35,712
from caffe2.python import workspace, core def GetGPUMemoryUsageStats(): """Get GPU memory usage stats from CUDAContext/HIPContext. This requires flag --caffe2_gpu_memory_tracking to be enabled""" workspace.RunOperatorOnce( core.CreateOperator( "GetGPUMemoryUsage", [], ...
84cd6d5b4786f666bfa756addf4d3010af6737f9
35,713
import typing def from_jsonable(return_type: typing.Any, obj: typing.Any) -> typing.Any: """Return an instance of the specified 'return_type' that has been constructed based on the specified 'obj', which is a composition of python objects as would result from JSON deserialization by the 'json' module. ...
6e7df09a53c116fe48cabb6e18587f297640e2cc
35,714
def _convert_symbol(op_name, inputs, attrs, identity_list=None, convert_map=None): """Convert from mxnet op to nnvm op. The converter must specify some conversions explicitly to support gluon format ops such as conv2d... Parameters ---------- op_name : st...
bf525a15b131369cb5f77d4681cab374afc1287c
35,715
from typing import List from typing import Union def non_parametric_double_ml_learner(df: pd.DataFrame, feature_columns: List[str], treatment_column: str, outcome_column: str, ...
0a78944ecf81d5d40114a517dbae587bfc5bb13c
35,716
def convert_image_cv2_to_cv(image, depth=cv.IPL_DEPTH_8U, channels=1): """ Converts an OpenCV2 wrapper of an image to an OpenCV1 wrapper. Source: http://stackoverflow.com/a/17170855 Args: image: image used by OpenCV2 depth: depth of each channel of the image ...
9a803eedadbb1082d8614f823b6d4063772fdaa3
35,717
def create_targetmd_input(cvs, stringpath, steps_per_point=10000, kappa=10000.0, backwards=False): """ Units info https://plumed.github.io/doc-v2.4/user-doc/html/_u_n_i_t_s.html default kj/mol for energy, A for distance. Spring constant has unit Energy units per Units of the CV :param args: :par...
b0ccd59105bd4dbbe5deec61ba74efd32e3e9822
35,718
def split_game_path(path): """Split a game path into individual components.""" # filter out empty parts that are caused by double slashes return [p for p in path.split('/') if p]
9b939058aa7f8b3371d3e37b0252a5a01dba4e7b
35,719
from typing import Any from re import DEBUG import sys def group_requirement(ctx: Any, institution: str, requirement_id: str) -> dict: """ group_requirement : NUMBER GROUP groups qualifier* label? ; groups : group (logical_op group)*; // But only OR should occur group : LP (...
32eff5af577afed6905988786d3110c272fd3bf7
35,720
def create_complete_dag(workbench: Workbench) -> nx.DiGraph: """creates a complete graph out of the project workbench""" dag_graph = nx.DiGraph() for node_id, node in workbench.items(): dag_graph.add_node( node_id, name=node.label, key=node.key, versio...
026cb6ab7e168f6c4f1d84e7ae574d4b62bbbfe2
35,721
import os from datetime import datetime def read_geojson_metadata(geojson_file, start_epoch, end_epoch, date_field, date_format): """Reads metadata from geojson file from an input directory and returns a list of wkt strings for points within the given time range :param geojson_file: input geojson file...
612b538f324124e1b86d51d131050c848fb1da20
35,722
import csv def read_single_disk(image_id): """ Stores a single image to disk. Parameters: --------------- image_id integer unique ID for image Returns: ---------- image image array, (32, 32, 3) to be stored label associated meta data, int lab...
094b8b98fba85a224d613efc7623ed497129bfc7
35,723
import click def try_get_balance(agent_config: AgentConfig, wallet: Wallet, type_: str) -> int: """ Try to get wallet balance. :param agent_config: agent config object. :param wallet: wallet object. :param type_: type of ledger API. :retun: token balance. """ try: if type_ no...
5cf32708c493b54a4950eee01144259be3be481d
35,724
def test_self_iat_hook_success(): """Test hook success in single(self) thread""" pythondll_mod = [m for m in windows.current_process.peb.modules if m.name.startswith("python") and m.name.endswith(".dll")][0] RegOpenKeyEx = [n for n in pythondll_mod.pe.imports['advapi32.dll'] if n.name == function_to_hook][0...
682a8c251d0dee3e923f92bdfe0b4402d69c6b69
35,725
def ravel(a, order='C'): """Returns a flattened array. It tries to return a view if possible, otherwise returns a copy. This function currently does not support the ``order = 'K'`` option. Args: a (cupy.ndarray): Array to be flattened. order ({'C', 'F', 'A'}): Read the ele...
5f0f74a10c20caba4c2b97c7a50430b9948e992e
35,726
import re def find_kwic(item, regexes, shell_nouns): """This function takes the location of a vertically annotated text of COCA/COHA and transforms it to the form [['word', 'lemma', 'POS'], ['word2', 'lemma2', 'POS2'], ...] As a second argument the regex objects to be used in the search are passed (they are built...
65a76b7be4037f2e142b20378ac7a8c68dc7f4c2
35,727
def is_numeric(value: str): """Return True if given value is a number""" return value.isdigit()
fe61469ab388534a17d079590591378f87078cd3
35,728
def mixed(operations, paths, _fs=None): """Decorates a function that supports multiple types of action. :param operations: The list of operations (e.g. ["readlink"]). :param paths: The paths to match (e.g. ["/<file>", "/<file>.txt"]). :param _fs: An optional _DiazedFileSystem instance (mostly for testi...
7a7144cb49d64cca74f0e366af3d4a9574a86f8b
35,729
def bladeTELoss(w, t, Temp, alpha, beta, rho, C, K, Y): """Thermoelastic calculations for blades Invoked for upper joint only (there is no lower blade) w = angular frequency t = blade thickness Temp = temperature alpha = coeff of thermal expansion beta = temp dependence of Young's modulus ...
d655542a0e09bff311c6f0cbbf57e2c8de954149
35,730
def pretty_snp_association(association): """ Prints association stats in roughly the same format as STOPGAP for a cluster of SNPs Args: GeneSNP_Association Returntype: String """ snp = association.snp gene_name = association.gene.name gene_id = association.gene.id score = association.score results = [sn...
f302c451463cce38a2abcab60d322ec876da4efb
35,731
import torch def nb_Genes(w, device="cpu"): """ ========================================================================== \n Return the number of selected genes from the matrix w \n #----- INPUT \n w ...
ba9d7f150e177799c1fdf4c521859b6879b09997
35,732
def S_IMODE(mode): """Return the portion of the file's mode that can be set by os.chmod(). """ return mode & 0o7777
b77df185704a5df812dc1fe2431f80d847c9bc15
35,733
import threading import sys import six def sync(loop, func, *args, **kwargs): """ Run coroutine in loop running in separate thread. """ if not loop._running: try: return loop.run_sync(lambda: func(*args, **kwargs)) except RuntimeError: # loop already running pa...
ecf9563df0968c367773e3ad0add1a47b5f54390
35,734
def storage_initial_constraint_rule(backend_model, node, tech): """ If storage is cyclic, allow an initial storage to still be set. This is applied to the storage of the final timestep/datestep of the series as that, in cyclic storage, is the 'storage_previous_step' for the first timestep/datestep. ...
b538cd05f834b18471b348d73e6c5a4ca3c5acab
35,735
def get_hform_298k_thermp(output_string): """ Obtains deltaHf from thermp output """ # Line pattern containing the DeltaHf value at 298 K dhf298_pattern = ('h298 final' + app.one_or_more(app.SPACE) + app.capturing(app.FLOAT)) dhf298 = float(apf.last_c...
1ac0a111501a0dff5987c662302b6cabf09e6477
35,736
def filter_peaks_width(peakdic, width_range): """ Filter a dictionary of peaks by peak range width. - peakdic: Dictionary of peaks per sequence (chromosome) - with_range: Tuple with the minimum and maximum peak peak width to keep. Other peaks will be discarded """ minim, maxim = width_r...
ede51a85999daf589c233fb53e4834ebb3cf3b0a
35,737
def scrape_course(data): """Initializes the course if it doesn't exist and returns a list of ("instructor", data) pairs.""" print " " + data['url'] instructors = [] coursesoup = BeautifulSoup(requests.get(data['url']).text) ratingstab = coursesoup.find(id="tab-ratings") floatdivs = ratingsta...
0e3fc6e05774ec89fb67dcaab1acf3d38853ae0b
35,738
def send_tp(mcr, x, y, z, a, b, player): """ Send the telepor command using mcr. 'x', 'y' 'z' are cartesian coordinates, 'a' and 'b' are angles. """ tp_parameters = [str(i) for i in ["/tp", player, x, y, z, a, b]] mc_command = ' '.join(tp_parameters) resp = mcr.command(mc_command) return...
43c5d94d209c6a4f9d988c6c2711fc3927bd37c3
35,739
import os def f2suff(forfile, opath, suff): """ Construct output filename in opath with new suffix Parameters ---------- forfile : str Fortran90 file name opath : str Relative output path. Script assumes output path: dirname(forfile)/opath suff : str Suffix...
8f4d66aaec7b46ed40d3bca6fedbea4646872203
35,740
def ori_smooth(directions,frames_per_second=None,return_missing=False): """smooth orientations using an RTS smoother This treats orientations as XYZ positions """ dt = 1.0/frames_per_second A = np.array([[1, 0, 0, dt, 0, 0], [0, 1, 0, 0, dt, 0], [0, 0, 1, 0, 0, ...
85871a95409d059617d41931155c14c6b9532d93
35,741
from typing import Sequence import array def compile_array(data: Sequence[float], format="xyseb") -> array.array: """Gather point components from input data. Format codes: - ``x`` = x-coordinate - ``y`` = y-coordinate - ``s`` = start width - ``e`` = end width - ``b`` ...
6de809fdcd32a1b39a2cc3e8639cb8047fc476fa
35,742
def nms(bboxes, iou_threshold, sigma = 0.3, method = 'nms'): """ function to implement non-maximal suppression / softmax non-maximal supression of bboxes """ """ takes bboxes with the shape of (num_of_box, 6), where 6 => (xmin, ymin, xmax, ymax, score, class) """ # remove duplicates in classes ...
5e2b390f2c920d6d0f6909bb058cc50b316a36b3
35,743
def hls_to_hex(h, l, s): """Converts a (hue, lightness, saturation) tuple to a "#rrbbgg" string. Args: h, l, s: the HLS values Returns: a hex string """ return rgb_to_hex(*hls_to_rgb(h, l, s))
562e4f802b1cc19734574186cbf107f3a288e044
35,744
import sys def get_run_info_hiseq( instrument_model, application_version, tree ): """ Helper function to get some info about the sequencing runs. Args: tree: xml tree Returns: dict: basic statistics about run, like date, instrument, number of lanes, flowcell ID, read lengths, etc. ...
23b29deee55b7edd98671f44181e4b7fe2be77b1
35,745
def seconds_to_hhmmssms(seconds): """Parses the number of seconds after midnight and returns the corresponding HH:MM:SS.f-string. Args: seconds (float): number of seconds after midnight. Returns: str: the corresponding HH:MM:SS.f-string. """ int_seconds = int(seconds) ms = roun...
ce68c6238de4229aed99d3e4a72596d72f97af7c
35,746
import torch def sample_with_probs(model, x, steps, temperature=1.0, sample=False, top_k=None, first_sentence=False): """ A modified version of sample from mingpt.util that also returns probability of each sentence and allow end with first sentence complete """ block_size = model.get_block_size() ...
643e8e0f05c126180fa0998212d8070394df8764
35,747
def expression(processor, composer, searcher): # type: (Parser, Compiler, scanner.Scanner) -> Tuple[Parser, Compiler] """Compiles expression.""" return parse_precedence(processor, composer, searcher, Precedence.PREC_ASSIGNMENT)
84b2e3f832a6dcbb89199f1e5c3b69f2044fb36c
35,748
import time def get_games_results(game_name: str, web: str = "all"): """ Get games results from spiders :param game_name: :param web: :return: list of games, obtained from spiders. """ games = [] not_formatted_games = [] time.sleep(get_random_delay()) if web == "eneba": ...
a78b520aa9426a4ba733a060f4a34432b35d8bce
35,749
def plot_pr_curve(y_true, y_pred, title=None): """ Convenience function for plotting precision recall curve @param: y_true - ground truth @type: array like @param: y_pred_train - predictions @type: array like """ precision, recall, _ = precision_recall_curve(y_true, y_pred) avg_prec...
ad8575afc92d1e03b2ab9a8f27395ebfec0f606f
35,750
def matrix_from_interactions(interactions, mapping, default=0.0): """Generate numpy matrices from interaction dictionary :param interactions: dictionary read from WORDOM avgpsn :param mapping: residuemap, preserves residue names :param default: default interaction :return: tuple of interaction stre...
c120ed1d56aed8c3b25a2c06d579af5d76705377
35,751
def to_flags(value): """Return a (flags, ednsflags) tuple which encodes the rcode. *value*, an ``int``, the rcode. Raises ``ValueError`` if rcode is < 0 or > 4095. Returns an ``(int, int)`` tuple. """ if value < 0 or value > 4095: raise ValueError('rcode must be >= 0 and <= 4095') ...
12477f6db3f1124d08884815ded5f2313ab1af98
35,752
def map_mix_query_attr_to_ch(mixing_query): """Map the mixing query attributes (tip_angle and phase) to the channel index. If the attribute is defined for the channel use the defined value else set it to 0. Args: spectral_dimension: A list SpectralDimension objects. index: The index of the ...
9192b9abbc2710b8ebdf172ad34c3dfadf8048ef
35,753
def masked( arr, v, mask ): """ Performs the 1D convolution on arr, omitting pixels under the mask """ arr = arr.astype(float) smoothed = conv( arr*mask, v ) norm = conv( mask.astype(np.float), v ) return smoothed/norm
ac12e1703b931800bcaea1d496dceb98e1c9303b
35,754
def fetch_ssr(url): """Retrive ssr links form url, return a list.""" # TODO: sometimes we need to try to get via a proxy. # base64_ssr = requests.get(url).text headers = { 'User-Agent': 'Mozilla/5.0', } req = request.Request(url, headers=headers) base64_ssr = request.url...
4174ce3cce0c2ba8018e93a005dedec74e6bd47c
35,755
import subprocess def check_smv_with_counterexample(FnameSMV, DynamicReorder=True, DisableReachableStates=True): """ Calls :ref:`installation_nusmv` with the query defined in the *smv* file *FnameSMV*. The remaining arguments are :ref:`installation_nusmv` options, see the manual at http://nusmv.fbk.eu for...
0402269e8a627012f1f08d6e91526ed69bede07b
35,756
from datetime import datetime def api_get_videos_duration(list_videos, api_service): """Get the duration of 50 videos at once. :param list_videos: A list of video IDs, maximum size 50. :param api_service: API Google Token generated with Google.py call. :return: a dictionary associating video id and d...
a88dd81b510ba99038401e90eb524194860a2c83
35,757
def build_pieces(headers, batch_size, start, end, max_piece_size=100000, metadata_columns=None): """ Build pieces function takes as input a list of headers and returns a list of pieces split in size maximum max_piece_size. Input: (filename, count, count_before) Output: (filename:str, piece_start:int...
92f3ac97d1a9ec16c0aea491ac773707463d05e3
35,758
from typing import Dict def collect_values(wdlfile: str, separate_required: bool, category_key: str, fallback_category: str, description_key: str, fallback_description: str, fallback_description_to_object: bool, strict: bool) -> Dict: """...
356fcdde70ca644c2bf9fd8d78ed0fba539c3aaf
35,759
def _GetConfigMapsChanges(args): """Return config map env var and volume changes for given args.""" volume_kwargs = {} env_kwargs = {} updates = _StripKeys( getattr(args, 'update_config_maps', None) or args.set_config_maps or {}) volume_kwargs['updates'] = { k: v for k, v in updates.items() if _I...
c82e3d8d85cf224c4af7ebb397136aa253e36a17
35,760
import os def get_std_out_file(app_name: str): """Get temporary stdout file for the app Args: app_name: Name of the Application """ default_dir = get_default_dir(app_name) file_name = os.path.join(default_dir, "std_out.txt") return file_name
7993450a0d40effe07d061f8fdb90a3fbbea4aba
35,761
import torch def dice_loss(pred, target): """Cacluate dice loss Parameters ---------- pred: predictions from the model target: ground truth label """ smooth = 1.0 pred = torch.sigmoid(pred) p_flat = pred.view(-1) t_flat = target.view(-1) i...
5bdede57fd34340b823324f962b20e5481333adf
35,762
import tqdm import requests def stock_em_dxsyl(market: str = "上海主板") -> pd.DataFrame: """ 东方财富网-数据中心-新股数据-打新收益率 http://data.eastmoney.com/xg/xg/dxsyl.html :param market: choice of {"上海主板", "创业板", "深圳主板"} :type market: str :return: 指定市场的打新收益率数据 :rtype: pandas.DataFrame """ market_ma...
42eaac231a9c5a2ab7e5d209ac8f2093de0869a8
35,763
def get_warningness() -> int: """Gets the warning level of the entire program""" return _warningness
57bb29e6697698707132435ccf0f27aba9bab0d2
35,764
import scipy def distanceMetrics(vol1, vol2, voxelsize_mm): """ avgd[mm] - Average symmetric surface distance rmsd[mm] - RMS symmetric surface distance maxd[mm] - Maximum symmetric surface distance """ # crop data to reduce computation time pads1 = getDataPadding(vol1) pads2 = getDataP...
684db2e73cf861fcf657ccd6a979ee42187f5b47
35,765
def point_in_quadrilateral_2d( point: np.ndarray, quadrilateral: np.ndarray ) -> bool: """Determines whether a point is inside a 2D quadrilateral. Parameters ---------- point : np.ndarray (2,) array containing coordinates of a point. quadrilateral : np.ndarray (4, 2) array conta...
cde2c018d792f8ee406a8fe4ca3eaf336ccdd0b1
35,766
def pSEDIa( sedtype ): """ returns the likelihood of observing host galaxy with the given rest-frame B-K color, assuming the SN is a Ia. The SED type is from the GOODZ SED template set (Dahlen et al 2010). 1=E, 2=Sbc, 3=Scd, 4=Irr, 5,6=Starburst plus 4 interpolations between each. ...
493966a39f5a8d01390f4652643e861c7570963d
35,767
import re def markov(bot, msg): """Return the best quote ever.""" if final_model: # This tries to generate a sentence that doesn't "overlap", or # share too much similarity with seeded text. # Read more here: https://github.com/jsvine/markovify#basic-usage sentence = final_mode...
24ea657257880ec0755360eb64d9bbcd9dfaf62f
35,768
def two_body_mc_stress_stress_jit( bond_array_1, c1, etypes1, bond_array_2, c2, etypes2, d1, d2, d3, d4, sig, ls, r_cut, cutoff_func, ): """2-body multi-element kernel between two partial stress components accelerated with Numba. Args: bon...
f5f702398f7bb3e8b498b60653bcc2a520e81f95
35,769
import os def pytest_configure(config): """ pytest hook used to add plugin install dir as place for pytest to find tests """ if config.getoption("repo_health"): # Add path to pytest-repo-health dir so pytest knows where to look for checks file_dir = os.path.dirname(os.path.dirname(os...
2a911a4bfc65db433b778c49826f554bd061d080
35,770
def new_world_news(cat): """[categories]\n\n lore \n general\n updates\n """ return nww.news(cat)
696fc748cc8927ba75059fda9dd787afe6250471
35,771
import time def aggregation_svg(es, query: Query): """ Execute aggregation query and render as an SVG. """ is_internal = "/logs" in request.headers.get('Referer', '') width = query.args.pop('width', '100%' if is_internal else '1800') width_scale = None if width != '100%': width_scale = ti...
3ef3e01232fcaeccdb810df80bc824494569b439
35,772
def transposem(inp): """Transpose multiple matrices.""" perm = list(range(len(inp.shape))) perm[-2], perm[-1] = perm[-1], perm[-2] return tf.transpose(inp, perm)
1851aef9afa0717953bf409ac9ecdb993f0dd674
35,773
import sys def interpolate(x, y, x0): """ Interpolates array Y (y=f(x)) at point x0, returning y0 x must be in increasing order """ x_a = 0 i_a = -1 x_b = 0 i_b = -1 i = 0 for point in x: if (point <= x0): x_a = point i_a = i if (point >...
fc2c7bbbb3b5994fdad7c623b6fb24fcf2f08794
35,774
from typing import Any def list_api_tokens( component_manager: ComponentManager = Depends(get_component_manager), token: str = Depends(get_api_token), ) -> Any: """Returns list of created API tokens associated with the authenticated user.""" authorized_access = component_manager.verify_access(token) ...
7b52a3fff5594cdf3be5eaf0a344c23ea0e320c4
35,775
def get_val_via_socket(key): """Retrieve value of key from redis over Unix socket file.""" set_redis_socket_pool() global SOCKET_POOL # retrieve value r = StrictRedis(connection_pool=SOCKET_POOL) res = r.get(key) return res.decode() if hasattr(res, "decode") else res
3783d121ec16365edc81c8a538015598a100dd55
35,776
def euclidean_distance(goal_pose): """Euclidean distance between current pose and the goal.""" return sqrt(pow((goal_pose.pose.position.x - pose.pose.pose.position.x), 2) + pow((goal_pose.pose.position.y - pose.pose.pose.position.y), 2))
bdcf6f005eb548f2fb8a2d3f530cf276f75725a2
35,777
def get_rel_join_parts(database, from_table, rel) -> QueryParts: """ :param Database database: The database being reviewed. :param Table from_table: :param Relationship rel: The relationship to get the parts from. :return: New join parts for a join based on a relationship. """ to_table = dat...
75346106c368f760eef36a7c0eb504d04eafe298
35,778
from lightgbm import LGBMRegressor from entmoot.learning.tree_model import EntingRegressor, MisicRegressor def cook_estimator(base_estimator, std_estimator=None, space=None, random_state=None, base_estimator_params=None): """Cook a default estimator. For the special base_estimator called "DUMMY" the...
53fea2782062124d1814cc298a55a45195b145af
35,779
from pandas import Series from typing import Optional def _convert_and_box_cache( arg: DatetimeScalarOrArrayConvertible, cache_array: "Series", name: Optional[str] = None, ) -> "Index": """ Convert array of dates with a cache and wrap the result in an Index. Parameters ---------- arg ...
60d2f5752b51aa16f2d5d2a67192158dc27f57d1
35,780
def generate_file_path(package_path, file_name): """ Dynamically generate full path to file, including filename and extension. :param package_path: (array) ordered list of packages in path to test file :param file_name: (string) name of the file w/ test, including the extension :return: (string) fu...
a6d2ac12cdc726c4727e23301971e921cab9455b
35,781
from typing import Tuple def pdread_2col(filename: str, noheader: bool = False) -> Tuple[ndarray, ndarray]: """Read in a 2 column file with pandas. Parameters ---------- filename: str Name of file to read. noheader: bool Flag indicating if there is no column names given in file. ...
b1cd7282bf7122abf412351069d7f949be7928cc
35,782
async def infer_type_map_array(engine, fn, ary): """Infer the return type of map_array.""" fn_t = await fn['type'] ary_t = await ary['type'] if not isinstance(ary_t, Array): raise MyiaTypeError('Expected array') xref = engine.vref({'type': ary_t.elements}) return Array(await fn_t(xref))
c3bed37c4adfb0e1a1acfe86242bae9349edffa7
35,783
def _fullname(attr): """Fully qualified name of an attribute.""" fullname = "" if hasattr(attr, "__module__"): fullname += attr.__module__ if hasattr(attr, "__name__"): if fullname: fullname += "." fullname += attr.__name__ if not fullname: fullname = str(...
672120f7b16175b9fed091fbdd93456ba5d89004
35,784
def example_positionfixes(): """Positionfixes for tests.""" p1 = Point(8.5067847, 47.4) p2 = Point(8.5067847, 47.5) p3 = Point(8.5067847, 47.6) t1 = pd.Timestamp("1971-01-01 00:00:00", tz="utc") t2 = pd.Timestamp("1971-01-01 05:00:00", tz="utc") t3 = pd.Timestamp("1971-01-02 07:00:00", tz="...
496283dc4d73588e7c9891577bc8915a8ec58863
35,785
import sys def GetGClientCommand(platform=None): """Returns the executable command name, depending on the platform. """ if not platform: platform = sys.platform if platform.startswith('win'): # Windows doesn't want to depend on bash. return 'gclient.bat' else: return 'gclient'
3f4fee1065f18f8420bba3d79469ade8a1520dc6
35,786
def do_histtestbasic() -> bool: """Run this unit test with hard coded, default parameters.""" file = "sample.txt" par = [5, 0, 15] test = HistTestBasic(txtfile=file, params=par) return test.test(False)
b8f033ba62d073a44b9208f8233892774cc7b502
35,787
from typing import Any import operator def log_param_shapes(params: Any) -> int: """ # Maybe could be useful: https://github.com/google-research/scenic/blob/ab3083d8cbfe3216119a0f24fce23ca988e20355/scenic/common_lib/debug_utils.py Prints out shape of parameters and total number of trainable parameter...
e2d41c68b44e043e1d048fa3a96fe063c8188048
35,788
def static(**kwargs): """ Return a predefined ``dict`` when the given regex matches. """ return lambda values: kwargs
ac12595cc1b70dd5f9cccd8ae043f650f0ef59c5
35,789
def ring_background_estimate(pos, on_radius, inner_radius, outer_radius, events): """Simple ring background estimate No acceptance correction is applied TODO : Replace with AnnulusSkyRegion Parameters ---------- pos : `~astropy.coordinates.SkyCoord` On region radius inner_radius :...
50642a8acfe429b827773a697807618f254b5b8a
35,790
def get_user_profile(email): # GET """Get user profile Fetches from the user collection by using the user's email as key. Args: User's email (str) Returns: User profile object (dict) """ # NOTE: This method previously called LCS with director credentials in order to retrieve ...
10fe0b3ff37d54d51d456392cb1984d92e10c10a
35,791
import hashlib def sha1(string): """Compute the sha1 hexdigest of the string.""" return hashlib.sha1(string.encode('utf-8')).hexdigest()
b663fc501e24a2331f69847024756b97dabc0cd4
35,792
import cgi import re def generate_rss(): """ Generate the RSS feed pages on a daily basis """ def parse(): try: form = cgi.FieldStorage() form_play = form.getfirst('play', '') form_date = form.getfirst('start', '') # alphanumeric only for play ...
9b92b9cc6095ccbce0bfab204476c205c7e47569
35,793
from datetime import datetime def current_weather(): """ Get all stations render template to client """ global last_updated_weather_time, last_updated_weather_data, first_run_weather if (((last_updated_weather_time - datetime.datetime.now())).total_seconds() < -900 or first_run_weather): ...
25dfb78759903c1f089d397b548a79d36304cf74
35,794
import re def parse_timedelta(time_str): """ Parse a time string e.g. (2h13m) into a timedelta object. Stolen on the web """ regex = re.compile(r'^((?P<days>[\.\d]+?)d)?((?P<hours>[\.\d]+?)h)?((?P<minutes>[\.\d]+?)m)?((?P<seconds>[\.\d]+?)s)?$') time_str=replace(time_str,{ 'sec':'s', ...
0b18f77197f8122cb92ccd7b7552baab800173f7
35,795
def gmtime(space, w_seconds=None): """gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst) Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a. GMT). When 'seconds' is not passed in, convert the current time instead...
f4095b64c60c67454f7ef24e295438f3eff68a77
35,796
from typing import Callable def nested_defaultdict(default_factory: Callable, depth: int = 1) -> defaultdict: """Creates a nested default dictionary of arbitrary depth with a specified callable as leaf.""" if not depth: return default_factory() result = partial(defaultdict, default_factory) fo...
58b162431d70f559dc58a256e78d201644cddde3
35,797
def main(client_id, client_secret): """Console script for boxcast_python_sdk.""" client = BoxCastClient(client_id, client_secret) account = client.get_account() print(account) return 0
ec6562052d7bf6cb8594356df16cbcf0d98314b2
35,798
import pytz from datetime import datetime def now(timezone): """Get the current time in the given timezone Args: timezone: The desired timezone as a string. eg 'US/Eastern' """ utc = pytz.timezone('UTC').localize(datetime.utcnow()) return utc.astimezone(pytz.timezone(timezone))
ebd89601ebcb945f01c3e68fbe0f5350e4fc2d0a
35,799