content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def kineticEnergyCOM(robot : object, symbolic = False): """This function calculates the total kinetic energy, with respect to each center of mass, given linear and angular velocities Args: robot (object): serial robot (this won't work with other type of robots) symbolic (bool, optional): used t...
5f0559e55a389741ad0591b5ac3f220ffdb76a2c
21,920
def get_input(request) -> str: """Get the input song from the request form.""" return request.form.get('input')
de237dc0ad3ce2fa6312dc6ba0ea9fe1c2bdbeb3
21,921
from typing import Hashable import math def _unit_circle_positions(item_counts: dict[Hashable, tuple[int, int]], radius=0.45, center_x=0.5, center_y=0.5) -> dict[Hashable, tuple[float, float]]: """ computes equally spaced points on a circle based on the radius and center positions ...
66f60f5b90f7825f2abfdd2484375c9558786250
21,922
import re def rate_table_download(request, table_id): """ Download a calcification rate table as CSV. """ def render_permission_error(request, message): return render(request, 'permission_denied.html', dict(error=message)) table_permission_error_message = \ f"You don't have permis...
d62eb09d11c0e91cca3eb36388f1165e2a4433ee
21,923
def rgb_to_RGB255(rgb: RGBTuple) -> RGB255Tuple: """ Convert from Color.rgb's 0-1 range to ANSI RGB (0-255) range. >>> rgb_to_RGB255((1, 0.5, 0)) (255, 128, 0) """ return tuple([int(round(map_interval(0, 1, 0, 255, c))) for c in rgb])
1fe460a4716244efbbacbc6d44f10a3fc6ba8d3f
21,925
import requests import re def check_rest_version(host="http://www.compbio.dundee.ac.uk/jpred4/cgi-bin/rest", suffix="version", silent=False): """Check version of JPred REST interface. :param str host: JPred host address. :param str suffix: Host address suffix. :param silent: Should the work be done s...
f9c5e858e4a4681d8b5045e8ed08738f1c32016a
21,926
def analyzer_options(*args): """ analyzer_options() Allow the user to set analyzer options. (show a dialog box) ( 'ui_analyzer_options' ) """ return _ida_kernwin.analyzer_options(*args)
e0b78523d32cce303fe8048012ae1e57c7c422bd
21,927
import torch def vector_vector_feature(v_a, v_b, weight, p_idx, frames, symmetric): """ Taking outer product, create matrix feature per pair, average, express in SO2 feature. :param v_a: [E, 3] :param v_b: [E, 3] :param weight: [E] :param p_idx: [E] index [0, V) :param frames: [V, 3, 3] ...
6b583cc834d79d463fc5e6b68b98cd027c4969ec
21,928
def parse_steps(filename): """ Read each line of FILENAME and return a dict where the key is the step and the value is a list of prerequisite steps. """ steps = defaultdict(lambda: list()) all_steps = set() with open(filename) as f: for line in f: words = line.split(' ') ...
450d93cb72cf92c186cbcecc1992c6e4391ca428
21,929
import glob import json def sitestructure(config, path, extra): """Read all markdown files and make a site structure file""" # no error handling here, because compile_page has it entire_site = list() for page in glob.iglob(path + '**/*.md', recursive=True): merged = compile_page(None, config, page, extra) if...
6c7d21bce30ebb418a8146f302ce62bbe0386bbf
21,930
import uuid def _create_component(tag_name, allow_children=True, callbacks=[]): """ Create a component for an HTML Tag Examples: >>> marquee = _create_component('marquee') >>> marquee('woohoo') <marquee>woohoo</marquee> """ def _component(*children, **kwargs): if 'c...
a11572de6d079b35ffe0492154939cceb953b199
21,931
def typeof(val, purpose=Purpose.argument): """ Get the Numba type of a Python value for the given purpose. """ # Note the behaviour for Purpose.argument must match _typeof.c. c = _TypeofContext(purpose) ty = typeof_impl(val, c) if ty is None: msg = _termcolor.errmsg( "can...
83d8e84fca58ce78b15e9106a14ff95c86ccac68
21,932
import logging def scale_site_by_jobslots(df, target_score, jobslot_col=Metric.JOBSLOT_COUNT.value, count_col=Metric.NODE_COUNT.value): """ Scale a resource environment (data frame with node type information) to the supplied share. This method uses the number of jobslots in each node as a target metric. ...
c46129ebf4761fbcb7c3e40165c83259d0eb24e0
21,933
def primesfrom2to(n): """Input n>=6, Returns a array of primes, 2 <= p < n""" sieve = np.ones(n / 3 + (n % 6 == 2), dtype=np.bool) sieve[0] = False for i in xrange(int(n ** 0.5) / 3 + 1): if sieve[i]: k = 3 * i + 1 | 1 sieve[((k * k) / 3)::2 * k] = False sieve[(k * k + 4 * k - 2 * k * (i &...
e66a8dd1bb23f1aab8786d4832e382d07e5973e0
21,934
import time def TimeFromTicks(ticks): """construct an object holding a time value from the given ticks value.""" return Time(*time.localtime(ticks)[3:6])
96651ff5e0da5e88988640b5e3f544ad82dd90b2
21,936
def check_key_exists(file_location, section, key): """ Searches an INI Configuration file for the existance of a section & key :param file_location: The file to get a key value from :param section: The section to find the key value :param key: The key that can contain a value to retrieve :retur...
afdc8bad295cd2b0ed0576eab0ff633fb1f854b3
21,937
def replace_na(str_value: str, ch: str = "0") -> str: """replaces \"0\" with na, specifically designed for category list, may not work for others need Args: str_value (str): category list ch (str, optional): Replacemet char. Defaults to "0". Returns: str: clean cotegory name ""...
d8e6dfe6806c7a008163ba92c62e7b2b18633538
21,938
def intent_requires(): """ This view encapsulates the method get_intent_requirement It requires an Intent. :return: A dict containing the different entities required for an Intent """ data = request.get_json() if "intent" in data: return kg.get_intent_requirements(data["intent"]) ...
75901abc3d0833eba39c229cc35249c8cb3e6162
21,939
def standardize_df_off_tr(df_tr:pd.DataFrame, df_te:pd.DataFrame): """Standardize dataframes from a training and testing frame, where the means and standard deviations that are calculated from the training dataset. """ for key in df_tr.keys(): if key != 'target': ...
04438b7f31efbe80129ef1cda488ea3c93bcf55e
21,940
def filter_clusters(aoi_clusters, min_ratio, max_deviation, message, run=None): """ min_ratio: Has to have more than x % of all dots in the corner within the cluster max_deviation: Should not deviate more than x % of the screen size from the respective AO...
2767afd05093e364cf6be22b98b4821c6811165e
21,941
def set_to_true(): """matches v1, which assign True to v1""" key = yield symbol res = Assign(key, True) return res
e1a8eb62be409252475ad39d9d72a087b0344f9f
21,942
def d1_to_q1(A, b, mapper, cnt, M): """ Constraints for d1 to q1 """ for key in mapper['ck'].keys(): for i in range(M): for j in range(i, M): # hermetian constraints if i != j: A[cnt, mapper['ck'][key](i, j)] += 0.5 ...
1ee9ec17f4464ef280aa22780d6034309941954e
21,944
from typing import OrderedDict def _get_dict_roi(directory=None): """Get all available images with ROI bounding box. Returns ------- dict : {<image_id>: <ROI file path>} """ d = OrderedDict() for f in listdir(directory or IJ_ROI_DIR): d[splitext(f)[0]] = join(directory or...
56c2b6a8cb3cb296489050a5465e19e6829ee383
21,947
from operator import index def geol_units(img, lon_w, lat, legend=None): """Get geological units based on (lon, lat) coordinates. Parameters ---------- img: 2d-array 2D geol map image centered at 180°. lon_w: float or array Point west longitude(s). lat: float or array ...
d564ee29139d6a8c5d2235da10acb11b24866d80
21,948
def Water_Mask(shape_lsc,Reflect): """ Calculates the water and cloud mask """ mask = np.zeros((shape_lsc[1], shape_lsc[0])) mask[np.logical_and(Reflect[:, :, 3] < Reflect[:, :, 2], Reflect[:, :, 4] < Reflect[:, :, 1])] = 1.0 water_mask_temp = np.copy(mask) retur...
6bcf7b4a96c4de9938c1520253d81460dd7a8025
21,949
def get_gs_distortion(dict_energies: dict): """Calculates energy difference between Unperturbed structure and most favourable distortion. Returns energy drop of the ground-state relative to Unperturbed (in eV) and the BDM distortion that lead to ground-state. Args: dict_energies (dict): ...
2f23103ccac8e801cb6c2c4aff1fb4fc08341e78
21,951
def parse_accept_language(data: str = None): """Parse HTTP header `Accept-Language` Returns a tuple like below: ``` ((1.0, Locale('zh_Hant_TW')), (0.9, Locale('en')), (0.0, _fallback_ns)) ``` """ langs = {(0.0, _fallback_ns)} if data is None: return tuple(langs) for s in d...
fd2d9aef4825dc0d7fd7a84b69391c69353e9f86
21,952
def stop_service(): """ Stopping the service """ global __service_thread dbg("Trying to stop service thread") shutdown_service() __service_thread.join() __service_thread = None info("Server stopped") return True
97f7b9fb60a7a271f3c234be43b2b513c42ce77e
21,953
def get_constants_name_from_value(constant_dict, value) : """ @param constant_dict : constant dictionary to consider @param value : value's constant name to retrieve @rtype : a string """ try: return constant_dict[value] except KeyError: log.error("The c...
3848e3e83946196250f3987a976b5a74da016a34
21,954
def rotxyz(x_ang,y_ang,z_ang): """Creates a 3x3 numpy rotation matrix from three rotations done in the order of x, y, and z in the local coordinate frame as it rotates. The three columns represent the new basis vectors in the global coordinate system of a coordinate system rotated by this matrix. ...
779c4ca37d5636ad7cff38d9200a9b50b3b0fffe
21,955
def hpdi(proba, array): """ Give the highest posterior density interval. For example, the 95% HPDI is a lower bound and upper bound such that: 1. they contain 95% probability, and 2. in total, have higher peaks than any other bound. Parameters: proba: float A value b...
a417b6adba19ef6206326791250c880e3b2a28a1
21,956
import urllib def _capabilities(repo, proto): """return a list of capabilities for a repo This function exists to allow extensions to easily wrap capabilities computation - returns a lists: easy to alter - change done here will be propagated to both `capabilities` and `hello` command witho...
764c59bbbe525b8d825dfded871643bb88a1588f
21,958
import types from typing import Dict import collections def dep(doclike: types.DocLike) -> Dict[str, int]: """ Count the number of times each syntactic dependency relation appears as a token annotation in ``doclike``. Args: doclike Returns: Mapping of dependency relation to count...
e4fcb5a54578b2b001eda4255cd3a22b89a6d195
21,959
def fix_phonology_table(engine, phonology_table, phonologybackup_table, user_table): """Give each phonology UUID and modifier_id values; also give the phonology backups of existing phonologies UUID values. """ print_('Fixing the phonology table ... ') msgs = [] #engine.execute('set names latin1...
746ca4a479b450f3320b4c04a3ce6013beb88ed4
21,960
def D(field, dynkin): """A derivative. Returns a new field with additional dotted and undotted indices. Example: >>> D(L, "01") DL(01001)(-1/2) >>> D(L, "21") DL(21001)(-1/2) """ undotted_delta = int(dynkin[0]) - field.dynkin_ints[0] dotted_delta = int(dynkin[1]) ...
1ee408a8cc2923b141c5ffe1c41d919a501111ae
21,961
def _det(m, n): """Recursive calculation of matrix determinant""" """utilizing cofactors""" sgn = 1 Det = 0 if n == 1: return m[0][0] cofact = [n*[0] for i in range(n)] for i in range(n): _get_cofact(m, cofact,0,i,n); Det += sgn*m[0][i]*_det(cofact, n - 1); ...
9019dd9dc1054fc4c36e72a6e3c9a3c478afa4ad
21,962
from typing import List def get_vcps() -> List[LinuxVCP]: """ Interrogates I2C buses to determine if they are DDC-CI capable. Returns: List of all VCPs detected. """ vcps = [] # iterate I2C devices for device in pyudev.Context().list_devices(subsystem="i2c"): vcp = LinuxV...
ce3766c695fe9ffb0a6ebcced4ac04808987f340
21,963
def toGoatLatin(S): """ :type S: str :rtype: str """ l_words = [] for i, word in enumerate(S.split()): if not is_vowel(word[0]): word = word[1:] + word[0] aa = "a" * (i + 1) l_words.append(word + "ma" + aa) return " ".join(l_words)
5ed41084a0d35d69e65b2821b43c2373cf289d26
21,964
def list_startswith(_list, lstart): """ Check if a list (_list) starts with all the items from another list (lstart) :param _list: list :param lstart: list :return: bool, True if _list starts with all the items of lstart. """ if _list is None: return False lenlist = len(_list) ...
6f8952a80da81381464521fec55abaaee4a04881
21,965
def get_subscribers(subreddit_, *args): """Gets current sub count for one or more subreddits. Inputs ------- str: Desired subreddit name(s) Returns ------- int: sub count or dict:{subreddit: int(sub count)} """ if len(args) > 0: subreddit = reddit.subreddit(subreddit_) ...
2648eb7db5fe0ebc9940f714fab8770947960463
21,967
def pattern_match(value, pattern, env=None): """ Pattern match a value and a pattern. Args: value: the value to pattern-match on pattern: a pattern, consisting of literals and/or locally bound variables env: a dictionary of local variables bound while matching ...
145ef26283f4e21f7ab763317174c5e6da043d84
21,968
import functools import six def wraps(wrapped): """A functools.wraps helper that handles partial objects on Python 2.""" # https://github.com/google/pytype/issues/322 if isinstance(wrapped, functools.partial): # pytype: disable=wrong-arg-types return six.wraps(wrapped, assigned=_PARTIAL_VALID_ASS...
8e3762c9d7f50c8e26df0f0de545de7991d59e92
21,971
def byte_to_bits(byte): """Convert a byte to an tuple of 8 bits for use in Merkle-Hellman. The first element of the returned tuple is the most significant bit. Usage:: byte_to_bits(65) # => [0, 1, 0, 0, 0, 0, 0, 1] byte_to_bits(b'ABC'[0]) # => [0, 1, 0, 0, 0, 0, 0, 1] byte_to_bit...
231272c60a3d06de0a914b38fee4f50a0209bcd4
21,972
def KK_RC48_fit(params, w, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params["Rs"] R1 = params["R1"] R2 = params["R2"] R3 = params["R3"] R4 = params["R4"] R5 = params["R5"] R6 = params["R6"] ...
1395f182880db7f42d43eba05605673eab83770b
21,973
def race(deer, seconds): """ Use the reindeer's speed and rest times to find the timed distance """ distance = 0 stats = reindeer[deer] resting = False while True: if resting: if seconds <= stats[2]: break seconds -= stats[2] else: ...
ea7cb0577cdfa4aab558ca8ad6f4ddde2d79e996
21,974
def AsdlEqual(left, right): """Check if generated ASDL instances are equal. We don't use equality in the actual code, so this is relegated to test_lib. """ if left is None and right is None: return True if isinstance(left, (int, str, bool, pybase.SimpleObj)): return left == right if isinstance(le...
ac5752cd30ff31488ecc000426b6f2430acb1718
21,975
import torch def attention_padding_mask(q, k, padding_index=0): """Generate mask tensor for padding value Args: q (Tensor): (B, T_q) k (Tensor): (B, T_k) padding_index (int): padding index. Default: 0 Returns: (torch.BoolTensor): Mask with shape (B, T_q, T_k). True element ...
49d1dc8dd4e59284eb090711545cf70c9ba5fad4
21,977
import itertools def process_params(request, standard_params=STANDARD_QUERY_PARAMS, filter_fields=None, defaults=None): """Parse query params. Parses, validates, and converts query into a consistent format. :keyword request: the bottle request :keyword standard_params: query param...
06de4c5df0bdcfcc091aefa12cc8aa7fd4c06597
21,980
import inspect def all_attributes(cls): """ Each object will have the attributes declared directly on the object in the attrs dictionary. In addition there may be attributes declared by a particular object's parent classes. This function walks the class hierarchy to collect the attrs in the object's p...
3d1a1013fe36cef776b6a9842f774f5394aaeff5
21,981
def _reshape_model_inputs(model_inputs: np.ndarray, num_trajectories: int, trajectory_size: int) -> np.ndarray: """Reshapes the model inputs' matrix. Parameters ---------- model_inputs: np.ndarray Matrix of model inputs num_trajectories: int Number of traje...
2562d143c5dbf7b6c1c018afe2f87df6297752da
21,982
def VIS(img, **normalization): """Unmixes according to the Vegetation-Impervious-Soil (VIS) approach. Args: img: the ee.Image to unmix. **normalization: keyword arguments to pass to fractionalCover(), like shade_normalize=True. Returns: unmixed: a 3-band image file in o...
2c85aa894f6ccfae3da8650cb9c32cc125a19a45
21,984
def create_labels(mapfile, Nodes=None): """ Mapping from the protein identifier to the group Format : ##protein start_position end_position orthologous_group protein_annotation :param Nodes: set -- create mapping only for these set of nodes :param mapfile: file that contains the...
634eefc5a837e484059278939ba34fd2482846bf
21,985
def sortKSUID(ksuidList): """ sorts a list of ksuids by their date (recent in the front) """ return sorted(ksuidList, key=lambda x: x.getTimestamp(), reverse=False)
0476bc0ef19f8730488041ac33598ba7471f96e7
21,987
from typing import Counter def get_vocabulary(list_): """ Computes the vocabulary for the provided list of sentences :param list_: a list of sentences (strings) :return: a dictionary with key, val = word, count and a sorted list, by count, of all the words """ all_the_words = [] for tex...
d6c357a5768c2c784c7dfe97743d34795b2695c0
21,989
def check_field(rule: tuple, field: int) -> bool: """check if a field is valid given a rule""" for min_range, max_range in rule: if min_range <= field <= max_range: return True return False
32e34da10fff12e765dd6d48472acf0ac5ad72af
21,991
import math def split(value, precision=1): """ Split `value` into value and "exponent-of-10", where "exponent-of-10" is a multiple of 3. This corresponds to SI prefixes. Returns tuple, where the second value is the "exponent-of-10" and the first value is `value` divided by the "exponent-of-10". ...
776ded073807773b755dcd7ab20c47d1f33ca1e1
21,992
import requests def test_cert(host, port=443, timeout=5, **kwargs): """Test that a cert is valid on a site. Args: host (:obj:`str`): hostname to connect to. can be any of: "scheme://host:port", "scheme://host", or "host". port (:obj:`str`, optional): port t...
3d0e0098b5f654305c187f2a566c25f8c87a5ce3
21,994
def get_predicates(): # noqa: E501 """get_predicates Get a list of predicates used in statements issued by the knowledge source # noqa: E501 :rtype: List[BeaconPredicate] """ return controller_impl.get_predicates()
7f3f89b300a0e43449a1860cff8200af6d33a3b1
21,995
def noisy_job_stage3(aht, ht, zz, exact=False): """Adds noise to decoding circuit. Args: ===== aht, ht, zz : numeric Circuit parameters for decoding circuit exact : bool If True, works with wavefunction Returns: ======== noisy_circuit : cirq.Circuit Noisy versio...
a5f1bcb8cced41b2b6179d2eeb68e8b8939aca96
21,996
import math def buy_and_hold_manager_factory(mgr, j:int, y, s:dict, e=1000): """ Ignores manager preference except every j data points For this to make any sense, 'y' must be changes in log prices. For this to be efficient, the manager must respect the "e" convention. That is, the ...
2225b6f41979e1781a778f397b699751456dc2a4
21,997
def explicit_wait_visibility_of_element_located(browser, xpath, timeout=35): """Explicitly wait until visibility on element.""" locator = (By.XPATH, xpath) condition = expected_conditions.visibility_of_element_located(locator) try: wait = WebDriverWait(browser, timeout) result = wait.un...
2fd6fe951d1d55121909e2a326b72af4524f577b
21,998
def list_all_resources(): """Return a list of all known resources. :param start_timestamp: Limits resources by last update time >= this value. (optional) :type start_timestamp: ISO date in UTC :param end_timestamp: Limits resources by last update time < this value. (optional) :type ...
c2b42abd7c03d2f2b6541a45b7b45b2cb420ebc4
21,999
def get_completed_exploration_ids(user_id, collection_id): """Returns a list of explorations the user has completed within the context of the provided collection. Args: user_id: str. ID of the given user. collection_id: str. ID of the collection. Returns: list(str). A list of e...
7d3456f8fa0af83d776d7f2daf0edde33c83adb6
22,000
import re def clean_str(string): """ Tokenization/string cleaning for all datasets except for SST. """ string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) string = re.sub(r"\?", " ? ", string) string = re.sub(r"\s{2,}", " ", string) return string.strip().lower()
dec81e721fb3a83c8ea372d21dfa805394edc0e3
22,001
def transitive_closure(graph): """ Compute the transitive closure of the graph :param graph: a graph (list of directed pairs) :return: the transitive closure of the graph """ closure = set(graph) while True: new_relations = set((x, w) for x, y in closure for q, w in closure if q == y...
3bb6567033cf920ccced7565e75f8f789c55c37d
22,002
def call_function(func_name, func_args, params, system): """ func_args : list of values (int or string) return str or None if fail return ROPChain if success """ if( system == Systems.TargetSystem.Linux and curr_arch_type() == ArchType.ARCH_X86 ): return call_function_linux_x86(func...
ede0b62dfa6d47c2c79ff405b056c26198e5afb5
22,003
import traceback def error_handler(update, context): """Log Errors caused by Updates.""" log.error( 'with user: "%s (%s)"\nmessage: "%s"\ntraceback: %s', update.effective_user, update.effective_user.id, context.error, traceback.format_exc() ) return Conversation...
45ea22efe64c600ede6de81ee278493ff14dc772
22,004
def jac(w, centred_img_patches, F, NUM_MODES): """ The Jacobian of the numerical search procedure. Parameters ---------- w : numpy array (floats) Column vector of model weights, used to construct mapping. centred_img_patches : numpy array (floats) The mean-centred {p x NUM_PATCH...
ee780ac6e366f14c1ab7c661db99bcdbdd3cc033
22,005
def get_session(): """Entrega uma instancia da session, para manipular o db.""" return Session(engine)
eb528d0de57e704e96ffa502e7504746efac6cbb
22,006
def sdm_ecart(f): """ Compute the ecart of ``f``. This is defined to be the difference of the total degree of `f` and the total degree of the leading monomial of `f` [SCA, defn 2.3.7]. Invalid if f is zero. Examples ======== >>> from sympy.polys.distributedmodules import sdm_ecart ...
00d4e8807eef38326ee8a588a81287a1c9d62d0d
22,007
def draw_gif_frame(image, bbox, frame_no): """Draw a rectangle with given bbox info. Input: - image: Frame to draw on - length: Number of info (4 info/box) - bbox: A list containing rectangles' info to draw -> frame id x y w h Output: Frame that has been drawn on""" obj_id = b...
462773a88179361bc013777405b04f99ac73bd3b
22,008
def create_host(api_client, orig_host_name, orig_host_uid, cloned_host_name, cloned_host_ip): """ Create a new host object with 'new_host_name' as its name and 'new_host_ip_address' as its IP-address. The new host's color and comments will be copied from the the "orig_host" object. :param api_client: Ap...
18fb2f727bae8150c98510a45e69409ff8aa4fe9
22,010
def parenthesize(x): """Return a copy of x surrounded by open and close parentheses""" cast = type(x) if cast is deque: return deque(['('] + list(x) + [')']) return cast('(') + x + cast(')')
ae76b220fd3bc00d3df99ec97982b44010f36e64
22,011
def get_logo_color(): """Return color of logo used in application main menu. RGB format (0-255, 0-255, 0-255). Orange applied. """ return (255, 128, 0)
a6eee63d816a44af31893830ac641d6c0b1b9ba1
22,012
def DG(p,t,Ep=10): """ Entrenamiento por Descenso de Gradiente """ # m será igual al número patrones de # entrenamiento (ejemplos) y n al número # de elementos del vector de caracteristicas. m,n = p.shape a = 0.5 #--- Pesos iniciales --- w = np.random.uniform(-0.25,0.25,2) ...
d23c5b11432cfb6d7d4e3beb56b917f82809442e
22,013
def delete_video_db(video_id): """Delete a video reference from the database.""" connection = connect_db() connection.cursor().execute('DELETE FROM Content WHERE contentID=%s', (video_id,)) connection.commit() close_db(connection) return True
c91428f5f60590d7f0219d732900ae24fcc39749
22,015
import numba def int_to_float_fn(inputs, out_dtype): """Create a Numba function that converts integer and boolean ``ndarray``s to floats.""" if any(i.type.numpy_dtype.kind in "ib" for i in inputs): args_dtype = np.dtype(f"f{out_dtype.itemsize}") @numba.njit(inline="always") def inpu...
f47f9485fa83acb2e7a0237c7ef851d3c23f8fe6
22,016
from numpy import sqrt def vel_gradient(**kwargs): """ Calculates velocity gradient across surface object in supersonic flow (from stagnation point) based upon either of two input variable sets. First method: vel_gradient(R_n = Object radius (or equivalent radius, for shapes that a...
8ee3ef490c113551e9200743e52378a8206a3666
22,017
from functools import reduce def lcm(numbers): """ Get the least common multiple of a list of numbers ------------------------------------------------------------------------------------ input: numbers [1,2,6] list of integers output: 6 integer """ return reduce(lambda x, y: int((x * y) / gcd(x, ...
a1c3ce93b0ea4f06c8fb54765110fa85f7517fe5
22,018
def parseBracketed(idxst,pos): """parse an identifier in curly brackets. Here are some examples: >>> def test(st,pos): ... idxst= IndexedString(st) ... (a,b)= parseBracketed(idxst,pos) ... print(st[a:b]) ... >>> test(r'{abc}',0) {abc} >>> test(r'{ab8c}',0) {ab8c...
d78617fa8a85c234920d0f985566d7a00ebe6b1a
22,019
def compute_agg_tiv(tiv_df, agg_key, bi_tiv_col, loc_num): """ compute the agg tiv depending on the agg_key""" agg_tiv_df = (tiv_df.drop_duplicates(agg_key + [loc_num], keep='first')[list(set(agg_key + ['tiv', 'tiv_sum', bi_tiv_col]))] .groupby(agg_key, observed=True).sum().reset_index()) if 'is_...
246ea2d61230f3e3bfe365fdf8fdbedbda98f25b
22,020
from typing import List def convert_configurations_to_array(configs: List[Configuration]) -> np.ndarray: """Impute inactive hyperparameters in configurations with their default. Necessary to apply an EPM to the data. Parameters ---------- configs : List[Configuration] List of configurati...
09b14dc5d5bb5707b059b7a469d93c7288da84cf
22,021
from typing import Optional from datetime import datetime import requests def annual_mean( start: Optional[datetime] = None, end: Optional[datetime] = None ) -> dict: """Get the annual mean data ---------------------------- Data from March 1958 through April 1974 have been obtained by C. David Ke...
4fd06301f9f414e08629cdbfeae75adcc6febdcf
22,022
def exception(logger,extraLog=None): """ A decorator that wraps the passed in function and logs exceptions should one occur @param logger: The logging object """ print logger def decorator(func): print "call decorator" def wrapper(*args, **kwargs): print "call e...
52a0ca19b738576a5e42da9d720ec5a5118466fe
22,023
def read_external_sources(service_name): """ Try to get config from external sources, with the following priority: 1. Credentials file(ibm-credentials.env) 2. Environment variables 3. VCAP Services(Cloud Foundry) :param service_name: The service name :return: dict """ config = {} ...
a8008efecf6cbc8801022c9a99617480d50ad525
22,024
import torch def intersect(box_a, box_b): """ We resize both tensors to [A,B,2] without new malloc: [A,2] -> [A,1,2] -> [A,B,2] [B,2] -> [1,B,2] -> [A,B,2] Then we compute the area of intersect between box_a and box_b. Args: box_a: (tensor) bounding boxes, Shape: [A,4]. box_b: (tensor)...
96f67dd8ee1b40af469b5e40dc1f3456250451b3
22,025
import re def tokenize(text): """ tokenize text messages Input: text messages Output: list of tokens """ # find urls and replace them with 'urlplaceholder' url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' text = re.sub(url_regex, 'urlplaceholder'...
02c322b01b0af995030c007be634b7d3d1603518
22,026
import scipy import copy def peakFindBottom(x, y, peaks, fig=None, verbose=1): """ Find the left bottom of a detected peak Args: x (array): independent variable data y (array): signal data peaks (list): list of detected peaks fig (None or int): if integer, then plot results ...
dd79a4fd572f69f5db9adeaaf56ab4c8661c0ca1
22,027
def replacelast(string, old, new, count = 1): """Replace the last occurances of a string""" return new.join(string.rsplit(old,count))
6af2cd56cc43e92b0d398e8aad4e25f0c6c34ddd
22,028
def _safe_read_img(img): """ Read in tiff image if a path is given instead of np object. """ img = imread(img) if isinstance(img, str) else np.array(img) return np.nan_to_num(img)
a9a50b5ad76a6ed5833c2c149b1366b318814d6a
22,030
def max_version(*modules: Module) -> str: """Maximum version number of a sequence of modules/version strings See `get_version` for how version numbers are extracted. They are compared as `packaging.version.Version` objects. """ return str(max(get_version(x) for x in modules))
34ad9bd27591e3496e6a5a7e75dbf0191a8c077e
22,031
def load_secret(name, default=None): """Check for and load a secret value mounted by Docker in /run/secrets.""" try: with open(f"/run/secrets/{name}") as f: return f.read().strip() except Exception: return default
1aac980ad6bc039964ef9290827eb5c6d1b1455f
22,032
from operator import sub def snake_case(x): """ Converts a string to snake case """ # Disclaimer: This method is annoyingly complex, and i'm sure there is a much better way to do this. # The idea is to iterate through the characters # in the string, checking for specific cases and handling...
133ff68eb42e5e009fe2eee03d1e52f7d015732c
22,033
async def process_manga(data_list: list[dict], image_path: str) -> str: """对单张图片进行涂白和嵌字的工序 Args: data_list (list[dict]): ocr识别的文字再次封装 image_path (str): 图片下载的路径(同时也作为最后保存覆盖的路径) Returns: str: 保存的路径 """ image = Image.open(image_path).convert("RGB") for i in data_list: ...
47574e11067c00d3c5ab4110a7dae8100d450a1f
22,034
def padded_nd_indices(is_valid, shuffle=False, seed=None): """Pads the invalid entries by valid ones and returns the nd_indices. For example, when we have a batch_size = 1 and list_size = 3. Only the first 2 entries are valid. We have: ``` is_valid = [[True, True, False]] nd_indices, mask = padded_nd_indic...
61a57aa95c1d3151900aba3db07bba0eae542dfd
22,035
def part_two(data: str) -> int: """The smallest number leading to an md5 hash with six leading zeros for data.""" return smallest_number_satisfying(data, starts_with_six_zeros)
57195761f388654f9aa099162f337e8177e56111
22,036
def showlatesttag(context, mapping): """List of strings. The global tags on the most recent globally tagged ancestor of this changeset. If no such tags exist, the list consists of the single string "null". """ return showlatesttags(context, mapping, None)
e04b03a9dca54a93f450de676ea05c307f157dab
22,037
def list_filters(): """ List all filters """ filters = [_serialize_filter(imgfilter) for imgfilter in FILTERS.values()] return response_list(filters)
e43da929925872f5eefca5da2659052a1a48d442
22,038
def len_adecuada(palabra, desde, hasta): """ (str, int, int) -> str Valida si la longitud de la palabra está en el rango deseado >>> len_adecuada('hola', 0, 100) 'La longitud de hola, está entre 0 y 100' >>> len_adecuada('hola', 1, 2) 'La longitud de hola, no está entre 1 y 2' :para...
df217a0159cd04c76f5eb12ca42e651ee62fcd99
22,039
import warnings def ECEF_from_ENU(enu, latitude, longitude, altitude): """ Calculate ECEF coordinates from local ENU (east, north, up) coordinates. Args: enu: numpy array, shape (Npts, 3), with local ENU coordinates latitude: latitude of center of ENU coordinates in radians longit...
13561632731d59e40e4232f8dc2798e8dcd8067f
22,040