content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def first_order_smoothness_loss( image, flow, edge_weighting_fn): """Computes a first-order smoothness loss. Args: image: Image used for the edge-aware weighting [batch, height, width, 2]. flow: Flow field for with to compute the smoothness loss [batch, height, width, 2]. edge_weighting_f...
92e0eb047bb9d5d67a32c8ba7a601e4b7c0333b8
13,151
def where_is_my_birthdate_in_powers_of_two(date: int) -> int: """ >>> where_is_my_birthdate_in_powers_of_two(160703) <BLANKLINE> Dans la suite des <BLANKLINE> 0 1 3 765 2 , 2 , 2 , …, 2 <BLANKLINE> Ta date de naissance apparaît ici!: <BLANKLINE> …568720026062381...
656e7c76c849ba4348a5499a1c5cbd02574db011
13,152
def make_df_health_all(datadir): """ Returns full dataframe from health data at specified location """ df_health_all = pd.read_csv(str(datadir) + '/health_data_all.csv') return df_health_all
c9fe0efe65f4455bc9770aa621bed5aaa54fb47f
13,153
def lothars_in_cv2image(image, lothars_encoders,fc): """ Given image open with opencv finds lothars in the photo and the corresponding name and encoding """ # init an empty list for selfie and corresponding name lothar_selfies=[] names=[] encodings=[] # rgb image rgb = cv2....
be869c922299178dd3f4835a6fd547c779c4e11a
13,154
def approx_nth_prime_upper(n): """ approximate upper limit for the nth prime number. """ return ceil(1.2 * approx_nth_prime(n))
9cfebe3c1dbac176fe917f97664b287b8024c5d4
13,155
def wavelength_to_velocity(wavelengths, input_units, center_wavelength=None, center_wavelength_units=None, velocity_units='m/s', convention='optical'): """ Conventions defined here: http://www.gb.nrao.edu/~fghigo/gbtdoc/doppler.html * Radio V = c (c/l0 - c/l)/(c/l0) f(V) = (c/l0) ( 1...
ffa1c1bb69a7f6767efcd2f5494da43847a80d3b
13,156
import json def gen_api_json(api): """Apply the api literal object to the template.""" api = json.dumps( api, cls=Encoder, sort_keys=True, indent=1, separators=(',', ': ') ) return TEMPLATE_API_DEFINITION % (api)
d9acea9483199746a9c97d905f06b17f20bff18c
13,157
import copy from bs4 import BeautifulSoup import re def get_massage(): """ Provide extra data massage to solve HTML problems in BeautifulSoup """ # Javascript code in ths page generates HTML markup # that isn't parsed correctly by BeautifulSoup. # To avoid this problem, all document.write frag...
b2a7555b48f4a208545ffb75a4cc36c8c43a1eb7
13,158
def generate_test_images(): """Generate all test images. Returns ------- results: dict A dictionary mapping test case name to xarray images. """ results = {} for antialias, aa_descriptor in antialias_options: for canvas, canvas_descriptor in canvas_options: for fu...
d4de85956dfae0cc7d5405b55c21a5063c4dc2c6
13,159
from typing import Dict from typing import Type import copy def registered_metrics() -> Dict[Text, Type[Metric]]: """Returns standard TFMA metrics.""" return copy.copy(_METRIC_OBJECTS)
0311def576648d6e621d35e6ac89f8cda1302029
13,160
def text_dataset_construction(train_or_test, janossy_k, task, janossy_k2, sequence_len, all_data_size=0): """ Data Generation """ janossy_k = 1 janossy_k2 = 1 args = parse_args() task = str(args.task).lower() X = np.load('../data_'+str(task)+str(sequence_len)+'.npy') output_X = np.load('../label_'+str(task)+str(...
d55cdade5e2b9bd8a4a2d3ee1e80f0e15f390fc8
13,162
def neo_vis(task_id): """ Args: task_id: Returns: """ project = get_project_detail(task_id, current_user.id) return redirect( url_for( "main.neovis_page", port=project["remark"]["port"], pwd=project["remark"]["password"], ) )
cb0af50364e857d8febb8771abd0222a6d993b2e
13,163
def getfont( fontname=None, fontsize=None, sysfontname=None, bold=None, italic=None, underline=None): """Monkey-patch for ptext.getfont(). This will use our loader and therefore obey our case validation, caching and so on. """ fontname = fontname or ...
04f12244126efd8cf6f274991193a2d71f8797f5
13,164
def change_box(base_image,box,change_array): """ Assumption 1: Contents of box are as follows [x1 ,y2 ,width ,height] """ height, width, _ = base_image.shape new_box = [0,0,0,0] for i,value in enumerate(change_array): if value != 0: new_box[i] = box[i] + valu...
960b9f2c3ab1b65e9c7a708eac700dfaf65c67ac
13,165
def fetchRepositoryFilter(critic, filter_id): """Fetch a RepositoryFilter object with the given filter id""" assert isinstance(critic, api.critic.Critic) return api.impl.filters.fetchRepositoryFilter(critic, int(filter_id))
76aa247ddf63838ff16131d0d7f1a04092ef3c41
13,166
def load_it(file_path: str, verbose: bool = False) -> object: """Loads from the given file path a saved object. Args: file_path: String file path (with extension). verbose: Whether to print info about loading successfully or not. Returns: The loaded object. Raises: No...
59795488dffbc1a69556b2619e8502cfa23d6d63
13,167
def connect_contigs(contigs, align_net_file, fill_min, out_dir): """Connect contigs across genomes by forming a graph that includes net format aligning regions and contigs. Compute contig components as connected components of that graph.""" # construct align net graph and write net BEDs if align_net_fi...
dc262d7469f524d8b37eebc50787a6e687a1ff90
13,168
import torch import time def train(loader, model, crit, opt, epoch): """Training of the CNN. Args: loader (torch.utils.data.DataLoader): Data loader model (nn.Module): CNN crit (torch.nn): loss opt (torch.optim.SGD): optimizer for every parameters with True ...
64a8213d103f57b3305060b42f41c94a3d710759
13,169
def add_scatter(x, scatter, in_place=False): """ Add a Gaussian scatter to x. Parameters ---------- x : array_like Values to add scatter to. scatter : float Standard deviation (sigma) of the Gaussian. in_place : bool, optional Whether to add the scatter to x in place...
27c1423441f7841284201afd873c2c6050812d5f
13,171
def validate_job_state(state): """ Validates whether a returned Job State has all the required fields with the right format. If all is well, returns True, otherwise this prints out errors to the command line and returns False. Can be just used with assert in tests, like "assert validate_job_state(st...
f108b7a80dee7777931aae994384d47f4a474d67
13,172
def get_urls(session): """ Function to get all urls of article in a table. :param session: session establishes all conversations with the database and represents a “holding zone”. :type session: sqlalchemy.session :returns: integer amount of rows in table """ url = session.query(Article.url...
ad5e4797c1a41c63ef225becaee1a9b8814a3ea2
13,173
def bboxes_protection(boxes, width, height): """ :param boxes: :param width: :param height: :return: """ if not isinstance(boxes, np.ndarray): boxes = np.asarray(boxes) if len(boxes) > 0: boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, width - 1) boxes[:, [1, 3]] ...
8ab0c64788815f6ec66f42c90a4c2debc0627548
13,175
def mark_astroids(astroid_map): """ Mark all coordiantes in the grid with an astroid (# sign) """ astroids = [] for row, _ in enumerate(astroid_map): for col, _ in enumerate(astroid_map[row]): if astroid_map[row][col] == "#": astroid_map[row][col] = ASTROID ...
36ac179f1cbc040142bea8381c4c85f90c81ecba
13,176
def process_player_data( prefix, season=CURRENT_SEASON, gameweek=NEXT_GAMEWEEK, dbsession=session ): """ transform the player dataframe, basically giving a list (for each player) of lists of minutes (for each match, and a list (for each player) of lists of ["goals","assists","neither"] (for each mat...
dcbf210242509fa3df1ae5ca35614d802c460381
13,177
def copy_to_table(_dal, _values, _field_names, _field_types, _table_name, _create_table=None, _drop_existing=None): """Copy a matrix of data into a table on the resource, return the table name. :param _dal: An instance of DAL(qal.dal.DAL) :param _values: The a list(rows) of lists(values) with values to be ...
765ae0310811fe64b063c88182726174411960a0
13,178
from scipy.optimize import minimize def Uni(A, b, x=None, maxQ=False, x0=None, tol=1e-12, maxiter=1e3): """ Вычисление распознающего функционала Uni. В случае, если maxQ=True то находится максимум функционала. Parameters: A: Interval Матрица ИСЛАУ. ...
d81f8f38e4b2f196c79eaaa00c1b604cf119b1bb
13,180
def boqa(alpha, beta, query, items_stat): """Implementation of the BOQA algorithm. Args: alpha (float): False positive rate. beta (float): False negative rate. query (dict): Dict of query terms (standard terms). Key: term name, value: presence value items_stat (dict): Dictionnar...
37ea565fa05b4a9bceeeb50f31e79394e9534966
13,181
from operator import inv def d2c(sys,method='zoh'): """Continous to discrete conversion with ZOH method Call: sysc=c2d(sys,method='log') Parameters ---------- sys : System in statespace or Tf form method: 'zoh' or 'bi' Returns ------- sysc: continous system ss or tf ...
41bb37fcf5b8726b5f20f54f492a568f508725fc
13,182
import ipaddress def ipv4(value): """ Parses the value as an IPv4 address and returns it. """ try: return ipaddress.IPv4Address(value) except ValueError: return None
499918424fe6a94d555379b5fc907367666f1cde
13,183
from typing import Callable from typing import Mapping from typing import cast from typing import Any def test_from( fork: str, ) -> Callable[ [Callable[[], StateTest]], Callable[[str], Mapping[str, Fixture]] ]: """ Decorator that takes a test generator and fills it for all forks after the specifi...
6c8704978c3ab37bb2ad8434b65359683bd76bbb
13,184
import hashlib def get_hash_name(feed_id): """ 用户提交的订阅源,根据hash值生成唯一标识 """ return hashlib.md5(feed_id.encode('utf8')).hexdigest()
edd1caf943635a091c79831cc6151ecfa840e435
13,185
from typing import Dict from typing import Counter def merge_lineages(counts: Dict[str, int], min_count: int) -> Dict[str, str]: """ Given a dict of lineage counts and a min_count, returns a mapping from all lineages to merged lineages. """ assert isinstance(counts, dict) assert isinstance(min...
3eea022d840e4e61d46041dffb188cbd73ed097b
13,187
def str2bool(s): """特定の文字列をbool値にして返す。 s: bool値に変換する文字列(true, false, 1, 0など)。 """ if isinstance(s, bool): return s else: s = s.lower() if s == "true": return True elif s == "false": return False elif s == "1": return True ...
54b991e234896c0ad684ce5f0f2ccceeada65d8e
13,188
def show_map_room(room_id=None): """Display a room on a map.""" return get_map_information(room_id=room_id)
84c1e90ce5b0a210b75f104da429f03dff7b2ca1
13,191
def parse_line_regex(line): """Parse raw data line into list of floats using regex. This regex approach works, but is very slow!! It also requires two helper functions to clean up malformed data written by ls-dyna (done on purpose, probably to save space). Args: line (str): raw data line from...
b8b18a8d47f5f1c9a682ca86668bf311282b0439
13,193
def create_page_metadata(image_dir, image_dir_path, font_files, text_dataset, speech_bubble_files, speech_bubble_tags): """ This function creates page metadata for a single page. It inclu...
45499abf5374c8eaaa55a03f8ef0bb7fca6e18f5
13,194
def __merge_results( result_list: tp.List[tp.Dict[str, tp.Dict[str, tp.Set[tp.Union[CVE, CWE]]]]] ) -> tp.Dict[str, tp.Dict[str, tp.Set[tp.Union[CVE, CWE]]]]: """ Merge a list of results into one dictionary. Args: result_list: a list of ``commit -> cve`` maps to be merged Return: t...
685ce8e22483fc1dfe423763367857db22065a3c
13,195
def compactness(xyz): """ Input: xyz Output: compactness (V^2/SA^3) of convex hull of 3D points. """ xyz = np.array(xyz) ch = ConvexHull(xyz, qhull_options="QJ") return ch.volume**2/ch.area**3
b1185e8aaec5962e39866594aeccdd5d5ae2807d
13,196
def guide(batch, z_dim, hidden_dim, out_dim=None, num_obs_total=None): """Defines the probabilistic guide for z (variational approximation to posterior): q(z) ~ p(z|q) :param batch: a batch of observations :return: (named) sampled z from the variational (guide) distribution q(z) """ assert(jnp.ndim(...
1198ee7b12bed9118d7bb865ed45ff10eef917d4
13,198
def trip2str(trip): """ Pretty-printing. """ header = "{} {} {} - {}:".format(trip['departureTime'], trip['departureDate'], trip['origin'], trip['destination']) output = [header] for subtrip in trip['trip']: originstr = u'...
67daf3feb6b81d40d3102a8c610b20e68571b131
13,199
def station_suffix(station_type): """ Simple switch, map specific types on to single letter. """ suffix = ' (No Dock)' if 'Planetary' in station_type and station_type != 'Planetary Settlement': suffix = ' (P)' elif 'Starport' in station_type: suffix = ' (L)' elif 'Asteroid' in statio...
c28c4d3f0da8401ffc0721a984ec2b2e2cd50b24
13,200
def temperatures_equal(t1, t2): """Handle 'off' reported as 126.5, but must be set as 0.""" if t1 == settings.TEMPERATURE_OFF: t1 = 0 if t2 == settings.TEMPERATURE_OFF: t2 = 0 return t1 == t2
5c054d23317565e474f6c8d30b7d87c0b832fe9f
13,201
import csv def import_capitals_from_csv(path): """Imports a dictionary that maps country names to capital names. @param string path: The path of the CSV file to import this data from. @return dict: A dictionary of the format {"Germany": "Berlin", "Finland": "Helsinki", ...} """ capitals = {} ...
3c6a9c91df455cb8721371fe40b248fb7af8d866
13,203
def deg_to_qcm2(p, deg): """Return the center-of-momentum momentum transfer q squared, in MeV^2. Parameters ---------- p_rel = float relative momentum given in MeV. degrees = number angle measure given in degrees """ return (p * np.sqrt( 2 * (1 ...
4b1840a8c672b443ac1954c0bde0a81a01338862
13,205
from django.conf import settings def i18n(request): """ Set client language preference, lasts for one month """ next = request.META.get('HTTP_REFERER', None) if not next: next = settings.SITE_ROOT lang = request.GET.get('lang', 'en') res = HttpResponseRedirect(next) res....
a56289c03b14b76719fc31bcee7e0e4e590f47ef
13,206
import random def normal222(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2): """ for source and destination id generation """ """ for type of banking work,label of fraud and type of fraud """ idvariz=random.choice(bb3)...
5d0a4cfbd5e7ef3223cc67c4759967e86c4081c8
13,208
def _convert_to_coreml(tf_model_path, mlmodel_path, input_name_shape_dict, output_names): """ Convert and return the coreml model from the Tensorflow """ model = tf_converter.convert(tf_model_path=tf_model_path, mlmodel_path=mlmodel_path, out...
b7266a1afe0f03717a8e710f9099a0349cc5b085
13,209
def _tavella_randell_nonuniform_grid(x_min, x_max, x_star, num_grid_points, alpha, dtype): """Creates non-uniform grid clustered around a specified point. Args: x_min: A real `Tensor` of shape `(dim,)` specifying the lower limit of the grid. x_max: A real `Tensor`...
6c209871b3a8aba291b00a513056d5e1ebe111f8
13,210
import uuid def tourme_details(): """ Display Guides loan-details """ return render_template('tourme_details.html', id=str(uuid.uuid4()))
e332546257670bd26d08be8baf4122f93feab170
13,212
import json def gen_dot_ok(notebook_path, endpoint): """ Generates .ok file and return its name Args: notebook_path (``pathlib.Path``): the path to the notebook endpoint (``str``): an endpoint specification for https://okpy.org Returns: ``str``: the name of the .ok fi...
850827a3da476cc64bd50c40c2504d9765b25dfe
13,213
def sarig_methods_wide( df: pd.DataFrame, sample_id: str, element_id: str, ) -> pd.DataFrame: """Create a corresponding methods table to match the pivoted wide form data. .. note:: This requires the input dataframe to already have had methods mapping applied by running ``pygeochemtools.geoc...
95d969213de0702f3a6666e8e13ae2d37e404e3a
13,214
def vflip_box(box: TensorOrArray, image_center: TensorOrArray) -> TensorOrArray: """Flip boxes vertically, which are specified by their (cx, cy, w, h) norm coordinates. Reference: https://blog.paperspace.com/data-augmentation-for-bounding-boxes/ Args: box (TensorOrArray[B, 4]): Bo...
99128e7b6d928c1b58457fc6d51b971c109cc77e
13,216
import pathlib def example_data(): """Example data setup""" tdata = ( pathlib.Path(__file__).parent.absolute() / "data" / "ident-example-support.txt" ) return tdata
a8c9a88f8850fecc7cc05fb8c9c18e03778f3365
13,217
def add_ending_slash(directory: str) -> str: """add_ending_slash function Args: directory (str): directory that you want to add ending slash Returns: str: directory name with slash at the end Examples: >>> add_ending_slash("./data") "./data/" """ if directory[-...
2062a55b59707dd48e5ae56d8d094c806d8a2c1d
13,218
import scipy def antenna_positions(): """ Generate antenna positions for a regular rectangular array, then return baseline lengths. - Nx, Ny : No. of antennas in x and y directions - Dmin : Separation between neighbouring antennas """ # Generate antenna positions on a regular grid x...
f47a0c887489987d8fc95205816459db55bbaa19
13,219
from typing import Union from typing import List def folds_to_list(folds: Union[list, str, pd.Series]) -> List[int]: """ This function formats string or either list of numbers into a list of unique int Args: folds (Union[list, str, pd.Series]): Either list of numbers or one str...
f499cce7992b77867fc3a7d95c8dd6efc83c3c79
13,220
import gc def predict_all(x, model, config, spline): """ Predict full scene using average predictions. Args: x (numpy.array): image array model (tf h5): image target size config (Config): spline (numpy.array): Return: prediction scene array average probabilities...
6e5888b1d97c3a0924a67500c4b731fd00654cb2
13,221
def pre_arrange_cols(dataframe): """ DOCSTRING :param dataframe: :return: """ col_name = dataframe.columns.values[0] dataframe.loc[-1] = col_name dataframe.index = dataframe.index + 1 dataframe = dataframe.sort_index() dataframe = dataframe.rename(index=str, columns={col_name: 'a...
522c0f4ca29b10d4a736d27f07d8e9dc80cafba5
13,222
import numpy def wDot(x,y,h): """ Compute the parallel weighted dot product of vectors x and y using weight vector h. The weighted dot product is defined for a weight vector :math:`\mathbf{h}` as .. math:: (\mathbf{x},\mathbf{y})_h = \sum_{i} h_{i} x_{i} y_{i} All weight vector ...
e9bcc295517060f95004aec581055950358c9521
13,223
def dataframify(transform): """ Method which is a decorator transforms output of scikit-learn feature normalizers from array to dataframe. Enables preservation of column names. Args: transform: (function), a scikit-learn feature selector that has a transform method Returns: new_t...
cf21bb7aea90e742c83fb5e1abb41c5d01cddf4e
13,224
def plot_map(self, map, update=False): """ map plotting Parameters ---------- map : ndarray map to plot update : Bool updating the map or plotting from scratch """ if update: empty=np.empty(np.shape(self.diagnostics[self.diagnostic])) empty[:]=np.nan ...
a4effd8c7e958b694f2c01afdaa861455c855a0b
13,225
def definition_activate(connection, args): """Activate Business Service Definition""" activator = sap.cli.wb.ObjectActivationWorker() activated_items = ((name, sap.adt.ServiceDefinition(connection, name)) for name in args.name) return sap.cli.object.activate_object_list(activator, activated_items, coun...
61dd5de0d8e24339c67363e904628390cc79b1da
13,226
import re def extractCompositeFigureStrings(latexString): """ Returns a list of latex figures as strings stripping out captions. """ # extract figures figureStrings = re.findall(r"\\begin{figure}.*?\\end{figure}", latexString, re.S) # filter composite figures only and remove captions (preserv...
83a80c91890d13a6a0247745835e1ffb97d579f7
13,227
import time def osm_net_download( polygon=None, north=None, south=None, east=None, west=None, network_type="all_private", timeout=180, memory=None, date="", max_query_area_size=50 * 1000 * 50 * 1000, infrastructure='way["highway"]', ): """ Download OSM ways and ...
faf949e015c365c3822131634f55c73e2e9fef0c
13,228
from re import S def rubi_integrate(expr, var, showsteps=False): """ Rule based algorithm for integration. Integrates the expression by applying transformation rules to the expression. Returns `Integrate` if an expression cannot be integrated. Parameters ========== expr : integrand expre...
25eccde81fe0425fbf35c522b24e79195684f537
13,230
def daily_price_read(sheet_name): """ 读取股票名称和股票代码 :param sheet_name: :return: """ sql = "SELECT * FROM public.%s limit 50000" % sheet_name resultdf = pd.read_sql(sql, engine_postgre) resultdf['trade_date'] = resultdf['trade_date'].apply(lambda x: x.strftime('%Y-%m-%d')) resultdf['cod...
d68c326604c21b6375e77fb012a9776d87be617f
13,231
def _isfloat(string): """ Checks if a string can be converted into a float. Parameters ---------- value : str Returns ------- bool: True/False if the string can/can not be converted into a float. """ try: float(string) return True except ValueError...
74ae50761852d8b22ac86f6b6332bd70e42bf623
13,232
def get(url, **kwargs): """ get json data from API :param url: :param kwargs: :return: """ try: result = _get(url, **kwargs) except (rq.ConnectionError, rq.ReadTimeout): result = {} return result
a3c17ce6ab383373e7215dd0e5b3e63130739126
13,233
def sample_indep(p, N, T, D): """Simulate an independent sampling mask.""" obs_ind = np.full((N, T, D), -1) for n in range(N): for t in range(T): pi = np.random.binomial(n=1, p=p, size=D) ind = np.where(pi == 1)[0] count = ind.shape[0] obs_ind[n, t, :c...
69a469d45040ed1598f7d946b6706f70f23dc580
13,234
def _relabel_targets(y, s, ranks, n_relabels): """Compute relabelled targets based on predicted ranks.""" demote_ranks = set(sorted(ranks[(s == 0) & (y == 1)])[:n_relabels]) promote_ranks = set(sorted(ranks[(s == 1) & (y == 0)])[-n_relabels:]) return np.array([ _relabel(_y, _s, _r, promote_ranks...
e8c06364a717210da6c0c60c883fee05d61ed3eb
13,235
def exp(x): """Take exponetial of input x. Parameters ---------- x : Expr Input argument. Returns ------- y : Expr The result. """ return call_pure_intrin(x.dtype, "exp", x)
9ec31c0b9928108680c2818d1fe110d36c81b08d
13,236
def check_table(words_in_block, block_width, num_lines_in_block): """ Check if a block is a block of tables or of text.""" # average_words_per_line=24 # total_num_words = 0 ratio_threshold = 0.50 actual_num_chars = 0 all_char_ws = [] cas = [] # total_num_words += len(line) if num_li...
46c785eefc7694a88d1814b9ca01f41fffa9d1f8
13,237
def defaultSampleFunction(xy1, xy2): """ The sample function compares how similar two curves are. If they are exactly the same it will return a value of zero. The default function returns the average error between each sample point in two arrays of x/y points, xy1 and xy2. Parameters -...
5654145e9a2d3701d289094ababc94d9ed972def
13,238
from re import S def makesubs(formula,intervals,values=None,variables=None,numden=False): """Generates a new formula which satisfies this condition: for all positive variables new formula is nonnegative iff for all variables in corresponding intervals old formula is nonnegative. >>> newproof() >>> makesubs('1-x^...
238923ac5e6e9e577f90091b61b6182323fdee75
13,239
def generateKey(accountSwitchKey=None,keytype=None): """ Generate Key""" genKeyEndpoint = '/config-media-live/v2/msl-origin/generate-key' if accountSwitchKey: params = {'accountSwitchKey': accountSwitchKey} params["type"] = keytype key = prdHttpCaller.getResult(genKeyEndpoint, params...
5da825d809fbb03b5929bcc14f0da0451eaf639a
13,240
def positions_count_for_one_ballot_item_doc_view(request): """ Show documentation about positionsCountForOneBallotItem """ url_root = WE_VOTE_SERVER_ROOT_URL template_values = positions_count_for_one_ballot_item_doc.positions_count_for_one_ballot_item_doc_template_values( url_root) templ...
3c56d186560fa8fae6117b6b656ee0c8d40a8728
13,241
def atcab_sign_base(mode, key_id, signature): """ Executes the Sign command, which generates a signature using the ECDSA algorithm. Args: mode Mode determines what the source of the message to be signed (int) key_id Private key slot used to sign the message. (int) ...
87c9770d6ba456947206ea1abb46b10a3f413811
13,242
from typing import List def load_gs( gs_path: str, src_species: str = None, dst_species: str = None, to_intersect: List[str] = None, ) -> dict: """Load the gene set file (.gs file). Parameters ---------- gs_path : str Path to the gene set file with the following two columns, s...
0e13c355b1a3bd7e88785844262a01c6963ef0ee
13,243
from .points import remove_close def sample_surface_even(mesh, count, radius=None): """ Sample the surface of a mesh, returning samples which are VERY approximately evenly spaced. This is accomplished by sampling and then rejecting pairs that are too close together. Parameters ---------...
9dd9c4aa27f4811511d81ef0c8dabe3097026061
13,244
def allocate_probabilities(results, num_substations, probabilities): """ Allocate cumulative probabilities. Parameters ---------- results : list of dicts All iterations generated in the simulation function. num_substations : list The number of electricity substation nodes we wis...
5692517aa55776c94c7f4027f175eab985000fe1
13,245
def delete_page_groups(request_ctx, group_id, url, **request_kwargs): """ Delete a wiki page :param request_ctx: The request context :type request_ctx: :class:RequestContext :param group_id: (required) ID :type group_id: string :param url: (required) ID :type url...
d9802d66e87eb0ef9e9fe5bee98686caade3e79d
13,247
def solver(f, p_e, mesh, degree=1): """ Solving the Darcy flow equation on a unit square media with pressure boundary conditions. """ # Creating mesh and defining function space V = FunctionSpace(mesh, 'P', degree) # Defining Dirichlet boundary p_L = Constant(1.0) def boundary_L(x, on...
0630b1199f064044976c24d825332aa2d879dab2
13,249
def set_stretchmatrix(coefX=1.0, coefY=1.0): """Stretching matrix Args: coefX: coefY:coefficients (float) for the matrix [coefX 0 0 coefY] Returns: strectching_matrix: matrix """ return np.array([[coefX, 0],[0, coefY]])
cd11bf0351a205e52b1f99893fe43709636978d3
13,250
def set_bit(v, index, x): """Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value.""" mask = 1 << index # Compute mask, an integer with just bit 'index' set. v &= ~mask # Clear the bit indicated by the mask (if x is False) if x: v |= mask # If x was True, set the...
627744c06709eecec18f0c5956f1af4c57a57b8a
13,251
def test_credentials() -> (str, str): """ Read ~/.synapseConfig and retrieve test username and password :return: endpoint, username and api_key """ config = _get_config() return config.get(DEFAULT_CONFIG_AUTH_SECTION, DEFAULT_CONFIG_USERNAME_OPT),\ config.get(DEFAULT_CONFIG_AUTH_SECT...
2ceb441b338b5ea8b1154c19406af9b1e21ed85e
13,252
import re def BCA_formula_from_str(BCA_str): """ Get chemical formula string from BCA string Args: BCA_str: BCA ratio string (e.g. 'B3C1A1') """ if len(BCA_str)==6 and BCA_str[:3]=='BCA': # format: BCAxyz. suitable for single-digit integer x,y,z funits = BCA_str[-3:] e...
36375e62d70995628e253ba68ba8b777eb88d728
13,253
import numpy def get_strongly_connected_components(graph): """ Get strongly connected components for a directed graph The returned list of components is in reverse topological order, i.e., such that the nodes in the first component have no dependencies on other components. """ nodes = lis...
42783756d8fdada032e2d0ca8a306f10d4977e16
13,254
def dot(a, b): """ Computes a @ b, for a, b of the same rank (both 2 or both 3). If the rank is 2, then the innermost dimension of `a` must match the outermost dimension of `b`. If the rank is 3, the first dimension of `a` and `b` must be equal and the function computes a batch matmul. Sup...
789c9d045d82eb048ff5319d5a7ae99ffb02376d
13,255
def unreshuffle_2d(x, i0, shape): """Undo the reshuffle_2d operation.""" x_flat = unreshuffle_1d(x, i0) x_rev = np.reshape(x_flat, shape) x_rev[1::2, :] = x_rev[1::2, ::-1] # reverse all odd rows return x_rev
72cf59b9e547cf2eb516fca33e9eea7d01c1702b
13,256
def findNodeJustBefore(target, nodes): """ Find the node in C{nodes} which appeared immediately before C{target} in the input document. @type target: L{twisted.web.microdom.Element} @type nodes: C{list} of L{twisted.web.microdom.Element} @return: An element from C{nodes} """ result = No...
85d435a2c10dbaabb544c81d440e2110a6083dd7
13,257
def _format_line(submission, position, rank_change, total_hours): """ Formats info about a single post on the front page for logging/messaging. A single post will look like this: Rank Change Duration Score Flair Id User Slug 13. +1 10h 188 [Episode](gkvlja) <AutoLovepon> <...
70840d0e57194b43fbaf0352ebecdfefa74bd4d7
13,258
from typing import List from typing import Dict from typing import Any from typing import Tuple def run_erasure( # pylint: disable = too-many-arguments privacy_request: PrivacyRequest, policy: Policy, graph: DatasetGraph, connection_configs: List[ConnectionConfig], identity: Dict[str, Any], a...
2b9579ca1c4960da46ee7bb1388ab667dc808f40
13,259
def RichTextBuffer_FindHandlerByName(*args, **kwargs): """RichTextBuffer_FindHandlerByName(String name) -> RichTextFileHandler""" return _richtext.RichTextBuffer_FindHandlerByName(*args, **kwargs)
1122822db4885b6d745f4e893522fb01b988ee3f
13,261
def likelihood(tec, phase, tec_conversion, lik_sigma, K = 2): """ Get the likelihood of the tec given phase data and lik_var variance. tec: tensor B, 1 phase: tensor B, Nf tec_conversion: tensor Nf lik_sigma: tensor B, 1 (Nf) Returns: log_prob: tensor (B,1) """ mu = wrap(tec*tec_...
c5f566484ee8f8cbc48e5302365f0e06c81f49e3
13,262
def angle_between(v1, v2): """Returns the angle in radians between vectors 'v1' and 'v2':: >>> angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 >>> angle_between((1, 0, 0), (1, 0, 0)) 0.0 >>> angle_between((1, 0, 0), (-1, 0, 0)) 3.141592653589793 """ # https://stackoverflow.co...
fc2246c9d3fb55a0c2f692c1533e821a187599b8
13,263
from aiida.engine import ExitCode from ase.lattice.cubic import FaceCenteredCubic from ase.lattice.cubic import BodyCenteredCubic def create_substrate_bulk(wf_dict_node): """ Calcfunction to create a bulk structure of a substrate. :params wf_dict: AiiDA dict node with at least keys lattice, host_symbol a...
cb232093c3f6866bd14d2b19115ef988f279bf2f
13,264
def run_Net_on_multiple(patchCreator, input_to_cnn_depth=1, cnn = None, str_data_selection="all", save_file_prefix="", apply_cc_filtering = False, output_filetype = 'h5', save_prob_map = False): """ run runNetOnSlice() on neighbouring blocks of data. if opt_...
9d4c9c2fa3248258299243e3d7585362f47776a2
13,265
def user_to_janrain_capture_dict(user): """Translate user fields into corresponding Janrain fields""" field_map = getattr(settings, 'JANRAIN', {}).get('field_map', None) if not field_map: field_map = { 'first_name': {'name': 'givenName'}, 'last_name': {'name': 'familyName'},...
767b7003a282e481c1d1753f4c469fec42a5002a
13,266
from typing import Callable from typing import Optional from typing import Generator def weighted(generator: Callable, directed: bool = False, low: float = 0.0, high: float = 1.0, rng: Optional[Generator] = None) -> Callable: """ Takes as input a graph generator and returns a new generator functi...
d4c4d0b93784ca7bee22ecaffc3e8005315aa631
13,267
def generate_sampled_graph_and_labels(triplets, sample_size, split_size, num_rels, adj_list, degrees, negative_rate,tables_id, sampler="uniform"): """Get training graph and signals First perform edge neighborhood sampling on graph, then...
7386eada0e0aa70478c063aa4525c62cbc997b2e
13,269