content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_image_ids(idol_id): """Returns all image ids an idol has.""" c.execute("SELECT id FROM groupmembers.imagelinks WHERE memberid=%s", (idol_id,)) all_ids = {'ids': [current_id[0] for current_id in c.fetchall()]} return all_ids
036dfdc9d757b2a7c70b26653252bbb5e180a5f1
22,154
def sortarai(datablock, s, Zdiff, **kwargs): """ sorts data block in to first_Z, first_I, etc. Parameters _________ datablock : Pandas DataFrame with Thellier-Tellier type data s : specimen name Zdiff : if True, take difference in Z values instead of vector difference NB: this...
5127b293b63a0d67da9e0ec21ff3085beea5a836
22,155
import json def _extract_then_dump(hex_string: str) -> str: """Extract compressed content json serialized list of paragraphs.""" return json.dumps( universal_extract_paragraphs( unpack(bytes.fromhex(hex_string)) ) )
6be6f045ff86580e5d33239e8b8232f5c343723b
22,157
import base64 import hmac import hashlib def sso_redirect_url(nonce, secret, email, external_id, username, name, avatar_url, is_admin , **kwargs): """ nonce: returned by sso_validate() secret: the secret key you entered into Discourse sso secret user_email: email address of the user who lo...
7aefb1c67a23f0c1311ce4297760a13ea39769fe
22,158
def normalized_cluster_entropy(cluster_labels, n_clusters=None): """ Cluster entropy normalized by the log of the number of clusters. Args: cluster_labels (list/np.ndarray): Cluster labels Returns: float: Shannon entropy / log(n_clusters) """ if n_clusters is None: n_clusters...
aaed21c7cd91e1b61eb8a8336978eded8673960e
22,159
def ingest_data(data, schema=None, date_format=None, field_aliases=None): """ data: Array of Dictionary objects schema: PyArrow schema object or list of column names date_format: Pandas datetime format string (with schema only) field_aliases: dict mapping Json field names to desired schema names ...
94ac4c13a71275485a79404f20c702886b39fb1c
22,160
def build_messages(missing_scene_paths, update_stac): """ """ message_list = [] error_list = [] for path in missing_scene_paths: landsat_product_id = str(path.strip("/").split("/")[-1]) if not landsat_product_id: error_list.append( f"It was not possible to bui...
07865a38fad6e3f642d3e55b80fac734dbb7d94b
22,161
def DecrementPatchNumber(version_num, num): """Helper function for `GetLatestVersionURI`. DecrementPatchNumber('68.0.3440.70', 6) => '68.0.3440.64' Args: version_num(string): version number to be decremented num(int): the amount that the patch number need to be reduced Returns: string: decremente...
e42585791063d7982675065be7480ae7b5ea637d
22,162
def hi_means(steps, edges): """This applies kmeans in a hierarchical fashion. :param edges: :param steps: :returns: a tuple of two arrays, ´´kmeans_history´´ containing a number of arrays of varying lengths and ´´labels_history´´, an array of length equal to edges.shape[0] """ sub_...
60d242f1ed9a4009bac706053e56f0d450ca7a7a
22,163
def tag_item(tag_name, link_flag=False): """ Returns Items tagged with tag_name ie. tag-name: django will return items tagged django. """ print C3 % ("\n_TAGGED RESULTS_") PAYLOAD["tag"] = tag_name res = requests.post( GET_URL, data=json.dumps(PAYLOAD), headers=HEADERS, verify=False)...
038b6a81dec1ea7c6fb9c4d83eaa6425d950c2fd
22,164
def movie_info(tmdb_id): """Renders salient movie data from external API.""" # Get movie info TMDB database. print("Fetching movie info based on tmdb id...") result = TmdbMovie.get_movie_info_by_id(tmdb_id) # TMDB request failed. if not result['success']: print("Error!") # Can'...
ee7188eddcc50d0114ae5b80bc753e803632d557
22,165
def diabetic(y, t, ui, dhat): """ Expanded Bergman Minimal model to include meals and insulin Parameters for an insulin dependent type-I diabetic States (6): In non-diabetic patients, the body maintains the blood glucose level at a range between about 3.6 and 5.8 mmol/L (64.8 and 104.4 mg/d...
35949f9a3d6010e89346ebb7f2818230ca6148a0
22,166
def get_spacy_sentences(doc_text): """ Split given document into its sentences :param doc_text: Text to tokenize :return: list of spacy sentences """ doc = _get_spacy_nlp()(doc_text) return list(doc.sents)
30345e04add02fd74e8470ce667fee60ddc7140d
22,167
def get_recommendations(commands_fields, app_pending_changes): """ :param commands_fields: :param app_pending_changes: :return: List of object describing command to run >>> cmd_fields = [ ... ['cmd1', ['f1', 'f2']], ... ['cmd2', ['prop']], ... ] >>> app_fields = { ... ...
03fa583a5d4ea526cfeaa671418488218e1b227f
22,168
import collections def file_based_convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, output_file): """Convert a...
efb6a0d347ae3a99a5859cbd3e0c1216d09377e6
22,169
def hello(): """Return a friendly HTTP greeting.""" return 'Hello World!!!'
ae3528d10f94c92c169f53d5c3897572c9032bc2
22,170
from typing import Union from typing import List from typing import Tuple def _findStress( syllables: Union[List[Syllable], List[List[str]]] ) -> Tuple[List[int], List[int]]: """Find the syllable and phone indicies for stress annotations""" tmpSyllables = [_toSyllable(syllable) for syllable in syllables] ...
d4adc4b6156e4d823640a29815d75832c21f68ac
22,171
from hydrus.data.helpers import get_path_from_type import random import string def gen_dummy_object(class_title, doc): """ Create a dummy object based on the definitions in the API Doc. :param class_title: Title of the class whose object is being created. :param doc: ApiDoc. :return: A dummy objec...
88f096a483699b9126496564cfe755386012acce
22,172
def gather_info(arguments) -> Info: """Gather info.""" if arguments.integration: info = {"domain": arguments.integration} elif arguments.develop: print("Running in developer mode. Automatically filling in info.") print() info = {"domain": "develop"} else: info = _...
4cc527373fe29b36526388716f2402101039cea2
22,173
def __is_geotagging_input(question_input, _): """Validates the specified geotagging input configuration. A geotagging input configuration contains the following optional fields: - location: a string that specifies the input's initial location. Args: question_input (dict): An input configuratio...
8fc392f832cc6d5c38eb5ffd2e7e20ff50b4ffd3
22,176
def _be_num_input(num_type, than, func=_ee_num_input, text='', error_text="Enter number great or equal than ", error_text_format_bool=True, error_text_format="Enter number great or equal than {}", pause=True, pause_text_bool=True, pause_text='Press Enter...', clear=...
92f8d3c119b0c331c50c4213644003c62534deb9
22,177
def createParetoFig(_pareto_df,_bestPick): """ Initalize figure and axes objects using pyplot for pareto curve Parameters ---------- _pareto_df : Pandas DataFrame DataFrame from Yahoo_fin that contains all the relevant options data _bestPick : Pandas Series Option data for the b...
dc6d8e6566c8c12d9938bf57a22c569124b65895
22,178
def rem4(rings, si): """finds if the silicon atom is within a 4 membered ring""" for i in range(len(rings)): triangles = 0 distances = [] locations = [] for n in range(len(rings[i]) - 1): for m in range(1, len(rings[i]) - n): distances.append(distance(...
e38fb7e1349597fa79cd21d39ecb222f39de86b3
22,179
def ilogit(x): """Return the inverse logit""" return exp(x) / (1.0 + exp(x))
064383b65c2e8b011d2a6cd6ce14bf7936dd3178
22,180
def get_out_of_bounds_func(limits, bounds_check_type="cube"): """returns func returning a boolean array, True for param rows that are out of bounds""" if bounds_check_type == "cube": def out_of_bounds(params): """ "cube" bounds_check_type; checks each parameter independently""" ...
56c82efd63afdb36fc4d60cda7912fd9a4edb1d0
22,181
from typing import Dict from typing import Set def inspectors_for_each_mode(lead_type="lead_inspector") -> Dict[str, Set[str]]: """ We want to be able to group lead inspectors by submode. """ if lead_type not in ["lead_inspector", "deputy_lead_inspector"]: raise ValueError("Can only query for ...
b712e82a14ddc8153c0ce61ebd3e95faca5993ae
22,182
import tables def is_hdf_file(f): """Checks if the given file object is recognized as a HDF file. :type f: str | tables.File :param f: The file object. Either a str object holding the file name or a HDF file instance. """ if((isinstance(f, str) and (f[-4:] == '.hdf' or f[-3:] == '.h5')...
55d89b0d1afdf2acf705d5266e2c44f6d3901c2e
22,184
def dummy_receivers(request, dummy_streamers): """Provides `acquire.Receiver` objects for dummy devices. Either constructs by giving source ID, or by mocking user input. """ receivers = {} for idx, (_, _, source_id, _) in enumerate(dummy_streamers): with mock.patch('builtins.input', side_ef...
70d8e0f7c4f84f949bdc73a4fd240684d86baaed
22,185
def construct_reverse_protocol(splitting="OVRVO"): """Run the steps in the reverse order, and for each step, use the time-reverse of that kernel.""" step_length = make_step_length_dict(splitting) protocol = [] for step in splitting[::-1]: transition_density = partial(reverse_kernel(step_mapping[...
7526e1cab43eeb3ef58a1ac4a673bf9a9992e287
22,187
def tabinv(xarr, x): """ Find the effective index in xarr of each element in x. The effective index for each element j in x is the value i such that :math:`xarr[i] <= x[j] <= xarr[i+1]`, to which is added an interpolation fraction based on the size of the intervals in xarr. Parameter...
c020222355e4d7671e7117c30e3babf0fa1d1f46
22,188
import configparser def getldapconfig() : """ Renvoie la configuration ldap actuelle""" cfg = configparser.ConfigParser() cfg.read(srv_path) try : return (cfg.get('Ldap', 'ldap_address'), cfg.get('Ldap', 'ldap_username'), cfg.get('Ldap', 'ldap_password').replace("$perce...
505c7d3728b986811a86841003cd763912c82a93
22,189
def rename_dict_key(_old_key, _new_key, _dict): """ renames a key in a dict without losing the order """ return { key if key != _old_key else _new_key: value for key, value in _dict.items()}
ddc497796e0e52677afdf09b7f4995cf3a534cbc
22,190
def api_browse_use_case() -> use_cases.APIBrowseUseCase: """Get use case instance.""" return use_cases.APIBrowseUseCase(items_repository)
653525c9338bf8f520014a530228512fae1ed03d
22,191
def get_descriptive_verbs(tree, gender): """ Returns a list of verbs describing pronouns of the given gender in the given dependency tree. :param tree: dependency tree for a document, output of **generate_dependency_tree** :param gender: `Gender` to search for usages of :return: List of verbs as st...
ec021c89cb59da2ff8abb0169ea2567cb2e3a13c
22,193
def client(): """Return a client instance""" return Client('192.168.1.1')
19cda306e37e7a34395b86010fb4331a238a6cbc
22,194
import termios, fcntl, sys, os def read_single_keypress(): """Waits for a single keypress on stdin. This is a silly function to call if you need to do it a lot because it has to store stdin's current setup, setup stdin for reading single keystrokes then read the single keystroke then revert stdin bac...
646c04bc5441557064714716087a9893c7fa66dc
22,196
def set_table(table, fold_test, inner_number_folds, index_table, y_name): """ Set the table containing the data information Set the table by adding to each entry (patient) its start and end indexes in the concatenated data object. In fact each patients i is composed by `n_i` tiles so that for example patie...
d46c0601b59f27a60ec99a5305113d94893ba748
22,197
def parse_args(): """ 引数パース """ argparser = ArgumentParser() argparser.add_argument( "-b", "--bucket-name", help="S3 bucket name", ) argparser.add_argument( "-d", "--days", type=int, help="Number of days", ) return argparser.par...
36302c14466a2c1a1791217566c49687fc55b567
22,198
def predict(file): """ Returns values predicted """ x = load_img(file, target_size=(WIDTH, HEIGHT)) x = img_to_array(x) x = np.expand_dims(x, axis=0) array = NET.predict(x) result = array[0] answer = np.argmax(result) return CLASSES[answer], result
98ce2d770d7bffc47e6fe84521fd6992ab2a53fa
22,199
def sample_categorical(pmf): """Sample from a categorical distribution. Args: pmf: Probablity mass function. Output of a softmax over categories. Array of shape [batch_size, number of categories]. Rows sum to 1. Returns: idxs: Array of size [batch_size, 1]. Integer of category sa...
5b270e63bb5e290a97cacede9bd0f8bf34fc0ecf
22,200
def make_Dex_3D(dL, shape, bloch_x=0.0): """ Forward derivative in x """ Nx, Ny , Nz= shape phasor_x = np.exp(1j * bloch_x) Dex = sp.diags([-1, 1, phasor_x], [0, Nz*Ny, -Nx*Ny*Nz+Nz*Ny], shape=(Nx*Ny*Nz, Nx*Ny*Nz)) Dex = 1 / dL * sp.kron(sp.eye(1),Dex) return Dex
1d3a47624f180d672f43fb65082f29727b42f720
22,201
def feature_decoder(proto_bytes): """Deserializes the ``ProtoFeature`` bytes into Python. Args: proto_bytes (bytes): The ProtoBuf encoded bytes of the ProtoBuf class. Returns: :class:`~geopyspark.vector_pipe.Feature` """ pb_feature = ProtoFeature.FromString(proto_bytes) retur...
ff7cdc6c0d7f056c69576af2a5b5eb98f57266af
22,202
async def calculate_board_fitness_report( board: list, zone_height: int, zone_length: int ) -> tuple: """Calculate Board Fitness Report This function uses the general solver functions api to calculate and return all the different collisions on a given board array representation. Args: boa...
a770863c044a4c4452860f9fccf99428dbfb5013
22,203
def quote_fqident(s): """Quote fully qualified SQL identifier. The '.' is taken as namespace separator and all parts are quoted separately Example: >>> quote_fqident('tbl') 'public.tbl' >>> quote_fqident('Baz.Foo.Bar') '"Baz"."Foo.Bar"' """ tmp = s.split('.', 1) if len(tmp)...
26cf409a09d2e8614ac4aba04db1eee6cac75f08
22,204
def row_generator(x, H, W, C): """Returns a single entry in the generated dataset. Return a bunch of random values as an example.""" return {'frame_id': x, 'frame_data': np.random.randint(0, 10, dtype=np.uint8, size=(H, W, C))}
e99c6e8b1557890b6d20ea299bc54c0773ea8ade
22,205
def accuracy(output, target, topk=(1,)): """Computes the precor@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: ...
80e73c907e57b9666a8f399b8ed655c919d79abb
22,206
def define_model(input_shape, output_shape, FLAGS): """ Define the model along with the TensorBoard summaries """ data_format = "channels_last" concat_axis = -1 n_cl_out = 1 # Number of output classes dropout = 0.2 # Percentage of dropout for network layers num_datapoints = input_sh...
4d6bea9444935af1b95e9b209eee2df7d455e90c
22,207
import re import collections def group_files(config_files, group_regex, group_alias="\\1"): """group input files by regular expression""" rx = re.compile(group_regex) for key, files in list(config_files.items()): if isinstance(files, list): groups = collections.defaultdict(list) ...
7f0c14387a9a63d03e8fdcb2297502a4ebf31e80
22,208
def get_current_icmp_seq(): """See help(scapy.arch.windows.native) for more information. Returns the current ICMP seq number.""" return GetIcmpStatistics()['stats']['icmpOutStats']['dwEchos']
4e5798a6187cd8da55b54698deab4f00aec19144
22,209
def text_mocked_request(data: str, **kwargs) -> web.Request: """For testng purposes.""" return mocked_request(data.encode(), content_type="text/plain", **kwargs)
fe9acfd2d7801a387f6497bdd72becd94da57ea9
22,210
def get_imu_data(): """Returns a 2d array containing the following * ``senses[0] = accel[x, y, z]`` for accelerometer data * ``senses[1] = gyro[x, y, z]`` for gyroscope data * ``senses[2] = mag[x, y, z]`` for magnetometer data .. note:: Not all data may be aggregated depending on the IMU device co...
24f24316a051a4ac9f1d8d7cbab00be05ff11c25
22,211
def parse_proc_diskstats(proc_diskstats_contents): # type: (six.text_type) -> List[Sample] """ Parse /proc/net/dev contents into a list of samples. """ return_me = [] # type: List[Sample] for line in proc_diskstats_contents.splitlines(): match = PROC_DISKSTATS_RE.match(line) if ...
af24bc01d7e31dc43cf07057fae672ba62b20e53
22,212
def normalize(x): """Normalize a vector or a set of vectors. Arguments: * x: a 1D array (vector) or a 2D array, where each row is a vector. Returns: * y: normalized copies of the original vector(s). """ if x.ndim == 1: return x / np.sqrt(np.sum(x ** 2)) eli...
f4e813b22a9088c3a9a209e94963b33c24fab88e
22,213
def compute_perrakis_estimate(marginal_sample, lnlikefunc, lnpriorfunc, lnlikeargs=(), lnpriorargs=(), densityestimation='histogram', **kwargs): """ Computes the Perrakis estimate of the bayesian evidence. The estimation is based on n marginal pos...
70a287e3ed8391ecef1e48d7db846593fe240823
22,214
def postNewProfile(profile : Profile): """Gets all profile details of user with given profile_email Parameters: str: profile_email Returns: Json with Profile details """ profile_email = profile.email profile_query = collection.find({"email":profile_email}) profile_query = [it...
be81eac071e89a9ff8d44ac8e2cd479e911763b6
22,215
from typing import List def get_templates() -> List[dict]: """ Gets a list of Templates that the active client can access """ client = get_active_notification_client() if not client: raise NotificationClientNotFound() r = _get_templates(client=client) return r
b7603ba33e1628eb6dad91b861bf17ecb914c1eb
22,217
def svn_mergeinfo_intersect2(*args): """ svn_mergeinfo_intersect2(svn_mergeinfo_t mergeinfo1, svn_mergeinfo_t mergeinfo2, svn_boolean_t consider_inheritance, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t """ return _core.svn_mergeinfo_intersect2(*args)
5c8176eec56fb1a95b306af41c2d98caa75459ec
22,218
def conv_backward(dZ, A_prev, W, b, padding="same", stride=(1, 1)): """ Performs back propagation over a convolutional layer of a neural network dZ is a numpy.ndarray of shape (m, h_new, w_new, c_new) containing the partial derivatives with respect to the unactivated output of the convolutional lay...
d55eab80411efa903e03b584464ff50196468d7d
22,220
import collections def get_final_text(pred_text, orig_text, do_lower_case): """Project the tokenized prediction back to the original text.""" # When we created the data, we kept track of the alignment between original # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So # now `orig_...
5ca989a4ae5ce00cd9c09c4d9480dbeb935d6ca8
22,222
def createContext(data, id=None, keyTransform=None, removeNull=False): """Receives a dict with flattened key values, and converts them into nested dicts :type data: ``dict`` or ``list`` :param data: The data to be added to the context (required) :type id: ``str`` :keyword id: The I...
a97c599689932cbfea7063fdae32702d413352ac
22,223
import math def haversine(phi1, lambda1, phi2, lambda2): """ calculate angular great circle distance with haversine formula see parameters in spherical_law_of_cosines """ d_phi = phi2 - phi1 d_lambda = lambda2 - lambda1 a = math.pow(math.sin(d_phi / 2), 2) + \ math.cos(phi1) * math...
acb25fc8d305dde7b18059a770bdcd9b135b295a
22,225
import yaml from datetime import datetime def get_backup_start_timestamp(bag_name): """ Input: Fisrt bag name Output: datatime object """ info_dict = yaml.load(Bag(bag_name, 'r')._get_yaml_info()) start_timestamp = info_dict.get("start", None) start_datetime = None if start_timestamp i...
b8ee55c3028fb6f6e1137d614e836724c3e00bd6
22,226
def get_mask_areas(masks: np.ndarray) -> np.ndarray: """Get mask areas from the compressed mask map.""" # 0 for background ann_ids = np.sort(np.unique(masks))[1:] areas = np.zeros((len(ann_ids))) for i, ann_id in enumerate(ann_ids): areas[i] = np.count_nonzero(ann_id == masks) return are...
bf584c9529118d9946e461b4df22cf64efbeb251
22,228
def cursor_from_image(image): """ Take a valid cursor image and create a mouse cursor. """ colors = {(0,0,0,255) : "X", (255,255,255,255) : "."} rect = image.get_rect() icon_string = [] for j in range(rect.height): this_row = [] for i in range(rect.width): ...
173c3fc6bfcc6bb45c9e1e6072d7c68244750da9
22,229
def h_matrix(jac, p, lamb, method='kotre', W=None): """ JAC method of dynamic EIT solver: H = (J.T*J + lamb*R)^(-1) * J.T Parameters ---------- jac: NDArray Jacobian p, lamb: float regularization parameters method: str, optional regularization method Ret...
fc4d225bb2d98ee067b03c10f14ad23db6fad1a9
22,230
def _get_flavors_metadata_ui_converters_from_configuration(): """Get flavor metadata ui converters from flavor mapping config dir.""" flavors_metadata_ui_converters = {} configs = util.load_configs(setting.FLAVOR_MAPPING_DIR) for config in configs: adapter_name = config['ADAPTER'] flavor...
4cb8dc1737579cd76dd696ec08f984015e3ef77b
22,231
def outermost_scope_from_subgraph(graph, subgraph, scope_dict=None): """ Returns the outermost scope of a subgraph. If the subgraph is not connected, there might be several scopes that are locally outermost. In this case, it throws an Exception. """ if scope_dict is None: scope_dict...
0bd649d00b745065e75e2dcfc37d9b16eaa0c3db
22,232
def calc_entropy_ew(molecule, temp): """ Expoential well entropy :param molecule: :param temp: :param a: :param k: :return: """ mass = molecule.mass / Constants.amu_to_kg * Constants.amu_to_au a = molecule.ew_a_inv_ang * Constants.inverse_ang_inverse_au k = molecule.ew_k_kca...
7d4d2c13ce5b081e4b209169a3cf996dd0b34a44
22,233
def csm(A, B): """ Calculate Cosine similarity measure of distance between two vectors `A` and `B`. Parameters ----------- A : ndarray First vector containing values B : ndarray Second vector containing values Returns -------- float d...
cebca4a53ed3200d4820041fca7886df57f4a40c
22,235
import random import string def rand_email(): """Random email. Usage Example:: >>> rand_email() Z4Lljcbdw7m@npa.net """ name = random.choice(string.ascii_letters) + \ rand_str(string.ascii_letters + string.digits, random.randint(4, 14)) domain = rand_str(string.ascii...
9898669f59511d5b8fd403de0ab7174e7710d898
22,237
import asyncio async def value_to_deep_structure(value, hash_pattern): """build deep structure from value""" try: objects = {} deep_structure0 = _value_to_objects( value, hash_pattern, objects ) except (TypeError, ValueError): raise DeepStructureError(hash_patte...
05df4e4cec2a39006631f96a84cd6268a6550b68
22,239
def get_users_run(jobs, d_from, target, d_to='', use_unit='cpu', serialize_running=''): """Takes a DataFrame full of job information and returns usage for each "user" uniquely based on specified unit. This function operates as a stepping stone for plotting usage figures and return...
ab40605468e40b7e76a35d4bc2c1344be9050d5f
22,240
import collections def get_classes_constants(paths): """ Extract the vtk class names and constants from the path. :param paths: The path(s) to the Python file(s). :return: The file name, the VTK classes and any VTK constants. """ res = collections.defaultdict(set) for path in paths: ...
e58531e99c37c1c23abb46b18f4b2af0b95c5db9
22,241
def predict_unfolding_at_temperature(temp, data, PDB_files): """ Function to predict lables for all trajectoires at a given temperature Note: The assumption is that at a given temperature, all snapshots are at the same times Filter should be 'First commit' or 'Last commit' or 'Filter osc' as descri...
9fec4ee407bf41692c57899e96ff16ad2acdf4ea
22,242
def _frac_scorer(matched_hs_ions_df, all_hyp_ions_df, N_spectra): """Fraction ion observed scorer. Provides a score based off of the fraction of hypothetical ions that were observed for a given hypothetical structure. Parameters ---------- matched_hs_ions_df : pd.DataFrame Dataframe of...
a341b02b7ba64eb3b29032b4fe681267c5d36a00
22,243
def role_in(roles_allowed): """ A permission checker that checks that a role possessed by the user matches one of the role_in list """ def _check_with_authuser(authuser): return any(r in authuser.roles for r in roles_allowed) return _check_with_authuser
24ff0423dc50187f3607329342af6c8930596a36
22,244
from typing import List def elements_for_model(model: Model) -> List[str]: """Creates a list of elements to expect to register. Args: model: The model to create a list for. """ def increment(index: List[int], dims: List[int]) -> None: # assumes index and dims are the same length > 0 ...
a0769d762fc31ac128ad077e1601b3ba3bcd6a27
22,245
def form_IntegerNoneDefault(request): """ An integer field defaulting to None """ schema = schemaish.Structure() schema.add('myIntegerField', schemaish.Integer()) form = formish.Form(schema, 'form') form.defaults = {'myIntegerField':None} return form
322671035e232cfd99c7500fe0995d652a4fbe7a
22,246
import string def tokenize(text, stopwords): """Tokenizes and removes stopwords from the document""" without_punctuations = text.translate(str.maketrans('', '', string.punctuation)) tokens = word_tokenize(without_punctuations) filtered = [w.lower() for w in tokens if not w in stopwords] return fil...
7a231d124e89c97b53779fee00874fb2cb40155e
22,247
def to_dict(prim: Primitive) -> ObjectData: """Convert a primitive to a dictionary for serialization.""" val: BasePrimitive = prim.value data: ObjectData = { "name": val.name, "size": val.size, "signed": val.signed, "integer": prim in INTEGER_PRIMITIVES, } if val.min...
32d57b89e6740239b55b7f491e16de7f9b31a186
22,248
import requests def get_raw_img(url): """ Download input image from url. """ pic = False response = requests.get(url, stream=True) with open('./imgs/img.png', 'wb') as file: for chunk in response.iter_content(): file.write(chunk) pic = True response.close() ...
67b2cf9f2c89c26fca865ea93be8f6e32cfa2de5
22,249
def get_and_validate_study_id(chunked_download=False): """ Checks for a valid study object id or primary key. If neither is given, a 400 (bad request) error is raised. Study object id malformed (not 24 characters) causes 400 error. Study object id otherwise invalid causes 400 error. Study does n...
405420481c343afcaacbcfc14bc75fc7acf5aae9
22,250
import re def tokenize_char(pinyin: str) -> tuple[str, str, int] | None: """ Given a string containing the pinyin representation of a Chinese character, return a 3-tuple containing its initial (``str``), final (``str``), and tone (``int; [0-4]``), or ``None`` if it cannot be properly tokenized. """ ...
e4bfb4712857d9201daff187ab63c9846be17764
22,251
def is_in_cell(point:list, corners:list) -> bool: """ Checks if a point is within a cell. :param point: Tuple of lat/Y,lon/X-coordinates :param corners: List of corner coordinates :returns: Boolean whether point is within cell :Example: """ y1, y2, x1, x2 = corners[2][0], corn...
5f8f13a65ea4da1909a6b701a04e391ebed413dc
22,252
def json_response(function): """ This decorator can be used to catch :class:`~django.http.Http404` exceptions and convert them to a :class:`~django.http.JsonResponse`. Without this decorator, the exceptions would be converted to :class:`~django.http.HttpResponse`. :param function: The view function whi...
0b13ff38d932c64fd5afbb017601e34c1c26648b
22,253
import re def generate_junit_report_from_cfn_guard(report): """Generate Test Case from cloudformation guard report""" test_cases = [] count_id = 0 for file_findings in report: finding = file_findings["message"] # extract resource id from finsind line resource_regex = re.search...
cdf747c535042bf93c204fe8d2b647b3045f7ed7
22,254
def new_custom_alias(): """ Create a new custom alias Input: alias_prefix, for ex "www_groupon_com" alias_suffix, either .random_letters@simplelogin.co or @my-domain.com optional "hostname" in args Output: 201 if success 409 if the alias already exists """ ...
552812711eefd182d7671e3ac72776bbf908ff33
22,255
def seq(seq_aps): """Sequence of parsers `seq_aps`.""" if not seq_aps: return succeed(list()) else: ap = seq_aps[0] aps = seq_aps[1:] return ap << cons >> seq(aps)
ab94d3372f229e13a83387b256f3daa3ab2357a5
22,257
def Growth_factor_Heath(omega_m, z): """ Computes the unnormalised growth factor at redshift z given the present day value of omega_m. Uses the expression from Heath1977 Assumes Flat LCDM cosmology, which is fine given this is also assumed in CambGenerator. Possible improvement could be to tabulate...
c14e93a871f57c0566b13adb9005c54e68fbfa0f
22,258
def freq2bark(freq_axis): """ Frequency conversion from Hertz to Bark See E. Zwicker, H. Fastl: Psychoacoustics. Springer,Berlin, Heidelberg, 1990. The coefficients are linearly interpolated from the values given in table 6.1. Parameter --------- freq_axis : numpy.array ...
f6bd27c54debe8cd8b79099f106e1bf7d4350010
22,259
def close_connection(conn: Connection): """ Closes current connection. :param conn Connection: Connection to close. """ if conn: conn.close() return True return False
bca91687677860a7937875335701afb923ba49cc
22,261
import warnings def tile_memory_free(y, shape): """ XXX Will be deprecated Tile vector along multiple dimension without allocating new memory. Parameters ---------- y : np.array, shape (n,) data shape : np.array, shape (m), Returns ------- Y : np.array, shape (n, *sha...
f800c44ddd2a66553619157d8c8374a4c33dde18
22,262
def load_ref_system(): """ Returns d-talose as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" C -0.6934 -0.4440 -0.1550 C -2.0590 0.1297 0.3312 C -3.1553 -0.9249 0.167...
7b41df916cb06dccaa53f13461f2bb7c6bfd882a
22,263
def format_user_id(user_id): """ Format user id so Slack tags it Args: user_id (str): A slack user id Returns: str: A user id in a Slack tag """ return f"<@{user_id}>"
2b3a66739c3c9c52c5beb7161e4380a78c5e2664
22,264
import socket import ssl def test_module(params: dict): """ Returning 'ok' indicates that the integration works like it is supposed to. This test works by running the listening server to see if it will run. Args: params (dict): The integration parameters Returns: 'ok' if test pass...
0f49bff09fcb84fa810ee2c6d32a52089f2f0147
22,265
def class_loss_regr(num_classes, num_cam): """Loss function for rpn regression Args: num_anchors: number of anchors (9 in here) num_cam : number of cam (3 in here) Returns: Smooth L1 loss function 0.5*x*x (if x_abs < 1) x_abx - 0...
cad962f1af1a1acb2013063c6803261535652c18
22,266
import smtplib import ssl def smtplib_connector(hostname, port, username=None, password=None, use_ssl=False): """ A utility class that generates an SMTP connection factory. :param str hostname: The SMTP server's hostname :param int port: The SMTP server's connection port :param str username: The SMTP...
511fe48b1f3f2d5d3b9ef3a803166be1519a1b7f
22,267
def _to_one_hot_sequence(indexed_sequence_tensors): """Convert ints in sequence to one-hots. Turns indices (in the sequence) into one-hot vectors. Args: indexed_sequence_tensors: dict containing SEQUENCE_KEY field. For example: { 'sequence': '[1, 3, 3, 4, 12, 6]' # This is the amino acid ...
32ff14139b53f181d6f032e4e372357cf54c1d62
22,268
def kaiser_smooth(x,beta): """ kaiser window smoothing """ window_len=41 #Needs to be odd for proper response # extending the data at beginning and at the end # to apply the window at the borders s = np.r_[x[window_len-1:0:-1],x,x[-1...
2b766edd85927766330c8cddded3af639d5f16f3
22,269
def get_indel_dicts(bamfile, target): """Get all insertion in alignments within target. Return dict.""" samfile = pysam.AlignmentFile(bamfile, "rb") indel_coverage = defaultdict(int) indel_length = defaultdict(list) indel_length_coverage = dict() for c, s, e in parse_bed(target): s = i...
e8f6883f1cf1d653fe0825b4f10518daa2801178
22,270