content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_model_kind(model): """Returns the "kind" of the given model. NOTE: A model's kind is usually, but not always, the same as a model's class name. Specifically, the kind is different when a model overwrites the _get_kind() class method. Although Oppia never does this, the Apache Beam framework...
58465fd8d9a7893aeb046b5e05e713a912ff4a2f
3,637,039
def get_Zvalence_from_pseudo(pseudo): """ Extract the number of valence electrons from a pseudo """ with open(pseudo.get_file_abs_path(),'r') as f: lines=f.readlines() for line in lines: if 'valence' in line: try: return int(float(...
aade59ef7d9d7d517c19f95d237993433f21ed7a
3,637,040
import ruptures as rpt def detect_data_shifts(time_series, filtering=True, use_default_models=True, method=None, cost=None, penalty=40): """ Detect data shifts in the time series, and return list of dates where these data shifts occur. Parameters ----...
d924d36a53f965b76943f1a466d3b88649cbe0ef
3,637,041
def read_rds(filepath): """Read an RDS-format matrix into a Pandas dataframe. Location can be data, scratch, or results. Index is populated from first column""" raw_df = pyreadr.read_r(filepath)[None] if raw_df.isnull().values.any(): raise ValueError("NaN's were found in the data matrix.") ...
c4b171638883fc2c3b32397e79a413a9441567f0
3,637,042
def history(): """Show history of transactions.""" # Read Transactions database for desired elements transactions = db.execute("SELECT symbol, share, price, method, timestamp FROM Transactions WHERE id = :uid", uid = session["user_id"]) # Convert prices to 2 decimal places for transaction in tr...
5eac4a49c473467db851fe2ea6e58b29cc1a9bfe
3,637,043
from typing import get_args def generate_args(job_name, common, cloud_provider, image, k8s_version, test_suite, job): """Returns a list of args fetched from the given fields.""" args = [] args.extend(get_args(job_name, common)) args.extend(get_args(job_name, cloud_provider)) args...
7f53dcf66269b0d14f9fad1c1079cf1716529f09
3,637,045
import math def isPrime(n): """ check is Prime,for positive integer. 使用试除法 """ if n <= 1: return False if n == 2: return True i = 2 thres = math.ceil(math.sqrt(n)) while i <= thres: if n % i == 0: return False i += 1 return True
458775fbd324dc976c91a035898b3122e6bc1109
3,637,046
from typing import Tuple import torch def reconstruction_loss(loss_type: str, in_dim: Tuple[int], x: torch.Tensor, x_reconstr: torch.Tensor, logits: bool = True, ) -> torch.Tensor: """ Compu...
30dbd75eddbc7f2d0994f867e2f9492b24f707b1
3,637,047
def NOR(*variables): """NOR. Return the boolean expression for the OR of the variables. Equivalent to ``NOT(OR(*variables))``. Parameters ---------- *variables : arguments. ``variables`` can be of arbitrary length. Each variable can be a hashable object, which is the label of t...
e3b9d5eb3c167ac04de66609828583bb5eeb7004
3,637,048
import io import time def timing_run(args, shell: bool = False, stdin=None, stdout=None, stderr=None, environ=None, cwd=None, resources=None, identification=None, shuffle=False) -> RunResult: """ Create an timing process with stream :param args: arguments for execution :param shell: use...
936d9611769dc5e04381131cd7bf18be73580bb3
3,637,049
def alterMethods(cls): """ Alter Monte methods on behalf of AutoHelp. Return the signatures of the altered methods. NOT_RPYTHON """ atoms = [] imports = set() def nextName(nameIndex=[0]): name = "_%d" % nameIndex[0] nameIndex[0] += 1 return name execNames...
9c1dcbda1a96196bdde3f31563d53f8c2be6eeb1
3,637,050
from typing import List from typing import Union def make_multiclouds(docs: List[Union[dict, object, str, tuple]], opts: dict = None, ncols: int = 3, title: str = None, labels: List[str] = None, show: bool = True, ...
9c1f6363d1cc6cd0e20591c1ab54b1761414d29c
3,637,051
def action_prop(param, val=1): """A param that performs an action""" def fdo(self): self.setter(param, val) return fdo
6a4f6e7e178e62755113d6b93a59534675dfa2dd
3,637,052
def find_or_create(find, create): """Given a find and a create function, create a resource if it doesn't exist""" result = find() return result if result else create()
ffe608bf2da1b83d662b93266f4309976424300f
3,637,053
import math def Gsigma(sigma): """Pickle a gaussian function G(x) for given sigma""" def G(x): return (math.e ** (-(x**2)/(2*sigma**2)))/(2 * math.pi* sigma**2)**0.5 return G
77eac3ca8b6ced0063074527b83c50e8681f980d
3,637,054
from indico.modules.events.contributions.ical import generate_contribution_component def session_to_ical(session, detailed=False): """Serialize a session into an iCal. :param session: The session to serialize :param detailed: If True, iCal will include the session's contributions """ calendar = i...
9f0cb5a5ce6f31c6690b71948fbe6e8eeb2f7080
3,637,055
def _normalize_hosts(hosts): """ Helper function to transform hosts argument to :class:`~elasticsearch.Elasticsearch` to a list of dicts. """ # if hosts are empty, just defer to defaults down the line if hosts is None: return [{}] # passed in just one string if isinstance(hosts,...
ef3a6cfadd6a297f31afdfec4b8a77a0f88cd08f
3,637,056
def data(self: Client) -> DataProxy: """Delegates to a :py:class:`mcipc.rcon.je.commands.data.DataProxy` """ return DataProxy(self, 'data')
072806ad6f27e8bd645bd04cf34619946a83bf06
3,637,057
def proximal_policy_optimization_loss(advantage, old_prediction, loss_clipping=0.2, entropy_loss=5e-3): """ https://github.com/LuEE-C/PPO-Keras/blob/master/Main.py # Only implemented clipping for the surrogate loss, paper said it was best :param advantage: :param old_prediction: :param loss_clip...
ca7e1a602a6da6236fbd85facb373fa623fc62d5
3,637,058
import re def tokenize_string(string): """Split a string up into analyzable characters. Returns a list of individual characters that can then be matched with the regex patterns. Note that all accent characters can be found with the range: \u0300-\u036F. Thus, strings are split by [an...
f3757e190f99d3430dee17ca51ea6a6d7fa70ff9
3,637,059
def compute_final_metrics(source_waveforms, separated_waveforms, mixture_waveform): """Permutation-invariant SI-SNR, powers, and under/equal/over-separation.""" perm_inv_loss = wrap(lambda tar, est: -signal_to_noise_ratio_gain_invariant(est, tar)) _, separated_waveforms = perm_inv_loss(source_waveforms,sepa...
3e7a6a52b8a26c4a4fa7fec9de17559617e4d467
3,637,060
import numpy import pandas def gen_sdc_pandas_series_rolling_impl(pop, put, get_result=result_or_nan, init_result=numpy.nan): """Generate series rolling methods implementations based on pop/put funcs""" def impl(self): win = self._window minp = self._min_...
8fb25c10e862d21af75b244053ac96075c1efa19
3,637,061
def gen_random_colors(num_groups, colors=None): """ Generates random colors. Parameters ---------- num_groups : int The number of groups for which colors should be generated. colors : list : optional (contains strs) Hex based colors that should be appended if no...
462835c6bacd5024ac20bab960d2c2e9d95e4dab
3,637,062
def build_graph(sorted_sequence): """ Each node points to a list of the nodes that are reacheable from it. """ elements = set(sorted_sequence) graph = defaultdict(lambda : []) for element in sorted_sequence: for i in [1, 2, 3]: if element + i in elements: grap...
a14d2278909df459856e23c7073d551b354f258d
3,637,065
from numpy import std def _findCentralBond(mol, distmat): """ Helper function to identify the atoms of the most central bond. Arguments: - mol: the molecule of interest - distmat: distance matrix of the molecule Return: atom indices of the two most central atoms (in order) """ # ge...
bbaca8c48bf8c5e1a5d2ffa317448f05235c834e
3,637,066
def transform(data, transformer): """This hook defines how DataRobot will use the trained object from fit() to transform new data. DataRobot runs this hook when the task is used for scoring inside a blueprint. As an output, this hook is expected to return the transformed data. The input parameters are p...
b52577c0b2a3f3edb1297dcf9c567f9845f04bd5
3,637,067
import asyncio import base64 async def sign_params(params, certificate_file, private_key_file): """ Signs params adding client_secret key, containing signature based on `scope`, `timestamp`, `client_id` and `state` keys values. :param dict params: requests parameters :param str certificate_file: p...
be9980e5fb0b60da8a21c77b4ac7c9795560b557
3,637,068
def sum_of_fourth_powers(matrix): """ :param matrix: (numpy.ndarray) A numpy array. :return: The fourth power of the four-norm of the matrix. In other words, the sum of the fourth power of all of its entries. """ squared_entries = matrix * matrix return np.sum(squared_entries * squared_e...
51039a259594205a88b223b1e3d8387e05581c0f
3,637,069
from typing import Dict def key_in_direction(start: Key, direction: str, keypad: Keypad) -> Key: """ Return the value of the key in the given direction. """ row = next(r for r in keypad if start in r) x_pos = row.index(start) col = [c[x_pos] for c in keypad] y_pos = col.index(start) d...
c0a8909517ec1de29325d0acc18e0c8968bda3b5
3,637,070
def vectorize_args(nums): """ Decorator for vectorization of arguments of a function. The positions of the arguments are given in the tuple nums. See numpy.vectorize. """ def wrap(func): @wraps(func) def wrapped(*args, ** kwargs): args = list(args) for i,...
cd9b13bdcd26f1c74a2eaa18396ebfb11ed02446
3,637,071
def parse_lambda_config(x): """ Parse the configuration of lambda coefficient (for scheduling). x = "3" # lambda will be a constant equal to x x = "0:1,1000:0" # lambda will start from 1 and linearly decrease # to 0 during the first 1000 iterations ...
d85980c2efd46284de8e939f42ef4f5dd49dfd73
3,637,072
def format_cols(colname, direction='in'): """Formats columns beween human-readable and pandorable Keyword arguments: real -- the real part (default 0.0) imag -- the imaginary part (default 0.0) """ if imag == 0.0 and real == 0.0: return complex_zero ... if direction == 'in': ...
a61dbedb2e08c4de03c719c4daff10de41e19304
3,637,073
def convert_decimal_to_binary(number): """ Parameters ---------- number: int Returns ------- out: str >>> convert_decimal_to_binary(10) '1010' """ return bin(number)[2:]
01a9be2e70c87091adc1d85759075668da9270f2
3,637,074
from typing import Optional import pathlib import tarfile def fetch_tgz( dataname: str, urlname: str, subfolder: Optional[str] = None, data_home: Optional[str] = None, ) -> pathlib.Path: """Fetch tgz dataset. Fetch a tgz file from a given url, unzips and stores it in a given directory. ...
00c4f91a657e37767a43b3af0766b5b407144617
3,637,075
def choisir_action(): """Choisir action de cryptage ou de décryptage Entree : - Sortie: True pour cryptage, False pour décryptage""" action_est_crypter = True action = input("Quelle est l'action, crypter ou décrypter ? \n<Entrée> pour crypter, autre touche pour decrypter, ou <Crtl> + Z ou X pour arréter.\n") ...
c0bceb748afb1fc32b865136c4a477f06a6412b2
3,637,076
def σ(u, p, μ): """Stress tensor of isotropic Newtonian fluid. σ = 2 μ (symm ∇)(u) - p I This method returns a UFL expression the whole stress tensor. If you want to plot, extract and interpolate or project what you need. For example, to plot the von Mises stress:: from dolfin import ...
03f61ea7c128503ee930714107a8f7a007641cee
3,637,077
async def cycle(command: Command, switches: PowerSwitch, name: str, portnum: int): """cycle power to an Outlet""" command.info(text=f"Cycle port {name}...") for switch in switches: current_status = await switch.statusAsJson(name, portnum) if current_status: break # print(...
7b5a17eaeecb4d8f1072f014de716bb1bb95dc97
3,637,078
def zk_delete_working_node(zk_client, server): """删除服务节点""" node_path, root_path = get_path_to_current_working_node(server) zk_client.ensure_path(root_path) result = zk_client.delete(node_path, ephemeral=True) return result
45effe39d8cd5eb22742c6eed19984ae40b0e192
3,637,079
import torch def construct_filters_from_2d(matrix, filter_starts, decomp_level): """ construct the filters in the proper shape for the DWT inverse forward step Parameters ---------- matrix filter_starts decomp_level Returns ------- """ exp = filter_starts[0] low = ma...
10411e774dc654586cd9b88b40e405b695a12919
3,637,080
def minpoly(firstterms): """ Return the minimal polynomial having at most degree n of of the linearly recurrent sequence whose first 2n terms are given. """ field = ring.getRing(firstterms[0]) r_0 = uniutil.polynomial({len(firstterms):field.one}, field) r_1 = uniutil.polynomial(enumerate(rev...
8cad899aa40859884b4cdbe01b0734de84782804
3,637,081
def scale_gradient(tensor, scale): """Scales the gradient for the backward pass.""" return tf.add(tensor * scale ,tf.stop_gradient(tensor) * (1 - scale))
e3ea3a7baf06ebab5de0510ea13260e89b9397ca
3,637,082
import ast import random def t_rename_local_variables(the_ast, all_sites=False): """ Local variables get replaced by holes. """ changed = False candidates = [] for node in ast.walk(the_ast): if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): if node.id not i...
8faeea81faac55d5d45b897776cd87cb508404a5
3,637,084
from typing import List def get_scale(notes: List[str]) -> int: """Convert a list of notes to a scale constant. # Args - *notes*: list of notes in the scale. This should be a list of string where each string is a note ABC notation. Sharps should be represented with a pound sign preceding...
91cbcc7bfa05df52adf741b85f78beeabf819966
3,637,085
import math def slurm_format_bytes_ceil(n): """ Format bytes as text. SLURM expects KiB, MiB or Gib, but names it KB, MB, GB. SLURM does not handle Bytes, only starts at KB. >>> slurm_format_bytes_ceil(1) '1K' >>> slurm_format_bytes_ceil(1234) '2K' >>> slurm_format_bytes_ceil(12345678) ...
ce48c778b9605105ed9b66a55d27796fb90499cc
3,637,086
def factory_payment_account(corp_number: str = 'CP0001234', corp_type_code: str = 'CP', payment_system_code: str = 'PAYBC'): """Factory.""" return PaymentAccount( corp_number=corp_number, corp_type_code=corp_type_code, payment_system_code=payment_system_code, ...
896fe2ac0162455c4da97bd629d0e3f2d9b2a1e2
3,637,087
def foo(): """多参数函数的传参书写格式, 和类实例化的格式""" ret = foo_long(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8) # 类实例化,传多个参数的格式 object_ = ClassName( a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8 ) return ret
4571ef723cab1601acfa01eb0765eaf8002df2e0
3,637,089
def posture_seq(directory,postures,sampling_fraction): """posture_seq grabs samples locomotion files from a directory and converts them to strings of posture_sequences Input: directory = the directory containing locomotion files postures = the mat file or numpy array of template postur...
7e1554f85dfc68b293c9db5a5db3aa5bd6414bff
3,637,090
from ._finite_differences import _window1d, _lincomb import torch def membrane_diag(voxel_size=1, bound='dct2', dim=None, weights=None): """Diagonal of the membrane regulariser. If no weight map is provided, the diagonal of the membrane regulariser is a scaled identity with scale `2 * alpha`, where `...
3329c43aa5ae025a14660e1ddd4c1f658740e1d4
3,637,091
def get_groups(parsed, store, conf): """ Return groups based on argument provided :param Namespace parsed: arguments parsed :param store: Otter scaling group collection :param dict conf: config :return: Deferred fired with list of {"tenantId": .., "groupId": ..} dict """ log = mock_log...
0441863984173236b09b50987c6f22838679a497
3,637,093
import json def get_content_details(site_code, release_uuid, content_type, content_key): """ get_content_details """ publisher_api = PublisherAPI() content_release = None try: if release_uuid: # get ContentRelease content_release = WSSPContentRelease.objects.get( ...
f71a4e4584474e24cfb6d25aad2465538575cbdf
3,637,094
import scipy def _czt(x, M=None, W=None, A=1.0): """Calculate CZT (Stripped down to the basics).""" # Unpack arguments N = len(x) if M is None: M = N if W is None: W = np.exp(-2j * np.pi / M) A = np.complex128(A) W = np.complex128(W) # CZT algorithm k = np.arange(...
a0852eacd8d4e35e0c6e96cc59e8692d9d806c5d
3,637,095
from typing import Any from typing import Optional def build_obs_act_forward_fc( n_out: int, depth: int, hidden: int, act_layer: Any, last_layer: Optional[Any] = None, ) -> hk.Transformed: """Build a simple fully-connected forward step that takes an observation & an action. Args: ...
0d330910730ccf80213852aa7cd08950f09e6300
3,637,097
def update_nested(key, d, other): """Update *d[key]* with the *other* dictionary preserving data. If *d* doesn't contain the *key*, it is updated with *{key: other}*. If *d* contains the *key*, *d[key]* is inserted into *other[key]* (so that it is not overriden). If *other* contains *key* (and poss...
efbbfd576652710c92939581c48e32edce1a956e
3,637,098
def quicksort(arr, low, high): """ Quicksort function uses the partition helper function. """ if low < high: pi = partition(arr, low, high) quicksort(arr, low, pi-1) quicksort(arr, pi+1, high) return arr
aa51f8536f47f8529c2bda74ea96138062d939e7
3,637,099
def make_word_dict(): """read 'words.txt ' and create word list from it """ word_dict = dict() fin = open('words.txt') for line in fin: word = line.strip() word_dict[word] = '' return word_dict
a4213cf5ff246200c7a55a6d1525d6fd6067e31f
3,637,100
def voidobject(key_position: int, offset: int) -> HitObject: """ 引数から判定のないヒットオブジェクト(シングルノーツのみ)のHitObjectクラスを生成します 引数 ---- key_position : int -> キーポジション、1から入れる場合はkey_assetから参照したものを入れてください offset : int -> (配置する)オフセット値 戻り値 ------ HitObject -> 空ノーツのHitObjectクラス """ return HitObject(key_position, max_off...
d7d47204bfb09592811fa85c4aa71e3e80bfa7bc
3,637,101
def mock_user_save(): """Функция-пустышка для эмуляции исключения во время записи пользователя.""" def user_save(*args, **kwargs): raise IntegrityError return user_save
144ad41b9b9a2d477d622b6c2284c36514581ea1
3,637,102
def index(): """首页""" banners = Banner.query_used() page = request.args.get("page", 1, type=int) # 指定的页码 per_page = current_app.config["MYZONE_ARTICLE_PER_PAGE"] # 每页的文章数 pagination = Article.query_order_by_createtime(page, per_page=per_page) # 创建分页器对象 articles = pagination.items # 从分页器中获取查询...
ba3f6a558e4edb60025ef01832bb5ff5a1fb7f7a
3,637,103
def create_temporal_vis(ldf, col): """ Creates and populates Vis objects for different timescales in the provided temporal column. Parameters ---------- ldf : lux.core.frame LuxDataFrame with underspecified intent. col : str Name of temporal column. Returns ----...
9a52600c1aac10a76b85b63c2879341dcc14b415
3,637,104
def num_neighbours(skel) -> np.ndarray: """Computes the number of neighbours of each skeleton pixel. Parameters ---------- skel : (H, W) array_like Input skeleton image. Returns ------- (H, W) array_like Array containing the numbers of neighbours at each skeleton pixel and ...
aad9f1de0f192777ebc41e603cd6ac47aa3cd49f
3,637,106
def FakeSubject(n=300, conc=0.1, num_reads=400, prevalences=None): """Makes a fake Subject. If prevalences is provided, n and conc are ignored. n: number of species conc: concentration parameter num_reads: number of reads prevalences: numpy array of prevalences (overrides n and conc) "...
91230288344c55cd4417175560ec7b3e714d9f98
3,637,107
from datetime import datetime import pytz def build_results_candidate_people(): """ Return DataFrame containing results, candidates, and people joined """ people = pd.read_csv('data/people.csv') candidates = pd.read_csv('data/candidates.csv') results = pd.read_csv('data/results.csv') res...
5e330b026b3546e728f9a06df33eaf8fc429775c
3,637,108
def div(lhs: Value, rhs: Value) -> Value: """ Divides `lhs` by `rhs`. """ return lhs.run() // rhs.run()
73cb05b536c94e56331054e92e7d9fb84f75fdb5
3,637,109
def get_seat_total_per_area(party_id: PartyID) -> dict[AreaID, int]: """Return the number of seats per area for that party.""" area_ids_and_seat_counts = db.session \ .query( DbArea.id, db.func.count(DbSeat.id) ) \ .filter_by(party_id=party_id) \ .outerjoi...
35aced1f8e149a06f54ed43f41b80f796608316b
3,637,110
def toCamelCase(string: str): """ Converts a string to camel case Parameters ---------- string: str The string to convert """ string = str(string) if string.isupper(): return string split = string.split("_") # split by underscore final_split = [] for...
5197ad3353f2e88ccf1dfca62aeae59260e016e7
3,637,111
def aggregate_testsuite(testsuite): """ Compute aggregate results for a single test suite (ElemTree node) :param testsuite: ElemTree XML node for a testsuite :return: AggregateResult """ if testsuite is None: return None tests = int(testsuite.attrib.get('tests') or 0) failures = int...
3b7ff5b353e0f6efffed673e1dcb463f00a0e708
3,637,112
def rowwidth(view, row): """Returns the number of characters of ``row`` in ``view``. """ return view.rowcol(view.line(view.text_point(row, 0)).end())[1]
f8db1bf6e3d512d1a2bd5eeb059af93e8ac3bc5f
3,637,113
import json def dry_query(event, *args): """Handles running a dry query Args: url: dry_query?page&page_length&review_id body: search: search dict <wrapper/input_format.py> Returns: { <wrapper/output_format.py> } """ # try: body = json.l...
0c69da353d958e9628e31dce68fe6bcafd482f2c
3,637,115
def fixed_prior_to_measurements(coords, priors): """ Convert the fixed exchange and met conc priors to measurements. """ fixed_exchange = get_name_ordered_overlap(coords, "reaction_ind", ["exchange", "fixed_x_names"]) fixed_met_conc = get_name_ordered_overlap(coords, "metabolite_ind", ["metabolite",...
3dab3eddb5f785dd04bba4caddbc631a0cdfd187
3,637,116
def get_batch_size(): """Returns the batch size tensor.""" return get_global_variable(GraphKeys.BATCH_SIZE)
4b030738c78fa5a06d27a2aee62f15ff3e6be347
3,637,117
from altdataset import CSVDataset def get_dataloader(config: ExperimentConfig, tfms: Tuple[List, List] = None): """ get the dataloaders for training/validation """ if config.dim > 1: # get data augmentation if not defined train_tfms, valid_tfms = get_data_augmentation(config) if tfms is None e...
d314a0bf6f7c9707ce46127e06bc8c22183246f1
3,637,118
def retournerTas(x,numéro): """ retournerTas(x,numéro) retourne la partie du tas x qui commence à l'indice numéro """ tasDuBas = x[:numéro] tasDuHaut = x[numéro:] tasDuHaut.reverse() result = tasDuBas + tasDuHaut # print(result) return result
579798cf5fe8bec02109bfd46c5a945faee1a42c
3,637,119
def nback(n, k, length): """Random n-back targets given n, number of digits k and sequence length""" Xi = random_state.randint(k, size=length) yi = np.zeros(length, dtype=int) for t in range(n, length): yi[t] = (Xi[t - n] == Xi[t]) return Xi, yi
37ec70fdc60104fc5a99c6ba13923a2e3d56f0a4
3,637,121
def makeStateVector(sys, start_time=0): """ Constructs the initial state vector recursively. Parameters ---------- sys: inherits from control.InputOutputSystem start_time: float Returns ------- list """ x_lst = [] if "InterconnectedSystem" in str(type(sys)): for...
e184d476c9ba94d88ee462c95987cabc31e459d0
3,637,122
def make_random_tensors(spec_structure, batch_size = 2): """Create random inputs for tensor_spec (for unit testing). Args: spec_structure: A dict, (named)tuple, list or a hierarchy thereof filled by TensorSpecs(subclasses). batch_size: If None, we will have a flexible shape (None,) + shape. If <= 0 ...
dd2569def0863b1e9722de9c6175e680353ccf56
3,637,123
def simulate(robot, task, opt_seed, thread_count, episode_count=1): """Run trajectory optimization for the robot on the given task, and return the resulting input sequence and result.""" robot_init_pos, has_self_collision = presimulate(robot) if has_self_collision: return None, None ...
13c069282636e7b4215654d958621ed418bc40a8
3,637,124
import time def config_worker(): """ Enable worker functionality for AIO system. :return: True if worker-config-complete is executed """ if utils.get_system_type() == si_const.TIS_AIO_BUILD: console_log("Applying worker manifests for {}. " "Node will reboot on completio...
4ab82a2988a70ec9fe2f2ab6aa45099b7237b07a
3,637,125
def convert_dict_to_df(dict_data: dict): """ This method is used to convert dictionary data to pandas data frame :param dict_data: :return: """ # create df using dict dict_data_df = pd.DataFrame.from_dict([dict_data]) # return the converted df return dict_data_df
550e33b0b3bacbdfb3abeb8019296be2c647000e
3,637,126
def sec2msec(sec): """Convert `sec` to milliseconds.""" return int(sec * 1000)
f1b3c0bf60ab56615ed93f295e7716e56c6a1117
3,637,127
import aiohttp async def _request(session:aiohttp.ClientSession, url:str, headers:dict[str,str]) -> str: """ 获取单一url的愿望单页面 """ async with session.get(url=url, headers=headers, proxy=PROXY) as resp: try: text = await resp.text() except Exception as err: text = ""...
f891736d4598adc0005c096e12ab43d41544ab36
3,637,128
def get_pretrained_i2v(name, model_dir=MODEL_DIR): """ Parameters ---------- name model_dir Returns ------- i2v model: I2V """ if name not in MODELS: raise KeyError( "Unknown model name %s, use one of the provided models: %s" % (name, ", ".join(MODELS.keys(...
75657f039763ae73219eae900061a426ed2b11fd
3,637,129
def object_get_HostChilds(obj): """Return List of Objects that have set Host(s) to this object.""" # source: # FreeCAD/src/Mod/Arch/ArchComponent.py # https://github.com/FreeCAD/FreeCAD/blob/master/src/Mod/Arch/ArchComponent.py#L1109 # def getHosts(self,obj) hosts = [] for link in obj.InLis...
dccba2ef151207ebaa42728ee1395e1b0ec48e7d
3,637,130
import torch def collate_fn(batch): """ Collate function for combining Hdf5Dataset returns :param batch: list List of items in a batch :return: tuple Tuple of items to return """ # batch is a list of items numEntries = []; allTensors = []; allLabels = []; for...
b49ec88b4de844787d24140f5ef99ad9a573c6e3
3,637,131
def test_psf_estimation(psf_data, true_psf_file, kernel=None, metric='mean'): """Test PSF Estimation This method tests the quality of the estimated PSFs Parameters ---------- psf_data : np.ndarray Estimated PSFs, 3D array true_psf_file : str True PSFs file name kernel : int...
10feef6a483cfa6345561dcf5d1717a466a78c7d
3,637,132
def EulerBack(V_m0,n_0,m_0,h_0,T,opcion,t1,t2,t3,t4,I1,I2,h_res=0.01): """ :param V_m0: Potencial de membrana inicial :param n_0: Probabilidad inicial de n :param m_0: Probabilidad inicial de m :param h_0: Probabilidad inicial de h :param T: Temperatura indicada por el usuario :param opcion:...
33660894f80d3060206da3ddbb96d40b8453fc72
3,637,133
def wiggle(shape, scope, offset, seed=0): """Shift points/contours/paths by a random amount.""" if shape is None: return None functions = { "points": wiggle_points, "contours": wiggle_contours, "paths": wiggle_paths} fn = functions.get(scope) if fn is None: retu...
0cd587646013810ca512de5d327c2fdc24b110f5
3,637,134
def parseAndDisplay(line, indentLevel): """Indents lines.""" if line.startswith("starting "): printArgumentLine(indentLevel, line) indentLevel += 1 elif line.startswith("ending "): indentLevel -= 1 printArgumentLine(indentLevel, line) else: printLine(indentLevel, ...
14c9ebe27140aa77f5f7980e1da2bec30e7ccf8b
3,637,135
def insert_question(question): """ Insert a particular question @param: question - JSON object containing question data to be inserted """ return db.questions.insert_one(question)
f4d22a137a1e7d9fbe43a1e03414d551cceb27c9
3,637,136
def sequence_vectorize(train_texts, val_texts): """Vectorizes texts as sequence vectors. 1 text = 1 sequence vector with fixed length. # Arguments train_texts: list, training text strings. val_texts: list, validation text strings. # Returns x_train, x_val, word_index: vectoriz...
f32c40ca2f8bc6d2c78f8093ccf94fee192b87c8
3,637,137
def parse_preferences(file, preferences): """Parse preferences to the dictionary.""" for line in open(file, "r").readlines(): # all lower case line = line.lower() # ignore comment lines if line[0] == "!" or line[0] == "#" or not line.split(): continue key ...
09c0251cd34cfbb6c9342eccd697a08259c744c6
3,637,138
def func_hex2str(*args): """字符串 -> Hex""" return func_hex2byte(*args).decode('utf-8')
732f333cd942ecd8bee4ac4b974f0301e0c69baf
3,637,139
import collections def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() with open(vocab_file, "r", encoding="utf-8") as reader: tokens = reader.readlines() for index, token in enumerate(tokens): token = token.rstrip("\n") vocab[token] = ind...
801833664a67e5d6e62dfb5379cabeb1b1b5058c
3,637,141
from typing import List def triage(routes: List[Route]) -> Route: """ This function will be used to determine which route to use """ eva = {} for i, route in enumerate(routes): stored_route: StoredRoute = route.pop("stored_route") reg_path = stored_route["path"] segments = ...
625b143c3284526b71d21a7c0113e892df92ed3a
3,637,142
def upsert_object(data, cursor=None): """ Upsert an object in the repository. """ cursor = check_cursor(cursor) data = _set_object_defaults(data, cursor) cursor.execute(''' INSERT INTO objects (pid_id, namespace, state, owner, label, versioned, log, created,...
de0de4a48bf4f1d846938e174bb5a5300dd49083
3,637,143
import torch def sparsity_line(M,tol=1.0e-3,device='cpu'): """Get the line sparsity(%) of M Attributes: M: Tensor - the matrix. tol: Scalar,optional - the threshold to select zeros. device: device, cpu or gpu Returns: spacity: Scalar (%)- the spacity of the matr...
b8675a768c8686571d1f7709d89e3abeb5b56a80
3,637,144
def geospace(lat0, lon0, length, dx, strike): """ returns a series of points in geographic coordinates""" pts_a = [] npts = length // dx + 1 for idx in range(npts): # convert to lat, lon new = convert_local_idx_to_geo(idx, lat0, lon0, length, dx, strike) pts_a.append(new) ret...
78a380b59768cf83eca8edba5f1e21a0b6b61636
3,637,145
def linearOutcomePrediction(zs, params_pred, scope=None): """ English: Model for predictions outcomes from latent representations Z, zs = batch of z-vectors (encoder-states, matrix) Japanese: このモデルにおける、潜在表現Zから得られる出力の予測です。 zs = ベクトル z のバッチ(袋)です。 (encoder の状態であり、行列です) (恐らく、[z_0, z_1, z_2, ...
3e92fe0c0d16d8565066216c1da96b6fdbeb8dc9
3,637,146
from datetime import datetime import collections def _check_flag_value(flag_value): """ Search for a given flag in a given blockette for the current record. This is a utility function for set_flags_in_fixed_headers and is not designed to be called by someone else. This function checks for valid ...
2e4da676ad7abf95aa157aaca5aae80975b893e2
3,637,147
def logout(): """ Logout a user """ session.pop('user_id', None) session.pop('player_id', None) return redirect(url_for('index'))
d7d375e28a3e432c42b845cccf0adecb37cf46e1
3,637,148
def get_available_gpus(): """Returns a list of available GPU devices names. """ local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == "GPU"]
9c62204fa1bdc8ad22fd56ecad14bde895a08ec6
3,637,149