content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def normalize(array, inplace=False): """ Normalize an array using the mean and standard deviation calculated over the entire dataset. @param array: Numpy array to normalize. @param inplace: Whether to perform the normalization steps in-place. @return: Normalized array. """ if inplace: ...
563c4b79392eaf653c2c09261f87b574e25b6398
64,822
def guess_type(v, consumer='python'): """Guess the type of a value (None, int, float or string) for different types of consumers (Python, SQLite etc.). For Python, use isinstance() to check for example if a number is an integer. >>> guess_type('1') 1 >>> guess_type('1', 'sqlite') 'integer' ...
a9361d5ce7f070f09dca267afb4ffcae866040eb
64,823
def _html_alert_danger(msg: str) -> HTML: """Display a message as a Bootstrap-styled HTML alert in a Jupyter notebook.""" html_str = f'<div class="alert alert-danger" style="margin: 5px;">☠️ &nbsp; {msg}</div>' return HTML(html_str)
acce8d423bd3c831e2c06edfb188492be895e23d
64,824
from typing import Tuple from typing import Dict from typing import Set from typing import Counter import tokenize def read_sentences(sentence_file: str) -> Tuple[Dict[int, Tuple[str, str]], Dict[str, Set[str]]]: """Read and process a sentence file. Paramenters ----------- sentence_file: str ...
861e12e52019700ee5cf592e23be035969a0cb7a
64,826
def resize_deprecated(X,shape=None): """ Deprecated since 2017.06.26 resizes N-D array X into shape. For example, 2D 100 * 100 array -> 200 * 200 new = resize(img, [200,200]) NOTE ---- Doesn't work if the image is not rectangular. """ if shape==None: return X ...
44c8fdd32fa21bce892d76c5968b9be6dbbc74bc
64,827
def _gaussian_weighting(x): # pragma: no cover """ Kernel function for loess with a gaussian shape. The span f covers 95% of the gaussian. """ w = np.exp(-(x ** 2) / (2 * (1 / 1.96) ** 2)) w[x >= 1] = 0 return w
0c4e9d15ee94d099aa9171898b825da6a272a995
64,829
import torch def array_from_skew_matrix(x, device=torch.device("cpu"), dtype=torch.float32): """ Receives a skew matrix and returns its associated 3-element vector (array). :param x: Skew matrix (3x3) :return: Associated array (3-element). :param device: Device to allocate new tensors. Default: torch...
54dcb699db154e8c995dc324888b633451cfb7fc
64,830
def binary(img,th=128): """generate binary image Args: img : image array th : threshold """ img[img<th] = 0 img[img>=th] = 255 return img
627c3fc928886facbae8ca4cf692f543f4cbca40
64,831
from datetime import datetime def parse_string_to_timedelta(string): """Convert a string in the form "4 horas" to timedelta object""" string_mapping = {"horas": "hours", "hora": "hours", "días": "days", "día": "days", "dia...
74acaba66dde87951b798df6a1957652d6a2a06e
64,833
from typing import Any def squeezenet1_1( pretrained: bool = False, progress: bool = True, **kwargs: Any ) -> SqueezeNet: """ Constructs the SqueezeNet 1.1 model. .. note:: SqueezeNet 1.1 model from the `SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size <https...
7a01d0acdb551900d6d9302d54c50063e8a322a8
64,835
def get_set_layout_path(): """ creates and return the config folder path for layout files """ return get_set_config_path('layout_configs')
fcabe52039bccba5a1718d5db8870041c49b42d7
64,836
import socket def make_data_sender_socket(ip_address=None): """Create a socket for sending multicast data.""" ip_address = gethostip() if not ip_address else ip_address datasock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) datasock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) dat...
bc1b523a70fa41fb1d15245d6bf4e46ebc51e0c4
64,837
def tgp_eur_data_path(): """ Return the path of the attached 1000G sample data for European individuals (N=378) and chromosome 22 (p=15938) """ return osp.join(osp.dirname(__file__), 'data/1000G_eur_chr22')
daa617745dc47aaad688a4e90b92ed292d590ac3
64,838
import hashlib def _bundle(repo, bases, heads, node, suffix, compress=True, obsolescence=True): """create a bundle with the specified revisions as a backup""" backupdir = "strip-backup" vfs = repo.vfs if not vfs.isdir(backupdir): vfs.mkdir(backupdir) # Include a hash of all the nodes in ...
831955e75e7fc3e11df1bde12211f3adec69f7d2
64,839
def make_external(url): """Return the external version of a url.""" return urljoin(request.url_root, url)
81f11aff77d385e7eab351eb167b21c6438c1ff5
64,840
def preprocess_text(text, fix_unicode=False, lowercase=False, transliterate=False, no_urls=False, no_emails=False, no_phone_numbers=False, no_numbers=False, no_currency_symbols=False, no_punct=False, no_contractions=False, no_accents=False): """ Normal...
f5472121bf3b9581df8cc58c32659ccf23d2c1f4
64,841
def makemove (b): """computer moves""" # return makemove1st (b) return makemoverand1 (b)
5850639a09cfd64989ce4e33fec0ce87b2c99ea5
64,842
def float16_scope(): """Scope class for float16.""" def _custom_getter(getter, *args, **kwargs): """Returns a custom getter that methods must be called under.""" cast_to_float16 = False requested_dtype = kwargs['dtype'] if requested_dtype == tf.float16: kwargs['dtype...
8c5c555ba2f32853c40fb1799ca0de8f4bd9b275
64,843
def download_works_file(data_dir=None, save=True): """ Download the runeberg.org works file to t.lst and convert it to utf-8. @param data_dir: the directory to which the data should be downloaded. Defaults to DATA_DIR. @param save: whether the file should be saved or the stream returned @re...
a9e6a94ef976de12d2b64f5ea21221ff5db1277a
64,844
import csv def csv_download(request): """ Creates a CSV file using all of the applications to the users organization. """ apps = get_all_applications_for_users_org(request.user) data = ApplicationCSVDownloadSerializer(apps, many=True).data fields = [] for datum in data: these_field...
65fbf7937475abd40c7ebd8bf1d037dba878d3e5
64,845
import logging def build_bifpn_layer(feats, feat_sizes, config): """Builds a feature pyramid given previous feature pyramid and config. Args: feats: [P3, P4, P5, P6, P7] config: a dict-like config, including all parameters. Returns: {3:P3", 4:P4", 5:P5", 6:P6", 7:P7"} """ if conf...
3a3f9d2dcccf6a36c23b044f19082c8732c7f165
64,846
def get_trace_len(df): """ get the length of trace """ cid = list(df['CaseID']) dic = {} for i in cid: if i in dic: dic[i] += 1 else: dic[i] = 1 trace_len = int(max(dic.values())) return trace_len
a199b320df2c61a04cde676814350878b0bf89a0
64,847
def div_pow2_fp(x, powof2): """Divide by a power of two.""" if _np_instance(x): return x / np.power(2, powof2) return _apply_vectorized(x, lambda z: z >> powof2)
c8f58a3425b5ecb73f99a8fada6d30be661ee534
64,848
def check_all_validations_for_new_login(email1,email2,pw1,pw2,shipName): """ This used during the create new user process. This method calls other validation methods and baically determines if any of the info that the user entered was illegal. args: all args should be strings and less than 256 ...
24445871a2cc6da14a6966dced8eb72c9f248c8b
64,849
import json def hello(event, context): # pylint: disable=unused-argument """Hello lambda function. Args: event (dict): Contains information from the invoking service (service defines the event structure) context (obj): Contains methods and properties that provi...
fabe319ab98cfcdd9208b021a6b4e42d6aa46a05
64,850
def _check_dparam(dparam=None): """ Check basic properties of dparam It must be a dict with only str as keys with only some fields allowed for each key with values that can be scalars, arrays, or functions <Missing fields are filled in from defaults values in models._DFIELDS """ # ch...
1d7527ea813cb5a55baf4bb8f0027ffd283dd937
64,851
def yaml_load(path: str): """Reads yaml file in path and return it content in string form.""" with open(path, "r") as file: data = load(file, Loader=FullLoader) return data
a690fddb842810ad2a48d17c9875a09793d29e69
64,852
def lr_domain(results, train_idx, test_idx, balance=False, clf_da=None, clf_base=None, inits=None): """ :param results: :param train_idx: :param test_idx: :return: """ label_raw = results['label_raw'] fvs_base = results['fvs_base'] fvs_da = results['fvs_da'] print('------------...
72d5afc4198eeaa328c37c199f8d87f7e500d235
64,853
def performChipSeq( sequences=[], spEnergies=[], numCells=100000, depth=100, ampRatio=1000, pExt=1.0, pcrCycles=15, bgEnergy=1, chemicalPotential=0, secondTFspEnergies=[], secondTFchemicalPotential=0, chromAccessibility=[], secondTFintEnergies=[], indirectLocations=[], indirectSequences=[], numFPlocations=0 ): """ ...
bf5197442d8fec0cb4ed761c871e0d15e36354eb
64,854
import pkg_resources def get_duplicate_entry_points(group, name=None): """Create list of entry points with duplicates.""" return [pkg_resources.EntryPoint.parse('dev = tests.test_get_entry_points:dev'), pkg_resources.EntryPoint.parse('dev = tests.test_get_entry_points:dev')]
3bed4e7eecf8c74361f472928c4a9865956e051a
64,855
from typing import List def fill_array( blocklist: List[int], maxsize: int, numdata: int, numblocks: int, blocksize: int ) -> Array: """Fills a new array of integers with the indices corresponding to the specified block structure. Parameters ---------- blocklist : list List of integer...
86da6914f039629e95f773676cd10518aabce24d
64,856
import re def find_dlls(data: bytes) -> list: """ lists the dlls mentioned in the strings Args: data: strings data from "Strings.txt" file Returns: List of hardcoded .dll names in the strings output """ pattern = rb".+\.dll|.+\.DLL" return list(map(lambda x: x.decode(...
51a44b0563dcd61990f35562f3a624aaed6085c7
64,857
import re def uid(n=5): """ Generate a UID with the specified length. """ global _count c = next(_count) if len(str(c)) > n: raise ValueError('UID width exceeded') return re.sub('\s', '0', ('{c:%i}' % n).format(c=c))
4ce047e251813e236af62353730e4df7fdc7f518
64,858
def get(resource, data='', results_only=True): """ Makes an HTTP GET request to the API :param resource: API resource (e.g. user) :type resource: str :param data: Data payload for request :type data: dict :param results_only: Whether or not to return metadata along with results :type re...
782c61f2d87f17956dfef68c5a8b0bf25355a5a4
64,859
def get_column_mapping(): """ Reads the column names from columns.txt Returns a list of column names as well as a mapping of the position of these columns """ with open(COLUMN_FILE, "r") as f: columns = f.read().rstrip().split("\n") # Mapping of column to column index column_...
ad1c1f3f113c2c0f4bba9a2b7db6a72775035b91
64,860
from typing import List from typing import Dict def single__intent_topk_precision_score( intent_prediction: List[Dict[str, str]], y_true: List[str], k: int = 1, ) -> float: """Compute the Precision of a single utterance with multi-intents Precision of a single utterance is defined...
3b67849670f80a3fa148249a6fe41ce4627546e5
64,861
from typing import List from typing import Tuple import copy def codelToGraphNode(image: np.ndarray, inputCodel: codel, edgePointers: List[direction]) -> Tuple[graphNode, List[BaseException]]: """ :param image: image :param inputCodel: set of positions within the same color :param edgePointers: list o...
4f60eb0ff761dff4a92e1c674578825affd436c5
64,863
def parameter_estimation_lr_n(follower_orig, total_follower_t, no_events, event_pred): """ Fit the parameters of the linear regression with degree :param follower_orig: array, containing the number of followers of the original tweeting person for all tweets (d_0). :param total_follower_t: array, contain...
75aca1b801bc2f36f61ce482a478b67d2035dbee
64,864
import six def time_monotonically_increases(func_or_granularity): """ Decorate a unittest method with this function to cause the value of :func:`time.time` (and :func:`time.gmtime`) to monotonically increase by one each time it is called. This ensures things like last modified dates always increas...
30f4896c41832737a33f5f67bc86ed763283a332
64,867
def b(s, encoding="utf-8"): """ bytes/str/int/float type to bytes """ if isinstance(s, bytes): return s elif isinstance(s, (str, int ,float)): return str(s).encode(encoding) else: raise TypeError(type(s))
8c98944fb018cb747cc79859a147e529b41dfdcb
64,868
def process_results(results, check_mode): """ Process the list of individual (exitcode, output) `results` according to `check_mode`, and return an overall (exitcode, output) pair. """ statuses = [ status for (status,_) in results ] critical_count = len([ s for s in statuses if s == EXIT_CRIT...
9daf131c1b30221ead10e7732e0ef912ba745afc
64,870
def conjugateGradient(*args): """ conjugateGradient(Matrix< double > * A, Vector< double > * b, Vector< double > * x, double const tol, int const itermax) conjugateGradient(Matrix< float > * A, Vector< float > * b, Vector< float > * x, float const tol, int const itermax) """ return _spams_wrap.conju...
bd4aa58990599465088aae9a324ebe3151f94d69
64,871
def spatFT_RT(data, spherical_harmonic_weighted): """Perform spatial Fourier transform for real-time applications (otherwise use `spatFT()` for more more convenience and flexibility). Parameters ---------- data : array_like Data to be transformed, with signals in rows and frequency bins in ...
6942b48b50e3dc6879c9afbebd47835a2c754151
64,872
async def get_all_laps_for_driver(driver, laps): """Get the lap times for each lap of the race for one driver to tabulate. Each dict entry contains lap number, race position and lap time. The API can take time to process all of the lap time data. Parameters ---------- `driver_id` : dict ...
2fe52de69842ea9c7a36c752c4200b56d23d14d4
64,873
def snake_case(name): """takes a PascalCase input string and converts to snake_case.""" split_str = FIRST_CAP_RE.sub(r'\1_\2', name) return ALL_CAP_RE.sub(r'\1_\2', split_str).lower()
1af4ce05b83ba08753644bcb18e6d7503f687f8a
64,874
def joint_from_driver_ctl(node): """ Will try find the joint given the Driver control by searching through the mGear nodes. TO DO: Expand this to be more robust. Check all channels / not rely on translate connections only. Arguments: node (PyNode): node to search connection...
4fe6c9043c878407a44d64ea569b82e80d85b0e9
64,875
import heapq def astar( start, neighbour, finish_condition, heuristic=None, stat=None): """ Perform an A* search. finish_condition = (position) -> bool neighbour - neibhbourhood generation function heuristic = A* heuristic function. (new position, old position) -> distance ...
d75d2595d0a4d433a54c096667e3497bb841d8d7
64,876
def load_data(): """ Load the cleaned data with latitudes, longitudes & timestamps """ travel_log = pd.read_csv("clean_data.csv") travel_log["date"] = pd.to_datetime(travel_log["ts"]) return travel_log
c53a411c39da1b71ce2069f5b532a2cdb3b710d7
64,877
def spatial_reflection_2d_padding(x, padding=((1, 1), (1, 1)), data_format=None): """ Pad the 2nd and 3rd dimensions of a 4D tensor. :param x: Input tensor :param padding: Shape of padding to use :param data_format: Tensorflow vs Theano convention ('channels_last', ...
0d6d99ae2685fd82891898c2f69dddb4ae6d9b23
64,878
def category_delete(): """method to delete a recipe category """ if g.owner: if request.method == "POST": category_name = request.form['category_name'] delete_result = new_cat.category_delete(category_name, g.owner) delete_recipes = new_recipe.delete_category_recipes(...
c4af21277e1a8601dda0cb4be69636de1a4550ec
64,879
def create_zone(domain, profile, type="master", ttl=None): """ Create a new zone. :param domain: Zone domain name (e.g. example.com) :type domain: ``str`` :param profile: The profile key :type profile: ``str`` :param type: Zone type (master / slave). :type type: ``str`` :param ...
c01e876d3133ad21d99e83c3df5c78ba34eabebf
64,880
def simulation(numTrials, numDoors = 3, toprint = False): """ numTrials: number of times the game will be played. numDoors = number of doors in the game. """ results_switch = [] #storing the results of player that makes a switch results_not_switch = [] #same for the player that doesnot mak...
dd5cfcb017c39383fda6875a8b3deadef9862a08
64,881
def setup_hdev_engine(): """Setup HDevEngine by setting procedure search paths.""" source_dir = 'E:/Customer evaluation/Seagate/' hdev_source_dir = source_dir engine = ha.HDevEngine() engine.set_procedure_path('C:/Program Files/MVTec/HALCON-20.11-Progress/procedures') engine.set_procedure_path...
9fc1fbca29970b19208dafb2cdaebedc46dac723
64,882
import xarray.plot.utils def logpolar_plot(ds, ax=None, name='CONC', perM=.95, perm=0.0, colorbar=True, patch_args=None, quantile=True, fig_ops=None, drop_z...
093d573638bd5208813a0503c4a5c8e6f4607dba
64,883
def orthogonal(shape, scale=1): """From Lasagne. Reference: Saxe et al., http://arxiv.org/abs/1312.6120""" flat_shape = (shape[0], np.prod(shape[1:])) a = np.random.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) # pick the one with the correct shape q = u if u.shape...
1b54197d157fa36d52befb2386838a88a4d4902e
64,885
def main(): """main entrypoint""" releases = get_releases() render(releases) return 0
30c1c1be0a418f06a07d0dc3729dca09861dbea1
64,886
def _init_hoomd_bonds(structure, ref_distance=1.0, ref_energy=1.0): """Harmonic bonds.""" # Identify the unique bond types before setting bond_type_params = {} for bond in structure.bonds: t1, t2 = bond.atom1.type, bond.atom2.type t1, t2 = sorted([t1, t2], key=natural_sort) if t1...
58ca189e825cf31358f81450c3d20eae1fa80281
64,887
import math def _fix_lambda_path(lambda_path): """Replace the first value in lambda_path (+inf) with something more reasonable. The method below matches what is done in the R/glmnent wrapper.""" if lambda_path.shape[0] > 2: lambda_0 = math.exp(2 * math.log(lambda_path[1]) - math.log(lambda_path[2]...
b1587354156bdfeb63f5442e5ac3e171aecd3f99
64,888
def unf_fvf_Glaso_m3m3_below(rs_m3m3, t_K, gamma_oil, gamma_gas, p_MPaa): """ Glaso correlation(1980) for total formation volume factor below bubble point pressure ref Generalized Pressure-Volume-Temperature Correlations, Glaso, 1980 :param rs_m3m3: gas-oil ratio in m3/m3 :param t_K: temperature in ...
9d2b983a731e4436c2c18deb9c17744ac018ba8a
64,889
def get_user_by_email(email): """依據 email 取得 user dict""" if not email: raise NotFoundException('No such user.') db = get_db() cursor = db.cursor() # query user cursor.execute("SELECT id, email, profile_id FROM users where email=? ", (email,)) db.commit() user_record = cursor.f...
4ef75d1f72054405fec165d4e276c075a2c29a8e
64,890
def my_clip(x, a_min, a_max): """Unlike topi's current clip, put min and max into two stages.""" const_min = tvm.tir.const(a_min, x.dtype) const_max = tvm.tir.const(a_max, x.dtype) x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name="clipA") x = te.compute(x.shape, lambda *i: tvm.t...
48fbf643d88451e97b46c373f3147d0dcb0e74d7
64,891
import time def session_end_pb(status, end_time_secs=None): """Creates a summary that contains status information for a completed training session. Should be exported after the training session is completed. One such summary per training session should be created. Each should have a different run. Arguments...
3d9ffb7921c5b402b1141bebbc57007d19a6c14e
64,893
from typing import Any def compute_target(obj: Any, format_spec: FormatSpec) -> Target: """Retrieve the target formatting function given an object and format specifier. The SimpleFormatters associated with obj are combined to find the target. """ cls = type(obj) empty_dict = dict() # build ...
b667a0d55f74fd72d307c7191949d131b500bef1
64,895
def createTeam(firstIndex, secondIndex, isRed, first='OffensiveReflexAgent', second='DefensiveReflexAgent'): """ This function should return a list of two agents that will form the team, initialized using firstIndex and secondIndex as their agent index numbers. isRed is True if the red t...
39094a0577b09a47827f5c34a6ba1fe78e5ce367
64,896
def make_ping(): """Makes a ping transaction (a transaction that does nothing but make sure the validator and transaction processor is up and responding)""" payload = "ping".encode("utf-8") header = transaction_pb2.TransactionHeader( inputs=[], outputs=[], batcher_public_key=BATC...
d3a280382d9839b9c6e3a7be5c078ea20ab61818
64,897
def fetch_all_upids(): """ Fetch all available genome accessions from genome table return: A list of UP/RG ids as stored in genome """ # connect to db cnx = RfamDB.connect() # get a new buffered cursor cursor = cnx.cursor(buffered=True) # update is_significant field to 0 quer...
d2bc3d463b0d54b7e304f6366c6c468f8e49a12f
64,898
import json def photo_list(): """ Retrieve Photo table items with signed URL attribute. :return: """ current_user = cognito.user_info(cognito.get_token(app.current_request)) try: photos = Photo.query(current_user['user_id']) data = {'ok': True, 'photos': []} [data['phot...
babf8ee7b4d5dd3241f06b1c8d8fd1515a9c10f0
64,899
def run_hyperband(project_name,X_ros, y_ros, test, actual): """Set up and run the Keras Tuner Hyperband which creates a bracket of many different neural network models with different hyperparameters and trains, tests and evaluates them to determine the best one and stores the values in best_hps.""" MET...
6974edb467faacdad215994932d393a7b9238b2c
64,900
def all_images(request, profile_id): """ function gets and displays all images uploaded by a user """ current_user = request.user.profile user = current_user images = Image.objects.filter(profile_id=profile_id) return render(request, 'profile_templates/user_posts.html', {'images':images})
3133e121da93b28646d925cf7ea1d0d6048cb076
64,902
import time def overloaded_abstract_retrieval(identifier, view='FULL', refresh=True, id_type='eid'): """ The only thing this extra layer does is swap api-keys on error 429 Any multi-threading etc is done elsewhere (and may need its own testing as always) """ try: res = AbstractRetrieval(id...
acc13ab14b77cbdcead83ff826153f72c55a20c9
64,903
import json import logging def api_station_create(): """ This function creates a new station """ # execute and return result result_data = json.loads(request.data) logging.info('Create station %s', result_data["item"]["name"]) result = station_set( result_data["item"]["name"], ...
7d7d4485cfb78719f8829dea21a854552bd075d5
64,904
import requests import json def _login(email: str, password: str, login_url: str = LOGIN_URL) -> requests.Response: """ Login to Shipped Brain :param email: shipped brain account email :param password: shipped brain account password :param login_url: login url :return: requests.Response with aut...
15f5a66127daf7ff9532d91d60d87140ee25d4bc
64,906
import scipy def simpson(dataset, *args, **kwargs): """ Integrate using the composite Simpson's rule. Wrapper of scpy.integrate.trapezoid. Performs the integration along the last or given dimension. If there are an even number of samples, N, then there are an odd number of intervals (N-1), ...
eb6162fbdecadaf51588d528197cb13f2d72a1aa
64,907
from pathlib import Path def get_cache_dict(db_instance): """Return a dictionary `{identifier: path}` keys and values. Args: db_instance: Connected Database file with `DBConnect()`. Returns: dict: dictionary `{identifier: path}` keys and values """ table = get_files_table(db_ins...
687e766dfc04e911131fb361a72cf6ac2743d84b
64,909
from pathlib import Path def build_raw_ben_s2_parquet( ben_path: Path, output_path: Path = Path() / "raw_ben_s2_gdf.parquet", n_workers: int = 8, target_proj: str = "epsg:3035", verbose: bool = True, ) -> Path: """ Create a fresh BigEarthNet-S2-style parquet file from all the image pat...
fb58ca6eb5e7e1095789e7d978a029585850fe8c
64,910
def _validate_belongs(*options): """ Return a validator ensuring the item belongs in the list. """ def _validate_belongs(value): # noqa: E306 for opt in options: if isinstance(value, str) and isinstance(opt, str): if value.lower() == opt.lower(): # noqa: E501 ...
9284b6ff4f55138a3606cc530891f8d1c206ece3
64,911
import re def mw(formula): """ Tokenize a molecular formula to determine total molecular weight. Calculation is based on atomic weight values from IUPAC [1]_. Parameters ---------- formula : str Molecular formula or element. Returns ------- mw : float Molecular wei...
e9e59e8010eee227351ad7fdc21d3171ee0dac9d
64,912
def get_credentials(url, token): """ Get the credentials list Returns requests object """ r_endpoint = "credentials" r = api_get(url, r_endpoint, token) return r
79c9ba149a70485e0f851c781989f78a0a0b718f
64,913
def sorted_ext_names(config, ext_names): """Sort extensions if `EXT_ORDER` is specified. Extensions not listed in `EXT_ORDER` will be appended to the end of the list in an arbitrary order. """ ext_order = [e.strip() for e in config['EXT_ORDER'].split(',')] def sort_key(ext_name): try: ...
6265b6c6ea21915b148648d9adeb800f6d9a8a95
64,914
import functools def of_int_to_int(real_simplex_result, d): """convert all of_int terms to integer terms""" pt1 = real_simplex_result # a ⋈ x, ..., c ⋈ z ⊢ false for hyp in pt1.hyps: pt1 = pt1.implies_intr(hyp) dd = [pt.on_lhs(top_conv(real.real_eval_conv()), bottom_conv(rewr_conv('real_mul_li...
26a492463b26080095729d1447b4d5f60bb8a140
64,915
def _deal_with_axis(obj, axis): """Handle the `axis` parameter Parameters ---------- obj: DimArray object axis: `int` or `str` or `tuple` or None Returns ------- newobj: reshaped obj if axis is tuple otherwise obj idx : axis index name : axis name """ # before apply...
ae0eec4bdf7f172f9617e9f9d1330d75b08f8e97
64,916
def build_optimizer(model, opts): """ Re linear may get larger learning rate """ no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] param_optimizer = [(n, p) for n, p in model.named_parameters() if 're_output' not in n] param_top = [(n, p) for n, p in model.named_parameters...
df373cd0df51efa625200a02260bedcae13da7cd
64,917
def do_train(dataset_dict): """provide dict in train mode""" # USER: Modify this if you want to keep them for some reason. dataset_dict.pop("annotations", None) dataset_dict.pop("sem_seg_file_name", None) return dataset_dict
d6a2bc73baa41218c24282695f7b2a2c57d086d4
64,918
def load_data(time,info): """docstring for load_data""" sfc = load_sfc(time, info) atm = load_atm(time, info) return Bunch(sfc=sfc, atm=atm)
d7f8bd9a83e090c24a591fa124742fa4d687a4fc
64,919
import pytz from datetime import datetime def daily_forecast_embed(obs, loc): """ Accepts pyowm OneCall and geopy Location. Returns Embed for 7-day forecast. """ # forecast details forecasts = obs.forecast_daily loc_str = loc.raw['address']['formattedAddress'] tz = pytz.timezone(obs.ti...
f0a8d67a8a0a4b574f46d6fe38167618191aaf53
64,920
import bisect def calc_precision_recall(ground_truths_list, predictions_list, match_labels): """Adjust threshold to get mutiple precision recall sample.""" true_positive_list, false_positive_list = get_confidence_list( ground_truths_list, predictions_list, match_labels) true_positive_list = sorted...
0507f350c83597eb0ace3fc1fa6a22aa0b019a7d
64,921
from typing import Optional import scipy def solve_regularized_weighted_lstsq( coefs: np.ndarray, result: np.ndarray, *, weights: Optional[np.ndarray] = None, penalty_matrix: Optional[np.ndarray] = None, lstsq_method: LstsqMethod = lstsq_svd, ) -> np.ndarray: """ Solve a regularized an...
408c3e6dbc5723cebbd7b1afc3edeb2802edd1cf
64,922
def checkSum(n, cType, errMsg): """do chksum for card is real card or not Args: n (str): card # cType (str): card type errMsg (str): error msg Returns: bool: true if valid chksum or false otherwise """ errorMsg = errMsg or "Not a Valid Card!" tracker = int(n) ...
5b2087bb7c4d051300ed4079adc66a3d86aaab27
64,923
def clear_noise(image, size): """利用自定义矩形框清除噪点 :param image: 二值图 :param size: 自定义矩形框的大小 type: tuple :return: image """ image = image.convert('L') for y in range(image.size[1] - size[1]): for x in range(image.size[0] - size[0]): white = True for xx in range(x...
e9b5a00e724eb6c2d464d02e1041c59c128e490d
64,924
def create_mclp_model(coverage_dict, num_fac, model_file=None, delineator="$", use_serviceable_demand=False): """ Creates an MCLP model using the provided coverage and parameters Writes a .lp file which can be solved with Gurobi Church, Richard, and Charles R Velle. 1974. The maximal covering location...
d6b818207ff575a1206415d6a1f6c499a5901182
64,925
def simple_bet(pressure, n_monolayer, c_const): """A simple BET equation returning loading at a pressure.""" return (n_monolayer * c_const * pressure / (1 - pressure) / (1 - pressure + c_const * pressure))
601701b608a48fe634d028023068fcadc636499b
64,926
def _select_identifier(identifiers, dict_to_identify): """Select the right field identifier. Args: identifiers (list): List of identifiers. dict_to_identify (dict): Dictionary to identify. Returns: str: Identifier. """ for identifier in identifiers: if identifier i...
647be77f4f87b6d6cba1d979882ac78741134484
64,928
def setup_fab_data(clay_bullets): """Check for placed bullets in JSON. Parameters ---------- clay_bullets : list of :class:`compas_rcf.fabrication.clay_objs.ClayBullet` Original list of ClayBullets. Returns ------- list of :class:`compas_rcf.fabrication.clay_objs.ClayBullet` ...
9df151634186cb693539e10f31366b08d97db41e
64,929
def filter_permission_names(permissions): """ Generate a Permission model query filtered by names, e.g.: ['<app_label>.<codename>', ...] """ permission_pks = [] for permission in permissions: assert '.' in permission, f'Wrong format: {permission!r}' app_label, codename = permission.s...
f4907537efbb58d9b4289733d516518e71092f96
64,930
def positions_func(inputs, pad=0): """ A layer filling i-th column of a 2D tensor with 1+ln(1+i) when it contains a meaningful symbol and with 0 when it contains PAD """ position_inputs = K.cumsum(K.ones_like(inputs, dtype="float32"), axis=1) position_inputs *= K.cast(K.not_equal(inputs, pad...
4db34c8c9fc0dee07ba4017793caff95fbff40c1
64,931
from typing import List def create_contact( create_contact_input: contacts.Create, db: DbSession = Depends(get_db_session), user: User = Depends(require_user), principals: List[str] = Depends(get_active_user_principals), ): """Creates a new contact. Raises an exception if the user is not logged in...
64ed02d1b8d57dbd4d39784c54772cb7c5ea4ea7
64,932
from typing import AnyStr from typing import List from typing import Dict def get_pods_metrics_rating(start: AnyStr, end: AnyStr, tenant_id: AnyStr, namespaces: List[AnyStr]) -> List[Dict]: """ Get the rating by pods and names...
fc58a63905da19eb57494dc7622c035b38ceb350
64,935
def parsing_rule(f): """ Wrap a parsing function to memoize its calls :param f: the function to wrap :return: the wrapped function """ def wrapped_func(self: BaseParser, *args): self.reader.consume_non_significant() pos = self.mark() ...
412f64d954b59dc66fa16f68b1f5a594741db362
64,936
def dot_product(a, b): """ >>> dot_product({'a': 1, 'b': 2, 'c': 3}, {'b': 4, 'c': -1, 'd': 'whatever'}) 5 """ return sum(ak * bk for _, ak, bk in _aligned_items(a, b))
f6e8d5a39667faf4b4d1e2f576b98a3ab445cf9a
64,939
def get_group_summary(conn, group_name): """Return the summary of the group results""" cur = conn.execute(''' select t.path, t.filename, cast(substr(reverse(group_concat(cast(result as char))), 1, 1) as integer), duration, t.lines from results inner join tests t on resu...
806b6a34f379aa2b7c74edc43d523fa9ee169602
64,940