content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def insert_workspace(cursor, specification): """workspace情報登録 Args: cursor (mysql.connector.cursor): カーソル specification (Dict)): ワークスペース情報のJson形式 Returns: int: ワークスペースID """ # insert実行 cursor.execute('INSERT INTO workspace ( organization_id, speci...
1dcc08af71e133bc9a34d3bc1a23f641ba253ec0
70,100
import xarray as xr from aux_gps import save_ncfile def produce_final_dsea_pwv(ims_station=None, savepath=None, use_pressure=True): """use ims_station='SEDOM' to get close ts, pressure""" if ims_station is not None: ts = xr.open_dataset(ims_path/'IMS_TD_israeli_10mins.nc')[ims_station] pres = ...
5a172a9b940307fe6d6d8786ab1666d4b77d4a40
70,101
import urllib def url_encode(params): """Wrapper for urllib.urlencode which doesn't handle UTF-8 encoded characters""" for key, value in params.items(): if isinstance(value, str): params[key] = value.encode('utf-8') return urllib.parse.urlencode(params, doseq=True)
4d6313a1624228e786e9ebdce1a0c2e8055391fa
70,102
def f_classification (dataset): """ ANOVA: avalia afirmações através das médias das populações. A análise permite verificar se exite ou não diferença significativa entre as médias e se os fatores têm influência nas variáveis dependentes. """ X = dataset.X y = dataset.y aa = [] for...
47c88588e37e5ffb34a92f8c63bb92d81a0198cb
70,103
from typing import Union from typing import Callable def get_source(object_: Union[type, Callable, ModuleType]) -> str: """ Get the source code which defined an object. """ object_source: str = getattr(object_, "_source", "") if not object_source: object_source = getsource(object_) ret...
00bf59045495fd8fd3d15fb205e6edf9f4f8f385
70,104
def get_read_params(stmt): """Get the feature map parameters from a read loop nest. Parameters ---------- stmt : tvm.tir.AttrStmt The outermost attribute statement of a read loop nest. Returns ------- SerialFeatureMap The serializable feature map. input_pointer : tvm.ti...
bcdab9cbc5ebd73fb3bf30fdccd8e56a12a43410
70,105
def asRawURL(url): """ rawURL is just the name followed by the claim_id, without channel info, like blog#4fa3e1b8c62e9b41e6cf4a3eb9faafe3778f1445 """ l = fixedAPI() res = l.resolveOrNone(url) if not res: return None permalink = "" claimID = recGetter(res, 'claim', 'claim_id') i...
ce2240c0a27712672dcbe665f503356140ddc67a
70,106
def cellbasis(angles, edges): """ For the unit cell with given angles and edge lengths calculate the basis transformation (vectors) as a 4x4 matrix """ rad = np.deg2rad(angles) basis = np.identity(4) basis[0][1] = np.cos(rad[2]) basis[1][1] = np.sin(rad[2]) basis[0][2] = np.cos(rad[1...
ec67067039c67c78df3d5b1300928e545a9b8f59
70,107
from typing import Any from typing import Tuple from typing import Union from typing import List import signal def peak_detector( filtered_magnetic_signal: NDArray[(2, Any), int], twitches_point_up: bool = True, start_time: float = 0, end_time: float = np.inf, prominence_factors: Tuple[Union[int, ...
83efbcd6fc6aa5933f7626a81017730c45b983ad
70,108
def point_in_polygon(points, x, y): """ Ray casting algorithm. Determines how many times a horizontal ray starting from the point intersects with the sides of the polygon. If it is an even number of times, the point is outside, if odd, inside. The algorithm does not always report c...
26ab72c6b545f94d41b0d1228dd312d590ad208b
70,109
import os def find_local_raw_file(unix_time_sec=None, top_directory_name=None, raise_error_if_missing=False): """Finds raw file on local machine. This file should contain all variables for all stations and one 5-minute time step. :param unix_time_sec: Time in Unix format. ...
a283b0bb3a3ce9c2284e9ec4423d0e10fc3f66d2
70,110
def task3(ob): """ Function that take an object as input and prints its docs (__doc__) every sentence in one line. Input: name of object (e.g. int) Output: string ready to write. """ return ob.__doc__
859996692629a61664acf39309741020192f3da5
70,111
def word_count(sentence,method): """ 切割字符后计算词的出现频率 :param sentence: :return: """ res = {} word_list = CUT_METHODS.get(method)(sentence) for word in word_list: if len(word) > 1: res[word] = sentence.count(word) return res
bac9fc45c1cbe84d0afd5c0e3aad988d34ede75d
70,112
def validate_integer(value, name, min_value=None, max_value=None): """Make sure that value is a valid integer, potentially within range.""" try: value = int(str(value)) except (ValueError, UnicodeEncodeError): msg = _('%(value_name)s must be an integer') raise exception.InvalidInput...
b14230ddd0835b3a2c206472baa6a6e6dc6f59d0
70,113
from typing import Dict from typing import Union import requests def search_entry( journal_base_url: str, message_ts: str, reaction_user: str, bugout_user: SlackBugoutUser, bot_installation: SlackOAuthEvent, ) -> str: """ Search journal via message_ts """ entry_search = f"{journal...
be65f4f80c65c2f3a844e78dd1102e48a30bffc9
70,114
def create_cost(bounds_true, bounds_pred): """ create_cost(bounds_true, bounds_pred) Parameters ---------- bounds_true : 2d ndarray (rows = seizrs, columns = start,stop), ground truth bounds_pred : 2d ndarray (rows = seizrs, columns = start,stop), predicted Returns ------- cost : F...
3e38cccae0f03c986fb3079c072d55b404aeb48a
70,115
def mrr_ng_to_fsr(lambda0, n_g, radius): """ description: Calculate the free-spectral range (FSR) based on the central resonance wavelength, group index and MRR radius. (Bogaerts et al., Silicon microring resonators, Laser and Photonics Review 2011, Eq.(9))\\ lambda0 {float} Resonance wavelength (unit: ...
b4b74f1ed8bff28cfceb4ebbbf8bc42a92eec05c
70,116
def _indexed_tags(tags): """Returns a list of tags that must be indexed. The order of returned tags is from more selective to less selective. """ if not tags: return [] return sorted(set( t for t in tags if t.startswith(('buildset:', 'build_address:')) ))
0a85c2f88e452c4898cc3a77d9cf5ebc9a90b8f6
70,117
def set_default_blockchain(blockchain: Blockchain): """ Δ(β) \n \t Makes privacychain adopt β as the default blockchain: \t 1: "HYPERLEDGER" \n \t 2: "ETHEREUM (default)" \n \t 3: "BITCOIN" \n """ blockchain = { 1: "HYPERLEDGER", 2: "ETHE...
8e6ebe455595e0bf0baa5e766bdb82df9abc3281
70,118
def test_sequential(): """call `set_seed` just before generating random variables""" def build(): set_seed(200) layers = [ tf.keras.layers.Conv2D(4, 3, input_shape=(16, 16, 3)), tf.keras.layers.BatchNormalization(), tf.keras.layers.Activation("relu"), ...
d2b547e7a69d580f6316429801f9e09d5262a85e
70,119
from typing import Callable from datetime import datetime def gogetcisdata(startyear: int = STARTYEAR, startmonth: int = STARTMONTH, startday: int = STARTDAY, storefunc: Callable[[str, str], None] = None): """ manage getting CIS data, uses multiple sessions to avoid throttling """ thisyear = ...
b20222a23cc506977d9aa3a9c9fa93028183657a
70,120
def render_figure(code, code_dir, language, output_dir, output_base, config=None): """ Run a GMT code and save the images in *output_dir* with file names derived from *output_base*. """ # pylint: disable=too-many-arguments if language == "bash": figname = eval_bash(code, code_dir, output...
59741e88b00568298535f57fa0a6c8b3a80f3f17
70,121
def add_server_subparser(subparsers): """ Create the subparser for 'shorts serve' """ server_parser = subparsers.add_parser('serve', help="serve this site") server_parser.set_defaults(func=shortstack.server.start) server_parser.add_argument('--port', '...
788972926bdd63b14f92d8613140aa8ec061aee4
70,122
from functools import reduce def ensure_latest_source_from_artifacts( source, name, destination=None, host=None, port=22, only_cache=False ): """ Ensure a repository is checked out and the latest version in the name directory in the INSTALL DIR on the specified machine. Caches the repository in artifa...
1cef445e7029d87c9b179d44e9972bb748b4b535
70,123
from datetime import datetime def plot_forecast( fig, ax, y, f, samples, dates, linewidth=1, linecolor="b", credible_interval=95, **kwargs, ): """ Plot observations along with sequential forecasts and credible intervals. """ ax.scatter(dates, y, color="k") ...
63be9c6fc5099d6114efdff8dacb5dfaf013414f
70,124
import logging import sys def srv_or_die(name): """Get a service instance or return None""" if name in SERVICES: return SERVICES[name] logging.error("Unable to find service %s", name) sys.exit(1)
81f96a9be06f97d98ef7f7632d31e70cd250e127
70,125
def update_user(user_id): """ Update a user's atat role. PUT /users/<user id> { atat_role: <name of an atat role> } Returns the updated user. """ try: atat_role_name = request.json["atat_role"] except (KeyError, TypeError): abort(400) try: upda...
cc3de44ee393d37e6911c38aa07cf4f8dc1e66bd
70,126
def get_finger_joint_limit_state(x,m): """Gets the joint limit state of the finger from a hybrid state""" return m[3:6]
90fa8e3dce6c9f9dc08e3e7c2fd9e447690202c1
70,127
def test_id(id): """Convert a test id in JSON into an immutable object that can be used as a dictionary key""" if isinstance(id, list): return tuple(id) else: return id
11e18a57648cb09f680751d1596193020523e5e1
70,128
import re def MakeHeaderToken(filename): """Generates a header guard token. Args: filename: the name of the header file Returns: the generated header guard token. """ return re.sub('[^A-Z0-9_]', '_', filename.upper()) + '__'
d29f756e30c3214aac174302175c52ca28cad6cb
70,129
def interpret_met_auxsens_code(auxsenscode): """interpret integer code for the availability of auxiliary sensors in MET files, return dict of contents vars""" auxsenscode_int8 = np.uint8(auxsenscode) auxsensbits = np.unpackbits(auxsenscode_int8, bitorder='little') if auxsensbits is None: out = {...
2d030b2a212a9555af6867a3b73f3971fbff01af
70,130
def admin_board_delete(): """ This function is used for logged in admin to delete a board :return: json information if the deletion is successful it will return status 1 otherwise it will return error message """ Bid = request.form.get("Bid") if not Bid or not Bid.isnumeric(): return...
bb12323c1e9e8e0f7586e850566d4094d4d52d81
70,131
def check_byte(b): """ Clamp the supplied value to an integer between 0 and 255 inclusive :param b: A number :return: Integer representation of the number, limited to be between 0 and 255 """ i = int(b) if i < 0: i = 0 elif i > 255: i = 255 return i
374e0ffbe1d0baa80c56cafd3650fba8441c5ea0
70,132
from typing import List def apply_over_under_sampling( X_train: DataFrame, y_train: Series, target_balance: str ) -> List: """ Apply over or under sampling to adjust class balance in imbalanced data """ if target_balance in ["under_sampled", "over_sampled"]: if target_balance == "under...
f7bd51d8c9ed69549881cfc7a185ccaf8e918d28
70,133
from typing import Dict def get_piece_value(piece: Piece, color: bool) -> int: """ Helper function for piece value herustic, values each individual piece :param piece: the current piece :param color: color of the player :return: piece value """ if piece is None: return 0 piece...
4c39dd5847710bc9c6f31725f24ee417f40f8afb
70,134
def run(): """Requirements for Task 1B""" # Build list of stations stations = build_station_list(False) #run inconsistency check inconsistent_stations = inconsistent_typical_range_stations(stations) #Function to sort the list of inconsistent stations def inconsistent_stations_details(...
69f390abc6a7bbd39c6631461daa3b04e3b71206
70,135
import logging import os def SearchWindowsProgramPath(key_names, value_names, path_end): """ Search a program path on a Windows machine using the registry. \param path_end Unicode string to append at the end of the registry value. \param key_names List of registry keys to try. Will stop at the first ...
18140e1ef0cbf4193ccf5443341575f80060fdc5
70,136
def observations(): """Example observation list for testing.""" datastore = DataStore.from_dir("$GAMMAPY_DATA/cta-1dc/index/gps") return datastore.get_observations([111630])
d23949f5c6b1a439a723b52275ddf7cb261675ad
70,137
def getCIDsFromAID(AID, usepost=True): """ Return a list of pubchem cids that correspond to an AID. @param AID The AID to search on. @param usepost Boolean value indicating whether post or get should be used. """ if usepost: url = PROLOG + "/assay/aid/cids/TXT" payload = {'aid':AID} response =...
4c3642b7048b7525f62f79434745fe6697bddd0a
70,138
def check_worker_lookup_response(response, operator, value): """ This function will verifies the worker lookup response """ if env['proxy_mode']: if operator(response[0], value): err_cd = 0 else: err_cd = 1 else: if operator(response["result"]["totalCo...
37e64cb71c5d0ab51d787db94619f048491c83b8
70,139
def create_unsubscription_list(correls, options): """ unsubscribe list including correlations """ subscriptions = blpapi.SubscriptionList() for ticker, correlid in correls.items(): subscriptions.add(ticker, options.fields, options.options, correlid) return subscriptions
66083db52f0c54c17e10d897ccacf351a32421d5
70,140
def connect(): """ :return: """ return psycopg2.connect("dbname=forum")
35674dd904cab4539d0bd0089b55e8935986b95a
70,141
import sys import termios import tty def getch(): """ Fetches a single character from stdin. If EOF is encountered then it is replaced with 'q'. """ # https://stackoverflow.com/questions/510357 fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.std...
023136a4c4ebbb4a6a1f5a328ec8dee72f756597
70,142
def find_edge_distance(model, src_anchor_index, dest_anchor_index): """ Find the distance of the variables commonly shared between two anchors. The distance is assumed to be Euclidean. Parameters: ----------- model : Model() The model object containing the relevant anchors. src_...
dbb5611f98dc1a08cc07b922a5b1e62915c85d2a
70,143
import numpy def get_signal_to_fluctuation_noise_ratio(signal_array, tfn_array, roi_size=10): """ The SFNR image is is obtained by dividing, voxel by voxel, the mean fMRI signal image by the temporal fluctuation image. A 21 x 21 voxel ROI, placed in the center of...
4240adee5062b7a1302f010c92b91ed272287df7
70,144
def insert(rcd, insert_at_junctions, genotype): """ Given the genotype (ie the junction that was chosen), returns the corresponding insert """ junctions = ["x", "y", "z"] if genotype[1] != "-": j = junctions.index(genotype[1]) return insert_at_junctions[j] else: return "-...
1bf3d7e8bb84659c3992e55fc51490c19701cff0
70,145
def checkout(skus: str) -> int: """ Arguments: -------------- skus: str A string of all skus in the basket Returns: -------------- @return: int total value of all items in the basket. It will be an int and not a float since the price of every item is a whole number ...
91eb966990534f46d9e72b51695da1b7587021ab
70,146
def nc_domegazetadzeta(Surfs, Surfs_star): """ Produces a list of derivative matrix d(omaga x zeta)/dzeta, where omega is the rotation speed of the A FoR, ASSUMING constant panel norm. Each list is such that: - the ii-th element is associated to the ii-th bound surface collocation point, an...
d979d8418e02195339c67a25fd7a126901e8b3d2
70,147
import torch def fp16_compress_hook(process_group: object, bucket: dist._GradBucket): """ This DDP communication hook implements a simple gradient compression approach that converts ``GradBucket`` tensors whose type is assumed to be ``torch.float32`` to half-precision floating point format...
5e2ad4afaff402cc97d9604effac6229dc6985bb
70,148
def clone_model(model, **kwargs): """Clone an arbitrary sqlalchemy model object without its primary key values.""" table = model.__table__ non_pk_columns = [k for k in table.columns.keys() if k not in table.primary_key] data = {c: getattr(model, c) for c in non_pk_columns} data.update(kwargs) ...
5aa3efe0d508390a7f4ec6f22c0d4ffbfe3f04b5
70,149
import networkx as nx def nodes_class(graph, nodeslist): """ Classify nodes in the graph network with reference to nodeslist. From the list of nodes in arg nodelist, verify if these nods are part of the network in arg graph. If they are, and attribute "type" is set as "internal". Otherwise, the attr...
aa1380116cf9b6b6ed457429099a9946ac1d35fb
70,150
def redistribute_data( old_dist, new_dist, shared_manager, detdata_manager, intervals_manager, times=None ): """Helper function to redistribute data in an observation. Given the old and new data distributions, redistribute all objects in the shared, detdata, and intervals manager objects. The input ma...
0bcd67f9f9ff85b63f11b34e99c4357b60df6568
70,151
import sys import io import ast import traceback def demo_callback(controller: Controller, command: str) -> str: """Parse and execute the command.""" if command == 'exit': pygame.quit() sys.exit(0) output_buffer = io.StringIO() if command == 'help': print("Commands:", file=outp...
604a876b6564895730e669b41576ee0891840bd4
70,152
import os from datetime import datetime def get_modification_date(filename): """ http://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python E.g. print(modification_date('/var/log/syslog')) >>> 2009-10-06 10:50:01 Args: filename: Returns: ...
a4a03604123d71b5f1bc82fefefa87f834f4a27e
70,153
import os import fnmatch def gpcp_filelist(parent_directory, variable='precip', start='1999-01-01', end='2019-12-31', freq='D'): """ Create list of daily GPCP Version 2.3 Combined Precipitation Data Set files. https://www.ncei.noaa.gov/data/global-precipitation-climatology-project-gpcp-daily/access/ ...
358a5dc91109613e83caf08fae21477f8297a9f3
70,154
def Search(request): """ Searching for phones or by manufacturer name is handled via post requests sent to this view. """ searchString = request.POST["searchString"].lower() if "manufacture" in request.POST.keys(): if searchString: return redirect(Manufacturer, manufacturer = searchString) else: return...
e26334f8f2cd2a7700fcb421e9ba789fcf5ce3e7
70,155
def within_discussion_comment_and_user_anonymization(comment_gen, extract_comment_name, extract_user_name, anonymous_coward_name): """ Reads all distinct...
a3ccdaff147a14ce966d942ca958ecfe9723a131
70,156
def all_conditionals(results,prior_correct): """For each class, prob of results given that class.""" cond_probs = [prob_results_given_c(results,c,prior_correct) for c in range(len(results))] assert np.sum(cond_probs) < 1.01 return np.array(cond_probs)
cd7ac1ba2ce05c175a255cb24e7fbf0a08d4b662
70,157
from typing import Tuple def restart_seek( point: Tuple[float, float], world_state: Tuple[rc.WorldState] ) -> float: """ func to find a point to move to robot "most open" @ point found by optimizer """ cost = 0 pt = np.array(point) ball_pos = world_state.ball.pos # hard constraint ...
4eeb4ca9975fe58549c8ceee520ae4a53e3a2f2e
70,158
def resize(file_paths): """ Resize the list of images in the file_path :param file_paths: a file_path with the .jpeg images :return: np array of resized images """ image_list = [] for image in file_paths: image_list.append(cv2.resize(cv2.imread(image), (128, 128))) return np.arra...
7648ead15a61b1ab48b0b8b29086751c3597d216
70,159
def __process_sample(nbins, i): """ A helper function for the multiprocessing of kappamode.out files Args: nbins (int): Number of bins used in the GPUMD simulation i (int): The current sample from a run to analyze Returns: np.ndarray: A 2D array of each...
022dac2231115d3738c6e7ceef8df313b5620127
70,160
def autoclose_stream(f): """Decorator to close gRPC stream. Args: f (func): The function to decorate Returns: wrapper: wrapper of the decorator """ def wrapper(*args): """Wrapper function, checks context state to close stream. Args: *args (list): All a...
3f5dda42f4d9c1467c3d84e0adf18112d9a261a7
70,161
def maskPeaks(df, peaks, width): """df is the dataframe to mask rows peaks are the row indices width is the extent to mask around each row in peaks""" e = extendMaskArray(peaks, width) # make sure no values are outside the row count (although pandas would not care f = pd.Series(e.values[(e>=0) &...
401af9594f3756284ffad5a967a9512acbd75e07
70,162
def _convert_labels_for_svm(y): """ Convert labels from {0, 1} to {-1, 1} """ return 2.*y - 1.0
eca685bea6fd991245a299999fcbe31cd3b1a9ad
70,163
def test_xlabel(dash_threaded): """Test that xlabel displays as set via UI.""" def assert_callback(p_value, nclicks, input_value): answer = '' if nclicks is not None: if input_value == p_value: answer = 'PASSED' return answer template_test_python_compone...
eb1d8451852ccf3537858203a7ba27594df7a852
70,164
def get_rasterio_crs_object(crs_string: str) -> rs.crs.CRS: """ Returns a valid rasterio CRS object from given EPSG, ESRI, PROJ4, or WKT string """ err_string = (f'Rasterio: {crs_string} is an invalid crs!\n' 'Choose a valid EPSG, ESRI, PROJ4, or WKT string') try: proj_crs = CR...
825c7b2d1f6716b53c7ab3130b28e684618ad432
70,165
def E_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, t, current=1., length=1., orientation='X', kappa=0., epsr=1.): """ Computing the analytic electric fields (E) from an electrical dipole in a wholespace - You have the option of computing E for multiple times at a single reciever location ...
f8d4581aacc62556c7cfd7581a394eaad751c0cb
70,166
from typing import List def not_statement(args: List, node): """Evaluate (< a b) as {a < b}""" if len(args) != 1: evaluator.error("(special_forms.control_statements.not) 1 parameter expected, {} given".format(len(args)), node) return evaluator.evaluate_node(args[0]) in FALSE_STATEMENTS
6cfedca03846d53a215d40a644595b3f3bd51367
70,167
def lookup_drop(curve): """ TODO """ load = curve[:, 1] diff = np.diff(load) maxx = np.max(load) idx = np.where(diff < -maxx/3) if len(idx[0]) == 0: ii = -2 else: ii = idx[0][0] #print(load.shape, diff.shape) #print(idx[0]) fail_point = curve[ii+1, 0] ...
934b84a248e6bc76a2796a99d43fc0d2e00acef2
70,168
def scrabble_word(word: str) -> str: """ Randomly reorders all but the first and the last letters in a word Parameters: word(str): the word to scrabble Returns: str: the word with randomly reordered all but the first and the last letters Examples: >>...
8bb025c29b361419ec8bb68c5a308510bd5d155b
70,169
def DFS(graph, start, end, path=None, paths=None): """ Depth first traversal from start to end node """ counter = 0 if path is None: path = [start] paths = [] counter += 1 else: path = path + [start] counter += 1 if start == end: paths.appen...
2d2120d426643d1f5328229056d8340ad63d8a48
70,170
def cate_query(keyword): """Return a list of business Information based on categorical keywords.""" results = session.query(*sel_all).filter(Basic_data_model.categories.ilike('%'+keyword+'%')).all() jsondata_list = [] results_list = build_metadata_list(jsondata_list,results) return jsoni...
ac5a1d200a5e8c07d371f0620a3928e6dc17338d
70,171
import numpy def rgb2hslv(r:numpy.ndarray, g:numpy.ndarray, b:numpy.ndarray): """ Convert RGB to HSLV values Parameters ---------- r, g, b : ndarray Arrays with red, green, blue channel values (any dims, must match!) Returns ------- (h, sl, l, sv, v) : tuple Hue, ...
f25148f97139315cc7e6d49fa4eacdef286c05b2
70,172
def plot_parametric(*args, **kwargs): """ Plots a 2D parametric plot. The plotting uses an adaptive algorithm which samples recursively to accurately plot the plot. The adaptive algorithm uses a random point near the midpoint of two points that has to be further sampled. Hence the same plots ca...
92beb2ea21d331ada16b1d07115d30ba1b2df61e
70,173
def user(): """ exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://.....
8419712bfeabdf18f10209158814a6fa57641b4d
70,174
def ilr( data_frame, voxmats, ilr_formula, verbose = False ): """ Image-based linear regression. This function simplifies calculating p-values from linear models in which there is a similar formula that is applied many times with a change in image-based predictors. Image-based variables are st...
aaa5abd2ae3d072842f6764bc5bcf5ed9b5c9159
70,175
import platform import ctypes import os def freespace(): """ Return folder/drive free space (in bytes) """ if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(folder), None, ...
8108b9cdd6f4de13e8acee15d4f44690e57f5e81
70,176
import math def chunks(l, n): """Divide l into n approximately-even chunks.""" chunksize = int(math.ceil(len(l) / n)) return [l[i:i + chunksize] for i in range(0, len(l), chunksize)]
c7b395dec7939b863097b3da9cdd49fbe2a47740
70,177
from typing import Callable from typing import Any from typing import Tuple from typing import Mapping import logging import collections import time def _run_training(training_fn: computation_base.Computation, client_selection_fn: Callable[[int], Any], state: Any, round_num: int) -...
8ff9c15efc117c3d9fb25bdd88ecc7702bd1ed8e
70,178
def camp_sweeps_by_time(request): """ Number of camp sweeps by time. Optional query parameters are: Query params: timeframe options: 'month', 'week' default: 'week' """ timeframe = request.query_params.get('timeframe', 'week').lower() if timeframe not in ('week', 'month'): msg ...
b1fc73333bb528ab58ebb01c867211e7fc9d673c
70,179
import sys def main(): """ Main routine """ if sys.argv[1].startswith("-"): executable = "dogecoind" else: executable = sys.argv.pop(1) #Container running arbitrary commands unrelated to dogecoin if executable not in CLI_EXECUTABLES: return execute(executable, sys....
e1760c0db76b277ecab44e250fc582593f046ff8
70,180
def filter_by_recovery(dividends): """ Takes a dataframe and returns those stock symbols who have historically recovered well after dividend distributions :param dividends: :return: """ # TODO: Write this entire method; return dividends
a69f4853decc675128265bd22b25760d8f8158fc
70,181
import torch def vec_ans_index_buffered_encoder(symbols, indices, cdf, cdf_length, cdf_offset, precision, coding_shape, overflow_width=OVERFLOW_WIDTH, **kwargs): """ Vectorized version of `ans_index_encoder`. Incurs constant bit overhead, but is faster. ANS-encodes unbounded integer data using ...
4aef22a40a612b037fed7c4acd92f5c546349b4b
70,182
def file_picker(): """shows a file picker for selecting a postQC.tsv file. Returns None on Cancel.""" chooser = sg.Window('Choose file', [ [sg.Text('Filename')], [sg.Input(), sg.FileBrowse(key='-FILE-', file_types=(('PostQC TSV files', '*.postQC.tsv'),))], [sg.OK(), sg.Cancel()]], icon=i...
5e052974ac775cd0dcd622df419040a8561ceeca
70,183
def slide_selection(request, course_id): """ Teacher form for adding slide(s) to a course """ course = get_object_or_404(Course, id=course_id) slidesInCourse = [slide for slide in course.slide.all()] # Filter slides by tags filteredSlides = Slide.objects.all() organs = request.GET.getl...
b836bc3b43d3c3ca47d14ac81522b4516cb5eb5d
70,184
def calcPptm(freq, T): """ payment time to maturity """ return freq * T
82c9935494ba32e9f990bdcd87ff86dc34ce7232
70,185
def ternary_decoder(encoded_data, scaler, shape): """Decoding the signs to float format """ a = tf.cast(encoded_data, tf.int32) a_split1 = tf.mod(a,4) a_split2 = tf.to_int32(tf.mod(a/4,4)) a_split3 = tf.to_int32(tf.mod(a/16,4)) a_split4 = tf.to_int32(tf.mod(a/64,4)) a = tf.concat([a_split1, a_split2, a_sp...
f8c72fba26eb1c9fa0813670279fc8e3b7c3a3ed
70,186
import re def filter_single(error_dictionary, error, regex_pat, sub_sym): """Filter_single filters errors wrapped in single quotes. Ideally all errors should have this simple format from the json log""" if len(error) == 2: error_dictionary["error"] = "_NULL_" error_dictionary["err_prefix"] = "...
97efb421bc1500b66dcb0e58aa00b183171630d8
70,187
def create_gloo_context(rank, world_size): """Create a GLOO context using GLOO APIs. Args: rank (int): the rank of this process. world_size (int): the number of processes of this collective group. Returns: context (pygloo.Context): a GLOO context. """ context = pygloo.rende...
716df295e1a9484097990d1ca1411457ea2e319f
70,188
def npl_api_root(request, format=None): """ Returns a list of all active API endpoints for EBA Template Data """ data = [ {'EBA Template Endpoints': [ {'npl_counterparty_group': reverse('npl_counterparty_group_api', request=request, format=format)}, ...
c48917a118d7226468979a8086dc325139a62e4e
70,189
def permutation_test(function, x, y=None, n_perm=500, alpha=0.02, seed=0, n_jobs=-1, **function_params): """ Permutation test. :param function: of the form func(x) -> float, or func(x,y) -> : eg. rs.spearman, np.mean_fr_map## :param x: array. first variable :param y: array. second variable (must be ...
ec293d19fd8fda5511986d50929304df79cfa35d
70,190
import select def lambda_stmt_and_join_attributes( schema_version: int, no_attributes: bool, include_last_changed: bool = True ) -> tuple[StatementLambdaElement, bool]: """Return the lambda_stmt and if StateAttributes should be joined. Because these are lambda_stmt the values inside the lambdas need ...
dfa0cacce8f25ce68e2d244d4d015a4328802371
70,191
import os def load_hparams_for_evaluation(pre_config_file, cmd_args=None): """ load hparams for evaluation. priority(file_args) > priority(cmd_args) unless arg in allowed_to_change set. """ allowed_to_change = ['model_dir', 'eval_episode', 'game_episode_terminal_t'] deps_to_change = ['dat...
7ef4aa76b469b028f0c6a8793867c9d075fe5d46
70,192
import torch def Swish(): """ out = x * sigmoid(x) """ return Expression(lambda x: x * torch.sigmoid(x))
b494cb91790dd611df740ee8b72aead0b0c97228
70,193
from typing import Optional from typing import Callable def build_gradient_clipper(config: dict) -> Optional[Callable]: """ Define the function for gradient clipping as specified in configuration. If not specified, returns None. Current options: - "clip_grad_val": clip the gradients if they e...
6df45246f47de0861baf0b6399c97147e893a642
70,194
def commute(): """Return sample OBD-II commuting data. Returns ------- table: :class:`toyplot.data.Table` Table containing a stream of OBD-II data collected from an automobile during a morning commute. """ return read_csv(commute.path)
85965417d25a6f4af27bffdee9b6c2a165bcb9d0
70,195
def is_namespace_absolute(ns: Text) -> bool: """Return `True` if `ns` is absolute.""" return ns.startswith('/')
58fc833fff1dead31b0bf6888c14174de8bf2e8e
70,196
import re def isXML(file): """Return true if the file has the .xml extension.""" return re.search("\.xml$", file) != None
7fcfbb105a59f7ed6b14aa8aa183aae3fdbe082d
70,197
def abs(n): """ this is abs function example: >>> abs(1) 1 >>> abs(-1) 1 >>> abs(0) 0 """ return n if n>=0 else (-n)
0e2c42526deca4658e65cbe6c9954e88cb5d9ff6
70,198
def all_seasons(): """ Returns all seasons of weeks w/ start & end dates """ return nfl.seasonsdata.SEASONS
6622771a6785c191ecd9af8a6d60d2946eee8a16
70,199