content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os import json def _get_fixture(fixture_name): """Reads a fixture from a file""" with open( os.path.join(os.path.dirname(__file__), "fixtures/{}".format(fixture_name)), "r" ) as f: return json.load(f)
de83bf433015c013b0fc3b2b6cdbfb3ae3bab8ea
644,009
def solution(): """Returns the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. >>> solution() 142857 """ i = 1 while True: if ( sorted(list(str(i))) == sorted(list(str(2 * i))) == sorted(list(str(3 * i))) ...
0b82d54fa546e49800835c91a3f9c4cd73babd94
644,011
def save_spectrum(qso_spec_obj): """ :type qso_spec_obj: QSOData :return: """ qso_rec = qso_spec_obj.qso_rec index = qso_rec.index ar_wavelength = qso_spec_obj.ar_wavelength ar_flux = qso_spec_obj.ar_flux ar_ivar = qso_spec_obj.ar_ivar return [index, ar_wavelength, ar_flux, ar_i...
cb9be78f578a052c90ba5930b4c5e628d7d0eb6f
644,012
import re def replace_argument(script, from_, to): """Replaces command line argument.""" replaced_in_the_end = re.sub(u' {}$'.format(re.escape(from_)), u' {}'.format(to), script, count=1) if replaced_in_the_end != script: return replaced_in_the_end else: ...
44f7dd41004f77e15d8e04a913941f61d6c01244
644,013
import functools def if_true(toggle_attr): """Returns a decorator that executes its method if a condition is met.""" def if_true_decorator(instance_method): """Execute the decorated method conditional on a toggle attribute.""" @functools.wraps(instance_method) def wrapper(self, *args, ...
6cfcb384eb133a8558755136b66329c8ce266af5
644,014
import hashlib def key_sha1(*args): """This method creates an SHA-1 from the input parameters, used for caching filename""" return hashlib.sha1("".join(str(args)).encode("utf-8")).hexdigest()
b38cc450a2714abd3951915ec7d50bcd11f2a892
644,015
def add_to_dict(d, key, base): """Function to add key to dictionary, either add base or start with base""" if key in d: d[key] += base else: d[key] = base return d
a13cbd99956bc551999cf30a39e87fb5dde90ece
644,016
def boundary_to_mosaic_window(boundary_gdf, crs): """Get tuple of xy coordinates from input geodataframe. Args: boundary_gdf (geopandas.GeoDataFrame): Geodataframe from which full extent coords will be extracted. crs (str): The coordinate reference system for the window in EPSG:<code> format. ...
58e146d7c46545bfacd3ff8f92d4b623c7c7701d
644,017
def make_columns_grammar(columns): """Return a lark rule that looks like // These are my raw columns str_0: "[" + /username/i + "]" | /username/i str_1: "[" + /department/i + "]" | /department/i str_2: "[" + /testid/i + "]" | /testid/i """ items = [] for k in sorted(columns.keys()): ...
9ee62b9fee1bfb66ab5ec49b90420d401b1200f7
644,019
def only_once(fn): """Decorate the given function to be a no-op after it is called exactly once.""" once = [fn] def go(*arg, **kw): if once: once_fn = once.pop() return once_fn(*arg, **kw) return go
2deea9d3f5db39476f601082ecf0aa1341f04394
644,020
def add_model_params_tree(info_dict): """Adds model parameters to `info_dict` for tree models. Only model-related parameter information will be added in this function. A series of these functions are used in a flow to get all information needed in tree model summary. The flow is `~greykite.algo.com...
7e2fdc4e576ee26e3f0f70da2d2d7083369bf35c
644,021
import string def buildGoodSet(goodChars=string.printable, badChar='?'): """Build a translation table that turns all characters not in goodChars to badChar""" allChars = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+...
34e31f3aeb62204572304858c59298f348651b98
644,022
import re def get_offsets(cam_section): """ Convert a CAM string containing a number, a linear-units string, a space, another number, and another linear-units string, to a tuple of two floats representing inches. """ units = { 'mil': (1 / 1000.0), 'cm': (1 / 25.4), 'mm': (1 / 25.4...
d5f2e544c37487cf93d2850fbc79612862713193
644,023
def get_newsentry_meta_description(newsentry): """Returns the meta description for the given entry.""" if newsentry.meta_description: return newsentry.meta_description # If there is no seo addon found, take the info from the placeholders text = newsentry.get_description() if len(text) > 16...
9a0713978e513129ae7487d4d5a34e5b2eedd0c1
644,024
import base64 def javascript_uri(html, filename=""): """Because data-uri for text/html is not supported by IE.""" if isinstance(html, str): html = html.encode("utf-8") return ( "javascript:(function(el){{" "var w=window.open();var d='{}';" "w.document.open();" "w.do...
329064696f0754dbf869b856698186422c831c5f
644,025
import os def find_config(name='config.ini'): """ :param name: config file name (defaults to 'config.ini') """ # start in cwd and work downwards towards filesystem root path = '.' # Stop before falling off root of filesystem (should be platform # agnostic) while os.path.split(os.path.a...
fee107dad9a7744c8d58da9d67c094815452cfcc
644,026
def CleanFCSstring(strFCS): """ If string can be converted to int, then returns clean string with only the int. othervise returns '-1'.""" try: return str(int(strFCS)) except: return "-1"
b14ec6642f6d4bc822059bc7fdaaceaa63e1eeb7
644,027
import multiprocessing def get_num_cpus(): """ Get the number of CPU processes on the current machine. Returns: Integer of the number of CPUs on the current machine """ return multiprocessing.cpu_count()
21ee30d77bcfbd39dee0cee6a3c98a52699c5486
644,028
def nrcs_cutoff(precip, curve_number): """ A function to find the cutoff between precipitation/curve number pairs that have zero runoff by definition, and those that do not. """ if precip <= -1 * (2 * (curve_number - 100.0) / curve_number): return True else: return False
448e894fae7dd79b7673bb068cdb1d0e84c056d4
644,029
def local_extra_dirs(func): """Non-local plugin decorator using local directories for the extra_dirs (job_work and temp).""" def wraps(self, *args, **kwargs): if kwargs.get('base_dir', None) is None: return func(self, *args, **kwargs) else: for c in self.__class__.__mro_...
cb3a6ec3b8de411896a9a49d7cda837790770828
644,030
from typing import Any import ast def _is_lexical_match(matched: Any) -> bool: """Returns whether the match can be a lexical one. Its not well documented what ast objects return token information and which ones don't, and there are known instances of the token information being wrong in certain cases. Arg...
faf8ea20b02e0a38219ab1e9b0495d06fcc0bb54
644,031
def dest_times(t): """Given t1 * t2, return (t1, t2).""" assert t.is_times(), "dest_times" return (t.arg1, t.arg)
ce6c36e5076f4f306e27ec4afd751e34dc4a69a0
644,032
import inspect import warnings def deprecated(func, solution): """ Mark a parser or combiner as deprecated, and give a message of how to fix this. This will emit a warning in the logs when the function is used. When combined with modifications to conftest, this causes deprecations to become fatal...
1b7b8c27cc1eac1695c26181f53d04523874c270
644,033
import torch def image_distance(x: torch.Tensor, y: torch.Tensor, order=2) -> torch.Tensor: """Returns the distance between two batches of images Args: x (torch.Tensor): First batch of images y (torch.Tensor): Second batch of images order (int, optional): Order of the norm. Defaults t...
730704fb1b3e5ba0b748316b4c30102e0888ad7b
644,034
def get_inputfile(atom_strs, coordinates, charge, spin, header, footer=None, **kwargs): """ """ inputstr = header + 2 * "\n" inputstr += f" {kwargs['title']}" + 2 * "\n" inputstr += f"{charge} {spin} \n" for atom_str, coord in zip(atom_strs, coordinates): inputstr += f"{atom_str} " + " ...
d2568046fd1c67c0a25357030583486925a56ca3
644,035
def gower_normalization(K): """ Perform Gower normalizion on covariance matrix K the rescaled covariance matrix has sample variance of 1 """ trPCP = K.trace() - K.mean(0).sum() r = (K.shape[0]-1) / trPCP return r * K
ea6131fa6ce8e12b21beb2bd27561b82cbc9fd4f
644,036
def escape_nmap_filename(filename): """Escape '%' characters so they are not interpreted as strftime format specifiers, which are not supported by Zenmap.""" return filename.replace("%", "%%")
c33a77405caca59d5a0f5ba9eee1acb1e6e6914d
644,037
def shift_and_zero(buf): """Shift 1 -> 0, and zero out 1.""" buf[0, :] = buf[1, :] buf[1, :] = 0.0 return buf
530eb99730d5dbc9964667bd3d3bdfcf6fe9a4c6
644,038
def to_aws_tags(tags): """ Convert tags from dictionary to a format expected by AWS: [{'Key': key, 'Value': value}] :param tags :return: """ return [{'Key': k, 'Value': v} for k, v in tags.items()]
c038d183f2456179d134692d50bfddcd9249b976
644,039
def duplicate_count(text): """ Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric dig...
ef58a9990849b1c52cd7e0236a77730ec794a446
644,040
def limit_to_interval(a,b,score_sent_pairs): """score sent pairs: list of tuples (score, sent)""" return list(filter(lambda x: a<x[0]<b, score_sent_pairs))
425016611a2b5bdae996317cddb10566c963b66b
644,041
def damping_from_reduction_factor(eta): """ Inversion of reduction factor equation :param eta: :return: """ return (0.07 / eta ** 2) - 0.02
1fabb183a684da55ca9558236a938e09a83571ce
644,042
import time def epoch2iso(timestamp): """Returns the ISO representaton of a UNIX timestamp (epoch). >>> epoch2iso(1620459129) '2021-05-08 09:32:09' """ timestamp = float(timestamp) return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
d8238b50189417db302846f4c194b6d3bd04ce3f
644,044
import gzip import sys def fetch_lines(file=None): """Gets the lines from the given file or stdin if it's None or '' or '-'.""" if file and file != '-': with gzip.open(file, 'rt') if file[-1] in 'zZ' else open(file, 'r', encoding='utf-8') as f: return [l.strip() for l in f.readlines()] ...
900a62e9d83e208e50a241f3db84a23049e04879
644,045
def convert_to_xs_and_ys(waypoint, lon_min, lon_max, lat_min, lat_max, w, h): """Convert from a list of positions to their x/y coordinates in the image.""" xs = [] ys = [] for step in waypoint: xs.append((step["lon"] - lon_min) / (lon_max - lon_min) * w) ys.append((lat_max - step["lat"...
d61c753c12f058c4332c7dd543fa707e8240f2ec
644,046
def process_picker(args, proclist): """Pick a process according to the command line arguments.""" candidate = None # Match by PID if args.pid and args.pid in proclist: candidate = proclist[args.pid] # Match by exact name elif args.process: for proc in proclist.values(): ...
89b302ebc590ff5078f4548858adef6edc6bffad
644,047
def playfair_decrypt_col_pair(grid, pair): """if two letters are in the same col, this is the method to decrypt Args: grid ([list]): [list of the playfair grid] pair ([str]): [pair of strings in form e.g "AB"] Returns: [first_decrpyted_letter, second_decrpyted_letter]:...
c1c8b2326b2bdaeff4b166afe81fb6c0fcc9be1c
644,048
import os import re def directory(directory_path): """Puts you in the right directory. Gives you list of files in path""" os.chdir(re.findall("^(.*[\\\/])", directory_path)[0]) csv_files = os.listdir(directory_path) return csv_files
25d647e9155169ea6ea45c962b9e37b68d24b8f4
644,049
import re def validate(single_passport): """Validate passport vals""" valid = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] ecl_valid = ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'] vflag = True for v in valid: if v not in single_passport: vflag = False if vflag: ...
943de6f39b1c8feba45e09d262710c7333214201
644,050
import binascii def b64encode(s, altchars=None): """Encode a byte string using Base64. s is the byte string to encode. Optional altchars must be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or f...
0a31ffe5eaf307657e27a77fe7d3859cdeeb068a
644,051
def ensure_str(s): """ Simple conversion of the value `s` to a `str`, that is, a byte string on Python 2 and a unicode string on Python 3. Input is expected to be a byte-string or unicode string in both Py2 or Py3. """ if not isinstance(s, str): return s.decode('utf-8') return s
c1ea872f96043c9be2e3676190e0491a87fd8827
644,052
import sys import csv def parse_table(input_grid): """Given an input grid in TSV or CSV, get the data as a dictionary. Also set the headers for the HTML grid. """ global headers data = {} if ".tsv" in input_grid: delim = "\t" elif ".csv" in input_grid: delim = "," else...
268d726791606de43fec3c42a2a988e9ecde4108
644,053
def verify_node_verifiers(G): """ Node classes can define their own verifiers """ problems = [] for node in G.nodes(): problems.extend(node.verify(G)) return problems
b25c5929236323355e6c9b94c7d6686651971e9c
644,054
def header_line_to_anchor( line ): """ duplicate (approximately) the GitLab algorithm to make a header anchor """ s1 = line[3:].strip().replace( '=', '' ) s2 = ' '.join( s1.split() ) s3 = s2.lower() return s3
3690349eff03731ee0bec8cb1e51d3e2f6ee269f
644,055
def get_cli_input_year() -> str: """Get CLI input for the year of the car""" car_year = input("Enter the year of the car: ") return car_year
79e8636cd5f0b58b495f7e7b71b011fa1be35d44
644,056
def argify(argname, argval): """ :param argname: String naming a parameter for a script called from terminal :param argval: Object to assign in string form as the value of the argument :return: String, a parameter assignment for a script called from terminal """ return "--{}={}".format(argname, ...
b22872fa7e3b4ec532b8b5ccf0d09db72fa1aaa6
644,057
def human_size(bytes, units=None): """Returns a human readable string representation of bytes""" if not units: units = [" bytes", "KB", "MB", "GB", "TB", "PB", "EB"] return str(bytes) + units[0] if bytes < 1024 else human_size(bytes >> 10, units[1:])
89d9eb04b0eff0289c4b03960a49840fd0e5be63
644,059
def normalizeHomogenious(points): """ Normalize a collection of points in homogeneous coordinates so that last row = 1. """ for row in points: row /= points[-1] return points
88f6927989e6247784f82ad90b4da979ca129c57
644,060
def get_wikitables_from_string(string): """ Get raw wikitables from "unstructured" string :param string: :return: list of raw wikitables """ last = '' in_table = False newline = False waiting = False temp_string = '' table_count = 0 list_of_tables = [] table_nest_le...
e9274b9241f019ff377d18a869ce46383e2400fb
644,061
def float_param_options_method_dict(optionName, portName): """Creates a method dictionary for a module that has one port taking a floating-point value. This dictionary will be used to dynamically create a VisTrails module. """ def compute(self): o = self.create_output_file() option...
5c392207e970afad35952a5da8286819313ec219
644,062
def count_parameters(net, as_int=False): """Returns total number of params in a network""" count = sum(p.numel() for p in net.parameters()) if as_int: return count return f"{count:,}"
d52db72eced2c536292f4f398485505b95a83578
644,063
def final_reclassifier(original_classifier, seq): """Reclassify the strategy""" original_classifier["makes_use_of"].update(["length"]) original_classifier["memory_depth"] = max( len(seq), original_classifier["memory_depth"] ) return original_classifier
ce95b5b47a9f3329e030060b51488d311036042a
644,064
def count_chars(template: str, instructions: dict[str, str], n: int) -> int: """ Counts the characters in the would-be string after `n` steps and returns the highest count (most common) - lowest count (least common). Args: template (str): The polymer template e.g. "NNCB" instructions (d...
16b639b0e07eb719d392992d92513c85375a59b2
644,065
def parameter_lr(): """Specify the relative learning rate for every parameter. The final learning rate in every parameter will be the one defined here multiplied by the global one Args: Returns: Dictionary with the relative learning rate for every parameter """ vars_corresp = dict() var...
8e5bf2459d600e76807eee21955c332cc0accdf8
644,066
def test_ris_file_exists(ris_path): """Test if an RIS file exists. Returns: True -- if file can be opened False -- if file cannot be opened """ if ris_path.endswith(".ris"): try: open(ris_path, 'r') return True except IOError: print("...
8a58df37f76644cef3d8fe613a6e417962c7058d
644,067
import re def song_name_extractor(file_link): """ Pulls out song name from file path, strips disc/track numbers and file extension. --- IN file_link: os path to audio file (str) OUT sname: song name (str) """ # first pattern takes everything between last / and .ext p1 = r...
41b29c9944e2d24e510db4b525ec6a0aac56e82c
644,068
def get_integrated_mean(depth_list, value_list, depth_interval): """ Created: by Magnus Wenzer Last modified: 20180423 by Magnus Wenzer This seem slower than "get_integrated_mean" """ # depth_list = list(depth_list) #...
333d869f733876ba35da667054c88f93c868b7d6
644,069
def sha_padding(used_bytes, align_bytes): """ The SHA3 padding function """ padlen = align_bytes - (used_bytes % align_bytes) if padlen == 1: return [0x86] elif padlen == 2: return [0x06, 0x80] else: return [0x06] + ([0x00] * (padlen - 2)) + [0x80]
b281d22eb7ba138fd851f35080e7e8e14ef4acc5
644,070
def optimized_bubble_sort(numbers: list) -> list: """ This function implements the Optimized Bubble Sort algorithm. """ # check if the list is empty if len(numbers) == 0: raise ValueError("Empty List") # check if the list contains only numbers for number in numbers: if not is...
b604cb71ca36e6715ef2a242243ead1f365bd172
644,071
def has_blank_ids(idlist): """ Search the list for empty ID fields and return true/false accordingly. """ return not(all(k for k in idlist))
bb25fc94c6ba3bedad1597b21032d8cd998bbccf
644,072
import math def applyPan(min_, max_, panFactor, isLog10): """Returns a new range with applied panning. Moves the range according to panFactor. If isLog10 is True, converts to log10 before moving. :param float min_: Min value of the data range to pan. :param float max_: Max value of the data rang...
152eae9f48a6831c3d2059a074605e35daf5df27
644,074
def multiply(a, b): """Multiply x and y""" b += 1 print (a, b) pepe = a * b print (pepe) return pepe
8766ce39dc74defde0f32f1ed06424a4c8bd7193
644,077
def get_local_settings(): """ local settings for C++ codes """ setting = { # end time "end_t": 5.0, # critical time, after which print out more data points "critical_t": 5.0, # reference time, real time, to a combustion system, this is gonna be the ignition delay ...
293077eaa01afa8634ccd88fae94086142de14e3
644,078
import glob import os import fnmatch def traverseFolders(topFolder='/SAN/medic/Net_Mod_MS/HCPData/ADNIGIF3_SC', wildcard='*_5TT_gif3.mif', depth=1): """Traverses the file hierarchy within topFolder looking for files named *_5TT_gif3.mif (or other supplied wildcard) and returns a list containing the paths, in...
7a0eb65e4337012a45e2c0953b16810307c1dc0f
644,079
def has_real_message(l): """ Determine if module has any real messages. """ return any(m.static and m.is_real_message for m in l)
414c27448cc981821645685fe6e331f988e2a5db
644,081
from typing import List def find(arr: List[int], key: int) -> int: """Modified version of binary search: one half of the array must be already sorted. Therefore check the sorted half to decide whether to search the left or right half. This takes O(lg n) time and O(1) space. """ lo = 0 hi = len...
b4a49cc73009b27344fc403a79c26130339b5d04
644,082
import os def is_valid_mypy_path_entry(path_entry: str) -> bool: """ We try to configure MYPYPATH to be the same as PYTHONPATH, but without any site-packages directories. Otherwise, mypy gives us the following message: .../site-packages is in the MYPYPATH. Please remove it. See https://mypy.readt...
f967b042f71e63352a976bca3553b3ea595d0e66
644,083
def after_request(response): """设置默认的响应报文格式为application/json""" # 如果响应报文response的Content-Type是以text开头,则将其改为默认的json类型 if response.headers.get('Content-Type').startswith('text'): response.headers['Content-Type'] = 'application/json' return response
c244c9d0a6500e37a6fc80c1910af5bf7c1412ee
644,084
def error_margin_sample(z_star, SE): """ Get the margin of error of a sampling distribution. Parameters ---------- > z_star: the critical score of the confidence level > SE: the standard error of the sample Returns ------- The margin of error, given by z_star/SE. """ return z_star / SE
3574771cd0a7778ff58a9de88c824a2cabf9a5c3
644,085
def beta(asset_returns, market_returns, window): """ Calculates the beta, or market risk premium """ rolling = market_returns.rolling(window) return rolling.cov(asset_returns) / rolling.var()
29de40933c8c65906d29f29dda7dca1a0b5e544a
644,086
from typing import Union from typing import IO from typing import Counter from typing import Optional from typing import Dict from bs4 import BeautifulSoup import json def _puzzle_json_from_file_or_str(input_data: Union[IO, str], ctr: Counter) -> Optional[Dict]: """ Take a file handler, fh, representing HTML ...
3626f994593f08aa6997fbdce71043928b4c28b6
644,087
from typing import Mapping from typing import Any from typing import Union from typing import Sequence import functools import operator def recursive_getitem(d: Mapping[str, Any], keys: Union[str, Sequence[str]]) -> Any: """Recursively retrieve an item from a nested dict. Credit to: https://stackoverflow.com...
290bd14d940da28562883d60c3654d2bbc0e0d3c
644,088
def group_type(type_string): """ Surround a type with parentheses as needed. """ return ( '(' + type_string + ')' if '|' in type_string else type_string )
d1e17463bfec696f19c0009d7d006c7e9672ee74
644,089
from typing import List import os def list_files(folder_path: str, extension: str) -> List[str]: """get paths of files ending with <extension> in a folder""" filenames = [f for f in os.listdir(folder_path) if f.endswith(extension)] return sorted([os.path.join(folder_path, f) for f in filenames])
7330eb37c856f39ff3ac105019a2fd16bf5c590e
644,090
from contextlib import suppress def unbound_method(method): """ Allow to use single-argument functions as input or output processors (no need to define an unused first 'self' argument) """ with suppress(AttributeError): if '.' not in method.__qualname__: return method.__func__ ...
e341cf554ff7bb1297f0166ecbe03f1b9fff0ec3
644,091
import sys def fs_encoding_is_utf8(): """ :return: True if the current filesystem encoding is set to UTF-8 """ return sys.getfilesystemencoding() == 'utf-8'
737bf6da5c66602fb656273eb4c4e8de7d9f15f0
644,092
def isExist(browser, xpath): """ 判断页面中是否存在此元素 :param browser: 浏览器对象 :param xpath: 要判断的元素的xpath :return:bool """ try: browser.find_element_by_xpath(xpath) return True except: return False
3606964e4d0caa2e56053b7855950567d3bfd81c
644,093
import numpy as np def arnoldi_iteration(A,b,nimp): """ Input A: (nxn matrix) b: (initial vector) nimp: number of iterations Returns Q, h """ m = A.shape[0] # Shape of the input matrix h = np.zeros((nimp+1, nimp)) # Creats a zero matrix of shape (n+1)x n Q = np....
148526a94239da4093bb25112c332f53cd47a9a2
644,094
import os def create_temporary_dir(name='tmp'): """Creates temporary directory and returns its path. When running tests in the install tree, a temporary folder is created by bazel and its path is accessible by getting the value of `os.environ['TEST_TMPDIR']`. However, in the install_test_helper frame...
7dadbd7ff87f275967b803799c04f03de6b7e1cb
644,095
import os def number_of_files_in_folder(folder): """ checks the presents of a folder and counts the number of files it contains. returns number of files found or -1 if the folder is not present. """ if not os.path.exists(folder): return -1 nfiles = 0 for root, dirs, files in os.wal...
7d9f284a78d6ae0c610c6596c490a51cc3f1e0b5
644,096
from typing import Union from typing import Tuple def get_input(params: Union[dict, list]) -> Tuple[list, dict]: """ Get positional or keyword arguments from JSON RPC params :param params: Parameters passed through JSON RPC :return: args, kwargs """ # Backwards compatibility for old clients t...
563b87ad6f4dde1a5e8021b656efa299567acf35
644,097
import re def search_string(data_fetched): """ Function to search the returned email string for the word 'Hi' and return the words after it. Chose to collect 90 expressions after the keyword to ensure variance in the length of ship names and locations are accounted for. It returns the matched stri...
c12287026d000d7df26c9c82e167d560ddee8203
644,098
def _pseudo_voigt_mixing_factor(width_l, width_g): """ Returns the proportion of Lorentzian for the computation of a pseudo-Voigt profile. pseudoVoigt = (1 - eta) Gaussian + eta * Lorentzian Parameters ---------- width_l, width_g : float FWHM for the Gaussian and Lorentzian parts, r...
7723370d749c62dcddcbf95272727baa9995f23a
644,099
def make_refresh_script(path, x_rebuild_time): """ Create a snippet of javascript to inject into static pages. The snippet should reach back to our http server and long-poll for updates. """ x = str(x_rebuild_time).encode("utf8") return ( b''' <script> start_check = function...
82c1bcaf7c7e9ba87c7862036e8b34dd2c4f7584
644,100
import collections import operator def is_batch_good(batch): """ Checks if a batch of tokens is valid. Parameters ---------- batch : list A list of integer tokens """ my_dict = collections.defaultdict(int) for i in batch: my_dict[i] += 1 sorted_x = sorted(my_...
538af49a20939f3adca6bb4313f07c5fde574c0c
644,101
def create_conll_line(token): """Create one line of the output conll file @param token: the token for the line being created @param match_index_to_tag: the dictionary mapping token index to entity tag """ word = token.text pos = token.pos_ tag = "O" linking_tag = "_" entity_ta...
21d69014fed0ca46a05cd4de5dd114acf58fc823
644,102
def odds(nums): """Odds: Given a list of numbers, write a list comprehension that produces a list of only the odd numbers in that list. >>> odds([1, 2, 3, 4, 5]) [1, 3, 5] >>> odds([2, 4, 6]) [] >>> odds([-2, -4, -7]) [-7] """ lst = [a for a in nums if a%2...
253ce5257f102eb65a948d05af025ba4963028b8
644,103
from math import floor def conv_output_dim(input_size, kernel_size, stride=1, padding=0, dilation=1, **kwargs): """Calculate the output dimension of a convolutional layer """ return floor((input_size + 2*padding - dilation*(kernel_size-1) - 1)/stride + 1)
955fd5e69e1ae5b1822fd28000d2db2fa3881f19
644,104
import math def cylinder_plane(F, L, D1, E1, E2): """ Calculate line contact pressure a cylinder and a plane. Arguments; F: Force, e.g. in [N]. L: Contact length, e.g. in [mm]. D1: Diameter of cylinder in e.g. [mm]. E1: Young's modulus of first cylinder in e.g. [MPa]. ...
81cf48127f4f68f805ab10515e4a1b95f2295af7
644,105
import os import struct def get(fn, magic): """Get payload string or None.""" with open(fn, 'rb') as f: f.seek(0, os.SEEK_END) if f.tell() < 8: return None f.seek(-8, os.SEEK_CUR) size, id_ = struct.unpack('LL', f.read(8)) if magic != id_: return...
20d4b8d1ccbd7b2434a421fcc71dc908d6e2daa4
644,106
def do_if(tag, dictionary): """Removes a tag if its condition is False. :param tag: Tag to be evaluated :type tag: BeautifulSoup :param dictionary: Canonical dictionary of parameters :type dictionary: dict :return: Whether or not the tag was deleted :rtype: bool""" if tag.get("tuscon_if...
4108c6508e3a19bfca46d803fa9d573d2313b379
644,107
def verifica_reservada(token): """Verifica se determinado token é reservado e retorna um código para o mesmo""" reservada_list = ['int', 'float', 'char', 'if', 'else', 'printf', 'for', 'while', 'return', 'continue', 'break', 'read'] cont = 0 for i in reservada_list: con...
e59443739ca3c34f94de2c2d5e679b5d19f229a6
644,108
import sqlite3 def get_quote(): """Returns a random quote to be displayed on the page""" # Connect to SQLite database conn = sqlite3.connect("aggregator.db") c = conn.cursor() # Get a random quote from the database and return it for quote in c.execute("SELECT quote FROM quotes ORDER BY RANDO...
537d4ccd780d4bcb55a7bd82d0ac1c4055f64435
644,110
import re def find_url(string): """Find if a string contains an URL""" # findall() has been used # with valid conditions for urls in string url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',string) if len(url) > 0: return True
b4d3c42aa2037000f65a7f209ec7fc6a1654e19c
644,111
def parse_header(line, numeric_vals=True): """ Parse a line of the form: #param=val\tparam=val\tparam=val... Return a dictionary of params: vals """ line = line.strip() if line[0] == '#': line = line[1:] params = {} for pair in line.split('\t'): k, v = pair.spli...
98c3ff35a7a86beddd0b6cb4c4315986ed13725f
644,113
def get_highest_core_state(nstates, energies, lmoments): """Find highest lying core state from list of core states, needed to find and check energy contour""" idx = energies.argmax() lval = lmoments[idx] nquant = sum(lmoments == lval) + lval level_descr = f"{nquant}{'spdfgh'[lval]}" return lval...
12b5924f9e2a027c8d97f5b293ee0f36c9646420
644,114
def filter_issues(issues): """ Returns only the issues the user is not watching """ not_watching = [] for issue in issues: watching = issue['fields']['watches']['isWatching'] if not watching: not_watching.append(issue) return not_watching
be1617d6c8bbd281c8c33c8ae996ac8f56ba7a6d
644,115
def split_string(value, arg=None): """ A simple string splitter So you can do that : :: {% if LANGUAGE_CODE in "fr,en-ca,en-gb,zh-hk,it,en,de"|split:',' %} """ return value.split(arg)
931927e4aaf23806c7d6af4228154ce40bc31eb4
644,117
import subprocess def get_default_ext_command(cmd_name): """ Try to get valid path to external software command file without user input :param cmd_name: String naming the executable command file :return: String, path to the command if the user has the command alias in their .bashrc / $PAT...
65df8da63674927547a909f0feac10047b5aa331
644,118
def resample_prices(close_prices, freq='M'): """ Resample close prices for each ticker at specified frequency. Parameters ---------- close_prices : DataFrame Close prices for each ticker and date freq : str What frequency to sample at For valid freq choices, see http...
a1a5c0e12074680436372aafc0236cc1604e7c8a
644,119