content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_all_snapshots(volume_ids): """ Creates the snapshots of all volumes in the provided list. Params: volume_ids (list): List of volumes attached to the instance Returns: None """ for i in volume_ids: snapshot(i) return True
c985bdce6b11e85cedb3d8951447fdf234e3aeb4
27,964
def stack_subsample_frames(x, stacking=1, subsampling=1): """ Stacks frames together across feature dim, and then subsamples x.shape: FEAT, TIME output FEAT * stacking, TIME / subsampling """ # x.shape: FEAT, TIME seq = [] x_len = tf.shape(x)[1] for n in range(0, stacking): tm...
6cab964588d01cdecec1862cd3c1db681923d20d
27,965
def compute_TVL1(prev, curr, TVL1, bound=20): """ Args: prev (numpy.ndarray): a previous video frame, dimension is `height` x `width`. curr (numpy.ndarray): a current video frame, dimension is `height` x `width`. bound (int): specify the maximum and minimux of op...
94d83e0cbfc8e20ed78ba0ab3763d5ddd4e2859a
27,966
def _fetch_all_namespace_permissions(cursor): """ Fetches all user-namespace-permissions mapping registered with Herd :param: cursor to run hive queries :return: list of all users that have READ on each respective namespace """ namespaces = _fetch_all_namespaces() user_namespace_permissions...
0802b81a8d731cabbd51b1d3699c0ce64ac6c64a
27,967
def for_in_right(obj, callback=None): """This function is like :func:`for_in` except it iterates over the properties in reverse order. Args: obj (list|dict): Object to process. callback (mixed): Callback applied per iteration. Returns: list|dict: `obj`. Example: >...
6d85f7245cd454be61015ca69e1844d1dc830c86
27,968
def metadata_fake(batch_size): """Make a xr dataset""" # get random OSGB center in the UK lat = np.random.uniform(51, 55, batch_size) lon = np.random.uniform(-2.5, 1, batch_size) x_centers_osgb, y_centers_osgb = lat_lon_to_osgb(lat=lat, lon=lon) # get random times t0_datetimes_utc = make_t...
fa55cb231e013f3b5c4193af9c5cfff6f79fce82
27,969
def delete_document(ix: str, docid: str): """ delete a document PUT request body should be a json {field: value} mapping of fields to update """ check_role(Role.WRITER, _index(ix)) try: elastic.delete_document(ix, docid) except elasticsearch.exceptions.NotFoundError: abort(4...
a87c7c23b31ce24da83b81e8d241d4173542a930
27,970
def sentence_segment(doc, candidate_pos): """Store those words only in cadidate_pos""" sentences = [] for sent in doc.sents: selected_words = [] for token in sent: # Store words only with cadidate POS tag if token.pos_ in candidate_pos and token.is_stop is False and l...
6c56d47470e60edddfedfeb476aa7833be765218
27,971
def get_speckle_spatial_freq(image, pos, cx, cy, lambdaoverd, angle=None): """ returns the spatial frequency of the speckle defined in the area of aperture mask """ """ lambdaoverd = nb of pixels per lambda/D """ nx, ny =image.shape[0], image.shape[1] k_xy = (np.roll(pos,1,axis=0)-[cx,cy])/lambdaoverd ...
beace113642545f74ba3a49a4a15b0308d0f4535
27,972
def verify_ping( device, address, loss_rate=0, count=None, max_time=30, check_interval=10): """ Verify ping loss rate on ip address provided Args: device ('obj'): Device object address ('str'): Address value loss_rate ('int...
df19e0815a49388189bf480623c156b9992a2fe2
27,973
def get_default(key): """ get the default value for the specified key """ func = registry.defaults.get(key) return func()
081588445955da66d9988e962d2a360ed1193240
27,975
from typing import List def antisymmetric(r: Relation) -> (bool, List): """Kiểm tra tính phản xứng của r""" antisymmetric_tuple = [] for x, y in r: if x == y: continue if (y, x) in r: return False, [((x, y), (y, x))] antisymmetric_tuple.append(((x, y), (y, x...
d7a7900192850a9b86a56263fec5daea551a034f
27,976
def calc_negative_predictive_value(cause, actual, predicted): """Calculate negative predictive value (NPV) for a single cause Negative predictive value is the number of prediction correctly determined to not belong to the given cause over the total number of predicted to not be the cause: .. math:...
f89976fc5ec9c03e5d8d42a8265ba92e87d91ec8
27,977
def print_atom_swap(swap): """Return atom swap string for DL CONTROL""" return "{} {}".format(swap["id1"], swap["id2"])
4c2fa18434e7a66b98b9716b89a26b622b588cd6
27,978
def dot_product_area_attention(q, k, v, bias, dropout_rate=0.0, image_shapes=None, name=None, attention...
947864002406597931c663340e1a258ac2ae5bed
27,980
def random_transform(x, seed=None): """Randomly augment a single image tensor. # Arguments x: 3D tensor, single image. seed: random seed. # Returns A randomly transformed version of the input (same shape). """ np.random.seed(seed) img_row_axis = 0 img_col_axis = 1 ...
9f0b09dd4c5b0a0f9f00ae15682a27645894b064
27,983
def global_avg_pooling_forward(z): """ 全局平均池化前向过程 :param z: 卷积层矩阵,形状(N,C,H,W),N为batch_size,C为通道数 :return: """ return np.mean(np.mean(z, axis=-1), axis=-1)
f12efc7bd368af81164246fcb39a27f9de7e122d
27,985
def label_encoder(adata): """ Encode labels of Annotated `adata` matrix using sklearn.preprocessing.LabelEncoder class. Parameters ---------- adata: `~anndata.AnnData` Annotated data matrix. Returns ------- labels: numpy nd-array Array of encoded labels """ le = ...
421aa578a965b2e8e66204a368e1c42348148ef6
27,987
def is_plus_or_minus(token_type: TokenType) -> bool: """Check if token is a plus or minus.""" return is_plus(token_type) or is_minus(token_type)
1f0210505e8e882f07380ffd0d412a62f1d4d44f
27,988
def gen_data(test_size=TEST_SIZE, channels=CHANNELS, width=WIDTH, height=HEIGHT, mmean=0, vmean=1, channel_last=False, fc_output=False): """ Generate random data to pass through the layer NOTE: - The generated data should not be normal, so that the layer can try to ...
0030330bf93d6abb34f41575aaf1f45a52199393
27,989
from typing import Union from typing import List def plot_r2_pvalues( model: mofa_model, factors: Union[int, List[int], str, List[str]] = None, n_iter: int = 100, groups_df: pd.DataFrame = None, group_label: str = None, view=0, fdr: bool = True, cmap="binary_r", **kwargs, ): ""...
784a5333514a270bdf69960fa1a857668b414e5a
27,990
import itertools def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None, pred_labels=None, title=None, normalize=False, hide_zeros=False, x_tick_rotation=0, ax=None, figsize=None, cmap='Blues', title_fontsize="large", ...
f2f690a410d933ecdffee1898b9d991482a5eb67
27,991
def _check_lfs_hook(client, paths): """Pull the specified paths from external storage.""" return client.check_requires_tracking(*paths)
403b3db59f6eeec72c8f4a3b18808997b0f34724
27,992
def name_to_zamid(name): """Converts a nuclide's name into the nuclide's z-a-m id. Parameters ---------- name: str Name of a nuclide """ dic = d.nuc_name_dic elt_name = name.split('-')[0] na = int(name.split('-')[1].replace('*','')) if '*' in name: state = 1 ...
89129a288a93c96f3e24003b6dee2adba81dc935
27,994
def sample_category(name): """Create and return a sample category""" return models.Category.objects.create(name=name)
b9b38954520611ca7808592200ebf871da90bab6
27,995
def plan_add(request): """ 测试计划添加 :param request: :return: """ user_id = request.session.get('user_id', '') if not get_user(user_id): request.session['login_from'] = '/base/plan/' return HttpResponseRedirect('/login/') else: if request.method == 'POST': ...
4da776fd83e30019fbd6cdb1b659d8626e0620cc
27,999
import itertools def get_state_vect_cols(prefix=''): """Get the column names of the state vector components with the provided `prefix`. :param prefix: The prefix that is used in front of the state vector components in the column names, examples are `physics_pred` and `physics_err` or none...
d61c5ebd2aad8c679dda50fa1e310ebf11480e01
28,001
import six import shlex def parse_options(options=None, api=False): """ Parse given option string :param options: :type options: :param api :type api: boolean :return: :rtype: """ if isinstance(options, six.string_types): args = shlex.split(options) options = v...
f8a2b3671dab3ffc5f23bd937181324bc1c0d9c7
28,003
import random from datetime import datetime def data_for_column(column: dict, kwargs: dict, size: int) -> list: """Generates data for schema column :param dict column: Column definition :param dict kwargs: Faker keyword arguments :param int size: Number of rows :return: List of random data for a ...
d2ba76d48d80cc256f1959d8fa617b81301119d0
28,004
def peak_bin(peaks, i): """Return the (bin) index of the ith largest peak. Peaks is a list of tuples (i, x[i]) of peak indices i and values x[i], sorted in decreasing order by peak value.""" if len(peaks) > i: return peaks[i][0] else: return np.nan
fc667fe04c856e3090ded9ca8eb0a45d51cda74a
28,005
def fetch_all(path, params=None, client=default_client): """ Args: path (str): The path for which we want to retrieve all entries. Returns: list: All entries stored in database for a given model. You can add a filter to the model name like this: "tasks?project_id=project-id" """...
d663414388b9b6e105fab42d8e4d9cde558322cf
28,006
from datetime import datetime import calendar def plotter(fdict): """ Go """ pgconn = get_dbconn('coop') cursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor) ctx = get_autoplot_context(fdict, get_description()) station = ctx['station'] table = "alldata_%s" % (station[:2],) nt...
4b11cee286494963afb43cfc5b6ab7e56c281476
28,007
def link_library_dynamic(hs, dep_info, object_files, my_pkg_id): """Link a dynamic library for the package using given object files. Returns: File: Produced dynamic library. """ dynamic_library = hs.actions.declare_file( "lib{0}-ghc{1}.{2}".format( pkg_id.library_name(hs, my_pkg_id), hs.too...
5171d75c71b52e2487ff1d349add86c042a84062
28,008
def save_mvgcca_latents_space(X, W, model, path, prefix, epochs): """Saves the list containing the common latent space Z and all the views latent space Z_m. - X : [np.array(n x d1),...,np.array(n x dM)] multivews features ; n number of instances; dm dimension of views m ; M number of views ...
dc0fbb15dd73e44bf1b1b2c74b173cfb6b8cf1d8
28,009
def TDC_sampling(in_channels, mode='downsampling'): """ wrapper_function: -> TIC_sampling [B, in_channels, T, F] => [B, in_channels, T, F//2 or F*2] in_channels: number of input channels """ return TIC_sampling(in_channels, mode)
8458e9fe9bfd6bc92af2940b4c3ea5d2f09eb40a
28,010
def bmxbm(s, t, batch_first=True): """ Batched matrix and batched matrix multiplication. """ if batch_first: equation = "aij,ajk->aik" else: equation = "ija,jka->ika" return tf.einsum(equation, s, t)
6ac60eb1ffeed2caad312fd4691d689e705986c0
28,011
import re def get_all_semantic_case_ids(): """Get iterator over test sorted IDs of all cases in the SBML semantic suite""" pattern = re.compile(r'\d{5}') return sorted(str(x.name) for x in SBML_SEMANTIC_CASES_DIR.iterdir() if pattern.match(x.name))
d4a5cba008010f02398bb61c32f06450610de350
28,012
def generate_points(n=500, min_=0, max_=1): """ Generate a list of n points. Parameters ---------- n : int min_ : float max_ : float Returns ------- list List of length n with tuples (x, y) where x is in [min_, max_] and y is either 0 or 1. """ assert ma...
fe2dbe0ed281716a465804d67014badab96fb414
28,013
def gce(nvf): """ Write the necessary code for launch the VNF using GCE :param nvf: :return: vagrantfile code """ element = Template(u'''\ config.vm.box = "{{image}}" config.vm.provider :google do |google, override| google.google_project_id = {{google_project_id}} google.google_client_email = {...
588c2472b2a957a1eda64bef526b6410103b72b2
28,014
from datetime import datetime def get_ethpm_birth_block( w3: Web3, from_block: int, to_block: int, target_timestamp: int ) -> int: """ Returns the closest block found before the target_timestamp """ version_release_date = datetime.fromtimestamp(target_timestamp) while from_block < to_block: ...
c2448152cea2a3c9a9dd227a5126e2dd0767b773
28,016
def Line(p0, p1=None, c="r", alpha=1, lw=1, dotted=False, res=None): """ Build the line segment between points `p0` and `p1`. If `p0` is a list of points returns the line connecting them. A 2D set of coords can also be passed as p0=[x..], p1=[y..]. :param c: color name, number, or list of [R,G,B] c...
1a56c260ad0d3478b51db03fa267898c637bf819
28,017
def date_dd(dataset, source): """Display 3 blocks: 1. image of the patent, 2. choice block, 3. text block for date. 2 is artifical and should be ignored""" def get_stream(): # Load the directory of images and add options to each task stream = Images(source) for eg in stream: ...
fae232b97ab4d758aceea806ebc95816db3cb044
28,018
def sort(array=[12,4,5,6,7,3,1,15]): """Sort the array by using quicksort.""" less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) elif x == pivot: equal.append(x) ...
bc31df069f8e985d620032b9053bd8f13880780f
28,019
from typing import Optional async def remove_completed_game(player_id: str, game_id: str) -> Optional[dict]: """ Updates the player's current games by removing a game from it. :param player_id: the object id of the player :param game_id: the object id of the game :return: an awaitable resolving ...
2e5f4ec3af053d1f1685e6a576d8027db585bc87
28,021
def is_multioutput(y): """Whether the target y is multi-output (or multi-index)""" return hasattr(y, "shape") and y.ndim == 2 and y.shape[1] > 1
bcdaa46c304fec50c173dffca5f1f1d5d8871a58
28,023
def read_all(db: Session): """ Get all dimensions. :param db: :return: List[QuestionModel] """ question = db.query(QuestionModel).all() return question
a854c4667dc30918cd1e9ec767d65fa8ad1fb5ca
28,024
def get_all_tenants(context): """Returns a list of all tenants stored in repository. :param context: context of the transaction """ return context.session.query(db_models.AristaProvisionedProjects)
62d8fed653f5b8e380caa47f5f408ecab860a58b
28,025
def total_sub_pixels_2d_from(mask_2d: np.ndarray, sub_size: int) -> int: """ Returns the total number of sub-pixels in unmasked pixels in a mask. Parameters ---------- mask_2d : np.ndarray A 2D array of bools, where `False` values are unmasked and included when counting sub pixels. sub_...
98461ffe073172db596570630ccfbd27384c7e3a
28,027
from simtk import unit as simtk_unit import torch def formaldehyde_conformer(formaldehyde) -> torch.Tensor: """Returns a conformer [A] of formaldehyde with an ordering which matches the ``formaldehyde`` fixture.""" formaldehyde.generate_conformers(n_conformers=1) conformer = formaldehyde.conformers[...
f5a9a19f6dd8e26a121e496161fa6da7b8f63047
28,029
import warnings def reduce_function(op_func, input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None): """ Handler function for Tensorflow depreciation of keep_dims for tf 1.8 and above, but tf 1.4 requires keep_dims :param op_func: expects the function to handle ...
f6433479bcb01a8fc5dfc2c08dd70bf2fe500e94
28,030
from typing import Mapping def filter_dict(function_or_value, dict_to_filter): """ Filter by value >>> filter_dict(123, {'a': 123, 'b': 1234}) {'b': 1234} Filter by value not applicable >>> filter_dict(123, {'a': 1234, 'b': 5123}) {'a': 1234, 'b': 5123} Embedded filter by val...
6403f716c21a1cfef046174899183858837bb92e
28,031
def resnet50(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) return model
ba0f11d8645f3dcc5ccc48ec718de0c6ff624930
28,033
import torch import math def irfft(x, res): """ :param x: tensor of shape [..., m] :return: tensor of shape [..., alpha] """ assert res % 2 == 1 *size, sm = x.shape x = x.reshape(-1, sm) x = torch.cat([ x.new_zeros(x.shape[0], (res - sm) // 2), x, x.new_zeros(x....
8f383523bc0c4ed6895d8aad0aca2758401d2fe5
28,034
import torch def calc_ranks(idx, label, pred_score): """Calculating triples score ranks. Args: idx ([type]): The id of the entity to be predicted. label ([type]): The id of existing triples, to calc filtered results. pred_score ([type]): The score of the triple predicted by the model....
1f3d56c9a93afdd314c9a244319ef78668426481
28,035
def GBT(trainingData, testData): """ Gradient Boosted Tree Regression Model :param trainingData: :param testData: :return: Trained model, predictions """ gbt = GBTRegressor( maxIter=100, maxDepth=6, seed=42) model = gbt.fit(trainingData) predictions = model.transform(testData) r...
4e17c7188ccdd2676463a705a4e3ab4ccbc5adeb
28,036
def fromcolumns(cols, header=None, missing=None): """View a sequence of columns as a table, e.g.:: >>> import petl as etl >>> cols = [[0, 1, 2], ['a', 'b', 'c']] >>> tbl = etl.fromcolumns(cols) >>> tbl +----+-----+ | f0 | f1 | +====+=====+ | 0 | 'a'...
c033e0fbc11e18a73eb8216e4a3a2c79a0756bb8
28,037
import re def function_sql(field, mysql_result_list): """ 替换MySQL查询结果的方法 :param field: 第一个参数是yaml文件里面定义的字段 :param mysql_result_list: 第二个参数是MySQL查询结果列表 :return: """ if "{__SQL" in field: mysql_index_list = re.findall("{__SQL(.+?)}", field) # 获取索引列表 for i in mysql_in...
769881ae5e3a7caa036c977785827e219e5ab92b
28,038
def enable_dropout(model, rate=None, custom_objects={}): """ Enables the droput layer - used for monte carlo droput based uncertainty computation Note: the weights needs to be reloaded after calling this model >>> model = enable_dropout(model) >>> model.load_weights('path to model weight') :par...
2268c23bc5598fcf0befe76a15f0dbc444e28828
28,040
import ctypes def get_max_torque_norm(p_state, idx_image=-1, idx_chain=-1): """Returns the current maximum norm of the torque acting on any spin.""" return float(_Get_MaxTorqueNorm(ctypes.c_void_p(p_state), ctypes.c_int(idx_image), ctypes.c_int(idx_chain)))
b6ae73ef269a192b5aafc96e939a0ab1f9a937be
28,041
def filter_by_zscore(data, features, remove_z): """Remove rows with |z scores| > remove_z""" return data[(np.abs(np.nan_to_num(zscore(data[features]), posinf=0.0, neginf=0.0)) < remove_z).all(axis=1)]
bbaad3ee7879d64dafb2e45062c6cbe97ff457bc
28,042
def _GetProperty(obj, components): """Grabs a property from obj.""" if obj is None: return None elif not components: return obj elif (isinstance(components[0], _Key) and isinstance(obj, dict)): return _GetProperty(obj.get(components[0]), components[1:]) elif (isinstance(components[0], _...
d887613e06078fcde887d51c8f83cc9ddc8f16f8
28,043
def make_similarity_function(similarity=None, distance=None, radius=None): """ Function creating a similarity function returning True if the compared items are similar from a variety of functions & parameters. Basically, if a distance function is given, it will be inverted and if a radius is given,...
b8eeeeb466f21f2b3605941253f56392c3e41e88
28,044
from typing import Optional def prepare_error_message(message: str, error_context: Optional[str] = None) -> str: """ If `error_context` is not None prepend that to error message. """ if error_context is not None: return error_context + ": " + message else: return message
ea95d40797fcc431412990706d5c098a07986156
28,045
def _options_from_args(args): """Returns a QRCodeOptions instance from the provided arguments. """ options = args.get('options') if options: if not isinstance(options, QRCodeOptions): raise TypeError('The options argument must be of type QRCodeOptions.') else: # Convert t...
ff895e537a0d2c00f42e10f827b8176865902774
28,046
def calc_q_rq_H(region, R_type): """単位面積当たりの必要暖房能力 Args: region(int): 省エネルギー地域区分 R_type(string): 暖冷房区画の種類 Returns: float: 単位面積当たりの必要暖房能力 Raises: ValueError: R_type が '主たる居室' または 'その他の居室' 以外の場合に発生する """ table_3 = get_table_3() if R_type == '主たる居室': return t...
1b413f0d83d723e1ef01c558cbc54e8afddc65ac
28,047
def tuple_compare_lt(left, right): """Compare two 'TupleOf' instances by comparing their individual elements.""" for i in range(min(len(left), len(right))): if left[i] > right[i]: return False if left[i] < right[i]: return True return len(left) < len(right)
8f93d0c1336fd63d7c7f04cf54680de25acfdafb
28,048
def multilevel_roi_align(inputs, boxes, image_shape, crop_size: int = 7): """Perform a batch multilevel roi_align on the inputs Arguments: - *inputs*: A list of tensors of shape [batch_size, width, height, channel] representing the pyramid. - *boxes*: A tensor and shape [batch_size, num_b...
3b150e6b6bcada3d3633f1edf61a99a566792849
28,049
def login(): """Login user""" # Instantiate login form form = LoginForm() username = form.username.data if form.validate_on_submit(): # Query database for username and validate form submission user = User.query.filter_by(username=username).first() # if user exists i...
fa1e1814d71bcbf04fda08b282f3f1a58965dcfb
28,050
from datetime import datetime import uuid def serialize(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime.datetime): serial = obj.isoformat(sep='T') return serial if isinstance(obj, uuid.UUID): serial = str(obj) retur...
c20abaac68e8f8c8314a6dbbaee128b54110705c
28,051
def clean_names_AZ(col): """ Removes any non-alpha characters (excluding spaces) from a string. Replaces these characters with an empty space. Trims outer whitespace. Example -------- >>> Input: "JOHN SMITH 2000" >>> Output: "JOHN SMITH" """ return trim(regexp_replace(col, "[^A-Z ]+...
4db710ec573087df59109046ea2a965c7545f1a2
28,052
def check_continent_node_membership(continents, continent_node_id): """The function checks that a node continent is bound to the corresponding relation through 'label' membership. """ assert continent_node_id[0] == 'n', ("A node expected in " "check_continent...
7ef0895e26fdd495f54ac58ea35513178f00eb19
28,053
import string def remove_punctuation(input_string): """ remove the punctuation of input Parameters ---------- input_string : string Returns ------- output_string : string string without punctuation ###from assignment encoder """ out_...
2bbd1dc90d37c1ad16698092b6269c0fe601d902
28,054
from typing import Any def field_value_between(value: Any = None, field: str = None, lower: float = None, upper: float = None) -> bool: """ Validate value at the given field to be between the lower/upper boundaries. """ if not value: return False if not isinstance(...
4ff2dfa814f0ddda7efca3ce19f137a0d86b9f40
28,055
import yaml def j2_to_json(path_in, path_out, **kwargs): """Render a yaml.j2 chart to JSON. Args: path_in: the j2 template path path_out: the JSON path to write to kwargs: data to pass to the j2 template Returns: the file path and JSON string """ return pipe( rend...
2cd41eb29e293e44772855f7d66e7425eedaec8d
28,056
def user_logged_out(connection,user): """ update login status to false when user has logged out :param connection: :param user: :return: """ with connection: return connection.execute(UPDATE_USER_LOGIN_STATUS_TO_FALSE,(user,))
b355fa6e74180adb7504e60602cb164095e1898d
28,057
def findGrayscaleTilesInImage(img): """ Find chessboard and convert into input tiles for CNN """ if img is None: return None, None # Convert to grayscale numpy array img_arr = np.asarray(img.convert("L"), dtype=np.float32) # Use computer vision to find orthorectified chessboard corners in image cor...
d3431c519f53c0a56b144dde8196d58000f2f788
28,058
def run(df, docs, columns): """ converts each column to type int :param df: :param columns: :return: """ for doc in docs: doc.start("t07 - Change type of {} to int".format(str(columns).replace("'", "")), df) for column in columns: df[column] = df[column].astype(int) ...
5d360a764ad30a80c39d58f9aeb520d7c57f7903
28,059
import requests def get_articles(): """ Retreives the articles list (via an API request) """ endpoint = "%s%s" % ( settings.API_BASE_URL, reverse("api:articles-list") ) headers = DEFAULT_REQUESTS_HEADERS r = requests.get( endpoint, headers=DEFAULT_REQUE...
fb2b59cc301890b8c6f4c6c115b6f08f4a4cbe72
28,060
import numpy def fmin_ncg(f, x0, fprime, fhess_p=None, fhess=None, args=(), avextol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0, callback=None, preconditioner = None): """ Unconstrained minimization of a function using the Newton-CG method. Parameters ...
bb2d4c3d1303adebe856f6c3ac13cd92beeee0ab
28,061
def add_missing_flow_by_fields(flowby_partial_df, flowbyfields): """ Add in missing fields to have a complete and ordered :param flowby_partial_df: Either flowbyactivity or flowbysector df :param flowbyfields: Either flow_by_activity_fields, flow_by_sector_fields, or flow_by_sector_collapsed_fields ...
49eb8810c7c2c4e852a40aa86e2d2d2a8506f253
28,062
from datetime import datetime def calcular_diferencia_dias(fin_dia): """ Obtiene la diferencia de dias entre una fecha y hoy """ hoy = datetime.now() end = datetime.strptime(str(fin_dia), '%Y-%m-%d') return abs(end - hoy).days
41b732f3bb09d2deca4be034273a5fed74971386
28,063
def matrix_base_mpl(matrix, positions, substitutions, conservation=None, secondary_structure=None, wildtype_sequence=None, min_value=None, max_value=None, ax=None, colormap=plt.cm.RdBu_r, colormap_conservation=plt.cm.Oranges, na_color="#bbb...
ef661fd556b3ba2e4c313e032e8ef3be532bb73d
28,064
def gaussian_laplace(input, sigma, output=None, mode="reflect", cval=0.0, **kwargs): """Multi-dimensional Laplace filter using Gaussian second derivatives. Args: input (cupy.ndarray): The input array. sigma (scalar or sequence of scalar): Standard deviations for each axis ...
6b5f184b658dd446a4f3ec7de0ee126f33663b0c
28,065
def perimeter_mask(image, corner_fraction=0.035): """ Create boolean mask for image with a perimeter marked as True. The perimeter is the same width as the corners created by corner_mask. Args: image : the image to work with corner_fraction: determines the width of the perimeter Re...
afc755dccfffa9ff68e060a6af3da0d38d323178
28,067
def vgg13_bn(**kwargs): """VGG 13-layer model (configuration "B") with batch normalization""" model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs) return model
1fa3ffdbb301b55a48fc1912baab84006705e15f
28,068
import regex def convert_version_to_tuple(version: str) -> VersionTuple: """ Convert version info from string representation to tuple representation. The tuple representation is convenient for direct comparison. """ m = regex.fullmatch(r"(?P<major>\d+)\.(?P<minor>\d+)", version) if not m: ...
6c197988ae2c98481f9b16f90f9ae3f7072ac7c8
28,069
from typing import Callable def SU3GradientTF( f: Callable[[Tensor], Tensor], x: Tensor, ) -> tuple[Tensor, Tensor]: """Compute gradient using TensorFlow GradientTape. y = f(x) must be a real scalar value. Returns: - (f(x), D), where D = T^a D^a = T^a ∂_a f(x) NOTE: Use real v...
93b029e0a2854e651d4c6ea5995f8d952f9a64e6
28,070
def create_app(config): """Flask application factory. Returns: Flask Application with BrazilDataCubeDB extension prepared. """ app = Flask(__name__) BrazilDataCubeDB(app) return app
d8ba6d7306508e4a55f9f3dbee5d17df16c56820
28,071
import string def genpass_comprehension(length=8, chars=string.letters+string.digits): """Generate password using a list comprehension. """ # Can be rewritten as a list comprehension. return ''.join([choice(chars) for i in range(length)])
d77b89e2872eef92390d08f555adbb52f9da1c34
28,072
import functools def typed(*types): """Type annotation. The final type is the output type. """ if len(types) < 1: raise SyntaxError('Too few arguments: typed{}'.format(types)) if len(types) > 3: raise NotImplementedError('Too many arguments: typed{}'.format(types)) result_typ...
90f100bebd5778d36eee1ad04b7c831b003ce604
28,073
from typing import Tuple def insert_linebreaks( input_fragments: StyleAndTextTuples, max_line_width: int, truncate_long_lines: bool = True) -> Tuple[StyleAndTextTuples, int]: """Add line breaks at max_line_width if truncate_long_lines is True. Returns input_fragments with each charact...
ec9faf8ff80e3500487634b759a136dc2deca684
28,074
def score_reactant_combination(candidate_combination, scoring_fcn): """ Generates a score for a combination of reactant candidates according to the criteria. """ # Extract only the reactant candidate compound ID's. reactant_ids = [combo[0] for combo in candidate_combination] # Score the reactant candi...
715a21bf24af0a60ba3ea421b7bf8dcebcca17fc
28,075
def get_named_entities(df): """ Count the named entities that are neither A nor B. Hopefully this correlates with class "Neither". :param df: competition data with one extra field spacy_nlp_doc: precomputed nlp(text) :return: """ named_df = pd.DataFrame(0, index=df.index, columns=["named_e...
65469fe65c8808943343d952fd82ebe62bb9df97
28,078
def normalize(vectors): """ Normalize a set of vectors. The length of the returned vectors will be unity. Parameters ---------- vectors : np.ndarray Set of vectors of any length, except zero. """ if len(vectors.shape) == 1: return vectors / np.linalg.norm(vectors) ...
839104d17a3ccbfd1191474bf95076445b4b0464
28,079
def get_all_requests(current_user): """Gets all requests""" all_requests = [] for request in request_model.requests.values(): all_requests.append(request) return jsonify(all_requests)
bcadfb936826b3a33f809cc95af1a991c5bf741e
28,080
def RunManifestExe(target, source, env): """Calls RunManifest for updating an executable (resource_num=1).""" return RunManifest(target, source, env, resource_num=1)
629ffccb7b163514bd91c790894bdfec3683110e
28,081
import torch def dist_reduce_tensor(tensor, dst=0): """Reduce to specific rank""" world_size = get_world_size() if world_size < 2: return tensor with torch.no_grad(): dist.reduce(tensor, dst=dst) if get_rank() == dst: tensor.div_(world_size) return tensor
d64d153145bffaf454dd3f46154db156b600bac3
28,082
def upload_blob(bucket_name, source_file_name, destination_blob_name): """Uploads a file to the bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_file(source_file_name) print('File {} uploaded ...
b63d6bb0ede33d68d684b98968e3e94efbd0c5df
28,083
def get_lines(matrix, loc): """Returns lines that pass though `loc`. Matrix can be indices. Args: matrix: a N by N matrix representing the board loc: a tuple of loc coordinates Returns: Numerical values on the horizontal, vertical, and diagonal lines that pass through loc. ...
43909460e847d5dde88216cc37b902a56ba2d261
28,084
from bs4 import BeautifulSoup from typing import Dict def process_citations_in_paragraph(para_el: BeautifulSoup, sp: BeautifulSoup, bibs: Dict, bracket: bool) -> Dict: """ Process all citations in paragraph and generate a dict for surface forms :param para_el: :param sp: :param bibs: :param br...
74418fafc2a2d828b702555b79b515d9b16d9f10
28,085