content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
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
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 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
def __virtual__(): """Only load if grafana4 module is available""" return "grafana4.get_org" in __salt__
acbfe3b15dafc45ab36955d0a72b92544f4dd41a
5,844
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 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
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
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
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
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
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 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
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
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
import logging def update_softwaretitle_packages(api, jssid, pkgs): """ Update packages of software title :param jssid: Patch Software Title ID :param pkgs: dict of {version: package, ...} :returns: None """ logger = logging.getLogger(__name__) data = api.get(f"patchs...
0acb3dfbff0e85a2e8a876d5e5d484c4d1e52068
5,900
from typing import List def get_balances(session: Session, redis: Redis, user_ids: List[int]): """Gets user balances. Returns mapping { user_id: balance } Enqueues in Redis user balances requiring refresh. """ # Find user balances query: List[UserBalance] = ( (session.query(UserBalance...
82f6fdf0fcc8bcd241c97ab50a89ba640793b704
5,901
from typing import Optional from typing import Tuple def kmeans(observations: ndarray, k: Optional[int] = 5) -> Tuple[ndarray, ndarray]: """Partition observations into k clusters. Parameters ---------- observations : ndarray, `shape (N, 2)` or `shape (N, 3)` An array of observations (x, y) to...
1a8cb2e61e8d96a45d4165edf1b148fd7c8ab5e3
5,902
def encloses(coord, points): """ """ sc = constants.CLIPPER_SCALE coord = st(coord.to_list(), sc) points = st(points, sc) return pyclipper.PointInPolygon(coord, points) != 0
d5d7aeb8f52087653027d57c7a718832dbf32200
5,903
def arpls(y, lam, ratio=1e-6, niter=1000, progressCallback=None): """ Return the baseline computed by asymmetric reweighted penalized least squares smoothing, arPLS. Ref: Baseline correction using asymmetrically reweighted penalized least squares smoothing Sung-June Baek, Aaron Park, Young-Jin Ahn a...
d149397827d89b8708a09f4ceb7c38c989d99e17
5,904
async def test_function_raised_exception(dut): """ Test that exceptions thrown by @function coroutines can be caught """ @cocotb.function async def func(): raise ValueError() @external def ext(): return func() with pytest.raises(ValueError): await ext()
acd31a1142dea0cd300861e75721a4597e2b5bbc
5,905
def dismiss_notification_mailbox(notification_mailbox_instance, username): """ Dismissed a Notification Mailbox entry It deletes the Mailbox Entry for user Args: notification_mailbox_instance (NotificationMailBox): notification_mailbox_instance username (string) Return: bo...
9955361ac42c079adefcd8402fb9a1d5e3822a57
5,906
import operator def knn(x, y, k, predict_x): """ knn算法实现,使用欧氏距离 :param x: 样本值 :param y: 标签 :param k: 个数 :return: """ assert isinstance(y, np.ndarray) y = y.flatten('F') def cal_distance(a, b): return np.sqrt(np.sum(np.power(a - b, 2), axis=0)) dists = { ...
425095898acce2fc966d00d4ba6bc8716f1062f8
5,907
def piano(): """A piano instrument.""" return lynames.Instrument('Piano', abbr='Pno.', transposition=None, keyboard=True, midi='acoustic grand', family='percussion', mutopianame='Piano')
792a1dd3655ac038bdde27f9d1ad27451e2b9121
5,908
from typing import Any from typing import Dict def extract_fields(obj: Any) -> Dict[str, Any]: """A recursive function that extracts all fields in a Django model, including related fields (e.g. many-to-many) :param obj: A Django model :return: A dictionary containing fields and associated values """ ...
bc6b45a82ab2a336e116ce528aaed45b2b77ef39
5,909
from re import T def decomposeM(modified): """Auxiliary in provenance filtering: split an entry into name and date.""" splits = [m.rsplit(ON, 1) for m in modified] return [(m[0], dtm(m[1].replace(BLANK, T))[1]) for m in splits]
1f613d11d2f8c3ceec4f6c853b9412b5b7eb3e0c
5,910
def get_2d_peaks_coords( data: np.ndarray, size: int = None, threshold: float = 0.5 ) -> np.ndarray: """Detect peaks in image data, return coordinates. If neighborhoods size is None, default value is the highest value between 50 pixels and the 1/40th of the smallest image dimension. Detection thre...
815979bd0105acc7bb3fb58db691a8963d9ca2f4
5,912
def border_positions_from_texts(texts, direction, only_attr=None): """ From a list of textboxes in <texts>, get the border positions for the respective direction. For vertical direction, return the text boxes' top and bottom border positions. For horizontal direction, return the text boxes' left and rig...
8b0f57e21b015b6092104454195254861432b610
5,913
def progress(self): """Check if foo can send to corge""" return True
89a0c9671645f9fa855db35bf5e383145d6b7616
5,914
def write_sample_sdf(input_file_name, valid_list): """ Function for writing a temporary file with a subset of pre-selected structures :param input_file_name: name of input file :param valid_list: list of indexes of pre-selected structures :return: name of subsampled file """ sample_fil...
0b22c14452f6de978e7ea811d761195d92bfe6c4
5,915
import math def rotx(theta, unit="rad"): """ ROTX gives rotation about X axis :param theta: angle for rotation matrix :param unit: unit of input passed. 'rad' or 'deg' :return: rotation matrix rotx(THETA) is an SO(3) rotation matrix (3x3) representing a rotation of THETA radians about th...
b05a6116c64837de163ad26dc36ffe1a7166635d
5,916
from typing import Sequence def _table(*rows: Sequence) -> str: """ >>> _table(['a', 1, 'c', 1.23]) '|a|1|c|1.23|' >>> _table(['foo', 0, None]) '|foo|||' >>> print(_table(['multiple', 'rows', 0], ['each', 'a', 'list'])) |multiple|rows|| |each|a|list| """ return '\n'.join([ ...
d566da2ad9240e73b60af00d3e4b4e25607234b4
5,917
def trunc(s, n): """ Truncate a string to N characters, appending '...' if truncated. trunc('1234567890', 10) -> '1234567890' trunc('12345678901', 10) -> '1234567890...' """ if not s: return s return s[:n] + '...' if len(s) > n else s
0f3c9f03f566f9f50a557f6b5592ec20a12e92bc
5,918
def cs_geo(): """Geographic lat/lon coordinates in WGS84 datum. """ cs = CSGeo() cs.inventory.datumHoriz = "WGS84" cs.inventory.datumVert = "mean sea level" cs.inventory.spaceDim = 2 cs._configure() cs.initialize() return cs
28df90e7b1490d681c9d13f4604dbc3966d896dc
5,920
def make_range(value): """ Given an integer 'value', return the value converted into a range. """ return range(value)
385d23eaebd04249f9384e0d592b7fb3a9bbb457
5,921
def run(actor, observer, content): """ Shortcut to run an Onirim and return the result. Returns: True if win, False if lose, None if other exception thrown. """ return Flow(Core(actor, observer, content)).whole()
03b1dee5bd993d8a88debd558878de5a32e9c318
5,922
def GetPoseBoneFCurveFromArmature(armatureObj, poseBoneName, data_path, parameterIndex): """ In Blender the FCurves are used to define the Key Frames. In general, for a single object, there's one FCurve for each of the following properties. data_path, index 'location', 0 (.x...
450d98306adf43ea171dffa0fe6afa71ebabce57
5,923
def get_document_instance(conf=None): """ Helper function to get a database Document model instance based on CLA configuration. :param conf: Same as get_database_models(). :type conf: dict :return: A Document model instance based on configuration specified. :rtype: cla.models.model_interfaces.D...
054f6ff6acc38ed44a9bd2a97e0598ed34b322f8
5,924
from typing import List def get_full_private_keys(gpg: gnupg.GPG) -> List[GPGKey]: """Get a list of private keys with a full private part. GPG supports exporting only the subkeys for a given key, and in this case a stub of the primary private key is also exported (the stub). This stub cannot be used ...
d2bbb248613c3be9ed103212e0ca2a433de07e03
5,925
def create_blueprint(): """Creates a Blueprint""" blueprint = Blueprint('Health Check Blueprint', __name__) blueprint.route('/')(healthcheck.healthcheck) return blueprint
348c6ff172bb0d230d83eab73dd451edba0d1b00
5,926
def playable_card(card, fireworks, n_colors): # if isinstance(card, pyhanabi.HanabiCard): # card = {'color':colors[card.color],'rank':card.rank} """A card is playable if it can be placed on the fireworks pile.""" if (card.color == pyhanabi.HanabiCard.ColorType.kUnknownColor and card().rank != pyh...
a96c6935c6b57ead9c639f13d8eccccbaf21aa4b
5,927