content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_conversation_ids(emails_ids_per_sender, df_info): """ :return: dict of dict, with keys: sender then recipient with mids as values """ conversation_ids = {} for sender, ids in emails_ids_per_sender.items(): recs_temp = [] for my_id in ids: recipients = df_info[df_...
68ae2b3ac6c667505f9ed506e727c7807b3df29c
650,282
def adjust_displacement(n_trials, n_accept, max_displacement): """Adjusts the maximum value allowed for a displacement move. This function adjusts the maximum displacement to obtain a suitable acceptance \ of trial moves. That is, when the acceptance is too high, the maximum \ displacement is incre...
cc513be27481d239cf8c937bd260e1db8f182775
650,283
def wildcard_to_regexp(instring): """ Converts a player-supplied string that may have wildcards in it to regular expressions. This is useful for name matching. instring: (string) A string that may potentially contain wildcards (* or ?). """ regexp_string = "" # If the string starts with an...
f70737b9186882907cefddb02a94de68e5ec8783
650,285
def makeHtmlInlineImage(text): """Create HTML code for an inline image. """ return """<IMG SRC="%s" ALT="%s">""" % (text, text)
b10072cb6c1b703ee9cf0a2ed1942415ce66a191
650,286
def rollout(env, sess, policy, framer, max_path_length=100, render=False): """ Gather an episode of experiences by running the environment. Continues until env.done is True or length of episode exceeds max_path_length """ t = 0 ob = env.reset() obs = [ob] logps = [] rews = [] acs...
67b5e5dfe35cbe382e552e94758a595e80d09f4f
650,287
def lower_case(text: str) -> str: """Convert `text` to lower case. Args: text (str): The text to convert to lower case. Returns: The converted text. """ return text.lower()
24b93a43f11d61194ff2429e4d5ee731a88a0a6c
650,288
import torch def reverse(input, dim=0): """ Reverses a tensor Args: - input: tensor to reverse - dim: dimension to reverse on Returns: - reversed input """ reverse_index = input.new(input.size(dim)).long() torch.arange(1 - input.size(dim), 1, out=reverse_index) ...
7924d55daec78743afff99eda093b10c2f2d32d2
650,289
import os def rel_path(path, basedir): """Relativize an absolute path with respect to a base dir.""" if not path.startswith(basedir): return None return os.path.relpath(path, basedir)
2d3eb0e9711d3e494f5bcc53f422478a5fd73b5e
650,290
def get_last_col(worksheet, row_num: int = 1) -> int: """Retrives the last nonblank column on Google Sheets Parameters ---------- worksheet : Google Sheets worksheet The worksheet being queried row_num : int, optional Row that's indicative of the overall data length, by default 1 ...
1e3c422bc1425b2f47aa32f08e5662c346c6cd66
650,291
import math def input_choices_from_list(choices, text): """Lets the user choose from a list Args: choices (list): the list the choose from text (str): the text to display for user input Returns: a list of indices chosen by the user """ no_courses_text = """ init wi...
64575f4688a06ea1e41380ee2d2a78fd12c07d46
650,292
def NLLLoss2dConfig(argument_parser): """ Set CLI arguments :param argument_parser: argument parser :type argument_parser: ```ArgumentParser``` :returns: argument_parser :rtype: ```ArgumentParser``` """ argument_parser.description = """The negative log likelihood loss. It is useful to ...
e9dba9cc8eb3ce3227a9fa6539df4ff76ff4753e
650,293
def pairwise(iterable): """ Iter over an iterable, two items by two items >>> list(range(10)|pairwise()) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] """ a = iter(iterable) return zip(a, a)
b10528ab7315f6eb5ed78accfdf9135ae90c5b9a
650,294
def filter_tags(job): """Filter out tags attached to post.""" tag_list = '' tag_container = job.find('div', attrs={'class': '-tags'}) job_tags = tag_container.findAll('a', attrs={'class': 'post-tag'}) for tag in job_tags: tag_list += '{}, '.format(tag.text) return tag_list
b036741b6797a225ba6b07791f882e177ccf231c
650,295
def bc(val): """ Convert bool to single letter T or F """ if val is True: return "T" return "F"
628255892a5c6545f20a3df4f4f20ca0615323b4
650,296
def remove_chars(word): """Used to replace all the characters of the word. In this program we replace it in the wiki page title, so it can reply to some words . Example: word: austin page title: austin, texas If the ',' is kep in the page title, bot will not reply """ c...
fa4e8bc42c844b3ce8677fb6ad79d8b13e20d6a2
650,297
def isExtensionSupported(filename): """ Supported extensions viewable in SlideShow """ if filename.endswith('PNG') or filename.endswith('png') or\ filename.endswith('JPG') or filename.endswith('jpg'): return True
af1242e7821ba52a266e9fce5b6422cd85c837db
650,298
def assign_county(point, counties): """Assign a single point to its county.""" try: match = next( county['NAME'] for _, county in counties.iterrows() if point.intersects(county['geometry']) ) except StopIteration: match = None return match
b884ce7ca4727967e412633b44edca5140e19edc
650,299
import mpmath def cdf(x, mu=0, sigma=1): """ Log-normal distribution cumulative distribution function. """ if x <= 0: return mpmath.mp.zero lnx = mpmath.log(x) return mpmath.ncdf(lnx, mu, sigma)
7c984386d5947e0882fc115e68afcdb26197b960
650,300
import glob import os def get_every_json_paths(dirpath): """Get every json path. Args: dirpath (string): path of directory which contains json and png. Returns: list[string]: List of json path. """ return glob.glob(os.path.join(dirpath, "**", "*.json"), recursive=True)
92fa1cc22d28cf0f7d2bf07516218146d4805947
650,301
import torch def broadcast_to_tensor(tensor, encoding, ch_axis): """ This helper method takes n-dimension tensor and a 1-dimension encoding. And the encoding is broad-casted to match the n-dimensional tensor :param tensor: Tensor to use as target for the broadcasting operation :param encoding: Enc...
8a15c0fade8793ea9e327eb788aae58264133405
650,302
import yaml def write_yaml_data(filepath, data): """Write data to YAML file Args: filepath: the path to the YAML file data: a dictionary to write to the YAML file """ with open(filepath, 'w') as stream: yaml.safe_dump(data, stream, default_flow_style=False, indent=2) return (...
7706ded443e2a110770f742166481fa6e6ccb12d
650,304
import re def get_space_normalized_segment(segment): """Remove leading/trailing as well as multiple spaces from a string. :param str segment: a segment (sentence) :return: a string with no leading/trailing spaces and only containing single whitespaces :rtype: str """ return re.sub(r'\s{2,}', ...
5f1c04f28e5fda8fc501f979652846aacbb33cd8
650,305
def i2osp(x: int, xLen: int) -> bytes: """ https://tools.ietf.org/html/rfc8017#section-4.1 """ assert xLen >= 0 assert x <= pow(256, xLen), "Input integer is too big for the xLen." # need to return big endian of the integer left padded with zero bytes. return x.to_bytes(xLen, byteorder='big'...
94f59e5368fbc50bbd24d0e65a76b736ed3266f7
650,306
def decimal_digits(x: float, precision: int) -> int: """Forms an integer from the base-10 digits of a floating-point number. Args: x: A floating point number, which may be negative. precision: The number of digits after the decimal point to include. Returns: An integer containing a...
7a0d6b3ef34efa276a9537cefa899be6ed16a60a
650,307
def _compare_composition(peptide, sub_seq): """ controls if two string have the same composition. This functions is designed to compare by weight two peptides (To happen this they be have the same composition) "note" that Isoleucine and Leucine are isomers >>> _compare_composition("YAYAYA", "A...
ab7dd7c59bfa86e254b413232d21cbcd32708ad5
650,309
def coerce_values(spec): """coerce_values(spec)(indict) : change some values of indict >>> mappings = {'count': int} >>> coerced = coerce_values(mappings)({'a': 'foo', 'count': '3000'}) >>> coerced['count'] 3000 >>> coerced['a'] 'foo' """ def _coerce_values(indict): outdict ...
fe652e459dc795391d24ebab99ff50408687700f
650,310
def describe_class_or_specification(obj): """ Simple description of a class or interface/providedBy. """ return obj.__name__ if obj is not None else 'None'
dd298eb8febaad889b0019b87ee9cd7c43009279
650,311
from typing import Any from typing import Sequence def a_seq_int(request: Any) -> Sequence[int]: """Provide random values that are sequences of ints.""" return request.param[1]
c7c2c6901b274f747364ac7b9790208c0eddf341
650,313
from pathlib import Path def missing_useful_files(result_dir): """Return list of missing useful files""" useful_files = [ 'ordered_activity_codes.json', # activity codes 'product_dict.pickle', # lca.product_dict 'bio_dict.pickle', # lca.biosphere_dict 'activity_dict.pickle',...
d02c9f69ab6cffac683066eecf032745967cbb5d
650,314
def _extract_synonym(rest_of_line: str) -> str: """ Extracts synonym name from obo line. :param rest_of_line: string containing line except for "synonym: " :return: """ synonym = rest_of_line.split('"')[1].lower() return synonym
1b2ea52bf2673646e43f5e2d03250e35795e16c5
650,315
def get_count_rounds(): """Return count of game round. Returns: num (int): count of game round """ return 3
09bf2130c586fa5bed38adc126a5159dd5750b5c
650,316
def sort_members_key(name): """Sort members of an object :param name: name :type name: str :return: the order of sorting :rtype: int """ if name.startswith("__"): return 3 elif name.startswith("_"): return 2 elif name.isupper(): return 1 else: ret...
89d8fa066275f8281cd9a896afdd4374aa6799c9
650,317
def color_temp_post_response_ok(devid, color_temp): """Return color temp change response json.""" return ''' { "idForPanel": "''' + devid + '''", "colorTemperature": ''' + str(int(color_temp)) + ''' }'''
bb110f55e5cf8e8c62cab43bced1461df1937938
650,318
def ord_word(word): """ Convert an alphanumeric string to its ASCII values, used for ES keys. """ return ''.join([str(ord(letter)) for letter in word])
db6f6742b203b000bf6027be24f81b4b10a9e20e
650,319
def Add_Splitter(sentence): """ Add sentence splitter mark (newline) to be recognized by split_sentences.pl, even if text is lowercased. """ return sentence + "\n"
83cf41d0088003dd3d493a806ac1010de0128b15
650,320
def cleanup_libs_list(libs): """Cleans up libs list by removing invalid entries""" cleaned = [] for lib in libs: lib = lib.strip() if not lib.endswith('.lib.recipe'): cleaned.append(lib) return cleaned
2fc9efec02af449793b2f3b98f3e13e67ea7477f
650,321
def tweet_answer(tweet, tweets_left): """ Function that making text answer from tweet object """ answer = '"{message}" - {author} \n\n{link}\n\n{more} more tweets.'.format( message=tweet['text'], author=tweet['screen_name'], link=tweet['link'], more=tweets_left ) ...
78b1c3335f9a8e15d09b9affe494a868b6e16440
650,322
import os def inVNCSession(): """Returns ``True`` if this application appears to be running over a VNC (or similar) session, ``False`` otherwise. Currently, the following remote desktop environments are detected: - VNC - x2go - NoMachine """ vncVars = ['VNCDESKTOP', 'X2GO_SESSIO...
76ad7e29a03f1078169501479007651277e28b4d
650,323
def AddServiceAccountToDatasetPolicy(access_message_type, dataset_policy, member, role): """Add service account to dataset.""" for entry in dataset_policy.access: if entry.role == role and member in entry.userByEmail: return False dataset_policy.access.append( ...
e96e22f70d92f93cf9e2ea603839d701e48e20df
650,326
def draw_rectangles(frame, rect, thickness = 1): """ Draws rectangles onto frame. """ if rect is None: return frame tmp = frame.copy() for r in rect: if r is None: continue tmp = r.draw_rectangle(tmp, thickness) return tmp
27677d4715ea1adc7a2f2b3c3c58bd09dc310316
650,327
def query_result_to_dict(key, values): """ SQLAlchemy returns tuples, they need to be converted to dict so we can jsonify :return: """ return dict(zip(key, values))
09b6567b6690757548ed54648fa9b0bbb51104ec
650,328
import sys def dijkstra(graph, source): """Dijkstra's Shortest Paths Algorithm (Naive) - O(m*n) Complexity""" explored = set([source]) shortest_paths = {source: 0} n = len(graph) while n > 1: min_key = None min_value = sys.maxsize for tail in explored: for hea...
4a52558e0adbda3fbf9f9ef092adbdbf9c34b278
650,330
def read_num_from_file(file_with_path): """ read a number from a file """ with open(f"{file_with_path}", "r", encoding='utf-8') as text_file: return int(text_file.read())
8b87b746a03308724c5cc15fd7eca4cf4e85b283
650,331
def _FlattenList(l): """Flattens lists of lists into plain lists, recursively. For example, [[4, 5, 6], [7, 8], []] will become [4, 5, 6, 7, 8]. Non-list elements will get wrapped in a list, so 'foo' becomes ['foo']. None becomes []. Args: l: a list, or not. Returns: A flattened list. """ re...
ca4df94f51568e93e217bdf50987f47fd0a257f8
650,332
def ceil(x): """Return the ceiling of *x* as a float, the smallest integer value greater than or equal to *x*.""" return 0.0
5050fc19d5d02760bfd5d94972db3d419044d3c6
650,333
import re def feat_tokens(for_artist=True): """Return a regular expression that matches phrases like "featuring" that separate a main artist or a song title from secondary artists. The `for_artist` option determines whether the regex should be suitable for matching artist fields (the default) or title...
764c5c9295a1d5f6e01fa95059cc079949a12d25
650,334
import asyncio def pytest_pyfunc_call(pyfuncitem): """Run coroutines in an event loop instead of a normal function call.""" if asyncio.iscoroutinefunction(pyfuncitem.function): testargs = {arg: pyfuncitem.funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} _loop = p...
c04b85c483ee927b6f26bc9692daf14331f8a48d
650,335
import math def wind_speed(height, friction_velocity, roughness_length, kappa=0.41): """ returns the wind speed at a given height May want to consider Deaves & Harris (1978) model for high speed wind """ return friction_velocity / kappa * math.log(height / roughness_length)
76967302a2aa8aa3b516e1303677ed68d30cfb0e
650,337
def nonzero_indices(arr, max_number=1): """get an array of indices that have nonzero value""" result = [] for i in range(len(arr)): if arr[i] != 0.0: result.append((arr[i], i)) result = sorted(result, reverse=True) n = min(max_number, len(result)) return [result[_][1] for _ i...
453c5709c83dfc6555080d1cde3e00eaab22d89a
650,339
def _validate_tcp(_value, model): """Validate that the TCP does not conflict with other attributes. :param str _value: The TCP value :param consulate.models.agent.Check model: The model instance. :rtype: bool """ return not model.args and not model.grpc \ and not model.http and not mod...
10172859ce3cd25aebcbf580492c173a842aad73
650,340
from textwrap import dedent def dals(string): """dedent and left-strip""" return dedent(string).lstrip()
ccfaa324c6341edbbffd4eba5cc0a8b2779b5e55
650,341
import os def disk_status(folder): """ 查看文件夹占用磁盘信息 :param folder: 文件夹路径 :return: """ hd={} disk = os.statvfs(folder) # print(disk) # 剩余 free = disk.f_bavail * disk.f_frsize hd['free'] = str(round(free/float(1024*1024*1024), 2)) + " GB" # 总共 total = disk.f_blocks * ...
c333628318cc113899fc504e9937cdaf2de46396
650,342
def test_geojson(distribution): """ Test if a DCAT:distribution is GeoJSON. """ return ( distribution.get("mediaType") == "application/vnd.geo+json" or distribution.get("format", "").lower() == "geojson" )
c321795d4f38f7188fb4d9f3ab6403ce8b866bad
650,343
from typing import List def clean_source(source: List[str]) -> List[str]: """ Cleans the source content of a Synapse notebook cell. :param source: The source content of the cell. :returns: The cleaned source content of the cell. """ source = list([line.rstrip() for line in source]) source...
773915a1ec7fc88d1a7ae0eb4cf95578ac4d21a0
650,345
def shorten(body, keep_header=0, keep_trailer=0): """ Smartly shorten a given string. """ # Normalize byte-like objects try: body = body.decode('utf-8') except (UnicodeDecodeError, AttributeError): pass # Cut header if (keep_header and not keep_trailer ...
30a04a2a0cded4487a4876b8ce1b18e62fc21e45
650,346
import warnings def puppy_vid_inspected_trajectory(grp, step_width, loc_marker, epoch_idx, obs_offset): """ .. deprecated:: 1.0 Use :py:class:`PuppyActionVideo` instead """ warnings.warn('deprecated, use PuppyActionVideo instead') loc_x = grp['puppyGPS_x'][obs_offset+step_width*e...
582083bc76950437b9ebdd1258393c3c6f0311c8
650,348
from struct import pack def makePalMeta(color_table_ptr: int, colors_count: int, title_len: int): """Generates a metadata record for a palette in a pal file. Since we don't have a serializer in KS, we use the manual one.""" res = bytearray() res += b"\0\0\0" res += pack("<I", color_table_ptr) res += pack("<I",...
61844fcb2cff96ba23e45e8e9647e673b0a0f8d9
650,350
import itertools import collections import sys def total_size(o, handlers={}, verbose=False): """ Returns the approximate memory footprint an object and all of its contents. Automatically finds the contents of the following builtin containers and their subclasses: tuple, list, deque, dict, set and froze...
644a243e2d7abd32f871b36db91f6bb0acc73f5b
650,351
import os def iter_dir(directory, endwith='.csv', split=True): """ iterate csv files in a given directory :param directory: path to the folder :@param endwith: :return: list of file names end with csv """ filenames = [] for name in os.listdir(directory): if name.endswith(endwit...
d221bb03787803d23381294046cff9d484005c5f
650,354
def arrayElement(value, arg): """Removes all values of arg from the given string""" return value[arg]
434ed021a114bccf5443de71be9c653f718e9e35
650,355
def get_module(module_id, module_registry): """Obtains a configured ContourFeatures given an algorithm identificator. Parameters ---------- module_id : str Module identificator (e.g., bitteli, melodia). module_registry : dict Dictionary of module_ids to class instances Returns ...
479d98c93ef0d9cf852a0e330a2e71827c38f2a6
650,356
def subclass_responsibility (f) : """Raise a NotImplementedError unless the method is redefined in descendents. For classmethods, use `subclass_responsibility` as first decorator:: @subclass_responsibility @classmethod def meth (cls, ...) : ... ""...
13364a721d496fdb423569afb264cd2717269d82
650,357
from typing import List from typing import Any def flatten(ll: List[List[Any]]) -> List[Any]: """ Flatten a list of lists into a single list. """ return [a for l in ll for a in l]
85c948a15777a1b8f6f401f1cf4a0caf3b18cbe9
650,358
def get_pytest_marks_on_function(f): """ Utility to return *ALL* pytest marks (not only parametrization) applied on a function :param f: :return: """ try: return f.pytestmark except AttributeError: try: # old pytest < 3: marks are set as fields on the function ob...
c60eb684b987c6ff08fe17a75b7264c621a7d740
650,359
def _class_required(type_, class_, params): """Return true if method requires a `cls` instance.""" if not params or class_ is None: return False return type_ == 'classmethod'
8e4f92074e06e3bc22a1bea435534c062e72761b
650,360
def _gaussian_elimination_complexity(n, k, r): """ Complexity estimate of Gaussian elimination routine INPUT: - ``n`` -- Row additons are perfomed on ``n`` coordinates - ``k`` -- Matrix consists of ``n-k`` rows - ``r`` -- Blocksize of method of the four russian for inversion, default is zero ...
d521fcf07e1e6f71a57c370dadc788d531df5b2d
650,361
def _make_version(major, minor, micro, level, serial): """Generate version string from tuple (almost entirely from coveragepy).""" level_dict = {"alpha": "a", "beta": "b", "candidate": "rc", "final": ""} if level not in level_dict: raise RuntimeError("Invalid release level") version = "{0:d}.{1:...
5bca2be7e0c4cc31b11bea7fe5ddccb5da1caf0d
650,362
def char_to_decimal(text): """ Converts a string to its decimal ASCII representation, with spaces between characters :param text: Text to convert :type text: string :rtype: string For example: >>> import putil.misc >>> putil.misc.char_to_decimal('Hello world!') '...
e104f5b3aa86347dc0ab10310b10ce83bc72400a
650,363
def _structure_parent_category(_parent_id, _payload): """This function structures the portion of the payload for the parent category. .. versionadded:: 2.5.0 :param _parent_id: The ID of the parent category (if applicable) :type _parent_id: str, None :param _payload: The partially constructed payl...
ea21347aeefcc588270d7b287c82f696f18c259d
650,364
def parse_drive_size(line): """Parses a drive line in the partition information file. """ parts = line.split(":") if len(parts) != 2 or parts[0] != "drive": raise ValueError("Drive size line format is 'drive:<size>'") return parts[1]
5c9eee6463e90c31191e36dfd77edec4c0911343
650,366
import torch def get_duplicate_labels(labels, n_items, max_label): """ Converts the number of items that exist in the game (not including the targets) to a count word that is interchangeable with another count word meaning the same thing. For example, the label for the value "0" can either be 0 or...
dc853331ae5b52c25f654265bba15e3b8b080071
650,367
import torch def create_transform_matrix(roi_patch): """Creates a 3x3 transformation matrix for the patches""" transform_matrix = torch.zeros((roi_patch.shape[0], roi_patch.shape[1], roi_patch.shape[2], 3, 3)).to(roi_patch.device) transform_matrix[:, :, :, 0, 0] = torch.cos(roi_patch[:, :, :, 4]) tran...
ef4a3bc6c7a2529b3d5634304442710eaad80b3a
650,368
def NOT(event, sample_space): """Returns subset of events from set of samples that are NOT in the subset event.""" return sample_space - event
838d2641b887cf87ceaa819d1ff4de0c27f2b012
650,369
def _patsplit(pattern, default): """Split a string into the optional pattern kind prefix and the actual pattern.""" if ':' in pattern: kind, pat = pattern.split(':', 1) if kind in ('re', 'glob', 'path', 'relglob', 'relpath', 'relre', 'listfile', 'listfile0', 'set'): ...
d25ead13ec9ab7ea4d660fbf46bec20f6a7f6bbc
650,370
def query_to_json(query, name): """This query is useful to fetch a complex join with some aggregations as a single blob, and later, just hydrate it without having to iterate over the resultset .. Example: SELECT u.id::varchar, to_jsonb(array_agg(scopes)) as scopes, ...
07bee3c4c7f541cafccd1b31a3134bd8378f9de4
650,372
import os def resolve_ncase(path): """ Resolve a case insensitive path on a case sensitive system, returning a string with the path if found else return the original path. """ def _ncase_path_found(path): if not path or os.path.exists(path): return path, True # filen...
14400997bc657c8d84fb37dd825ea88847975cab
650,373
def filter_space(xpath_result: list) -> list: """ 除去xpath提取结果中包含的空格符,换行符,制表符等 :param xpath_result: :return: """ return_list = list() temp_list = " ".join(xpath_result).strip().split("|") for element in temp_list: temp_element = element.replace("\n", " ").replace("\r", " ").strip(...
4bcda02034a687980d875c7374f8daa88b517074
650,374
def computeGenerators(nodeLists = "const std::vector<NodeList<%(Dimension)s>*>&", boundaries = "const std::vector<Boundary<%(Dimension)s>*>&", meshGhostNodes = "const bool", xmin = "const typename %(Dimension)s::Vector&", xmax = "co...
e61b60427aa0626a4375ada2bb50353a21fe90f4
650,376
def are_features_consistent(train_df, test_df, dependent_variables=None): """Verifies that features in training and test sets are consistent Training set and test set should have the same features/columns, except for the dependent variables train_dr: pd.DataFrame training dataset test_df: pd.Dat...
cc9f0f42519a77bb01ff1ceb31c89b64f0af0832
650,377
import pathlib from typing import List from typing import Any def get_downloaded_partitions(path_to_folder: pathlib.Path) -> List[Any]: """Retrieves the full paths of the partitions file in a folder. Parameters ---------- path_to_folder: pathlib.Path A pathlib.Path indicating the full path to...
34fe6c78125fda392c28eba47e38cbb206c15864
650,378
from typing import Any def mandatory(val: Any) -> Any: """Raises a ValueError if the provided input is None, otherwise returns it""" if (val is None): raise ValueError("Missing mandatory configuration value") return val
8c6f74c3886f3464488b8f6c6b6529c2cd2ba5a3
650,379
import argparse def parse_argument() -> str: """Parse command line option Return twitter screenname """ parser = argparse.ArgumentParser(description='Retrieve all available tweets of user and inserts into SQLite database.') parser.add_argument('--screen_name', help='Screen name of user to be retri...
6be969999113cc5f1ff71a7723d82c061fe02cb8
650,380
import re def APart(op): """A and B parts of operations: We provide the ability for multiple B operation types to map onto the same A operation type. This is most useful (so far) when describing "same address" vs. "different address" mappings. For example, the MOST for TSO looks like this: ...
973c943d4bfc22c522418e5a8f4eedf25d086a5a
650,381
def _snapshot_v2_to_v1(snapv2_result): """Transform a v2 snapshot dict to v1.""" snapshots = snapv2_result.get('snapshots') if snapshots is None: snapshots = [snapv2_result['snapshot']] for snapv1 in snapshots: # The updated_at property was added in v2 snapv1.pop('updated_at', N...
9b7bb020d023d0f85293d5b0ef82e31108ed64ce
650,382
def render_path(path, context): """ Replace variables in path with values. """ # Check for tokens delineated by "+" (e.g.: +variable+) if '+' not in path: return path for token, value in context.items(): path = path.replace('+' + token + '+', value) return path
aeb59918c4de6f66cd82a7843533586edc3506a0
650,383
from typing import List from typing import Dict def _piecewise_translate(in_list: List[str], in_dict: Dict[str, str]): """ Needed to put a (modified) copy of this function in this file, to fix recursive import problem """ outlist = [] # list to build & return dictitems = list(in_dict.items()) for out in in...
ca127262829e9d5087de456c3fb87c22896ba7e5
650,384
def _table_type(typestr): """Return the translation of CRDS fuzzy type name `typestr` into numpy dtype str() prefixes. If CRDS has no definition for `typestr`, return it unchanged. """ int_types = [">i","<i","uint","int"] float_types = [">f","<f","float","float"] complex_types = [">c","<c","com...
c4be4b3ce4ceb1a90ad6308598976175d8e3c7ea
650,385
def validate_words_are_anagram(word1, word2): """Compare if this two words are anagrams""" if sorted(word2) == sorted(word1): return True return False
e0b5007d634c206c9e314cc10ee96c999d6f9a10
650,386
def alpha(s: int, initial_val: float, half_life_fraction: float, max_iter: int, alpha_type: str) -> float: """ Alpha function: determines extent to which node matrix is altered over time This function accepts hyper-parameters initial_val, alpha_type, and half_life_fraction which can be adjusted to improve performan...
de58fe898445a7518243588178d76169467c1526
650,387
def complex_transmission_reflection(in_m0,in_m1,in_m2): """ complex_transmission_reflection(in_m0,in_m1,in_m2) Calculate the complex transmission and reflection coefficients between media 0, 1, and 2 given their complex refractive indices. In the Kramers-Kronig implementation (in which this is most likely us...
a1726a8b5e133582ad2cb0e07eb2e5a1ba561829
650,388
import os import pickle def get_keys(num: int) -> list: """Return a list of peers loaded from the corresponding file.""" my_path = '/'.join( os.path.realpath(__file__).split('/')[0:-1]) # Path to this script working_dir = my_path + "/../bin" # Path to peer files file = working_dir + "/keys_%...
543aad67cb8fd07488b18d4260b5e071617bfdc4
650,389
import random def _select_sequences(unweighted_msa_file: str, max_seqs: int): """Return path to file with sequences, may select only some sequences.""" sequence_names = [] with open(unweighted_msa_file) as stream: for line in stream: if line.startswith("#=GS"): sequence...
1e260a16d2a0a2aeee8f9235a8d2402e8bf848e1
650,390
from typing import Union from typing import Any from typing import Iterable def produces(objects: Union[Any, Iterable[Any]]) -> Union[Any, Iterable[Any]]: """Specify products of a task. Parameters ---------- objects : Union[Any, Iterable[Any]] Can be any valid Python object or an iterable of ...
61a4e0f59eb93e8901d3e60bf20e8ee95bbbf658
650,391
def is_number(word: str) -> bool: """Check if string/words is a number. Args: word: Word to check. Returns: True, if given word is a number. """ try: float(word) return True except ValueError: return False
552f8bdb040d1b6e89d088c85b3db02e0ba1af77
650,392
def rectcenter(rect, cast=float): """Returns the center ``[x,y]`` of the given `rect`. Applies the given `cast` function to each coordinate.""" return [cast((rect[0]+rect[2]-1)/2.0), cast((rect[1]+rect[3]-1)/2.0)]
febc9e064cfd668c45ec6ecfa3cbaf6590d1cc5a
650,393
def mod_exp(val, exp, modulus): """Computes an exponent in a modulus. Raises val to power exp in the modulus without overflowing. Args: val (int): Value we wish to raise the power of. exp (int): Exponent. modulus (int): Modulus where computation is performed. Returns: ...
5b2de4ce19807cbd7b1ffc6d0a532012d183f1ac
650,394
import os import subprocess import shlex def run_shell(cmd, stin=None, outp=None, err=None, do_wait=True): """ Utility tool for launching a bash command and waiting for it to finish, optional input/output redirection @param cmd The command to be launched @param stin File to redirect standard in from ...
a45a5b07da39f954cbd978b40c8165616f75801a
650,395
def buildCov(rs): """ Genomic region coverage """ lims = {} cov = {} for r in rs: #coverages if r[0] not in cov: cov[r[0]] = set() cov[r[0]].update(range(r[1], r[2] + 1)) #range limitations if r[0] not in lims: lims[r[0]] = [r[1], r...
3ce12f107cbb809a8ac3f175bfaab8d25cab27c6
650,397
import pickle def read_pickle(filepath): """Read pickle file""" infile = open(filepath,'rb') data = pickle.load(infile) infile.close() return data
eb356661b5ca1f530da0f7623397cf6d8b4eb663
650,398
def convertPrice(priceStr): """This function translates the string price with all the garbage caracters to a float """ for ch in [' ','.','$',',','\n','\t']: if ch in priceStr: priceStr=priceStr.replace(ch,"") return float(priceStr)
cd9bd726373cbb5371ced5c316a0d3d6f64ae5bc
650,399