content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import functools def voice_only(fn): """A decorator that modifies a cog function command to require a sender to be in a voice channel. On failure, it'll notify the author with an error message. Note: discord.py checks would cause it to not show on the help function. So we do this instead. """ @fun...
f75cdf2ecc84d45166564945c06d98343b82c25d
665,466
def _to_string(val): """Convert to text.""" if isinstance(val, bytes): return val.decode('utf-8') assert isinstance(val, str) return val
16ec1789a0f79f7b6856557caee21b8b61696838
665,468
def get_model_top_scope_name(model_name, problem_name): """ Returns the top scope name of all models. Args: model_name: The model string. problem_name: The problem name. Returns: A str. """ if model_name is None: model_name = "SequenceToSequence" return problem_name or ...
b9ad22a9090b1588726d57246b3af467c2678647
665,477
def get_wildcard_constraints(image_types): """Return a wildcard_constraints dict for snakemake to use, containing all the wildcards that are in the dynamically grabbed inputs Parameters ---------- image_types : dict Returns ------- Dict containing wildcard constraints for all wildc...
63f6383f20c3229d34889fc3359ef93112adfadb
665,479
def _get_raw(platform: str, command: str) -> str: """Get raw cli output.""" command = str(command.replace(" ", "_")) with open( "tests/" + platform + "_" + command + "/" + platform + "_" + command + ".txt", "r", ) as structured: raw = structured.read() return raw
57eceb39f92daa5cc7e97cd2ec1a67cd7a670cc1
665,480
import torch def angle_axis_to_quaternion(angle_axis: torch.Tensor) -> torch.Tensor: """Convert an angle axis to a quaternion. Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h Args: angle_axis (torch.Tensor): tensor with angle axis. Return: torch.Tensor: tensor ...
e429c2d570e209741e143cb5992bb6a44e8fe80a
665,482
def t_evap(r, phi): """Return estimated evaporation time at T=293 K. - r: radius (m) - phi: relative humidity """ return 3.6e9 * r**2 / (1 - phi)
11e2ab7186b2402832674c0ba45f87c5b5ed8b07
665,483
def is_kanji(character): """ Return if the character is a kanji character """ return 0x4E00 <= ord(character) <= 0x9FBF or character == '々'
000a206352c6cf4f6df3d74ac822ec2c851536e3
665,488
def get_verbose_name(model, field): """ Get Django instance's field's verbose_name. """ return model._meta.get_field(field).verbose_name.title()
add17b7e4b48235b75b4b70b4ab0e95150f17119
665,490
def _has_method(obj, name): """ Check if the object has a method with that name Args: obj: the object name: the name of the method Returns: True if the object has a callable method with that name, otherwise False """ mth = getattr(obj, name, None) if mth is None: ...
2c0a2432e48184cfa7ac0792bee81ba2456cc01c
665,492
def replace(template, pattern, subst) : """If pattern in the template replaces it with subst. Returns str object template with replaced patterns. """ fields = template.split(pattern, 1) if len(fields) > 1 : return '%s%s%s' % (fields[0], subst, fields[1]) else : return templa...
46b544ac3edcc3e99b470ba8a780c8cad98b00c9
665,498
def _edge_mapping(G): """Assigns a variable for each edge in G. (u, v) and (v, u) map to the same variable. """ edge_mapping = {edge: idx for idx, edge in enumerate(G.edges)} edge_mapping.update({(e1, e0): idx for (e0, e1), idx in edge_mapping.items()}) return edge_mapping
6d3ec0d16f7483671a2a5fba779c015dd0e7edfc
665,499
import json def json_format(text: str) -> str: """Simple utility to parse json text and format it for printing. """ obj = json.loads(text) return json.dumps(obj, indent=4, sort_keys=True)
bc7e613287d23f1c51ec8c6c825b5422316d71a0
665,501
def get_all_followings(igapi, target_userid): """ Returns a list of {"username": "", "userid": 0, "is_private": false, "full_name": ""} """ following_list = [] current_followings_list = igapi.getTotalFollowings(target_userid) for following in current_followings_list: user = { ...
c428d2044071a2430b05e793d5ecbf5326479767
665,502
from typing import Any def flag(argument: Any) -> bool: """ Check for a valid flag option (no argument) and return :py:obj:`True`. Used in the ``option_spec`` of directives. .. seealso:: :class:`docutils.parsers.rst.directives.flag`, which returns :py:obj:`None` instead of :py:obj:`True`. :raises: :exc:`Va...
7aeb0b0ddf5b98cafebf868adbc95204518513db
665,503
import math def _calculate_label_rotation(startx, starty, endx, endy): """ Calculates the appropriate rotation angle for a label on an arrow (matches line, is between -90 and 90 degrees) :param startx: start of arrow (x) :param starty: start of arrow (y) :param endx: end of arrow (x) :param e...
45a4928102f040847e99c6983ccbff59aa2c841f
665,505
def object_info_as_dict(object_info): """Convert a KBase object_info list into a dictionary.""" [ _id, _name, _type, _save, _version, _owner, _ws, _ws_name, _md5, _size, _meta, ] = object_info return dict( ob...
1d2976b4026efdfa8988ca19695f8815075644eb
665,506
import random def random_promotion(data_objects, distance_function): """ Randomly chooses two objects to be promoted. """ data_objects = list(data_objects) return random.sample(data_objects, 2)
8a3e78b690e4db44d09adb07bf1c1e0aae7aa06e
665,507
def css_rgb(color, a=False): """Get a CSS `rgb` or `rgba` string from a `QtGui.QColor`.""" return ("rgba({}, {}, {}, {})" if a else "rgb({}, {}, {})").format(*color.getRgb())
f3f15c2c5fdb7317f679cc080b4f0c6fb343f45a
665,509
def _calc_basic_subreddit_stats(sr_about): """ :param dict sr_about: An unmarshalled sub-Reddit about.json 'data' dict. :rtype: tuple :returns: Tuple in the form of: sub_count, accounts_active """ sub_count = int(sr_about['subscribers']) accounts_active = int(sr_about['accounts_active']) ...
02a2e43fd0e8d80ee723a36044257793a0e64c10
665,510
def read_database(db, query, params): """ Execute query with params against the database. :param db: database connection :param query: str: query to execute :param params: [object]: list of parameters to use with query :return [object] rows returned from query """ rows = [] cur = db....
46fa9032f3762872f1d524d1c5c5e1dad07d7b0f
665,514
def match_shared(self, shared_length: int, shared_features: int) -> int: # pylint: disable=unused-argument """Calculate the size of the task variable to match the shared variable.""" return shared_length * shared_features
bac550d8920c5f170176610764837685819061be
665,515
def length(value): """ Find the length of a value :type value: variable :param value: The value to find the length of """ # Try to return the length return len(value)
a7d842f432743eb8cbab137d19fb4a9937af7021
665,516
def read_template(template_path): """Read template file. Args: template_path: template file path Returns: template file data """ with open(template_path, "r") as f: template_data = f.read() return template_data
85e2ae06fbf052fac9f03ca516d5fc5ee28d8319
665,518
import math def binomial(n, k): """Computes the binomial coefficient "n over k". """ if k == n: return 1 if k == 1: return n if k > n: return 0 return math.factorial(n) // ( math.factorial(k) * math.factorial(n - k) )
1f7a6e7709cb6adaf178a49fced2f1961f70ef87
665,520
def export_to_pascal(ibs, *args, **kwargs): """Alias for export_to_xml""" return ibs.export_to_xml(*args, **kwargs)
b7fd4d3c68e09f5665dd658c42fc297341fb0b1e
665,522
def daily_visit_count(user, count): """Returns True if the number of the user daily visit equals to count.""" return user.get_profile().daily_visit_count >= count
07fd9bbee88c0645929c22029bb4563e4238710e
665,524
def _remove_whitespaces_beginning_end_text(text: str) -> str: """ Removes whitespace from the beginning and end of the given text. """ return text.strip()
c8859388e4c60a7413363e1967f876c2714762ea
665,525
import math def is_relative_prime(num, larger_num): """Determine if num is a relative prime to larger_num.""" return math.gcd(num, larger_num) == 1
a71c00fc66b888723f8a681beda618c5fa899ee3
665,529
def _user_profile(user_profile): """ Returns the user profile object. For now, this just comprises the profile_image details. """ return { 'profile': { 'image': user_profile['profile_image'] } }
8952e86db5dfdf84442ff52f89b038a1b45e2351
665,530
from datetime import datetime def FindLatestTime(time_list): """Find latest time from |time_list|. The current status is compared to the status of the latest file in |RESULT_DIR|. Args: time_list: a list of time string in the form of 'Year-Month-Day-Hour' (e.g., 2011-10-23-23). Strings not in th...
9af56f4d0a3e2c51e0e038b47b450b106852cfe8
665,532
def is_proper_component_name(component): """Check if the component name is properly formatted.""" return "@" not in component and "/" not in component
51e26fa4074508b1f60988428806e1990c3d1f2b
665,534
def is_ssh_for_nimbus(env_config): """Check if we need to use SSH access to Nimbus or not.""" return env_config.get("use_ssh_for_nimbus", True)
8c6d31e131f04deeaf09d97c3dd046515795c9eb
665,536
import string def has_string_formatters(s): """ Determine if a string has ``{}`` operators. Parameters ---------- s : str The string to analyze. Returns ------- bool ``True`` if yes, ``False`` if no. """ assert isinstance(s, str), f'`s` of wrong type: {type(s)...
430d6f627690029e32eac3862c16bfee58b8aec6
665,538
def run_model(*params, return_preds=False, integrate=False): """ Given a model, loss function and daily death data, along with the parameters, run the model on these parameters. Arguments -------------- params : A list of parameters. The last three must be the model function, loss function a...
531854ca22ebb489da34980ba6143ce01751cf6a
665,544
import re def replace_spaces(some_string): """ Substitute spaces with underscores""" return re.sub(" ", "_", some_string)
23f6bb9079ec92afc97f1da1aa0c0eec8af512c8
665,548
def get_all_constraints(max_domain_val): """ Purpose: get all binary constraints of the form xi,xj and put them in a list. To save space, we just put the row and column indices in the list. @param max_domain_val int, The dimensions of each side of the square board @return constraints list of t...
bfe57d948aca3dbcdc61b8736e1aac9918346502
665,549
def tier_count(count): """ If a tier quota is 9999, treat it as unlimited. """ if count == 9999: return "Unlimited" else: return count
dc702e930377d1533fbacf434a2acd0ddfefc457
665,552
def get_card_split(df, cols, n=11): """ Splits categorical columns into 2 lists based on cardinality (i.e # of unique values) Parameters ---------- df : Pandas DataFrame DataFrame from which the cardinality of the columns is calculated. cols : list-like Categorical columns to lis...
91cfd36af62cb7b88be44fe9cd3ea292e61c141e
665,553
def degrees_to_cardinal(degrees): """Convert degrees >= 0 to one of 16 cardinal directions.""" CARDINALS = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"] if degrees < 0: return None i = (degrees + 11.25)/22.5 return CARDINALS[int(i % 16)]
2c0032be80da7cbf9b7c5ca2236d393cc519a4f5
665,554
def get_401_error_hint(ctx, opts, exc): """Get the hint for a 401/Unauthorised error.""" # pylint: disable=unused-argument if opts.api_key: return ( 'Since you have an API key set, this probably means ' 'you don\'t have the permision to perform this action.') if ctx.info...
e115e102570447fd685f4e62a0b0551077a5982f
665,555
def model_summary(model): """Return a summary of Keras model intance. Args: model (Keras model instance): A Keras model instance. Returns: str: A summary for the model. """ summary = model.summary() return summary
c01a142d8387cae0fd7e864c194109f1b770cc7d
665,556
import hashlib def sha(data): """hashes data Args: data (bytes): the data to hash """ sha2 = hashlib.sha256() sha2.update(data) return sha2.digest()
2eca70d990c85779de22807508ab4e3fb193213c
665,559
def build_tree(elems, root, currentkey, parentkey): """ Constructs a hierarchic tree from a flat dictionary. https://stackoverflow.com/questions/35452512/construct-hierarchy-tree-from-python-flat-parent-children-dict-list :param elems: flat dictionary :param root: root node of current recursion :p...
60d21e56027a2b396d5f58e466ea58786135268d
665,566
def match_strings(str_in, match_list): """ Check if any of a list of strings is found in another string. str_in input string. match_list list of strings to find in str_in. returns True if a match is found and False if no match is found. """ for match in match_list: if match i...
a8a977304c0f85858a7c89c75299c5630849fd53
665,568
def parse_destination(phone_number, destinations): """Find the matching destination for a phone number. Args: phone_number: a string number with no leading '+' destinations: a list of Destination instances Returns: a Destination instance or None if the prefix wasn't found. """ # ...
bab6e6e17196a7ab5a624bb799c9bb700bff852e
665,569
def bedl_matches_vcf(variant, line_split: list) -> bool: """ Consecutive checks of whether the chromosome, start position and repeat unit in the supplied variant and (split + stripped) bedl line match. If all matches, return True, otherwise return False """ if not line_split[0] == variant.CHROM: ...
c8950677bdfab2152314acf95138662de6e373d1
665,570
def add_try_clause(code, excpt): """Add a try/except clause, excepting 'excpt' around code.""" code = code.replace('\t', ' ') return ("try:\n" + '\n'.join([" " + line for line in code.split('\n')]) + "\nexcept " + excpt.__name__ + ":\n pass")
5863fcf0c8f8af426425c982042d3d05a0ab497e
665,571
def recursive_binomial_coefficient(n, k): """Calculates the binomial coefficient, C(n,k), with n>=k using recursion Time complexity is O(k), so can calculate fairly quickly for large values of k. >>> recursive_binomial_coefficient(5,0) 1 >>> recursive_binomial_coefficient(8,2) 28 >>> recu...
07af2d622d91228eb370d6074c43702c10fdede6
665,572
def check_file(df): """Check a file format for correct column names and structure""" if not all(x in df.columns for x in ["image_path", "xmin", "xmax", "ymin", "ymax", "label"]): raise IOError( "Input file has incorrect column names, the following columns must exist 'image_pa...
f1eb49ef1b08b4e538979897d6848b5f80e9713b
665,576
def sort_by_numnodes(node): """ Sort by number of nodes. """ return len(node.nodes)
476d20c55c109faf6a3622dd598fcc1e63617293
665,580
def MostSimilar(caseAttrib, queryValue, weight): """ Most similar matches using ES default (works for all attribute types). Default similarity for strings and exact match for other types. """ # build query string query = { "match": { caseAttrib: { "query": queryValue, "boost": weight, "_name": "...
3d6b1e199208b24f7228066ffbcda89cb26aecbd
665,583
def split_data(dataframe): """ Split the dataset into features and labels Parameters ---------- dataframe : the full dataset Returns ------- features : the features of the dataset labels : the attack flag label of the dataset """ label = ...
99f982def66318f3ab40de5cb868cce6548f19f8
665,585
def is_instance_or_subclass(val, class_): """Return True if ``val`` is either a subclass or instance of ``class_``.""" try: return issubclass(val, class_) except TypeError: return isinstance(val, class_)
a8b008e9fa877647a02723d950006f6123e27ec3
665,586
def require_atlas(f): """Decorator that ensures a subject (the first argument) is from the ATLAS survey. """ def g(subject, *args, **kwargs): if subject['metadata']['survey'] != 'atlas': raise ValueError('Subject not from ATLAS survey.') return f(subject, *args, **kwargs) ...
1fe2e88ae190ffde179e1c2f5945604f235c9382
665,589
def add2(a, b): """ Test coverage with docstring >>> add2(1, 2) 3 """ return a + b
d3060a5d7b010497557ac3a03aab9c51e75470a5
665,590
def rl_decode(buf): """ Uncompresses the buffer by adding the correct number of 1s identified by the digit after 0 (since 0 indicates a repeated character when the original compression is performed). """ decoding = [] for index, char in enumerate(buf): if char == 0: for repeats in range(buf[index+1]):...
9ddf93dda96f157f9fdb0d8aa05b83305f011506
665,594
def _make_choices_from_int_list(source_list): """ Converts a given list of Integers to tuple choices. Returns a dictionary containing two keys: - max_length: the maximum char length for this source list, - choices: the list of (value, value) tuple choices. """ _choices = [] for value in...
49f49946512249d6fb879fc31aac49eb55cdfc2e
665,595
def readlines_without_newlines(path): """ Read file into a list of lines, this exists because open(path).readlines() will preserve trailing newlines """ with open(path) as file: return [line.strip() for line in file]
b050d61fdcde4f6f724c7089e3b947b02f6c7771
665,597
from typing import List import json def _parse_str_list(string: str) -> List[str]: """ Parse a list of string from string like "['a', 'b', 'c']" or those separated by \n :param string: string like "['a', 'b', 'c']" or those separated by \n :return: a list of string """ try: res = json....
68ee3e8508b09a5d95656eedeb13af0a582f7028
665,602
from typing import Union import uuid def get_cache_key_for_site(site_uuid: Union[str, uuid.UUID]): """ Get the cache key for a site. """ return 'site_config_client.backend.{site_uuid}'.format( site_uuid=site_uuid, )
03e24116cbafcc215e07a1c529613451953113e9
665,604
def add_node_ids(node): """ Adds node IDs to the tree (the recursive Python dict) in a breadth-first fasion. Arguments: node -- the root node for the tree Returns: the same tree (Python dict), but with a new key for each node (the ID) """ nodes_to_explore = [node] counter ...
a7273edaeca3ea97b841c90142014e7ad511ed42
665,605
def contains_whitespace(text): """ Returns True if there are any whitespace characters in the string """ return any(x.isspace() for x in text)
1fdd1c1c5d4f36e62365e7729e9332fed491b12e
665,611
def guess_content_type(name): """Return the content type by the extension of the filename.""" if name.endswith(".jpg"): return "image/jpg" elif name.endswith(".jpeg"): return "image/jpeg" elif name.endswith(".png"): return "image/png" elif name.endswith(".gif"): retur...
3f6681e1df2384e3fcba58eda436cb31c3e8d18c
665,613
def h1(text): """h1 tag >>> h1('my heading') '<h1>my heading</h1>' """ return '<h1>{}</h1>'.format(text)
19bed612f8ff77146df14cff197a846cab58ff8c
665,619
def find_verb(sent): """Pick a candidate verb for the sentence.""" verb = None for word, part_of_speech in sent.pos_tags: if part_of_speech.startswith('VB'): # This is a verb verb = word break return verb
1d54a2d717a06176a6f53b4f8be0c27be16a4db2
665,629
def deal_with_out_boundary(img): """ Deal with the outlier. :param img: input image. :return: image without outlier. """ img[img > 255.] = 255. img[img < 0.] = 0. return img
9dc8549183adab719b7e9b557e9b99b8f91b18b8
665,638
def is_this_list(lst: list, count: int) -> bool: """ Returns true iff the list is not empty and the last item of the list equals the 'count' :param lst: :param count: :return: """ return len(lst) > 0 and lst[-1] == count
542bcc31e68728e75ad6ae301ee8a7b7a9beffa8
665,652
def open_no_nl(filepath, mode="r"): """Open a file for reading without translating newlines.""" return open(filepath, mode, newline="")
5412cd2f84c552a38e6d350ff81863b9176251f4
665,653
def apply_polynomial(coeff, x): """Given coefficients [a0, a1, ..., an] and x, compute f(x) = a0 + a1*x + ... + ai*x**i + ... + an*x**n. Args: coeff (list(int)): Coefficients [a0, a1, ..., an]. x (int): Point x to on which to evaluate the polynomial. Returns: int: f(x) = a0 + a...
08bc04ca19b9289b726fec0b9ad832470709270d
665,654
def limit_speed(speed): """Limit speed in range [-900,900].""" if speed > 900: speed = 900 elif speed < -900: speed = -900 return speed
5ad91ce28264e5aa127b9c8be22697a23dc8327a
665,655
def decomposition(x): """ Return the decomposition of ``x``. EXAMPLES:: sage: M = matrix([[2, 3], [3, 4]]) sage: M.decomposition() [ (Ambient free module of rank 2 over the principal ideal domain Integer Ring, True) ] sage: G.<a,b> = DirichletGroup(20) ...
9ce34f0e57c2729a8ffe631230c1da71d9676cd1
665,660
def _sum_ft(tensor): """sum over the first and last dimention""" return tensor.sum(dim=0).sum(dim=-1)
5102e22efa399bfdf9e090f0a8e825fc65290fef
665,661
import torch def _get_anchor_negative_triplet_mask(labels): """Return a 2D mask where mask[a, n] is True iff a and n have distinct labels. Args: labels: torch.Tensor with shape [batch_size] Returns: mask: Variable with torch.ByteTensor with shape [batch_size, batch_size] """ # Chec...
a00bd917946886f7d8586bf6fe92f31b0c8b1891
665,662
def bool_as_int(val: object) -> str: """Convert a True/False value into '1' or '0'. Valve uses these strings for True/False in editoritems and other config files. """ if val: return '1' else: return '0'
d931e992fbb0d4baa5dbd2d7d2643d82a74590bf
665,665
import re def pack_article(article_raw): """ article preprocessing, splitting paragraphs :param article_raw: article as string :return: list of paragraphs """ article = list() article_split = re.split(r'(?<=>)(.+?)(?=<)', article_raw) ## parse articles (no tags) for p in range(1,...
89f811ce43ace325bb38c98b8121ab3584d0a398
665,666
def read_file(fname): """Read file and return the its content.""" with open(fname, "r") as f: return f.read()
e802fbb4574b2d25c4b7d48f60e8a248c5f1f050
665,669
def get_config_file_needed(args): """ Determines whether or not we need to fetch additional config variables from a file. """ return not (args.project_name and args.source_dir and args.data_dir and args.volumes_dir)
e5ad6c8a67cab488b519e2e7eeca812cd7851f9a
665,673
def mastinMER(H, DRE = 2500): """Calculates Mass Eruption Rate (MER) using Mastin et al. 2009 equation. Input is height (km), dense rock equivalent (DRE) (kg/m^3). dV = volumetric flow rate (m^3/s) Output is MER (kg/s). Optional input is DRE""" p=1/0.241 dV=(H/2.00)**p MER=dV*DRE return...
33e5229044560e412ba9ae2d80721bacbe094085
665,677
def _set_vmin_vmax(d, cbrange): """Set minimum and maximum values of the color map.""" if 'vmin' not in d.keys(): d['vmin'] = cbrange[0] if 'vmax' not in d.keys(): d['vmax'] = cbrange[1] return d
90b7e22fd3f340a0ff1c04729eef11ffb532dd23
665,679
def get_param(request, name, default_value=None): """ Return required request param, or default_value if not found. """ if request.body: if default_value is None: # This is required. if request.POST: # Must be a form POST. return request.POST[name...
3c1dc61ab01fa58646fe5dbb218979352833be4c
665,683
def save_userLUT(voidef, out_lut_file): """ Save look-up table for user-defined VOI. Format for outputted table: |user VOI No.|user VOI name| """ df = voidef[["user VOI No.", "user VOI name"]] df2 = df.drop_duplicates(["user VOI name"]) df2.to_csv(out_lut_file, index=False, sep=" ...
1af47899adecfe904f65b962794f19b186476897
665,685
import six import re def _replace_series_name(seriesname, replacements): """Performs replacement of series name. Allow specified replacements of series names in cases where default filenames match the wrong series, e.g. missing year gives wrong answer, or vice versa. This helps the TVDB query get the...
a5373553fb6a8f4a59801503a806828a953ba63f
665,690
def is_experimental_class(klass): """ Test CIM compoments of the klass parameter and if any have the experimental qualifier and its value is True return True. Otherwise return False Parameters: klass :class:`~pywbem.CIMClass`: The CIMClass to test for the experimental qualifier Retur...
a98771dd3e5d5e5200ada71a9c8285e1ea82c526
665,693
def long2base(n, q): """ Maps n to a list of digits corresponding to the base q representation of n in reverse order :param int n: a positive integer :param int q: base to represent n :return: list of q-ary 'digits', that is, elements of {0,1,..,q-1} :rtype: list""" lt = [] while n > 0: ...
eda623195285685e91583f0caa51fa5c8158b326
665,696
def not_found(request): """ This is the view that handles 404 (not found) http responses """ request.response.status_int = 404 return { 'url': request.resource_url(request.root) }
be166a3763abfdf14f5120c01538359747f1d189
665,697
def assign_assumed_width_to_province_roads_from_file(asset_width, width_range_list): """Assign widths to Province roads assets in Vietnam The widths are assigned based on our understanding of: 1. The reported width in the data which is not reliable 2. A design specification based understanding of the ...
afe1f7e19423802739c844952b244dc4f2c85eca
665,699
def calculate_mturk_cost(payment_opt): """MTurk Pricing: https://requester.mturk.com/pricing 20% fee on the reward and bonus amount (if any) you pay Workers. HITs with 10 or more assignments will be charged an additional 20% fee on the reward you pay Workers. Example payment_opt format for paying r...
8bbfb58031d884371d19c95755683c67ed6d6fdb
665,705
from typing import Dict def dict_union(*args: Dict) -> Dict: """ Unite two or more dicts into one. Results in a new dict. >>> dict_union({'a': 1}, {'b': 2}) {'a': 1, 'b': 2} """ new_dict = {} for dict_ in args: new_dict.update(dict_) return new_dict
b771224cb777d812a7b81810ff9c1c5ebc1039f4
665,706
def assign_linux_server_policy(api, configuration, api_version, api_exception, computer_id): """ Assigns a Linux server policy to a computer. :param api: The Deep Security API modules. :param configuration: Configuration object to pass to the api client. :param api_version: The version of the API to us...
92b00c7bd666265119651c0d05b3a318d130e316
665,707
def _df_elements(df): """Yields all the values in the data frame serially.""" return (x for row in df.itertuples() for x in row)
6b9ae811693539f374e3125f870788c574a7eb79
665,708
from typing import OrderedDict def filter_graph(dictionary, include_keys): """ Create new list that contains only values specified in the ``include_keys`` attribute. Parameters ---------- dictionary : dict Original dictionary include_keys : list or tuple Keys that will co...
abdd07ef374a85718ac54319a1f982cf3043a28e
665,709
def _get_collapsed_course_and_dist_req_sets(req): """ Returns the sets of all courses and all distribution requirements in req's subtree as a tuple: (course_set, dist_req_set) Note: Sets may contain duplicate courses if a course is listed in multiple different ways """ if "course_list" i...
8ad1e36d40d751f06e380a73845cf5d082f1afe9
665,710
from typing import List def get_required_cols(geom_type: str, columns: List[str]) -> List[str]: """Get the required columns for a given geometry type.""" req_cols = ["id", geom_type, "dates", "region"] for var in ["time_scale", "pet", "alpha"]: if var in columns: req_cols.append(var) ...
8861004e54a4d741c9727b268164c87e9a091f12
665,712
def parse_spinsolve_par_line(line): """ Parse lines in acqu.par and return a tuple (paramter name, parameter value) """ line = line.strip() # Drop newline name, value = line.split("=", maxsplit=1) # Split at equal sign (and ignore further equals in attribute values) # remove spaces name =...
0f35597c5eb47205a4f8c880574b2ab187c82d94
665,713
def create_sloping_step_function(start_x, start_y, end_x, end_y): """ create sloping step function, returning start y-value for input values below starting x-value, ending y-value for input values above ending x-value and connecting slope through the middle :param start_x: float starting x-...
67c8778a9aaba03cb7847de59dd018e128876ba0
665,715
def is_crud(sql): """Check that given sql is insert , update, delete or select :param sql: Sql string to check for is_crud :return: Boolean result """ crud = ['insert', 'update', 'delete', 'select'] if not isinstance(sql, str): raise TypeError('`sql` argument is not valid. `sql` must...
0639b370404ae1e7488124000be0d0963e8484cf
665,719
def is_table(cur, table_name): """ Simple check to see if table exists or not :param cur: cursor :param table_name: str - name of table :return: True/False """ sql_command = f"SELECT EXISTS ( SELECT FROM information_schema.tables WHERE table_name = '{table_name}' );" cur.execute(sql_comm...
0cdf2138a6ed1c9a6c698790e889cdaf20aa8bf3
665,722
def generic_mon_cb(source, signal): """ Create a generic callback for sending a signal from source value. :param source: Object representing the EPICS PV data source. This object needs to be properly initialized and monitored. :type source: Pv :param signal: Signal to send the v...
6bc3c67681d7c46c57fa6911438b4aeedf137deb
665,724
import uuid def _make_job_id(job_id, prefix=None): """Construct an ID for a new job. :type job_id: str or ``NoneType`` :param job_id: the user-provided job ID :type prefix: str or ``NoneType`` :param prefix: (Optional) the user-provided prefix for a job ID :rtype: str :returns: A job ID...
9d710f7103adc3a77f6f07d8d3d61877b360723c
665,725