content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def find_empty_cell(board): """ finds the empty cell going left to right, top to bottom on the board """ for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 0: return (i, j) return None
8c94c7b7d55376142b8d8dc0d8ac97c5c006e1c0
668,551
import numpy def _create_scale_matrix(scale_factors): """ Creates scale matrix for scaling """ return numpy.array([[scale_factors[0], 0, 0, 0], [0, scale_factors[1], 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
43d040e83700ec93a6477492eab78a8aa3548930
668,552
def splitLast(myString, chunk): """ returns a tuple of two strings, splitting the string at the last occurence of a given chunk. >>> splitLast('hello my dear friend', 'e') ('hello my dear fri', 'nd') """ p = myString.rfind(chunk) if p > -1: return myString[0:p], myString[p + len(chun...
6bdf7c2f3b16ca3b0885bdb41623183342c4d4af
668,553
def sum(num1: int, num2: int) -> int: """ :type num1: int :type num2: int :rtype: int """ res = num1 + num2 print(str(res)) return res
21b84d3f710bb07e15caf7c6cdb2267e822b5b56
668,554
import random def _gen_noise(nmag, period_pre, period, fftlen, gauss): """ Generates the appropriate amount of noise at the correct energy """ s = (fftlen // 2) - (period_pre // 2) e = (fftlen // 2 + fftlen % 2) + (period // 2) noise = [t > s and t < e for t in range(fftlen)] if gauss: ret...
7955ed8d9b6810cb17dd2cb63d9c221eec8554a3
668,555
import os def getUniqeFileNames(path): """Return a list of files from the given path, where each item is unique""" # def cropBaseName(fname): # name_split = fname.split("_") # if "(" in name_split[1]: # base is of the form <number1>_(<number2>) # return "_".join([name_split[0], nam...
86f9c0b9167de2d323658930b8125be5e5eedd56
668,556
def server_no_key(server_factory): """ Return a :class:`saltyrtc.Server` instance that has no permanent key pair. """ return server_factory(permanent_keys=[])
18614069c21af369eeb3d36f2993873ac0690572
668,557
def lower_tree(tree): """ Change all element names and attribute names to lower case. """ root = tree.getroot() for node in root.iter(): node.tag = node.tag.lower() attributes = dict() for attribute in node.attrib: attributes[attribute.lower()] = node.attrib[a...
c61737154a86ee62f0c825de5d006913c624d817
668,558
def _gr_text_to_no(l, offset=(0, 0)): """ Transform a single point from a Cornell file line to a pair of ints. :param l: Line from Cornell grasp file (str) :param offset: Offset to apply to point positions :return: Point [y, x] """ x, y = l.split() return [int(round(float(y))) - offset[0], int(round(flo...
b07a7587cc82ecc9b6a8796e0d09119086092ad7
668,559
def create_asset(bitshares, default_account): """Create a new asset.""" def _create_asset(asset, precision, is_bitasset=False): max_supply = 1000000000000000 / 10 ** precision if precision > 0 else 1000000000000000 bitshares.create_asset( asset, precision, max_supply, is_bitasset=is...
73145e59e73cf16d65557e1d957490851e17b550
668,560
import os def _get_files(path): """ Helps to list all files under the given path. """ if os.path.isfile(path): return [path] all_files = [] for root, _dirs, files in os.walk(path, followlinks=True): for file in files: file = os.path.join(root, file) all_...
d6339de247d9e368fe6bb18057732caaa5c52721
668,561
def normalize(feature, feature_space): """normalizes a feature vector according to the space boundaries.""" norm_feature = feature - feature_space.low norm_feature /= (feature_space.high - feature_space.low) norm_feature = norm_feature * 2. - 1. return norm_feature
fb58a0ebb5acfd0128fd8b281add2c14180cbf31
668,562
def _PyDate_FromTimestamp(space, w_type, w_args): """Implementation of date.fromtimestamp that matches the signature for PyDateTimeCAPI.Date_FromTimestamp""" w_method = space.getattr(w_type, space.newtext("fromtimestamp")) return space.call(w_method, w_args)
bec844b8184c17c46c16a284bc56b8f140ab6e84
668,563
import time def beats(text): """- Gets the current time in .beats (Swatch Internet Time).""" if text.lower() == "wut": return "Instead of hours and minutes, the mean solar day is divided " \ "up into 1000 parts called \".beats\". Each .beat lasts 1 minute and" \ " 26.4 s...
83eee649e21fae5770cf6ed4729e7ad960ac14b8
668,564
import re def format_regex_stack(regex_stack): """Format a list or tuple of regex url patterns into a single path.""" formatted = ''.join(regex_stack) formatted = re.sub('\([^<]*(<[^>]*>).*?\)', '\\1', formatted) formatted = formatted.replace('^$','/') formatted = formatted.replace('^','/') fo...
1d781b311154dd2699fb788ede90a82cef53fdf0
668,565
def get_frame_interface(pkt): """Returns current frame interface id alias. """ iface_raw = pkt.frame_info._all_fields['frame.interface_id'].showname_value ifname = ".".join(iface_raw.split()[1][1:-1].split(".")[:2]) return ifname
e50d056db6743154d65c896ba646169a52f21fe4
668,566
import functools def use_fallback_value(fallback_value): """ Parameterized function decorator that acts as a safety net when parsing values. If any exception is raised while parsing a value, the exception is caught and the fallback value is returned by the decorated function. """ d...
368237049e76404918cecd5ff342e097ac691525
668,567
import re def norm_key(key_name): """ Normalize key names to not have spaces or semi-colons """ if key_name: return re.sub('[;\s]', '_', key_name) return None
5ea501c15ca8bafc13f3148efe77eaeabdfb0a4c
668,568
def list_entries(): """Get list of entries to be displayed via rofi.""" return(['a', 'b', 'bb', 'c'])
d247a03c36be2bf22f90942805a24a2f7e8a483a
668,570
def after_request(rv): """ All after request operations will be handled here """ return rv
09b397aa3b93122d4161654360d32bd80df46526
668,571
import networkx import itertools def motif_adjacency(mtf_id, mtf_sz): """ Very fast - due to python, platform-independent - way of computing the motif adjacency matrix from the binary representation of its integer ID. """ mtf_adj = networkx.DiGraph() # infinitely increasing index 'i' for i in iter...
bf10b06127138f57a6135f376636fa3f171c94a0
668,572
def dragons_bpm(ad, prefix=None): """ Add header things to a BPM to convert it into a DRAGONS compatible BPM. Sets header keywords, OBJECT BPMASK Writes out a file with the DRAGONS naming convention. """ if prefix is None: prefix = '' namps = None nbuffer = prefix+"{}_...
bad306e6b48c1d9a28831e731ac0c560e2ced5c2
668,573
import math def dB(x): """Returns the argument in decibels""" return 20 * math.log10(abs(x))
8f31606d217d0eacfced6dd42e1db50fe3d4f17f
668,574
import json def load_from_json_file(filename): """Creates an Object from a “JSON file”.""" with open(filename, 'r') as f: return json.load(f)
be9041c016c58a89fbae1b86bae60c86f7099934
668,575
def normalize_measurement(measure): """ Transform a measurement's value, which could be a string, into a real value - like a boolean or int or float :param measure: a raw measurement's value :return: a value that has been corrected into the right type """ try: return eval(measure, {}, {}...
aa918e06ee4e9ebceeb6597c5fdedd90aa20b5e6
668,576
def generate_entity_results(entity_class, count, **kwargs): """ generates entity results with given entity type using given keyword arguments and count. :param type[BaseEntity] entity_class: entity class type to put in result. :param int count: count of generated results. :rtype: list[BaseEntity] ...
de431eb24ac7d1a75a8c9ad862b780c22b7872a2
668,577
def clean_float(num): """ Pasa de string a float """ ntmp = num.replace('.', '').replace(',', '.') return float(ntmp)
ed170c6d6bfd5b0c6f6ca2e12c5f77c51e950694
668,578
from datetime import datetime def get_iso_time() -> str: """ Return the current time in ISO 8601 format. """ return datetime.now().isoformat()
57feee4572877197e0e2ddd9f1f4f4370bf8da3e
668,579
def cli(ctx, name, owner, changeset_revision, tool_shed_url, remove_from_disk=True): """Uninstalls a specified repository revision from this Galaxy instance. Output: If successful, a dictionary with a message noting the removal """ return ctx.gi.toolshed.uninstall_repository_revision(name, owner, chan...
738aa5123c125a07a77f76618af0f1a45084685f
668,580
import ast from typing import TypeGuard def _is_ipython_magic(node: ast.expr) -> TypeGuard[ast.Attribute]: """Check if attribute is IPython magic. Note that the source of the abstract syntax tree will already have been processed by IPython's TransformerManager().transform_cell. """ return ( ...
20e59f3ba1e5a5b5b0497ad78f5ecd3655059602
668,581
def length(vec): """ returns the length/norm of a numpy array as the square root of the inner product with itself """ return vec.dot(vec) ** 0.5
6a22c83a57ab98dc1e179fd589dd7a1a292c3cd8
668,582
def dump_profiles(profiles): """ Dump profiles into json format accepted by the plotting library :return: list of dicts representing points in the profiles """ data = [] for cp_profile in profiles: for i, row in cp_profile.profile.iterrows(): data.append(dict(zip(cp_profile....
ca47cd11ce6d9aac8f9413386eccda0074737520
668,583
def evaluate_left_to_right(exp: str) -> int: """Do left-to-right expression evaluation on the parm flat expression.""" # A flat expression contains no brackets. assert '(' not in exp assert ')' not in exp terms = exp.split(' ') result = int(terms.pop(0)) # First term in the expressio...
75af99781d873a501a338997cbb71c86a46615d4
668,584
def get_label_from_iri_list(iri_list, iri2label_dict): """ Helper for getting labels of a df with IRI lists as values using an iri2label dict""" label_list = [iri2label_dict[iri] for iri in iri_list] return label_list
213e6262f9663dbf162d7255477483ad362f23bd
668,585
import hashlib def EncryptPassword(pwd): """ 从教务系统的首页看 其密码是经过MD5加密的 :param pwd: 未加密的密码 :return: 加密过后的密码 """ encrypt = hashlib.md5() encrypt.update(pwd.encode("ASCII")) return encrypt.hexdigest()
3235bcc74a76e3887da6ad8a4b8423443f87f208
668,586
def interface_r_cos(polarization, n_i, n_f, cosTh_i, cosTh_f): """ reflection amplitude (from Fresnel equations) polarization is either "s" or "p" for polarization n_i, n_f are (complex) refractive index for incident and final th_i, th_f are (complex) propegation angle for incident and final ...
fd7da775fbba9c411ff2a461aa8d41c673fe8584
668,587
def non_empty_slices(u, aut): """Return parameters that yield non-empty `u` slice.""" qvars = aut.vars_of_all_players return aut.exist(qvars, u)
388594368c93d4ba5d6fd236248f9f8d675a4c1e
668,588
def box_text(text: str) -> str: """ Draws an Unicode box around the original content Args: text: original content (should be 1 line and 80 characters or less) Returns: A three-line string. Unicode box with content centered. """ top = "┌" + "─" * (len(text) + 2) + "┐" bot =...
2ec9d33cfeb0da60318235345cd1b8d25498e614
668,589
def strip_position(pos): """ Stripes position from +- and blankspaces. """ pos = str(pos) return pos.strip(' +-').replace(' ', '')
1097bf545d58cea0ef526683cf020be7678aa029
668,590
import re def _extract_drive_size(drive_size: str): """ Extract Drive size drive_size: - 1024 Гб """ if not drive_size: return pattern = r"(\d+) \w{2}" if match := re.search(pattern, drive_size): return match.group(1)
8bd7aaad0cc47d14b810aa103c68639b17bddce2
668,591
def convert_bit_index(x): """ Convert x in a bit index. """ if x == 666666666:#if x is a non data value return 255 x_string = str(x) sum = 0 for i in range(1,6): if str(i) in x_string: sum += 2**i return sum
d640c876a8ba22b148e87e5a99f23579ad2e434a
668,592
def index_map(i, d): """ The index map used mapping the from 2D index to 1D index Parameters ---------- i : int, np.array the index in the 2D case. d : int the dimension to use for the 2D index. Returns ------- int, np.array 1D index. """ return 2 *...
b322d7377eb319333343467017044356a97862a0
668,593
def should_run_stage(stage, flow_start_stage, flow_end_stage): """ Returns True if stage falls between flow_start_stage and flow_end_stage """ if flow_start_stage <= stage <= flow_end_stage: return True return False
2e241aad6752553bc1b1ca4f76e1e300e5692ce8
668,594
def td_rotate_90ccw(txtdict, wout, hout): """Rotate 90 CCW""" # y: x # x: w - y - 1 ret = {} for y in range(hout): for x in range(wout): xin = hout - y - 1 yin = x try: val = txtdict[(xin, yin)] except KeyError: ...
be1635023d2f1eb9e36cf67b4e3bb22c84cc2d5e
668,595
import re def parse_lines(lines): """ return dictionary whose keys are names of processes and values are lines belonging to the respective process """ parsed = {} regex = r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{1,3} (?P<process_id>[a-zA-Z0-9\-]+) .*$' process_id = 'MainProcess' for line in l...
7114dbb4785ebf29271dddbe5cec01b06d4b6457
668,596
def connect_anat_preproc_inputs(strat, anat_preproc, strat_name, strat_nodes_list_list, workflow): """ Parameters ---------- strat : Strategy the strategy object you want to fork anat_preproc : Workflow the anat_preproc workflow node to be connected an...
6d76f473a5b5cd46b8f1e45ecbcff5568b2220d8
668,598
from typing import Union from pathlib import Path from typing import Tuple from typing import List import re import hashlib def split_dataset( root_dir: Union[str, Path], max_uttr_per_class=2 ** 27 - 1 ) -> Tuple[List[Tuple[str, str]], List[Tuple[str, str]]]: """Split Speech Commands into 3 set. Args...
3b3ee8b4972c7a38bbc3884786fa1982c86ec992
668,599
import os def bids_clean_filename(filename): """ External files are accepted, but their names must fit within BIDS formatting. This function BIDS-ifies. Any underscores, hyphens, periods, or spaces are simply removed. :param filename: actual name of the picked matrix file :return: BIDS-ified str...
184e4607d420b330e4142e031b749f7210504931
668,601
import os def join_if_not_abs(*args, project_dir=None, exist=True): """if last argument is an absolute path, don't join the path arguments together""" if os.path.isabs(args[-1]): return args[-1] else: if project_dir: pathname = os.path.join(*args[:-1], project_dir, args[-1]) ...
62c685e42129b514a3a4cee3a818a6f12dbb0def
668,603
def get_launch_args(argv, separator=':='): """ Get the list of launch arguments passed on the command line. Return a dictionary of key value pairs for launch arguments passed on the command line using the format 'key{separator}value'. This will process every string in the argv list. NOTE: all ...
a2cdb11d134cca904be5158846362e12769b5556
668,604
def _add_months(date, delta): """Add months to a date.""" add_years = delta // 12 add_months = delta % 12 return date.replace(year=date.year + add_years, month=date.month + add_months)
65f1a4fab2dfc94681edaf398a788b1f3eea2d8e
668,605
import pickle import zlib def blobloads(blob): """ Inverse of blobdumps(). Decompress the pickled object, and unpickle the uncompressed object. Returns a Python object. """ return pickle.loads(zlib.decompress(blob.encode('latin1'))) # No need to specify pickle protocol, as it will be au...
b4bf4fa9abd232d6aa6d4d78ceb7dc94fe1f7f9a
668,606
def memoized_coin_change(amount, denoms, denoms_length): """ Memoized version Parameters ---------- amount : int Target amount denoms : list<int> denominations denoms_length : int number of unique denominations Returns ------- int count of ways ...
614ab634fee52ea14e58a6d2922175fa186281d8
668,607
def is_lowhigh_ascending(lhs): """用于判断一组高低价是否连续上升""" plh = lhs[0] for i in range(1,len(lhs)): clh = lhs[i] if clh[0] > plh[0] and clh[1] > plh[1]: plh = lhs[i] else: return False return True
3e36df10b4e9d4899c3646e16a06e4228b54c821
668,608
def _get_error_list(error_code): """ Get error list. Args: error_code (int): The code of errors. Returns: list, the error list. """ all_error_list = ["nan", "inf", "no_prev_tensor"] error_list = [] for i, error_str in enumerate(all_error_list): error = (error_cod...
521759ba0e02e0b69b1756439c06d4c3082a93e3
668,611
def short_dna_edges(request, short_dna): """ Create successively a system with edges produced by :class:`vermouth.AddMoleculeEdgesAtDistance` and by :class:`vermouth.MergeNucleicStrands`. Having this fixture allows to run :func:`test_add_molecule_edges_distance` with the output of both :func:`sh...
08dc9738a0e358d8e871d27a37ebcdb22a024885
668,612
import math def vec_2norm (x): """[Lab 14] Returns ||x||_2""" return math.sqrt (sum ([x_i**2 for x_i in x]))
dd7bf1411b7f506baf77eabd20bd704b2e559333
668,613
def format_timedelta(timedelta): """Format datetime.timedelta object as str with units. Parameters ---------- timedelta : datetime.timedelta object A datetime.timedelta object. Returns ------- str Formatted string with the following format: %%h %%m %%.%%s ...
5d6473dba29f9a5b4bab5293905a993ffdd5168d
668,614
from typing import Optional import requests def get_page_text(url: str) -> Optional[str]: """ Download complete HTML text for a url """ cookies = {"devsite_wall_acks": "nexus-image-tos"} request = requests.get(url, timeout=10, cookies=cookies) if request.ok: return request.text req...
ad6f8576f52efa3c7faae7c98a28d076c968ecd7
668,615
def ssh_cmd_docker_container_exec( detail, command_on_docker, wait_press_key=None ) -> str: """SSH command to execute a command inside a docker containter.""" wait_cmd = "" if wait_press_key: wait_cmd = "; echo 'Press a key'; read q" return ( f"TERM=xterm ssh -t {detail['ec2InstanceI...
21392652f692199934cfe88271e673cc5fdb01ae
668,616
def safestr(value): """ Turns ``None`` into the string "<None>". :param str value: The value to safely stringify. :returns: The stringified version of ``value``. """ return value or '<None>'
71ef04a33a4329c9a17aa96f83a50859f813e2b0
668,617
def my_schema_callback(schema): """Remove fields that start with _, fix key names with embedded /, fix id lookups """ for k in [k for k in schema['properties'] if k.startswith('_')]: del schema['properties'][k] for k in [k for k in schema['properties'] if '/' in k]: schema['properties'][k.sp...
a6bb1aee81a34d71ee17a6ed9d0f93158b2d3af8
668,618
def rest_api_parameters(in_args, prefix='', out_dict=None): """Transform dictionary/array structure to a flat dictionary, with key names defining the structure. Example usage: >>> rest_api_parameters({'courses':[{'id':1,'name': 'course1'}]}) {'courses[0][id]':1, 'courses[0][name]':'course1'} ...
f62faa8bbd3e65eb2f61144b7e4fff2cd75076a8
668,619
def process_input(input: list[list[str]]) -> dict: """Convert the input data structure (lists of pairs of caves that are connected) into a dict where each key is a cave and the corresponding value is a list of all the caves it is contected to. """ input_processed = {} cave_pairs = [] for ...
88b6a11049e30f8aed99b7cac2e6445c5d342827
668,620
from pathlib import Path def make_file_path(output_folder_path, file_name): """ takes a prefix with operation and a short RDF URI notation (prefix:name) and returns a filename""" base = Path(output_folder_path) file_path = base / file_name file_path.resolve() return str(file_path)
0e825742e9c72452c23fdb53ab14a07fe403d4d6
668,621
import socket def port_connected(port): """ Return whether something is listening on this port """ s = socket.socket() s.settimeout(5) try: s.connect(("127.0.0.1", port)) s.close() return True except Exception: return False
ad198aa4cda1e358e2fedcd596bef2772eafdb60
668,623
import operator def le(n: float): """ assertsion function to validate target value less or equal than n """ def wrapper(x): return operator.le(x, n) return wrapper
d70acd5fb7946c725bede2c27056645f61db52ec
668,624
import argparse def parse_arguments(): """ get command-line arguments. """ parser = argparse.ArgumentParser(prog='example.py', description="a little sample script for for running python code " + \ "on a HPC cluster. It requires one of the arguments 'listsize', " + \ "...
5aff6e84ab03fb6509e51685230d443c8bff364a
668,625
def bubblesort(a): """ bubble sort implementation >>> bubblesort([6, 4, 8, 2, 1, 9, 10]) [1, 2, 4, 6, 8, 9, 10] """ for i in range(len(a)): for j in range(i, len(a)): if a[i] > a[j]: a[i], a[j] = a[j], a[i] return a
e7105a2ff797d5ad5f0fba8e93993221da38f6ed
668,626
import numpy def findTwigs(Cells, C, twig, NCRIT): """ It finds the twig cells, the ones that have < NCRIT. Arguments ---------- Cells: array, cells of the tree. C : int, index of cell in the Cells array. twig : array, indices of twigs in Cells array. NCRIT: int, maximum number of ...
4e48b22239a28978232049411cbabf06d2fe7a4f
668,627
import ast def split_table(table_name): """ :param table_name: gets table_src_target value stored in TestSuite table :return: returns a list consist of source and destination db. """ table_names = ast.literal_eval(table_name) lst1 = {} tables = table_names["table"] for key in tables: ...
678e2aea690196b51876d19ebcf0291f1f324e5c
668,628
import os def getODBinaryDir( srcpath ): """Get the binary directory from the source directory Only useful for development environments Parameters ---------- srcpath : Full path to a directory Path to the OpendTect source directory, configured with cmake Returns ------- Fu...
fb2c2daf40aa5e681c246b7b966fdd1511dfe6fe
668,629
from typing import Any import typing from typing import Union def deannotate(annotation: Any) -> tuple[Any]: """Returns type annotations as a tuple. This allows even complicated annotations with Union to be converted to a form that fits with an isinstance call. Args: annotation (Any): ty...
c74de52db80aa91f1d0ae7db3d1095b88ac3ff2e
668,630
import re def template_to_regex(template): """Convert a string template to a parsable regular expression. Given a data_path_format string template, parse the template into a parsable regular expression string for extracting each %VAR% variable. Supported %VAR% variables: * %EXPE...
b24378fab8eb80568b5dcdaaaba80d602c28bcab
668,631
def calculate_points_for_street(street): """ Calculates the points for a given street :param street: List of chips, that can be placed :return: int with points for street """ points = 0 for chip in street: # print(chip[0]) points += chip[0] return points
88a506a76a447682d00875efe37c6f7c7813d3eb
668,632
def lookup_attribute_chain(attrname, namespace): """ Ignore: >>> attrname = funcname >>> namespace = mod.__dict__ >>> import utool as ut >>> globals_ = ut.util_inspect.__dict__ >>> attrname = 'KWReg.print_defaultkw' """ #subdict = meta_util_six.get_funcglobals(...
d5a81407b6dacc314f25e0381ae2afc6a33ad0fa
668,634
import re def parse_show_udld_interface(raw_result): """ Parse the 'show udld interface {intf}' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show udld command in a \ dictionary of the form: :: { ...
eed8255cadf9be7377b4e94b60850688d60899fe
668,635
from typing import Dict from typing import List from typing import Tuple from typing import Counter def score_chars(all_char_weights: Dict[str, List[Tuple[str, float]]], text: str) -> Dict[str, float]: """Gets a score for each language for the given text based on how common the characters are.""" chars = Coun...
4ad5ef5d5ef8b3fec8d6d3104f9b17141fe7192b
668,636
def remove_prefix(string: str, prefix: str) -> str: """ Removes a prefix substring from a given string Params: - `string` - The string to remove the prefix from - `prefix` - The substring to remove from the start of `string` Returns: A copy of `string` without the given `prefix` """ ...
786c1fa55a08cb1155960c60c611fe07b766d8b0
668,637
def pgo_stage(stage): """ Returns true if LLVM is being built as a PGO benchmark :return: True if LLVM is being built as a PGO benchmark, false if not """ return stage == "pgo"
ea13020b79301ae6b60850fadc0b4decacc45aa7
668,638
def ReadGoldStandard(gold_file): """Read in gold standard data.""" fp = open("../test_data/gold_data/%s" % gold_file, "rb") gold_content = fp.read() fp.close() return gold_content
89747ed04283bfce1fe96b26a31abc143f924dee
668,639
import os def dump_exists(dirname): """ whether or not dump_dir has dumped to the given dirname """ filename = os.path.join(dirname, "main.pkl") return os.path.exists(filename)
75c0b2a76a177aa2aa7280df288f250fb7ea4f59
668,640
import subprocess def stop_docker_container(container_id, wait_time=1): """Stops the docker container, |container_id|. Returns True on success.""" result = subprocess.run( ['docker', 'stop', container_id, '-t', str(wait_time)], check=False) return result.returncode == 0
6d243813462fa4f20ae4d998595f954776396a48
668,642
import hashlib def string_hash_to_md5(str): """ 将字符串HASH :param param1: this is a first param :param param2: this is a second param :returns: this is a description of what is returned :raises keyError: raises an exception @author: jhuang @time:09/05/2018 """ return hashlib....
13cd07c1dfd49c847d169ac4539af49e0a91ed36
668,643
from bs4 import BeautifulSoup def from_content(content): """ """ soup = BeautifulSoup(content, 'html.parser') new_image = "" if soup.find_all('img'): image = soup.find_all('img')[0] alt = image['alt'] if 'alt' in image else '' title = image['title'] if 'title' in image els...
922ddc716e6579e8c000de9b53dc6ed5fd74a5a9
668,644
def escape_filename_sh_ansic(name): """Return an ansi-c shell-escaped version of a filename.""" out =[] # gather the escaped characters into a list for ch in name: if ord(ch) < 32: out.append("\\x%02x"% ord(ch)) elif ch == '\\': out.append('\\\\') else: ...
d1414e920dc9ff53e482a148358550c716130a50
668,645
import random def interchanging_mutation(genome): """Performs Interchanging Mutation on the given genome. Two position are randomly chosen and they values corresponding to these positions are interchanged. Args: genome (required): The genome that is to be mutated. Returns: The mu...
ae816f0a7619b516c31e27949f22c7a920c9c437
668,646
import logging def get_genes_in_region(db, chrom, start, stop): """ e.g., UI: https://biobankengine.stanford.edu/region/16-50727514-50766988 MongoDB: db.genes.find({'xstart': {'$lte': 1650766988}, 'xstop' : {'$gte': 1650727514}}, fields={'_id': False}) SciDB: ...
9d3b50fe9ea15424093057c420ac634a136b3a29
668,647
from typing import List def generate_numbers(parallel_steps: int) -> List[int]: """Generate a list of numbers from 0 to 'parallel_steps'.""" numbers = [i for i in range(parallel_steps)] print(f"Numbers: {numbers}") return numbers
227cd8bc8db7fc0e9d150bbb48e19213d14808aa
668,649
def _multi_line(in_string): """true if string has any linefeeds""" return "\n" in str(in_string)
d1381d2a86548178cd4a4b4690018092fe989b5f
668,650
def get_user_name_from_soup(soup, website_type): """Get the name of the user by website.""" # if website_type == 'channel': # section = soup.find_all('section', {'class': 'channelsProfile'})[0] # wrapper = section.find_all('div', {'class': 'bottomExtendedWrapper'})[0] # h1 = wrapper.find_all...
7c1b68a7ada4f75efc5d2ff8cf184bce2b753dd4
668,651
import re import ast def read_csv(filename, skip_rows=0): """ Read a csv file. It is possible use ',' or ';' as delimiter and use string delimeters too. Ex: "a", "b,", 'c,' 1, 2, 3 @param filename File name (*.csv) @param skip_rows Number of lines to skip at the beginning of ...
24c413e2d328973c486d38e86097005ab1c3692f
668,652
def filter_values(values, **wanted): """ Return a list of desired Value objects. :param networks: list of Value dicts :param wanted: kwargs of field/value to filter on """ ret = [] for v in values: if all(v.get(field) == value for field, value in wanted.items()): ...
6e8535667815f7ca38c512fe0182aa509b033f99
668,653
def BuildDtd(desc_json): """Create a list out of a single detailed timing descriptor dictionary. Args: desc_json: The dictionary of a single detailed timing descriptor info. Returns: A list of 18 bytes representing a single detailed timing descriptor. """ d = [0] * 18 # Set pixel ...
bfe59efe3d022630a2983c08d51118865d9974d2
668,654
def to_list(dataseq): """Converts a ctypes array to a list.""" return list(dataseq)
00f139988633549efa7037c63e6285021068ed82
668,655
import sys def _import_module(name, package=None): """ 根据模块名载入模块 :param name: :param package: :return: """ if name.startswith('.'): name = '{package}.{module}'.format(package=package, module=str(name).strip('.')) __import__(name) return sys.modules[name]
718781e1b13f175751bfde8d099635bac66c4837
668,656
def parse_top_output(out): """ Parses the output of the Docker CLI 'docker top <container>'. Note that if 'ps' output columns are modified and 'args' (for the command) is anywhere but in the last column, this will not parse correctly. However, the Docker API produces wrong output in this case as well. ...
36d210bf6e012e36ca616a9e0506b53d828c57c1
668,657
def grep_init_lr(starting_epoch, lr_schedule): """ starting_epoch : starting epoch index (1 based) lr_schedule : list of [(epoch, val), ...]. It is assumed to be sorted by epoch return init_lr : learning rate at the starting epoch """ init_lr = lr_schedule[0][1] for e, v in lr_...
e02445b3d61912385a4e7899dfc4bb7c9a3c168e
668,658
def _random_subset_weighted(seq, m, fitness_values, rng): """ Return m unique elements from seq weighted by fitness_values. This differs from random.sample which can return repeated elements if seq holds repeated elements. Modified version of networkx.generators.random_graphs._random_subset ""...
438b72a0d36e529ec554e33357b7ad6dc37aaea5
668,659
def add_tag(tag: str, s: str) -> str: """ Adds a tag on either side of a string. """ return "<{}>{}</{}>".format(tag, s, tag)
86b7b66cf595651e1da25e7cb342e42e80628193
668,660