content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def findRef(pattern, haystack): """Return a reference to the matching subexpression within the original structure (for in-place modifications) or None if there is no match.""" x = searchFirst(pattern, haystack) if x is None: return None else: return get(haystack, x[0])
a0d42658fd2d0b04b6b80f873697ee5c75dc44f3
3,633,100
def parse_record(filename): """ This function parses house related data into a dictionary """ # Initialize content content = {} # Parse all lines with open(filename) as f: # Read all lines at once all_lines = f.readlines() # Skip the first three lines ...
994352f78bf333c6986927e5f0da37186deb663f
3,633,101
import socket import logging def get_hostname(): """ :return: safely return the hostname """ hostname = "<Host Undetermined>" try: hostname = socket.gethostname() except Exception as e: logging.error(f"Could not get hostname.\nException: {e}") return hostname
d5420b275c336b1295b16216a473557a24d54a61
3,633,102
def dict_get(d, key, default=None): """:yaql:get Returns value of a dictionary by given key or default if there is no such key. :signature: dict.get(key, default => null) :receiverArg dict: input dictionary :argType dict: dictionary :arg key: key :argType key: keyword :arg default:...
5fb6a71e507f62eb530215385c97c56a75765df7
3,633,103
def expect_keys_middleware(f): """ Returns a 400 error to the client if the route function tries to get a key from an object and cause a KeyError :param f: function :return: function """ def handle(*args, **kwargs): try: result = f(*args, **kwargs) except KeyError: ...
01f0c00158147ec43a4d6f67c1adf776ce05f6aa
3,633,104
def _Request(endpoint, params): """Sends a request to an endpoint and returns JSON data.""" assert datastore_hooks.IsUnalteredQueryPermitted() return request.RequestJson( endpoint, method='POST', use_cache=False, use_auth=True, **params)
0a998021638bcb1a04b13db5bbd5f2513e8a10ab
3,633,105
def dist(p, q): """ Euclidean distance for multi-dimensional data Examples -------- >>> dist((1, 2), (5, 5)) 5.0 """ return sqrt(sum((x - y) ** 2 for x, y in zip(p, q)))
1de287b22c892ad11d14c4dda1300029a23acf67
3,633,106
from typing import cast def create_item(metadata_href: str) -> pystac.Item: """Creates a STAC Item from modis data. Args: metadata_href (str): The href to the metadata for this hdf. This function will read the metadata file for information to place in the STAC item. Returns: pystac...
3e646852d3cb03215d86643253e17cd90da0241b
3,633,107
import argparse def get_args(): """ get args """ parser = argparse.ArgumentParser('NewP eval') parser.add_argument('--pred_path', required=True) parser.add_argument('--golden_path', required=True) args = parser.parse_args() return args
db9073bfc4d41c387b52fe5253a287940401c45a
3,633,108
def getQRdataImg(file:str = "img.jpg") -> dict: """ Girilen resim dosyasında qr kodunu arar ve bulursa {'barkod':barkod,'tckn':tckn} olarak returnler. """ return parseQRdata(readQRImg(file))
3207faf0cb23c259db0c16b0164797b1978916ab
3,633,109
def removeHandler(handler): """ Remove a handler from the internal logger Parameters ---------- handler: :class:`python.logging.Handler` Handler to be removed """ return __logger__.removeHandler(handler)
b156d9b34759e5062e7079e7dcb15110bd6e12ab
3,633,110
import subprocess def find_telomeres(seq, telomere="ACACCCTA", minlength=24): """Find telomere sequences with NCRF in a list of sequences Assumes that NCRF is in the PATH. Parameters ---------- seq : str Sequence to be scanned telomere : str Sequence of the telomere repeat. D...
3ae2e190a86b39ca21f59dba13aa98d6eb8247a5
3,633,111
def has_prefix(sub_s, d): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ for key in d[sub_s[0]]: if key.startswith(sub_s): return True
e5dfca7177362b7ec8d1e5ca67d43f2e963a1a46
3,633,112
def empty_transition_values(): """Return an empty transition value.""" return TransitionValues(0, 0)
837f66baaf8142f3e9bab764dbf6810f147cee3f
3,633,113
def float32(img, start_range, end_range): """Convert image to data type float32""" return cv2.normalize(img, None, start_range, end_range, cv2.NORM_MINMAX, cv2.CV_32F)
34921a34d13e5369f20be22ed87b1213b7e2dc3f
3,633,114
from typing import Iterable import uuid def loadtest_name(prefix: str, scenario_name: str, uniquifiers: Iterable[str]) -> str: """Constructs and returns a valid name for a LoadTest resource.""" base_name = loadtest_base_name(scenario_name, uniquifiers) elements = [] if prefix: ...
f449bba90ddb4bc58ff1de9268a535be34414377
3,633,115
def get_STP_in_multi_cameras(obj_single_camera_stp_cam_1, obj_single_camera_stp_cam_2, associate_dict): """ Parameters: obj_single_camera_stp_cam_1: STP in cam 1 obj_single_camera_stp_cam_2: STP in cam 2 associate_dict:mapping relation between objects in cam_1 and cam_2 """ # cho...
4f664158d5d8a6c04a659566ce7f207740925fa0
3,633,116
def resize(I, scale): """ Resize the image `I` by a factor of `scale`, while keeping the original aspect ratio. If `scale` is smaller than `1.0`, cubic interpolation is used, otherwise nearest-neighbor interpolation. """ interpolationType = cv2.INTER_CUBIC if (scale < 1.0) else cv2.INTER_N...
81aa82b8926ea241a1ab17a86ce4b1ac6eb7e0ad
3,633,117
def collisioncallback(report,fromphysics): """Whenever a collision or physics detects a collision, this function is called""" s = 'collision callback with ' if report.plink1 is not None: s += '%s:%s '%(report.plink1.GetParent().GetName(),report.plink1.GetName()) else: s += '(NONE)' s...
168aec1aba472f5fed1c6ad19821d8aa32ee9897
3,633,118
def flip_3D_bb(x, image_width): """ Flips the annotation of the image around y axis. Input: x: coordinates of points fbr, rbr, fbl, rbl, ftr, rtr, ftl, rtl image_width: width of the flipped image Return: x - flipped coordinates """ # First flip the x coordinates of the points x[0,:] = image_widt...
846f3ae9edf4927b2ab58e374085122056d967c4
3,633,119
import torch def train_model(bert_model, dataloader_train, optimizer, scheduler, device): """The architecture's training routine.""" bert_model.train() loss_train_total = 0 for batch_idx, batch in enumerate(dataloader_train): # set gradient to 0 bert_model.zero_grad() batc...
fafa12c999d3c2d9716298b1ae64bd2f53dd9d09
3,633,120
from typing import Tuple from typing import Set from typing import List import random import re def get_content(num_pages: int = constants.NUM_PAGES) -> Tuple[Set[str], List[str]]: """Retrieves page contents from random Wikipedia articles Args: num_pages: maximum number of pages to generate outpu...
c5ef011d7e6a8cc0cffdcdc2b4260de9eda847e5
3,633,121
import requests def find_flight(location_from, location_to, date_from, date_to = None, num_adults = 1, num_children = 0, round=True): """Returns list of flights with given parameters Args: location_from (str): IATA code of departing airport location_to (str): IATA code of arriving airport ...
d5b5e68d3cebb05d4cece6c4c66ca4ab9b22d056
3,633,122
def get_date_row(repositories): """Generate row with dates.""" row = ["Date"] for repository in repositories: row.append("Sources") row.append("Issues") row.append("Correct") # one more for summary row.append("Sources") row.append("Issues") row.append("Correct") ...
460b5d47e631dac4e918965eca9c11d4f6085bb1
3,633,123
import yaml def get_extensions() -> list: """ Gets extensions from the `features.yml` to be loaded into the bot :return: list """ log.info("Getting extensions...") exts = [] if osp.isfile(features_path): with open(features_path, 'r') as file: data = yaml.full_lo...
c5ca8f7d797e14bf52eb7c3edc7e3c43dd3f4662
3,633,124
def mini_batch_grad_descent(X, y, mini_batch_size=64, seed=0): """an implementation of the mini-batch gradient descent to improve the convergence speed""" np.random.seed(seed) m = X.shape[0] num_mini_batches = m // mini_batch_size mini_batches = [] permutation = list(np.random.permutation(m)) ...
4c14dbde155dfc1090505dd5711b66bcf9947f90
3,633,125
def light_percentage_schema(gateway, child, value_type_name): """Return a validation schema for V_PERCENTAGE.""" schema = {"V_PERCENTAGE": cv.string, "V_STATUS": cv.string} return get_child_schema(gateway, child, value_type_name, schema)
22fdf2eb6b4b1d55d628448389cae924cd709aae
3,633,126
def get_generator(ds_root, # dataset root directory (where to find meta.db file) batch_size=8192, # how many samples per batch to load mode='train', # mode of use of the dataset object (may be 'train', 'validation' or 'test') num_workers=None, # how many subproc...
616ec6e7709aaeb5dbfde61bf516a0444fc3513c
3,633,127
def nodeclass_from_tag(tag): """Get the class for a reST node given its tag name. This searches in antidox's pseudo-elements, docutils' nodes and sphinx' addnodes. """ if tag in PseudoElementMeta.tag_map: return PseudoElementMeta.tag_map[tag] try: return getattr(addnodes, tag) ...
d0403de978cb900b60423e3827fe238d321999ec
3,633,128
def observation_space(): """Return observation space. The state is (susceptible, exposed, infected, recovered). """ state_dim = State.num_variables() state_space_low = np.zeros(state_dim) state_space_high = np.inf * np.ones(state_dim) return spaces.Box(state_space_low, state_space_high, dtyp...
b988db328736166c23817a2f2ccb19f7b3fed6bf
3,633,129
def generate_sun_hits_products(dataset, prdcfg): """ generates sun hits products. Accepted product types: 'PLOT_SUN_HITS': Plots in a sun-radar azimuth difference-sun-radar elevation difference grid the values of all sun hits obtained during the processing period 'PLOT_SU...
ecf86308a2a4a3d4e9dca0dd4884e79748e46473
3,633,130
import requests def get_option_chains(symbol: str, expiry: str) -> pd.DataFrame: """ Parameters ---------- symbol : str Ticker to get options for expiry : str Expiration date in the form of "YYYY-MM-DD" Returns ------- chains: pd.DataFrame Dataframe with optio...
ac955c87543ac03f1019bc0ba359e2d251e3bd39
3,633,131
def _fid(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 by Dougal J. Sutherlan...
ac70f17f30160e34f40dd3fbd953303175684263
3,633,132
from typing import Tuple def gen_structures_n(size: Tuple[int, int], n: int) -> Pylist: """Generates a list of numpy arrays, where each array is a grid representation of the adsorbate distribution, 1 means that an adsorbate is present on a grid space and 0 means that the adsorbate is not present Args...
b437469247b34fff5e57aef8d69a2e566837544a
3,633,133
def get_neutron_subnetpool_name(subnet_cidr): """Returns a Neutron subnetpool name. :param subnet_cidr: The subnetpool allocation cidr :returns: the Neutron subnetpool_name name formatted appropriately """ name_prefix = cfg.CONF.subnetpool_name_prefix return '-'.join([name_prefix, subnet_cidr])
2f438ad9f53e76d5ff8cfe11e7eb613e8c2eab08
3,633,134
def verify(ui, repo): """verify the integrity of the repository Verify the integrity of the current repository. This will perform an extensive check of the repository's integrity, validating the hashes and checksums of each entry in the changelog, manifest, and tracked files, as well as the in...
07689fb0f75408f3a976218d08f20fa0783586dc
3,633,135
def error500(request): """ http 500 page :param request: :return: """ return render(request, "50x.html", status=500)
3ee60a73a526dc1337bbac01d3515c332febb74b
3,633,136
def apply_anti_area( self: Player, target: Player, rules: dict, left: bool ) -> EffectReturn: """ Apply the effects of anti_attack: Take damage if self uses area """ if self.action == "area": self = inflict_damage(100, self) return self, target, rules
65bd6f39e88b93fd03bce54db0ead906ac8cf924
3,633,137
import pytz def as_utc(time): """Convert a time to a UTC time.""" return time.astimezone(pytz.utc)
716858e88daa43b61f5cedae72e74dafcf67d423
3,633,138
import math def gelu_new(x): """ Implementation of the gelu activation function currently in Google Bert repo (identical to OpenAI GPT). Also see https://arxiv.org/abs/1606.08415 """ return 0.5 * x * (1 + th.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * th.pow(x, 3))))
7cb1108b33617341c71c08f470c68a273b654fe1
3,633,139
def message(): """Mimic message abstraction""" def _message(fields): required_fields = { "is_direct": False, "is_private_chat": False, "is_group_chat": True, "will_is_mentioned": False, "will_said_it": False, "sender": "TBD", ...
d17cc18562d76cce4dbc77409e9b53d2c04b5d40
3,633,140
def detail_url(product_id): """Return product detail Url""" return reverse('api:products-detail', args=[product_id])
362b6101b352cdc8b241af6cc4e4747b4feed282
3,633,141
import itertools def encode(data): """Encode data using LZ78 compression. Args: data: A str to encode. Returns: A list of two-element tuples of int and str. """ dictionary = {} index = itertools.count(1) word = '' result = [] for character in data: new_wor...
fcfe0b294eed92812380a60d1ec1b642084c8dfe
3,633,142
import ray def start_router(router_class, router_name): """Wrapper for starting a router and register it. Args: router_class: The router class to instantiate. router_name: The name to give to the router. Returns: A handle to newly started router actor. """ handle = router...
e309b318d48991bc9fca86c4cfbd49a675a01a39
3,633,143
def completeness_scores(include_commutative=False): """ Provide a dict with the completeness scores of rings in database :param include_commutative: if False, it will filter out the specialized commutative Properties. If True, it will include all Properties. ...
376b748da0ebff964b73059c9a2e2b1e3793487e
3,633,144
def _is_activity_overlapping(df): """ checks if any activity is overlapping another Parameters ---------- df : pd.DataFrame """ assert df.shape[1] == 3 epsilon = pd.Timedelta('0ms') mask = (df[END_TIME].shift()-df[START_TIME]) > epsilon overlapping = df[mask] return not over...
4037966bfcb3453a0cd528cb3fc2a5e345db8b74
3,633,145
def logarithmic(x, y, new_x): """ Linearly interpolates values in new_x based in the log space of y. Parameters ---------- x : array_like Independent values. y : array_like Dependent values. new_x : array_like The x values to return interpolated y values at. """...
0df18f969ef0baba082410f8794592a2f7cc5b8e
3,633,146
def replace_num(s): """Remueve los numeros de los tweets""" for i in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]: s = s.replace(i, "") return s
8d46f3e8d44cfc80f1efbb685b4a952c253763bd
3,633,147
def rotation_phi_beta(x, y, L, phi_deg, beta_deg, scale) : """Returns horizontal and vertical components of the scattering vector in units of scale (k) x, y can be arrays, L-scalar in the same units, ex. scale = k[1/A] or in number of pixels etc. """ xrot, yrot = rotation(np.array(x), np.array(y), ph...
5d971c86fd8ecbfe076281cb4689e747f95be68c
3,633,148
def _sample_rois(self, all_rois, gt_boxes, gt_labels, fg_rois_per_image, rois_per_image, num_classes): """Generate a random sample of RoIs comprising foreground and background examples. """ # overlaps: (rois x gt_boxes) overlaps = bbox_overlaps( np.ascontiguousarray(all_rois[:, 1:5], dtype=n...
4acbf052dddd5fed0c3d024728c8893341f4fc1c
3,633,149
import math def hough_line (im, nr=512, na=512, yc=None, xc=None, threshold=10,\ disp=False, dispacc=False): """ Perform the Hough transform for lines of the image 'im'. This routine performs a straight-line Hough transform of the image 'im', which should normally contain output from ...
d546e2684f06ac0fe99111a64c17ecbf7b0708f5
3,633,150
def build_response(session_attributes, speechlet_response): """builds resopnse""" return { 'version': '1.0', 'sessionAttributes': session_attributes, 'response': speechlet_response }
96bc754e1a58300b2861851be678aa0e984845a8
3,633,151
def insertion_sort(L): """Implementation of insertion sort.""" n = len(L) if n < 2: return L for i in range(1, n): tmp = L[i] j = i while j > 0 and tmp < L[j - 1]: L[j] = L[j - 1] j -= 1 L[j] = tmp
ca7cbb5c676173ad10ce98d8b9e579a65afad0fb
3,633,152
def get_bgp_peer(): """ collects local and bgp neighbor ip along with device name in below format { 'local_addr1':['neighbor_device1_name', 'neighbor_device1_ip'], 'local_addr2':['neighbor_device2_name', 'neighbor_device2_ip'] } """ config_db = ConfigDBConnector() config_db.connec...
681b70cbef1b2c551c9d5040f9921f25edea6a17
3,633,153
def _do_nothing(string): """Makes the ConfigParser case sensitive.""" return string
4011cbe5b00bef5fe9fc13420bbd988729641676
3,633,154
def show_game(game_id): """Return the rendered template for a game with game_id. Args: game_id(int) Returns: Rendered html template """ game = session.query(Games).filter_by(id=game_id).one() date = game.release_date.date().strftime("%d, %B %Y") category = session.query(Category)....
63a9fc5240164953e37de7dbc3e323a60bc46364
3,633,155
def is_symmetric(mat): """Return whether a sy.Matrix is symmetric.""" n, nc = mat.shape return nc == n and all(mat[j,i] == mat[i,j] for i in range(n) for j in range(i+1, n))
e23cb03ec06f16584a99c82d66770491a6635ef5
3,633,156
def download_ftp_text(file_url: str) -> str: """Download FTP file to memory return it as string (ASCII encoding is assumed). :param file_url: file URL which must start with ftp:// """ with open_ftp_file(file_url) as fp: return fp.read().decode('ASCII')
daf8dbe8f0d06b42d228b58084e074e6543fc216
3,633,157
def choice_likeFestival(user_id): """ 가고 싶은 축제 선택 """ print('choice_likeFestival') for row in userInfoDB.rows: if row[0].value == user_id: # 방문했던 적이 있었던 사람, 리스트로 저장되므로 리스트로 접근 userRow = row[0].row() index = contentListCode.index(stateDB.loc[user_id, 'contentCode']) ...
46b0ea332c19a5b2998c4a04c665d6f59d32cd17
3,633,158
def least_square_regression(x, y, xlabel = "x", ylabel = "y", prefix="", suffix=""): """ Perform least square regression to find the best fit line and returns the slope of the line. **Parameters** x : List of values along x axis. y : List of values along y axis. """ X = np.asa...
88d4601203031659e905be210e8621a9f1f72ab1
3,633,159
def build_dict(*param_dicts, **param_dict): """ Create a merged dictionary from the supplied dictionaries and keyword parameters. """ merged_param_dict = param_dict.copy() for d in param_dicts: if d is not None: # log.info("param_dicts %r"%(d,)) merged_param_dict.upda...
1f77e1ca81051913ed32ea5bfdb684cf468e27af
3,633,160
def calc_volume(all_vertices, element): """Calculate the volume for the given element based on type. Returns length between points (2D) and volume within points (3D).""" vertices = all_vertices[element.vertice_ids] # 1D case with lines (volume) and points (area) if element.element_type == ElementTy...
39c631c8dc4bc8e00776ee14237fc054a4d6546e
3,633,161
def Mode(hist): """Returns the value with the highest frequency. hist: Hist object returns: value from Hist """ p, x = max([(p, x) for x, p in hist.Items()]) return x
2db7d658ad58a80041c3f450104aada006b11eaf
3,633,162
def get_img_space(wsp, img): """ Find out what image space an image is in Note that this only compares the voxel->world transformation matrix to the reference image for each space. It is quite possible for two images to be in the same space but not be registered to one another. In this case, ...
b455dd6300cf13cbba5d8e2d44685e06d8fb4cad
3,633,163
import os def get_dir(algorithm, mode): """ Used to determine the plotting folder Parameters ---------- algorithm: String The name of the current ANC algorithm running mode: String The MODE (precorded or anc) the server is currently running Returns ------- path :...
350e47f729bddbc7d85e306b6b6af5d6a14222ea
3,633,164
def get_comma_delimiter(include_a_space=True): """Return the comma delimiter appropriate for the current language (Arabic or English). When include_a_space is True (the default), the delimiter includes a space to make the returned value easy to use with join() when constructing a list. """ delimite...
60622204de1ccf381b4c87abd2dedc5406f99a1a
3,633,165
def str_to_bool(string): """Used as a type in argparse so that we get back a proper bool instead of always True """ return string.lower() in ("y", "yes", "1", "true")
ab54e7cff5721f91f78c90498c16d68f2760ee11
3,633,166
import re def _run_canned_tests(env,osenv): """Run the tests from the tests subdirectory""" retval = 0 # success env['test_dir'] = env.escape_string(mbuild.join(env['src_dir'],'tests')) cmd = "%(python)s %(test_dir)s/run-cmd.py --build-dir %(build_dir)s/examples " dirs = ['tests-base', '...
17b85edeacbfeff77ebdd238da817a869b04ebde
3,633,167
def new(nbits, prefix=b"", suffix=b"", initial_value=1, little_endian=False, allow_wraparound=False): """Create a stateful counter block function suitable for CTR encryption modes. Each call to the function returns the next counter block. Each counter block is made up by three parts: +------+---------...
a0cdadcf6eb81ad323c205e08db97d094326f513
3,633,168
from typing import Tuple def scoreNF(shelf: Shelf, item: Item, self=None) -> Tuple[int, Shelf, bool]: """ Next Fit """ if self.shelves: open_shelf = self.shelves[-1] if self._item_fits_shelf(item, open_shelf): return (0, open_shelf, False) if self.rotation and self._item_fi...
33205a6b87ae894156778d515b2bf68635c15586
3,633,169
def parse_str_to_date(date_str): """ Recieves a Date String (e.g. 2019-10-09) and returns a datetime object """ #T22:25:00-03:00 if type(date_str) != str: return None return dt.datetime( int(date_str[0:4]), #Year int(date_str[5:7]), #Month int(date_str[8:10])...
42083fbcc37fb9739154759ae7f278a1f958b0ca
3,633,170
def size(imageOrFilter) : """Return the size of an image, or of the output image of a filter This method take care of updating the needed informations """ # we don't need the entire output, only its size imageOrFilter.UpdateOutputInformation() img = image(imageOrFilter) return img.GetLargestPossibleReg...
1459e7d5f8b1c762e2a351a0b933d3bc9c651e48
3,633,171
def fetch_eigenv(odb_name, step_name, n_eigen): """ Get eigenvalues. Return the eigenvalues of a perturbation buckling analysis from an abaqus database. Parameters ---------- odb_name : class Abaqus model containing the eigenvalues step_name : string Name of the step n_...
603c0b40e95a181437c5f6b615f282db6c9eea90
3,633,172
def _not_exhausted(last_fetched): """Check if the last fetched tasks were the last available.""" return len(last_fetched) == 100
570cf94ba9c723cced8ec3a746f2ce070d780fd5
3,633,173
import os def files_by_extension(root, extensions): """ Returns a list of files that match the extensions given after crawling the root directory """ assert(os.path.isdir(root)) file_list = [] for roots, _, files in os.walk(root): for f in files: ext = os.path.splitext(f)[1][1:].strip().lower() if ext...
637d8f2fc8d35f1f78e81c328541519b32b34d7b
3,633,174
import requests def playonyt(topic: str, use_api: bool = False, open_video: bool = True) -> str: """Play a YouTube Video""" if use_api: response = requests.get( f"https://pywhatkit.herokuapp.com/playonyt?topic={topic}" ) if open_video: web.open(response.content...
b897fb7271b2aaf6b421702dc851fa90fcc79b17
3,633,175
def get_data(filename: str = "test", roi: str = []) -> list: """ Return data (pixel values) from an ROI in an image for every extension. NOT FINISHED! Args: filename: image filename. roi: Region-Of-Interest. Returns: list of pixel values. """ filename = azcam.utils....
1c4fd0634853f06a82525245374eec24016769df
3,633,176
import logging def execute_select_dataframe_columns(dataframe, select_dataframe_columns): """ Filter dataframe using the provided columns Args: dataframe (array[str]): Array of columns names select_dataframe_columns (pandas.Dataframe): Dataframe Returns: pandas.Dataframe: Da...
12ce4343e97886820a3fecb3d79d5eddd593a7fa
3,633,177
import os import argparse def extant_file(x): """ 'Type' for argparse - checks that file exists but does not open. """ if not os.path.exists(x): # Argparse uses the ArgumentTypeError to give a rejection message like: # error: argument input: x does not exist raise argparse.Argu...
2572516acbc1b6a661e4d85f36d8adb96f832d0f
3,633,178
def test_from_format(schema, to_fn, buf_cls): """ Test that check_types-guarded function reads data from source serialization format. """ @pa.check_types def fn(df: pa.typing.DataFrame[schema]): return df for df, invalid in [ (mock_dataframe(), False), (invalid_inpu...
d1ce34befb2255ee15b86d36d28d24075c4638f0
3,633,179
def has_oxidation_states(comp): """Check if a composition object has oxidation states for each element Args: comp (Composition): Composition to check Returns: (boolean) Whether this composition object contains oxidation states """ for el in comp.elements: if not hasattr(el, ...
702595070b588761142055bc1532ce26acd287fb
3,633,180
def check_fsig_int(quad_int, cryst_ptgrp, sigma, *args): """ For specific sigma rotations, a function of m, U, V, W (fsig) is computed. The ratio of fsig and sigma should be a divisor of kmax. This condition is checked and those integer quadruples that satisfy this condition are returned Parame...
c610da0a1055354fd1a0f27b73cf251b7a7db458
3,633,181
def exit_flow(exit_inputs: Tensor) -> Tensor: """ Exit flow Implements the second of the three broad parts of the model. Includes the optional fully-connected layers, and the logistic regression segment of the model. :param exit_inputs: Tensor output generated by the Middle Flow segment, having shap...
fa73280187448f0acd89ea834d78b261e9f95415
3,633,182
def check_Latitude(observation): """ Validates that observation contains valid age value Returns: - assertion value: True if age is valid, False otherwise - error message: empty if age is valid, False otherwise """ value = observation.get("Latitude") ...
65582eea8a5c40a08054eb5b4889aa3bc6d0af68
3,633,183
def read_and_reshape_data(filename): """ Read in the Snake grid output and reshape it into a 3d array of (ncycles, ncells, ncols). Parameters ---------- None Returns ------- sgrid: (ncycles, ncells, ncols) array of str The reshaped grid output from Snake. The columns are as...
f9be8e78d359e4c74d7122c11294ca478f1958c7
3,633,184
def chart(start: str, stop: str): """График с данными.""" return flask.render_template('chart.html', start=start, stop=stop)
745ec2f593cdac79494da36e33e7c29ae7facb01
3,633,185
def toa_error_cross_corr(snr, bandwidth, pulse_len, bandwidth_rms=None): """ Computes the timing error for a Cross-Correlation time of arrival estimator, given the input signal's bandwidth, pulse length, and RMS bandwidth. Ported from MATLAB Code Nicholas O'Donoughue 11 March 2021 ...
0fe5fc399108bc6a57ce3e5e5b340e1b5dfa45eb
3,633,186
import re def search_projects(): """ Search for projects - When given the name of a known project (*modulo* normalization), redirect to that project's page - When given an unknown project name, search for all known project names that have it as a prefix - When given a search term wi...
3d4823f6c26324e80f8250f51d32fa466b25ca61
3,633,187
from typing import Optional def parse_opt_int(s: Optional[str]) -> Optional[int]: """ parse_opt_int(s: Optional[str]) -> Optional[int] If s is a string, parse it for an integer value (raising a ValueError if it cannot be parsed correctly.) If s is None, return None. Otherwise, raise a TypeErro...
91a102c8c8e6a6ee109e9c88c56d9a6959f1f838
3,633,188
def get_record_parser(config, is_test=False): """ Get the tfrecords sample parser. :param config: Contains the configurations to be used. :param is_test: Indicate if the data_type is test. :return: The parser method. """ def parse(example): """ Extract features from a single ...
0daec653596082160872d2222569849c6caa6fdd
3,633,189
from typing import Optional def get_model_loader(namespace: Optional[str] = None) -> ModelConfigLoader[SegmentationModelBase]: """ Returns a ModelConfigLoader for segmentation models, with the given non-default namespace (if not None) to search under. """ return ModelConfigLoader[SegmentationModel...
cd57837a21b49d04876ef9162b5b47984a38b109
3,633,190
from typing import Optional def beam_search(mat: np.ndarray, chars: str, beam_width: int = 25, lm: Optional[LanguageModel] = None) -> str: """Beam search decoder. See the paper of Hwang et al. and the paper of Graves et al. Args: mat: Output of neural network of shape TxC. chars: The set...
fe6575a42c02dd0174125b588590d9d46318b614
3,633,191
def generate_hyperparameters(k): """ generate k sets of hyperparameters randomly : (mutate_prob, elite, alpha, beta) Args: k: number of sets Returns: list of settings, where each setting is a set of hyperparameters """ settings = [] for i in range(k): setting = [np....
7e326170b872ba8bcd82b0411a4d88f004f1f773
3,633,192
def unparse_point_sources(point_sources, strict=False, expand_env_vars=False, properties=lambda x:''): """ Convert a list (or other iterable) of PointSource objects into XML. strict : bool set True to generate exception, error message identifying offending source, reason properties : a f...
03fcc44b85523b7f082eed774fc1f4a271d30867
3,633,193
def pion_to_muon_avg(x_lower, x_upper): """ Energy distribution of a numu from the decay of pi Args: x_lower,x_lower (float): energy fraction transferred to the secondary, lower/upper bin edge Returns: float: average probability density in bins (xmin,xmax) """ if x_lower.shape != x_...
d6be736cb901555e3539c892941e887bda0ac0e2
3,633,194
def secord_update(t, x, u, params={}): """Second order system dynamics""" omega0 = params.get('omega0', 1.) zeta = params.get('zeta', 0.5) u = np.array(u, ndmin=1) return np.array([ x[1], -2 * zeta * omega0 * x[1] - omega0*omega0 * x[0] + u[0] ])
b5af03a1b1da8a3b5d7ca9ef9f50d77279f567b2
3,633,195
from javax.swing.event import ChangeListener def addChangeListener(target, listener, *args, **kwargs): """ Shortcut for addEventListener(target, ChangeListener, 'stateChanged', listener). """ return addEventListener(target, ChangeListener, 'stateChanged', listener, *ar...
c9cde3efe17f321b79097c84887f2b1c852c7345
3,633,196
from typing import List def drop_no_image(df: pd.DataFrame, imaged_samples: List[int]) -> pd.DataFrame: """ Pandas pipe function to drop any rows from table for samples that have no images. """ df_temp = df[df['Sample'].isin(imaged_samples)] return df_temp
796f23720828c265e0d96b330f23802b7f14dd02
3,633,197
from typing import OrderedDict def parse_fasta(handle): """Parse sequences in a FASTA file. Sequence headers are trimmed after the first whitespace. Returns: Sequences in FASTA file keyed on their headers (i.e. > line) """ sequences = OrderedDict() skip = False for line in handl...
acab430c325aaca5de0bc5851ffe948830dc21f0
3,633,198
def assign_cat(plugin): """Assigns `symbols` module mapping to the `Warp` plugin.""" items = [] for item in MAPPING_SYMBOLS: items.append( plugin.create_item( category=plugin.CATEGORY_SYMBOLS, label=item[0], short_desc=item[1], ...
f5ec84d0e3662cafe69ac85d7e52965720109528
3,633,199