content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def block2dict(block: list, kind: str = None, sequence: int = -1) -> dict: """Takes a text block from a SerialEM .nav file and converts it into a dictionary.""" patt_split = re.compile(r'\s?=\s?') d = {} for item in block: key, value = re.split(patt_split, item) try: ...
7169d95d88e6e68d7f5716a5d50b629030ae8783
43,528
def plurality(l): """ Take the most common label from all labels with the same rev_id. """ s = l.groupby(l.index).apply(lambda x:x.value_counts().index[0]) s.name = 'y' return s
4e363648e79b5e9049aca2de56fd343c1efe1b93
43,529
import uuid def trace_using(logger): """Decorator factory to trace callables. Args: logger: The logger to use for tracing Returns: The decorator, which takes a function and decorates it. """ def real_decorator(func): """Decorate a callable to report args, kwargs and ret...
51b6dacfd36b52dde7a3bdf3b3c939b51adb2eb2
43,530
def lowpass_filter(data: FLOATS_TYPE, sampling_freq_hz: float, cutoff_freq_hz: float, numtaps: int) -> FLOATS_TYPE: """ Apply a low-pass filter to the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :mat...
4bb15468e3a26d15c0184c1094e07b3675aa321c
43,531
def uncollect_if_test_explainer(**kwargs): """ This function is used to skip combinations of explainers and classifiers that do not make sense. This is achieved by using the hooks in conftest.py. Such functions should be passed to the @pytest.mark.uncollect_if decorator as the func argument. The...
cca68a9ff3656fcfa0181c84554f920b5beee0fc
43,532
def electric_field(relative_permittivity, relative_permeability, frequency, current, length, r, theta): """ Calculate the electric far field for the Hertzian dipole. :param relative_permittivity: The relative permittivity. :param relative_permeability: The relative permeability. :param frequency: Th...
9e154f9c7110027b1e67f991b59d04df259d7c46
43,534
def get_messages_per_week(msgs): """Gets lists of messages for each calendar week between the first and the last message. Args: msgs (list of Mymessage objects): Messages. Returns: A dictionary such as: { week (datetime.date): list of messages within this week ...
43ade76498c38d9977e6baddd8c651abc03e6ee7
43,535
def _handle_text_outputs(snippet: dict, results: str) -> dict: """ Parse the results string as a text blob into a single variable. - name: system_info path: /api/?type=op&cmd=<show><system><info></info></system></show>&key={{ api_key }} output_type: text outputs: - name: system_in...
693a3e5cba6d72d09b2adb3745abb4fcf07f92d3
43,536
def make_uuid(): """generate uuids even on Python 2.4 which has no 'uuid'""" return _uuids.pop(0)
596702b0eed0c6f7563e25c0fd6f33756d8811ae
43,538
from datetime import datetime def _to_iso_format(traintime: datetime) -> str: """Return isoformatted utc time.""" return dt.as_utc(traintime).isoformat()
04b0c7f8695bcec1de3a759d46f54a4b3a890a4c
43,539
from datetime import datetime def parse_timestamp(datetime_repr: str) -> datetime: """Construct a datetime object from a string.""" return datetime.strptime(datetime_repr, '%b %d %Y %I:%M%p')
ddacf877c55466354559f751eac633b5bcd7313c
43,540
def proxy_request(request, **kwargs): """ generic view to proxy a request. Args: destination: string, the proxied url prefix: string, the prrefix behind we proxy the path headers: dict, custom HTTP headers no_redirect: boolean, False by default, do not redirect to "/" ...
539e1bd2e70e49435ec6272888193943076d0129
43,541
def image_stabilisation_proj( image: xpArray, axis: int = 0, projection_type: str = "max-min", **kwargs ) -> SequenceRegistrationModel: """ Computes a sequence stabilisation model for an image sequence indexed along a specified axis. Instead of running a full nD registration, this uses projections inste...
86e04bdcb529bbe3abbec42b4334b280f6404f4f
43,542
def get_LOR_colors(LOR_list, min_max=(-2, 2)): """Use Log Odds Ratios list to create color map for allele columns """ cmap = cm.coolwarm if min_max!=False: norm = Normalize(vmin=min_max[0], vmax=min_max[1]) else: bnd_Val = max(abs(min(LOR_list)), abs(max(LOR_list))) print("mi...
6b6f6c35bf38ce70a5f9a1f17600a332d99d0459
43,543
from typing import Tuple def _shard(split: Split, shard_index: int, num_shards: int) -> Tuple[int, int]: """Returns [start, end) for the given shard index.""" assert shard_index < num_shards arange = np.arange(split.num_examples) shard_range = np.array_split(arange, num_shards)[shard_index] start,...
ffb6410e0e806f3a91e7959e047bdc93f51d8ce9
43,544
def refractive_index(h_gp): """average atmospheric refractive index""" delta = 2.93e-4 rho = atmosphere(h_gp) n = 1. + delta * (rho / RHO0) return n
75dd302a50ff56abc9a93f3a815435b681b564c3
43,545
import random def randvec(n): """ Given the number of vertices n returns a random 2^n x 1 basis vector Parameters ---------- n : integer Number of bits in string which represents the number of verticies in graph. Returns ------- v : ndarray A random 2...
2c97e7907bd6972bb791a60142f95e26001d960b
43,546
def assemble_result_str(ref_snp, alt_snp, flanking_5, flanking_3): """ (str, str, str, str) -> str ref_snp : str DESCRIPTION: 1 character (A, T, G or C), the reference SNP. alt_snp : str DESCRIPTION: 1 character (A, T, G or C), the variant SNP. flanking_5 : str DESCRIPTI...
bc0b43464124d0d19f4bfc5646730a1f951a5ced
43,547
def encrypt_blob(raw_data, public_key) -> bytes: """Return RSA + AES encrypted byte data from raw data input. :ivar raw_data: Bytes rsa + aes data. :raw_data raw_data: bytes :ivar public_key: urlsafe base64encoded rsa public key string value. :public_key public_key: string""" decrypted_bytes = b...
f9a1f592014cb02b0d11c39d665ab1cba1dea490
43,548
import requests def get_api_data(session, url, date_time): """Get the JSON-formatted response from the AMM API for the desired date-time. """ session = session or requests.Session() return session.get(url, params={"dt": date_time.format("DD/MM/YYYY")}).json()
ff44be4a958c4f05cc5bd562854059c552f693e1
43,549
def validate_cnpj(doc): """Basic function to validate the CNPJ number for serializer field Args: doc (str): The CNPJ number, accepts with or without characters Raises: ValidationError: CNPJ inválido! Returns: doc: The CNPJ number """ if not cnpj(doc): raise Val...
e1cc1b4c0287efb02c80fccb2ae3c9dc15d1b5ea
43,551
def make_trefoil(size=100, noise=0.0, a=2, b=2, c=3, **kwargs): """Generate synthetic trefoil dataset. Params ----- :size = int (default = 1000) - the number of data points to use """ # generate trefoil phi = np.linspace(0, 2*np.pi, size) x = np.sin(phi) + a*np.sin(a*phi) y = n...
ed75bde74997dd29d599d1cffe3900f882c33f90
43,552
def _makeOperator(operatorInput, expectedShape): """Takes a dense numpy array or a sparse matrix or a function and makes an operator performing matrix * blockvector products. Examples -------- >>> A = _makeOperator( arrayA, (n, n) ) >>> vectorB = A( vectorX ) """ if operatorInput i...
df6246eabfae83b11c77570ffc091dac9166f447
43,553
def search(state, goal_state): """Iterative deepening depth-first""" depth = 0 def dls(node): if node.is_goal(goal_state): return node if node.depth < depth: node.expand() for child in node.children: result = dls(child) if ...
f29c8d2abeb3f4f98bb2b37da880ed815c94aead
43,554
from rasterio._io import window_union def union(*windows): """Union windows and return the outermost extent they cover. Parameters ---------- windows: list-like of window objects ((row_start, row_stop), (col_start, col_stop)) Returns ------- ((row_start, row_stop), (col_start, co...
5a0b331e9b6eb923c553e6e4aef3cf590b9d0792
43,555
from typing import Mapping def create_remote_executor( channel: GRPCChannel, cardinalities: Mapping[placements.PlacementLiteral, int], ) -> _executor_bindings.Executor: """Constructs a RemoteExecutor proxying service on `channel`.""" uri_cardinalities = data_conversions.convert_cardinalities_dict_to_strin...
264d2a02547fb1bae7e7b35a5d3136a03f3488df
43,556
def complex_abs(data): """ Compute the absolute value of a complex valued stacked input array. Args: data (numpy.array): A complex valued array with real and imaginary parts stacked,where the size of the final dimension should be 2. Returns: numpy.array: Absolute value of data """ ...
70d4a9691e6a4697dec4a3a6778bb4bd2ae7f50d
43,557
def _build_batch_norm_params(batch_norm, is_training): """Build a dictionary of batch_norm params from config. Args: batch_norm: hyperparams_pb2.ConvHyperparams.batch_norm proto. is_training: Whether the models is in training mode. Returns: A dictionary containing batch_norm parameters. """ batc...
892cf0891c5738e89f98f95c900d2e70dc99974d
43,558
def search_abstracts(search_terms, reldate): """ :arg list search_terms: :arg int reldate: :returns object: """ query = '"{}"'.format('" OR "'.join(search_terms)) return Entrez.read(Entrez.esearch( db='pubmed', term=query, reldate=reldate, datetype='pdat', usehistory='y'))
5a4b47ba6c0f51a91fae218168ca5e9edf04d566
43,560
def tokenize(string: str) -> [str]: """Tokenize a string. :param string: [description] :type string: str """ return string.split(" ")
dfc2d11e0445a6b2f867660f101e7ade7823d8ed
43,561
from datetime import datetime import html import requests def get_liste_match(nb_jour): """ Fonction permettant de chercher les matchs qui vont avoir lieu entre aujourd'hui et un horizon en paramètre. :param nb_jour: Le nombre de jour à parcourir :return: Un dictionnaire contenant pour chaque date la ...
57f754484e3bed11f9e4abe3fa2b220a481911f2
43,562
def setBvar(value): """If `value` is a dict returns a generic_json object, otherwise it returns the value - - - - - **Args**: - `value` (any type): value to assing **Returns** - `generic_json` if value is a dict, otherwise it returns the value """ if type(value) == dict: retur...
c9832f81f8d9fc2ab4fc1b3f1cfb5a698b6181a4
43,563
def convex_attributes(variables): """Returns a list of the (constraint-generating) convex attributes present among the variables. """ return attributes_present(variables, CONVEX_ATTRIBUTES)
d46605e5a5240271cbfb94732182c387f166a4c6
43,564
def LMStep4InitializePyBrainNetworkForLearning(fNetwork): """ This function realize Learning mode step: 4. Initialize empty PyBrain network for learning or reading network configuration from file. fNetwork is a PyBrain format neural network, created at 1st step. Function returns True if all operatio...
7d5721447e63bbf2d3982c4ed36e86604006b3e5
43,565
def is_installed(service): """Check whether the Snips service `service` is installed. Args: service (str): The Snips service to check. Returns: bool: True if the service is installed; False otherwise. Example: >>> is_installed('snips-nlu') True .. versionadded:: ...
d892d12095a458fd90f7822d86bfad57f2c3bba8
43,566
def trunc(s, length): """Truncate a string to a given length. The string is truncated by cutting off the last (length-4) characters and replacing them with ' ...' """ if s and len(s) > length: return s[:length - 4] + ' ...' return s or ''
ea6d1702d709ac7d94cc2bcb2e945da71009c0fe
43,567
def user_preference_form_builder(instance, preferences=[], **kwargs): """ A shortcut :py:func:`preference_form_builder(UserPreferenceForm, preferences, **kwargs)` :param user: a :py:class:`django.contrib.auth.models.User` instance """ return preference_form_builder( UserPreferenceForm, ...
a53b3e0f6bfef2b7ad80c522786223a7a9e52c50
43,568
def get_parser(subparsers, parent=None): """ "Define and return a subparser for the tune subcommand.""" parser = subparsers.add_parser( "tune", description="Tune model using the ML on MCU flow.", parents=[parent] if parent else [], add_help=(parent is None), ) parser.set_...
cc351315ab5852d3cbad00cc3784f260018c8a6a
43,569
from re import M def find_prime(bits: int) -> int: """Returns a prime number with the specified amount of bits.""" p = random_odd(bits) while True: # if p is not coprime with M then it isn't prime. if gcd(p, M) != 1: p += 2 continue if miller_rabin(p, 10): ...
7a10c8346986dc037bde486ef61b4f056170c84d
43,570
import operator def sort_values(values: list[tuple]) -> list[tuple]: """Returns a list of tuples sorted by x value (the value at index 0 of the inner tuple.""" return sorted(values, key=operator.itemgetter(0))
f172f68418988d4e01dcc406de8ec467abfe7aa8
43,571
def calc_rank(age, is_veteran=False, has_disability=False): """ Calculate a participant's rank. A higher number is higher ranked (top of the list). (i.e., Reverse this when sorting.) Change this function to change the ranking algorithm. The code in the comments below is a ranking system based ...
2c3ab7446ac12e634ffe47b0e57e2232908b12b9
43,572
def say(text: str) -> str: """Return an ASCII art skeleton with a speech bubble Args: text: What to put in the speech bubble >>> print(say("Hello")[1:28]) ------- ( Hello ) ------- """ template = Template(template_path.read_text()) return template.render(text=text)
42222ac2a54c7d15da9366327937b0f24a0e6cb6
43,573
def jwtauth(handler_class): """ Class decorator to check for authorization """ # pylint: disable=W0613 def wrap_execute(handler_execute): def require_auth(handler, kwargs): auth = handler.request.headers.get('Authorization') token_validation_res = validate_toke...
3b66460a4d41883beb9efe32b86a66f9f8c79726
43,575
def js_prerelease(command): """decorator for building minified js/css prior to another command""" class DecoratedCommand(command): def run(self): print('inner runnn.....') try: self.distribution.run_command('jsdeps') except Exception as e: ...
5856d5765383415f2c994bf0d10b921b38f23f98
43,576
from typing import Sequence def is_sequence(obj): """Check if `obj` is a sequence, but not a string or bytes.""" return isinstance(obj, Sequence) and not BinaryClass.is_valid_type(obj)
ec25a6bc25c1feeacb460ea14d788369b718c0f4
43,577
def is_user_stasised(nick): """Checks if a user is in stasis. Returns a tuple of two items. First parameter is True or False, and tells if the user is in stasis. If the first parameter is False, the second will always be None. If the first parameter is True, the second is an integer of the amount o...
f61f4bf5554a046724d1c5cc0eedcd9323b3d46c
43,579
def expose(class_method): """ Decorator which exposes given method into interface :param class_method: method to expose :return: given method with modifications """ class_method.is_exposed = True return class_method
ee234bd7535f29c39fc80643997b89aeb3c0f533
43,580
def merge_length_list(lists): """ Merge the list that demonstrates the word length """ res_list = [] for l in lists: if len(res_list) < len(l): res_list[len(res_list):] = [0] * (len(l)-len(res_list)) for length, num in enumerate(l): res_list[length] += num ...
564742fd7e0a7f3a0a8535a1f02c343d193a69ac
43,581
def func(pseudo_state, a1, a2, b1, b2, c1, c2, d1, d2): """ quadratic fit function for the Bellman value at given pseudo-state :param pseudo_state: list(float) - list of the four state variables for a given state :param a1, a2, ... d2: float - parameters of the quadratic fit function """ sum = a1*pseudo_state[0...
6478219704999dc4cfcbc915126d919e15fe3043
43,582
async def fav_(request:Request,user_id:int=None,authorization: str = Header(None),info : dict=Depends(is_valid_token),insert:str=None,delete:str=None,toggle:str=None): """gallerys endpoint""" token_user_id=int(info['id']) token_user_secret=info["secret"] username=None if user_id: resp=await ...
0d308b266cf1bdff6f1e716ab187adaf9906984f
43,583
def intersection(box1, box2): """ Args: box1: bounding box box2: bounding box Returns: float: the area that intersects the two boxes """ y_min1, x_min1, y_max1, x_max1 = box1 y_min2, x_min2, y_max2, x_max2 = box2 min_ymax = min(y_max1, y_max2) max_ymin = max(y_mi...
71746d93ead54aa5b36e7e6a5eb40e757711bef5
43,584
import json def make_json_buffer(json_obj): """Returns a file-like object containing json_obj serialized to JSON >>> f = make_json_buffer([1, 2, 3, True, {u'distance': 4.5}]) >>> f.read() '[1, 2, 3, true, {"distance": 4.5}]' """ return make_string_buffer(json.dumps(json_obj))
41d1306722583a302a440cfb5d79e923c5e04615
43,585
import re def remove_emoji(string): """ Remove emoticons from a text string and return a cleaned string """ emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs ...
436b71c2a9c36621b659630d5eb3b141800025bb
43,586
def delete_project(): """ 删除项目 :return: """ data = request.get_json() project_id = data["project_id"] project = Project.objects.filter(id=project_id).first_or_404() project.delete() devices = Device.objects.filter(project_id=project_id).get_or_404() for device in devices: ...
41fc3a09f65518e6bc63b6c95e52c01550bb9c52
43,587
def verify_proof(request: VerifyProofRequest) -> bool: """Verifies the proof Args: request: Request for the proof verification operation Return: True if verification was successful, False if not """ handle = bbs_verify_proof.bbs_verify_proof_context_init() bbs_verify_proof.bbs_v...
a8fa27924df8004e0ba86294e9d402fadbaf08bf
43,588
def _wrapAngle360(lon): """wrap angle to [0, 360[.""" lon = np.array(lon) return np.mod(lon, 360)
501a0004f7162369acea5db145e079f5de86275a
43,589
async def purge_all(ctx, amount, *args, **kwargs): """ Removes messages in given channel Args: ctx: amount: *args: **kwargs: Returns: """ channel = ctx.channel num = int(amount) + 1 # call is additional if num >= 1: def check_true(m): ...
bfb806b37ce5400ed08c5d8ea3693761bdb21e9a
43,590
def extended_5_3_predict(t, power_anaerobic_alactic, power_anaerobic_decay, cp, tau_delay, cp_delay, cp_decay, cp_decay_delay, tau): """ Credits to Damien Grauser. Source: https://github.com/GoldenCheetah/GoldenCheetah/blob/master/src/Metrics/ExtendedCriticalPower.cpp """ model ...
0b73eb9c4bde57cef9612418b30792d3091d191a
43,591
def tuplesums(tuplelist): # type: (List[Tuple[int, int]]) -> Tuple[int, ...] """[(a, b), (c, d), (e, f)] -> [sum(a, c, e), sum(b, d, f)] """ return tuple(sum(x) for x in zip(*tuplelist))
7367bb63789218b4ce4beb4f164ebbba5daed14c
43,592
def remove_emoji(data: str) -> str: """Remove the emoji from the 'data' string.""" return demoji.replace(data)
270d280152d79eb8b9c98361e34aa48df9c20944
43,593
def get_header_value(header_list, key): # type: (List[Tuple[str, str]], str) -> List[str] """Filter the header_list with provided key value. This method is used to parse through the header list obtained from the SMAPI response header object and retrieve list of specific tuple objects with keys like...
8cdd0630b5539c6229135a53ec4eb1add35fd1be
43,596
def data_by_variable(datalines, variable): """ This function takes in a list of datalines and returns a new list of datalines for a specified variable. Parameters: ----------- datalines : list This is a list of datalines output by Temoa. variable : string This is the variabl...
93c87625c9fce159424819a3fcfedeaa0fffd8b1
43,597
import torch def compute_gradient_penalty(D, real_samples, fake_samples, opt): """Calculates the gradient penalty loss for WGAN GP""" # Random weight term for interpolation between real and fake samples alpha = torch.tensor(np.random.random((real_samples.size(0), 1, 1, 1))).float() if opt.cuda: ...
3996eaf7c2600be1b8184e39d4c5108ac4deccb3
43,598
import glob def remove_skipped_echo_direct_transfer(df, fn): """Remove wells that were reported as skipped in the Echo protocol (xml). This functions works with Echo direct transfer protocols. Function supports using wildcards in the filename, the first file will be used. Returns a new dataframe witho...
a8ef266ad859fe1118c21f5d46925d86314b60e8
43,599
def log_access(request, location=None, reason=None): """ Checkin form used by LNL members when accessing a storage location (contact tracing) :param location: The name of the location (must match a location that contains equipment) :param reason: Should be set to "OUT" if user is checking out of a loca...
401b08bd1bd736551aac33dc5855e250e88d4944
43,600
import array import logging def oep(atoms,orbs,energy_func,grad_func=None,**kwargs): """oep - Form the optimized effective potential for a given energy expression oep(atoms,orbs,energy_func,grad_func=None,**kwargs) atoms A Molecule object containing a list of the atoms orbs A matrix of ...
a6036f391aa0b3435550abcfcf69d70044477267
43,602
from jeepney.bindgen import code_from_xml # type: ignore[import] from typing import Generator def generate(conn: znc.Socket, save_path: str) -> Generator[None, None, str]: """Dump latest Signal interface description to file. See ``jeepney.bindgen.generate``. """ message = yield from send_dbus_messa...
863037b02f8133972d8238e0099b4d9eaa4baa48
43,603
import copy import torch def deepfool(image, net, device, num_classes=10, overshoot=0.02, max_iter=50): """ :param image: 输入图像:1x1x28x28 :param net: network :device: cuda or cpu :param num_classes: num_classes (limits the number of classes to test against, by default = 10) :par...
db92768fda05fe8e37856082e4e353bc7184b304
43,604
def preprocess_cost_reward(data, ind_trace, steps_per_epoch, window=1): """Preprocess the given cost and the given reward and return the mean, mean+std and mean-std values as metrics. This function requires data from a single trace (execution). EVolution with respect to the number of epochs. """ ...
a89d477900e9dd1ff858baaff30c7d93b71edc22
43,605
def is_valid_url(string: str) -> bool: """Returns boolean describing if the provided string is a url""" result = urlparse(string) return all((result.scheme, result.netloc))
a111a1ac4d4821d5baa00f3053f808f3ffdff5d6
43,606
def MLP( input_shape, output_size, loss, optimizer, hidden_layers=[32, 16, 8], dropout=0.0, activation="linear", out_activation="linear", ): """Multi Layer Perceptron. Args: input_shape (tuple): Shape of the input data output_size (int): Number of neurons of the ...
0db53ded4d0e7ac87f2ddb296bffdacec586c285
43,608
def _get_crm_resource_v1(credentials): """ Instantiates a Google Compute Resource Manager v1 resource object to call the Resource Manager API. See https://cloud.google.com/resource-manager/reference/rest/. :param credentials: The GoogleCredentials object :return: A CRM v1 resource object """ ...
adc1f2576404e67f95262711ab1089ca80ed5153
43,609
def line_intersection(lines, lines2, abs_tolerance = 1e-14, full_output = False): """ Generic Line to line intersection function :param lines: The first set of lines, with shape [n_lines, 2, 2] where lines[i, 0, :] is the first point of the ith line :type line: np.ndarray :param lines2: Th...
d68d07499da2bbd0e8532862abf1181fc86ab800
43,610
import re def get_tag_name(tag): """ Get the name field of a tag: {#x:name_field:t} Parameters ---------- tag: str Returns ------- name: str """ name = re.findall(NAME_REGEX, tag)[0] return name
976891bfe6e4a286f1b47f0a1fcd0cf061ac7101
43,611
from typing import Dict from typing import Callable def snap_array_registry( file_pointer: h5py.File, data_source: str, name_map: Dict[str, str] = None, ) -> Dict[str, Callable]: """Generate snap array registry. Parameters ---------- file_pointer The h5py file pointer to the snap file. ...
21bf78ebc33c9d213c49f360fa2f05a22a11bf7a
43,612
import inspect def get_storage(dictionary, index=None): """Get a unique storage point within a class method. Parameters ---------- dictionary : dict A dictionary used for storage. index : hashable An index under which to load the element. Needs to be hashable. This is usef...
199aa57fc9b04a0d4ec64b0357b31ec2877e2b03
43,613
def sample_hyperparameters(): """ Yield possible hyperparameter choices. """ return { "no_components": np.random.randint(5, 64), "learning_schedule": np.random.choice(["adagrad", "adadelta"]), "loss": np.random.choice(["bpr", "warp", "warp-kos"]), "learning_rate": np.ran...
89100422e66312450b8c0ab2232fdd69ea9efebe
43,614
def waypoint_sampling(X, n_waypoints=100): """ Min-max sampling of waypoints in a two dimensional embedding. :param X: :param n_waypoints: :return: """ # store waypoints and initiate distances wps = [] N = X.shape[0] dists = np.zeros((N, n_waypoints)) # random sampling of f...
a2fa30d90c94d6a9323b6f73ff0711315719267b
43,615
import threading def threadpool_waited_join(thread_object, timeout): """ Call threadpool.join() with timeout. If join completed return True, otherwise False Notice: This function creates another daemon thread and kills it, use with care. :param thread_object: Thread to join :param float timeout: ...
a1f143775684aecca85c02c26879e8ec546938a9
43,616
from typing import Union def get_relevant_terms( phi: Union[ndarray, DataFrame], topic: int, lambda_: float = 0.6) -> Series: """Select relevant terms. Parameters ---------- phi : Union[np.ndarray, DataFrame] Words vs topics matrix (phi). topic : int Topic ...
e7266c9258cd7b36b2ec976ab41bfece8b1d9a03
43,617
import posixpath import re def GetCudaToolkitVersion(vm): """Get the CUDA toolkit version on the vm, based on nvcc. Args: vm: the virtual machine to query Returns: A string containing the active CUDA toolkit version, None if nvcc could not be found Raises: NvccParseOutputError: On can not p...
e3f18651e4865b40012e53d6762b8297fab76295
43,618
def divided_by_sentences(abstract): """Divides abstracts by sentences :param abstract:load :return: list of sentences of the abstract """ nlp_l = English() nlp_l.add_pipe(nlp_l.create_pipe('sentencizer')) doc = nlp_l(abstract) sentences = [sent.string.strip() for sent in doc.sents] ...
360f21f0d4a5caa2c906b4691503a99a2f8a885b
43,619
def write_submission_pool(outputs, args, dataset, conf_thresh=0.1, horizontal_flip=False, max_workers=20): """ For accelerating filter image :param outputs: :param args: :param dataset: :param conf_thresh: :param horizontal_flip:...
2fbe04fef67bc52c49840ba176837a6f1ff22ff0
43,621
def transform_one(transformer, X=None, y=None): """Transform the data using one estimator.""" def prepare_df(out): """Convert to df and set correct column names and order.""" use_cols = inc or [c for c in X.columns if c not in exc] # Convert to pandas and assign proper column names ...
c2f7a177bc6a547419c38bfa0a8ca62dbe2f748c
43,622
def calculateHeaders(tokens: list, rawHeaders: tuple) -> tuple: """ Takes sanitised, tokenised URCL code and the rawHeaders. Calculates the new optimised header values, then returns them. """ BITS = rawHeaders[0] bitsOperator = rawHeaders[1] MINREG = 0 MINHEAP = rawHeaders[3] ...
472eeb4397d68e232b66517064f91e5688c33e3c
43,623
import toml import logging def from_file(): """try to load the configuration from file""" try: return toml.load(Config.get_path_to_conf()) except FileNotFoundError: logging.info(f"Configuration file '{Config.get_path_to_conf()}' not found.")
4a833987e563fdc52fabb861f84f89dbf889bf92
43,624
def synthetic_data(w, b, num_examples): """ y = Xw + b + noise """ X = tf.zeros((num_examples, w.shape[0])) X += tf.random.normal(shape=X.shape) y = tf.matmul(X, tf.reshape(w, (-1, 1))) + b y += tf.random.normal(shape=y.shape, stddev=0.01) y = tf.reshape(y, (-1, 1)) return X, y
e861c9af287108f1f08c491142093ad10bcd5a8f
43,625
def weg(m) -> str: """capture multiple "weg"s""" return m
2be9b16a4969d04f1322c22b07ffd98318fa05fb
43,626
from typing import Iterable def cossin(X, p=None, q=None, separate=False, swap_sign=False, compute_u=True, compute_vh=True): """ Compute the cosine-sine (CS) decomposition of an orthogonal/unitary matrix. X is an ``(m, m)`` orthogonal/unitary matrix, partitioned as the following where uppe...
2350d8b65a470346631d2d657f900c899c6b3bec
43,627
def getBlankBoard(): """Create a new, blank tic tac toe board.""" board = {} # The board is represented as a Python dictionary. for space in ALL_SPACES: board[space] = BLANK # All spaces start as blank. return board
1db53045128b6ae246d9be6ef52d443aa9d8e7a1
43,628
def isopycnal_arr(arrin,target_density,pd,interp=None): """ Returns the value of an input array along an isopycnal. """ if target_density < 100: target_density += 1000 if not interp: i0 = isopycnal_mask(target_density,pd) if len(arrin.shape) > 1: i1,i2 = np.indi...
51bdd3dbb5c410178bc2581bb14a0f48230c559f
43,629
def forecast(model, predict_data, seq_len=50, forward=10, stride=1): """Step through the out-of-sample data and make predictions. Args: model (keras.Model): Trained model. predict_data (numpy.array): Out-of-sample data. seq_len (int): Sequence length. forward (int): Forward. stride (int): Step size. Retu...
d1e520f2008d0ef74b17c1c91f5e8d8bdba26bbf
43,630
def _run_on_failure_decorator(method, *args, **kwargs): """ A decorator to run when the tests fail :param method: the method to run :param args: the tuple arguments to pass to the method :param kwargs: the dict arguments to pass to the method :return: runs the method on failure, raises exception...
fbc6a273da852eeecb269dd89b851b6965b48a9a
43,631
def get_xy_arrs(m_size, ant_rad): """Finds the x/y position of each pixel in the image-space Returns arrays that contain the x-distances and y-distances of every pixel in the model. Parameters ---------- m_size : int The number of pixels along one dimension of the model ant_rad : f...
6ce7b6aed1a4d1e3535ef57dfc2f5dac976b99f0
43,633
import json def build_data(known_languages): """Build primary objects edge_struct and nodes from graph_base.""" with (SRC_DATA / 'graph_base.json').open() as base_fh: primary_data = json.load(base_fh) edge_struct = {} for relation_type, edges in primary_data['edges'].items(): edge_str...
a3af7ae5aaf45e5a52d97f45a4fb126daee52439
43,635
def PrepareSipCollection(adornedRuleset): """ Takes adorned ruleset and returns an RDF dataset formed from the sips associated with each adorned rule as named graphs. Also returns a mapping from the head predicates of each rule to the rules that match it - for efficient retrieval later """ ...
dde70f55c559e01ca2c050a56b3903a2658958bc
43,636
def negate_q(a: ElementModQ) -> ElementModQ: """ Computes (Q - a) mod q. """ return ElementModQ(_Q_gmp - a.elem, make_formula("negate_q", a))
39d9e845adf52e41a6d4ff063aac0116be8e7c52
43,637
def candidate_synsets(lemma, pos): """ Used to restrict our attention only to synsets from the entire probability distribution over the output layer :param lemma: :param pos: :return: list(Candidate synsets) or lemma if nothing in Wordnet """ pos_dict = {"ADJ": wn.ADJ, "ADV": wn.ADV, "NOUN":...
f7f5f02765a0c93b499a706c4d1d30ea7bdb8632
43,638
from unittest.mock import patch def start_session(username="user", password="password", enterprise="enterprise", api_url="https://vsd:8443", version="3.2", api_prefix="api"): """ Log in and fetch api key """ session = NURESTTestSession(username=username, password=password, enterprise=enterprise, api_url=api_...
b82a0ea396084e9fdbc11c93926f08b77ed6d2b3
43,639
def nodes_or_number(which_args): """PORTED FROM NETWORKX Decorator to allow number of nodes or container of nodes. Parameters ---------- which_args : int or sequence of ints Location of the node arguments in args. Even if the argument is a named positional argument (with a default va...
3166c80d6bd5c2faaee16d70b919eda412f4d33a
43,640