content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def get_breadcrumbs(query, path): """ Get breadcrumbs. """ breadcrumbs = [] dir_query = "" if path: for item in path.split(os.sep): dir_query = os.path.join(dir_query,item) breadcrumbs.append([item,dir_query]) return breadcrumbs
b6cac2a6939067733a454ef56ec1d46a41ed6a65
671,826
def students_by_errors(assignment) -> dict: """ Takes an assignment object and creates a sorted list of students ranked by how few to how many errors they made based on the # of calls. """ students = {} for problem in assignment.problems.all(): for error in problem.error...
71024db9e14828a60133176e121e8046cfb23b27
671,827
from pathlib import Path from typing import Iterable def glob_files(dir_: Path, file_patterns: Iterable[str]) -> set[Path]: """Search a directory looking for file patterns.""" for pattern in file_patterns: found_files = list(dir_.glob(pattern)) if found_files: return set(found_file...
141c5618bca2093456239ccb38528a62485eb9af
671,828
from pathlib import Path from typing import Dict def ploidy_file_to_dict(ploidy_file: Path) -> Dict[str, int]: """ Generates a dictionary from a ploidy tsv file :param ploidy_file: :return: A dictionary of contigs and their ploidy """ ploidy_dict = dict() with ploidy_file.open("r") as file...
94af8c95438dc4c0612b7cf6135f09298609d7d4
671,829
from numpy import array def geoSeqsBoundingBox(segs): """ return corners (LB+TR) of smallest box containing all segments in segs """ yMin = 1e100 yMax =-1e100 xMin = 1e100 xMax =-1e100 for s in segs: (y0,x0),(y1,x1) = s yMax = max(yMax, y0) yMin = min(yMin, y0)...
ae3e0a11965116cec69ef0ad4e2a9f3b4d73ba7b
671,830
def cube_contains_coords(cube, *coords): """Check whether the given cube contains all the requested coordinates.""" for coord in coords: if not cube.coords(coord): return False return True
6b7d0f40c2c7d941149334f0496aa23a3ff5645f
671,831
import torch def arimean(iterable): """Calculate arithmetic mean of a given iterable. :param iterable: a torch.Tensor with one dimension :return: the arithmetic mean of a given iterable """ return torch.mean(abs(iterable), -1)
ed2565ad401f2508214ef5bff7de23054dcb6c5f
671,832
def mock_addon_options(addon_info): """Mock add-on options.""" addon_info.return_value["options"] = {} return addon_info.return_value["options"]
7b59f676784d8e810b9faf21d3f403e099a52adc
671,833
from random import choice def generate_email(fullname: str): """ returns a string of a generated email for a user based on a passed full name :param fullname: :return: """ user_format = choice(['fi last', 'first li', 'first last']) if user_format == 'fi last': user = (fullnam...
0a6cecead2f4ced7836169e40fa8bc82802b5a1b
671,834
def find_argmax(topics_list): """ returns the maximum probability topic id in a [(topic_id, topic_prob)...] topics distribution """ m = -1. r_tid = -1 for tid, tprob in topics_list: if tprob > m: m = tprob r_tid = tid return r_tid
9f00f79004c9e3aac48dd14c03f9f418e2dc4e02
671,835
from typing import List import re def extract_resolution(stderr: bytes, sep: str = "x") -> List[str]: """ Extract resolution from dwebp or djxl :param stderr: Console output :param sep: Separator string - e.g.: 1920x1080, sep="x" :return: """ res: str = re.findall(rf"\d+{sep}\d+", str(stderr...
1d3af37122734bbb8ba84937af027a1246b27696
671,836
import sys def convertString(path): """convert path between WINDOWS and LINUX""" if ("win" in sys.platform): return path.replace("/","\\") elif ("linux" in sys.platform): return path.replace("\\","/")
21604e848c4911ab998796963ffae445b731b054
671,837
def _gtn_get_all_leaves(self): """ Get all the leaves under this node """ if '_children' not in self.__dict__: return [self] l = [] for n in self.children: l.extend(n.get_all_leaves()) return l
1327c9ff51d4ccde0f71c004f3c075b551c08ea8
671,838
def get_unique_movienames(theater_chain): """ Given a 'cadena' data structure, returns a set of (unique) movie names. """ data = set() # We just need unique movie names, in no particular order for theater in theater_chain.theaters: for movie in theater.movies: # print '-- %s'% movie.name data.add(mov...
b49121a96c91eb2088a59808bcf6bb1246d22fe4
671,839
from bs4 import BeautifulSoup def html_fragment(source): """ Parse an HTML string representing a single element, and return that element """ return BeautifulSoup(source, 'html.parser').contents[0]
f41f349f82e376b7780a5d875aa0b7a98e13dd87
671,840
def declared_attr(m): """ Mark a class-level method as a factory of attribute. This is intended to be used as decorators on class-level methods of a :class:`~Model` class. When initializing the class as well as its subclasses, the decorated factory method will be called for each class, the retu...
52fb02192ab409914872ab9f9c41070e640cbdf6
671,841
def work_grid(grid, fig): """Take a two dimensional grid, add subplots to a figure for each cell and do layer work. Parameters: ----------- grid: a two dimensional grid of layers fig: matplotlib figure to draw on Returns: -------- axes: a two dimensional list of matplotlib axes """...
f1cf6dc59e75f7d50c9aff8651c12ba6e9f5bee5
671,842
def get_bookmarks_slug_for(instance): """Returns the slug for a bookmark menu valid for the given model instance. """ kls = instance.__class__ return "%s_%d_bookmarks" % (kls.__name__.lower(), instance.pk)
dd7838048db49d12aa3b6614a616137fdb875660
671,843
import os def num_directories(path): """ Takes a path and returns the number of directories at or below that path including the current directory """ count = 0 for root, directories, files in os.walk(path): count += 1 return count
6e711bf536f8c1497ac888ba09120ff7c4e6d586
671,844
def decode_utf8(raw): """ Returns a Unicode object on success, or None on failure """ try: return raw.decode('utf-8-sig', errors='replace') except BaseException: return None
42270ec7108a12206d8288d54062f8fd65e2707c
671,845
def count_bags(bags, bag): """Recursively count the bags of each type.""" if not bags.get(bag): return 1 else: counter = 0 for bag_a in bags[bag]: counter += count_bags(bags, bag_a) * bags[bag][bag_a] return counter + 1
85d0c6d58df7d177c01fef6ba35d0128aaa7c9ed
671,846
import re def _unshorten_amount(amount: str) -> int: """Given a shortened amount, return millisatoshis""" # BOLT #11: # The following `multiplier` letters are defined: # # * `m` (milli): multiply by 0.001 # * `u` (micro): multiply by 0.000001 # * `n` (nano): multiply by 0.000000001 # *...
84064add642cbdd323ab62fa2f1c1cb0ac48a2ee
671,847
def SetNumberKinetics(number): """ This function will set the number of scans (possibly accumulated scans) to be taken during a single acquisition sequence. This will only take effect if the acquisition mode is Kinetic Series.""" return None
bf3800d9299585bf1bf1f90c4ec2144df946ca5b
671,848
import logging import requests import json def calling_processing(json_obj: str, log: logging.Logger) -> bool: """This is something which works with/on REST api.""" try: header = {'api-key': ('epVgnissecorP2020yjbadsdsa05jdagdsah22a' 'll0ahm0duil0lah03333fo0r33eve0ryt0hin0g')} #...
ef5760a8f835ddb0781065ebe5e7807c559c880f
671,849
def onehot_from_logits(logits): """ Given batch of logits, return one-hot sample """ # get best (according to current policy) actions in one-hot form argmax_acs = (logits == logits.max(1, keepdim=True)[0]).float() return argmax_acs
a547290dda23b37cb91b8c47f9d496bad1a2987a
671,850
def get_taxon_id(page): """Get the taxon ID from the page.""" taxon_id = page.select_one('#carregaTaxonGrupoIdDadosListaBrasil') taxon_id = taxon_id['value'] return taxon_id
684f3fae4a9488f10a6720b48ef525d74da6cd97
671,851
import pwd import os def getuser(): """Get the username from the environment or password database. First try various environment variables, then the password database. This works on Windows as long as USERNAME is set. """ for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'): user = os....
9e2498ce864ea95531c05928bf66cdcbecb039a3
671,852
def get_saif_files(): """ Gets filenames for Saif's dataset. """ emotions = ['anger', 'fear', 'joy', 'sadness'] files = [f'data/{e}.tsv' for e in emotions] return files
5eec8aedd668feedf8b0a44061bc62c30b76343f
671,853
import functools def wraps(wrapped): """ a convenience function on top of functools.wraps: - adds the original function to the wrapped function as __wrapped__ attribute.""" def new_decorator(f): returned = functools.wraps(wrapped)(f) returned.__wrapped__ = wrapped return returned ...
9c5c4d78b167f70b2afcd99e699e0ea98ab8f8c2
671,854
def get_init_partition(nodes): """ Parameters ---------- nodes : arr_like. Vertices of the netlist's graph. Returns ------- list, list Nodes in partition 1 and 2. """ return list(nodes[:len(nodes)//2]), list(nodes[len(nodes)//2:])
d998cb3c3f4de02884825e6f7ada8a637eb4b754
671,855
def yen(value): """Format value as YEN.""" return f"¥{value:,}"
c4c0571b81c693da6268e4d0788fa484c2053148
671,856
def get_axd_content(fname, mode='r', encoding='UTF-16'): """returns a string of everything""" with open(fname, 'rb') as f: content = f.read() return content.decode('UTF-16')
ef7235f8ef96e9134476f2a2899f0b8c40d51b5d
671,857
def _tuple_or_list(this_identifier, typ): """ Turn all lists to tuple/list so this becomes hashable/dcc.storable """ opposite = tuple if typ == list else list out = [] for i in this_identifier: if isinstance(i, opposite): i = _tuple_or_list(i, typ) out.append(typ(...
3364120f93b71644d989f911f814a4542d59fa98
671,858
import torch def batch_lookup(M, idx, vector_output=True): """ Perform batch lookup on matrix M using indices idx. :param M: (Variable) [batch_size, seq_len] Each row of M is an independent population. :param idx: (Variable) [batch_size, sample_size] Each row of idx is a list of sample indices. :p...
6201d7e72cbbe8608675d13f0581f349f18c1665
671,859
def least_common(column): """ >>> least_common(["0", "0", "1"]) '1' >>> least_common(["1", "1", "0", "0", "1"]) '0' """ occurs = {} for bit in column: occurs[bit] = occurs.get(bit, 0) + 1 if occurs["0"] == occurs["1"]: return "0" return min(occurs, key=lambda v: o...
7f58ec3d505e0ab049d96c41e7596f54c81c2a75
671,860
def soft_capitalize(string: str): """Capitalizes string without affecting other chars""" return f"{string[0].upper()}{string[1:]}"
9cfadc1b5fb51e88625eaad2f64fe3812d226a10
671,861
def add_prefix(dic, prefix): """Adds a prefix to every key in given dictionary.""" return {f'{prefix}_{key}': value for key, value in dic.items()}
612bf97a3ced88e2e26d11b97f640ec14f38273c
671,862
from re import match def introspect_file(file_path, re_term): """ Takes a (str) file_path and (str) re_term in regex format Will introspect file_path for the existance of re_term and return True if found, False if not found """ try: ifile = open(file_path, "r") except: retu...
68db079119639afc3de2f7c84e35df044310c513
671,863
def human_format_number(number): """Reformat `number` by switching to engineering units and dropping to two fractional digits, 10s of megs for G-scale files. """ convert = [ (1e12, "T"), (1e9 , "G"), (1e6 , "M"), (1e3 , "K"), ] for limit, sym in convert: ...
a57882b98e68b367af571ead526e7ef10e4930ca
671,864
import os def find_executable(cmdname): """ Searches the path for a given cmdname. Returns an absolute filename if an executable with the given name exists in the path, or None if one does not. :param cmdname: The bare name of the executable to search for """ # Keep an eye out for the p...
24715acfbdeae7d3172760c52d805435c7a8e8b3
671,865
def url_developer_data(): """return URL for data in exojax Returns: URL for ExoJAX """ url=u"http://secondearths.sakura.ne.jp/exojax/data/" return url
ac33c332f49b940dabe559099b230d748597104f
671,866
def meImage(): """ Store my ascii image in a separat variabel as a raw string """ return r""" Θ ╞|╡ ╞|╡ Θ==[Φ]==Θ ||| ||| ||| ||| ||| ...
0681dce6edeba7388fe0369b158de39eda177baf
671,868
def should_send_email(config): """Only opt to send an email if the following are provided You must set these variables in your flask curren_app's config """ required_email_fields = [ "EMAIL_FROM_ADDRESS", # from "EMAIL_SUPPORT_ADDRESS", # to "EMAIL_NOTIFICATION_SUBMISSION", ...
c7a4527f7d0ed76e6f2f75b9f03238aac7a4cc82
671,869
import os def mtime(f): """ return time file was last modified, or 0 if it doesnt exist """ if os.path.isfile(f): return int(os.path.getmtime(f)) else: return 0
531ff2e51668450f097bc092179ec62900c83e04
671,870
from typing import Type from typing import List from typing import Tuple def get_required_class_field(class_type: Type) -> List[Tuple[str, Type]]: """Gets all the (valid) class fields which are mandatory. Args: class_type (Type): [description] Returns: List[Tuple[str, Type]]: [descriptio...
6ff5878238877b011b7366dbfa4e530547c01d2c
671,871
def qgen(x, qset): """ Helper function to slice a list of all residues of a protein of the list of the residues of all proteins """ start = False for i in range(len(qset)-1,0,-1): if not start and qset[i].protein_conformation.protein == x: start = i if start and qset[...
31ff3414efbd9fb2e2c0b49b64b7b9245b4f2991
671,872
def getHitmask(image): """returns a hitmask using an image's alpha.""" mask = [] for x in range(image.get_width()): mask.append([]) for y in range(image.get_height()): mask[x].append(bool(image.get_at((x, y))[3])) return mask
e60b2d3a59f71a83c965751f5eebe18d9b7d2715
671,873
import numpy def extinction_cross_section(surf_array, k, n, wavelength, electric_field): """ It computes the extinction cross section (Acording to Mischenko2007). Arguments --------- surf_array : array, contains the surface classes of each region on the surface. ...
64a05625febecfdec5d4483ec89277b185378429
671,874
def dtd_correction(params): """ When normalizing DTDs to 1 sometimes a correction factor is needed, caused by the uncertainty in the value of the integral of the DTD for the whole mass range """ if "dtd_correction_factor" in params: return params["dtd_correction_factor"] return 1.0
e3a0f587f0a354cdb661631248b89e34a82574b0
671,875
import re def IsJunk(contig): """returns true, if contigs is likely to be junk. This is done by name matching. Junk contigs contain either one of the following: random, unknown, chrU, chU. """ c = contig.lower() negative_list = "random", "unknown", "chru", "chu" for x in negative_l...
8c34dae8bfb235259d679018fb37e177435ddd34
671,876
def gateway(arg): """Return a regex that captures gateway name""" assert isinstance(arg, str) return r"(?P<%s>[\w_\-@\' \.]+)" % (arg,)
0f8dddac685b5396da25134b8ce08094f51b6945
671,877
import json import zlib def decompress(s): """Decompress with gzip, then load obj from JSON string""" return json.loads(zlib.decompress(s))
7fc69a5f9e408f58139582d53af0f2deb1fc34f1
671,878
def last_posted_user_name(ticket): """ Get the username of the last post created :param ticket: The requested ticket to get last post for :return: username of last post """ last_post = ticket.posts.all().order_by('created_at').last() return last_post.user.username
904f35f8923422f35c970a5efc452394a7deb12b
671,879
def get_node_connections(nodelist, network, depth=1): """ Gets quantity of connections of first or second grade. From the list of nodes in arg nodelist, finds the number of direct connections (if depth equals 1) or of second degree connections (if depth equals 2) in the node network in the arg network...
7437fb680f0f8316e7ac78a61705bb63b2d69b9b
671,880
def email_delete(imap, uid): """Flag an email for deletion. """ status, response = imap.store(str(uid), '+FLAGS', '\Deleted') return status, response
8d086d36722985b8631a6b6a70f5511357df65ef
671,881
def backup_policy_filename(name): """ Generate a .old file from a policy name or path """ return '{0}.old'.format(name)
9ea5df32be0d834726ad646ea5d696dda22fffb7
671,882
def countRun(s, c, maxRun, count): """parameter s: a string parameter c: what we're counting parameter maxRun: maximum length of run returns: the number of times that string occurs in a row""" """ trial: def countRunHelp(s,c,maxRun, count): if count == maxRun: return...
c0c71ef86055cd93294a3898bbd23c72df846b6a
671,883
from typing import Callable import importlib def _lookup_pdu_class(pdu_fn: str) -> Callable: """Utility to retrieve a PDU function from string representation because pytest can't parametrize class names.""" module = importlib.import_module('givenergy_modbus.pdu') return getattr(module, pdu_fn)
709485cc8a037aa8c88e0d34fe23401be54787aa
671,884
def _tensors_names_set(tensor_sequence): """Converts tensor sequence to a set of tensor references.""" # Tensor name stands as a proxy for the uniqueness of the tensors. # In TensorFlow 2.x one can use the `experimental_ref` method, but it is not # available in older TF versions. return {t.name for t in tenso...
3e4356b3779ffcb60559e396843aeae29420f1d3
671,886
def compute_loss_ref_gen(generation, reflection): """ Compute loss percentage based on a generation count and a reflection count. """ if generation != 0: loss = (1.0 - reflection / generation)*100 else: loss = (1.0 - reflection / (generation+0.1))*100 return loss if loss >=0 el...
8c3f7acc1d4b5d5a6892e53bb6fee6960d378356
671,887
def B3(cube_obj): """ 90 degree counterclockwise turn of the B face """ cb = cube_obj.get_cb() new_c = cb.copy() new_c[0] = cb[42] new_c[1] = cb[39] new_c[2] = cb[36] new_c[11] = cb[0] new_c[14] = cb[1] new_c[17] = cb[2] new_c[33] = cb[17] new_c[34] = cb[14] new_...
477de2c2c92d431ccee5ad51e097159894e73d4a
671,888
def addDigits(s): """Assumes s is a str each character of which is a decimal digit. Returns an int that is the sum of the digits in s""" val = 0 for c in s: val += int(c) return val
e135d1f0d243b9a9573a67bfde44606278b0bb3d
671,889
def twoPointsCrossoverMethod(parent1,parent2,locL,locU): """ Method designed to perform a twopoint crossover on 2 arrays: Partition each array in three sequences (A,B,C): parent1 = A1 B1 C1 parent2 = A2 B2 C2 Then: children1 = A1 B2 C1 children2 = A2 B1 C2 @ In, parent1: first array ...
7cc4e854c89ee55f3295cc61e15377c4d434c11c
671,890
def generate_addresses(): """ Generates a list of all display addresses :return: a list of display addresses in the flip dot display """ addr = [b'']*18 addr[0] = b'\x00' addr[1] = b'\x01' addr[2] = b'\x02' addr[3] = b'\x03' addr[4] = b'\x04' addr[5] = b'\x05' addr[6] = b...
3177ab03e567811566a1c7fcf80f7669de50090a
671,891
import asyncio def completed_future(): """Utility function to create a stub Future object that asyncio can wait for.""" future = asyncio.Future() future.set_result(True) return future
b7b48890cca940ad4b9a24e17633260f0e627951
671,892
def get_bin_number(bins, val): """ Gets the bin number of a value in a binspace Parameters ========== bins :: list The bin edges val :: real number The value to get the bin number for Returns ======= The bin number of the test value. -1 if it is not within the binspace """ for i in range(l...
76175c23e3da6697e2cbfb80d3fa7fe85a8abed3
671,893
import re def remove_line_folding(instring): """Remove line folding from instring""" if re.match(r"\\[ \v\t\f]*" +"\n",instring) is not None: return re.sub(r"\\[ \v\t\f]*$" + "\n?","",instring,flags=re.M) else: return instring
a79db341772710f7050dbe6508740b2f47532a80
671,894
def first_vs_rest(first_func, rest_func=lambda w: w): """Supply one or two transformer functions for the first and rest of words respectively. Leave second argument out if you want all but the first word to be passed through unchanged. Set first argument to None if you want the first word to be pas...
9bcf193e300a3838ecd4a3551fce24341431bb20
671,895
def make_event_cname(ev_spec) -> str: """Create a transition connector name based on an event name and an optional signature""" if not ev_spec.signature: return ev_spec.name else: return ev_spec.name + '( ' + ', '.join( [f'{p.name}:{p.type}' for p in ev_spec.signature]) + ' )'
ca291484d972b9cda4d1f40db3045e3c9075e7a4
671,896
def check_type(item, expected_type): """ Checks a object to make sure that it is a certain type :param item: any type :param expected_type: string (ex:"str") :return: type """ item_type = str(type(item)) if "str" in expected_type.lower() and item_type == "<class 'str'>": pass ...
a2e2fd4fb9a7667d6073c469ee979ac05b9798e0
671,897
import os import platform def py_shell() -> str: """ Returns string containing current python shell name. """ shell: str = "" PY_ENV = os.environ PY_BASE = os.path.basename(PY_ENV["_"]) if "JPY_PARENT_PID" in PY_ENV: shell = "ipython notebook" elif "pypy" in PY_ENV: shell = "p...
d40a174f5ad96ed28821920525583afae640c670
671,898
def happy_color(health): """Return pyplot color for health percentage.""" if health > 0.8: return 'g' if health > 0.6: return 'y' return 'r'
8abb43423f9baa91790bfa69be8d4b850108c112
671,899
def remaining_evals(cur_step, epoch, train_steps_per_epoch, evals_per_epoch): """Helper function to calculate remaining evaluations for a trainer. Args: cur_step: current step of the supervised trainer epoch: current epoch of the RL trainer train_steps_per_epoch: supervised trainer steps per RL epoch ...
b897af4f78e9a6946326f28392834d2d9e085471
671,900
from typing import Any from operator import getitem def _getitem(sequence: Any, key: object, default: object = None) -> Any: """Helper for the map filter. Same as sequence[key], but returns a default value if key does not exist in sequence. """ try: return getitem(sequence, key) excep...
6f9c45ddbf27949ca4bf0ec12d9d6d9b377254be
671,901
def _process(user_input, mapping, extra=[]): """Processes `user_input` string.""" target = user_input for symbol in mapping: target = target.replace(symbol[0], symbol[1]) for symbol in extra: target = target.replace(symbol[0], symbol[1]) # short_desc = target # Some magic... ...
d8e5758660e8e05e17da3263c77fe055bfc01586
671,902
import click def serror(message, *args, **kwargs): """Print a styled error message.""" if args or kwargs: message = message.format(*args, **kwargs) return click.secho(message, fg='white', bg='red', bold=True)
e0ea22165a86345b019987b5d4a196b11e8c4b01
671,904
import threading def 线程_取所有活动对象(): """ 返回Thread当前所有活动对象的列表。该列表包括守护线程,由创建的伪线程对象 current_thread()和主线程。它不包括终止的线程和尚未启动的线程。 """ return threading.enumerate()
6c262bbcb274460ee5bcd39e9a1bdc5237755583
671,905
def check_script(script): """ Checks if a given string is a script (hash160) (or at least if it is formatted as if it is). :param script: Script to be checked. :type script: hex str :return: True if the signatures matches the format, raise exception otherwise. :rtype: bool """ if not isins...
e7d8f5227a9e9d399b591736d7c3f04a371d02ed
671,906
def normalize_route(route: str) -> str: """Strip some of the ugly regexp characters from the given pattern. >>> normalize_route('^/user/<user_id:int>/?$') u'/user/(user_id:int)/' """ normalized_route = str(route).lstrip('^').rstrip('$').rstrip('?') normalized_route = normalized_route.replace('<...
d2e7bf657ecf1cef657d13b5682b346d66e8cacf
671,907
def unquote_option_value(value): """Remove quotes from a string.""" if len(value) > 1 and value[0] in ('"', "'") and value[0] == value[-1]: return value[1:-1] return value
089e8ca9006004703e649684af6f0bd1a1cc74ca
671,908
import logging def get_tables(in_tables): """ Evaluate input and output table names. Only taking the first one into consideration! """ # input file table = in_tables[0] in_name = table["full_path"] in_destination = table["destination"] logging.info("Data table: " + str(in_name)) ...
63e8b31d359a3a3d76171b6f21fb28c5b7c06143
671,909
def custom_provider_account_user(request, threescale, testconfig): """Parametrized custom Provider account user Args: :param params: dict for remote call, rawobj.AccountUser should be used """ def _custom_user(params, autoclean=True): user = threescale.provider_account_users.create(param...
cc69a530a6a3b3ef4dcf407adbfd72ade8c25fdb
671,910
def bisect_find(n, f, *args, **kw): """ Find largest `k` for which `f(k)` is true. The k is integer in range 1 <= k <= n. If there is no `k` for which `f(k)` is true, then return `0`. :param n: Range for `k`, so :math:`1 <= k <= n`. :param f: Invariant function accepting `k`. :param *args...
7279788d8e4edb8f4e4f49becd26652cd477fa24
671,911
import re def lineMatching(regexStr, lines): """ Searches through the specified list of strings and returns the regular expression match for the first line that matches the specified regex string, or None if no match was found Note: if you have a pre-compiled regex pattern, use lineMatchingPattern() ins...
5587f06878abc663fd44908630d97450e6dc1243
671,912
import smtplib def connect(smtp_server, smtp_port, email, password): """ Connect to the SMTP server to send emails. :param smtp_server: Hostname or IP Address of the SMTP server :param smtp_port: Port number of the SMTP server. :param email: Valid email address for authentication. :param pass...
34ac16b58b86f0e99709e80829114c6753fbc1d3
671,913
def rgb_hex_to_rgb_list(hex_string): """Return an RGB color value list from a hex color string.""" return [int(hex_string[i:i + len(hex_string) // 3], 16) for i in range(0, len(hex_string), len(hex_string) // 3)]
310bf3de778d6557729132f89e7888296d21da18
671,914
import re def get_latest_hub_per_task(hub_module_paths): """Get latest hub module for each task. The hub module path should match format ".*/hub/[0-9]*/module/.*". Example usage: get_latest_hub_per_task(expand_glob(["/cns/el-d/home/dune/representation/" "xzhai/1899361/*...
17d5f763ca3837dd6cf1fe1dff5b265a64dfa976
671,915
def get_subdirectories(qcnode): """ Return a list of refs to sub-directories of given qcnode. """ subdirectories = [] nodes = qcnode.SubNodes for node in nodes: subdirectories.append(node) return subdirectories
169c8059897d444862cd7f872c362ed9443d51ab
671,916
import time def search_updated_intrusion_prevention_rules(api, configuration, api_version, api_exception, num_days): """ Searches for Intrusion Prevention rules that have been updated within a specific number of days. :param api: The Deep Security API modules. :param configuration: Configuration object t...
ee29d5e0fd59b9dfa188fdbcbbc2955f522950e2
671,917
def sexp(self, labr="", lab1="", lab2="", exp1="", exp2="", **kwargs): """Forms an element table item by exponentiating and multiplying. APDL Command: SEXP Parameters ---------- labr Label assigned to results. If same as existing label, the existing values will be overwritten by t...
6825e5a553a0866f509e3a1023ce571a0f64ff03
671,918
import json def collect_rest_data(response): """Extracts raw rest-countries data from requested resources. Parameters ---------- response : dict If the requested resources were available the `response` dictionary will contain the raw rest-countries data. Returns ------- r...
c9ac17f859e21cdc7c72195ff07f1ff12f4b24f3
671,919
import random def get_random_integer(number): """ This function takes in a number and returns a random integer between 0 and that number """ return random.randint(0, number)
e5456480530f01f013428f9c5827421b7aaa12f0
671,921
def registerConfigurable(name, registry, ConfigClass=None): """A decorator that adds a class as a configurable in a Registry. If the 'ConfigClass' argument is None, the class's ConfigClass attribute will be used. """ def decorate(cls): registry.register(name, target=cls, ConfigClass=ConfigClass...
c3d9eccfb2ec0b90f371be1413d1738987e8d90a
671,922
def vectors_from_indices(bm, raw_vert_indices): """Return List of vectors from input Vertex Indices. Args: bm: Object Bmesh raw_vert_indices: List of Chosen Vertex Indices Returns: List of Vertex coordinates. """ return [bm.verts[i].co for i in raw_vert_indices]
bbbdb246a5d3f434f13d0ee00301957a331ae569
671,923
import re def _split_url(url): """ 将url拆分为host和path :return: host, path """ m = re.match('\w+://([^/]*)(.*)', url) if m: return m.group(1), m.group(2)
8fa45fc166307fbba93b9b5d52b357581f1ad320
671,924
def rsq(true, predicted): """ ---------- Parameters ---------- true: true value predicted: predicted value Returns ------- r-squared """ sse = sum((predicted - true) ** 2) sst = sum((true - sum(true)/len(true)) ** 2) return 1 - sse / sst
51ea4a215d2247e1fda8111f431173685592731a
671,927
def _target_selectors(targets): """ Return the target selectors from the given target list. Transforms the target lists that the client sends in annotation create and update requests into our internal target_selectors format. """ # Any targets other than the first in the list are discarded. ...
1da3ed91f6f9151d8ed967ab5dfc0931a39e0d1f
671,928
def play_game(game): """ Play cards. Higher card wins. If value on the cards for both players is same or lower than count of cards players have in package, then the sub-game is playing. Result of subgame determine winner of parent game. If the game is in infinitive loop, then the winner is automatic...
85642ab5caa295b6661ba8ccfa981869082dcf09
671,929
def _has_matched_brackets(text: str) -> bool: """ Evaluate whether every opening bracket '[' in the 'text' has a matching closing bracket ']'. :param text: the text. :return: Boolean result, and associated message. """ open_bracket_stack = [] for index, _ in enumerate(text): if text...
4c8b0e30654a3f5ad72da173233b7a64110042a4
671,930
import glob import os def getAllFilesInDirectory(paths, recursive=False, maxLevel=10, extensions=[]): """ Return all files in the given directory. :param directory: Directory in which we look for files :type directory: str :param recursive: If subdirectories should be included :type recursi...
1135d1209ae3268d022b92a68e6c2fbb726719f1
671,931