content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_model_names(model='all'): """ Returns all available model names as a list of strings. Parameters ---------- models: str OPTIONAL. Default value is 'all' in which case all keys in default_models are returned. If 'mixed' is passed, only the MixedFluid model names are return...
9ebf63306e298877c64fc80ce82e54381e005764
59,600
from operator import add from typing import Concatenate def compile_bigrus_attention(shape, n_hidden_layers, hidden_units_size, dropout_rate, word_dropout_rate, lr, mode): """ Compiles a BiGRU based on the given parameters :param mode: Depending on your choice : ['Single Task', 'Multi Task-1', 'Multi Task...
e3e8b1ca514e1dbb6c93e5f933aa19d8c9f48953
59,601
def get_dom_attr_value(dom, tag_name, attr_name): """ Return value of a tag's attribute from dom (XML file). Arguments: tag_name -- name of dom tag in which the attribute is found. attr_name -- name of dom attribute for which the value should be returned. """ tag=dom.getElementsByTag...
26f31fd7db526bb5503b7ce156b19a99705041d1
59,602
def render_xml(request, template, context=None, **kwargs): """Safely renders xml, stripping out nasty control characters.""" if context is None: context = {} rendered = render_xml_to_string(request, template, context) if 'content_type' not in kwargs: kwargs['content_type'] = 'text/xml' ...
5212ce2a41bb5a968d85f1e70d4b200866d46897
59,603
from pathlib import Path def read_camera_intrinsics(settings_path: Path) -> CameraIntrinsics: """ Read the camera intrinsics from file :param settings_path: The path to the camera settings file, output by the NDDS exporter :return: """ camera_settings = read_json(settings_path) return Came...
3a4745818c71357e6fe2d1f207f40a2ad42b0321
59,604
def share_server_get(context, id, session=None): """Get share server DB record by ID.""" return IMPL.share_server_get(context, id, session=session)
e7ba5854d72687c1c791bc2ddcd1edd1ca8086a4
59,605
def get_profile_for_plotting(equilibrium_list): """ List of symmetric equilibrium :param equilibrium_list: :return: Representative profile. """ selected_profile = None sample_team = 0 strategy_of_interest = simmodel.SIMPLE_INFLATE_STRATEGY for profile in equilibrium_list: ...
f07547821c5e92e7596d5474da6b736b29b3c306
59,606
def _hermite_moment_nonlinear(u,mu,sigma,mu3,mu4,fisher=True): """ Hermite moment models for nonlinear responses """ if fisher: mu4 = mu4 + 3 if mu4 > 3 : h3 = mu3/6 h4 = (mu4-3)/24 c4 = (np.sqrt(1+36*h4)-1)/18 c3 = h3/(1+6*c4) k = 1/(np.sqrt(1+2*c3...
c93b116c23066a21f68ac47ac051410540259dd4
59,607
def fmeasure(confusion_matrix): """Compute the f-measure of the linkage. The f-measure is calculated as: 2 * (precision * recall) / (precision + recall). Parameter Description: confusion_matrix : The matrix with TP, FP, FN, TN values. The method returns a float value. """ ...
c148f52952d5d5a71c6880dc5777e83eaac1f5f8
59,608
def probability_of_category_A(stimulus_i, category_a_exemplars, category_b_exemplars, w, c, r, alpha, b): """ Function that calculates the probability of stimulus_i belonging to category A. Note that this assumes there are only two categories in total, which is typical of categorization experiments (equatio...
33eb4c7b105f310e43d2b55ae0221e01e56b9390
59,609
def role_list(auth=None, **kwargs): """ List roles CLI Example: .. code-block:: bash salt '*' keystoneng.role_list salt '*' keystoneng.role_list domain_id=b62e76fbeeff4e8fb77073f591cf211e """ cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return clou...
90bfa586af63155eb298138eb9007df38aaefd77
59,610
def Inv_UpSample(name, x, scale=False, reverse=False): """ Upsample the given inputs by factor 2x2, but will decrease the channel num by factor of 4, such that the overall number of units remains unchanged :param name: name scope :param x: given inputs, [NHWC] :param scale: if true, scale the sp...
472267e1be3c596f5c4dffb49b3ed66f21f19ad5
59,611
def collide(Aleft, Aright, Bleft, Bright): """ optimised for speed. """ # quickest rejections first; if Aright < Bleft: return(False) if Aleft > Bright: return(False) if Aleft == Bleft: return(1) # I have to cheat here otherwise it returns 0 which will evaluate as False; ...
d66afddce5f7a464446d598d948cc74c0d97a70a
59,612
def wendlingModel_2(y, P, h = 1./512, u = np.zeros(1), couplIntra = 0, couplInter = 0 ): """ Modified Wendling's neural mass model ODEs y: last state P: model parameters h: step (1/Fs) u: stimulation input - 2 elements u[0] voltage deflection to all cells. u[1] sums the stimulus to the model input ...
79c409da2692f21c3ccb0e081d25926d0de30b7b
59,613
def construct_graphql_query(dict_object, queryDict=None, key="query"): """ {"name": "wallet", "key": "username", "fields": ["owner", "upcoming_earnings", {'name': "transactions", 'key': None, "fields": ["display", "type"] }]} :returns query{ wallet(username:""){ ...
27af54cc6f10e57cc9e6d98dc0816f51d82dd103
59,614
import shutil def delete_directory(path): """ Deletes a ticket attachments directory from disk """ path = '{}/{}'.format(settings.MEDIA_ROOT, path) try: shutil.rmtree(path) return path except: return False
42b06b7eb563cfea86409afd85df2964c69dad15
59,615
def sort_SMILES_list_by_MW(SMILES_list): """ sort smiles by molecular weight """ if len(SMILES_list) == 0: return [-1] mw_list = [calc_MW_from_SMILES_list(i) for i in SMILES_list] dataset = (list(zip(mw_list, SMILES_list))) dataset.sort(key=lambda x: x[0]) mw_list, SMILES_list =...
bc21a370c767b849978882882bdd0641b0f702e2
59,616
from typing import Tuple def fetch_dbt_data(dbt: DbtCloud) -> Tuple[dict, dict]: """call dbt api for all latest runs and jobs Args: dbt (DbtCloud): dbt cloud api instance Returns: Tuple[dict, dict]: dict of both runs and jobs """ all_runs = get_all_runs(dbt) all_jobs = get_al...
a832fdcc7083e106da6f92dbabb71906cb64968d
59,617
from typing import List import ray import random def run_wrk_on_all_nodes(trial_length: str, num_connections: int, http_host: str, http_port: str, all_endpoints: List[str] = None): """ Use ray task to run one w...
48c95de8ec87d789b984925a81914db28167fe98
59,618
def plaintext(): """Test 6: Plaintext""" return b"Hello, World!", {"Content-Type": "text/plain"}
8005ee608a45956d5aa9fc4edf34c9ee3c8605d6
59,619
def get_simbad_names(name, verbose=False): """ Get list of alternate names from Simbad Parameters ---------- name : str Name to resolve verbose : bool Verbosity flag Returns ------- List of names """ t = Simbad.query_objectids(name) if t is not None and...
6d0518f75d21891792b9820f9654e73261d3b384
59,620
def logout_view(request): """Logging off the user :param request: Django's HTTP Request object :return: Redirect to homepage """ logout(request) return redirect("homepage")
ad11a78c918f89b199f62f371fa40be2b5c9d153
59,621
import os def save_path(filename): """Save path of last opened file""" if len(filename) > 1: fp = open(config_path + '\\path.txt', 'w') path, fname = os.path.split(filename) fp.write(path) fp.close() else: path = '.' return path
7a4bd7c7608fe8cd7b30cdfd207f61d033a9204b
59,622
import re def generate_stencil(pcb_footprints, config): # type: (list, Config) -> dict """ Generate BOM from pcb layout. :param pcb_footprints: list of footprints on the pcb :param config: Config object :param extra_data: Extra fields data :return: dict of BOM tables (qty, value, footprint...
493386d3a4bcb8b4184bd027d9e43da01b4954e3
59,623
def inspect_calibration_surface(df, param_zf, microns_per_pixel): """ To run: dict_fit_plane, fig_xy, fig_xyz, fig_plane = correct.inspect_calibration_surface(df, param_zf, microns_per_pixel) :param df: :param param_zf: :param microns_per_pixel: :return: """ if 'x' not in df.column...
90aec909eb00aa06d879e34fbf72bb2e19c38fa8
59,624
import subprocess import warnings def execute(*args, **kwargs): """Run an executable, but suppress its output.""" try: return subprocess.run(*args, check=True, stdout=subprocess.DEVNULL, **kwargs) except FileNotFoundError: warnings.warn( "{} not in path, skipping".format(args[0...
76db362ff75b597a8be3d512c890583502d17f0f
59,625
def check_inside_points(points, cur_boxes): """ points: [num, n] cur_boxes: [m 7] return: [num, m] """ # first cast points to second format points = points.copy() cur_boxes = cur_boxes.copy() points_xyz = points[:, :3] points_xyz = points_xyz[:, [0, 2, 1]] cur_boxes = cur_bo...
d458c067bbf87e8b5f2a53e7284f548db093ee60
59,626
def data_route(): """`/data/` endpoint handler""" filename = get_filename(request) path = request.args.get("path") selection = request.args.get("selection") format_arg = request.args.get("format") flatten = parse_bool_arg(request.args.get("flatten"), fallback=False) with h5py.File(filename,...
8f9304d0efc045660dead59ef983e2b2ab6ca801
59,627
def drop_voxels_with_mean_negative_amplitudes(df): """drop all voxels that have an average negative amplitude (across stimuli) """ groupby_col = ['voxel'] if 'indicator' in df.columns: groupby_col += ['indicator'] try: # in this case, we have the full dataframe (with each bootstrap ...
2799c866b411ff0e63cdcc4b28adf3bde9595f4e
59,628
def categorical_focal_ignoring_last_label(alpha=0.25,gamma=2): """ Focal loss implementation Variables: weights: numpy array of shape (C,) where C is the number of classes Usage: weights = np.array([0.5,2,10]) # Class one at 0.5, class 2 twice the normal weights, class 3 10x. ...
bf93ffb8dbadee85756c8e9204e809917b409f94
59,629
def split_peaks(prot_arr, pr, skp=0): """ split peaks in n samples giving skp fractions of window returns 'right_bases': array([32]), 'left_bases': array([7]) """ peaks = list(st.peak_picking(prot_arr)) left_bases = peaks[1]["left_bases"] right_bases = peaks[1]["right_bases"] fr_peak...
47dc06e53d46e146e42116274473f46e0c2f0dac
59,630
from typing import List def download_media( client: pyrogram.client.client.Client, chat_id: str, last_read_message_id: int, media_types: List[str], ) -> int: """Download media from Telegram. Parameters ---------- client: pyrogram.client.client.Client Client to interact with Te...
1171043981ac8fb4e25dfbaa5c74c1f72d728d1f
59,631
import re def follow_directions(starting_point, starting_orientation, *directions): """Given a starting point, starting orientation and a list of directions of the form DN, where D is R (right) or L (left) and N is an integer, return the ending point and orientation.""" point = starting_point ...
5d276bd25a317e1051c56596df7e165a6dc39593
59,632
from . import routes def create_app(): """ create and return the flask application """ app = Flask(__name__) # pylint: disable=import-outside-toplevel app.register_blueprint(routes.bp) return app
d751ba54c1ad4f60abb0a452aad7e428ac2a7bb6
59,633
from .pb import test_pb2 from .pb import test_pb2_grpc import random import string def test_mock_stream_stream_call(import_path): """Test Bidirectional Streaming gRpc Call""" class TestServicer(test_pb2_grpc.GRPCTestServicer): _server_id = random.randint(2, 2 ** 10) def BidirectionalStreami...
ab10c22a2b186a9defd551550933ef17923640d0
59,634
def flip_y(prob=0.8): """ Construct a transformation randomly containing X/Y flips (or not). Args flip_x_chance: The chance that the result will contain a flip along the X axis. flip_y_chance: The chance that the result will contain a flip along the Y axis. Returns a homogeneous...
381ed2efde5e7e8e6d44adeea3a2006daa539222
59,635
def column_stats(collection, column, stats_type): """Aggregates over a given property of the objects in a collection, calculating the sum, min, max, mean, sample standard deviation, sample variance, total standard deviation and total variance of the selected property. Args: collection (FeatureColl...
c4792043d44b0f6d23c843d0df6dde9603c1d426
59,636
import os import json def read_data(directory): """ Read the data and associated files from the data directory and return it in the form of arrays args: directory: The data directory specified by FLAGS.data_dir """ if not os.path.exists(FLAGS.logs_dir+FLAGS.config_id+'/'): ...
3228b47d8214dad4f78c21961cccc18250c81f0c
59,637
def EGCD(a, b): """ Extended Euclidean algorithm computes common divisor of integers a and b. a * x + b * y = gcd(a, b) returns gcd, x, y or gcd, y, x. Sorry, I can't remember """ if a == 0: return (b, 0, 1) else: b_div_a, b_mod_a = divmod(b, a) ...
81a9365bfe2b82f0856489710afb7186d1fcf803
59,638
def _get_module(module: Module, name: str) -> Module: """Recursively get a sub-module from a module. Args: module: A `torch.nn.Module`. name: The name of the submodule to return, in the form of a period-delinated string: `sub_module.subsub_module.[...].leaf_module`. Returns: ...
913f9920c9079aa2d746d8e61469611181664f9f
59,639
from typing import List import os def get_topologies(scenario: str) -> List[str]: """Get topology list of specified built-in scenario name. Args: scenario(str): Built-in scenario name. Return: List[str]: List of topology name. """ scenario_topology_root = f'{scenarios_root_folder...
dc697ce159c9db4a15355bcfd7957730bb2a9b0f
59,640
import html def description_card(): """ :return: A Div containing dashboard title & descriptions for tab 1. """ return html.Div( id="description-card", children = [ html.H3("Welcome to CZviz"), dcc.Markdown('''This app allows you to explore the full dataset and ...
5a2a2d0c042fa408c10bc0e0f86f0ec63a06828e
59,641
import csv def np_float_array_from_file(data_file, delimiter=" ", header=False, gather_hist=False): """ Adds to the basic np.loadtxt by performing data checks. @param data_file: file expected to have space-separated values, with the same number of entries per row @param delimiter: default is a space-s...
0a48de03974f425677425d61e89433011387b5c0
59,642
def _evaluate(p_eval_step, params, eval_batch): """Computes evaluation metrics. Args: p_eval_step: Parallelized evaluation step computation. params: Model state. eval_batch: Batch of evaluation examples. Returns: Raw model predictions and metrics. """ n_devices_per_host = jax.l...
11d17ec8bedcd3cbfacf7e6cc12fef5a4f95221c
59,643
def _assemble_frequencies(animal_obj, start_time, end_time): """ Converts the coordinates of the animal trajectory into frequency data over the grid. Gathers the frequency data for approximating the heatmap representing the amount of time an animal spent in each location over a specified time interval. ...
1e4fe463e49bafb91f7e95088c12c3580313d66d
59,644
import argparse def parse_command_line(argv): """ Parse command line arguments. See the -h option. Args: argv (str): Command line arguments, including caller filename. Returns: dict: Dictionary of command line arguments and their parsed values. """ parser = argparse.Argument...
a05422b71605356e22be53c4b0fc2fcafcc9ec85
59,645
def compute_ood_logsums( choosers, logsum_settings, nest_spec, logsum_spec, od_skims, locals_dict, chunk_size, trace_label): """ Compute one (of two) out-of-direction logsums for destination alternatives Will either be trip_origin -> alt_dest or alt_d...
7d8edd8ee79ac2e06ddbaf9f09ea801e3f61eed8
59,646
def view_profile(request, username=None): """ Display profile info, such as snippets, tags, and followed users """ #Set current user and check if it's my profile if username is None or username == request.user.username: user = request.user my_profile = True else: user = get_obje...
ec2e4b296dc01bf46e59983af84d658b6e058536
59,647
def filter_attr(the_dict, attr_names): """ Only return the item that in the attr_names list :param the_dict: :param attr_names: comma separated names :return: dict """ if isinstance(the_dict, dict): attrs = attr_names.split(',') return dict((k, v) for k, v in the_dict.items...
1ca5ad38af808c6a533c3abb22ce7cc26d5f82f2
59,648
def _GetFlagMetavar(flag, metavar=None, name=None, markdown=False): """Returns a usage-separator + metavar for flag.""" if metavar is None: metavar = flag.metavar or flag.dest.upper() separator = '=' if name and name.startswith('--') else ' ' if isinstance(flag.type, arg_parsers.ArgList): metavar = flag...
e8fef13fa12ea47b41ec5328dba7efb56991e9e9
59,649
def getTempDirectory(rootDir=None): """ returns a temporary directory that must be manually deleted """ if rootDir is None: return tempfile.mkdtemp() else: while True: rootDir = os.path.join(rootDir, "tmp_" + getRandomAlphaNumericString()) if not os.path.exist...
d29ff7d01fd24e5281f33d9d94b5d413c52cf47b
59,650
def test_single_for_builtin_function_numpy_sum(): """ Feature: JIT Fallback Description: Test fallback with control flow. Expectation: No exception. """ @ms_function def control_flow_for(): x = np.array([1, 3, 5, 7, 9]) y = np.array([0, 2, 4, 6, 8]) result = x ...
5801d02abed47cd65d33e12056717eaabe90ab64
59,651
from typing import Optional import re def get_default_branch_from_remote( remote: str, ) -> Optional[str]: """ Get default branch from remote. :param remote: the remote name :return: the default branch, or None if it failed """ # https://stackoverflow.com/questions/28666357/git-how-to-get...
c18e20cdd5d861dc324296761c71bb5d4416e471
59,652
import re def oerp_get_ids_from_order(po_id, oerp): """ Fetches the product IDs of a purchase order :param po_id: The openERP purchase order ID :param oerp: the openERP lib instance :return: an array containing the openERP product IDs of a purchase """ po_id = int(po_id.lower().replace("po...
88b87ed35317818f7d3bc3d693cd025385734756
59,653
def form_update_node(user, handle_id, form, property_keys=None): """ Take a node, a form and the property keys that should be used to fill the node if the property keys are omitted the form.base_fields will be used. Returns True if all non-empty properties where added. """ meta_fields = ['relati...
1f1d33cd18bc6f1f186114f038065fe0518a93ca
59,654
import zlib def decompress_zip(data, # type: bytes shape, # type: Tuple[int, int] depth, # type: int version # type: int ): # type: (...) -> np.ndarray """ Decompress zip (zlib) encoded data. {} """ data = zlib....
3cd7d24287a8c6991de4997d83108b16251c0491
59,655
def add_user_key(request, **kwargs): """ Create a new User API key. Requires a name and a readonly boolean. """ user = request.user name = request.POST.get("name") readonly = convert_to_bool(request.POST.get("readonly")) api_key, key = UserAPIKey.objects.create_key( name=name,...
500512fa5f336f5d6f0aae44312ab1621005bd57
59,656
def find_neighbors_for_1D(cog, target_res, max_codon_dist=3): """ Overloaded version of find neighbors 1D that allows us to find the neighbors of only the residues we want Parameters: ----------- cog : dictionary dictionary of residue ids and their centers of geomeetry m...
69cf517735ca18c2f442e457ad7d59f0a33db768
59,657
def batch_norm_relu(inputs, is_training): """Performs a batch normalization followed by a ReLU.""" _BATCH_NORM_DECAY = 0.997 _BATCH_NORM_EPSILON = 1e-5 axis = 1 # Workaround because there is currently no NCHW fused BN on CPU if not tf.test.is_built_with_cuda(): inputs = tf.transpose(inpu...
aeca62585c5b53f50d82e087530228629252d1ef
59,658
import os import errno def find_file_in_path(filename, search_path) : """General utility to search for a file name in a path :param str filename: name of the file to locate, absolute path ignores search_path :param list(str) search_path: list of directories where the files may be located """ # o...
68d4cfc693357e9cdb8949dec66fcc121d4467ec
59,659
def decode_soft_encoding_batch_rgb(x_batch, y_batch, q_ab, epsilon = 1e-8, T = 0.38, x_post_fn = None, version = 0, usegpu = False, **kwargs): """ q_ab = np.load(os.path.join(module_dir, "data", "pts_in_hull.npy").replace("\\", "/")) x_batch: L channel (batchsize, height, width, 1), (height, width) --> gray...
93a24748166047a3a9748715f46ed995975bd0a1
59,660
import torch def word_to_one_hot(word, word2idx): """Return the one hot encoding of the word given to this function. Args: word (str): The word for which one hot representation is required. word2idx (Dict): The dictionary mapping from word to indices. Returns: x (torch.Tensor): The on...
6628f25695cacb202dd51be070ff03f9a594654d
59,661
def dcopy(x): """ Returns a deep copy of an array. Parameters ---------- x: array-like The array to create a deep copy of. Returns ------- array-like: The deep copy of the input. """ backend = getBackend(x) if backend == 'numpy': return x.copy() ...
4a7cc6da52c6c3f7fc106c38524adfe3735a5806
59,662
def dhcp_offer_packet(eth_dst='00:01:02:03:04:05', eth_src='06:07:08:09:10:11', ip_src='0.0.0.0', ip_dst='255.255.255.255', ip_len=308, ip_tos=16, ip_ecn=None, ip_dscp=None, ip_ttl=128, ...
a763f6b2303624912d8fe0d91928a310be1f2b74
59,663
def save_video_categories(regionCode: str): """儲存該國籍的主題內容 Args: regionCode (str): 國籍簡碼 Returns: [bool]: 成功或報錯 """ category = videos.get_video_category(regionCode=regionCode) if not isinstance(category, dict): return False for i in category['items']: schemas ...
2ed1d9806727ee79a3560a7d03cc8ec0782836c1
59,664
from pathlib import Path from typing import Type def parse_text_level(file_path: Path) -> LevelElements: """Parses a level layout file into `LevelElements`. Takes a file path to the level layout and converts the ASCII characters into a grid of level elements (Python objects). Args: file_path...
c3122292474520d89426c59de9969072c824f767
59,665
from typing import Container async def get_subscriber_subscriptions_handler( request: web.Request, *, subscription_service: SubscriptionService = Provide[ Container.subscription_service ], ) -> web.Response: # noqa """Handle subscriber subscriptions getting requests.""" ne...
302f3e5c2f1eb397bd0305251f5b6b1bd425f140
59,666
def primary_trefoil_y(rho, phi): """Zernike primary trefoil Y.""" return rho**3 * e.cos(3 * phi)
f9a73da106bd4979996b609981f28a481f0b84c4
59,667
def top_5_categorical_accuracy(y, y_pred): """ Return the top 5 categorical accuracy of the predictions """ return top_n_categorical_accuracy(y, y_pred, 5)
28b53e83e94489e903936740f815560c17e68c98
59,668
def get_to_do_filename(): """ Asks users to enter a filename od an existing To Do file. The user should be repeatedly prompted for a filename until a existing one is entered. Use os.path.isfile(to_do_list_file) to check if to_do_list_file exists :return: the existing To Do filename """ #...
1aa4022315736435cfc518a1b8e15c9acb160712
59,669
async def update_item(key, value): """Update an existing key.""" # Query db. result = await collection.update_one({"_id": key}, {"$set": {"value": value}}) if result.matched_count: return result.raw_result else: raise HTTPException(status_code=404, detail="Item not found.")
235e981cba897cbebc00d90b012e295e7bcbc426
59,670
import base64 def deserialize(employee_str) -> Employee: """ Given an base64 encoded string parse and convert to Employee object :param employee_str: base64 encoded string :return: Employee Object """ decoded = base64.b64decode(employee_str) employee_obj = Employee() employee_obj.Parse...
1e516fbc5da575afe5ad9fe867f449ec3574a0fb
59,671
def rev_comp(seq: str) -> str: """ Generates the reverse complement of a sequence. """ comp = { "A": "T", "C": "G", "G": "C", "T": "A", "B": "N", "N": "N", "R": "N", "M": "N", "Y": "N", "S": "N", "W": "N", "K...
cb6b95d2d3f15910ff3ad793d99bb56de898026e
59,672
def strip_variables(raw_df, targ_hd): """ Some of the ncdf files do not have a <complete> collection of variables (e.g. Rnet, Qg), such that the matrices are different shapes. In order to be able to concatenate all fluxnet datasets together, this function strips out the uncommon variables. """ ...
b732faf83d5946807c6e74b13297e52ced18ff1d
59,673
def check_unique(ser : pd.Series) -> any: """Check uniquness. If duplicated, raise Error. """ l = ser.unique() if len(l) != 1: raise Exception("Duplication found", l) return(l[0])
7f5c5bef6447812f02cb0dd4c7ed6f44b37c12a6
59,674
import getpass def mm_connect(): """ Connects to a FTP-Server using the Info given in the param file USRN and PSWD can be None to interactively get the Info. THIS IS NOT SECURE and should be replaced with SFTP in the next Versions """ """ monkeypatch https://stackoverflow.com/questions/440577...
13b03ba5ad4ad1a0e9681604ac9202bd4b6096ff
59,675
import ctypes def platformDisplay(device): """Get platform display from device specifier device -- EGLDeviceEXT, gbm card* path, or gbm card* ordinal (index) returns display, created_device (or None if passed in) raises RuntimeError if we can't create the display """ created_device = dis...
2f7e807d6ef844d76c2d10fbbccb21d54007b5b6
59,676
def _parse_dsn(dsn_text,defaults): """ Convert a DSN MIME part to a dictionnary keyed by DSN fields """ res = [] for sub in dsn_text.split("\n"): if ':' in sub: res.append(map(str.strip, sub.split(':', 1))) res = dict(res) for d in defaults.keys(): if not d in re...
6637acda9c66085fce9af8eca63cbe7ad8e1a989
59,677
def find_nuc_indel(gapped_seq, indel_seq): """ This function finds the entire indel missing in from a gapped sequence compared to the indel_seqeunce. It is assumes that the sequences start with the first position of the gap. """ ref_indel = indel_seq[0] for j in range(1,len(gapped_seq)): ...
d1f258229300f965d9e6d0a8fba0a7cb6a071131
59,678
def expected_dice_game (): """Function that generates expected accumulative of dice roles in accordance to probability theory.""" def evaluateSides (list): """Function that generates a list of numbers that occur on each side of a normal dice""" # initiate loop mechani...
2c224b4d4f7ee96a643eb65f605094c1f07663c1
59,679
def data_scientists_who_like(target_interest): """Find the ids of all users who like the target interest.""" return [user_id for user_id, user_interest in interests if user_interest == target_interest]
89a2473037d1ef30830b5383d4c39b52953e70ae
59,680
from io import StringIO import traceback def serialize_known_exception(e): """ Serialize a cloudify exception into a dict :param e: A cloudify exception :return: A JSON serializable payload dict """ tb = StringIO.StringIO() traceback.print_exc(file=tb) trace_out = tb.getvalue() # ...
e0c24480373d4d4d2be99f8cd4b2b8193a1f5120
59,681
def users(): """ Convert PostHistory.xml to pandas dataframe """ parsed_xml = et.parse("../../data/raw/Users.xml") dfcols = ['Id','AccountId','CreationDate', 'Reputation','Views','UpVotes','DownVotes','LastAccessDate'] df_xml = pd.DataFrame(columns=dfcols) i=0 for node in parsed_xml.getroot(): ...
edd3e2831e9fe2286fa74fd448f10fc0c059a901
59,682
import os def get_sample_writer(name, base=".."): """Returns a tensorboard summary writer """ return SummaryWriter(log_dir=os.path.join(base, SUMMARY_WRITER_DIR_NAME, name))
19edabf3d40ed61fa66edd656e85400bfa8145bd
59,683
def echo_an(ma, ga, Lpk, dist, t_age, gamma, tpk, tt, deltaE_over_E=ct._deltaE_over_E_): """ Analytic formula for the echo spectral irradiance [Jy], with transition time as input, and assuming constant DM density. NOTE: the frequency dependence prefactor, usually (nu/nu_pivot)^-alpha, is factorized out. Pa...
fa17ef6b9d3a51b4e5a9fbf896acd29d4a76df98
59,684
def log_out(request): """Log out page. Roure for 'logout'.""" logout(request) messages.info(request, "Logged out") return redirect("login")
990c42a9b5de6a8c720f4d58d7c62ebc22a66af4
59,685
def _match_identifier_re(): """ 匹配BundleId """ return r'^Identifier:\s*([a-zA-Z0-9_\-\.]+)\s*$'
cbca0e2924e77c43211bdadba4d434c178eb8e18
59,686
from typing import Any from typing import Tuple from typing import Iterator def create_generators( df: pd.DataFrame, train: pd.DataFrame, val: pd.DataFrame, test: pd.DataFrame, plot_augmentations: Any ) -> Tuple[Iterator, Iterator, Iterator]: """Accepts four Pandas DataFrames: all your data, the training, val...
ae4619ebf9efad29dcadca56e342824320f31713
59,687
def get_stats_for_unweighted_hpo_aggregate_metric( hpo_object, metric, date, hpo_name, tables_and_classes_counted, statistics_to_average): """ Function is used once an HPO is found and warrants its own AggregateMetricForHPO because it has a unique set of date and metric parameters. ...
2b451f6fc15b9f96e343d5577626a62fd57662b7
59,688
def part2(commands): """ down X increases your aim by X units. up X decreases your aim by X units. forward X does two things: It increases your horizontal position by X units. It increases your depth by your aim multiplied by X. Calculate the horizontal position and depth you would ...
68664bc4fc708f67d4cbce121f16f273aeeffd86
59,689
def cantor_pairing(a, b): """Create an unique number from two natural numbers For more information about the Cantor pairing function, have a look at: https://en.wikipedia.org/wiki/Pairing_function This create an unique number from two natural numbers according to .. math:: \pi (a,b):={\frac{...
d8849a7c7a8497393e77f2b93e3555a09f704bf3
59,690
import functools def class_from_constructor(cls, func, **kwargs): """Creates a new class by extending the given one and using func as a constructor of the new class. Keyword arguments are passed to a metaclass.""" # For unknown reasons __doc__ attribute of type objects is # read-only, and update...
3159ff9387f2b5f7dc32ef8dc969a2266b46dd14
59,691
import os def file_writer_method (method): """Decorator for simplifying writing of files. Enables the given method to handle both filenames and file objects. The given method must take a file object as its second argument (the first argument being 'self', of course). This decorator will take a ...
947706cc61ab0386529cf6d2f39592dbec34119f
59,692
def codeblock(text): """ Returns text in a Markdown-style code block :param text: Str :return: Str """ return "```\n" + text + "\n```"
fb8fd7314273b47ace577a72c705742d6646aa0d
59,693
def get_Rx(theta): """Define matrix for rotation (roll) about x axis.""" Rx = matrix([[1, 0, 0], [0, cos(theta), -sin(theta)], [0, sin(theta), cos(theta)]]) return Rx
3ce94a9e7472deaaaccd44ead970fa14c31e1f26
59,694
def max(x: Tensor, axis: int = None) -> Tensor: """Returns the maximum value of the input tensor.""" output = Tensor(np.max(x.data, axis=axis), requires_grad=x.requires_grad) def backward_fn(): if x.requires_grad: local_gradient = output.grad.data * (x.data == output.data) ...
14e91fbc5bf8bb539fcc28c6b5ae0760da9cf395
59,695
from authlib.integrations.requests_client import OAuth2Session def set_oauth_cb(config): """Implement client support for KIP-768 OpenID Connect. Apache Kafka 3.1.0 supports authentication using OpenID Client Credentials. Native support for Python is coming in the next release of librdkafka (version 1...
b4ee2f6574e81fcf19f662697580531655407594
59,696
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version ...
6ca6e8be17607427c02fa3bc82667a730a7db1fc
59,697
def findDeviceID(): """ This method finds all devices available to play on a spotify account and returns the device to be used for playback. It always returns the ID of the Amazon Echo unless it is unavailable. Returns: deviceID(String): Returns the id of the Amazon Echo if it is available or the next...
1bf9b8e510e697e0ae19f4834c1536d02a40960a
59,698
def init_patched_conic(x, rf = 1837400.0, r0 = 6371000.0 + 185000.0, phi0 = 0.0, D = 384402000.0, V = 2.649e-6 * 384402000.0): """Generic objective function. x is [lam1, v0].""" lam1 ...
f1c6ab98114155f44ccc86effd7503cfebffb8fa
59,699