content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def applyAlign(mrt,al): """ Takes meaning representation triples (mrt) and combines with alignments """ for alignment in al.split(): # Alignment: x9:arg0:sell:x11-39 fromNode,rest = alignment.split(":",1) rest,toAlign = rest.rsplit("-",1) edgeLabel,toNode ...
098f7a42e2661938138c703d9e0c337816c1dcd4
3,631,900
def get_unverified_jwt_claims(encoded_token): """ Returns the Headers of an encoded JWT without verifying the actual signature of JWT. Note: The signature is not verified so the header parameters should not be fully trusted until signature verification is complete :param encoded_token: The encode...
b041ab4579c6907c229bf3dd590e8ea559de24c5
3,631,901
def dos_orbitals( folder, orbitals, output='dos_orbitals.png', fill=True, alpha=0.3, linewidth=1.5, sigma=0.05, energyaxis='x', color_list=None, legend=True, total=True, figsize=(4, 3), erange=[-6, 6], spin='up', soc_axis=None, combination_method='add', ...
85fa9e17eaaf62e801e6439b135ff1c1ed86150d
3,631,902
from .ginzburg_landau import GinzburgLandau2Components from .flory_huggins import FloryHuggins2Components from .general import FreeEnergy from typing import Union def get_free_energy_single( free_energy: Union[str, FreeEnergyBase] = "ginzburg-landau" ) -> FreeEnergyBase: """get free energy for systems with a ...
d40d29543a943eb5fc7a9122627d1635aaa8fe43
3,631,903
import sys import termios import tty def unbuffered_input(): """Read a single character from stdin, without waiting for the enter key.""" # Adapted from http://code.activestate.com/recipes/134892/ fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setcbreak(fd) c...
40914c5b5582b7d23f6bde6db1ca242852239cf1
3,631,904
def convert_bin_to_text(bin_str: str) -> str: """Convert a string of binary to text. Parameters: ----------- bin_str: string: A string of binary, terminating with 00000000. Returns: -------- text: string: A plaintext representation of the binary string. """ # get nu...
8890ff192ae4b6e01401dd7f018bf8906c3c37ce
3,631,905
import select def _retrieve_transaction_type(t_type: str, connection) -> RowProxy: """ Retrieves Transaction Type Args: ttype (str): The transaction type that represents the trasaction being recorded 'archive' or 'compress'. Returns: RowProxy: The transaction_type """ tr...
f6b883b7e524f3dff5757f46de11e6fb10af66f2
3,631,906
def myDijkstra(graph, source, start, end): """ Implements Dijkstra's single source shortest path algorithm for a directed graph Parameters: graph: the graph we are working on source (int): the vertex choose as source start (strin...
3296b510dafe4e3b08550ae771e137f7139f4eea
3,631,907
def scale_on_x_list(x_list, scaler): """Scale list of ndarray. """ return [scaler.transform(e) for e in x_list]
2fbe36cb23e99ca6eaf277fb5509e2e997ec4a52
3,631,908
from .model_store import get_model_file import os def get_centernet(backbone, backbone_out_channels, classes, model_name=None, pretrained=False, ctx=cpu(), root=os.path.join("~", ".mxnet", "models"), ...
3599aea3bb88eebf4c91c4d2bc3c3d1f30b713ce
3,631,909
def calc_distance(origin, destination): """ title:: calc_distance description:: Great-circle distance between two points on a sphere from their longitudes and latitudes. author:: Stackoverflow User: user2514381 https://stackoverflow.com/questions/1727312...
02f9e63970e9e2f561cea095c045e08618e5e444
3,631,910
import tokenizers def tokenize(string,tokenizer = tokenizers.keras): """ Tokenizes a string using the selected tokenizer. :param string: the string to tokenize :param tokenizer: which tokenizer to use (nltk or keras) :return: the list of tokens """ if tokenizer == tokenizers.nltk: ...
8d158f3bb97356724a1f1438bc8e5d91314af367
3,631,911
import math def move_point(pt: XY, distance: float, degrees: float) -> XY: """ Create a new point that is the original point moved by distance (m) in direction degrees. """ x = pt.x + distance * math.cos(math.radians(degrees)) y = pt.y + distance * math.sin(math.radians(degrees)) return XY(x, ...
51fa927ca06525b91985af652ed7579ed72903a9
3,631,912
import jinja2 from datetime import datetime def _generate_follow_up(the_date, vms, template='delete_followup.html'): """Create the HTML email body stating what VMs were randomly deleted. :Returns: String :param the_date: The specific time when vLab randomly deleted a user's VM(s). :type the_date: In...
8a72a21dd653c86fc4e6fb4bd5246b84b88300cd
3,631,913
def find_empty_node(grid): """There should be one and only one empty node. Find it and return its location as a tuple.""" for x in range(len(grid)): row = grid[x] for y in range(len(row)): if row[y][USED] == 0: return (x, y) # else: # p...
778b4424f4bcb45db093a40e879628b13f3d9a4f
3,631,914
import hashlib def md5(ori_str): """ MD5加密算法 :param ori_str: 原始字符串 :return: 加密后的字符串 """ md5_obj = hashlib.md5() md5_obj.update(ori_str.encode("utf8")) return md5_obj.hexdigest()
75efc3226c2f0355ce4b988acd6dcd1a95ea8294
3,631,915
import getpass def getuser() -> str: """ Get the username of the current user. Will leverage the ``getpass`` package. Returns: str: The username of the current user """ return getpass.getuser()
3f6053e9aba37f7eafcd7735d7509af290fd3940
3,631,916
import requests def order_depth(type_id: int, region_id: int = 10000002, system_id: int = None, order_type: str = 'sell'): """ Pulls the orders for a specified typeid in a region Args: type_id: typeid to pull the market orders for region_id: the region the orders should be pulled from. th...
da369f5732e642bf352be85541f52dd1531d0512
3,631,917
import ctypes def get_normal_amps(): """This parameter will deliver the normal ampere rating for the active PDElement.""" return dsslib.CktElementF(ctypes.c_int32(0), ctypes.c_double(0))
16a97d32658a5e6e19d99b952724116d5c729857
3,631,918
def cal_pipe_equivalent_length(tot_bui_height_m, panel_prop, total_area_module): """ To calculate the equivalent length of pipings in buildings :param tot_bui_height_m: total heights of buildings :type tot_bui_height_m: float :param panel_prop: properties of the solar panels :type panel_prop: di...
60c95cc1c5a38876095a77f4e68ab3b0df6280a3
3,631,919
def embedding_to_padding(maxlen, sequence_length): """ Calculates the padding mask based on `sequence_length`. Args: maxlen: The maximum sequence length. sequence_length: Length of each sequence in `emb`, a Tensor with shape [batch_size, ] Returns: A float Tensor with shape [bat...
fdd0660e7e9edbaa6523ac266dcd44873b8efccf
3,631,920
from typing import List import tqdm import csv def csv_fat_cross_time(arrival_enum: ArrivalEnum, list_number_servers: List[int], perform_param: PerformParameter, opt_method: OptMethod, mc_dist: MonteCarloDist, target_util: float) -> dict: """Cho...
5929ab69781ef979255f79f01d840fca336f19cd
3,631,921
def service_status() -> Response: """ Service status endpoint. Returns ``200 OK`` if the service is up and ready to handle requests. """ data, code, headers = controllers.service_status(request.params) response: Response = jsonify(data) response.status_code = code response.headers.exten...
dbdb33253cc2a74d4c02a91e711eba7731be60de
3,631,922
import os def handler500(request, exception=None, template_name='templates/500.html'): """500 Error Page Controller""" controller = Controller() helpers = Helpers() logger = helpers.get_logger(__name__) if exception is not None: logger.error("Server Error: %(exception)s" % { ...
03d1ad0a6aabc9fa117fc37047144ff4b9561305
3,631,923
def gromov_wasserstein2(C1, C2, p, q, loss_fun, epsilon, max_iter=1000, tol=1e-9, verbose=False, log=False): """ Returns the gromov-wasserstein discrepancy between the two measured similarity matrices (C1,p) and (C2,q) The function solves the following optimization problem: ...
5a30cc1ea70bfc6c0310d791f6bb61d37df59b83
3,631,924
import copy def parseOptions(json_options): """Parse the raw son options. Parses the parameter values into ranges and adds missing information that can be inferred from other values. Returns parsed options as dictionary""" parsed = dict(json_options) if "algorithms" in json_options: ...
d254c1fd36245119bca67f19935e4a76dcb8e592
3,631,925
def numeric_type(num): """ Verify that a value is given as a numeric data type. Return the number if the type is sensible or raise ValueError if not. """ if num is None: num = 0 elif not (isinstance(num, int) or \ isinstance(num, long) or \ isinstance...
3ef13db9477c0278e69bb7c2293083e00d01d48a
3,631,926
from typing import Union async def load(payload: None, context: EventContext, *, item_id: str, update_status: bool = False) -> Union[Something, SomethingNotFound]: """ Loads json file from redis as `Something` instance :param payload: unused :param context: EventContext :param item...
c56fcd15e9c7151c2b58c34c4cf32a36c9488a3a
3,631,927
def format_parameters(section): """Format the "Parameters" section.""" def format_item(item): item = map(lambda x: x.strip(), item) return ' - **{0}**: *{1}*\n {2}'.format(*item) return '**Parameters**\n\n{0}'.format('\n\n'.join( map(format_item, section)))
8f1393b843b6ea46d69d5644f932f7f0e62160ab
3,631,928
def get_kinds(cell, mf, kpts, tol=1e-6): """Given a list of kpts, return inds such that mf.kpts[inds] is a list of kpts equivalent to the input list""" kdiffs = mf.kpts[np.newaxis] - kpts[:, np.newaxis] frac_kdiffs = np.dot(kdiffs, cell.lattice_vectors().T) / (2 * np.pi) kdiffs = np.mod(frac_kdiffs + 0....
f187a01eef1349db1fb47582d409070f7362ecc5
3,631,929
from typing import List def restore_checkpoints( models: List[tf.keras.Model], ckpt_dir: str) -> tf.keras.Model: """Restores weights from the checkpoint.""" attr_names = list(ATTRIBUTES.keys()) for i in range(2): attr_name = attr_names[i] print("Restoring weights for attribute %s" % at...
25d7e9c5e6fbb27119e3be4888d9f7c3c5ec2391
3,631,930
def get_schema_piece(content_piece, uniprot_to_dcid): """Generate each Args: content_piece example: AAC ABCD_AU181 BIT Nanobody AID anti-SARS-CoV-2 Nb TTY Protein TGP UniProt:P0DTC2 TDE S, Spike protein, Spike glycoprotein TPE Receptor-bindi...
ad7e3a8f47624602057c1ffac6e772b721722488
3,631,931
import copy def editViewData(uniqueValue): """Edit the source service data for the current unique value""" # Create a copy from the source service data uniqueValueData = copy.deepcopy(_sourceServiceData) # Change service data to use current unique value information (assumes a string value ) uniq...
5a67a269e94d6906f7e1bbab757be75a875cbbd9
3,631,932
import sys as _sys def _add_dll_dir(): """ On windows for Python 3.8 or later, we have to add the bin directory to the search path for DLLs Because python will no longer use the PATH environment variable to find dlls. We assume here that this file is in $(RELEASE_DIR)\lib\python\htcondor and that the ...
0e3eb74d93c7bfd49f18a82a4b00d5cc431ebb28
3,631,933
import functools def _borg_pod_set_with_safe_self_access(wrapped_method): """ Wrapper for __setattr__ methods in @assimilate decorated classes to apply self.queen injection wrapper on any relevant instance methods set during runtime. :param Function wrapped_method: A @assimilate decorated class's...
b0dcfa6869a866794c088ac3c51eb682ca823206
3,631,934
from typing import Union from typing import Iterable from typing import Any def prepend(catch: Union[type, tuple[type]], *values: Iterable[Union[Any, Iterable[Any]]]): """ Return a context manager that catches exception(s), prepends value(s) to the exception's message (first argument) and reraises the exc...
9a6a1e4e1061cc6fde92b45bdc18e367d19504ec
3,631,935
import hashlib def sha256(message): """ Returns the hexadecimal representation of the SHA256 hash digest. """ return hashlib.sha256(to_bytes(message)).hexdigest()
1f57e10c59f896424f79dce274c153c036d4f85a
3,631,936
def _grouprule_aggs_filter(having, columns): """ Given (having) conditions, return what to filter on as a string, to be used after groupbys as grouped.query(string returned by this function). :param having: :type having: list :param columns: Columns on which the group by is made. :type colu...
86243383bc3bd6f66751effe275ffaa0c34edf5e
3,631,937
def _trim(s): """ Trim long string to LOG_ENTRY_MAX_STRING(+3) length """ return s if not isinstance(s, str) or len(s) < LOG_ENTRY_MAX_STRING else s[:LOG_ENTRY_MAX_STRING] + '...'
2e7a74796edcd63ffb5ab63254ae64989e3ad4bd
3,631,938
def get_id_or_name(value, model): """Returns the id or name of a model instance from value. If a number or a string is supplied, a check will be made to make sure it exists in the data store. """ if not issubclass(model, db.Model): raise TypeError('Invalid type (model); expected subclass of ...
169643c95443a51d87bab87efc9a80ff9f98eca7
3,631,939
def validate_query_handler(query_string): """Verify the input query is some level of valid, right now it does not check the value sent, just the key. Currently only support one key, value pair -- but does verify this is supplied.""" # likely throws an exception on parse error. query_dict = p...
c342ef1aee9d8cf022848b2cfa9c3c43b47c5c4a
3,631,940
from datetime import datetime import time def makevalue(t, value): """Get value of ctypes-compatible value in XDWAPI-compatible type.""" t = XDW_ATTRIBUTE_TYPE.normalize(t) if t == XDW_ATYPE_INT: return int(value) elif t == XDW_ATYPE_STRING: return str(value) elif t == XDW_ATYPE_DA...
176b4f86f7dde0a21f304cc6205792e8cdc9e6f2
3,631,941
from typing import Optional def parse_directive_definition( directive_definition_node: "DirectiveDefinitionNode", schema: "GraphQLSchema", ) -> Optional["GraphQLDirective"]: """ Computes an AST directive definition node into a GraphQLDirective instance. :param directive_definition_node: AST direct...
47cfdae0387373c1ed37627ec3194cf72070e3a9
3,631,942
def _find_literal(s, start, level, parts, exprs): """Roughly Python/ast.c:fstring_find_literal""" i = start parse_expr = True while i < len(s): ch = s[i] if ch in ("{", "}"): if level == 0: if i + 1 < len(s) and s[i + 1] == ch: i += 2 ...
39e7d97f8aa4bfcd79af00359395605c5910985c
3,631,943
import collections def evaluate(ref_intervals, ref_labels, est_intervals, est_labels, **kwargs): """Compute all metrics for the given reference and estimated annotations. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals,...
62dc19f4f8e5341db53ff59d89d0cda26b14e7fc
3,631,944
import argparse def parse_arguments(): """Arguments parsing.""" parser = argparse.ArgumentParser("my_agent", description="Launch my agent.") parser.add_argument("--name", default="my_agent", help="Name of the agent") parser.add_argument( "--oef-addr", default="127.0.0.1", help="TCP/IP address ...
d1b747e8ed9d57d63cb02c58eb585ffa649dc42e
3,631,945
import re def amex(value): """ Return whether or not given value is a valid American Express card number. Examples:: >>> amex('378282246310005') True >>> amex('4242424242424242') ValidationFailure(func=amex, args={'value': '4242424242424242'}) .. versionadded:: 0.15...
fa17a2631607d7e22b5b6cb5f0e85689e403c4d1
3,631,946
def rel_multihead_attn(q, k, v, pos_enc, seg_mat, attn_mask, d_model, n_head, d_head, dropout, dropatt, is_training, initializer, attn_bias=None, func_mask=None, scope="rel_attn", reuse=None, rel_attn_type="factorized", name='rel_attn'): """Multi-head attention with rel...
bc6fc963dee32c20f4dc54b25b7a615f39dc0ec2
3,631,947
import os import subprocess def validate_move(main_prefix: str, original_path: str, new_file: str) -> bool: """Checks that a given file exists at the location in the main bucket and no longer exists in the upload bucket. Returns True if this is the case and False otherwise. """ main_path = os.path...
12b9003604e6b5f79ebc3e1639a7162ca9b24ac6
3,631,948
def incident_created_modal_payload(pd_api_response): """Return the Slack Block Kit payload for the "Incident created" modal""" safe_summary = slack_escape(pd_api_response["summary"]) return { "response_action": "update", "view": { "type": "modal", "title": {"type": "p...
1e1e44c564aae6861099810f86de5051372a461e
3,631,949
import re def split_name(package: str): """ Use regex to properly split the string into name and version spec """ version_tuple = re.search('(-\d{1,10}\.\d{1,10}\.\d{1,10}-?.{0,50})', package) version_string = version_tuple.groups()[0] version = version_string.split("-", 1)[1] name = re.split('(-...
57923f6d1af86c2b6f1b4afeded92c7af1dfca30
3,631,950
def buchdahl_find_alpha(wv, indices, wv_center, n_center, order=3, gtol=1.0e-9): """ Find the Buchdahl alpha parameter which gives a refractive index versus omega curve that is closest to a straight line. Parameters ---------- wv : array of float Wavelengths at which the refractive index da...
fd8f5d16bf721f8b0385ad3c5af79ebe7cea3df2
3,631,951
import os import time def ddpg_n_step_new(env_name, render_env=False, actor_hidden_layers=[300, 300], critic_hidden_layers=[300, 300], seed=0, steps_per_epoch=5000, epochs=100, replay_size=int(1e6), gamma=0.99, n_step=1, backup_method='mi...
f9fd8b1f560253f45ab6a5121b558c5fbb788427
3,631,952
from re import T def shn_pentity_represent(id, default_label="[No ID Tag]"): """ Represent a Person Entity in option fields or list views """ pe_str = T("None (no such record)") pe_table = db.pr_pentity pe = db(pe_table.pe_id == id).select(pe_table.instance_type, ...
d48ce7d28f48d57f7386a34bacecc0f6a42bf21a
3,631,953
def calculate_mean_SD_CV(df, ranking, mean_col_name): """calculate the mean coefficient of variation of the tFs binding to a promoter""" # group by promoter and calculate mean for each promoter means = df.groupby("promoter_AGI")[ranking].mean() # turn into a dataframe means_df = pd.DataFrame(means) ...
8fbefc305ea3ada337cf929e19953c3e56549b64
3,631,954
def normalize_trinucleotide(trinucleotide): """Return the normalized representation of the input trinucleotide sequence Notes ----- Each trinucleotide sequence has two possible representations (the sequence and its reverse complement). For example, 5'-ACG-3' and 5'-CGT-3' are two representation...
fe04ba6fad28285eac9becbbd6e5324ec7734850
3,631,955
import os def extract_file_by_file(location, target_dir, arch_type='*', skip_symlinks=True): """ Extract all files using a one-by-one process from a 7zip-supported archive file at location in the `target_dir` directory. Return a list of warning messages if any or an empty list. Raise exception on...
895504f153318c3c84f6e4a1bcf58ac0867aa344
3,631,956
def r2z(data): """ Fischer's r-to-z transform on a matrix (elementwise). """ return(0.5 * np.log((1+data) / (1-data)))
8874829837c2b47d019325835b73080cd524c0ac
3,631,957
def loader_shift(loader, frame, relative=True): """Shift global in time by i preserving duration This moves the loader by i frames preserving global duration. When relative is False it will shift the global in to the start frame. Args: loader (tool): The fusion loader tool. frame (int)...
2593473b58aad8e073aaf7d4adc978e12df20762
3,631,958
import time def get_current_timestamp(): # pylint: disable=unused-variable """ Retrieves the current local time in a custom timestamp format """ return time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
839ef3e2bc434355d5b077ef4e2a1cb138fab2d1
3,631,959
from datetime import datetime def get_fight_updates(game_ids=None, before=None, after=None, order=None, count=None, page_size=1000, lazy=False, cache_time=5): """ Return a list of boss fight event updates Args: game_ids: list or comma-separated string of fight IDs. before: return elements...
69b32e224cd2651de850b03fd3ba2fef05e327cc
3,631,960
import math def format_float(number, decimal_places): """ Accurately round a floating-point number to the specified decimal places (useful for formatting results). """ divisor = math.pow(10, decimal_places) value = number * divisor + .5 value = str(int(value) / divisor) frac = value.sp...
e7aaa92025284489075ce053319c27310bb96a00
3,631,961
def make_mean_edisp( observations, position, e_true, e_reco, low_reco_threshold=Energy(0.002, "TeV"), high_reco_threshold=Energy(150, "TeV"), ): """Compute mean energy dispersion. Compute the mean edisp of a set of observations j at a given position The stacking is implemented in :...
3f8ba4d8f6434dd0e6711f691dc650a061ee2a9e
3,631,962
import time def formatTime ( sec, nsec, fmt ): """ Convert given time to a string presentation according to a given control sequence """ # replace %f (and its variations) with fractional seconds match = _ffmtre.search ( fmt, 0 ) while match : # make replacement string sub...
ad7e2b553545093b7834007453774bdb4cd62507
3,631,963
def CalculateChi6ch(mol): """ ################################################################# Calculation of molecular connectivity chi index for cycles of 6 ---->Chi6ch Usage: result=CalculateChi6ch(mol) Input: mol is a molecule object. ...
240d97be1740b9af691598cd71d47473ce770d53
3,631,964
def decode_transaction_filter(metadata_bytes): """Decodes transaction filter from metadata bytes Args: metadata_bytes (str): Encoded list of transaction filters Returns: decoded transaction_filter list """ transaction_filter = [] if not metadata_bytes: return None for i in...
c76638f6592fb098e2878471746152aa9df9a694
3,631,965
def get_signin_box(burl): """ xxx """ box_content = '' if user_is_login() == 0: l_app_header_title = 'Create unlimited optimized trading strategies' l_app_header_desc = 'Chart patterns, price movements, '+\ 'and news analysed using quantitative methods '+\ 'with the power of...
4181779ad6e8ce7924c2854e4e6e9b7d0d47926b
3,631,966
import json def jsonify(*args, **kwargs): """ jsonify with support for MongoDB ObjectId """ return Response( json.dumps( dict( *args, **kwargs), cls=MongoJSONEncoder), mimetype='application/json')
8001fe488e412bbf63cad7c9c359431fe9108b2c
3,631,967
def parse_variable(srcline, funcname=None): """Return a Variable for the variable declared on the line (or None).""" line = srcline.strip() # XXX Handle more than just static variables. if line.startswith('static '): if '(' in line and '[' not in line: # a function retur...
ff4027f1e3919087016c8169ff1ad8ac7ebf111b
3,631,968
def _assert_df_is_valid_cforest(candidate_model): """Assert *df* represents valid causal forest. A valid causal forest model is given by a pd.DataFrame which fulfills the following criteria: 1 (MultiIndex). The data frame *df* must have a MultiIndex with the first layer 'tree_id' and the second layer '...
cf1c52037705ce86940ca4c9e6fdf4b1055dea65
3,631,969
def is_ip(str_value: str) -> bool: """Returns True if string represents and IP address (either IPv4 or IPv6), else False. :param str str_value: String to evaluate. """ return is_ipv4(str_value) or is_ipv6(str_value)
1438148ab98ce882cd5e27961268726bae4450e0
3,631,970
def parse_ply(fin): """Parse vertex data from a PLY format Retuns a dictionary of keys to numpy arrays """ num_pts, attr_key, attr_type = parse_ply_header(fin) data = [[] for k in attr_key] for i in range(num_pts): line = next(fin) tokens = line.split() for j, t in enum...
13558f96b55d2155cc032771acda272cfa7e5d0b
3,631,971
def energy_change_charge_qa_atom( df_qc, df_qats, target_label, delta_charge, target_initial_charge=0, change_signs=False, basis_set='aug-cc-pV5Z', use_ts=True, ignore_one_row=True, considered_lambdas=None, return_qats_vs_qa=False): """Calculate the energy difference to change the charge of a target ato...
30c8b15a5e25edd0d05352066a1e3533c5182cd6
3,631,972
import click def initiate_XY_data(config): """Initiates an empty dictionary to contain the XY-data for each polygon, ie. both sample data and target data. This is needed for the reference run. By default, the first column is for the polygon ID, the second for polygon geometry. The antepenultimate col...
eb0b2167845920631982bab3b7bc3405178176cc
3,631,973
def load_key_string_pubkey(string, callback=util.passphrase_callback): # type: (str, Callable) -> PKey """ Load an M2Crypto.EC.PKey from a public key as a string. :param string: String containing the key in PEM format. :param callback: A Python callable object that is invoked ...
9283aff352a84cb99a382f88d6f7cca5ea0ee837
3,631,974
import os def lookuptemplate(ui, topic, tmpl): """Find the template matching the given -T/--template spec 'tmpl' 'tmpl' can be any of the following: - a literal template (e.g. '{rev}') - a map-file name or path (e.g. 'changelog') - a reference to [templates] in config file - a path to ra...
604b0d0b1a773464ce5cd61df0b1a2d0800a7314
3,631,975
def merge(left, right, path=None): """Merge dicts""" if path is None: path = [] for key in right: if key in left: if isinstance(left[key], dict) and isinstance(right[key], dict): merge(left[key], right[key], path + [str(key)]) elif left[key] == right[...
cb313f153225af41626885ae0ee066215dce3b0e
3,631,976
def resize_min_side(pil_img, min_len): """ Resize image such that the shortest side length = mins_len pixels :param pil_img: :param mins_len: :return: """ # What's the min side? w, h = pil_img.size if w < h: new_w = min_len new_h = int(np.round(h * (new_w / float(w)))...
38aeeedf107bedf2c82948248fbdc2483d6d2c10
3,631,977
def get_numeric_boundaries(df: DataFrame, column_name: str) -> (float, float): """ get the min and max values in a numric column. forces a cast to float. If the column can't be casted as such then this wil throw an error which is currently not trapped :param df: :param column_name: :return: (min...
a02eefd1d6e6f2697350d5e48201e57cbb24c870
3,631,978
from typing import Optional def concatenate(data: tvm.te.Tensor, axis: Optional[int] = 0): """Join a sequence of arrays along an existing axis. Optimized for CPU exeution. Parameters ---------- data : tuple of tvm.te.Tensor The arrays to concatenate axis : int, optional The axis ...
d9bb934f9518a565dab341316247294c525ea2c1
3,631,979
def defgrad_from_strain(E, kappa, flatten=1): """Compute the deformation gradient from the strain measure Parameters ---------- E : ndarray (6,) Strain measure kappa : int or float Seth-Hill strain parameter flatten : bool, optional If True (default), return a flattened ...
3b18515562c3dd30757f9942627ac082eb3947b7
3,631,980
import hashlib def get_url_gravatar(email): """ Obtenemos una url de gravatar """ m = hashlib.md5() m.update(email.encode('utf-8')) url = "http://www.gravatar.com/avatar/{0}.jpg?s=300".format(m.hexdigest()) return url
bf48d903445869ee91c685dd1b84e11034dc528c
3,631,981
def volume_type_qos_disassociate_all(context, qos_specs_id): """Disassociate all volume types from specific qos specs.""" return IMPL.volume_type_qos_disassociate_all(context, qos_specs_id)
16ff0f985dd96d1f2a3aa32022c06c84a1c5f531
3,631,982
def create_command_at_set(command_set, command): """ create a command on set """ command_entry = CommandEntry.objects.create( command_set=command_set, command=command ) return command_entry
a4e8367077f5a42b62e27be1e66f2a4c5cf490d0
3,631,983
def get_index_image(): """Formats html. Returns: Modified index.html content """ return """<!DOCTYPE HTML><html lang="en-us"> <head> </head> <body style='margin:0'> <img src='image.[[image_ext]]'> </body> </html>"""
41ea7fbc31e49879216e46083b102294edb5c76f
3,631,984
def merge_schema(original: dict, other: dict) -> dict: """Merge two schema dictionaries into single dict Args: original (dict): Source schema dictionary other (dict): Schema dictionary to append to the source Returns: dict: Dictionary value of new merged schema """ source =...
6425b64e6ab166ac14afc2e47392745903b8fd12
3,631,985
def noise_eq_bandwidth(window, axis=-1): """ Calculate the noise equivalent bandwidth (NEB) of a windowing function as sqrt(window.size * window.max ** 2 / sum(window ** 2)) See https://analog.intgckts.com/equivalent-noise-bandwidth/ Args: window : float ndarray axis : int,...
dd13abac6b9d39b68a1b3658fe4fba90be8c82cf
3,631,986
import hashlib def hash160(s: bytes) -> bytes: """ sha256 followed by ripemd160 :param s: data :return: hashed data """ return hashlib.new('ripemd160', hashlib.sha256(s).digest()).digest()
7b18fcdf51db707a17d5408c7b364818a6c5ee0c
3,631,987
def trim_frame(fr: NDFrame, freq: str) -> NDFrame: """Trim index of frame to only keep full periods of certain frequency. Parameters ---------- fr : NDFrame The (untrimmed) pandas series or dataframe. freq : str Frequency to trim to. E.g. 'MS' to only keep full months. Returns ...
c8b87ea993510725dc8f4074eeb07ea029445f0a
3,631,988
def settings_alert_rules(request): """ To allow users to manage alert rules for given sites """ context_dict = {} sites = _get_user_sites(request) user_sites = _get_user_sites(request) context_dict['permitted'] = get_org_edit_permissions(request.user) context_dict['sites_stats'] = g...
b8e1326abdb96929f3451c6aae06093f94de0723
3,631,989
from typing import List def generate_states_1qubit(c_sys: CompositeSystem, names: List[str]) -> List[State]: """returns a list of states on a common 1-qubit system. Parameters ---------- c_sys: CompositeSystem 1-qubit system names: List[str] list of 1-qubit state names Retur...
3c4188d50181a9a7c21b50f2b655cb212249c9e2
3,631,990
def fix_columns(data, text_1_name=None, text_2_name=None, label_name=None): """ Rename columns in an input data frame to the ones bisemantic expects. Drop unused columns. If an argument is not None the corresponding column must already be in the raw data. :param data: raw data :type data: pandas.Da...
7a87e853f5f5e41afcb4ec0a40ebddea234ca289
3,631,991
import os def substitute_placeholders_from_file_to_memory(filename, verb, data): """replace all variables placeholders in filename and return the result""" if os.path.exists(filename): with open(filename, "r") as in_file: buffer = substitute_placeholders_from_memory_to_memory( ...
9a46200f6984d31752bf79d4b8e13872ac278253
3,631,992
def unpack_kgrid(n, vals, log=null_log): """ Unpack the 'pyramid' of values u>=v>=w into the (n,n,n) k-grid. n - the size of the grid vals - m(m+1)(m+2)/6 values in the pyramid returns out - (n,n,n) float64 array. """ lib = _initlib(log) v = require(vals, dtype=float64, require...
62d7a364d43cc2c4cf1c181aa054d94200ea53a1
3,631,993
import re def valid_email(email): """Check for a valid email address. Args: email (str): Email. Returns: bool: Return True if in valid email format and False if not. """ return bool(re.match('^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$', email))
01c343008229fb2fdf2af3a9a74f3059930696eb
3,631,994
import traceback def db_remove(key): """ Endpoint Function to interact with PupDB's remove() method. """ try: if not key: return {'error': 'Missing parameter \'key\''}, 400 try: result = DB.remove(key) except KeyError as key_err: return {'error': s...
e354fe2f648cd4ad5c8ff7804789488b01edbe6c
3,631,995
def rgb2gray(img): """ Given an RGB image return the gray scale image. Based on http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale img = 0.299 R + 0.587 G + 0.114 B """ print('Converting RGB image to gray scale.') return np.uint8(np.dot(img[...,:3], [0.299, 0.587, 0.114]))
37207a3f66e5008a358f3e4961e809ca658687bc
3,631,996
def search(): """获取随机推荐""" html = '<form action="/blog/search/" method="get" name="form" ><div class="my-search" >' \ '<input type="text" name="q" autocomplete="off" placeholder="请输入搜索内容" class="search-input">' \ '<i class="layui-icon layui-icon-search search-btn" onclick="javascript:form....
86a02c2de79476ae6bea7cd733e502658a5f7555
3,631,997
def find_number(text, ignore_spaces=False, make_int=True, ignore_chars=None): """ Find the number in the `text`. :param text: unicode or byte-string text :param ignore_spaces: if True then groups of digits delimited by spaces are considered as one number :raises: :class:`Dat...
d15c5468e965913a6b885f3f5835ed7441481e6f
3,631,998
def PeerDownHasBgpNotification(reason): """Determine whether or not a BMP Peer Down message as a BGP notification. Args: reason: the Peer Down reason code (from the draft) Returns: True if there will be a BGP Notification, False if not """ return reason == 1 or reason == 3
8ee214798f6766916e8784dd907eeb45ff6620db
3,631,999