content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def find_feature_expectations(feature_matrix, o_feature_matrix, trajectories, global_trajectories, options_states): """ Find the feature expectations for the given trajectories. This is the average path feature vector. feature_matrix: Matrix with the nth row representing the nth state. NumPy ar...
0ace4de1933485b78823f43d2ce70b33d97d8b73
68,887
def select_t(func): """ Transformation for Sequence.select :param func: select function :return: transformation """ return Transformation( "select({0})".format(name(func)), partial(map, func), {ExecutionStrategies.PARALLEL}, )
0c8fdb9c5af061a023ee7a09b5d53bb1b73643c6
68,888
def group(x, n_filters, n_blocks, alpha): """ Construct a Depthwise Separable Convolution Group x : input to the group n_filters : number of filters n_blocks : number of blocks in the group alpha : width multiplier """ # In first block, the depthwise convoluti...
bd0233d7a672fdf5e1d1d0f84ccee9488d1f5432
68,889
import logging import time def evaluate(loader_dev, metric, segment): """Evaluate the model on validation dataset.""" logging.info('Now we are doing evaluation on %s with %s.', segment, ctxs) metric.reset() step_loss = 0 tic = time.time() out_list = [] label_list = [] for batch_id, seq...
e6ef4ed5553f877ad01ceb3a0e19bfc258ae6a86
68,890
def query_prob(result, Y, y, e): """ Query P(Y | e), or the probability of the variable `Y`, given the evidence set `e`, extended with the value of `Y`. All immediate parents of Y have to be in `e`. """ # if Y is continuous (with discrete parents) if Y in ['Nscore','Escore','...
3b7aec7ef40eca8544286de8b59e509c900b1979
68,891
async def get_user(request: web.Request) -> web.Response: """Handlers for GET /users/{username} List groups of {username} """ hostname = request.app["settings"]["hostname"] username = request.match_info["username"] claims = utils.enforce_authorization(request.headers, request.app["settings"]) ...
f1c509700b07e0631f0d46c17e72265d707337c4
68,892
def scoreboard(board, depthleft, evaluate): """ This method uses a Negated Minimax method. Instead of two subroutines for maximising and minimising players, it passes on the negated score due to following mathematical relation: max(a, b) == -min(-a, -b) """ # Note, if it...
079873b5500085c376015c60b40ff760af680ffa
68,894
def HaarGOB(treeG): """ HaarGOB generates Haar Global Orthonormal Basis for a chain or tree treeG INPUTS: treeG - chain or tree for a graph OUTPUTS: treeG1 - the updated chain treeG which is added for each level a Haar orthonormal basis and for the bottom level the basis is the ...
9934013622249dc14fe7d0a3082de8a0305d01be
68,895
def get_all_but_hidden_sites() -> list: """Returns all but hidden site identifiers.""" sites = get_from_data_portal_api("api/sites") sites = [site["id"] for site in sites if "hidden" not in site["type"]] return sites
50ee53142d58d8b27a7d0e14eda3df642e5b0443
68,896
def phasecycle(all_data, dim, receiver_phase): """Phase cycle Args: all_data (dnpdata_collection, dnpdata): data to process dim (str): dimension to perform phase cycle receiver_phase (numpy.array, list): Receiver Phase 0 (x), 1 (y), 2 (-x), 3 (-y) Returns: dnpdata: data obj...
d2035edcc56c09d70b1b221d4e552c3efb799561
68,898
def minutes_to_seconds(minutes): """A function that converts minutes to seconds :param minutes: The number of minutes do be converted :return: The number of seconds in a give number of minutes """ return 60 * minutes
b9dee8e669f7659fe669e5b97ef79e8e035b63bf
68,899
def all_boolean (phrase): """Returns TRUE if all elements of <phrase> are boolean""" if not isinstance(phrase,list): return False for x in phrase: if not isinstance(x,bool): return False return True
eaec8cae03041d5c8b2e7d4af0c2b4e373bfaa4c
68,900
def get_visualized_skeleton(img: np.ndarray, skeleton: SkeletonBase, min_limb_score_to_show: float = 0.4): """ Draws the skeletons joints and limbs in the image. :param img: The original image :param skeleton: The skeleton to be visualized :return: A copy of the image with the visualized skeleton ...
775f3845d47e00491d9f1161ed7cc11b276d69ee
68,901
def get_slips(read, slips, reference): """ Return a list of slips from the alignment with the most non-templated SNPs explained by Polymerase slippage events. :param read: :param slips: :param reference: :return: """ results_per_aln = [] for aln in read.alns: nontemplated_tf ...
f07c5d262365ca3c7ede179d5128b3e121040380
68,902
def __get_best_matching_chain(node, lineno): """ Get the best matching chain. """ result = [] while node and __get_line(node) <= lineno: result.append(node) node = __get_best_matching_child(node, lineno) return result
1946d76f2a61bb406bc055ac7d082e44eeec2c69
68,903
def frames_to_secons(frames, framerate): """ Returning secons. Args: frames (int): frame framerate (flaot): frame rate Returns: float: second value """ rt = _ot.from_frames(frames, framerate) return _ot.to_seconds(rt)
e2c01021c909e7dd7260a4f494ba0af50dda0817
68,904
import re def reverse_url(url): """ >>> reverse_url("http://www.face.bnl.gov/FACEDailyReports/Facts_I/Archive/03132003/ArchivePage.htm") 'gov.bnl.face.www.facedailyreports.facts_i.archive.03132003.archivepage.htm' """ components = urlsplit(url) hostname = components.netloc.partition(':')[0] ...
cfc5e636d6f545d8b57eff8abb0eb01343d3fa36
68,905
import time def tprint(string, dt=1, output=False): """ Print progress of a loop every dt seconds.""" if (time.time() - tprint.time) > dt: print(string) tprint.time = time.time() if output: return True else: return else: if output: ...
c6edad145fdab2e5612bdecdd562f44859d9feda
68,906
def in_range(length, start=None, end=None): """Return if start and end are between [0, length)""" if start is None and end is None: return False elif start is not None and end is None: end = start elif end is not None and start is None: start = end if not isinstance(start, i...
9449abd7bb962890b45ceaccdd6c3109d639174b
68,907
def get_ndmi_task(band_types='BANDS-S2-L1C'): """ EOTask that calculates the NDMI values Expects the EOPatch to have either Sentinel L1C or L2A bands. Will append the data layer "NDMI" to the EOPatch Run time parameters: - band_types(str): the name of the data layer to...
27f00054de49791b0f2655c880ae3f8ba4b37e5c
68,908
def calculate_halo_correspondence(source_halo_props, target_halo_props, n_threads=-1): """Calculating indexing array defined by a statistical correspondence between source and target halos. Parameters ---------- source_halo_props : sequence of n_props ndarrays Each ndarray should have shape...
e32f88188c1b137274292c2c6e2c6b163b861ecf
68,909
def eval_eigs(model, dataloader, fisher=True, train_mode=False, nsteps=10, return_evecs=False, pnames=None): """ Get "nsteps" approximate eigenvalues of the Fisher or Hessian marix via Lanczos. Args: model: the trained model. dataloader: dataloader for the dataset, may use a ...
c248031705792da8fd44eea34eac21d69690cec6
68,910
import random def calculate_shapley_value_for_single_node(g, prob_vals, node): """ This approach is based on the following paper - https://www.sciencedirect.com/science/article/pii/S0004370208000696?via%3Dihub :param g: graph :param prob_vals: node weights :param node: node under consideration ...
5144a62c5707032bf6e88dd47c08cea3c2ec682a
68,912
def nerf(key, args): """Neural Randiance Field. Args: key: jnp.ndarray. Random number generator. args: FLAGS class. Hyperparameters of nerf. Returns: model: nn.Model. Nerf model with parameters. state: flax.Module.state. Nerf model state for stateful parameters. """ deg_point = args.deg_poin...
7673aad74925ee8ee5fbbfbd43c882462e311c33
68,913
def psnr_delight(y_true, y_pred): """"Calculating peak signal-to-noise ratio (PSNR) between two images.""" return tf.image.psnr(y_pred, y_true, max_val=255.0)
75536092f76f626c5e0874bba46dfa0f610f7a18
68,914
import warnings def plot_convergence_results_m(iterations, distances, total_energies, *, modes, nodes=None, saveas1='t_energy_conver...
40e5c6057bcffdc35decb09904f7be40d0c77889
68,916
def add(ds_man, ds_id=None, params=None): """ :param ds_man: rest.SMapiDatasetManager :param ds_id: string :param params: { doc { name input_path upload_dt metadata is_public (ds_config keys from sm.engine.dataset.FLAT_DS_CO...
f9705e79d6ad27e027c9ae3f6414839dea510b27
68,917
def _traversable_path(path): """ Little helper to remove a leading slash (and trailing slashes as well) which the .restrictedTraverse method seems to dislike. >>> _traversable_path('/e-learning/') 'e-learning' Note: The method will still raise a KeyError if fht object is not yet there! """...
e147dc3da014db598ed5f7981e9a5664b33ec907
68,918
def _neurovault_images(parts, query): """Mocks the Neurovault API behind the `/api/images/` path. parts: parts of the URL path after "images", ie [] or ["<someimageid>"] query: the parsed query string, e.g. {"offset": "15", "limit": "5"} returns a dictionary of API results See the neurovau...
930929ac985e06b2f0d8281419b8b23b5bc9fa1b
68,919
import re def normalize_likes(sql: str) -> str: """ Normalize and wrap LIKE statements :type sql str :rtype: str """ sql = sql.replace("%", "") # LIKE '%bot' sql = re.sub(r"LIKE '[^\']+'", "LIKE X", sql) # or all_groups LIKE X or all_groups LIKE X matches = re.finditer(r"(or...
8059eb4bf1ee4a8045702024c81a4f8b35469358
68,920
def apply_filters(url, redfin_base_url): """Apply more filters to make it more fine-grained. Return a list of urls containing filters, which adds up to the original url. Filter priority: price, sqft-size, year-built """ if '/filter/' not in url: price_filters = [(300000, 600000)] ...
df411856ceb55c3f62f5cc463161b8b1cc9bcf45
68,921
def update_hand(hand, word): """ Does NOT assume that hand contains every letter in word at least as many times as the letter appears in word. Letters in word that don't appear in hand should be ignored. Letters that appear in word more times than in hand should never result in a negative count; ins...
43a976e5abddb66e3e33ff0f4a693278ac490410
68,922
def get_char_size1(coord1, v): """ if not vetical c1 c2 c4 c3 if vetical c1 c2 c4 c3 """ c1, c2, c3, c4 = coord1 if v: csz = (np.linalg.norm(c1 - c2) + np.linalg.norm(c3 - c4)) / 2 else: csz = (np.linalg.norm(c1 - c4) + np.linalg.norm(...
46166d8fd3e8c0384671beebe8bbf00745ccf0ba
68,923
def parse_xml(xml_file): """Create the python model for a test_run xml file""" return AutoCertKitRun(xml_file)
bf696dd2b3c8e00b567e480caa12df810977bca0
68,924
import logging def query(query_str): """Write rows to bigquery table. Args: query_str: str, the query to execute. Returns: list of google.cloud.bigquery.table.Row objects. """ job = gcp.bigquery_client().query(query_str) if job.error_result: logging.error('Bigquery: %s', job....
5854757273abc3739cba40b1db034a8acac04244
68,925
import logging import requests def removeGitHubTeamMember(teamID, login): """ Remove a team member from a team """ if str(int(teamID)) != str(teamID): logging.warning("Bad Team ID passed!!") return None if login.lower() == 'humbedooh': logging.info("Not removing Mr. Humbedooh just ...
c754e619b30720f5198edb1639b15b72eda52548
68,926
import pickle def load_omas_pkl(filename, consistency_check=None, imas_version=None): """ Load OMAS data set from Python pickle :param filename: filename to save to :param consistency_check: verify that data is consistent with IMAS schema (skip if None) :param imas_version: imas version to use ...
bdfca5f472cfedf86ad80c03e7869dac206f62ea
68,927
from bs4 import BeautifulSoup def get_job_id_indeed(card: BeautifulSoup) -> str: """ Function to retrieve the job ID from an HTML tag in the <div class='jobsearch-SerpJobCard unifiedRow row result'. The job ID appears to be unique for each job and is used to remove duplicate results and later may be u...
aeb252cd519f5ef1a1264e8e7d29d9a427d67b95
68,929
def pivot_df(df, var_name): """ Pivot DataFrame converting columns to source and data to var_name Parameters ---------- df : pandas.DataFrame Source DataFrame to convert to Seaborn long style var_name : str Column name to use for data in final DataFrame Returns ------- ...
f0e83b92c5ea46ed274173f0dcd5374df85b6a00
68,930
def escapes_sub(match): """Substitutes escaped characters.""" return match.group(1)
f9d535bfdeea2cf4791301c348d513b606ed258d
68,932
import json def ref_truncated(ref_scene, matched_footprints, covth=.99): """Return True if reference scene will be truncated.""" # geometries are in lat/lon projection src_srs = osr.SpatialReference() src_srs.SetWellKnownGeogCS("WGS84") #src_srs.ImportFromEPSG(4326) # use projection with uni...
1d9b32dcfb8bb819f9c51681a44d41b56cb53ee5
68,933
def mode(nums): """Return most-common number in list. For this function, there will always be a single-most-common value; you do not need to worry about handling cases where more than one item occurs the same number of times. >>> mode([1, 2, 1]) 1 >>> mode([2, 2, 3, 3, 2]) ...
752fa58dbf1cc34e95a1c53f1f38b0746ae25f62
68,934
def vit_tiny_patch32_224(pretrained=False, **kwargs): """ ViT-Tiny (Vit-Ti/16) """ model_kwargs = dict(patch_size=32, embed_dim=384, depth=12, num_heads=3, **kwargs) model = _create_vision_transformer('vit_tiny_patch16_224', pretrained=pretrained, **model_kwargs) return model
1d8673f713bbe2962b243d9142a1b89cf1b24b77
68,935
def minimum_time_to_make_a_sale(): """ Real Name: Minimum Time to Make a Sale Original Eqn: 1 Units: Months Limits: (None, None) Type: constant Subs: None What is the absolute minimum calendar time it would take to make a sale to a person, even if you had all the hours in the da...
ab6acc9421756d944c23119512bb84eb7750c83b
68,936
def read_data_line(line): """Process a line from data file. Assumes the following format: WORD W ER D i.e. word tab separated with pronunciation where pronunciation has space separated phonemes Args: line: string representing the one line of the data file Returns: chars:...
66a840e2f2dfbc5e6c9d4a62c938b1bc60454a1f
68,937
from typing import Optional def infer_compression(input_filename: str) -> Optional[str]: """ Infers compression for a file from its suffix. For example, given "/tmp/hello.gz", this will return "gzip" >>> infer_compression("/tmp/hello.gz") 'gzip' >>> infer_compression("/tmp/abc.txt") is None T...
fc4c434586b88113ba5bdff3d1a0b0ce52b60530
68,938
def _combine_samples(x_pos, x_neg, labels=None): """Combines sample data in one large numpy array and labels them according to class.""" y = [] y += [1] * x_pos.shape[0] y += [-1] * x_neg.shape[0] x = np.vstack((x_pos, x_neg)) return x, np.array(y)
596f46237b3dd04c6190c9d1f34f8c5b46ac1e14
68,939
def get_runner(tasks, args): """ :param tasks: :return: Runner """ if is_grid5k(): return Grid5kRunner(tasks, args) return LocalRunner(tasks, args)
5c0ab5d131b677a7541dcd7e3b0753e0dd1ee1dd
68,940
def artificial_to_original(params, errors, f, hiatus=0): """ Convert artificial beam parameters to original beam parameters. ISO 11146-1 section 9 equations are used to retrieve the original beam parameters from parameters measured for an artificial waist created by focusing the beam with a lens. ...
0bc94523a3e462221bca63e89a078f160dcb8386
68,941
def api_get_balance(addr): # noqa: E501 """get balance from address using woc. get balance from address using woc. # noqa: E501 :param addr: bitcoin sv address :type addr: str :rtype: ResponseGetBalanceModel """ return 'do some magic!'
b64771f02553e134f17b8cc5dcfddc3f48465849
68,942
def build_app_generator(request): """Build - App Generator page.""" app_generators = [ { 'css_name': 'app-stub', 'title': _('App Stub'), 'download': 'https://github.com/mozilla/mortar-app-stub/archive/v0.1.0.zip', 'preview': 'app-stub-screenshot.png', ...
609b47b9d5ecc78cd9a936ca889f762c7c6ecaf4
68,944
import copy def get_RF_color(rf_vec): """ Mapping RF space to color in a standard (historical) way. """ color = copy.deepcopy(rf_vec) def renormalize(v): v -= np.min(v) return v / np.max(v) for i in xrange(3): color[:, i] = renormalize(color[:, i]) return color
0c10e2622fc9394156b79c6ecae35d4a27c3d4c0
68,945
import pickle def get_probabilities(input): """ Reads the models from the models directory Gets the probabilities of the input for all the models :param input: sparse vector :return: data frame with the probabilities of the models """ with open('models/ada.pkl', 'rb') as file: ada_...
22984512263422ad53d3abe90bfd57830514bc7a
68,946
def setup(hass, config): """Set up this component.""" # Print startup message _LOGGER.info(STARTUP) # Check that all required files are present file_check = check_files(hass) if not file_check: return False # Create DATA dict hass.data[DOMAIN_DATA] = {} hass.data[DOMAIN] =...
089fe5f0f956841285c8d705431e57f46cbcbbc5
68,947
import sqlite3 def create_connection(db_file): # Establish SQLITE database connection cursor """ create a database connection to the SQLite database specified by the db_file :param db_file: database file :return: Connection or None """ conn = None try: conn = sqlite3.connect(db...
539474e31326cf95607b375e9469ece964b661a8
68,948
import click def eeq(config, inp: str, out: click.File, chrg: int): """Electronegativity equilibration atomic partial charges.""" molecule = ksr.constructMolecule(geometry=inp, out=out) nat = molecule.get_number_of_atoms() eeq = molecule.get_eeq(chrg) for i in range(nat): silentPrinter(co...
c0628d6483a81f2491bf831109dc4c1f422ae436
68,949
def get_holdings(xls: pd.ExcelFile) -> np.ndarray: """Retireve the holdings data from excel file. :param xls: The excel file. :return: The capacities. """ df_ward_info = pd.read_excel(xls, WARD_SHEET, index_col=0).astype("str") holdings = np.array(df_ward_info.loc[WARD_HOLDING_ROW]).astype( ...
7a400c090a022ac0a6a37f1d5a258dd2cfc82b0a
68,951
def formatted_constituent_array(constituent_array): """ Given a constituent array of Species, return the classic CALPHAD-style interaction. Parameters ---------- constituent_array : list List of sublattices, which are lists of Species in that sublattice Returns ------- str ...
b1e60d21c28b66620eaffed1cda20abcb394a833
68,954
def calc_automated_readability_index( n_letters: int, n_words: int, n_sents: int, a: float = 6.26, b: float = 0.2805, c: float = 31.04, ) -> float: """ Вычисление автоматического индекса удобочитаемости Описание: Чем выше показатель, тем сложнее текст для чтения Резу...
d2a49044749dc93bb8684b27a81f47ff1498cc46
68,957
def FirstFree(seq, base=0): """Returns the first non-existing integer from seq. The seq argument should be a sorted list of positive integers. The first time the index of an element is smaller than the element value, the index will be returned. The base argument is used to start at a different offset, i.e...
42323664c7bb2c59506ed3b24115a38bc0fcf63d
68,958
def overlap_set(str_mention1, set1): """ Receives a mention and a set of mentions and returns whether the mention is in the set :param str_mention1: a mention :param set1: a set of mentions :return: whether the mention is in the set """ return str_to_set(str_mention1).intersection(set1)
9b1a276f4d9b426efbb5d1d30b91e5c7a2f872bf
68,960
def get_eval_mask(labels, invalid_voxels): """ Ignore labels set to 255 and invalid voxels (the ones never hit by a laser ray, probed using ray tracing) :param labels: input ground truth voxels :param invalid_voxels: voxels ignored during evaluation since the lie beyond the scene that was captured by the laser ...
d02ac06abd89b0e0cc9a424a7c4a77ef796afeed
68,961
def partition_data(y, nfold=10, fold_method='sublock', nrepeat=None): """ partition data for K-Fold Cross-Validation. Parameters ---------- nobs : int type. Number of observations. nfold : int type, default is 10. number of folds. method : s...
04f072c731adc8014d84479e47f6d201867e97e0
68,963
def accept_penalty(employee_id: str = None, file: str = None, docname: str = None) -> dict: """ This is an API to accept penalty. To Accept Penalty, one needs to pass the face recognition test. Image file in base64 format is passed through face regonition test. And, employee is given 3 tries. If face recognition i...
608ff0c2ed3b3b5afd9e7cd371e17afa45bb944c
68,965
def evaluate_mae(dataloader, model): """ Calculates MAE using previously trained model Args: data_transforms: torchvision transforms to preprocess raw images; same as validation transforms model: densenet-121 from torchvision previously fine tuned to training data Returns: mae: ...
75fedb1b93d674323232176871924637c7a4a844
68,966
def user_drafts(): """Получить список черновиков""" user = get_user_from_request() query = Post.get_user_drafts(user) limit = max(1, min(int(request.args.get("limit") or 20), 100)) paginated_query = PaginatedQuery(query, paginate_by=limit) posts = [p.to_json() for p in paginated_query.get_obje...
c5f7d114d7e371f0fb6400b2ee982e3a167ec8f4
68,967
def _guessTrayPosition(screenGeometry, iconGeometry): """ Function uses simple heuristic to guess the position of system tray on the screen @param screenGeometry: screen size where the icon is located @type screenGeometry: QRect @param iconGeometry: geometry of the tray icon @type iconGeometry: ...
a65cb13d705c60691b28de7baa5c36c7cd96e6ee
68,969
def Mprop(d): """ M = Mprop(d) ------------ ABCD matrix for free space propagation of distance d. """ return np.matrix([[1, d], [0, 1]])
4a858b9e953df2b5e5268664797975af1863c158
68,970
import typing import collections def with_argument( key: str, /, converters: _MaybeIterable[ConverterSig[typing.Any]] = (), *, default: _UndefinedOr[typing.Any] = UNDEFINED, greedy: bool = False, max_value: _UndefinedOr[_CmpProto[typing.Any]] = UNDEFINED, min_value: _UndefinedOr[_CmpPr...
b698f6601cef00d42a0116383eb202c38c1f84ab
68,971
def possible_values1(grid, r, c): """Return the possible values for a cell in the r,c position""" n = max([max(l) for l in grid]) h = len(grid) w = len(grid[0]) # ret = [] # count = [0 for i in range(n+1)] # for dx in [-1, 0, 1]: # for dy in [-1, 0, 1]: # if dx == 0 and ...
3537c90917c7975cffe6bdfd537a406077101a39
68,972
from typing import Optional from datetime import datetime def logins(page: int = 1, login_type: Optional[str] = None): """Shows log of login attempts. Args: page: Page number for results pagination login_type: Login type (unique, failed) """ if login_type is None: query = Logi...
1aec22c635e99194bea69b76ac421d4ae857d5c6
68,973
def job_header_template(sequence): """ Returns a string with the job header template including SBATCH environment variables for sequencerXX.py script Parameters ---------- sequence: sequence object Returns ------- header: str String with job header template """ pyth...
aed419d5e2ef1dbde6b62b12e74707e50c0b90d5
68,974
import networkx def plot_graph(val_matrix, var_names=None, fig_ax=None, figsize=None, sig_thres=None, link_matrix=None, save_name=None, link_colorbar_label='MCI', node_colorbar_label='auto-MCI', ...
3cb5e99a29307bf94d8f067663130a3d0a4f8985
68,975
def get_details_items(project): """Return recent files/links for card on project details page""" files = File.objects.filter(project=project).order_by('-date_modified')[:5] links = HyperLink.objects.filter(project=project).order_by( '-date_modified' )[:5] ret = list(files) + list(links) ...
6d2fd670c1f499690a674af96bf87f6f07668ce5
68,976
import requests def invoke_action(action_name, api_host, api_key, data=None, ignore_certs=True, web=False): """ usage: invoke_action('hello-world', os.environ['__OW_API_HOST'], os.environ['__OW_API_KEY']) """ if data is None: data = {} api_host = api_hos...
44bc871599e7fc74bbaf8693d9d8b7a313193973
68,979
from typing import Iterable def flatten(nested): """Flatten a nested sequence where the sub-items can be sequences or primitives. This differs slightly from itertools chain methods because those require all sub-items to be sequences. Here, items can be primitives, sequences, nested sequences, or any c...
464cd221dfaf6f842bf6da0d96ad8322d1c84e71
68,980
def prep_irrigation_pws_ratio() -> pd.DataFrame: """prepping the ratio of water flows to irrigation vs. water flows to public water supply by county. Used to determine the split of electricity in interbasin transfers between the two sectors. :return: DataFrame of percentages by county "...
519eb1484c824b0bd6266a586cf17bbf49c34e9b
68,981
def negotiate_rpl_connection(server, is_master=True, strict=True, options=None): """Determine replication connection This method attempts to determine if it is possible to build a CHANGE MASTER command based on the server passed. If it is possible, the method will return a ...
daa64f7c20a80476f99c14ef88b75dd71adc234b
68,982
def __mailing_callback(update: Update, language_code): """show mailing menu""" text, reply_markup = __get_mailing_page(update.effective_user.id, language_code) cf.edit_message( update=update, text=text, reply_markup=reply_markup, ) return consts.PARAMETERS_MAIN_STATE
c557bee58d4684b323489a87a296fec7c7514b31
68,983
def populate_skills(request): """ This api populates dummy data in skills table """ skills = ['ruby on rails',"kafka","aws","python","django","mysql","mongodb","php","laravel","flask","html","javascript","jquery","css","dotnet","c++","c#"] for skill in skills: Skill.objects.create(name=ski...
91ffa96ecd54061e0c521e5c0ca420f336b9cff7
68,984
def _literal_params(params): """ Converts string parsed-params into a dicitionary """ if isinstance(params, dict): return params params = literal_eval(params) if params else {} if not isinstance(params, dict): abort(400, "Parsed params are not a valid map (dict)") return par...
57ca560429c8eae32916a54fd8023befdea13fe7
68,986
def create_computation_graph(num_lemmas, num_pos, num_dep, num_directions, num_relations, wv=None, num_hidden_layers=0): """ Initialize the model :param num_lemmas Number of distinct lemmas :param num_pos Number of distinct part of speech tags :param num_dep Number of distinct depenedency labels ...
131163c3e3c61a8e9dc10ec6355e340378a6ba4d
68,987
def get_update_from_args(args): """Find bot and update instance in the given args. Args: args(iterable): arguments to search for the bot and update. Returns: telegram.Update. instance of update that found in args. """ update = find_instance_in_args(telegram.update.Update, args) ...
ba72c8777909e61277b1439ec21f7f043fe95c7c
68,988
import warnings import traceback def render_tasks(write, tasks, field_limit=0, ignored_fields=None, human_readable=False, colorize=None, write_err=None, format_node=format_node, format_value=None, utc_timestamps=True, colorize_tree=False, ascii=False, ...
870cf69d6f594618be267de7d77544b6219aea11
68,989
from re import S def sub_post(e): """ Replace 1*-1*x with -x. """ replacements = [] for node in preorder_traversal(e): if isinstance(node, Mul) and \ node.args[0] is S.One and node.args[1] is S.NegativeOne: replacements.append((node, -Mul._from_args(node.args[2:]))) ...
c788adf09cedb8bba5a4405b17f54c1fc5932b7f
68,993
import array def seq2list(seq,result=None): """Given an OpenCV sequence object representing contours, returns a list of 2D point arrays.""" if result is None: result = [] while seq: l = list(seq) result.append(array(l,'i')) # sub = seq2list(seq.v_next(),result) seq = se...
aa6070b44b6c07fe6de25264ef2977b28d769589
68,994
def Rpost2M(radius, unit='Earth', grid_size = 1e3, classify = 'No'): """ Forecast the mass distribution given the radius distribution. Parameters --------------- radius: one dimensional array The radius distribution. unit: string (optional) Unit of the mass. Options are 'Earth' and 'Jupiter'. grid_size: int...
f5567a03edae59a326fd7c4cad9d6e91c237a5da
68,995
def all_sample_fractions(array, iterations=100, fractions=[0.1,0.15,0.2,0.25], compression=[50,50], background=np.nan): """ Generates a 4D array of several samples; the first axis allows choice of the fraction of each sampling; the second axis allows for each iteration of this fract...
c265f32eab6570bd23a3705bc42281cae3b9c847
68,996
def load_hdf5_array(object, node, array_attribute, tag = 'Values'): """Loads the property array data as an attribute of object, from the hdf5 referenced in xml node. :meta private: """ assert (rqet.node_type(node) in ['DoubleHdf5Array', 'IntegerHdf5Array', 'Point3dHdf5Array']) # ignore null value ...
867a08ea81159e5ac12351ac279aa18cbea6ab35
68,997
def test_model_tester(clf,my_dataset,featurs_list): """ This function will test our model into the tester file """ tester.dump_classifier_and_data(clf, my_dataset, features_list) return tester.main()
5ae1fb0d5d47eb0746fa8cc842c37bf7eb5a179f
68,999
def transaction(session: Session, nested: bool = False): """Auto transaction commit or rollback. This worked with ``session.autocommit=False`` (the default behavior of ``flask-sqlalchemy``) or ``session.autocommit=True``. See more: http://flask-sqlalchemy.pocoo.org/2.3/api/#sessions Tips: *...
65b27a8406157547cb6351c5f339fe404e894996
69,000
def update_talk_tags(talk, talk_json_data): """ Updates tags associated to this model instance """ tags = [] if "snippet" in talk_json_data: snippet = talk_json_data["snippet"] if "tags" in snippet: tags += snippet["tags"] for tag in tags: talk.tags.add(tag) ...
356bb6d1c25f2ea0499cf9f31768a9090d0f8180
69,001
def multi_callback_factory(callback_factories, **kwargs): """ A :func:`callback_factory` which multiplexes the messages Parameters ---------- callback_factories : iterable of :func:`callback_factory` The callback to use to issue the message Return ------ :func:`multi_callback` ...
65d052c51768897bb83d138bb27e300c1035e1fb
69,002
def calculadora(x = 1, y = 1): # Docstring """ Calculadora ----------- Cria um dicionário com as principais operações matemáticas, dado dois números. args ---- x : int ou float Primeiro número de entrada y : int ou float Segundo número de entrada re...
6fad4c8c1d388cb5b77c52d68f63a37070379657
69,003
def tmp_list_config(tmp_config) -> Config: """A temporary config for the list plugin with the cli.""" return tmp_config('default_plugins = ["cli", "list"]')
0afbe64b31f96d5fbeb2131a3785d920fcab594c
69,004
def center2corner(center): """ convert (cx, cy, w, h) to (x1, y1, x2, y2) Args: center: Center or np.array (4 * N) Return: center or np.array (4 * N) """ if isinstance(center, Center): x, y, w, h = center return Corner(x - w * 0.5, y - h * 0.5, x + w * 0.5, y + h * 0....
18dcf614a4115e8cab26e31bfecde5b623ef454d
69,005
from typing import Optional def log_softmax(tensor: MPCTensor, dim: Optional[int] = None) -> MPCTensor: """Applies a softmax followed by a logarithm. While mathematically equivalent to log(softmax(x)), doing these two operations separately is slower, and numerically unstable. This function uses an al...
2061b3ffac043a498661eda035f38eb68a3fd308
69,006
def unmold_mask_x(mask, bbox, image_shape): """Converts a mask generated by the neural network into a format similar to its original shape. mask: [height, width] of type float. A small, typically 28x28 mask. bbox: [y1, x1, y2, x2]. The box to fit the mask in. Returns a binary mask with the same siz...
75a344e92f549db147e5879c00caa4c1ab6051a6
69,007
def broadening(f,dm,model="B",dalpha=0): """ Pulse broadeing due to interstellar scattering The model is taken from Bhat et al., Ap.J. 605, 759 (2004), eqn. 7. The coefficients, a = -6.46, b = 0.154, and c = 1.07, are only slightly different from those of Cordes & Lazio (2003), a = -6.59, b = 0.129, and c =...
f940f56f6fd5786adc839566f14bbf821f7e504b
69,008
def get_queue_cluster_config(cluster_name, cluster_type): """ 获取队列集群信息 :param cluster_name: 集群名称 :param cluster_type: 集群类型(kafka/pulsar) :return: 队列集群信息 """ try: return QueueClusterConfig.objects.get(cluster_name=cluster_name, cluster_type=cluster_type) except QueueClusterConfig....
474141a542abcf662d4582505ae2ac995d28f9fb
69,009