content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import re def like(matchlist: list, array: list, andop=False): """Returns a list of matches in the given array by doing a comparison of each object with the values given to the matchlist parameter. Examples: >>> subdir_list = ['get_random.py', ... 'day6_15_payload-by-port.py', ... '...
b7cf450cdd06bd8e0e3bc6d35c3a6f8ba0cfa457
680,465
import argparse def get_args(): """Parse the arguments. Returns: parser: parser containing the parameters. """ parser = argparse.ArgumentParser( description="Runs the segmentation algorithm.") parser.add_argument( "mode", metavar="mode", choices=("train", ...
99d95bdddedd42e7cfadfca740629e7aeeb23e7d
680,466
from typing import Union import pathlib import yaml def load_config(config_path: Union[str, pathlib.Path]): """ Load config and secrets """ with open(config_path) as config_yaml: config = yaml.load(config_yaml, Loader=yaml.FullLoader) return config
1c1bd774cce47e2327af0d2abf1a09195671b3e9
680,467
def filter_by_param(confs, pars): """ Filters out Config objects from a list of objects given a dict of parameters that you wish to keep. Returns a list of the desired Config objects :param confs: A list of Config objects :type confs: list :params pars: A dict whose keys are dot separated p...
b72bd86f3f463b65b2132ed5308cfe154d2d2ceb
680,468
def build_index(links): """ 构建页面索引 :param links: :return: """ website_list = links.keys() return {website: index for index, website in enumerate(website_list)}
489131e93eb8220df6aa3c516baa65d2c5ab568e
680,470
def convert_to_date( value=None, format="%Y-%m-%d %H:%M:%S"): """convert_to_date param: value - datetime object param: format - string format """ if value: return value.strftime(format) return ""
670ca7dac70054ce8825b7f2accf808610e79afd
680,471
import torch def average_state_dicts(state_dicts): """Produces an average state_dict from an iterator over state_dicts. Note that at one time, this keeps two of the state_dicts in memory, which is the minimum memory requirement. Arguments --------- state_dicts : iterator, list The st...
28e567b4cda7affb710d46b71862faa95dfb7ab6
680,472
def colvec(vec): """ Convert to column vector """ return vec.reshape(-1, 1)
479de34100ca13ecda09b4c7fc012763737197ea
680,473
def parse_genes(gene_file): """Select gene to exclude: where sgt column is not 'yes' input: csv file with genes return: set of genes which should be exluded""" to_exlude = set() with open(gene_file) as lines: next(lines) for line in lines: gene, _, _, sgt = line.split('\...
91e236e18ee0da44567cdd3c6888e0036b88394d
680,474
def interpret_detection( detections_for_frame, downsampling_factor, is_yolo=False ): """normalizes the detections depending whether they come from centernet or yolo""" if not is_yolo: confs = [1.0] * len(detections_for_frame) labels = [0] * len(detections_for_frame) return detections...
d34001f877fe2e8bc4b400b945f2818bd2a4677b
680,475
def max_dot_product(a: list, b: list): """ >>> max_dot_product([23], [39]) 897 >>> max_dot_product([1, 3, -5], [-2, 4, 1]) 23 """ a.sort() b.sort() return sum([a[i]*b[i] for i in range(len(a))])
8a79591a4b9a99c8f214ab3647e798a5c217ec3e
680,476
def intervals_to_list(data): """Transform list of pybedtools.Intervals to list of lists.""" return [interval.fields for interval in data]
d8ca9ffbc138fb277a329c0a538e3318680b8181
680,477
def gen_first_n_second_n(first_n, first_n_val, second_n, second_n_val): """ Very specific where we fill @param first_n values of the array with the @param first_n_val, and the @param second_n values of the array with @param second_n_val. """ ans = [] for a in range(first_n): ans.a...
57ecf56c2c2398dae9e192532983b879029de1de
680,478
def to_examples(intent_group): """ Parse each row of intent group into a CreateIntent[] """ res = [] for _, row in intent_group.iterrows(): if row['utterance']: # Ignore empty examples res.append({'text': row['utterance']}) return res
57e92f066b9ce8e8439cc48f4e700e45112f72af
680,479
import os def is_process_running(process_id): """ Check whether process is still running. :param process_id: process id (int). :return: Boolean. """ try: # note that this kill function call will not kill the process os.kill(process_id, 0) return True except OSError...
27554be4883f8b450d8843dac191ae11fe774895
680,480
import zlib def encode_deflate(content): """ Returns compressed content, always including zlib header and checksum. """ return zlib.compress(content)
b4d9b8e2f217e702beb5c813177ee58d9525f570
680,481
def consume(queue_name): """ Decorate a function to signal it is a WCraaS consumer and provide its queue name. >>> @consume("awesome_queue") ... def func(): pass ... >>> func.is_consume True >>> func.consume_queue 'awesome_queue' """ def decorator(fn): fn.is_consume ...
55f20c98860fab686e3c11c72663007b81716f44
680,482
import re import os def secure_relative_file_path(file_path): """Return a secure version of file path by making path absolute Parameters ---------- file_path: str The path to file Returns ------- str The path with all relative references removed """ file_path = fi...
db894dd711923f50886cdb41beb9c16179f2ba7f
680,483
def presale_investor_4(accounts) -> str: """Test account planted in fake_seed_investor_data.csv""" return accounts[9]
21e5c64974ccfc00622b3ec39e4815e3dd9c0077
680,484
import functools def curried(func, **fixed_kwargs): """ A universal closure factory: can be used for `currying <http://en.wikipedia.org/wiki/Currying>`_. Works only with named arguments. (Possibly with positional arguments too, but that is untested.) :param callable func: The core function; ...
6600898ccb02156aa56e2c00466e52e8c689904b
680,485
import os def _create_file_path(dirname, basename, suffix="", extension="g3"): """Create the full path to the output file for writing. Parameters ---------- dirname : str dirname for output, likely from _create_dirname basename : str basename of file without extension or suffix ...
42af28629df3b9e3fa9201156792bdcab7f86f34
680,488
import numbers def is_numeric(value): """Return True if value is really numeric (int, float, whatever). >>> is_numeric(+53.4) True >>> is_numeric('53.4') False """ return isinstance(value, numbers.Number)
9fec44333b3f4da7ac33f3a7d970c0cc494ce908
680,489
def RIGHT(string, num_chars=1): """ Returns a substring of length num_chars from the end of a specified string. If num_chars is omitted, it is assumed to be 1. Same as `string[-num_chars:]`. >>> RIGHT("Sale Price", 5) 'Price' >>> RIGHT('Stock Number') 'r' >>> RIGHT('Text', 100) 'Text' >>> RIGHT('Te...
d45021b3d9f89d2cc5ad8533d194a8c6ead87d17
680,490
import os def get_path(file_name): """ Ensure file path is correct wherever the tests are called from """ my_path = os.path.abspath(os.path.dirname(__file__)) return os.path.join(my_path, file_name)
46ffdd562095fcfcc3e2e59a4a462d0d86bdd566
680,491
def _remap_dict_in_range(mydict, newrange=[1, 100]): """function that transform a dictionary in another with the values mapped in a defined range""" def translate(value, leftMin, leftMax, rightMin, rightMax): """local function that maps a single value""" # Figure out how 'wide' each range i...
ad3653d73b5cf5a08f5a3b1344c22e197ffc92f1
680,492
import math def degrees(d): """Convert degrees to radians. Arguments: d -- Angle in degrees. """ return d / 180 * math.pi
27ca9cab77c874af6272731a361f2e6755523f6d
680,494
def shortstr(obj): """ Where to put gritty heuristics to make an object appear in most useful form. defaults to __str__. """ if "wx." in str(obj.__class__) or obj.__class__.__name__.startswith("wx"): shortclassname = obj.__class__.__name__ ##shortclassname = str(obj.__class__).spli...
053c8e499ca52a517eadd6c1bf1f1cb6ff08f750
680,495
import argparse import textwrap def parse_args(): """Process command-line arguments.""" description = """Download data from the Brazilian Flora web service.""" arg_parser = argparse.ArgumentParser( description=textwrap.dedent(description), fromfile_prefix_chars='@') arg_parser.add_arg...
a491d5d9f36165a48a1c48cd94183c60fee15c6a
680,496
def gasoline_cost_sek(dist, sekpl=20.0, kmpl=9.4): """Gets cost of commute via car in Swedish Krona. Input dist: distance in kilometers (numeric) sekpl: Swedish Krona (SEK) per liter (L). Obtained from gasoline_price() function. kmpl: Kilometers (km) per liter (L). (Fuel efficiency) ...
197609d19e7ec3c03cf85e10ef4cbb9aec3d2795
680,497
import collections def weekday_average(datetime_per_sender): """Calculate the weekday average of each sender. :param dict datetime_per_sender: A dictionary with a list of datetime objects for each sender :returns: The average weekday for each sender :rtype: dict(str: int) """ # Average o...
7e3fd8f772e4ccfb171d4f0eabafe62e252504a4
680,498
def reverse_array_2(arr, start, end): """ A method to reverse an array within the given start and end ranges Space complexity = O(1) Time complexity = O(n)/2 :param arr: The array to reverse :param start: The start index within array to reverse :param end: The end index within array to rev...
40a7f1848fbc73f67af8e451823ef140ebc5fc6a
680,499
import typing def trace_lines_model_checking_mode(stdout) -> typing.List[typing.List[str]]: """ Returns list of lists. Each sublist is a list of lines that make a trace. Args: stdout : stdout of TLC execution run in model checking mode """ ret = [] lines = stdout.split("\n") h...
26b57ee29370a764b51961d672c5969050dccb85
680,500
from typing import List from typing import Any def pad_list(l: List[Any], length: int, item: Any) -> List[Any]: # noqa: E741 """Pads a list to the specified length. Note that if the input list is longer than the specified length it is not truncated. Args: l: The input list. length: ...
97b2a11a3e88598ad7f456133b7c7e2779295a96
680,501
def remove_list_items_and_duplicates(input_list, items_to_remove): """ If duplicates exist in input_list they will be removed. If maintaining list duplicates is required, use remove_list_items_and_retain_duplicates instead. """ if input_list is None: return [] elif items_to_remove is Non...
e5e14c4b0e236036870e60a2f758cd6fe57979df
680,502
def too_short(): """ Totally bogus messge that is too short """ return bytes([1, 2, 3, 4])
6430b922e93f4634002f0cf9b457cfb5e76b8c17
680,505
def get_user_id(flickr, user): """Get the user_id from the username.""" user_data = flickr.people.findByUsername(username=user) return user_data['user']['id']
26a4d45cb04b6599c9bb6b519806ebb6e3263b8f
680,506
def indent_level(level): """Display the field.level property""" indentation_depth = 2 indent = " " * indentation_depth return indent * (level - 1)
a68ba91b88283fdafd1665ed29631828667d5b14
680,507
def vac_to_air(vac_wvs): """ following the vald conversion http://www.astro.uu.se/valdwiki/Air-to-vacuum%20conversion """ s = vac_wvs/1.0e4 n = 1 + 0.0000834254 + 0.02406147 / (130 - s**2) + 0.00015998 / (38.9 - s**2) return vac_wvs/n
3e664a32754c208b901b61a96f83bcbb49e97089
680,508
import math def angle_to_pixel(angle, fov, num_pixels): """ angle: object angle fov: field of view of the camera num_pixels: number of pixels along the dimension that fov was measured """ if angle > 90.0 or angle < -90.0: raise ValueError x = math.tan(math.radians(angle)) limi...
498e867ad678aba82815af6d54f35be68a14ade7
680,509
def format_ip(addr): """Format IP addresses""" return str(ord(addr[0])) + '.' + \ str(ord(addr[1])) + '.' + \ str(ord(addr[2])) + '.' + \ str(ord(addr[3]))
f6a4f49e4c4aba8ac1fffcbb2d9aa77b47cba606
680,510
def convert_to_orca_zmatrix(lines): """Convert a proper zmatrix into an orca zmatrix""" # First line element = lines[0].split()[0] orca_zmatrix = [[element, '0', '0', '0', '0', '0', '0']] # Second lines element, atom1, distance = lines[1].split()[:3] orca_zmatrix.append([element, atom1, '0',...
43df31ead00cc32928129f8f0e515b9331cce950
680,511
import argparse def parse_cli_args(): """ Parse command line arguments :return: Parsed CLI arguments from :mod:`argparse`. """ parser = argparse.ArgumentParser( description='Import PEtab-format model into AMICI.') # General options: parser.add_argument('-v', '--verbose',...
223c4e78252e2bcdfc26b5835b05b69b67376d77
680,512
def find_triplet(entry): """Does the string contain a triplet? A letter which repeats with exactly one letter between them. """ for idx in range(2, len(entry)): if entry[idx - 2] == entry[idx]: return True return False
00a5056fe2f4a8d2f32dc5e9b88ac37a94597ccd
680,513
def create_data_dict(data): """ Function to convert data to dictionary format Args: ----------- data: train/dev data as a list Returns: -------- a dictionary containing dev/train data """ train = {} train['para'] = [] train['answer'] = [] train['question'] = [] ...
adf57e19186b2bf4f28a58b50851bb19782cef8c
680,514
import re def replace_halogen(smiles): """ Replace halogens with single letters (Cl -> L and Br -> R), following Olivecrona et al. (J Cheminf 2018). """ br = re.compile('Br') cl = re.compile('Cl') smiles = br.sub('R', smiles) smiles = cl.sub('L', smiles) return smiles
b3c90c8f00518d2f4edda99e4fd69335e69967cc
680,515
def _make_options_dict(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, sign=None, formatter=None): """ make a dictionary out of the non-None arguments, plus sanity checks """ options = {k: v for k, v in local...
03814d267f5438b4269ab92c41c952d04518aa85
680,517
def form_dataframe_to_arrays(df): """ Convert dataframes into arrays in both variables and target """ feature_order = list(df.filter(regex="[^M_t+\d]").columns) X = df.filter(regex="[^M_t+\d]").values Y = df.filter(regex="[\+]").values.flatten() return X,Y,feature_order
2046f0b91a12612a37414832337f18fd108abc2a
680,518
def filter_l2_word(df, col): """ Filter out boxes with < 2 words """ n_words = df[col].str.split().str.len() return df[n_words > 1]
5b8149eb683592957cb3bdd78e34718ca2816c8b
680,519
def svm_test(svm, kernel, features_train, features_test) : """predicts on the test examples""" kernel.init(features_train, features_test) output = svm.apply().get_labels() return output
0f5808d5683ff1ee8837e8ec8aac40ec40915a43
680,520
def service2(backends_mapping, custom_service, service_settings2, service_proxy_settings, lifecycle_hooks): """Second service to test with""" return custom_service(service_settings2, service_proxy_settings, backends_mapping, hooks=lifecycle_hooks)
88abf89aaa12fcfa64881db4829d38f63f094b78
680,521
from typing import Optional import re def _read_url_slug(file_contents: str) -> Optional[str]: """Returns slug parsed from file contents, None if not found.""" regex = r"""url=[^"]+\.[^"]+\/(?P<slug>[-\w]+)(\/|[\w.]+)?\"""" match = re.search(regex, file_contents, re.VERBOSE) if match: return m...
61dbe2186480ed1b0591c1fb2608d419a99ed29c
680,523
import pytz def parse_timezone_arg(value: str) -> pytz.BaseTzInfo: """Parse a timezone argument supplied by a user.""" value = value.lower() if value == "pst": return pytz.timezone("US/Pacific") elif value == "est": return pytz.timezone("US/Eastern") elif value == "cst": re...
f4f832046a57628b75b7c0eb1b9e2aa825e8b3e0
680,524
def permute_dimensions(x, pattern): """Transpose dimensions. pattern should be a tuple or list of dimension indices, e.g. [0, 2, 1]. """ pattern = tuple(pattern) return x.transpose(pattern)
87c7215721c0a02777e40c850f6daaa66f4b0045
680,525
def custom_gradient(*grad_funcs): """Decorate a function to define its custom gradient(s). This is a placeholder in order to have consistent backend APIs. """ def decorator(func): return func return decorator
17cfcdfabeb806a98c58e203ccb7ecdb74ef5da0
680,526
import time def wait_for_spawner(spawner, timeout=10): """Wait for an http server to show up polling at shorter intervals for early termination """ deadline = time.monotonic() + timeout def wait(): return spawner.server.wait_up(timeout=1, http=True) while time.monotonic() < deadline: ...
d9344caf27715789b37b3f19248a727af1eff014
680,527
def mandelbrot_set(left, top, width, height, image_size, max_iter): """Generates an upside-down section of the Mandelbrot Set as pixel data for an image of size `image_size` doing `max_iter` maximum iterations""" dx = width / image_size[0] dy = height / image_size[1] data = [] for y in range(ima...
0e84d829f33562717e5fd3d53a42754af3cc2027
680,528
import base64 def _make_user_code(code: str) -> str: """Compose the user code into an actual base64-encoded string variable.""" code = base64.b64encode(code.encode("utf8")).decode("utf8") return f'USER_CODE = b"{code}"'
066c483b6224dee044275636084c25f228250817
680,530
def find_missing_items(intList): """ Returns missing integers numbers from a list of integers :param intList: list(int), list of integers :return: list(int), sorted list of missing integers numbers of the original list """ original_set = set(intList) smallest_item = min(original_set) l...
8fcc77987834c16875f8a7062e4dcc596a7d7566
680,531
def errormessage(resultstring, expectedstring): """Does the formatting for the error message""" return "\n\nRESULT: %s.\nEXPECTED: %s." % (resultstring, expectedstring)
d3ce5477ca9f942710f3c0d7411160f96d1ddb5f
680,532
def AsList(arg): """return the given argument unchanged if already a list or tuple, otherwise return a single element list""" return arg if isinstance(arg, (tuple, list)) else [arg]
381094573889688dda32b37b8ce8344c9ddf31e9
680,533
def chunk_list(list_to_chunk, chunk_length): """ Returns n-sized chunks from list. """ return [list_to_chunk[i:i + max(1, chunk_length)] for i in range(0, len(list_to_chunk), max(1, chunk_length))]
e874f61f089386de095dd8a17711abd220aa15bb
680,535
def getMessage(row): """ Return a message tuple representing the text message. Assuming that row is an array having 3 elements """ return (row[0], row[1], row[2])
a798354d6bc3ac5147472e1dbb4d537dddec387d
680,536
def interactive_elem(elem, name, *args, **kwargs): """ Function useful for wrapping a wide range of ImGui widgets. Elements which take `name` as the first argument and return a pair `(changed, value)` can be wrapped using this function. It is used to wrap many imgui widgets in `concur.widgets`. """...
0bf1ff3a954d49fbd042a7badfb295282a747686
680,537
import io def has_fileno(stream): """ Cleanly determine whether ``stream`` has a useful ``.fileno()``. .. note:: This function helps determine if a given file-like object can be used with various terminal-oriented modules and functions such as `select`, `termios`, and `tty`. For m...
5daa9f765a9c706a085b97b6d63d67ed9ebb72d3
680,539
def select_dropdown(options, id=None): """Generate a new select dropdown form Parameters ---------- options: List[str] list of options the user can select id: str DOM id used to refer to this input form """ html_options = ''.join(f'<option>{opt}</option>' for opt in options...
001f8f61def33b33611158a34a2dc7416b6f382c
680,540
import re def _latex_preprocess(latex_str: str): """Attach Planetmath Latex commands and neatly print bibiliography.""" # Add a subsection (h2) named 'References' for bibliography. latex_str = latex_str.replace('\\begin{thebibliography}', r'\n\subsection{References}\n\begin{thebibliography}') latex_st...
bbbfe55e28342388569c2af3b8f71f6adb8d8eee
680,541
def add_precedence_edges(cropobjects, edges): """Adds precedence edges to CropObjects.""" # Ensure unique edges = set(edges) _cdict = {c.objid: c for c in cropobjects} for f, t in edges: cf, ct = _cdict[f] ,_cdict[t] if cf.data is None: cf.data = dict() ...
c684251b3e4a2db01d2b3dfea3b8e549ecfcdc68
680,542
def is_valid_parentheses(s: str) -> bool: """ >>> is_valid_parentheses('()[]{}') True """ if not s or len(s) % 2 != 0: return False stk = [] for bracket in s: if bracket not in "({[)]}": return False if bracket in "({[": stk.append(bracket) ...
9079eac198ca6eec060532aa79e6f7394bd6daba
680,543
from typing import List from typing import Any import numpy def get_vector_given_sequence( tag_sequence: List[Any], layout: List[Any] ) -> numpy.ndarray: """ This method is mainly useful for when we are to represent a sequence as a vector. Parameters ---------- tag_sequence: ``Lis...
93c62c8cee624c44a2b2e3143e80a8b4ae644b31
680,544
from typing import Dict def repair_template(data: Dict, lprint = print, eprint = print): """ Should apply fixes inplace on dictionary data :param data: Data dictionary :param lprint: function to use to log information :param eprint: function to use to log error information :return: Return cod...
364be97d8b9869b4328c632459d8a4675426a21f
680,545
def read(path): """ Read a file """ with open(path) as file_: return file_.read()
28143cce26b90e1fbea16554f80900da23b37ba6
680,546
import math def dist2pt(xa, xb, ya, yb): """distance entre deux points calcul""" calc = math.sqrt((xb - xa) ** 2 + (yb - ya) ** 2) return calc
a945e9034d4cf129be3da9e71bd26b0f6cd7ff56
680,547
def createDict(data, index): """ Create a new dictionnay from dictionnary key=>values: just keep value number 'index' from all values. >>> data={10: ("dix", 100, "a"), 20: ("vingt", 200, "b")} >>> createDict(data, 0) {10: 'dix', 20: 'vingt'} >>> createDict(data, 2) {10: 'a', 20: 'b'} ...
3afb604d81401cd4c5b1cac93fb26b05ab1fdb24
680,548
import textwrap def minimal_config(): """Return configuration text""" return textwrap.dedent( r""" static_data_config: {} step_config: {} data_sets: first_batch: sodar_uuid: 466ab946-ce6a-4c78-9981-19b79e7bbe86 file: sheet.tsv sea...
31c42a8199eb0efac4d60d2ca35ffa7174fa4f8e
680,549
def is_port_vlan_member(config_db, port, vlan): """Check if port is a member of vlan""" vlan_ports_data = config_db.get_table('VLAN_MEMBER') for key in vlan_ports_data: if key[0] == vlan and key[1] == port: return True return False
03a0de5b285fd7295526b1ef63d12629e27d9c8e
680,550
from typing import List import random def uniformly_split_num( sum: int, n: int, ) -> List[int]: """Generate `n` non-negative numbers that sum up to `sum`""" assert n > 0, 'n should be > 0' assert sum >= 0, 'sum should be >= 0' random_numbers = [random.randint(0, sum) for _ in range(n - 1)] ...
8136cce9bd258e7b187646967402dc428f04a764
680,551
def _update_count_down(previous_count_down_minutes, check_mail_interval, current_time, start_time, main_window) -> int: """ Utility method, update status message text ("count down") until next mail check begins :param previous_count_down_minutes: current state of counter :param check_mail_interval: give...
8f94896afe63cf61399e1ef5341e258216a8b59d
680,552
import numpy def stiffness_matrix(c, t): """ Utility routine to construct the stiffness matrix, K, based on the coefficient function c(x) and partition t. This matrix includes rows for the boundary nodes. """ Ke = numpy.array([[1, -1], [-1, 1]], dtype=float) n = t.size-1 h = t[1:]-t[:...
0f366111c4dcf61925600346806cc572a7e68dcd
680,553
async def get_int_list(redis, key): """Get a list of integers on redis.""" str_list = await redis.lrange(key, 0, -1) int_list = [int(i) for i in str_list] return int_list
61f84ba3122deaaaf3aba7d22312242b24161724
680,554
def swap_list_order(alist): """ Args: alist: shape=(B, num_level, ....) Returns: alist: shape=(num_level, B, ...) """ new_order0 = len(alist[0]) return [[alist[i][j] for i in range(len(alist))] for j in range(new_order0)]
ad73a3e74b18e8b2b6bc12d879c7477d673f3faa
680,555
import os def FindVtuFilenames(project, firstId, lastId = None, extensions = [".vtu", ".pvtu"]): """ Find vtu filenames for a Fluidity simulation, in the supplied range of IDs """ if lastId is None: lastId = firstId assert(lastId >= firstId) filenames = [] for id in range(firstId, lastId...
cbfe2ec5bc273285b812e0d67f276ff8d6f5328c
680,556
def PWM_scorer(seq, pwm, pwm_dict, pwm_type): """ Generate score for current seq given a pwm. """ seq_score = 0.0 for i in range(0, len(seq)): seq_score += pwm[pwm_dict[seq[i:i+1]]][i] return seq_score
e15cc95d972626ace134c2525b77895bb18ee882
680,557
def get_type(node): """ get type """ return node.func.attr
dde378ce1dddf56ee68030554b19c3a9e4315367
680,558
def _collect_facts(operators): """ Collect all facts from grounded operators (precondition, add effects and delete effects). """ facts = set() for op in operators: facts |= op.preconditions | op.add_effects | op.del_effects return facts
61fe46177502cdd164df65b4332fb66176c10641
680,559
def compile_truncate_table(qualfied_name): """Delete all data in table and vacuum.""" return 'TRUNCATE %s CASCADE;' % qualfied_name
e4e02e5ca26ac5c5e662c041f0a0a1ab59fa4169
680,560
def move_outflow(outflows,original_outflow_coords,new_outflow_coords, flowmap=None,rdirs=None): """Move the outflow from one point to another""" downstream_cell_map = [(1,-1),(1,0),(1,1), (0,-1),(0,0),(0,1), (-1,-1),(-1,0),(-1,1)] if ori...
5040a9c1c3600d8a984c19e31c92e4f4c614ad92
680,562
import math def _brevity_penalty(candidate, references): """Calculate brevity penalty. As the modified n-gram precision still has the problem from the short length sentence, brevity penalty is used to modify the overall BLEU score according to length. An example from the paper. There are three r...
b56c53730b2a90581a89f8cffa51f34c5d643984
680,563
def parse_args(request): """ Parse api query parameters """ title = request.args.get('title').replace(" ","_") ## pass arguments args = { 'title': title, } return args
1d7b8a061addfa6f3f854d60696dbbae28f1cc19
680,564
import os def _script_path(): """Returns the path to the dir this script is in""" return os.path.dirname(os.path.realpath(__file__))
a30d549e195723efad0206070c4b43314d9922c1
680,566
import hashlib import json def hash_dump(data): """Hash an arbitrary JSON dictionary by dumping it in sorted order, encoding it in UTF-8, then hashing the bytes. :param data: An arbitrary JSON-serializable object :type data: dict or list or tuple :rtype: str """ return hashlib.sha512(json.dum...
7dc9cc75df3c3b2e9c9aa7207bfcd11c236f26c6
680,568
def clean_dict(dictionary): """ Remove items with None value in the dictionary and recursively in other nested dictionaries. """ if not isinstance(dictionary, dict): return dictionary return {k: clean_dict(v) for k, v in dictionary.items() if v is not None}
50d87d097b00cee3a8c1fb1d6e4c4f7b7237c5e0
680,569
def get_padding_prp(hparams): """Get padding for pad_rotate_project measurements""" if hparams.dataset == 'mnist': paddings = [[0, 0], [6, 6], [6, 6], [0, 0]] elif hparams.dataset == 'celebA': paddings = [[0, 0], [14, 14], [14, 14], [0, 0]] else: raise NotImplementedError ret...
a26c6286aa6624baa2bb37de2eac29d124992586
680,570
def get_post_data(request): """ Attempt to coerce POST json data from the request, falling back to the raw data if json could not be coerced. :type request: flask.request """ try: return request.get_json(force=True) except: return request.values
c59aa6bd4d8059517761a4ec641b1a5f35ee075d
680,571
def sort_by_hw_count(user): """Sort students by the number of completed homeworks""" return sum([1 if hw['status'] == 'success' else 0 for hw in user['homeworks']])
f2d2818f207e09551ac54acae0080c689fc033e6
680,572
def getOrientation( geom , camera=True): """ build and return a dictionary storing the orientation for geom orientDict <- getOrientation( geom ) """ orientMem = {} orientMem['rotation'] = geom.rotation[:] orientMem['translation'] = geom.translation.copy() orientMem['scale'] = geom.scal...
c2affdabdc3cad50c5ed673ddb6739d6a96fe589
680,574
import os def get_abs_path(file): """if the file exists, return its abspath or raise a exception.""" work_path = os.path.abspath(os.getcwd()) if os.path.isfile(os.path.join(work_path, file)): return os.path.join(work_path, file) elif os.path.isfile(file): return file else: ...
dcc870ec92921d496939e6bc2bb40009e2deecc1
680,575
from datetime import datetime def timestampms_to_timestamp(timestampMs): """Summary line. timestampMsをtimestampに変換する Args: timestampMs(str) : timestampMs Returns: timestamp : タイムスタンプ(%Y%m%d%H%M%S) """ timestamp = datetime.fromtimestamp(int(timestampMs[:10])) return time...
b854f827fd810d18c020376c822f18611f715a59
680,576
def patch_from_tupled_dict(tupled_dict): """ Creates a nested dictionary that f90nml can interpret as a patch.""" patch = {} for replace_this, replace_val in tupled_dict.items(): group, field = replace_this group, field = group.lower(), field.lower() gdict = patch.get(group, {}) ...
325f563aea1e53560e4c3837f9f2028da9e1e504
680,577
import yaml def yaml_to_base_type(node, loader): """ Converts a PyYAML node type to a basic Python data type. Parameters ---------- node : yaml.Node The node is converted to a basic Python type using the following: - MappingNode -> dict - SequenceNode -> list - Sca...
f72650a71a7e3e7bcc1fe460c6e72acb7519fc98
680,578
import re def find_note_contents_start(md_text_lines): """ Some notes in Bear contain #tags near the title. This returns the index in the list that\ isn't the title or contains tags. If no index found, return len(md_text_lines) """ # Start at 1 to skip the title # Look for regex matches of tag...
d532657a78c259f60008fed6c3d14ed9779be6a9
680,579