content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os import subprocess def acta_plot(input_file: str, output_file: str) -> str: """Run ``acta_plot``.""" if not os.path.isfile(input_file): raise FileNotFoundError(f"file {input_file} does not exist") cmd_line = ["acta_plot", input_file, output_file] out = subprocess.check_output(cmd_lin...
7d4fdda8da15f728ec110b38ed9943621994f31d
653,842
def compare_phrases(required: bytes, suggested: bytes) -> bool: """ Compares two check-phrases. :param required: array of ATOM_LENGTH bytes :param suggested: array of ATOM_LENGTH bytes :return: """ return required == suggested
8889ddc7094ddc2d7729a9d835e68ddfa91d65f8
653,844
def to_int16(y1, y2): """ Convert two 8 bit bytes to a signed 16 bit integer. Args: y1 (int): 8-bit byte y2 (int): 8-bit byte Returns: int: 16-bit integer """ x = (y1) | (y2 << 8) if x >= 32768: x = -(65536 - x) return x
6bed81d20f68725b35498b157204b11ac13e730f
653,845
def any_positive_or_none(*args): """Return None if any argument is negative and the list of its argument otherwise""" for arg in args: if arg < 0: return None return list(args)
c25c90d6743435707dd79b46f5527cea06ebc834
653,846
def set_boundary_features(pseg_sentences): """ 设置边界特征 :param pseg_sentences: :return: """ results = [] for pseg_sentence in pseg_sentences: result = [] for word_p in pseg_sentence: word = word_p.split('/')[0] boundarys = [] if len(word) == ...
22467a00efe1444af229bd5afe42989dff09cbe2
653,847
def af_subtraction_3channel(ch1, ch2, ch3, m1, m2, c): """ """ af = m1 * ch2 + m2 * ch3 + c signal = ch1 - af return signal
8355ca80a47bd18faef92cb5bd4a6162d6d7d1ce
653,848
import glob def get_bridges(vnic_dir='/sys/devices/virtual/net'): """Return a list of bridges on the system.""" b_regex = "%s/*/bridge" % vnic_dir return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)]
685ffe3ccae18306c49eb4091c360e966674e606
653,850
import torch def create_dummy_tensors_seg(batch_size=16, channels=1): """ Binary: 1 actual, 1 predicted (tp: 1, fp: 0, fn: 0) """ base_shape = (channels, 15, 15) label = torch.ones((batch_size, ) + base_shape) pred = torch.ones((batch_size, ) + base_shape) return (label, pred)
825feca6a1a26da22280dbb03c4d708b13ead455
653,851
import math def compute_heading_angle(source_coordinates, target_coordinates, radians=True, apply_r2r_correction=True): """Computes heading angle in the xy plane given two xyz coordinates. Args: source_coordinates: Source triplet w...
05de53d86a65ba07e742af6af376b1f2c11de27a
653,852
import argparse def parse_args(): """Parse command line arguements. Parameters: Nothing Returns: arguments: argparse.Namespace object An object containing all of the added arguments. Outputs: Nothing """ copy_help = 'Copy files back to original target di...
1aa85da9cd1bf9a4a0bce709b26a335c227ff3dd
653,853
import uuid def get_mac(): """Get mac address.""" mac_addr = (':'.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff) for ele in range(0, 8 * 6, 8)][::-1])) return mac_addr
2721379dcf43a94875d78b9e0444379c590f2da3
653,854
import os def get_executable_path(name): """Find an executable on the current $PATH. :param str name: The name of the executable to find. :throws ValueError: When it cannot find an executable. >>> get_executable_path('toolbox') <snip $KS_TOOLS>/key_base/bin/generated/toolbox """...
118d977c55802d709cbccd6b2ad4d3dedf518b55
653,856
import torch def input_2_tensor(input_seq, encoding_space): """convert regular sequence of values to one hot encoding tensor""" input_tensor = torch.zeros((len(input_seq), len(encoding_space)), dtype=torch.float) for e, element in enumerate(input_seq): element_tensor = torch.zeros(len(encoding_sp...
0cb551201d0a321ad5a8ea5aa4a9a54e215b3299
653,857
def change_category(article, oldCat, newCat, comment=None, sortKey=None, inPlace=True): """Change the category of the article.""" return article.change_category(oldCat, newCat, comment, sortKey, inPlace)
5386e804cac881946996cc0e10d879a07598159c
653,858
import difflib def get_similar_words(word_with_typo, words): """Returns a list of similar words. The parameters we chose are based on experimenting with different values of the cutoff parameter for the difflib function get_close_matches. Suppose we have the following words: ['cos', 'cosh', '...
b1e37b2f475a59e7ec465316b47dc6ca3b8543ec
653,859
def decode(s): """ Decode base 58 encoded string into an integer. From https://gist.github.com/865912 """ alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' base_count = len(alphabet) """ Decodes the base58-encoded string s into an integer """ decoded = 0 multi ...
c2babe642dbf697c78ed55855d7ff7891387c233
653,861
def power_function(context, base, exponent): """ The math:power function returns the value of a base expression taken to a specified power. """ base = base.evaluate_as_number(context) exponent = exponent.evaluate_as_number(context) return base**exponent
f698691bec21f4bb8f3f306c0989077306b32bf5
653,862
def matrixElementsSum(matrix): """ https://codefights.com/arcade/intro/level-2/xskq4ZxLyqQMCLshr After becoming famous, CodeBots decided to move to a new building and live together. The building is represented by a rectangular matrix of rooms, each cell containing an integer - the price of the room....
7f981be6b3726d0eb6abf94051c021b20c1d45ad
653,863
import re def multireplace(string, replacements): """ Replace multiple matches in a string at once. :param string: The string to be processed :param replacements: a dictionary of replacement values {value to find, value to replace} :return: returns string with all matches replaced. Credit to b...
af5eef4a211dd5fb82ff07feb75b40fc1ce3e176
653,864
import torch def vae_loss(x, recon, mu, logvar, beta): """Standard VAE Loss. Args: x: input image. recon: model output as reconstruction of input. mu: mean of latent. logvar: logvar of latent distribution. beta : Hyper-param in loss function. Returns: floa...
e79f1f67a9cab255511886154d6bfd5a0109b05d
653,865
import types def ismodule(object): """Return true if the object is a module. Module objects provide these attributes: __cached__ pathname to byte compiled file __doc__ documentation string __file__ filename (missing for built-in modules)""" return isinstance(ob...
fe719e07509e3ad7875309deca668f36e7fcb0dc
653,866
def write_float_11e(val: float) -> str: """writes a Nastran formatted 11.4 float""" v2 = '%11.4E' % val if v2 in (' 0.0000E+00', '-0.0000E+00'): v2 = ' 0.0' return v2
ba6c808f5f8ee986046cc0752b8449d46be1f2fa
653,868
def EgVarshni(E0, VarshniA, VarshniB, tempDet): """ This function calculates the bandgap at detector temperature, using the Varshni equation Args: | E0: band gap at room temperature [eV] | VarshniA: Varshni parameter | VarshniB: Varshni parameter | tempDet: detector oper...
a3920d65a7d11a799962b3dc899275f96815651f
653,869
def get_kw_pos_association(kernel): """ Returns a tuple of ``(kw_to_pos, pos_to_kw)`` for the arguments in *kernel*. """ kw_to_pos = {} pos_to_kw = {} read_count = 0 write_count = -1 for arg in kernel.args: if not arg.is_output_only: kw_to_pos[arg.name] = read_c...
a219ea9ffe5eee36d346bd99eb3b2443a91df210
653,870
from typing import Sequence def _add_one(s: Sequence[int]) -> Sequence[int]: """Adds one to each element in the sequence of integer.""" return [i + 1 for i in s]
71af45b5f408c86b02eef50fa6c72ffd539649ab
653,871
def buffer_shp_corners(gdf_list, bufferwidth = 0): """ Finds the lower left and upper right corners of a list of geopandas.GeoDataFrame objects. Optionally define a buffer (in degrees) around the list GeoDataFrames :param gdf_list: :param bufferwidth: :return: """ lonmin = 181 lonmax = ...
feddebe25581590400f6845432e766e3453ebcee
653,872
def write_halos(halos_dset, halos_dset_offset, halos, nhalos_to_write, write_halo_props_cont): """ Writes halos into the relevant dataset(s) within a hdf5 file Parameters ----------- halos_dset: dictionary, required Contains the halos dataset(s) within a hdf5 file where eit...
408b275401b6f98a6cd6a888519d9681bdc84290
653,873
def transformPointsToImaris(points, scale = (4.0625, 4.0625, 3), offset = (0,0,0)): """Transform pixel coordinates of cell centers to work in Imaris Arguments: points (array): point coordinate array scale (tuple): spatial scale of the image data offset (tuple): spatial offset of the...
fcd9f6ace54c59c18f5df8816968ed6e99b0bc17
653,874
import base64 def file_to_base64(filepath): """ Returns the content of a file as a Base64 encoded string. :param filepath: Path to the file. :type filepath: str :return: The file content, Base64 encoded. :rtype: str """ with open(filepath, 'rb') as f: encoded_str = base64.b64e...
5baa42c50c91ef03c7bdbc12f79a652744975458
653,875
import os def SymLinkRel( fromFN, toFN, getio = None ): """Create a symlink from fromFN to toFN using relative paths""" if getio: return dict( depends_on = toFN, creates = fromFN, attrs = dict( piperun_short = True ) ) os.symlink( os.path.relpath( toFN, os.path.dirname( fromFN ) ), ...
39ef415b92c5c49ae7a40fa62db379580670bbeb
653,876
def merge_data(chunks): """concat content of all chunks of type IDAT""" return b''.join(chunk.body for chunk in chunks if chunk.type == b'IDAT')
c7e21a70350167b7ef721a9c35f53abdadfd9619
653,877
from typing import List from typing import Dict import os import json def find_dependency_libraries(libs: List[str], info_dir: str) -> Dict[str, dict]: """ Finds all transitively closed dependency libraries for given libraries. Returns a dictionary from library name to the info dict generated by gen_py_li...
610d2b8143b4373cfc8ad2cc6962878729788c2d
653,878
import shutil def concatenate_job(job, input_ids): """This job just concatenates the input files together and returns them.""" out_path = job.fileStore.getLocalTempFile() with open(out_path, 'w') as output: for input_id in input_ids: input_path = job.fileStore.readGlobalFile(input_id) ...
63aa0cbab3009180f98aaf1400d4d64e3e57bd8d
653,879
import os from pathlib import Path def read_file_list(filename): """Read file and print out each line separately with a "-" before it. For example, if we have a file, `dogs`, containing: Fido Whiskey Dr. Sniffle This should work: >>> read_file_list("dogs") - Fido...
a4a5f8b5c84e13af3df7fa791f1a68fea6714e38
653,880
import os def get_windowsroot() -> str: """get_windowsroot() -> str Requires calling on user's machine (for keyfiles) """ windowsPath = os.path.expandvars('%WINDIR%') return os.path.splitdrive(windowsPath)[0] + '\\'
992b2ad92923f02bbd3275526552947b3075c8ca
653,881
import os import subprocess def threshold_family_with_rfmake(family_dir, gathering_threshold, full_align=True): """ Calls rfmake.pl to set the gathering threshold of a family family_dir: The path to an Rfam family directory gathering_threshold: A float value specifying the gathering threshold for the...
ab9d26184ed85069cecf15276c3499f788b88008
653,882
def uncompact(creation_sequence): """ Converts a compact creation sequence for a threshold graph to a standard creation sequence (unlabeled). If the creation_sequence is already standard, return it. See creation_sequence. """ first = creation_sequence[0] if isinstance(first, str): # c...
dd61314f558c7f19818ee3c7670997061e3f6219
653,883
import numpy def exclude_nonfinite(m): """Exclude columns from m that have infinities or nans. In the context of color deconvolution, these occur in conversion from RGB to SDA when the source has 0 in a channel. """ return m[:, numpy.isfinite(m).all(axis=0)]
61eed4e4879fe16955a2e4f5e80be9440b039e50
653,884
def is_bmp(codepoint): """Determine if a codepoint (interger) is in the BMP""" return codepoint <= 0xffff
186b1255f4c3e4ac5821e1d4f5c88e926ee8faae
653,885
def adjust_BEV(TRANS_charge, adjustment_values): """Adjusts the charging profiles by applying weighting factors based on seasonal/monthly values :param (*numpy.ndarray*) TRANS_charge: normalized charging profiles :param (*pandas.DataFrame*) adjustment_values: weighting factors for each day of...
969f742314364516113fb4561ad2c5e3998bab2a
653,886
def str_concat(str1: str, str2: str) -> str: """Конкатенация двух строк Args: str1 (str): Строка 1 str2 (str): Строка 2 Returns: str: Новая строка из двух строк """ return str1 + ' ' + str2
c6171da71344adb3fb35bfde83cd64761365b1ec
653,887
def _lines_to_list(path): """ Reads file from at the specified path and creates a list which contains lines from the file, without a newline. """ with open(path, 'r') as f: return f.read().splitlines()
f156c67fda91f08df7fe065ee10eb5c9d9428886
653,890
def convert(value): """Convert value in milliseconds to a string.""" milliseconds = value % 1000 value = value // 1000 seconds = value % 60 value = value // 60 minutes = value % 60 value = value // 60 hours = value % 24 value = value // 24 days = value if days: result...
a26921bf1db8655f363360d0215d2d4c12f2e406
653,891
def porcentagem_canhoto(num,df): """Esta função calcula a porcentagem de canhotos entre os num jogadores mais bem avaliados. Parameters ---------- num : int Quantidade num de jogadores mais bem avaliados. df : pandas.core.frame.dataframe Dataframe. Returns ------- ...
8356e2a575b2ff81e18a2efea4246f0c160bedc7
653,892
def _get_subjects_and_metrics_by_tag(data_model, reports, tag: str): """Return all subjects and metrics that have the tag.""" subjects = {} for report in reports: for subject_uuid, subject in list(report.get("subjects", {}).items()): for metric_uuid, metric in list(subject.get("metrics",...
a3060d53c3689ecb426900a1fc476eeeee55d4c4
653,893
import numpy def magnetic_field_strength(t: float, alpha: float, mag_init: float): """One possible form of a magnetic field dependence on time, related to PHYS 557 HW 4 Prob 3 which is given by: B(t) = \frac{B_0}{2} (1 + e^{-\alpha t}) Args: t: float, the time ...
d33604f6289fd50cac8de4e285497cb2500731d2
653,894
def get_node_overview(data, requested_nodes): """ Creates a dictionary with all node keys as keys, and as value another dictionary which has all attribute names as keys and the corresponding values as values. :param data: The data objects corresponding to the nodes :param requested_nodes: The nodes ...
1a75d04c0ac0dc15a451137a435ed10cb2edab0f
653,895
import json def _validate_stringified_list_of_dicts(s): """Verify that a string can be parsed into a list. We have some types that are lists of dicts. Those cannot be stored directly in an h5ad, so we have to json.dumps them. This verifies that we can load them back. """ try: list_ = jso...
f3006d805969a46ce1169ed7828f8f004032c6bb
653,896
def reset_clickData(n): """ Resets the click data when new ticker is inserted :param n: new ticker inserted :return: None """ if n is None: pass else: return None
1aa808227a0d1b458f3d0df08fd99671d3675d17
653,897
import sys from pathlib import Path import configparser def main() -> int: """Read version from setup.cfg file passed as first argument.""" argv = sys.argv[1:] if (len(argv) < 1 or not Path(argv[0]).is_file()): return 1 parser = configparser.ConfigParser() parser.read(argv[0]) print(...
f620005ce6c900d8a87d1e461735ab79942e9959
653,898
def to_int(hexvar): """ This function returns hex thing like b"0x00000400" to integers """ return int(hexvar, 0)
1bc01aea02ab0a9dd7fa0ff51af22b214dc7b199
653,900
from pydantic import types from typing import List from typing import Type def get_int_like_types() -> List[Type]: """Returns many int-like types from stdlib and Pydantic.""" def _chk(x) -> bool: try: return issubclass(x, (int)) except Exception: return False can...
37024a5e5f49442e9ac3dec8f48274f4bacfec25
653,901
def is_rule_exists_violation(rule, policies, exact_match=True): """Checks if the rule is the same as one of the policies. Args: rule (FirweallRule): A FirewallRule. policies (list): A list of FirewallRule that must have the rule. exact_match (bool): Whether to match the rule exactly. Ret...
3972036abb454281ba11288e741b4614f58a4822
653,903
def _validate_raid_0(logical_disk, unassigned_pd, no_of_pds): """Checks if RAID 0 logical drive creation with requested size is possible This method finds a list of suitable unassigned physical drives which can be used to create a logical volume of requested size :param logical_disk: The logical disk ...
397329f38a82c3cee535dbce84dcb063f88691c2
653,905
def pkcs7_unpad(data, block_size=16): """Unpad a pkcs7 padded string. No error handling.""" return data[:-ord(data[-1])]
9fb0ed4b68ebab901944df4b2220aa52c7bc599d
653,906
def validate_higlass_file_sources(files_info, expected_genome_assembly): """ Args: files_info(list) : A list of dicts. Each dict contains the file's uuid and data. expected_genome_assembly(str, optional, default=None): If provided, each file should have this ge...
42124e5a3132861dc3a81b8751859630761b80d2
653,908
def run_validator(Validator, person): """ Execute validate function of the validator """ return Validator.validate(person)
95038ab7f47981427f02bfd4f46bac329a8de088
653,909
from typing import Tuple def get_channel_values(digitalOut, func) -> Tuple: """Get the result of applying 'func' to all DigitalOut channels.""" return tuple(func(channel_index) for channel_index in range(digitalOut.count()))
0f8fffa2bae965e72fe386ae356c8f11b14db9fc
653,910
def _filter_size_out(n_prev, filter_size, stride, padding): """Calculates the output size for a filter.""" return ((n_prev + 2 * padding - filter_size) // stride) + 1
286b970402e7b5a6d20f87dcaf6107f0eca459f0
653,911
def is_anyscale_connect(address: str) -> bool: """Returns whether or not the Ray Address points to an Anyscale cluster.""" is_anyscale_connect = address is not None and address.startswith( "anyscale://") return is_anyscale_connect
80bf6688d3914f5ea06c3cd398c4b5c4b610997a
653,912
import pathlib def get_path_and_name(path_dir): """返回path_dir下所有的文件路径以及name, 带有后缀""" paths = [] names = [] for path in pathlib.Path(path_dir).iterdir(): paths.append(str(path)) names.append(path.name) return sorted(paths), sorted(names)
be0aec330dcbbdecb03c3b4899b0c8ef6a054a65
653,913
def get_acmodel(core_data): """ gets the aircraft model from core data """ if core_data != 'error': try: # renames paramater data = core_data[1] if data.find('strong'): acmodel = data.strong.text.strip() # brea...
56495a59f38a30c2d04a4b0d878dcfc23feca54c
653,914
import numpy def _length(xyz, constant_step=None): """ Euclidean length of track line in mm """ if constant_step==None : if xyz.shape[0] < 2 : return 0 else : dists = numpy.sqrt((numpy.diff(xyz, axis=0)**2).sum(axis=1)) return numpy.sum(dists) else ...
7467e2f408314e9815a316114c29bd96023892b9
653,916
import bisect def findRelFileDotNodes(relFileNode, sortedList): """ This function will take a relfilenode without a dot '.' suffix, and find all of its dot suffix files in a sorted list (sortedList). Just the suffixes are returned. relFileNode and sortedList are assumed to contain full path list...
9a184a6fdc8778b3897e0d80aed43fc5b9b791d3
653,917
def configurePostfix(post): """configurePostfix(post) Configure a string that will be appended onto the name of the spectrum and other result attributes.""" return {'Postfix' : post }
9a4b0199fcc04bbd1c458d478608fecd68288f15
653,919
def select_utr3_first_boundary(transcripts): """Select transcript(s) with most 3' UTR boundary""" ret = [transcripts[0]] if transcripts[0].strand == '+': most3prime_exons = [[x[1],x[0]] for x in transcripts[0].utr3_exons[::-1]] else: most3prime_exons = transcripts[0].utr3_exons[::-1] ...
d0ddf13875a3784dd3fafa13cf5b221bc52e045d
653,920
import os def check_directory_path(path: str) -> bool: """Wrapper for os's isdir function""" return os.path.isdir(path)
8ee558dad646a47fe5725f14f0aff5c8e8c38744
653,921
import json def load_requested_urls(file_or_list): """载入已经被爬取ulr的json """ if isinstance(file_or_list, str): file = file_or_list with open(file, 'r', encoding='utf-8') as fp: data = json.load(fp) else: data = file_or_list data = set(data) return data
da78ce118f1588d2ef0237d566127c1a6b0ca1d9
653,922
import os def _parse_os_release(): """Parse the contents of /etc/os-release file. Returns: A dictionary containing release information. """ distro = {} os_release_file = os.path.join("/etc", "os-release") if not os.path.exists(os_release_file): return distro with open(os_r...
bf51027cacb1a35c9f306b42654117f92a651ab1
653,924
import os def kidname_to_libpath(kidname): """ Given the name of a WS kid, return the path to shared library. """ serial_libpath = os.path.join("procs", "proc_" + kidname + ".ws_so") parallel_libpath = os.path.join("procs", "proc_" + kidname + ".wsp_so") if os.path.exists(serial_libpath): ret...
d0f4384076f5fdb9b0422a65f679fee976ac1b41
653,925
def in_sector_bounding_box(polar_point, radius, start_theta, end_theta): """Check if a polar coordinate lies within the segment of a circle :param polar_point: tuple representing the point to check (r,phi) :param radius: radius of the segement :param start_theta: start angle of the segement in rad ...
c6c9c2a53ab75970870adcdea6c2161015a7e8e4
653,926
import hashlib def normalize_string(value): """ 5.1.1.4 - c.3: String values shall be rendered using the first eight characters of their md5 (Message-Digest Algorithm) checksum. """ md5 = hashlib.md5(value.encode('utf-8')).hexdigest() return md5[:8]
0849ffd23fc2e0c82e0786e50adb9a8f22996e62
653,927
def get_rotation(row): """Generate a rotation matrix from elements in dictionary ``row``. Examples --------- >>> sdict = { \ '_pdbx_struct_oper_list.matrix[{}][{}]'.format(i // 3 + 1, i % 3 + 1): i \ for i in range(9) \ } >>> get_rotation(sdict) [[0.0, 1.0, 2.0], [3.0, 4.0, ...
2afd9d01aa17b313b64d723c932fd4cd50f77d03
653,928
def anon_session_score(request, add=0, possible=0): """ returns the session score if number passed in then add this to the running total and then return session score examples: x, y = anon_session_score(1, 1) will add 1 out of a possible 1 x, y = anon_session_score(0, 2) will add 0 o...
87cb78c36ae3cc5d1d23858ad6964139865ae19b
653,929
import re import json def fix_tokens_file(file_path): """ Replace each # ::tok sentence by json parsable version # ::token json-parseable-sentence so that sentence == json.loads(json-parseable-sentence) """ token_line = re.compile('^# ::tok (.*)') # read and modifiy toke...
4ba6e2f7feabd1f970a5ccb7da437a765539323b
653,931
import types def type_repr(obj): """ #typing._type_repr() stolen from Python 3.8. """ if isinstance(obj, type): if obj.__module__ == 'builtins': return obj.__qualname__ return f'{obj.__module__}.{obj.__qualname__}' if obj is ...: return('...') if isinstance(obj, types.FunctionType): ret...
eabe99360acfd0cdcb369d7176efc9a15f8de10c
653,932
def w(el1, el2): """ Returns weight based on residue pair """ pair = el1 + el2 return int(pair == 'AU' or pair == 'UA' or pair == 'GC' or pair == 'CG')
b20ccb565dc4be5ea668b25314d4beb8f7ee3c0e
653,933
def int_str_to_int(int_str: str) -> int: """ example formats: 1234 0xabcd 0b0101 (so they always start with a digit) """ if int_str.startswith('0x'): int_value = int(int_str[2:], 16) elif int_str.startswith('0b'): int_value = int(int_str[2:], 2) else: in...
c9b6e56bdc170da60c22a5129c515fcd686466e1
653,934
from typing import Tuple import os def input_output(rundir: str, cmd: str) -> Tuple[str, str]: """Extract name of input file and output file from commands that are used to run the Metanome algorithms from the command line. Returns the path to the input and output files. Parameters ---------- ...
6d68eb71091a11eafa41b46eca2b3e3c8d9e2e9e
653,935
import requests def check_ud(term): """Lookup against urban dictionary API.""" results = [] msg = '' url = 'http://api.urbandictionary.com/v0/define?term={0}' search = requests.get(url.format(term)) if search.ok: data = search.json() results.append(data['list'][0]['definition']...
c09eefe9f87dcabf8cdf1203e56add39a2db4f0c
653,936
def scan2colfil(x, y, x0, y0, scale, tipo=0): """ Transforma de x/y en proyeccion geoestacionaria a En base a 5.2.8.2 de PUG3 Parameters ---------- x : float, float arr coordenada vertical, en radianes x : float coordenada vertical del primer punto en radianes x0 : float ...
d047c8ff939119aecec1dde9b9bf08e23e4acca8
653,937
from typing import Tuple def create_columns(column_def: Tuple[str, str]) -> str: """ Prepare columns for table create as follows: - types copied from target table - no indexes or constraints (no serial, no unique, no primary key etc.) """ return (','.join(f'{k} {v}' for k, v in column_def) ...
787ce1c3fc5e37c6055f48424e92eec84eb05448
653,938
def include_selection(data, selection): """Makes a new dataset including points whose 'id' is in selection.""" new_data = [ a_data_point for a_data_point in data if a_data_point.par.get('resonance_id', None) in selection ] return new_data
846e95fcb9f205459d531ffee3136f256af584ce
653,939
import torch def RGB2YUV(img): """ img.size() = [B, C, H, W] """ r = img[0, :, :] # [B, H, W] g = img[1, :, :] b = img[2, :, :] y = 0.257 * r + 0.504 * g + 0.098 * b + 16 u = -0.148 * r - 0.291 * g + 0.439 * b + 128 v = 0.439 * r - 0.368 * g - 0.071 * b + 128 return torch.sta...
f7fdbe31fd1426892bb42040ed803603372182e8
653,940
def referral_list_command(module): """1.0 holdover""" return "m{module.id}-referral-list".format(module=module)
34aed830f87ef38532f77cf3f0bea3ba6a82404f
653,941
def _tile_size(shape, out_shape, ndim): """Returns tile_size such that shape*tile_size = out_shape""" size = [1] * ndim for idx, (i, j) in enumerate(zip(shape, out_shape)): if i != j: size[idx] = j return tuple(size)
6f067243805b252cdabb3a9674d4d5d7fcea2703
653,942
def adjust_idx_labels(data_y, label): """Transforms original labels into the range [0, nb_labels-1] :param data_y: numpy integer array Sensor labels :param label: string, ['gestures' (default), 'locomotion'] Type of activities to be recognized :return: numpy integer array Modifi...
f4510109b3c28a7037641ce6641ca38c39f6b1b3
653,944
def has_already_cover(cover_metadata={}): """Check if record has already valid cover in cover_metadata.""" return cover_metadata.get("ISBN") or cover_metadata.get("ISSN")
7a1a09e4faa9d37f2d8b742fb91f8554bf83ff5a
653,945
import os from pathlib import Path import traceback def get_all_files_dict(root_dir=os.getcwd()): """ Get directory path and file name mapped structure as a dictionary Parameters: root_dir (string): root directory path Returns: dir_dict (dictionary...
7a3eb5e4f6f2fba243e27f70a2e7c26e70cda1c6
653,946
import os def strip_ext(path): """ Remove the extension from a path. """ return os.path.splitext(path)[0]
9273855fcc1867794bdca5eec5cbd0250aeeecc8
653,947
def futures_header(): """網頁瀏覽時, 所帶的 request header 參數, 模仿瀏覽器發送 request""" return { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-TW,z...
8fc064461cfe3a4a40c8543620265547f8b6dfc7
653,948
def append_concat_predictions(y_batch, predictions): """ Args: y_batch (torch.Tensor or list): predictions (list): accumulation list where all the batched predictions are added Returns: list: predictions list with the new tensor appended """ if isinstance(y_batch, list): ...
5659b77899dd3a48f24de3bef05b0c7e73cf8cea
653,949
def remove_comments(s): """remove comments (prefaced by #) from a single line""" r = s.split("#") return r[0]
73724d2d1d39efb97c95607be8048d9300a174be
653,950
def make_result(messages: list): """ Make result string from passed message list :param messages: message list (look above to check details) :return: formatted message """ if not messages: return "There were no starred items." text = "" for m in messages: if len(text) > ...
a5cea3d6f96f907e4a48cdccae3ed452ec2da9cd
653,951
import time def timer(func): """ time-consuming decorator """ def wrapper(*args, **kwargs): ts = time.time() res = func(*args, **kwargs) te = time.time() print(f"function: `{func.__name__}` running time: {te - ts:.4f} secs") return res return wrapper
033b314d3a09ca9193c2739a2d86be752f751dd9
653,952
def prepare_event_log(log): """ If trace attributes are considered, it is possible that trace attributes have the same name as event attributes. To tackle this issue, the attributes get renamed. For trace attributes, we add "t_" at the beginning of the dictionary keys. For event attributes, we add "...
44d5eb5e7c19be5a37b916390f423ecc3dbf012d
653,953
def compact(objects): """ Filter out any falsey objects in a sequence. """ return tuple(filter(bool, objects or []))
60af7d26e786113d9af7a29f1e6a46ee2191453d
653,954
def trim(text, max_length): """Trims text to be at most `max_length`, without splitting apart words.""" if len(text) <= max_length: return text text = text[:max_length + 1] # Trim until the last two characters are the boundary between an # alphanumeric character, and a non-alphanumeric cha...
8d7bdebd4d09887d8a38f6181e68b4239e2b05a7
653,955
import time def parse_date(value, dateformat='%Y-%m-%d'): """Parse a string into a date""" return time.strptime(value.strip(), dateformat)
87f382c74365e8a273355a6efe56ff94def5f9c0
653,956
def rayleigh_coefficients(zeta, omega_1, omega_2): """ Compute the coefficients for rayleigh damping such, that the modal damping for the given two eigenfrequencies is zeta. Parameters ---------- zeta : float modal damping for modes 1 and 2 omega_1 : float first eigenfrequen...
effb96fc4efed4ee57d31feb075099767cf5e03d
653,957