content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime def months2days(nmon=288, baseyear=1992, basemon=1): """ This routine converts the mid-month time to days from January 1st of a particular year. Parameters ---------- nmon : dtype=integer number of months baseyear : dtype=integer year of time of...
d456eaec22c5d58a71a62e46631b7024cee3384a
67,709
def run_defense_method(graph, method, k=3, seed=None): """ Runs a specified defense on an undirected graph, returning a list of nodes to defend. :param graph: an undirected NetworkX graph :param method: a string representing one of the attack methods :param k: number of nodes or edges to attack ...
186852827d5a8392986ccff3409d02bdc09e5311
67,711
def delta_S_2(psi_time, points, X, Y, ret_max=True): """ Short summary. Parameters ---------- psi_time : numpy.ndarray Description of parameter `psi_time`. points : list of two tuples Description of parameter `points`. X : numpy.ndarray Description of parameter `X`. ...
aed396051397436c950c90aa08696101f9c8d2ba
67,712
def fake_biblist(nb_codes): """ Generate a list of fake bibcodes :param nb_codes: number of bibcodes to generate :return: list of bibcodes """ bibcodes = [] for i in range(nb_codes): bibcodes.append(fake_bibcode()) return bibcodes
586ff939c50d07491dd0cc7466ff77cfaba1b2a6
67,713
def scalar_summary(tags, values, collections=None, name=None): # pylint: disable=line-too-long """Outputs a `Summary` protocol buffer with scalar values. This ops is deprecated. Please switch to tf.summary.scalar. For an explanation of why this op was deprecated, and information on how to migrate, look ['h...
cb169a9af97074d30ce096ed087c5398945b5421
67,714
def compute_convergence_data(f, u, t_final, dts, scheme, num_steps, error_idx=None, fixed_coefficients_twice=False, **kwargs): """ Compute the numerical errors obtained by the LMM `scheme` which uses `num_steps` previous step/derivative values for th...
cc904eb9ecd33266816b813b43ebd952cc40e9cb
67,715
def closeMap(): """ 类型:z_关闭地图 说明: close map 参数: test: 模版参数 desc: 描述方法操作功能,更具体的展示在测试报告 返回: False True """ r_v = AT.RunCommand(command="adb shell am force-stop com.baidu.naviauto",timeout="100") AT.sleep(sleepTime="200") ...
1650ab56bbfc89bf7327b6500e3bdaf0ac64e3a4
67,716
def filter_counts_by_interactions(counts: pd.DataFrame, interactions: pd.DataFrame, suffixes: tuple = ('_1', '_2'), counts_data: str = 'ensembl') -> pd.DataFrame: """ Removes counts if is not defined in interactions components """ genes = interactions['{}{}'.format(coun...
a57c8f482001186c6d269ddfcd80261644510158
67,717
def load_sentiment_data(): """ Load the data set :return: data_set """ data_set = list() download_data_if_not_yet() words_ids = dict(get_word_dict()) for sample_file in sort_files(): words_list = list() category = 0 if 'neg' in sample_file else 1 for word ...
43b7b829d6f87cccb45f3f2df24b075d27761b76
67,718
def ready_branched_dummy_context(branched_dummy_context, dummy_dataframe): """Get dummy ready by placing a dummy dataframe at every input edge node.""" print("ready branched") for dataset in branched_dummy_context.pipeline.inputs(): d = getattr(branched_dummy_context.catalog.datasets, dataset) ...
3cc4eef20f282f9128affc0638a4c8ad0ce14730
67,719
def get_ellipse_focus_add_by_standard_equation(a11, a12, a22, a1, a2, a0): """ a11 = 1/a^2 a22 = 1/b^2 a12 = a1 = a2 = 0 a0 = -1 """ if a11 < a22: a11_1 = 1 / a11 c = sqrt(a11_1 - 1 / a22) return [[c, 0], [-c, 0], 2 * sqrt(a11_1)] a22_1 = 1 / a22 c = sqrt(a22_...
85bce9536519787570bbc65c2854fd098954fadd
67,720
import requests from bs4 import BeautifulSoup def pullWksaCountryPages(): """Scrapes the WKSA schools website for the list of countries WKSA has locations in.""" KSW_SCHOOLS_PAGE = 'http://www.kuksoolwon.com/site/schools' r = requests.get(KSW_SCHOOLS_PAGE) schools_page = BeautifulSoup(r.text, 'lxml') ...
ee242319a7ad990827e61a99be6093959ebe2097
67,721
import struct def get_system_bits(): """Return 32 for 32-bit systems and 64 for 64-bit""" return struct.calcsize("P") * 8
252d5acab4dec512df238031f89c072129485959
67,722
def validateSubSequence(array, sequence): """ ### Description validateSubSequence -> validates if a sequence of elements is a subsequence of a list. ### Parameters - array: the list where it will validate the subsequence. - sequence: the potential subsequence of elements ...
ae780814e6f0ce59b21acb46cd272443bd2a5f92
67,723
import asdf def read_table(filename, data_key=None, find_table=None, **kwargs): """ Read a `~astropy.table.Table` object from an ASDF file This requires `asdf <https://pypi.org/project/asdf/>`_ to be installed. By default, this function will look for a Table object with the key of ``data`` in the...
a9457b17653213412389f453a23237e48c204f75
67,724
def _cleanse_dict(original): """Strip all admin_password, new_pass, rescue_pass keys from a dict.""" return dict((k, v) for k, v in original.items() if "_pass" not in k)
2691cc31f127548f5dc0693a0f117dad0b6139dd
67,725
def FPs(names, fpsort, ctx=None): """Return an array of floating-point constants. >>> x, y, z = FPs('x y z', FPSort(8, 24)) >>> x.sort() FPSort(8, 24) >>> x.sbits() 24 >>> x.ebits() 8 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z) fpMul(RNE(), fpAdd(RNE(), x, y), z) """ ctx = _...
660674f5ef4a07dfa057ae30a3d618ca01bae49e
67,726
def calc_mode(sample_list): """ Calculate mode from continuous samples. Parameters ---------- sample_list : list or numpy array Returns ------- mode : float """ hist_freqs = np.histogram(sample_list, bins="auto")[0] hist_edges = np.histogram(sample_list, bins="auto")[1] ...
c7c6d6274aa9680912e0793288a4c3c9d67ae6ce
67,727
import collections def pretty_recursive(value, htchar="\t", lfchar="\n", indent=0): """ Recursive pretty printing of dict, list and tuples - full creadit to: http://stackoverflow.com/questions/3229419/pretty-printing-nested-dictionaries-in-python """ nlch = lfchar + htchar * (indent + 1) if...
2538337ed0711bcf60040dc0f4112ea01184fabb
67,728
from datetime import datetime def process_weighted_time_avg(procstatus, dscfg, radar_list=None): """ computes the temporal mean of a field weighted by the reflectivity Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing ...
ec2edc41fedcde3755996c71821a379ec23c5468
67,729
import urllib def _get_authorize_url(client_id, response_type, state=None): """ 認可のためのURLを取得 :param client_id: ClientID :param response_type: code or token :param state: CSRFトークン :return: 認可するためのURL :rtype: str """ payload = {'client_id': client_id, 'response_type': res...
99086aec415174b48b850acdfd16b79f91086955
67,731
def format_knot_hash(value, format_spec): """ >>> format_knot_hash([64, 7, 255], '02x') '4007ff' >>> format_knot_hash(bytearray.fromhex('A0C20170'), '08b') '10100000110000100000000101110000' """ return "".join(format(h, format_spec) for h in value)
2a12f299807bcc6606a00092faecf1b34ec32170
67,732
def mazziotti_opdm_purification(opdm, trace_target): """ Mazziotti purification of the 1-RDM in Phys. Rev. E. 65 026704 i) set all negative eigenvalues to zero ii) correct the trace by decreasing the HOMO iii) set all eigenvalues >1 to 1 iv) correct the trace by increasing the LUMO :param ...
a170c58fbbe0bfa459a4cb0c6278662092429b85
67,733
from typing import Tuple import torch def get_mean_std(loader: DataLoader) -> Tuple: """Calculates mean and standard deviation of a dataset taken from the given DataLoader.""" cnt = 0 ds_mean = torch.empty(3) ds_std = torch.empty(3) for data in loader: b, c, h, w = data.shape n...
b6123a6fbf4d86a3139715e92e7251ef2ae43ede
67,734
def profiler(fname,scans=None, data_type=None, datetime_format=None, num_info_lines=5, check_na=['SPD','DIR'],na_values=999999, height_name='HT', read_scan_properties=False, verbose=False): """Wind Profiler radar with RASS ...
d291cb5839bbb9006aff048c87247a3aa0b7665e
67,735
def angle(v1, v2=None): """Compute angle between 2D vectors v1 and v2. If v2 is not specified it will default to e1 (the unit vector in the x-direction) The angle is measured as a number in [0, 2pi] from v2 to v1. """ # Prepare two numeric vectors if v2 is None: v2 = [1.0, 0.0] # ...
84e8105323809d55eb40af9cff102ebbe45a57bc
67,736
def read_gtf(f, full=True, as_df=False, nrows=None, duplicate_attr=False): """Read files in the Gene Transfer Format. Parameters ---------- f : str Path to GTF file. as_df : bool, default False Whether to return as pandas DataFrame instead of PyRanges. nrows : int, default ...
c596e402b0f387aae60265f8beca3f0ce136c138
67,738
from typing import Tuple def predict(model, data, tokenizer, label_map, batch_size=1): """ Predicts the data labels. Args: model (obj:`paddle.nn.Layer`): A model to classify texts. data (obj:`List(Example)`): The processed data whose each element is a Example (numedtuple) object. ...
5c2475b79ec104331d4654171d76ac8f9fd8b6cf
67,739
from typing import Optional import logging async def create_model(item: Optional[param] = None): """ the user submit a json object that contain all the details needed to create and train a model :param item: :return: """ if item is None: return {"name cannot be empty"} else: ...
e985b7747d562b3fe16f98762f68e545588283f8
67,740
def unmarshal_object(swagger_spec, object_spec, object_value): """Unmarshal a jsonschema type of 'object' into a python dict. :type swagger_spec: :class:`bravado_core.spec.Spec` :type object_spec: dict :type object_value: dict :rtype: dict :raises: SwaggerMappingError """ deref = swagge...
a16c70649a70ed7b89a357503f06e312ae0f46d8
67,741
def upvote_question(current_user, question_id): """Endpoint to upvote a question""" error = "" status = 200 response = {} question = db.get_single_question(question_id) if not question: error = "That question does not exist!" status = 404 elif db.upvote_question(current_use...
c294e2e81c7d3623bf984c35179514489a27bc42
67,742
from typing import Union import torch def update_lr( scheduler: Union[lr_scheduler.StepLR, lr_scheduler.LambdaLR, lr_scheduler.ReduceLROnPlateau, lr_scheduler.CosineAnnealingLR, lr_scheduler.CyclicLR], optimizer: optimizer.Optimizer, metric: torch.Tensor = None ) -> float: """Update learning rate ...
b11c6a5a49758554a7e1062d7f65da1543896678
67,744
def load_clean_captions(filename, dataset): """为图像标题首尾分别加上'startseq ' 和 ' endseq', 作为自动标题生成的起始和终止 Args: filename: 文本文件,每一行由图像名,和图像标题构成, 图像的标题已经进行了清洗 dataset: 图像名list Returns: dict, key为图像名, value为添加了'startseq'和'endseq'的标题list """ # load document doc = load_doc(filename...
5477c5e0ce972d42a1bb79d0c4b44b58b66db832
67,746
def get_python_packages_info(path, python_version="3"): """Get details about all python packages in an image filesystem. :param path: path were the docker image filesystem is expanded. :type path: string :param python_version: version of python to use. can be "2" or "3". default to "3". :type p...
515ff6c517e11d08f11e18b59ddfd921695e144e
67,747
def compute_intersection_length(A, B): """Compute the intersection length of two tuples. Args: A: a (speaker, start, end) tuple of type (string, float, float) B: a (speaker, start, end) tuple of type (string, float, float) Returns: a float number of the intersection between `A` and...
6cf038e1febbc1a7aa19eb104f5628ff2f935174
67,748
import random def Move(src, label, pad_color, max_move_ratio=0.2): """ item = { "img_name":save_name, "keypoints":save_keypoints, relative position "center":save_center, "other_centers":other_centers, "other_keypoints":other_keypoints, ...
5517b76215ed836d02f496e969fe072c8831e125
67,749
import copy def pcc_slower1(circ, supp, verbose=False): """ Args: circ(list(list(tuple))): Circuit supp(list): List of integers Returns: list(list(tuple)): Past causal cone of supp """ circ_rev= circ[::-1] circ_reduced = [] supp_temp = copy.deepcopy(supp) for u...
4f02c0db839456dc91b508b89b4d343d7c02beb0
67,751
import socket def bindsocket(port, host=''): """ Creates a socket assigned to the IP address (host, port). Parameters ---------- port : int port assigned to the socket. host : str, optional host assigned to the socket. The default is ''. Returns ------- tcpsock : ...
48be29952a3d35af0ec0886e3ca332f9280384f1
67,753
def _absolute_clustering(data, group_pop_var, total_pop_var, alpha=0.6, beta=0.5, metric='euclidean'): """ Calculation of Absolute Clustering index Parameters ---------- ...
4e80f6397f2b2f2c44039c6d517b0675c9ced3ed
67,754
def toText(p, alreadyLabeled=None): """Render a pattern as human-readable text. :type p: titus.P :param p: the pattern :type alreadyLabeled: set of strings or ``None`` :param alreadyLabeled: used to avoid recursion in recursive types :rtype: string :return: text representation of the patter...
602cd3caee485f235f4d6b1f4d774c81b34a0249
67,755
import re def _yesno(message, default='no', suffix=' '): """Modified from github.com/tylerdave/prompter to reduce depenencies. All credit to the creator.""" if default == 'yes': yesno_prompt = '[Y/n]' elif default == 'no': yesno_prompt = '[y/N]' else: raise ValueError("defa...
f66bdf51fd79deb9ccba52f426a691361c9c6993
67,756
def get_intersection(y_true, y_pred): """ aka TP, assuming binary images that were removed the background """ return K.sum(K.sum(K.squeeze(y_true * y_pred, axis=3), axis=2), axis=1)
d965c17d5f321fd4913997170d362d05863192ff
67,757
def MAD_outliers(data: pd.Series) -> pd.Series: """Detect outliers use MAD based method and return a binary index Detect outliers we can use robust method based on median absolute deviation ( Page 19, Data Cleaning, 2019 ): >> ... the median and the median absolute deviation (MAD) that can replace mean an...
bf22e1d3884811f7f974df53b0ffffd053728e65
67,758
def create_java_app_env(deployment_config): """ Returns the environment variables Java application servers uses. Args: deployment_config: A DeploymentConfig object. Returns: A dictionary containing the environment variables """ env_vars = {'APPSCALE_HOME': APPSCALE_HOME} gcs_config = {'scheme': 'h...
fc4ab2bd4c714cfdf17a9144d82afd09eda9b4ae
67,759
from datetime import datetime def date(): """ Return formatted date Parameters ---------- None Returns -------- None """ today = datetime.today() month = today.strftime("%B") day = today.day year = today.year date = f"{month} {day}, {year}" return date
c28eb0b89d524d9856cb18a53004a34278011e90
67,760
def _BroadcastMul(vec, mat): """Multiply after broadcasting vec to match dimensions of mat. Args: vec: A 1-D tensor of dimension [D0] mat: A 2-D tensor of dimension [D0, D1] Returns: A tensor of dimension [D0, D1], the result of vec * mat """ # Reshape vec to [D0, 1] vec = array_ops.expand_dim...
fedf209bdfc23838bc70a38aa1dce49816a1bad6
67,761
def broadcast_global_variables(root_rank): """Used to broadcast global variables""" variables = backend._get_variables(backend.get_graph()) candidate_vars = [] for v in variables: if getattr(v, "_keras_initialized", False): candidate_vars.append(v) op_list = [] if candidate_v...
7ea68f3f973325c33440de3d6c3507d5a88a805b
67,762
import json import logging def output(post, quiet=False, use_test_node=False, diagnostic=False, urls_only=False) -> int: """Prints out the post and extracts the custom_json""" data = json.loads(post.get("json")) if diagnostic: logging.info( ...
31f3e977d47d44ed6b9ec45d171cbe9cfecb7ed9
67,763
def rainbow_nums(freq, i): """create rgb values for part of a rainbow""" rgb = [] for channel in range(3): rgb.append(max(0, min(5, int(6 * (sin(2 * pi * (freq * i + 0.333 * channel)) / 2 + 0.5))))) return rgb
d163296b1dbf53218a730082379159de94f8853b
67,764
def local_ordering(circuit, weighted=True, verbose=False): """Permute qubit labels so that two-qubit gates are as local as possible. Parameters: circuit (qiskit.QuantumCircuit): An input quantum circuit. weighted (bool): Using weighting method. verbose (bool): Print values and plot ...
bf6d0404edc11d2321b9ede1822116972a2d46af
67,765
def _job_substring_match(search_string, job_name): """Return a bool on whether a string exists in a provided job name or use from environment if available (case insensitive).""" job_name = job_name or get_value('JOB_NAME') if not job_name: return False return search_string in job_name.lower()
8d056fcff3408736d5d13401cfb7f77380ca3594
67,766
def raw(func, **func_args): """Decorator for eager functions checking input array and stripping away the weld_type. Stripping the weld_type is required to keep the same code in Series.apply and because Numpy functions don't (all) have kwargs. Passing weld_type to NumPy functions is unexpected and r...
92b10d3ea54f3c0f8c0e4204c37371fca66be09e
67,767
def nanmean(x): """Average value of the array a, ignoring 'Not a Number' elements""" if not hasattr(x,"__len__"): return x x = asanyarray(x) valid = ~isnan(x) return sum(x[valid])/sum(valid)
2272021953e665278899ba00b8967e4dc30cc3dd
67,768
from datetime import datetime import six def obj2str(i, force_detailed=False): """Returns a human-readable ascii string representation of a model instance, even in some edge cases. """ if not isinstance(i, models.Model): if isinstance(i, (int, IncompleteDate)): return str(i) # Au...
72a16f25e27528f8bab638c5317570a877d52569
67,770
import urllib def facebook_authorize(request): """ Obtain authorization for Graph API access. If code exists in request.GET, then we should be good to move on to Step 3 and exchange the code for an access token. Otherwise, send the user to Facebook to grant access to our app. """ site = S...
27aaa3009c20a970fe70763d98639cfa6f894947
67,771
def is_video(video): """ Checks that `file` is a video file. `video` is cv.VideoCapture object. """ return video.get(cv.CAP_PROP_FRAME_HEIGHT) != 0
366a52d6bc40286efa2483dd36ac9098ef0197a1
67,772
from torchvision.models.resnet import resnet152 def resnet152(pretrained=False, fixed_feature=True): """ "ResNet-152 model from torchvision's resnet model. :param pretrained: if true, return a model pretrained on ImageNet :param fixed_feature: if true and pretrained is true, model features are fixed whil...
e172a833e3d38b9692a3a55bd4961a5444c54187
67,773
import six def _UnitsByMagnitude(units, type_abbr): """Returns a list of the units in scales sorted by magnitude.""" scale_items = sorted(six.iteritems(units), key=lambda value: (value[1], value[0])) return [key + type_abbr for key, _ in scale_items if key]
972a17b51901a133444ddb77989c4ebc372fc35e
67,775
def index(): """View root page function that returns index page and the various news sources""" title = 'Home- Welcome to the best News source page' # Getting the news sources news_sources = get_sources('sources') return render_template('index.html', title=title, news_sources=news_sources)
ee31a6f0a70cff1d057389a9c402e5d6498e23d0
67,776
def download_link(youtube_url: str, directory_path: str, audio_format: str = "wav") -> str: """ Downloads a track from the given youtube_url into the given directory_path :param youtube_url - the URL to a youtube video containing the audio file to download :param directory_path - the path to a local direct...
bc0cdec17bc5cee9d436dba790fda937832afd1e
67,777
def calc_I_MacDonald2014(TEMP): """ Temp. (C) to Macdonald2014 parameterised [iodide] in nmol/dm^-3 (nM) """ # Parameterisation is Arrhenius expression # y= 1.46E6 * exp(-9134.0/TEMP(K)) * 1E9 # NOTE: temp. is converted from degC to DegK return (1.46E6 * np.exp((-9134.0 / (TEMP+273.15))))*1E...
be929814a5f9b23c5789a9decbbe080dc215e0f8
67,778
def get_payload(job): """Construct payload for SqoopJob -> Genie 2.""" return Genie2Adapter.construct_base_payload(job)
d0af452837af02a82a2a4b5f95935b5d1106da5a
67,779
def replace_toffoli_with_alt(qasm): """ Replace all Toffoli gates (including parallelized ones) by their alternative representation. See src.grover.search_utilies.alternative_toffoli for more details. Args: qasm: The full qasm program that contains Toffoli gates to replace Returns: The sam...
2afda126a975c11f13e8f1fd71b73c2621dad032
67,780
def make_rpc_name(name: str) -> str: """ Convert python compatible name to Transmission RPC name. """ return name.replace("_", "-")
057f1446f230dac93a09661e4eeb27edb09fda62
67,781
async def document_convert_to_base64(encoding, the_file): """this function convert a pdf file to base64 format""" with open(the_file, 'rb') as open_file: byte_content = open_file.read() base64_bytes = b64encode(byte_content) base64_string = base64_bytes.decode(encoding) return base64_stri...
50b697c346ba46468543cdc317d6a643a3c26fed
67,782
def get_model_layers(model): """Returns all layers of a model.""" ret = [] def collect_layers(container): for layer in container.layers: assert layer not in ret ret.append(layer) if kchecks.is_network(layer): collect_layers(layer) collect_laye...
e3675dcaa3f7cb73543e6187f6cf06da68943b8c
67,783
def splitList(listToSplit, num_sublists=1): """ Function that splits a list into a given number of sublists Reference: https://stackoverflow.com/questions/752308/split-list-into-smaller-lists-split-in-half """ length = len(listToSplit) return [ listToSplit[i*length // num_sublists: (i+1)*length ...
1a22fcb061a6fce6a2971e277ecc94251e0a2011
67,784
def create_reader(reader_name, input_shape, is_multi_task, task_map_id, *gens): """ build reader for multi_task_learning """ placeholder = Placeholder(input_shape) pyreader, model_inputs = placeholder.build(capacity=16, reader_name=reader_name) joint_generator = create_joint_generator(input_shap...
04fb537882957e5d40a9460709acddd82751f54f
67,785
from dvc.fs.memory import MemoryFileSystem def _get_staging(odb: "ObjectDB") -> "ReferenceObjectDB": """Return an ODB that can be used for staging objects. Staging will be a reference ODB stored in the the global memfs. """ fs = MemoryFileSystem() fs_path = _make_staging_url(fs, odb, odb.fs_pat...
aafff52be65ede1dc011ecc2061d2cd5055a659e
67,787
def _block_array_reduction_wrapper(func): """Wraps a reduction (eg sum, norm) to allow for joint operation on `DeviceArray` and `BlockArray`""" @wraps(func) def wrapper(inp, *args, axis=None, **kwargs): all_args = (inp,) + args + tuple(kwargs.items()) if any([isinstance(_, BlockArray) ...
8353aff2a764c080f1709bcbc205579f238f5c6f
67,788
import functools import traceback def check_workchain_step(func): """ Decorator for workchain steps that logs (and re-raises) errors occuring within that step. """ @functools.wraps(func) def inner(self, *args, **kwargs): try: return func(self, *args, **kwargs) except Ex...
d6e5834b233075fbb1097a84f7e3010c3f292194
67,789
from app import main, admin def create_app(config_name): """ 创建flask的应用对象 :param config_name: str 配置模式的模式的名字 ("develop", "product") :return: """ app = Flask(__name__) # 根据配置模式的名字获取配置参数的类 config_class = config_map.get(config_name) app.config.from_object(config_class) # 使用app...
ee4c817b4c02e4dc4ae10ea5b95a81fdf94a687d
67,790
import json def kibana_api_request(url, method='GET', filename=None): """Kibana API request.""" data = {} if filename: curl_url = "curl -X%s %s -T %s" % (method, url, filename) else: curl_url = "curl -X%s %s" % (method, url) print_color_text(curl_url, MAGENTA) opener = urlli...
e44df7402f90ca9fe661d1f4597c3173e6eb083a
67,791
import inspect def worker_factory(service_cls, **injections): """ Return an instance of ``service_cls`` with its injected dependencies replaced with Mock objects, or as given in ``injections``. **Usage** The following example service proxies calls to a "math" service via and ``rpc_proxy`` inject...
ca0082472c866b512be45553ac2f9866dd6f3c1c
67,792
from typing import Optional from typing import Dict from typing import Any def values_to_numpy(data: Optional[Dict[Any, Any]]) -> Optional[Dict[Any, Any]]: """Replaces all tensorflow-tensor values with their numpy versions. Args: data: Any dictionary for which values should be converted. Returns...
b2546f78517b04711a9301feaf65d2ccc055302b
67,793
def naive_r(augend, addend): """A recursive definition of addition. (http://en.wikipedia.org/wiki/Addition#Natural_numbers) """ if addend == 0: return augend return inc(naive_r(augend, dec(addend)))
ea801ec069a0c4a86d9b18837bb3dc369edbff0a
67,794
import scipy def lqr(A, B, Q, R): """Solve the infinite-horizon, discrete-time LQR controller x[k+1] = A x[k] + B u[k] u[k] = -K*x[k] cost = sum x[k].T*Q*x[k] + u[k].T*R*u[k] # Arguments: A, B: Linear system matrices Q, R: State and input penalty matrices, both positiv...
d300ba4bbdb612ff4410fc1f320ad9825f9aa9d3
67,795
import scipy def get_gray_imgs_fn(file_name, path): """ Input an image path and name, return an image array; if RGB images, then mode = 'RGB'.""" # return scipy.misc.imread(path + file_name).astype(np.float) return scipy.misc.imread(path + file_name, mode='L')
d2dc0c8b8b098fc5b7cd8cfb2ebdf11f511a81d6
67,796
def file_url(repo_name, rev, path): """ Forges Github URL to a blob in a repo (through branch or commit rev). :param str repo_name: Github repository name such as 'Author/Repo' :param str rev: branch, commit or tag :param str path: the path to the file :return: URL :rtype: str """ r...
f9d85c3ffed30c3e6edc0d61b5fbffc9100e33ce
67,797
from typing import Callable from typing import Tuple def cross_validate(estimator: BaseEstimator, X: np.ndarray, y: np.ndarray, scoring: Callable[[np.ndarray, np.ndarray, ...], float], cv: int = 5) -> Tuple[float, float]: """ Evaluate metric by cross-validation for given estimator Para...
3ed043290a8839fa31ff0d684a6b05f27c61863d
67,798
def get_application_directory(): """Get the application directory. Returns: str: The application directory. .. versionadded:: 1.7 """ _check() return _ec.get_application_directory()
d87ecdf9542bd92165ebb656d7f1d18db989c52e
67,800
def insert_modification_record(method: str, resource_url: str, session: scoped_session) -> int: """ Insert a modification record into the database. :param method: HTTP method type of related operation. :param resource_url: URL of resource modified. :param session: sqla...
61430d3b40d2fdaaacdf6a734c19659e73584be2
67,801
def _construct_GPL_url(accession): """Example URL: ftp://ftp.ncbi.nlm.nih.gov/geo/platforms/GPLnnn/GPL570/annot/GPL570.annot.gz """ number_digits = len(accession) - 3 # 'GPL' is of length 3. if number_digits < 4: folder = accession[:3] + 'nnn' # e.g. GPLnnn. elif 3 < number_digits < 5: folder = accession[...
36527d413cc005abe5055eab46e4d7fe93f4aa8e
67,802
import struct def load_mbrec(package): """ Load master boot record and compute magic checksum """ data = package.read_and_pad(package['mbrec']['filename'], 512) checksum = file_checksum(data[2:-2], stride=2, magic=0x1234) checksum &= 0xffff struct.pack_into('<H', data, 0, checksum) return data
d2f839f8ed1d4a5fd1805aba875fb479b6a03a0a
67,803
def get_get_upload_details_retry_predicate(resp): """Triggers retry if upload details came back without last status.""" return not resp.last_status
ecadf182751e55c2c3cbd85f2a7343adc34821e5
67,804
def same_day_hour_moving_average( datetime_col, value_col, window_size, start_week, average_count, forecast_creation_time, output_col_prefix="moving_average_lag_", ): """ Creates moving average features by averaging values of the same day of week and same hour of day of previous ...
b50f2c5bdba602040f9695a359e5256bac66c1cf
67,805
def get_setuptools_package_version(setuptools_version: str) -> str: """ Generate the right setuptools command for pip command :param setuptools_version: Setuptools version obtained from :return: A string formatted for pip install command (e.g setuptools==58.0.0) """ setuptools_version = setupto...
99554292253752545d1bbf82edfef92a925b1746
67,806
import struct def replace_pyzzer_entry_point_shebang(all_data, placeholder, new_prefix): """Code adapted from pyzzer. This is meant to deal with entry point exe's created by distlib, which consist of a launcher, then a shebang, then a zip archive of the entry point code to run. We need to change the sheb...
5f9a4ac7b3c09e78cad6706570b9f45a022f0988
67,807
def _m_verify_mg(state, method, multigoal, history): """ _m_verify_g is a method that GTPyhop uses to check whether a multigoal method has achieved the multigoal for which it was used. """ goal_dict = _goals_not_achieved(state,multigoal) if goal_dict: raise Exception(f"depth {len(history...
dbf96a0896f444c44c070559137928700e6a17ba
67,808
def create_filters(fields=None): """ Decorator for extracting filter parameters from the request arguments and optionally verifying their validity according to the provided fields. :param fields: a set of valid filter fields. :return: a Decorator for creating and validating the accepted fields. ...
cb7d2e7b17d28de5a1010b5f4217ea7998bf1466
67,809
def unwrap2D(wraped_phase,type="boundary",noise = True): """ 2D unwarp function. There are several type to use in several different situation. Type: ----------------------------------------------- Simple: The very simple algorithm to unwrap 2D warpped phase just scan the whole matrix to unwrap phase. Very noi...
05e06287781234a3cdea692b7566de5974b553d2
67,810
import glob import json def getRecords(path): """ Method is used to get data for all CSV files in the path. Args: path (string) : The path for the CSV files. Returns: list: A list of dictionaries with file data. """ sales_data_files = [ file_name for file_name in glob.glob(f"...
b3338dbe3ed96c698b4aad8bfba94a797755f87a
67,811
def composite_conv_layer(inputs, num_filters=16, kernel_size=3, strides=1, activation='relu', batch_normalization=True, conv_first=True, regularization_factor=1e-4, layer_name=''): """ ...
daa43ff2dfa898339441c133017ccf5aad303b2f
67,813
def _generate_trace(distance, start_time): """ 生成轨迹 :param distance: :return: """ # 轨迹删除 trace = [[base_x, base_y, 1, 0]] for index, x in enumerate(tracks_list): trace.append([base_x + x, base_y + y_list[index], 3, timestamp_list[index] - start_time]) return trace[:-1]
d34a9e464327d0d3a2c445be3213c5b2627940c9
67,814
import torch def log1pMSELoss(log_predicted_counts, true_counts): """A MSE loss on the log(x+1) of the inputs. This loss will accept tensors of predicted counts and a vector of true counts and return the MSE on the log of the labels. The squared error is calculated for each position in the tensor and then averag...
ba7d244885303fa6755c4c25f1f991afae6d10ed
67,815
def prepare_res_align(gc): """ type (GenerateContactsPdbFile) -> dict :param gc: object of GenerateContactsPdbFile class. :return:dict key = residue_id; value = list atoms of triple. [[Atom N, Atom CA, Atom C, Atom O], [Atom N, Atom CA, Atom C, Atom O], [Atom N, Atom CA, Atom C, Atom O]] ...
2bd069a6b4f287c4127b85d3127ee34e6d4d69a7
67,818
import requests import http import json def get_upstream_constitution(): """ Retrieves a copy of the constitution from the master branch of the upstream repository. Returns a string in binary format. """ response = requests.get(UPSTREAM_API_PATH) if response.status_code == http.client.OK: result_dict ...
3bc470bf74e57f782ec8a1a73ff9727a282fb585
67,819
import logging def check_connection(ssh_conn): """ This will check if the connection is still available. Return (bool) : True if it's still alive, False otherwise. """ try: ssh_conn.exec_command("ls", timeout=5) return True except Exception as e: logging.error( ...
f443d6788eb4a79db7011f0ca9dc4ae15cdf6145
67,820
import re def parse_show_ip_bgp_route_map(raw_result): """ Parse the 'show ip bgp route-map' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show ip bgp route-map command in a \ dictionary of the form: :: { ...
48aecdc76da27fbbc991c30405d1efef82bcbfc3
67,821
from tqdm import tqdm from scipy.misc import comb from itertools import combinations from sklearn.metrics.pairwise import pairwise_distances import warnings def compute_distance_matrix(input_df, metric_func, fast=True, is_ones=False) -> pd.DataFrame: """ Compute a matrix that is symmetric down the diagonal. T...
55eb503ba18fa9a21b46fe7c0ca3a16f94d09f4a
67,822