content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def askfont(): """ Opens a :class:`FontChooser` toplevel to allow the user to select a font :return: font tuple (family_name, size, \*options), :class:`~font.Font` object """ chooser = FontChooser() chooser.wait_window() return chooser.font
8bce830a24d92be38c23ba09b6754f2e6cc6d161
4,100
def load_data(train_file, test_file): """ The method reads train and test data from their dataset files. Then, it splits train data into features and labels. Parameters ---------- train_file: directory of the file in which train data set is located test_file: directory of the file in which ...
d830f4bcd3efe467a23cab0dfa4a3cdb4694559e
4,101
import os def split_dataset_random(data_path, test_size=0.2): """Split the dataset in two sets train and test with a repartition given by test_size data_path is a string test_size is a float between 0 and 1""" #Initialise list for the names of the files sample_name = [] #Get the file of the da...
8c24f4a0dda3b3da8c637b624655dd98c6f9ff0a
4,102
def guide(batch_X, batch_y=None, num_obs_total=None): """Defines the probabilistic guide for z (variational approximation to posterior): q(z) ~ p(z|x) """ # we are interested in the posterior of w and intercept # since this is a fairly simple model, we just initialize them according # to our prior b...
889f3224424496a4f001d81b046e1279ba0efe77
4,103
import os def downloads_dir(): """ :returns string: default downloads directory path. """ return os.path.expanduser('~') + "/Downloads/"
f8c328a3176a664387059ebf6af567d018bcd57e
4,104
def get_reddit_tables(): """Returns 12 reddit tables corresponding to 2016""" reddit_2016_tables = [] temp = '`fh-bigquery.reddit_posts.2016_{}`' for i in range(1, 10): reddit_2016_tables.append(temp.format('0' + str(i))) for i in range(10, 13): reddit_2016_tables.append(temp.format(...
e590ab35becbe46aa220257f6629e54f720b3a13
4,105
def first_empty(): """Return the lowest numbered workspace that is empty.""" workspaces = sorted(get_workspace_numbers(get_workspaces().keys())) for i in range(len(workspaces)): if workspaces[i] != i + 1: return str(i + 1) return str(len(workspaces) + 1)
f9c9f868570bbcc15a28097930d304b308ddf452
4,106
import argparse def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Demonstrate affect on SVM of removing a support vector' , formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-o', '--outfile', ...
ab279b344be0c8b632eafe9e1f86a6638792eb8f
4,107
def get_local_tzone(): """Get the current time zone on the local host""" if localtime().tm_isdst: if altzone < 0: tzone = '+' + \ str(int(float(altzone) / 60 // 60)).rjust(2, '0') + \ str(int(float( ...
dec1d9f9c5ecf937779de55a33397436841913bc
4,108
def subscribers_tables_merge(tablename1: Tablename, tablename2: Tablename, csv_path=csvpath, verbose=True): """ Сводит таблицы, полученные загрузчиком, в одну. Может принимать pandas.DataFrame или имя группы, в этом случае группа должна быть в списке групп, а соответствующий файл - в <csv_path> """ ...
56c5c80b57aa4103f1836f8b9a5ca7bbb67e25bc
4,109
def get_current_offset(session): """ For backfilling only, this function works with the init container to look up it's job_id so it can line that up with it's consumer group and offest so that we can backfill up to a given point and then kill the worker afterwards. """ if settings.JOB_ID is None...
97d0b0485005a709a047582667f56a79f636388d
4,110
def get_params(p1, p2, L): """ Return the curve parameters 'a', 'p', 'q' as well as the integration constant 'c', given the input parameters. """ hv = p2 - p1 m = p1 + p2 def f_bind(a): return f(a, *hv, L) def fprime_bind(a): return fprime(a, hv[0]) # Newton-Raphson algorithm to fin...
eae7d942b4272b3addc6c3f3912abc564e93f339
4,111
def _unpack(f): """to unpack arguments""" def decorated(input): if not isinstance(input, tuple): input = (input,) return f(*input) return decorated
245d425b45d9d7ef90239b791d6d65bcbd0433d5
4,112
from .ops.classes import WriteRichOp from typing import Iterable from functools import reduce def chain_rich(iterable: Iterable['WriteRichOp']) -> 'WriteRichOp': """Take an `iterable` of `WriteRich` segments and combine them to produce a single WriteRich operation.""" return reduce(WriteRichOp.then, iterable...
fa75ab929fb01b9c68e58938aa04aebddc26f245
4,113
def sum_plot_chi2_curve(bin_num, sum_bin, r_mpc, ax=None, cov_type='bt', label=None, xlabel=True, ylabel=True, show_bin=True, ref_sig=None): """Plot the chi2 curve.""" if ax is None: fig = plt.figure(figsize=(6, 6)) fig.subplots_adjust( left=0.165, bottom=0.13...
6f0b7adf2daa98ecac9ff722eab9f6b748ef188b
4,114
import dfim import dfim.util def compute_importance(model, sequences, tasks, score_type='gradient_input', find_scores_layer_idx=0, target_layer_idx=-2, reference_gc=0.46, reference_shuffle_type=None, ...
a7ebe928f4e3b50d5c8735d438d28c034d5dfeb9
4,115
from typing import Iterable def test_check_non_existing() -> None: """Test a check on a non-existing column.""" class Schema(pa.SchemaModel): a: Series[int] @pa.check("nope") @classmethod def int_column_lt_100(cls, series: pd.Series) -> Iterable[bool]: return seri...
473b0e1c4b4c785970bdc648e4290426524882c7
4,116
import requests def fetch_url(url): """Fetches the specified URL. :param url: The URL to fetch :type url: string :returns: The response object """ return requests.get(url)
26198dbc4f7af306e7a09c86b59a7da1a4802241
4,117
def _nw_score_(s1, s2, insert=lambda c: -2, delete=lambda c: -2, substitute=lambda c1, c2: 2 if c1 == c2 else -1): """Compute Needleman Wunsch score for aligning two strings. This algorithm basically performs the same operations as Needleman Wunsch alignment, but is made more ...
009c9eb4afec828adde53bddfd2a8b4d2a952c24
4,118
import pickle import torch import re import warnings from typing import Counter from typing import OrderedDict def load_gisaid_data( *, device="cpu", min_region_size=50, include={}, exclude={}, end_day=None, columns_filename="results/usher.columns.pkl", features_filename="results/usher...
eaa9c5b3735f291706ea783272b3372ad9e7937c
4,119
def get_symbol_size(sym): """Get the size of a symbol""" return sym["st_size"]
b2d39afe39542e7a4e1b4fed60acfc83e6a58677
4,120
import argparse import functools import os def parse_args(argv): """Parse and validate command line flags""" parser = argparse.ArgumentParser() parser.add_argument( '--base-image', type=functools.partial( validation_utils.validate_arg_regex, flag_regex=IMAGE_REGEX), def...
afc558b05d247d1096c4c276edc4a74a34f93827
4,121
def to_unnamed_recursive(sexpr, scheme): """Convert all named column references to unnamed column references.""" def convert(n): if isinstance(n, NamedAttributeRef): n = toUnnamed(n, scheme) n.apply(convert) return n return convert(sexpr)
ffb58acb1cfbef654c5c936880961b8cc982ec01
4,122
def login_process(): """Process login.""" email_address = request.form.get("email") password = request.form.get("password") user = User.query.filter_by(email_address=email_address).first() if not user: flash("Please try again!") return redirect('/') if user.password != passwor...
afee068b653e5f759329658e3614b0ce7ee2d405
4,123
def get_doc_translations(doctype, name): """ Returns a dict custom tailored for the document. - Translations with the following contexts are handled: - doctype:name:docfield - doctype:name - doctype:docfield (Select fields only) - 'Select' docfields will have a values dict which will have trans...
e7fd896de3162452a77ab989670e61b01e8e35a2
4,124
from datetime import datetime def fetch_newer_version( installed_version=scancode_version, new_version_url='https://pypi.org/pypi/scancode-toolkit/json', force=False, ): """ Return a version string if there is an updated version of scancode-toolkit newer than the installed version and availabl...
efd0e92219efd8fb54064200acbdc3e512071f37
4,125
def app(request): """ Default view for Person Authority App """ return direct_to_template(request, 'person_authority/app.html', {'app':APP})
9e75c9cf381c69b19bfdf08c74b2e0dc2106822b
4,126
def is_xbar(top, name): """Check if the given name is crossbar """ xbars = list(filter(lambda node: node["name"] == name, top["xbar"])) if len(xbars) == 0: return False, None if len(xbars) > 1: log.error("Matching crossbar {} is more than one.".format(name)) raise SystemExit...
435b84a30f3f749f07d0cc6dfdd5e7f0c5343c4f
4,127
def index(): """ Root URL response """ return "Reminder: return some useful information in json format about the service here", status.HTTP_200_OK
d8128c8ba8976238c1d68376eaa64a77d09ce525
4,128
def backproject(depth, K): """Backproject a depth map to a cloud map depth: depth ---- organized cloud map: (H,W,3) """ H, W = depth.shape X, Y = np.meshgrid(np.asarray(range(W)) - K[0, 2], np.asarray(range(H)) - K[1, 2]) return np.stack((X * depth / K[0, 0], Y * depth / K[1, 1], depth)...
5433fd408932f48c238cad7e5e8d7b14ee7b00de
4,129
from pathlib import Path def get_parent_dir(os_path: str) -> str: """ Get the parent directory. """ return str(Path(os_path).parents[1])
3a6e518119e39bfbdb9381bc570ac772b88b1334
4,130
import os import ctypes def test_is_admin(): """Returns True if the program is ran as administrator. Returns False if not ran as administrator. """ try: is_admin = (os.getuid() == 0) except AttributeError: is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0 if is_admin == 1: ...
6ace6a49a40ded8df9dd065bfd2d8f8359850b68
4,131
def parse_work_url(work_url): """Extract work id from work url Args: work_url (str): work url Returns: str: bdrc work id """ work_id = "" if work_url: work_url_parts = work_url.split("/") work_id = work_url_parts[-1] return work_id
1e7f5e222a2f6c7d01cbcb7df556adf6dd33f7cf
4,132
def room(): """Create a Room instance for all tests to share.""" return Room({"x": 4, "y": 4, "z": 4}, savable=False)
f031faa1bf654ff32868b678f79c2af040926b44
4,133
import re def searchLiteralLocation(a_string, patterns): """assumes a_string is a string, being searched in assumes patterns is a list of strings, to be search for in a_string returns a list of re span object, representing the found literal if it exists, else returns an empty list""" results = [] ...
0f751bae801eaee594216688551919ed61784187
4,134
def UIOSelector_Highlight(inUIOSelector): """ Highlight (draw outline) the element (in app) by the UIO selector. :param inUIOSelector: UIOSelector - List of items, which contains condition attributes :return: """ # Check the bitness lSafeOtherProcess = UIOSelector_SafeOtherGet_Process(inUI...
9ab5930396aa9813f09d858c4bb94adc2170f312
4,135
import torch def completeMessage_BERT(mod, tok, ind, max_length=50): """ Sentence Completion of the secret text from BERT """ tokens_tensor = torch.tensor([ind]) outInd = mod.generate(tokens_tensor, max_length=50) outText=tok.decode(outInd[0].tolist()) newText=outText[len(tok.decode(ind)):] newText=n...
c2a47bbe90a9e5d222af0bbe5959c82d2ebd2cd3
4,136
import copy import json def _select_train_and_seat_type(train_names, seat_types, query_trains): """ 选择订票车次、席别 :param train_names 预定的车次列表 :param seat_types 预定席别列表 :param query_trains 查询到火车车次列表 :return select_train, select_seat_type """ def _select_trains(query_trains, train_names=None):...
519cba93eca3a676734f05d196a7f125917da88a
4,137
def load_real_tcs(): """ Load real timecourses after djICA preprocessing """ try: return sio.loadmat(REAL_TC_DIR)['Shat'][0] except KeyError: try: return sio.loadmat(REAL_TC_DIR)['Shat_'][0] except KeyError: print("Incorrect key") pass
68b148e6fc6088d8ef9f90daf25e07609010d9fe
4,138
def create_fsaverage_forward(epoch, **kwargs): """ A forward model is an estimation of the potential or field distribution for a known source and for a known model of the head. Returns EEG forward operator with a downloaded template MRI (fsaverage). Parameters: epoch: mne.epochs.Epochs ...
34d72211babf23e41927ebe7df13c58bf6876e4d
4,139
import os def make_file(path): """ Factory function for File strategies :param str path: A local relative path or s3://, file:// protocol urls :return: """ try: if not is_valid_url(path): return LocalFile(os.path.abspath(path)) url_obj = urlparse(path) if...
29163e04c676e81a8f01456e29529b219e9ad2a8
4,140
def midi_to_hz(notes): """Hello Part 6! You should add documentation to this function. """ return 440.0 * (2.0 ** ((np.asanyarray(notes) - 69.0) / 12.0))
7215126d25ff969a8aa187c7f49216ec7743a9e9
4,141
def bond_stereo_parities(chi, one_indexed=False): """ Parse the bond stereo parities from the stereochemistry layers. :param chi: ChI string :type chi: str :param one_indexed: Return indices in one-indexing? :type one_indexed: bool :returns: A dictionary mapping bond keys on...
02729db6888899a91e69a25dae81c06777b89182
4,142
def filter_camera_angle(places): """Filter camera angles for KiTTI Datasets""" bool_in = np.logical_and((places[:, 1] < places[:, 0] - 0.27), (-places[:, 1] < places[:, 0] - 0.27)) # bool_in = np.logical_and((places[:, 1] < places[:, 0]), (-places[:, 1] < places[:, 0])) return places[bool_in]
417fccfbb240c5defc36b4ce465fe14333922b94
4,143
def neural_log_literal_function(identifier): """ A decorator for NeuralLog literal functions. :param identifier: the identifier of the function :type identifier: str :return: the decorated function :rtype: function """ return lambda x: registry(x, identifier, literal_functions)
84651d58b7da677ee213d1ff4667dc3be702f243
4,144
def get_factors(n: int) -> list: """Returns the factors of a given integer. """ return [i for i in range(1, n+1) if n % i == 0]
c15a0e30e58597daf439facd3900c214831687f2
4,145
def fetch_tables(): """ Used by the frontend, returns a JSON list of all the tables including metadata. """ return jsonify([ { "tab": "animeTables", "name": "Anime", "tables": [ { "id": "englishAnimeSites", "titl...
5c07e7bc9f3366bc72e21dd5468edf57b6c448b3
4,146
def base_positive_warps(): """ Get warp functions associated with domain (0,inf), scale 1.0 Warp function is defined as f(x) = log(exp(x)-1) Returns ------- Callable[torch.Tensor,torch.Tensor], Callable[torch.Tensor,torch.Tensor], Callable[torch.Tensor,torch.Tensor] Function...
389db769f55f7542a45e6acbbccf5760dc7b8c26
4,147
import re import json from datetime import datetime def dev_work_create(): """ Create work order. :return: """ db_ins = current_user.dbs audits = User.query.filter(User.role == 'audit') form = WorkForm() if form.validate_on_submit(): sql_content = form.sql_content.data ...
b11f840bbc6428696afabe7f2fe00b5d0b6ad7d1
4,148
def blur(x, mean=0.0, stddev=1.0): """ Resize to smaller size (AREA) and then resize to original size (BILINEAR) """ size = tf.shape(x)[:2] downsample_factor = 1 + tf.math.abs(tf.random.normal([], mean=mean, stddev=stddev)) small_size = tf.to_int32(tf.to_float(size)/downsample_factor) x = tf.image.resize_...
b0101a4b820beb84c627bef048bbafeb1d11cdea
4,149
def improve(update, close, guess=1, max_updates=100): """Iteratively improve guess with update until close(guess) is true or max_updates have been applied.""" k = 0 while not close(guess) and k < max_updates: guess = update(guess) k = k + 1 return guess
3475c07a3e9a674661d90e116bfb91fa12344d63
4,150
def images_to_sequence(tensor): """Convert a batch of images into a batch of sequences. Args: tensor: a (num_images, height, width, depth) tensor Returns: (width, num_images*height, depth) sequence tensor """ num_image_batches, height, width, depth = _shape(tensor) transposed = tf.transpose(tenso...
cc89ce931239b5335d5788bc6e9007e5186648bf
4,151
from typing import Any import logging def transform_regions(regions: list[dict[str, Any]]) -> list[dict[str, Any]]: """ Transform aggregated region data for map regions -- aggregated data from region pipeline """ records = [] for record in regions: if "latitude" in record["_id"].keys(...
599e58e3bd66159114d0dbf27b339c47134c29c3
4,152
def _file_to_import_exists(storage_client: storage.client.Client, bucket_name: str, filename: str) -> bool: """Helper function that returns whether the given GCS file exists or not.""" storage_bucket = storage_client.get_bucket(bucket_name) return storage.Blob( bucket=storage_buc...
cb051aba0d5e787e85dbc0283aa439e3c17e819c
4,153
import sys def run(args, options): """ Compile a file and output a Program object. If options.merge_opens is set to True, will attempt to merge any parallelisable open instructions. """ prog = Program(args, options) VARS['program'] = prog if options.binary: VARS['sint'] = GC_...
bdaf9327a94c38b9e6ba3e8206ca6ea3664b1073
4,154
from typing import Optional from typing import List from typing import Tuple def get_relative_poses( num_frames: int, frames: np.ndarray, selected_track_id: Optional[int], agents: List[np.ndarray], agent_from_world: np.ndarray, current_agent_yaw: float, ) -> Tuple[np.ndarray, np.ndarray, np.nd...
e1dad983e5070310ce239615c98f85d8b09b9c45
4,155
import numpy def read_mat_cplx_bin(fname): """ Reads a .bin file containing floating-point values (complex) saved by Koala Parameters ---------- fname : string Path to the file Returns ------- buffer : ndarray An array containing the complex floating-point values read...
f2761f4cd7031dc16cb2f9903fd431bc7b4212d8
4,156
def DeleteDataBundle(**kwargs): """ Deletes a Data Bundle by ID. :param kwargs: :return: """ data_bundle_id = kwargs['data_bundle_id'] del data_bundles[data_bundle_id] return(kwargs, 200)
88ded979e45beebe885eeb1890ce66ae367b1fd6
4,157
def determineactions(repo, deficiencies, sourcereqs, destreqs): """Determine upgrade actions that will be performed. Given a list of improvements as returned by ``finddeficiencies`` and ``findoptimizations``, determine the list of upgrade actions that will be performed. The role of this function i...
0ec771565560607e839ce87a65426e01d0276f36
4,158
def filter_ccfs(ccfs, sc_thresh, min_ccf): """ Remove noisy ccfs from irrelevant experiments :param ccfs: 2d array :param sc_thresh: int number of sign changes expected :param min_ccf: float cutoff value for a ccf to be above the noise threshold :return: """ if sc_thresh ...
06941eaea7bc5dc25f261669532c66ac37cbb9ab
4,159
def market_data(symbol, expirationDate, strike, optionType, info=None): """Gets option market data from information. Takes time to load pages.""" assert all(isinstance(i, str) for i in [symbol, expirationDate, strike, optionType]) return robin_stocks.options.get_option_market_data(symbol, expirationDate, strike, opt...
153d15af1030be22fa6c97b8d68fdf2049ebc416
4,160
def get_documents_embeddings (y, embedder, column): """ Given a Dataframe containing study_id and a text column, return a numpy array of embeddings The idea of this function is to prevent to embed two times the same text (for computation efficiency) Parameters: ----------- ...
9a748ef8b276d68a61d78c6fa567a40aae4fc222
4,161
def index(request): """view fonction de la page d'accueil Render templates de la page d'accueil """ return render(request, "t_myapp/index.html")
b3cf3be5d3c2a286d5705281e35042ad19d0a050
4,162
def cidr_mask_to_subnet_mask(mask_num): """ 掩码位数转换为点分掩码 :param mask_num: 掩码位数, 如 16 :return: 十进制点分ipv4地址 """ return convert_to_ipv4(cidr_mask_to_ip_int(mask_num), stype='int')
83556c856f68e82824fa1f3a34b4d629361081af
4,163
def correlate(A,B, rows=None,columns=None, mode_row='zero', mode_column='zero'): """Correlate A and B. Input: ------ A,B : array Input data. columns : int Do correlation at columns 0..columns, defaults to the number of columns in A. rows : int Do correlatio...
88bfec52c318aaf119a6fac5cff731855f0a0d81
4,164
def getChrLenList(chrLenDict, c): """ Given a chromosome length dictionary keyed on chromosome names and a chromosome name (c) this returns a list of all the runtimes for a given chromosome across all Step names. """ l = [] if c not in chrLenDict: return l for n in chrLenDict[c]: ...
aedf613484262ac5bd31baf384ade2eb35f3e1eb
4,165
import argparse def build_arg_parser(): """ Build an argument parser using argparse. Use it when python version is 2.7 or later. """ parser = argparse.ArgumentParser(description="Smatch table calculator -- arguments") parser.add_argument("--fl", type=argparse.FileType('r'), help='AMR ID list file...
199332d5c6c6811ba4c11437c0cad8387bb8dd60
4,166
from typing import Optional def query_sessions(user_id: Optional[int]) -> TList[Session]: """ Return all user's sessions :param user_id: current user ID (None if user auth is disabled) :return: list of session objects """ adb = get_data_file_db(user_id) return [Session(db_session) for db...
c7449c7805f1ba0c425140603952215b67e3ce0e
4,167
import torch import math def positionalencoding3d(d_model, dx, dy, dz): """ :param d_model: dimension of the model :param height: height of the positions :param width: width of the positions :return: d_model*height*width position matrix """ # if d_model % 6 != 0: # raise ValueError("...
178dc3b86e3be0c9e799f5f0c658808f541f1eca
4,168
def make_headers(context: TraceContext) -> Headers: """Creates dict with zipkin headers from supplied trace context. """ headers = { TRACE_ID_HEADER: context.trace_id, SPAN_ID_HEADER: context.span_id, FLAGS_HEADER: '0', SAMPLED_ID_HEADER: '1' if context.sampled else '0', ...
474e3a57af1bda99585f7d140fbd0bb1d9bd18b2
4,169
def shiftRightUnsigned(col, numBits): """Unsigned shift the given value numBits right. >>> df = spark.createDataFrame([(-42,)], ['a']) >>> df.select(shiftRightUnsigned('a', 1).alias('r')).collect() [Row(r=9223372036854775787)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functio...
342d08644c56c2cce5e02f0d3d0ddd9df0b2f173
4,170
def scalar_sub(x: Number, y: Number) -> Number: """Implement `scalar_sub`.""" _assert_scalar(x, y) return x - y
74c9d44eaaabb1bfeea012b4ec1503e37d7c9f8b
4,171
def predict_attack(h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13): """ Parameters: -name:h1 in:query type:number required=True -name:h5 in:query type:number required:True -name:h4 in:query type:number required:True -name:h8 ...
907f6b52c3b1c24a409b8b7ebc157412bd67777d
4,172
def _check_varrlist_integrity(vlist): """Return true if shapes and datatypes are the same""" shape = vlist[0].data.shape datatype = vlist[0].data.dtype for v in vlist: if v.data.shape != shape: raise(Exception("Data shapes don't match")) if v.data.dtype != datatype: ...
1b6fedd1222757c0bc92490be85d8030ee877842
4,173
def subclassfactory(fact_method): """fact_method takes the same args as init and returns the subclass appropriate to those args that subclass may in turn override the same factory method and choose amoung it's subclasses. If this factory method isn't overridden in the subclass an object of that class is ini...
eb0b8227276ed7499d21d9998ec08fb830d89642
4,174
def simulate_var1(x_tnow, b, mu, sigma2, m_, *, j_=1000, nu=10**9, init_value=True): """For details, see here. Parameters ---------- x_tnow : array, shape(n_, ) b : array, shape(n_,n_) mu : array, shape(n_, ) sigma2 : array, shape(n_,n_) m_ : int ...
66bf82052e933e14d16e82738d36a4c96b51ca43
4,175
from typing import Optional def is_drom(insee_city: Optional[str] = None, insee_region: Optional[str] = None) -> bool: """ Est-ce que le code INSEE de la ville ou de la région correspond à un DROM ? Args: insee_city: Code INSEE de la ville insee_region: Code INSEE de la région Return...
7a33516eb31c5ff7800eb6dc663d76d5e2c445cb
4,176
import math def pack_rows(rows, bitdepth): """Yield packed rows that are a byte array. Each byte is packed with the values from several pixels. """ assert bitdepth < 8 assert 8 % bitdepth == 0 # samples per byte spb = int(8 / bitdepth) def make_byte(block): """Take a block o...
e0b8a4701adf1757a558475e2ea5830a3d53ab2a
4,177
def reset_user_pwd(username: str) -> int: """ :param username: 用户名 :return: 结果代码: 1: 成功, 0: 失败 """ return update_user_info(username=username, args={ 'password': '12345678' })
a9703bb82913b47e9b59ba36cd9257323cbfeec2
4,178
def location_engineering(df: pd.DataFrame) -> pd.DataFrame: """Call the `location_dict()` function to get the location dictionary and the `location_dataframe()` one to add the location dictionary info to the DataFrame. Parameters ---------- df : The dataframe to work with. Returns ...
cca3e1724da08ffcb895aa9fc323ebaf380760e4
4,179
import re def extract_energyxtb(logfile=None): """ Extracts xtb energies from xtb logfile using regex matching. Args: logfile (str): Specifies logfile to pull energy from Returns: energy (list[float]): List of floats containing the energy in each step """ re_energy = re.comp...
075f9d48d3bcc9f6bd12aa791cc4d0444299dd74
4,180
import os def GetPID(): """Returns the PID of the shell.""" return os.getppid()
28e56a9d0c1c6c1d005c58f5c9fffeb3857d8877
4,181
def make_transaction_frame(transactions): """ Formats a transaction DataFrame. Parameters ---------- transactions : pd.DataFrame Contains improperly formatted transactional data. Returns ------- df : pd.DataFrame Daily transaction volume and dollar ammount. - S...
ab8feafb1a441fddf574ebd12a7720a7c4d7398b
4,182
def find_or_create_role(name, desc): """ Find existing role or create new role """ role = Role.query.filter(Role.name == name).first() if not role: role = Role(name=name, desc=desc) return role return role
414b960488d55ea6c2cc41121132f06f0d677abd
4,183
import os def enumerate_shapefile_fields(shapefile_uri): """Enumerate all the fielfd in a shapefile. Inputs: -shapefile_uri: uri to the shapefile which fields have to be enumerated Returns a nested list of the field names in the order they are stored in the layer,...
1a1a128daa991854629894b7e23e90253761a1c8
4,184
def parse_nrrdvector(inp): """Parse a vector from a nrrd header, return a list.""" assert inp[0] == '(', "Vector should be enclosed by parenthesis." assert inp[-1] == ')', "Vector should be enclosed by parenthesis." return [_to_reproducible_float(x) for x in inp[1:-1].split(',')]
3e3c793d3ee53198c4cdb01832062be4f0c02876
4,185
def _estimate_gaussian_covariances_spherical(resp, X, nk, means, reg_covar): """Estimate the spherical variance values. Parameters ---------- responsibilities : array-like of shape (n_samples, n_components) X : array-like of shape (n_samples, n_features) nk : array-like of shape (n_components...
6f08d04528f5e515d5ae75d4dc47753cc4cebc7b
4,186
import os def parsed_codebook_importer(codebook): """ Import the parsed CPS codebook Parameters: codebook (str): the filename of the parsed codebook Returns: dataframe """ path_finder('codebooks') skip = row_skipper(codebook) codebook = pd.read_csv(codebook, sep='\t',...
abb0b261ab894f6ea5111be07eaa00d256bfa3c9
4,187
def get_html(url): """Returns html content of the url. Retries until successful without overloading the server.""" while True: # Retry until succesful try: sleep(2) debug('Crawling %s' % url) html = urllib2.urlopen(url).read() return html e...
a444151add46273c6e72ead585d04aa65e7e7734
4,188
def map_min(process): """ """ param_dict = {'ignore_nodata': 'bool'} return map_default(process, 'min', 'reduce', param_dict)
33dcc2192fd8b979e7238c1fdbe5e9bec551dd3f
4,189
def geoname_exhaustive_search(request, searchstring): """ List all children of a geoname filtered by a list of featurecodes """ if request.query_params.get('fcode'): fcodes = [ s.upper() for s in request.query_params.get('fcode').split(',')] else: fcodes = [] limit = request.qu...
5a04a158a146e7e0ad3265d89520774b65c3780a
4,190
import sys def guess_temperature_sensor(): """ Try guessing the location of the installed temperature sensor """ devices = listdir(DEVICE_FOLDER) devices = [device for device in devices if device.startswith('28-')] if devices: # print "Found", len(devices), "devices which maybe tempera...
d1a37d34eedb1e9a99e481ac3ffb6f5777fcdb7a
4,191
def count_reads(regions_list, params): """ Count reads from bam within regions (counts position of cutsite to prevent double-counting) """ bam_f = params.bam read_shift = params.read_shift bam_obj = pysam.AlignmentFile(bam_f, "rb") log_q = params.log_q logger = TobiasLogger("", params.verbosity, log_q) #sending...
ffd8cc6afc6c0b5b92d82292ab9d4a54ef918641
4,192
def rgbImage2grayVector(img): """ Turns a row and column rgb image into a 1D grayscale vector """ gray = [] for row_index in range(0, len(img)): for pixel_index, pixel in enumerate(img[row_index]): gray.append(rgbPixel2grayscaleValue(pixel)) return gray
a93bbb2dfa29cb3d4013334226e77f6beb526a13
4,193
def compute_MSE(predicted, observed): """ predicted is scalar and observed as array""" if len(observed) == 0: return 0 err = 0 for o in observed: err += (predicted - o)**2/predicted return err/len(observed)
e2cc326dde2ece551f78cd842d1bf44707bfb6db
4,194
def log_sum(log_u): """Compute `log(sum(exp(log_u)))`""" if len(log_u) == 0: return NEG_INF maxi = np.argmax(log_u) max = log_u[maxi] if max == NEG_INF: return max else: exp = log_u - max np.exp(exp, out = exp) return np.log1p(np.sum(exp[:maxi]) + np.sum(...
f2c7917bc806dc7ec3fbbb1404725f590a82e194
4,195
import os from datetime import datetime def gather_basic_file_info(filename: str): """ Build out the basic file metadata that can be gathered from any file on the file system. Parameters ---------- filename full file path to a file Returns ------- dict basic file attr...
cb18c5213ce7a7d4f1355e84e6f6debe2052490b
4,196
def special_value_sub(lhs, rhs): """ Subtraction between special values or between special values and numbers """ if is_nan(lhs): return FP_QNaN(lhs.precision) elif is_nan(rhs): return FP_QNaN(rhs.precision) elif (is_plus_infty(lhs) and is_plus_infty(rhs)) or \ (is_minus...
df64cf6c306c3192ba28d08e878add7ce0f27a2c
4,197
def parse_git_repo(git_repo): """Parse a git repository URL. git-clone(1) lists these as examples of supported URLs: - ssh://[user@]host.xz[:port]/path/to/repo.git/ - git://host.xz[:port]/path/to/repo.git/ - http[s]://host.xz[:port]/path/to/repo.git/ - ftp[s]://host.xz[:port]/path/to/repo.git/...
5eddf3aa9016996fb8aa1720b506c2f86b2e9c14
4,198
def make_wavefunction_list(circuit, include_initial_wavefunction=True): """ simulate the circuit, keeping track of the state vectors at ench step""" wavefunctions = [] simulator = cirq.Simulator() for i, step in enumerate(simulator.simulate_moment_steps(circuit)): wavefunction_scrambled = step....
af33d4a7be58ccfa7737deb289cbf5d581246e86
4,199