content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def calculatePredictions(ReviewsD, userIDTest, scoreTest, simmilarities): """ Function finds userIDTest in all simmilar items and uses all the scores for prediction calculation Returns actualScore and predictedScore for further calculations of finding rmse and mse value...
6b74b9d6ed4855030f2f7405190788db7e0dad52
5,800
def ensure_absolute_url(query_url): """This function adds the base URL to the beginning of a query URL if not already present. .. versionadded:: 3.2.0 :param query_url: The query URL that will be utilized in an API request :type query_url: str :returns: The query URL that includes a top-level doma...
eae729fc89515744615931a46dd87890863e5d7e
5,801
def create_data_source( simiotics_client: Simiotics, source_id: str, s3_root: str, ) -> data_pb2.Source: """ Registers an S3 data source against a Simiotics data registry Args: simiotics_client Simiotics client -- see the simiotics.client module source_id ...
c00de849d20017efd12395eb5c097f95d5efe207
5,802
def func_2(x: float, c: float, d: float) -> float: """ Test function 2. """ return x + c + d
b95400c6779c0e64e7bb6cda493c0ee5e6f05f7c
5,803
import aiohttp async def async_get(server: t.Union[Server, str], view_or_url: str, view_data: Kwargs = None, session: aiohttp.ClientSession = None, params: Kwargs = None, **kwargs) -> Response: """Sends a GET request.""" return await async_request('get', server, view_or...
fe8bb90c78df758e48971978831de5553809db48
5,804
def DictionaryAddSchemaVersion(builder, schemaVersion): """This method is deprecated. Please switch to AddSchemaVersion.""" return AddSchemaVersion(builder, schemaVersion)
cad601667ec715e9519de02d23ee0b13f3903285
5,805
import math def isInner(x1, y1, x2, y2, scale): """ Currently, it's a rectangular kernal Other options: rectangular f(x) = 1 if a <= scale <= b else 0 I don't get the rest of them http://saravananthirumuruganathan.wordpress.com/2010/04/01/introduction-to-mean-shift-algorithm/ ...
b2c715b33ae8b38fdfd19c71b54ee3980b336eeb
5,806
def add_sulci(fig, dataview, extents=None, height=None, with_labels=True, overlay_file=None, **kwargs): """Add sulci layer to figure Parameters ---------- fig : figure or ax figure into which to plot image of curvature dataview : cortex.Dataview object dataview containing data to be...
20d532a107f472a8f83a9a14c9ee85b54270dd08
5,807
def build_puller_tdwhdfs_config_param( cluster_name, connector, data_id, topic, kafka_bs, fs_default_name, hadoop_job_ugi, hdfs_data_dir, username, secure_id, secure_key, ): """ tdw 数据拉取任务配置 :param cluster_name: 集群名 :param connector: 任务名 :param data_id: da...
1c74207b2903a9672d56ac447576504e514493a8
5,808
def make_url(issue, sites=[]): """ Compose search terms and sites with url safe encoding. """ print('issue', issue) terms = issue.strip().split() terms = [quote(x, safe='') for x in terms] # TODO test with just spaces url = 'https://duckduckgo.com/?q=' + '+'.join(terms) if sites: url +=...
cb6193f7164a16e731874070e8a824273bfbc49f
5,809
import pandas def order_by_digestibility(sv_reg, pft_id_set, aoi_path): """Calculate the order of feed types according to their digestibility. During diet selection, animals select among feed types in descending order by feed type digestibility. Because digestibility is linearly related to crude prot...
f586cbecea72c1bf5a901908f4f9d1414f3d6b93
5,810
def match(pattern, sexp, known_bindings={}): """ Determine if sexp matches the pattern, with the given known bindings already applied. Returns None if no match, or a (possibly empty) dictionary of bindings if there is a match Patterns look like this: ($ . $) matches the literal "$", no bindings (...
5389534e437d9090b29af8137d9d106c6550941d
5,811
def who_is_it(image_path, database, model): """ Implements face recognition for the happy house by finding who is the person on the image_path image. Arguments: image_path -- path to an image database -- database containing image encodings along with the name of the person on the image mode...
60136acaaf1ef95a06917828eb9d545e9c802d59
5,812
def generate_map_bin(geo, img_shape): """Create a q map and the pixel resolution bins Parameters ---------- geo : pyFAI.geometry.Geometry instance The calibrated geometry img_shape : tuple, optional The shape of the image, if None pull from the mask. Defaults to None. Returns ...
964cbc13eb652acbdf85f656bb9d789c5f1949e5
5,813
import sys import os def read_poly_data(filename): """ This function.. :param filename: :return: """ # Check which PolyData reader should be used if ".vtk" in filename: reader = vtk.vtkPolyDataReader() reader.SetFileName(filename) reader.Update() return rea...
740d1a73121caef0e31c33b5d44c9d70d0865d5f
5,814
def wklobjective_converged(qsum, f0, plansum, epsilon, gamma): """Compute finale wkl value after convergence.""" obj = gamma * (plansum + qsum) obj += epsilon * f0 obj += - (epsilon + 2 * gamma) * plansum return obj
079841a8ee6d845cdac25a48306c023a1f38b5f7
5,815
def addFavDirections(request): """ Add favourite stop of currently logged in user by number. Currently works with the URL: http://localhost:8000/api/add-fav-stop/<number> """ try: user = request.user origin = str(request.query_params.get('origin')) destination = str(reque...
2585006e5ea1f73433671c984dce5ce4e8ed2079
5,816
import types import numpy import pandas def hpat_pandas_dataframe_index(df): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.DataFrame.index Examples -------- .. literalinclude:: ../../../examples/dataframe/dataframe_index.p...
64b512d170ca5734a416688a9728f535248e9395
5,817
def _get_should_cache_fn(conf, group): """Build a function that returns a config group's caching status. For any given object that has caching capabilities, a boolean config option for that object's group should exist and default to ``True``. This function will use that value to tell the caching decora...
7a11124c640bfb3ced28e2d9395593b70dc85a0a
5,818
def set_difference(lst1, lst2): """returns the elements and indicies of elements in lst1 that are not in lst2""" elements = [] indicies = [] for indx, item in enumerate(lst1): if item not in lst2: elements.append(item) indicies.append(indx) return elements, indicies
75e78de68fb2528341f7246b77f7046da2c9274f
5,819
import json def _get_dict(path): """ Parameters __________ path: string or array Path to json file. In case a list of paths is provided instead, read them all and merge then into a single dict. Assumes depth two. Returns _______ d: dict Dictionary containing marke...
fddeff3bdfb0c70b1f95c2cf26d164c95d4065c2
5,820
def _super_check(args, names, op, fmt, msg, val_err): """ A flexible function is used to check whether type or value of variables is valid, which supports in both graph/pynative mode. Args: args(any): 'args' is used as one of argument for operation function and format function. names(an...
07c63f34216e84c10c5ff0c2f886d27aaaf5f245
5,821
import json def obter_novo_username() -> str: """ -> Pede um novo nome de usuário. :return: Retorna o novo nome de usuário. """ username = input('Qual é o seu nome? ') arquivo = 'arquivos_json/nome_de_usuario.json' with open(arquivo, 'w') as obj_arq: json.dump(username, obj_arq) ...
b4d4922d68b1fb80e5a9270638d134b5806969fd
5,822
def BDD100K_MOT2020(path: str) -> Dataset: """`BDD100K_MOT2020 <https://bdd-data.berkeley.edu>`_ dataset. The file structure should be like:: <path> bdd100k_box_track_20/ images/ train/ 00a0f008-3c67908e/ ...
a850b874da64d9efaf13ae3f1f5ca79805f5307d
5,823
import logging def _parse_block_postheader(line): """ (209)**************!*****************!!*************... """ parts = line[1:].split(')', 1) qlen = int(parts[0]) if not len(parts[1]) == qlen: logging.warn("postheader expected %d-long query, found %d", qlen, len...
5eee6c11160c0f91cb37c025d6d265188488cad9
5,824
def _remove_dimer_outliers(bond_lengths, energies, zscore_cutoff=3.0): """Removes outliers """ z_score = stats.zscore(energies) idx_keep = np.where(z_score < zscore_cutoff)[0] return bond_lengths[idx_keep], energies[idx_keep]
409ca918213315cfeb3d279319f42bf6ca5651a5
5,825
def get_auth_token(cmd_args=None): """ :param cmd_args: An optional list of additional arguments to pass on the command line :return: The current user's token """ r = Result("whoami") r.add_action(oc_action(cur_context(), "whoami", cmd_args=['-t', cmd_args])) r.fail_if("Unable to determine ...
01edde0d4738a96d25dbea37d3d539e8a8aee7ca
5,826
import os def _is_toplevel_repository_dir(directory): """Returns if a directory is a git or mercurial directory. This works by searching for a file or directory named `.git` or `.hg` in the directory. This works for both submodules and normal repositories. """ return (os.path.exists(os.path.join(...
25db538b6ef4f7febbdb282561885ff807f03bbe
5,827
import sys def breakOnException(func=None, *, exceptionList=Exception, debugger='pdb'): """ A function wrapper that causes debug mode to be entered when the wrapped function throws a specified exception. Parameters ---------- func : The function to wrap. exceptionList : An exception or t...
9b031e230fc822b03d88bba65a2962f0c71ece30
5,828
import re def hash_sid(sid: str) -> str: """ Hash a SID preserving well-known SIDs and the RID. Parameters ---------- sid : str SID string Returns ------- str Hashed SID """ if re.match(WK_SID_PATTERN, sid): return sid usr_sid = re.match(SID_PATTE...
5966d82f1412f7bfdb64e6a9b4904861f43e7c46
5,829
def horizontal_move(t, h_speed=-2/320): """Probe moves horizontally at h_speed [cm/s]""" return 0.*t, h_speed*t, 2/16 + 0*t
d9cf0e5b968e7d8319b7f63f7d1d7a4666484ad3
5,830
def fix_pdp_post(monkeypatch): """monkeyed request /decision/v1 to PDP""" def monkeyed_policy_rest_post(uri, json=None, **kwargs): """monkeypatch for the POST to policy-engine""" return MockHttpResponse("post", uri, json=json, **kwargs) _LOGGER.info("setup fix_pdp_post") pdp_client.Poli...
18957f2c9f3501ec54962e39fe664a0221133566
5,831
def del_project(): """ @api {post} /v1/interfaceproject/del InterfaceProject_删除项目 @apiName interfaceProDel @apiGroup Interface @apiDescription 删除项目 @apiParam {int} id 子项目id @apiParam {int} all_project_id 总项目id @apiParamExample {json} Request-Example: { "id": 1, "all_p...
4697360bbdab0ce3b4b10ebbdd1fab66b938fb4b
5,832
from skimage.transform import resize from enum import Enum def draw_pattern_fill(viewport, psd, desc): """ Create a pattern fill. """ pattern_id = desc[Enum.Pattern][Key.ID].value.rstrip('\x00') pattern = psd._get_pattern(pattern_id) if not pattern: logger.error('Pattern not found: %s'...
5d03ae9ebf13b3aa39c9d7f56a68a4a9056331cc
5,833
def register_post(): """Registriraj novega uporabnika.""" username = bottle.request.forms.username password1 = bottle.request.forms.password1 password2 = bottle.request.forms.password2 # Ali uporabnik že obstaja? c = baza.cursor() c.execute("SELECT 1 FROM uporabnik WHERE username=%s", [usern...
7c6569828f33287b7ea19ab37eb0ac868fd87c0a
5,834
def check_format_input_vector( inp, dims, shape_m1, sig_name, sig_type, reshape=False, allow_None=False, forbid_negative0=False, ): """checks vector input and returns in formatted form - inp must be array_like - convert inp to ndarray with dtype float - inp shape must be ...
cd26290058fbf9fba65a5ba005eaa8bd6da23a32
5,835
def get_proyecto_from_short_url(short_url): """ :param short_url: :return: item for Proyecto """ item = Proyecto.objects.get(short_url=short_url) if item.iniciativas_agrupadas is not None and \ item.iniciativas_agrupadas != '' and '{' in \ item.iniciativas_agrupadas: ...
8f48d62db11bb80803ce13e259eed1b826a2450c
5,836
def select_x(data, order=None): """ Helper function that does a best effort of selecting an automatic x axis. Returns None if it cannot find x axis. """ if data is None: return None if len(data) < 1: return None if order is None: order = ['T', 'O', 'N', 'Q'] els...
8efe25aea57444093fe19abcf8df07080c2ec0a6
5,837
def map_clonemode(vm_info): """ Convert the virtualbox config file values for clone_mode into the integers the API requires """ mode_map = {"state": 0, "child": 1, "all": 2} if not vm_info: return DEFAULT_CLONE_MODE if "clonemode" not in vm_info: return DEFAULT_CLONE_MODE ...
39b62c11dbf9f168842a238d23f587aa64a0ff61
5,838
def update_dashboard(dashboard_slug): """Update Dashboard Update an existing Dashboard --- tags: - "Dashboards" parameters: - name: dashboard_slug in: path type: string required: true - name: name in: body schema: ...
90ecfd68f6c64076893248aa7a2de58ed01afe02
5,839
import torch def dqn(n_episodes=2000, max_t=1000, eps_start=1.0, eps_end=0.01, eps_decay=0.995, target=100.0, model='checkpoint.pth'): """Deep Q-Learning. Params ====== n_episodes (int): maximum number of training episodes max_t (int): maximum number of timesteps per episode ...
433484a848f645e4581702934748c428b5d59adf
5,840
def latLon2XY(xr, yr, lat, lon, ieast=1, azimuth=0): """ Calculate the cartesian distance between consecutive lat,lon points. Will bomb at North and South Poles. Assumes geographical coordinates and azimuth in decimal degrees, local Cartesian coordinates in km. :param xr: Reference longitude, n...
4ea265f02e87593d389bcd6839390b51cc024add
5,841
import os def create_pipeline_opts(args): """Create standard Pipeline Options for Beam""" options = pipeline_options.PipelineOptions() options.view_as(pipeline_options.StandardOptions).runner = args.runner google_cloud_options = options.view_as(pipeline_options.GoogleCloudOptions) google_cloud_options.pro...
dabf786dad2548eb04d1ae970b7160a007a30c57
5,842
import sys def check_if_module_installed(module_name): """Check if a module is installed. :param module_name: Name of Module :return: Bool if module is installed or not """ distribution_instance = filter(None, (getattr(finder, 'find_distributions', None) for finder in sys.meta_path)) for res ...
70149e9e285c71dbe62e9a46fcc8733b86bf3413
5,843
def __virtual__(): """Only load if grafana4 module is available""" return "grafana4.get_org" in __salt__
acbfe3b15dafc45ab36955d0a72b92544f4dd41a
5,844
def setup( key=None, force=False ): """Do setup by creating and populating the directories This incredibly dumb script is intended to let you unpack the Tcl/Tk library Togl from SourceForce into your PyOpenGL 3.0.1 (or above) distribution. Note: will not work with win64, both because the...
928553622010570f657bfe59b30aa3d5fad68435
5,845
def categories_report(x): """Returns value counts report. Parameters ---------- x: pd.Series The series with the values Returns ------- string The value counts report. str1 = False 22 | True 20 | nan 34 str2 = False (22) | True (20) | nan (34) ...
695ccd73ee73a13e92edbdf0eb242121d136ddbb
5,846
def train(total_loss, global_step, train_num_examples): """Train model. Create an optimizer and apply to all trainable variables. Add moving average for all trainable variables. Args: total_loss: Total loss from loss(). global_step: Integer Variable counting the number of training steps ...
66189c7fd3ec55d08e6a197f2f821adc6e1b3aad
5,847
def config_module_add(): """Add module for configuration Add an available module to the config file. POST json object structure: {"action": "add", "value": { "module": "modulename", "moduleprop": ... }} On success, an object with this structure is returned: ...
8ae9324e29408614ee324c3ba32ddab169e0b50e
5,848
def command_add(fname, ctype, **kwa): """returns (str) command to add consatants from file to the DB, ex.: cdb add -e testexper -d testdet_1234 -c test_ctype -r 123 -f cm-confpars.txt -i txt -l DEBUG """ exp = kwa.get('experiment', None) det = kwa.get('detname', None) runnum ...
b6c1622f635c5f75b462be6ce025094f6df88ae5
5,849
def ustobj2songobj( ust: up.ust.Ust, d_table: dict, key_of_the_note: int = None) -> up.hts.Song: """ Ustオブジェクトをノートごとに処理して、HTS用に変換する。 日本語歌詞を想定するため、音節数は1とする。促音に注意。 ust: Ustオブジェクト d_table: 日本語→ローマ字変換テーブル key_of_the_note: 曲のキーだが、USTからは判定できない。 Sinsyでは 0 ~ 11 または 'xx' である。 ...
53c92783d881702aa42b7f24c8a1596248b30108
5,850
def detect_ol(table): """Detect ordered list""" if not len(table): return False for tr in table: if len(tr)!=2: return False td1 = tr[0] # Only keep plausible ordered lists if td1.text is None: return False text = td1.text.strip() ...
b7082932fba6ba7f9634e70ea424561c084a2dc1
5,851
import os def read_dataset_test(data_dir, transforms=None): """ Read the Mini-ImageNet dataset. Args: data_dir: directory containing Mini-ImageNet. Returns: A tuple (train, val, test) of sequences of ImageNetClass instances. """ return tuple([_read_classes(os.path.join(data_dir, 'test'), transforms)])
e7b312bf60341fe13858049b5e3bff5a52c58811
5,852
def analyze_syntax(text): """Use the NL API to analyze the given text string, and returns the response from the API. Requests an encodingType that matches the encoding used natively by Python. Raises an errors.HTTPError if there is a connection problem. """ credentials = GoogleCredentials.get_...
84387cf163f9cfab4fcabd0a43e43aab250bd01d
5,853
from typing import List from typing import Optional import os def _parseArgs(args: List[str]) -> Arguments: """ Parse the arguments. Terminates the script if errors are found. """ argLen = len(args) # Initialize the argument values inputPath: str = None sheetName: Optional[str] = None ...
71b07ea7d32a4af23c7c08f52f8eb096fc126955
5,854
def kabsch_numpy(X, Y): """ Kabsch alignment of X into Y. Assumes X,Y are both (Dims x N_points). See below for wrapper. """ # center X and Y to the origin X_ = X - X.mean(axis=-1, keepdims=True) Y_ = Y - Y.mean(axis=-1, keepdims=True) # calculate convariance matrix (for each prot in th...
85e42d58f667c70b3ad0fe0fe888fdfb383d34ee
5,855
import six import base64 def _decode(value): """ Base64 解码,补齐"=" 记得去错多余的“=”,垃圾Docker,签发的时候会去掉 :param value: :return: """ length = len(value) % 4 if length in (2, 3,): value += (4 - length) * "=" elif length != 0: raise ValueError("Invalid base64 string") if not...
c4a28605fb7f8a0d5110fb06738c31b030cae170
5,856
def header_elements(fieldname, fieldvalue): """Return a sorted HeaderElement list from a comma-separated header string. """ if not fieldvalue: return [] result = [] for element in RE_HEADER_SPLIT.split(fieldvalue): if fieldname.startswith('Accept') or fieldname == 'TE': ...
8846a0b5e89e0a4d0d3d6192e988dfe78e394338
5,857
def line2dict(st): """Convert a line of key=value pairs to a dictionary. :param st: :returns: a dictionary :rtype: """ elems = st.split(',') dd = {} for elem in elems: elem = elem.split('=') key, val = elem try: int_val = int(val) dd[k...
86bb6c2e72c8a6b2a027d797de88089067ff7475
5,858
def transform(walls, spaces): """svg coords are in centimeters from the (left, top) corner, while we want metres from the (left, bottom) corner""" joint = np.concatenate([np.concatenate(walls), np.concatenate(spaces)]) (left, _), (_, bot) = joint.min(0), joint.max(0) def tr(ps): x, y = ps[...
5ae28593a72567cf3c15f75fd37b44ca7b9468a8
5,859
from typing import Union from pathlib import Path from typing import Dict from typing import Any import os import json def get_json(partition: str, start: float = 0.0, end: float = 1.0, return_data: bool = False) -> Union[Path, Dict[Any, Any]]: """path, gender, age, result ...
7260748f2197d1632f814c0c801f26d737fcce81
5,860
def isolate(result_file, isolate_file, mode, variables, out_dir, error): """Main function to isolate a target with its dependencies. Arguments: - result_file: File to load or save state from. - isolate_file: File to load data from. Can be None if result_file contains the necessary information...
16201bf1fb11bafc9913fc620f0efea3de887e62
5,861
def check_structure(struct): """ Return True if the monophyly structure represented by struct is considered "meaningful", i.e. encodes something other than an unstructured polytomy. """ # First, transform e.g. [['foo'], [['bar']], [[[['baz']]]]], into simply # ['foo','bar','baz']. def d...
e07a2f39c7d3b8f2454b5171119b8698f4f58a99
5,862
import torch def batchify_with_label(input_batch_list, gpu, volatile_flag=False): """ input: list of words, chars and labels, various length. [[words,biwords,chars,gaz, labels],[words,biwords,chars,labels],...] words: word ids for one sentence. (batch_size, sent_len) chars: char i...
aea1b271292751740b35fe0d18b133beb7df53c7
5,863
def symbolicMatrix(robot): """ Denavit - Hartenberg parameters for n - th rigid body theta: rotation on «z» axis d: translation on «z» axis a: translation on «x» axis alpha: rotation on «x» axis """ return np.array([[0, 0, 0, 0], [robot.symbolicJointsPositions[0, 0], robot.s...
3b476527336b15c171bbede76ff5b4ed2d4a6eb6
5,864
from typing import List import json def magnitude_list(data: List) -> List: """ :param data: :return: """ if data is None or len(data) == 0: return [] if isinstance(data, str): try: data = json.loads(data) except: data = data try: ...
fc124d9a21b4b08ac50731c9234676860b837acf
5,865
import subprocess def generate_keypair(passphrase): """ Create a pair of keys with the passphrase as part of the key names """ keypath = '/tmp/test_{}_key'.format(passphrase) command = 'ssh-keygen -t rsa -b 4096 -C "{p}" -P "{p}" -f {k} -q' command = command.format(p=passphrase, ...
d4c8155173273feda778f5f54a4b0513353a293b
5,866
def lookup_axis1(x, indices, fill_value=0): """Return values of x at indices along axis 1, returning fill_value for out-of-range indices. """ # Save shape of x and flatten ind_shape = indices.shape a, b = x.shape x = tf.reshape(x, [-1]) legal_index = indices < b # Convert indice...
6e93475d5c6324a709792903a453ffbb454d2d62
5,867
def delete_compute_job(): """ Deletes the current compute job. --- tags: - operation consumes: - application/json parameters: - name: agreementId in: query description: agreementId type: string - name: jobId in: query description: I...
112e79bdfb9c569aa0d49275bf3df14c7eecd7b5
5,868
import io def load_dict(dict_path): """ Load a dict. The first column is the value and the second column is the key. """ result_dict = {} for idx, line in enumerate(io.open(dict_path, "r", encoding='utf8')): terms = line.strip("\n") result_dict[idx] = terms return result_dict
cad2061561c26e247687e7c2ee52fb5cf284352a
5,869
def project(x, n): """ http://www.euclideanspace.com/maths/geometry/elements/plane/lineOnPlane/""" l = np.linalg.norm(x) a = normalize(x) b = normalize(n) axb = np.cross(a,b) bxaxb = np.cross(b, axb) return l * bxaxb
e80d87454457920edfbe9638e6793372000bb3bd
5,870
def topologicalSort(roots, getParents): """Return a topological sorting of nodes in a graph. roots - list of root nodes to search from getParents - function which returns the parents of a given node """ results = [] visited = set() # Use iterative version to avoid stack limits for large d...
eec46378dc2282447ff1567945334b6cf18dc180
5,871
def get_headers(metric_resource: MetricResource): """ Get the headers to be used in the REST query for the given metric. """ headers = {} # no headers will be used if metric_resource.spec.headerTemplates is None: return headers, None # initialize headers dictionary for item in me...
00ab2000ef83f12ebcdc26d834b285ca1ab2da40
5,872
from typing import Iterable def indra_upstream_ora( client: Neo4jClient, gene_ids: Iterable[str], **kwargs ) -> pd.DataFrame: """ Calculate a p-value for each entity in the INDRA database based on the set of genes that it regulates and how they compare to the query gene set. """ count = co...
1e95b4dc329d09055e0f441f3ddef3614a693005
5,873
import socket import sys def log(*args, host="127.0.0.1", port=3001, surround=3, **kwargs) -> bool: """ Create `Log` object and send to codeCTRL server in cbor format. The codectrl.log function collects and formats information about the file/function/line of code it got called on and send...
9ec5cfefda67b2ad8470145270f4978f0828cbb2
5,874
def _take_photo(gopro_instance, interval_secs = 600): """ Take a photo, this function still in dev """ try: img = gopro_instance.take_photo(); return img except TypeError: tl.send_alert() return False except: tl.send_alert( message = \ '🆘*E️rror desc...
04b59957c513eee44e487ba7f86bf296a0c19150
5,875
import time def evaluate( forecaster, cv, y, X=None, strategy="refit", scoring=None, return_data=False ): """Evaluate forecaster using cross-validation Parameters ---------- forecaster : sktime.forecaster Any forecaster cv : sktime.SlidingWindowSplitter or sktime.ExpandingWindowSplitt...
ea9663c942ee71c40674c64196b3ced5f61a2c2c
5,876
def euler(step, y0): """ Implements Euler's method for the differential equation dy/dx = 1/(2(y-1)) on the interval [0,4] """ x = [0] index_x = 0 while x[index_x] < 4: x.append(x[index_x] + step) index_x += 1 index_y = 0 y = [y0] def yprime(y): yprime = 1 / (2...
89c6e6409a1c43ce4766507fba2f401bb01cfbb8
5,877
import re import os from urllib.parse import urlparse from urllib.parse import urlparse import requests def get_fileinfo(url: str, proxy: str = '', referer: str = '') -> (str, str, requests.Response): """ 获取待下载的文件信息 Gets information about the file to be downloaded :param url: 文件url :param proxy:...
e8a0d093a997cfa43bab5bb41b0d71d2c78eb118
5,878
import random def generate_random_solution(): """generate_random_solution() Generates a random solution of random characters from [ ,!,..A..Z..a..z...~].""" global answer #codes for chars [ ,!..A..Z..a..z..~] chars = list(range(32,127)) solution = [] while len(solution) < len(answer): #ge...
534a4a249bbbbc9e285b3dc9ccc5010413239b66
5,879
import importlib.util import click from pathlib import Path import sys import traceback def entrypoint_module(config): """Lazily returns the entrypoint module defined in a qaboard config""" entrypoint = config.get('project', {}).get('entrypoint') if not entrypoint: click.secho(f'ERROR: Could not find the en...
2997eb2ba4ff11ec1e1b8133cb98b6d18712a03c
5,880
def getTV_Info(): """ 获取TeamViewer的账号和密码信息 使用 Spy++ 读取特定程序中子窗口及各个控件类的信息, 然后 使用 win32 api 读取文本框中的内容 注意: # FindWindowEx() 只能查找直接子窗口,因此需要逐级查找 # 该函数的第二个参数用于表示在哪个子窗口继续查找,用于查找包含两个相同类名的子窗口 参考: https://github.com/wuxc/pywin32doc/blob/master/md/win32gui.md#win32guifindwindowex ...
2d6de5029eda4b447d9fa87c271e18fe94148dc9
5,881
import jieba def tokenize_words(text): """Word segmentation""" output = [] sentences = split_2_short_text(text, include_symbol=True) for sentence, idx in sentences: if is_chinese_string(sentence): output.extend(jieba.lcut(sentence)) else: output.extend(whitespac...
f50c963316927a8051489a22cae674b19ab7b0d5
5,882
def segmentation_model_func(output_channels, backbone_name, backbone_trainable=True): """ Creates a segmentation model with the tf.keras functional api. Args: output_channels: number of output_channels (classes) backbone_name: name of backbone; either: 'vgg19', 'resnet50', 'resnet50v2', 'mob...
31f46e0fcde797c22c07abeabbf4e4879bddf180
5,883
def EventAddKwargs(builder, kwargs): """This method is deprecated. Please switch to AddKwargs.""" return AddKwargs(builder, kwargs)
b19aa256819f3be1b018baf469b72293a08fa4db
5,884
import json def generate_sidecar(events, columns_selected): """ Generate a JSON sidecar template from a BIDS-style events file. Args: events (EventInput): An events input object to generate sidecars from. columns_selected (dict): A dictionary of columns selected. Returns: d...
4fada8d65eab69384cb1d1f26f888d40fd0cea90
5,885
def _filter_artifacts(artifacts, relationships): """ Remove artifacts from the main list if they are a child package of another package. Package A is a child of Package B if all of Package A's files are managed by Package B per its file manifest. The most common examples are python packages that are in...
642f16fd4b9784288a283a21db8632cc11af6cba
5,886
def get_augmented_image_palette(img, nclusters, angle): """ Return tuple of (Image, Palette) in LAB space color shifted by the angle parameter """ lab = rgb2lab(img) ch_a = lab[...,1] ch_b = lab[...,2] theta = np.deg2rad(angle) rot = np.array([[cos(theta), -sin(theta)], [sin(theta), ...
89cfc4f50a70be413aa6525b9b462924baaf9907
5,887
import os def autodetect(uri: str, **kwargs) -> intake.source.DataSource: """ Autodetect intake source given URI. Keyword arguments are passed to the source constructor. If no other source is more suitable, it returns an instance of :class:`intake_io.source.ImageIOSource`, which uses `imageio <h...
b93e91d0fd54ccca71d1a64c269bac963bd82b69
5,888
def squeeze__default(ctx, g, self, dim=None): """Register default symbolic function for `squeeze`. squeeze might be exported with IF node in ONNX, which is not supported in lots of backend. """ if dim is None: dims = [] for i, size in enumerate(self.type().sizes()): if s...
7ce7672f187f2d699cc378d00b1415007a2fe04b
5,889
from predefinedentities import BANNED_PREF_BRANCHES, BANNED_PREF_REGEXPS import re def _call_create_pref(a, t, e): """ Handler for pref() and user_pref() calls in defaults/preferences/*.js files to ensure that they don't touch preferences outside of the "extensions." branch. """ if not t.im_s...
90ceef343ead469da5fb078b45ee30c87fceb84b
5,890
def pig_action_utility(state, action, utility): """The expected value of choosing action in state.Assumes opponent also plays with optimal strategy. An action is one of ["roll", "hold", "accept", decline", "double"] """ if action == 'roll': one = iter([1]) rest = iter([2, 3, 4, 5, 6]) ...
c2e06a074f5fefd62f8a810e338bb7938d1cf6fd
5,891
def to_canonical_url(url): """ Converts a url into a "canonical" form, suitable for hashing. Keeps only scheme, domain and path. Ignores url query, fragment, and all other parts of the url. :param url: a string :return: a string """ parsed_url = urlparse(url) return urlunparse([ ...
0991502fcd696308d0fe50a06a7fa5e2e12703af
5,892
from pydash import get from jobflow.utils.find import find_key_value from typing import Any def find_and_get_references(arg: Any) -> tuple[OutputReference, ...]: """ Find and extract output references. This function works on nested inputs. For example, lists or dictionaries (or combinations of list a...
a2b1873ecd921afbb3d254c0a0fe4706c0ca5d12
5,893
def get_fdr_thresh(p_values, alpha=0.05): """ Calculate the false discovery rate (FDR) multiple comparisons correction threshold for a list of p-values. :param p_values: list of p-values :param alpha: the uncorrected significance level being used (default = 0.05) :type p_values: numpy array :type alpha: float ...
5182eef60be397fe9f13ecb4e5440adc1a9ffd00
5,894
import typing def _rescue_filter( flags: RescueRenderFlags, platform_filter: typing.Optional[Platforms], rescue: Rescue ) -> bool: """ determine whether the `rescue` object is one we care about Args: rescue: Returns: """ filters = [] if flags.filter_unassigned_rescues: ...
bb192e4fd8eeb811bb681cec6e60956a71a1c15b
5,895
def penalty(precision, alpha, beta, psi): """Penalty for time-varying graphical lasso.""" if isinstance(alpha, np.ndarray): obj = sum(a[0][0] * m for a, m in zip(alpha, map(l1_od_norm, precision))) else: obj = alpha * sum(map(l1_od_norm, precision)) if isinstance(beta, np.ndarray): ...
e8563c82cb51a5e3efa25fac5647b782abecabdf
5,896
from propy.CTD import CalculateCTD from typing import Optional from typing import List def all_ctd_descriptors( G: nx.Graph, aggregation_type: Optional[List[str]] = None ) -> nx.Graph: """ Calculate all CTD descriptors based seven different properties of AADs. :param G: Protein Graph to featurise ...
71dc1559b1d3f3a682e1a2107b0cd9fb49c57b9e
5,897
def get_report_hash(report: Report, hash_type: HashType) -> str: """ Get report hash for the given diagnostic. """ hash_content = None if hash_type == HashType.CONTEXT_FREE: hash_content = __get_report_hash_context_free(report) elif hash_type == HashType.PATH_SENSITIVE: hash_content = _...
6f0ba5edfcc49daa9f700857e8b6ba5cd5f7d1ba
5,898
import json def parse_json_file(json_file_path, allow_non_standard_comments=False): """ Parse a json file into a utf-8 encoded python dictionary :param json_file_path: The json file to parse :param allow_non_standard_comments: Allow non-standard comment ('#') tags in the file :return:...
0df1108aedb60f0b0e0919c6cc7a66dd736ff8ac
5,899