content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def ignore_answer(answer): """ Should this answer be disregarded? """ return (answer == "<Invalid>") or \ answer.startswith("<Redundant with")
4ef4e55bae942d4c33b5fe1f4e6f9b339c332e92
315,004
import logging import time def execute_trade(market, action): """ Makes a trade via the API and responds once completed. May have multiple retrys before raising exception if it failed. Likely steps: 1. Initialise the trading API 2. Post trade to the API 3. Confirm success in response or retry if it failed 4. Return the response once successful Returns: dict of trade_information or raises Exception """ logging.info(f"{market} - Posting {action} trade.") time.sleep(5) logging.info(f"{market} - {action} trade successful.") return {"success": True, "trade_details": {}}
63bc6bf5d74fca5d242fd337c1cec8298d2a6626
445,946
def positive_negative(inputlist): """ return true if all items in the input list having same sign (+ or -)""" if ((all(item>0 for item in list(inputlist))) or (all(item<0 for item in list(inputlist)))): return True # elements with same sign (+ or -) else: return False
69ebde6129139f5212d50891b4b81c0a5a76d51f
576,430
import time def pretty_epoch(epoch, format_): """ Convert timestamp to a pretty format. """ return time.strftime(format_, time.localtime(epoch))
7cb0fd5185020da7e3c59592e8a476ecc0ff7046
429,617
import time async def bench_to_arrow(client): """Test how long it takes to create a view on the remote table and retrieve an arrow.""" table = client.open_table("data_source_one") view = await table.view() start = time.time() arrow = await view.to_arrow() end = time.time() - start assert len(arrow) > 0 return [end]
dccf9efc0516dc2774d886ec64182b85de97e428
102,328
def _xlRange_from_corners(xlWorksheet, r1, c1, r2, c2): """Get excel Range for (row1,column1) to (row2, column2), inclusive.""" return xlWorksheet.Range(xlWorksheet.Cells(r1,c1), xlWorksheet.Cells(r2,c2))
ced64e630adb07de1f4447a42afc08b3672efadb
467,878
def _is_version_range(req): """Returns true if requirements specify a version range.""" assert len(req.specifier) > 0 specs = list(req.specifier) if len(specs) == 1: # "foo > 2.0" or "foo == 2.4.3" return specs[0].operator != '==' else: # "foo > 2.0, < 3.0" return True
c0602a1b28d787d93897f8380e34ee683cc95ad0
640,911
import re def valid_mac_address(addr): """Validate a physical Ethernet address""" return re.match("[0-9a-f]{2}([-:][0-9a-f]{2}){5}$", addr.lower())
033ee7ccb4a2a4f5cca96f896a6c72ca26351377
539,428
import hashlib def _file_hash(filename: str) -> str: """Compute the hash of a file. Args: filename: the filename to hash. Returns: The hash hex string of the file contents. """ sha256_hash = hashlib.sha256() with open(filename, "rb") as f: # Read and update hash string value in blocks of 4K while True: l: bytes = f.read(4096) if not l: return sha256_hash.hexdigest() sha256_hash.update(l)
a3d1860701c5ea59807930929ccfcbccde6e6e18
454,247
def episode(sim, agent, params): """Builds an episode graph using a Simulator and an Agent Args: sim: a Simulator object agent: an Agent object params: application level constants Returns: (a_ts, q_ts) a_ts: (batch_size, num_actions)[time_steps], tf.int32, the chosen actions q_ts: (batch_size, num_actions)[time_steps], tf.float32, expected future return for each action """ a_ts = [] q_ts = [] for t in range(params.time_steps): o_ts = sim.get_observation() a_t, q_t = agent.next_action(o_ts) a_ts.append(a_t) q_ts.append(q_t) sim.do_step(a_t) return (a_ts, q_ts)
85c29ec80830ad1863ac75286b12208c5819d96e
159,448
def parse_distance(distance): """parse comma delimited string returning (latitude, longitude, meters)""" latitude, longitude, meters = [float(n) for n in distance.split(',')] return (latitude, longitude, meters)
954ef035e5aa5fa7965285622b5916ac1d51ac99
677,698
import re def escape(toencode): """URL-encode data.""" if toencode is None: return None return re.sub(r"[^a-zA-Z0-9_.-]", lambda m: "%%%02x" % ord(m.group()), str(toencode))
bc82512b9d5f23b8aa1a86d1db8c1278c5278738
497,701
def compress(traj, copy=True, **kwds): """Wrapper for :meth:`Trajectory.compress`. Parameters ---------- copy : bool Return compressed copy or in-place modified object. **kwds : keywords keywords to :meth:`Trajectory.compress` Examples -------- >>> trc = compress(tr, copy=True, forget=['coords']) >>> trc.dump('very_small_file.pk') """ if copy: out = traj.copy() else: out = traj out.compress(**kwds) return out
42ebefdddeaecd67f61dd884dab31a3ec7f864c9
26,823
def notfound(request): """Handle a request for an unknown/forbidden resource.""" request.response.status_int = 404 return {}
13693e24ba677e5095e7de651f7e85950502699c
159,223
import torch def dual_complete(u, v, s, alpha, beta, eps): """ min_{u>=0, v<=0} d(u, v) = E_xy [ u(x)alpha(x) + v(y)beta(y) + Softplus(1/eps)(s-u-v) ] """ u = torch.as_tensor(u, device=s.device).reshape((-1, 1)) v = torch.as_tensor(v, device=s.device).reshape((1, -1)) if eps > 0: sp = torch.nn.Softplus(1. / eps)(s - u - v) else: sp = torch.nn.ReLU()(s - u - v) return (u * alpha).mean() + (v * beta).mean() + sp.mean()
d0008182434509a7192495519373882f2c1f1e67
103,347
import uuid def create_hook_name(name=""): """ Utility to create a unique hook name. Optionally takes in a name. The output string is the name prefixed with a UUID. This is useful to prevent collision in hook names when one class with hooks inherits hooks from another class Example: >>> create_hook_name() >>> '7087eefc-8e94-4f0a-b7d3-453062bb7a34' >>> create_hook_name('my_hook') >>> '7087eefc-8e94-4f0a-b7d3-453062bb7a34:my_hook' Args: name (Optional[str]): Name of the hook """ prefix = str(uuid.uuid4()) return "{}:{}".format(prefix, name)
a7c72abc91cbe1395a5115388834d4cf7de40e8f
314,673
def permutation_from_disjoint_cycles(cycles, offset=0): """Reconstruct a permutation image tuple from a list of disjoint cycles :param cycles: sequence of disjoint cycles :type cycles: list or tuple :param offset: Offset to subtract from the resulting permutation image points :type offset: int :return: permutation image tuple :rtype: tuple """ perm_length = sum(map(len, cycles)) res_perm = list(range(perm_length)) for c in cycles: p1 = c[0] - offset for p2 in c[1:]: p2 = p2 - offset res_perm[p1] = p2 p1 = p2 res_perm[p1] = c[0] - offset #close cycle assert sorted(res_perm) == list(range(perm_length)) return tuple(res_perm)
3c992f3612340e94e569b81be9195f79de8f864e
587,045
def _decode_mask(mask): """splits a mask into its bottom_any and empty parts""" empty = [] bottom_any = [] for i in range(32): if (mask >> i) & 1 == 1: empty.append(i) if (mask >> (i + 32)) & 1 == 1: bottom_any.append(i) return bottom_any, empty
6b93a30881ed526e801b4ad55c4a04af5562d8b6
73,741
import logging import requests import json def add_intersight_resource_group(AUTH, MOIDS, CLAIM_CONFIG): """ Create an Intersight Resource Group for Claimed Devices """ request_body = { "Name":CLAIM_CONFIG['partner_id'] + "-rg", "Qualifier":"Allow-Selectors", "Selectors":[ { "Selector": ( "/api/v1/asset/DeviceRegistrations?$filter=Moid in('" + ",".join(MOIDS) + "')" ) } ] } logging.info(request_body) response = requests.post( CLAIM_CONFIG['intersight_base_url'] + 'resource/Groups', data=json.dumps(request_body), auth=AUTH ) logging.info(response.text) response_json = response.json() logging.info("RESOURCE GROUP: " + response_json["Moid"]) return response_json["Moid"]
b8d7653886b9ee2468eba447a452d625b9c6db0b
285,273
import json def read_config_file(fpath): """Create a dictionary of settings based on the json config file.""" with open(fpath) as input_file: cfg = json.load(input_file) return cfg
1ea6fd5ef952626adbef55cd85fd62c6aa191b5f
287,255
def returner( argument ): """ A module function that returns what you give it """ return argument
29384104d99d6cbc10fc10cc9b0b0a78a2c72b53
131,422
def get_first_aligned_bp_index(alignment_seq): """ Given an alignment string, return the index of the first aligned, i.e. non-gap position (0-indexed!). Args: alignment_seq (string): String of aligned sequence, consisting of gaps ('-') and non-gap characters, such as "HA-LO" or "----ALO". Returns: Integer, >= 0, indicating the first non-gap character within alignment_seq. """ index_of_first_aligned_bp = [i for i,bp in enumerate(alignment_seq) if bp != '-'][0] return index_of_first_aligned_bp
d16331cb0cf6e94cfcb8aa04730520aeec915480
682,367
import time def wait_release(text_func, button_func, menu): """Calls button_func repeatedly waiting for it to return a false value and goes through menu list as time passes. The menu is a list of menu entries where each entry is a two element list of time passed in seconds and text to display for that period. Text is displayed by calling text_func(text). The entries must be in ascending time order.""" start_t_ns = time.monotonic_ns() menu_option = None selected = False for menu_option, menu_entry in enumerate(menu): menu_time_ns = start_t_ns + int(menu_entry[0] * 1e9) menu_text = menu_entry[1] if menu_text: text_func(menu_text) while time.monotonic_ns() < menu_time_ns: if not button_func(): selected = True break if menu_text: text_func("") if selected: break return (menu_option, (time.monotonic_ns() - start_t_ns) * 1e-9)
63ac22a0fd9ed4eb4fcabeb54b37f55755a79ad1
247,498
import math def compute_air_distance(_src, _dst): """Compute Air Distance based on latitude and longitude input: a pair of (lat, lon)s output: air distance as km """ distance = 0.0 if _src == _dst: return distance radius = 6371.0 # km dlat = math.radians(_dst[0] - _src[0]) dlon = math.radians(_dst[1] - _src[1]) a = math.sin(dlat / 2.0) * math.sin(dlat / 2.0) + \ math.cos(math.radians(_src[0])) * \ math.cos(math.radians(_dst[0])) * \ math.sin(dlon / 2.0) * math.sin(dlon / 2.0) c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1.0 - a)) distance = radius * c return distance
856b1b1e8c720625daa73f511fe841429d9e47f7
148,177
import random def sample_baselines(bls, seed=None): """ Sample a set of baselines with replacement (to be used to generate a bootstrap sample). Parameters ---------- bls : list of either tuples or lists of tuples Set of unique baselines to be sampled from. If groups of baselines (contained in lists) are provided, each group will be treated as a single object by the sampler; its members will not be sampled separately. seed : int, optional Random seed to use if randomize=True. If None, no random seed will be set. Default: None. Returns ------- sampled_bls : list of tuples or lists of tuples Bootstrap-sampled set of baselines (will include multiple instances of some baselines). """ if seed is not None: random.seed(seed) # Sample with replacement; return as many baselines/groups as were input return [random.choice(bls) for i in range(len(bls))]
e53c66141fa4a90b6d74d64d59ecfae112d93d67
577,109
def get_w_gen_d_t(w_gen_MR_d_t, w_gen_OR_d_t, w_gen_NR_d_t): """(65a) Args: w_gen_MR_d_t: 日付dの時刻tにおける主たる居室の内部発湿(W) w_gen_OR_d_t: 日付dの時刻tにおけるその他の居室の内部発湿(W) w_gen_NR_d_t: 日付dの時刻tにおける非居室の内部発湿(W) Returns: 日付dの時刻tにおける内部発湿(W) """ return w_gen_MR_d_t + w_gen_OR_d_t + w_gen_NR_d_t
8166ea84c0adca839397fac35ee74d809bfe4b95
94,306
def ne(x, y): """Not equal""" return x != y
9e8f60889705122d0a6f98febdc689983a9e4cbf
640,071
import json def get_manageiq_config_value(module, name): """ Gets the current value for the given config option. :param module: AnsibleModule making the call :param name: ManageIQ config option name :return: dict of value of the ManageIQ config option """ returncode, out, err = module.run_command([ "rails", "r", "puts Vmdb::Settings.for_resource(MiqServer.my_server)[:%s].to_json" % (name) ], cwd=module.params['vmdb_path']) if returncode != 0: raise Exception("Error getting existing value for ':%s' config: %s" % (name, err)) return json.loads(out)
9e8d6c4afb5e7d962925c2b568836a04637c2c4b
299,955
def _start_lt_end(params): """Check that 'start' param is < 'end' param if both params are found in the provided dict. In-place edit of params. Parameters ---------- params : dict {param_ID:param_value} """ if ('start' in params) & ('end' in params): try: startVal = float(params['start']) endVal = float(params['end']) except TypeError: return None if startVal > endVal: params['start'] = endVal params['end'] = startVal elif startVal == endVal: # start-end cannot == if endVal >= 100: params['start'] = startVal - 1e-10 else: params['end'] = endVal + 1e-10
23379d1fbc443bd453b9239c971cda15efa7c05a
140,429
import requests def _post_request(url, token, body=None): """ Send a requests.post request :param url: URL :param token: authorization token :param body: body to be sent with request :return: json of response """ headers = { 'Authorization': 'bearer ' + token } if body is None: res = requests.post(url, headers=headers) else: res = requests.post(url, headers=headers, data=body) if res.status_code == 200: pass else: pass return res.json()
adb1923bb18f21b98356bc4bc7fd7e79b59e2dfb
84,893
def maybe(string): """ A regex wrapper for an arbitrary string. Allows a string to be present, but still matches if it is not present. """ return r'(?:{:s})?'.format(string)
ce86a3ef9c42df184954aabed43634370816b3ed
451,189
def HasPackedMethodOrdinals(interface): """Returns whether all method ordinals are packed such that indexing into a table would be efficient.""" max_ordinal = len(interface.methods) * 2 return all(method.ordinal < max_ordinal for method in interface.methods)
6c52e6ca065664480f3f32ac79906f9a9906b57e
636,564
import requests def get_resource(url, params=None, timeout=20): """Initiates an HTTP GET request to the SWAPI service in order to return a representation of a resource. Parameters: url (str): a url that specifies the resource. params (dict): optional dictionary of querystring arguments. timeout (int): timeout value in seconds Returns: dict: dictionary representation of the decoded JSON. """ if params: response = requests.get(url, params=params, timeout=timeout).json() else: response = requests.get(url, timeout=timeout).json() return response
411070c6795cf47a1cf2cee418043ebca1a1bace
452,299
import torch def split_train_test(X, y, train_size=0.8, shuffle=True): """ Split data into training and testing sets Parameters: X (Tensor): The input data y (Tensor): The labels train_size (float): The fraction of data used for the training shuffle (boolean): Whether to randomly shuffle data before splitting Returns: Tensor: The training data Tensor: The training labels Tensor: The testing data Tensor: The testing labels """ if shuffle: perm = torch.randperm(X.size(0)) X = X[perm] y = y[perm] cut = int(train_size * X.size(0)) X_train = X[:cut] y_train = y[:cut] X_val = X[cut:] y_val = y[cut:] return X_train, y_train, X_val, y_val
699615ca3ea8adb932aef457db8c13724cb5e73a
410,303
from typing import List def orderings3() -> List[List[int]]: """Enumerates the storage orderings for an input with rank 3.""" return [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]
6f67a43903c070fc0d650ca6826945dffee9ac96
162,801
def _IsOutsideTimeRange(timestamp, time_range = None): """Returns a boolean indicating whether a timestamp is in a given range.""" return time_range is not None and (timestamp < time_range[0] or timestamp > time_range[1])
05b72d28607b74f0b71517381583ca88dde0efc5
636,704
def sort_io_dict(performance_utilization: dict): """ Sorts io dict by max_io in descending order. """ sorted_io_dict = { 'io_all': dict(sorted(performance_utilization['io'].items(), key=lambda x: x[1], reverse=True)) } performance_utilization.update({**sorted_io_dict}) del performance_utilization['io'] return performance_utilization
86e30398d810b23b46f598926a08da62b1d3260d
376,696
import jinja2 def create_jinja2_template_env(searchpath: str = "./templates") -> jinja2.Environment: """ Creates a usable template environment for Jinja2. """ return jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath=searchpath))
7c9f2354ab32798de73c5d8b45a7042efb0b15f3
353,064
def format_speak_tags(sentence: str, include_tags: bool = True) -> str: """ Cleans up SSML tags for speech synthesis and ensures the phrase is wrapped in 'speak' tags and any excluded text is removed. Args: sentence: Input sentence to be spoken include_tags: Flag to include <speak> tags in returned string Returns: Cleaned sentence to pass to TTS """ # Wrap sentence in speak tag if no tags present if "<speak>" not in sentence and "</speak>" not in sentence: to_speak = f"<speak>{sentence}</speak>" # Assume speak starts at the beginning of the sentence if a closing speak tag is found elif "<speak>" not in sentence: to_speak = f"<speak>{sentence}" # Assume speak ends at the end of the sentence if an opening speak tag is found elif "</speak>" not in sentence: to_speak = f"{sentence}</speak>" else: to_speak = sentence # Trim text outside of speak tags if not to_speak.startswith("<speak>"): to_speak = f"<speak>{to_speak.split('<speak>', 1)[1]}" if not to_speak.endswith("</speak>"): to_speak = f"{to_speak.split('</speak>', 1)[0]}</speak>" if to_speak == "<speak></speak>": return "" if include_tags: return to_speak else: return to_speak.lstrip("<speak>").rstrip("</speak>")
354de2fb2b6cc6e4a688393135f179461b9cd417
131,457
from typing import List def ls_double_quote_if_contains_blank(ls_elements: List[str]) -> List[str]: """double quote all elements in a list of string which contain a blank >>> ls_double_quote_if_contains_blank([]) [] >>> ls_double_quote_if_contains_blank(['']) [''] >>> ls_double_quote_if_contains_blank(['', 'double quote']) ['', '"double quote"'] """ if (not ls_elements) or (ls_elements is None): return [] ls_newelements = [] for s_element in ls_elements: if " " in s_element: s_element = '"' + s_element + '"' ls_newelements.append(s_element) return ls_newelements
1f3759072101995eea9a5f5397c18cd402d5c5b0
214,978
def parseDBXrefs(xrefs): """Parse a DB xref string like HGNC:5|MIM:138670 to a dictionary""" #Split by |, split results by :. Create a dict (python 2.6 compatible way). if xrefs == "-": return {} return dict([(xrefParts[0], xrefParts[2]) for xrefParts in (xref.partition(":") for xref in xrefs.split("|"))])
8c64efd14d9dfc1367552a4af541d0c67dd749dc
237,038
def restapi_predict(model, X): """ Computes the prediction for model *clf*. :param model: pipeline following :epkg:`scikit-learn` API :param X: inputs :return: output of *predict_proba* """ return model.predict_proba(X)
a9bbb797948b4e238a3800fb3a225c9773c6bba8
449,235
import re def re_search(pattern, text, plural=False): """Regex helper to find strings in a body of text""" match = [m.group(1) for m in re.finditer(pattern, text)] if plural: return match else: if match: return match[0]
66998eb3b29978260eb60603cf440f95a16eb532
48,252
def calculate_resistivity(T, L_wire, rho, alpha, **kwargs): """ Temperature dependent resistivity model. Args: T: Temperature of wire (K) L_wire: Length of wire (cm) rho: Resistivity (Ohms*cm) alpha: Reference resistance coefficient **kwargs: Catch unused arguments Returns: Resistance (Ohms)l """ L_wire, rho_0, alpha = L_wire[0], rho[0], alpha[0] T_ref = 293.15 # 20 deg C Reference temperature for rho delta_T = T - T_ref rho_s = rho_0 * L_wire rho_t = rho_s * (1 + alpha * delta_T) return rho_t
d6f1e44dde91e051ad92c38a7a4e2f19d635ee1d
123,192
import re def parse_time(time_string: str) -> int: """ Parse a time stamp in h/m/s(default)/ms or any combination of these units. Args: time_string (str): timestamp, e.g., "0.23s", "5.234" (implied s), "1234 ms", "1h 10m 12.345s", "00h00m00.000". Supported units: h, m, s (default), ms and any combination thereof. Returns: int: time represented by time_string in milliseconds Raises: ValueError: if time_string cannot be parsed """ try: if not time_string.strip(): raise ValueError("empty time string") prev_end = 0 time_in_ms = 0 for unit_match in re.finditer(r"ms|h|m|s", time_string): # float() raises ValueError if text before the unit is not a valid number numerical_part = float(time_string[prev_end : unit_match.start()]) unit_part = unit_match.group() if unit_part == "h": time_in_ms += int(numerical_part * 3600000) elif unit_part == "m": time_in_ms += int(numerical_part * 60000) elif unit_part == "s": time_in_ms += int(numerical_part * 1000) else: # unit_part == "ms": time_in_ms += int(numerical_part) prev_end = unit_match.end() last_part = time_string[prev_end:].strip() if last_part: time_in_ms += int(float(last_part) * 1000) return time_in_ms except ValueError as e: # e might have been raised by any of the float() constructor raise ValueError( f'cannot parse "{time_string}" as a valid time in h/m/s/ms' ) from e
387ca46ad12faa404d446b6dd28583779638a024
327,853
import operator def equals(column, name='id', function=(lambda x: x)): """Make filter template for filtering column values equal to value transformed by given function. :param column: database model :param string name: name used in the filter template :param callable function: function for transforming the value :return dict: resulting template """ return {name: (column, operator.eq, function)}
da35503e46c306cbcef64d89566d526dc14bd46d
607,477
def fitness_fn(turns, energy, isDead): """Fitness function that scores based on turns and energy. Provides a score to a creature, with 3 times the amount of turns plus the energy, with a bonus for surviving. Args: turns: number of turns a creature survived. energy: amount of energy left after simulation. isDead: boolean of death state. Returns: int: score based on function calculation """ if (isDead): return (3*turns) + energy else: return (3*turns) + energy + 120
823d1295bf64c46cf0e4bb2a7b24b55c2024282d
67,935
def prompt_confirm(prompt: str) -> bool: """Prompt user for confirmation Args: prompt (str): question to user Returns: bool: confirmation """ return len(confirm := input(f"{prompt} [y/N]: ")) > 0 and confirm.lower()[0] == "y"
23e3c08466fa8272d8d26a47954696241645b2c4
554,761
def quote_join(values): """Join a set of strings, presumed to be file paths, surrounded by quotes, for CMake""" surrounded = [] for value in values: surrounded.append('\"' + value + '\"') return ' '.join(surrounded)
fa2a6ee278e7518fc12d7eb486d4668443b9b3d0
373,813
import csv def read_graph_history(file_path): """ Load graph history from file. Args: file_path (str): File path contains the graph execution order info. Returns: set[int], the executed iteration ids of each graph. """ with open(file_path, 'r') as handler: csv_reader = csv.reader(handler) history = set(int(row[0]) for row in csv_reader) return history
03c5f90894e6677d6d6fc942a1b19b6f65ef0dc2
358,143
def chop(n, xs): """ Create a list of lists sized with n from list elements in xs. """ if len(xs) == 0: return [] return [xs[:n]] + chop(n, xs[n:])
57b2a79aef38d1cf1bed3c7f2aac3d4eedf1d0ea
540,134
def format_time(date): """Print UTCDateTime in YYYY-MM-DD HH:MM:SS format Parameters ---------- date: UTCDateTime """ return date.datetime.strftime("%Y-%m-%d %H:%M:%S")
cebd0218110af67746e39dd954bb069067b889bf
387,255
def get_entity_at_location(x, y, entities): """ Return all entities at the given x, y coordinates. Return -1 if there is no entity at these coordinates.""" results = [] for entity in entities: if entity.x == x and entity.y == y: results.append(entity) if not results: return -1 else: return results
24b7ce7e828f1db9c2365c48b694a84f688652e6
391,673
import inspect def get_channelmethods(obj): """ Returns a sorted list of the names of all channelmethods defined for an object. """ channelmethods = list() # getmembers() returns a list of tuples already sorted by name for name, method in inspect.getmembers(obj, inspect.ismethod): # To be a channelmethod, the method must have an attribute called `is_channelmethod`, # *and* it must be bound to the object, since it is common for channelmethods from one # channel manager to be passed into the constructor of a subsequent channel manager! if hasattr(method, 'is_channelmethod') and (method.__self__ == obj): channelmethods.append(name) return tuple(channelmethods)
2443434f3b4141272cbf6266cfec2da5c57d1e90
679,727
def naive(pattern: str, text: str): """Naive pattern matching.""" res = [] n = len(text) for i in range(n): for j, c in enumerate(pattern): if i + j == n or text[i + j] != c: break else: res.append(i) return res
30030778f32ae1b8b56f02df21b2e5b07761a277
508,623
def get_account_username_split(username): """ Accepts the username for an unlinked InstitutionAccount and return a tuple containing the following: 0: Account Type (e.g. 'cas') 1: Institution Slug 2: User ID for the institution """ username_split = username.split("-") if len(username_split) < 3: raise ValueError("Value passed to get_account_username_split " + "was not the username for an unlinked InstitutionAccount.") slug = "-".join(username_split[1:len(username_split)-1]) return (username_split[0], slug, username_split[len(username_split)-1])
65a429b025e307b3a07b8f27303b7b16239b2b5a
136,065
def get_Theta_gsRW_d_ave_d(K_gsRW_H, Theta_ex_d_Ave_d, Theta_ex_H_Ave, Theta_ex_a_Ave, Delta_Theta_gsRW_H): """日付dにおける地中熱交換器からの戻り熱源水の日平均温度(℃) (17) Args: K_gsRW_H(float): K_gsRW_H: 地中熱交換器からの戻り熱源水温度を求める式の係数(-) Theta_ex_d_Ave_d(ndarray): 日付dにおける日平均外気温度 (℃) Theta_ex_H_Ave(float): 暖房期における期間平均外気温度(℃) Theta_ex_a_Ave(float): 年平均外気温度 (℃) Delta_Theta_gsRW_H(float): 暖房期における地中熱交換器からの戻り熱源水の期間平均温度と年平均外気温度との差(℃) Returns: ndarray: 日付dにおける地中熱交換器からの戻り熱源水の日平均温度(℃) """ # 日付dにおける地中熱交換器からの戻り熱源水の日平均温度(℃) (17) Theta_gsRW_d_ave_d = K_gsRW_H * (Theta_ex_d_Ave_d - Theta_ex_H_Ave) + Theta_ex_a_Ave + Delta_Theta_gsRW_H return Theta_gsRW_d_ave_d
99363e26c67e5e7e56176bd630c5beac39b38811
169,439
def getParent(path, num=1): """ Find parent directory of a file or subdirectory @param path: filepath or subdirectory from which to find a parent @type path: string @param num: how many subdirectories to traverse before returning parent @type num: int @return: path to parent directory @rtype: string """ for x in range(num): if "/" in path: path = path[:path.rindex("/")] return path
d031c52b9cb7bcad0ce5277b54e436ec8a7daa97
321,607
def digit(decimal, digit, input_base=10): """ Find the value of an integer at a specific digit when represented in a particular base. Args: decimal(int): A number represented in base 10 (positive integer). digit(int): The digit to find where zero is the first, lowest, digit. base(int): The base to use (default 10). Returns: The value at specified digit in the input decimal. This output value is represented as a base 10 integer. Examples: >>> digit(201, 0) 1 >>> digit(201, 1) 0 >>> digit(201, 2) 2 >>> tuple(digit(253, i, 2) for i in range(8)) (1, 0, 1, 1, 1, 1, 1, 1) # Find the lowest digit of a large hexidecimal number >>> digit(123456789123456789, 0, 16) 5 """ if decimal == 0: return 0 if digit != 0: return (decimal // (input_base ** digit)) % input_base else: return decimal % input_base
c350b844130de86bd1cc5ce06c7c175ab8d4727b
386,794
import json def load_json(path): """Opens a json file and returns the content as a python dictonary. Parameters: path(str): Path of json file """ if not path.lower().endswith('.json'): raise ValueError("Wrong file format!") with open(path) as f: return json.load(f)
3c9167a9816e1ad8cc1cab1d20baae2f012aea7b
362,071
def div0(num, denom): """Divide operation that deals with a 0 value denominator. num: numerator. denom: denominator. Returns 0.0 if the denominator is 0, otherwise returns a float.""" return 0.0 if denom == 0 else float(num) / denom
49f62d40c5bd90459b8304249e69ae4c2d9523d9
315,623
def _length(stream): """Returns the size of the given file stream.""" original_offset = stream.tell() stream.seek(0, 2) # go to the end of the stream size = stream.tell() stream.seek(original_offset) return size
8520dee110a8fbab37f9c296c6d73bda1c167f2b
60,915
import torch def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor: """ Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if our input was ``[2, 2, 3]``, with a ``max_length`` of 4, we'd return ``[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0]]``. We require ``max_length`` here instead of just computing it from the input ``sequence_lengths`` because it lets us avoid finding the max, then copying that value from the GPU to the CPU so that we can use it to construct a new tensor. """ # (batch_size, max_length) ones = sequence_lengths.new_ones(sequence_lengths.size(0), max_length) range_tensor = ones.cumsum(dim=1) return (sequence_lengths.unsqueeze(1) >= range_tensor).long()
c871c1e95e9b6918d14bf2c5d3dd8641cfeef645
311,994
import math def temporary_magnitude_quantity_reverse(C, J, n): """ Returns the temporary magnitude quantity :math:`t`. for reverse *CIECAM02* implementation. Parameters ---------- C : numeric *Chroma* correlate :math:`C`. J : numeric *Lightness* correlate :math:`J`. n : numeric Function of the luminance factor of the background :math:`n`. Returns ------- numeric Temporary magnitude quantity :math:`t`. Examples -------- >>> C = 68.8364136888275 >>> J = 41.749268505999 >>> n = 0.2 >>> temporary_magnitude_quantity_reverse(C, J, n) # doctest: +ELLIPSIS 202.3873619... """ t = (C / (math.sqrt(J / 100) * (1.64 - 0.29 ** n) ** 0.73)) ** (1 / 0.9) return t
c83034b95580dedd2dd39e62f89eea7185125c12
580,270
def Dup(x, **unused_kwargs): """Duplicates (copies) an element.""" return (x, x)
c068c7b4144e6e4f25ec6eb07a02d76ec2e80862
494,505
def transforms_are_applied(obj): """ Check that the object is at 0,0,0 and has scale 1,1,1 """ if ( obj.location.x != 0 or obj.location.y != 0 or obj.location.z != 0 ): return False if ( obj.rotation_euler.x != 0 or obj.rotation_euler.y != 0 or obj.rotation_euler.z != 0 ): return False if ( obj.scale.x != 1 or obj.scale.y != 1 or obj.scale.z != 1 ): return False return True
411a5c0211c6a0b6833352e8566814958a8adaab
679,064
def longest_common_substring(s1, s2): """ returns the longest common substring of two strings :param s1: a string :type s1: str :param s2: a second string :type s2: str >>> longest_common_substring('hello world how is foo bar?', 'hello daniel how is foo in the world?') ' how is foo ' """ m = [[0] * (1 + len(s2)) for i in range(1 + len(s1))] # @UnusedVariable longest, x_longest = 0, 0 for x in range(1, 1 + len(s1)): for y in range(1, 1 + len(s2)): if s1[x - 1] == s2[y - 1]: m[x][y] = m[x - 1][y - 1] + 1 if m[x][y] > longest: longest = m[x][y] x_longest = x else: m[x][y] = 0 return s1[x_longest - longest: x_longest]
2378ef6e620f997f3140c4a941a7e4955b355b66
564,065
def decode(encoded_digits: list[str], mapping: dict) -> int: """decode a number. Use the mapping to decode the encoded digits and combine them to a number. Args: encoded_digits (list[str]): encoded digits mapping (dict): mapping that decodes each segment Returns: (int) decoded number Examples: >>> decode(["cf", "fc", "acf"], {"a":"a", "c":"c", "f":"f"}) 117 >>> decode(["cb", "bc", "acb"], {"a":"a", "c":"c", "b":"f"}) 117 >>> decode(["fcdb", "bc", "acb"], {"a":"a", "b":"f", "c":"c", "d":"d", "f":"b"}) 417 """ digits = { "abcefg": "0", "cf": "1", "acdeg": "2", "acdfg": "3", "bcdf": "4", "abdfg": "5", "abdefg": "6", "acf": "7", "abcdefg": "8", "abcdfg": "9", } result = "" for digit in encoded_digits: decoded_segments = "" for segment in digit: decoded_segments += mapping[segment] decoded_segments = "".join(sorted(decoded_segments)) result += digits[decoded_segments] return int(result)
be4cbd2fbc8be31b1126676a3a115b345b598c8a
16,984
def readf(fname): """Utility function to read a file.""" with open(fname, 'r') as f: return f.read()
924ec495f31303a3101f7a09bd651db927de8a9b
225,810
from typing import Any def function_sig_key( name: str, arguments_matter: bool, skip_ignore_cache: bool, *args: Any, **kwargs: Any, ) -> int: """Return a unique int identifying a function's call signature If arguments_matter is True then the function signature depends on the given arguments If skip_ignore_cache is True then the ignore_cache kwarg argument is not counted in the signature calculation """ function_sig = name if arguments_matter: for arg in args: function_sig += str(arg) for argname, value in kwargs.items(): if skip_ignore_cache and argname == 'ignore_cache': continue function_sig += str(value) return hash(function_sig)
bfec647db5d819fb87cf3a227927acd5cd6dda10
699,267
def parseLogfileToInstanceid(fname): """Parse a file name and return the integer instance id for the service.""" if not fname.endswith(".log.txt") or "-" not in fname: return try: return int(fname[:-8].split("-")[-1]) except ValueError: return
528784ebe3dfebcafb33c30ccdbd771757ced1db
426,964
def make_exposure_shares(exposure_levels, geography="geo_nm", variable="rank"): """Aggregate shares of activity at different levels of exposure Args: exposure_levels (df): employment by lad and sector and exposure ranking geography (str): geography to aggregate over variable (str): variable we want to calculate shares over """ exp_distr = ( exposure_levels.groupby(["month_year", variable, geography])["value"] .sum() .reset_index(drop=False) .groupby([geography, "month_year"]) .apply(lambda x: x.assign(share=lambda df: df["value"] / df["value"].sum())) ).reset_index(drop=True) return exp_distr
02d990f2b08e3acb2a2b8ac01e44848770bdea71
3,734
def str_date(date): """ convert the datetime.date into string :param date: <class 'datetime.date'>, 2016-06-10 02:03:46.788409+10:00 :return 20160603 """ d = str(date).split('-') string_date = "" for i in range(len(d)): string_date += d[i] return string_date
c15850bbd9215a7fb35de75f954013794d2b05ad
495,498
def split_words_by_underscore(function_name): """ get_my_bag -> ['get', 'my', 'bag'] """ return [word for word in function_name.split('_')]
64145aeec269a6a4c3994bc3deb0cf8a460f19df
507,398
import re def get_text_refs(url): """Return the parsed out text reference dict from an URL.""" text_refs = {'URL': url} match = re.match(r'https://www.ncbi.nlm.nih.gov/pubmed/(\d+)', url) if match: text_refs['PMID'] = match.groups()[0] match = re.match(r'https://www.ncbi.nlm.nih.gov/pmc/articles/(PMC\d+)/', url) if match: text_refs['PMCID'] = match.groups()[0] match = re.match(r'https://www.biorxiv.org/content/([^v]+)v', url) if match: text_refs['DOI'] = match.groups()[0] return text_refs
f24cdec70775d10e707aa8ae693dfe5a977fee93
82,013
def sort_freq(freqdict): """ sort_freq reads word:frequency key:val pairs from dict, and returns a list sorted from highest to lowest frequency word :param freqdict: :return: list named aux """ aux: list = [] for k, v in freqdict.items(): aux.append((v, k)) aux.sort(reverse=True) return aux
287a06ceabfc946f822d0465d8b33eda044f22f4
153,659
from typing import Sequence from typing import Tuple import math def quaternion_to_euler(quat: Sequence[float]) -> Tuple[float,float,float]: """ Convert WXYZ quaternion to XYZ euler angles, using the same method as MikuMikuDance. Massive thanks and credit to "Isometric" for helping me discover the transformation method used in mmd!!!! :param quat: 4x float, W X Y Z quaternion :return: 3x float, X Y Z angle in degrees """ w, x, y, z = quat # pitch (y-axis rotation) sinr_cosp = 2 * ((w * y) + (x * z)) cosr_cosp = 1 - (2 * ((x ** 2) + (y ** 2))) pitch = -math.atan2(sinr_cosp, cosr_cosp) # yaw (z-axis rotation) siny_cosp = 2 * ((-w * z) - (x * y)) cosy_cosp = 1 - (2 * ((x ** 2) + (z ** 2))) yaw = math.atan2(siny_cosp, cosy_cosp) # roll (x-axis rotation) sinp = 2 * ((z * y) - (w * x)) if sinp >= 1.0: roll = -math.pi / 2 # use 90 degrees if out of range elif sinp <= -1.0: roll = math.pi / 2 else: roll = -math.asin(sinp) # fixing the x rotation, part 1 if x ** 2 > 0.5 or w < 0: if x < 0: roll = -math.pi - roll else: roll = math.pi * math.copysign(1, w) - roll # fixing the x rotation, part 2 if roll > (math.pi / 2): roll = math.pi - roll elif roll < -(math.pi / 2): roll = -math.pi - roll roll = math.degrees(roll) pitch = math.degrees(pitch) yaw = math.degrees(yaw) return roll, pitch, yaw
6bbce0b502f42e63b181ea65b6fff66d7294210b
687,404
def create_tree_from_list(dict_list, i): """creates binary tree Node of tree is element of dict_list at index i. Right child is element of list with index 2i + 2. Left child is element of list with index 2i + 1. Args: dict_list (list): list of dictionaries i (integer): index (i < len(dict_list)) Returns: dict: complete binary tree """ if i >= len(dict_list): return None else: tree = dict_list[i] tree.update({ "child_right": create_tree_from_list(dict_list, 2*i + 2), "child_left" : create_tree_from_list(dict_list, 2*i + 1) }) return tree
1f32503814781c0713507b61a5852e793843094c
138,854
def find_group_single_candidate(square: tuple, squares: list, grid: list) -> list: """ Checks for a single option a square can have based on no other square in a group having it as an option :param square: A tuple (row, column) coordinate of the square :param squares: A list of squares (tuples) to check the options of :param grid: The sudoku grid as a 3D list :return: A list of options """ if square in squares: squares.remove(square) square_options = set(grid[square[0]][square[1]][1]) for sq in squares: if grid[sq[0]][sq[1]][0] == 0: square_options = square_options - set(grid[sq[0]][sq[1]][1]) else: square_options = square_options - {grid[sq[0]][sq[1]][0]} return list(square_options)
1983720f4540b0bd964a2ba535455ca0510ef369
72,890
def osr_proj(input_osr): """Return the projection WKT of a spatial reference object Args: input_osr (:class:`osr.SpatialReference`): the input OSR spatial reference Returns: WKT: :class:`osr.SpatialReference` in WKT format """ return input_osr.ExportToWkt()
fb4b9bdb33f724d9c414ce7969ac516db1e91a85
618,004
from typing import Callable from typing import Any import time def set_timeout(function: Callable[[], Any], second: int) -> Any: """Runs a given function after a given number of seconds.""" time.sleep(second) return function()
95a0d4db16354774541f93e65bce3987b2a65029
455,762
import ipaddress def broadcast(addr): """Return the broadcast address of the current network """ ip = ipaddress.ip_interface(addr) return f"{ip.network.broadcast_address}/{ip.network.prefixlen}"
3d757804e7f98c0dda56730ec76f120631e5106b
449,496
def get_reservation_ports(session, reservation_id, model_name='Generic Traffic Generator Port'): """ Get all Generic Traffic Generator Port in reservation. :return: list of all Generic Traffic Generator Port resource objects in reservation """ reservation_ports = [] reservation = session.GetReservationDetails(reservation_id).ReservationDescription for resource in reservation.Resources: if resource.ResourceModelName == model_name: reservation_ports.append(resource) return reservation_ports
650f4962e327ab7dd1eeaa054743b5f096a9d3f2
477,815
import asyncio def run(coro, forever=False): """Convenience function that makes an event loop and runs the async function within it. Args: forever: If True then run the event loop forever, otherwise return on completion of the coro """ loop = asyncio.get_event_loop() t = None try: if forever: t = asyncio.ensure_future(coro, loop=loop) loop.run_forever() else: return loop.run_until_complete(coro) finally: if t: t.cancel() loop.stop() loop.close()
6bdb898f7f79b3d9eb591dc62826ead02e2b3cbe
425,771
def validate_list_deceased(gedcom): """ US29: List all deceased individuals in a GEDCOM file """ deceased = [] for individual in gedcom.individuals: if individual.alive is False: deceased.append(f'Deceased: US29: ({individual.id}) {individual.name} [DeathDate: {individual.death.date()}]') return deceased
b8c475475226e59c03986c4634374be1627266f4
487,339
def dict_lookup(d, key): """ Return dictionary value for given key """ return d[key]
9c703b88b57f641c57054e1fc692fa5695dc32b3
536,300
import torch def vector_to_parameter_list(vec, parameters): """ Convert the vector `vec` to a parameter-list format matching `parameters`. This function is the inverse of `parameters_to_vector` from the pytorch module `torch.nn.utils.convert_parameters`. Contrary to `vector_to_parameters`, which replaces the value of the parameters, this function leaves the parameters unchanged and returns a list of parameter views of the vector. ``` from torch.nn.utils import parameters_to_vector vector_view = parameters_to_vector(parameters) param_list_view = vector_to_parameter_list(vec, parameters) for a, b in zip(parameters, param_list_view): assert torch.all_close(a, b) ``` Parameters: ----------- vec: Tensor a single vector represents the parameters of a model parameters: (Iterable[Tensor]) an iterator of Tensors that are of the desired shapes. """ # Ensure vec of type Tensor if not isinstance(vec, torch.Tensor): raise TypeError( "expected torch.Tensor, but got: {}".format(torch.typename(vec)) ) params_new = [] # Pointer for slicing the vector for each parameter pointer = 0 for param in parameters: # The length of the parameter num_param = param.numel() # Slice the vector, reshape it param_new = vec[pointer : pointer + num_param].view_as(param).data params_new.append(param_new) # Increment the pointer pointer += num_param return params_new
9c7e4f4a3768e4b715026a6b0610da856653e714
555,823
def categoria_escolhida(categorias): """ Função que retorna a categoria escolhida pelo usuário :param categorias: lista com todas as categorias possíveis :return: retorna a escolha do usuário """ while True: print("Qual tipo de categoria deseja jogar? ") for i in range(len(categorias)): print(f"{i} - {categorias[i]}") try: escolha = (input(">>> ")).strip() escolha = int(escolha) if 0 <= escolha < (len(categorias)): break except: print("Digite um número dentro das categorias") return escolha
2b04554f92ed39aed005398d0cf78383923310cd
315,552
def is_dev_only(dockerfile_path=str) -> bool: """ Check the build.conf for "devonly" flag. Args: dockerfile_path (str): the dockerfile's path Returns: """ path = f"{dockerfile_path}/build.conf" try: with open(path) as f: content = f.read() if "devonly=true" in content: return True except FileNotFoundError: return False return False
d51668751d9577cd64a52fb85267cf4d18d3ef63
606,117
def starts_with(left: str, right: str) -> str: """Check if the `left` string starts with the `right` substring.""" return left + ' STARTS WITH ' + right
393ed46680d13130eee846e2a7c656f3f989425b
127,682
def adda(a, b, c=0, d=0, e=0): """Add number b to number a. Optionally also add any of numbers c, d, e to the result. """ print(f"Function `adda` called with arguments a={a} b={b}", end="") if c: print(f" c={c}", end="") if d: print(f" d={d}", end="") if e: print(f" e={e}", end="") print() return a + b + c + d + e
50a1a923f2dd046114bf92caffe9ba770d062f43
27,249
def final_well(sample_number): """Determines well containing the final sample from sample number. """ letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] final_well_column = sample_number // 8 + \ (1 if sample_number % 8 > 0 else 0) final_well_row = letter[sample_number - (final_well_column - 1) * 8 - 1] return final_well_row + str(final_well_column)
e48f0cc13c7dd30851f22fe3f32b4bbd9b71a0ed
194,378
def convert_temp(unit_in, unit_out, temp): """Convert farenheit <-> celsius and return results. - unit_in: either "f" or "c" - unit_out: either "f" or "c" - temp: temperature (in f or c, depending on unit_in) Return results of conversion, if any. If unit_in or unit_out are invalid, return "Invalid unit [UNIT_IN]". For example: convert_temp("c", "f", 0) => 32.0 convert_temp("f", "c", 212) => 100.0 """ if unit_in != "f" and unit_in != "c": return f"Invalid unit {unit_in}" if unit_out != "f" and unit_out != "c": return f"Invalid unit {unit_out}" if unit_in == "f" and unit_out == "c": temp = (temp - 32) / 9 * 5 if unit_in == "c" and unit_out == "f": temp = (temp * 5 / 9) + 32 return temp
59202152a54dbc33ecb35bb034af85ab3a897a18
241,669
def get_img_extension(path: str) -> str: """ Parse the path and return the image's extension (replacing jpg to jpeg with accordance with EPUB spec) """ path_list = path.rsplit(".", 1) if len(path_list) == 2: ext = path_list[1] else: ext = "jpeg" if ext == "jpg": ext = "jpeg" return ext
50f6f72885c5ad9a3e12663af18282c1ca78fe3d
209,488
import pickle def load_clifford_table(picklefile='cliffords2.pickle'): """ Load pickled files of the tables of 1 and 2 qubit Clifford tables. Args: picklefile - pickle file name. Returns: A table of 1 and 2 qubit Clifford gates. """ with open(picklefile, "rb") as pf: return pickle.load(pf)
25382d151456b926a317e3c820d29d650e28e31c
657,816
def ens_to_indx(ens_num, max_start=1000000): """ Get the index related to the ensemble number : e.g 101 => 0 :param ens_num: ensemble number, int :param max_start: max number of ensembles, int :return: index, int """ start = 100 while start < max_start: ind = ens_num % start if ind < start: return ind - 1 # Otherwise, try with bigger number of ensembles start *= 10 print("Error: ens_to_index function: ensemble number cannot be converted to index")
a0af56431df994d1c01207aa2c8a9cf9fd76e258
622,185
import re def FillForm(string_for_substitution, dictionary_of_vars): """ This function substitutes all matches of the command string //%% ... %%// with the variable represented by ... . """ return_string = string_for_substitution for i in re.findall("//%%(.*)%%//", string_for_substitution): return_string = re.sub("//%%" + i + "%%//", dictionary_of_vars[i], return_string) return return_string
192a502cfff97d58aeaa8c2201c588acc916616c
384,000
def get_class_name_no_json(i, soup): """Gets the name of a class for courses that do not use a JSON timetable As of 2018-11-13 it\'s saved as the content of an <h3> tag with id equal to tab{index}""" return soup.find("h3", id="tab{}".format(i)).find("a").contents[2].lstrip().rstrip()
542ac6cf620aca3067150ab776778581e9de0326
255,749
def latex_float(f, fmt='{:.1e}', phantom=False): """Convert float to LaTex number with exponent. Parameters ---------- f : float,int,double fmt : str Python format string. Default: '{:.1e}' phantom : bool Add phantom zeros to pad the number if it does not fill the format string. Default: False Returns ------- str Formatted string to be used in LaTeX. """ float_str = fmt.format(f) if phantom: float_str = float_str.replace(' ',r'\phantom{0}') if "e" in float_str: base, exponent = float_str.split("e") return r"{0} \times 10^{{{1}}}".format(base, int(exponent)) else: return float_str
b075035786d0e5468a15f34379817b85636f2bf8
614,403
def one(iterable): """Return the single element in iterable. Raise an error if there isn't exactly one element. """ item = None iterator = iter(iterable) try: item = next(iterator) except StopIteration: raise ValueError('Iterable is empty, must contain one item') try: next(iterator) except StopIteration: return item else: raise ValueError('object contains >1 items, must contain exactly one.')
49cbb2e829bccaeb3ba5337b00c8bb19c2842b02
629,750