content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def EG(d1,d2,P): """ Méthode permettant de calculer l'esperance de gain du joueur 1 s'il lance d1 dés et que le joueur 2 lance d2 dés ---------------------------------------------------- Args: - d1 : nombre de dés lancés par le joueur 1 - d2 : nombre de dés lancés par le joueur 2 ...
7032bbff4bcf721727c2cb86d6e6f480aa520ee2
15,800
def get_tx_data(request): """ JSON Needed: 1. txid E.g.: {"txid": "hgjsyher6ygfdg"} """ txid = request.data['txid'] try: # req_hex_data = get_tx_data(txid) req_hex_data = api.gettxoutdata(txid,0) # TODO except: return Response(status=status.HTTP_403_...
189f3a6cd9de5d035df0f438e42480e98a0b5f3d
15,801
def roi_max_counts(images_sets, label_array): """ Return the brightest pixel in any ROI in any image in the image set. Parameters ---------- images_sets : array iterable of 4D arrays shapes is: (len(images_sets), ) label_array : array labeled array; 0 is background. ...
2a8993ddb417ac9852ac8a85a4b021cd3db46b66
15,802
import unicodedata def normalize_full_width(text): """ a function to normalize full width characters """ return unicodedata.normalize('NFKC', text)
f8b443089e7083e11f6539f4103ce05f616170c4
15,803
import random def make_definitions(acronym, words_by_letter, limit=1): """Find definitions an acronym given groupings of words by letters""" definitions = [] for _ in range(limit): definition = [] for letter in acronym.lower(): opts = words_by_letter.get(letter.lower(), []) ...
bc0af7b4e81a443c0afe62c2d77ace15bd1ab306
15,804
def plot_effective_area_from_file(file, all_cuts=False, ax=None, **kwargs): """ """ ax = plt.gca() if ax is None else ax if all_cuts: names = ["", "_NO_CUTS", "_ONLY_GH", "_ONLY_THETA"] else: names = tuple([""]) label_basename = kwargs["label"] if "label" in kwargs else "" kw...
b2627c767dfe8abf64eba1b8b1c1f14a4bf52d87
15,805
def get_spreading_coefficient(dist): """Calculate the spreading coefficient. Args: dist: A Distribution from a direct (GC) spreading simulation. Returns: The dimensionless spreading coefficient (beta*s*A). """ potential = -dist.log_probs valley = np.amin(potential) split = ...
549a0052400466f64f707588e313a9e88829a4d7
15,806
from pathlib import Path def get_config_path() -> Path: """Returns path to the root of the project""" return Path(__file__).parent / "config"
b66ece2bc77717b59e88ac65746a2e3b3e8576a2
15,807
def round(x): """ Return ``x`` rounded to an ``Integer``. """ return create_RealNumber(x).round()
403f5f0b4316ef2f06f45885d21fe352f003e193
15,808
def author(repo, subset, x): """``author(string)`` Alias for ``user(string)``. """ # i18n: "author" is a keyword n = encoding.lower(getstring(x, _("author requires a string"))) return [r for r in subset if n in encoding.lower(repo[r].user())]
ee7bd62d52bd0e36ab910e53ca8e029780f4d6c6
15,809
def pianoroll_plot_setup(figsize=None, side_piano_ratio=0.025, faint_pr=True, xlim=None): """Makes a tiny piano left of the y-axis and a faint piano on the main figure. This function sets up the figure for pretty plotting a piano roll. It makes a small imshow plot to the left of the main...
dc2a43be63d77ee99230399b687e86c09570db6c
15,810
def exercise(request, exercisename): """Show single sport and its totals.""" e = exercisename cur_user = request.user exercises = Exercise.objects.filter(owner=cur_user, sport=e).order_by('-date') context = {'exercises': exercises, 'total': Stats.total(cur_user, sport=e), 'totaltime'...
8648673d6bdb3997d9b9d38155e2cb2039ff4f1b
15,811
import random def randomBinaryMatrix(scale, type): """ Generates a pseudo random BinaryMatrix of a given scale(small,large) and datatype(int). """ if(scale == "small" and type == "int"): nrow = random.randint(1, 10) ncol = random.randint(1, 10) data = [] for i in r...
289d266eee4f6244774f7138e9efbe18970545f4
15,812
from typing import Optional def load_batch(server_context: ServerContext, assay_id: int, batch_id: int) -> Optional[Batch]: """ Loads a batch from the server. :param server_context: A LabKey server context. See utils.create_server_context. :param assay_id: The protocol id of the assay from which to lo...
731d463bc1e0380107390caabae8c57c7e6cff02
15,813
def canvas_compose(mode, dst, src): """Compose two alpha premultiplied images https://ciechanow.ski/alpha-compositing/ http://ssp.impulsetrain.com/porterduff.html """ src_a = src[..., -1:] if len(src.shape) == 3 else src dst_a = dst[..., -1:] if len(dst.shape) == 3 else dst if mode == COMPO...
9d95b840f814a77077050cb43a081c01c496640b
15,814
import select async def get_timelog_user_id( *, user_id: int, epic_id: int, month: int, year: int, session: Session = Depends(get_session), ): """ Get list of timelogs by user_id, month. Parameters ---------- user_id : str ID of user from which to pull timelogs. ...
fe4bdcbda40c2d32b743262cb14139e89890b237
15,815
def _cross( vec1, vec2, ): """Cross product between vec1 and vec2 in R^3""" vec3 = np.zeros((3,)) vec3[0] = +(vec1[1] * vec2[2] - vec1[2] * vec2[1]) vec3[1] = -(vec1[0] * vec2[2] - vec1[2] * vec2[0]) vec3[2] = +(vec1[0] * vec2[1] - vec1[1] * vec2[0]) return vec3
2958a7365908bbd38c75f79e489d136f21fcc011
15,816
def _simplex_dot3D(g, x, y, z): """ 3D dot product """ return g[0] * x + g[1] * y + g[2] * z
fcc48153b34af7cef0811f21fc04d22e6536797a
15,817
import inspect def __get_report_failures(test_data: TestData) -> str: """ Gets test report with all failed test soft asserts :param test_data: test data from yaml file :return: str test report with all soft asserts """ test_id = __get_test_id() failed_assert_reports = __FAILED_EXPECTATION...
cedb24569acedf9bd251c233f220c44a1bb05772
15,818
def initialized_sm(registrations, uninitialized_sm): """ The equivalent of an app with commit """ uninitialized_sm.initialize() return uninitialized_sm
491e4366b81379b053d1dea203d338766c3afa86
15,819
from pathlib import Path from typing import Optional import os import sys def compute_options( platform: PlatformName, package_dir: Path, output_dir: Path, config_file: Optional[str], args_archs: Optional[str], prerelease_pythons: bool, ) -> BuildOptions: """ Compute the options from t...
ab233556f1099b1d29877dab84a83452a0cfe7ff
15,820
def coordinateToIndex(coordinate): """Return a raw index (e.g [4, 4]) from board coordinate (e.g. e4)""" return [abs(int(coordinate[1]) - 8), ("a", "b", "c", "d", "e", "f", "g", "h").index(coordinate[0])]
d3dcf6d01c4bec2058cffef88867d45ba51ea560
15,821
import re import logging def parse_page(url): """parge the page and get all the links of images, max number is 100 due to limit by google Args: url (str): url of the page Returns: A set containing the urls of images """ page_content = download_page(url) if page_conten...
5833e0092650488e8ef430de0eafd79f6e5d2ffa
15,822
import os def full_file_names(file_dir): """ List all full file names(with extension) in target directory. :param file_dir: target directory. :return: a list containing full file names. """ for _, _, files in os.walk(file_dir): return files
e70947c2ce1ff3eab5f7dd1074ba378498aedbf7
15,823
def json_page_resp(name, page, paginator): """ Returns a standardized page response """ page_rows = paginator.get_page(page) return JsonResponse({'page':page, 'pages':paginator.num_pages, name:[x['json'] for x in page_rows], 'size':len(page_rows)}, safe=False)
d615cfeaa2fafdb35333eee6aa6d63e1511a1dd3
15,824
from .interpreters import ScriptRunnerPlugin def get_script_runner(): """ Gets the script runner plugin instance if any otherwise returns None. :rtype: hackedit.api.interpreters.ScriptRunnerPlugin """ return _window().get_plugin_instance(ScriptRunnerPlugin)
2f76f46dd502fbd6ce9bd0a5f90eb7eed8bb64ca
15,825
def detect_peak(a, thresh=0.3): """ Detect the extent of the peak in the array by looking for where the slope changes to flat. The highest peak is detected and data and followed until the slope flattens to a threshold. """ iPk = np.argmax(a) d = np.diff(a) g1 = np.gradient(a) g2...
e4b520a4dd932992fb1cf20b34e253ecbaac9614
15,826
def latest_version(): """ Returns the latest version, as specified by the Git tags. """ versions = [] for t in tags(): assert t == t.strip() parts = t.split(".") assert len(parts) == 3, t parts[0] = parts[0].lstrip("v") v = tuple(map(int, parts)) ver...
346edcc6d087ca1511411b52de20b90f1a993f3a
15,827
import string def get_age_group(df,n: int=10): """Assigns a category to the age DR Parameters ---------- df : Dataframe n : number of categories Returns ------- Dataset with Age_group column """ df["Age_group"] = pd.cut(df["Age"], n, labels = list(string.ascii_upperc...
f793316c7c494adec1bfedf8613edf6c4ed5e2e2
15,828
def transformer_encoder_layer(query_input, key_input, attn_bias, n_head, d_key, d_value, d_model, d_inner_hid,...
fe300a8c72c39c7e847f400f8f874dabab80b6e6
15,829
def generate(ode, lenght=int(2e4)): """ Time series generation from a ODE :param ode: ODE object; :param lenght: serie lenght; :return: time serie. """ state = ode.initial_state data = np.zeros([int(state.shape[0]), lenght]) for i in range(5000): state = runge_kutta(ode...
442f5359e3225d00cf0396e710e3978d1a6e37f8
15,830
def complexFormatToRealImag(complexVec): """ A reformatting function which converts a complex vector into real valued array. Let the values in the input array be [r1+j*i1,r 2+j*i2,..., rN+j*iN] then the output array will be [r1, i1, r2, i2,..., rN, iN] :param complexVec: complex numpy ndarray :r...
d955f2b31581036594ca79cd4755327eaa8b2446
15,831
def displayaction(uid): """ Display the command from the xml file """ tree = ET.parse(OPENSTRIATOFILE) root = tree.getroot() textaction = root.findall("./action[@uid='"+uid+"']") if len(textaction) == 0: return "This UID does not exist!" else: return "UID %s action: %s" % (ui...
e34133a168b20cc9b018175ee5b4363fd2ff9690
15,832
def get_parent(inst, rel_type='cloudify.relationships.contained_in'): """ Gets the parent of an instance :param `cloudify.context.NodeInstanceContext` inst: Cloudify instance :param string rel_type: Relationship type :returns: Parent context :rtype: :class:`cloudify.context.RelationshipSubj...
06bc76ec55735a47a3cf26df2daa4346290671ee
15,833
def _query_param(key, value): """ensure that a query parameter's value is a string of bytes in UTF-8 encoding. """ if isinstance(value, unicode): pass elif isinstance(value, str): value = value.decode('utf-8') else: value = unicode(value) return key, value.encode('utf...
9c89517afd8d1684b1bb954f66cd2072296dee82
15,834
def _create_or_get_dragonnet(embedding, is_training, treatment, outcome, split, getter=None): """ Make predictions for the outcome, using the treatment and embedding, and predictions for the treatment, using the embedding Both outcome and treatment are assumed to be binary Note that we return the l...
7fc7fead338ac2c33bcfa016f9d66e34d15ac59c
15,835
def fit_ols(Y, X): """Fit OLS model to both Y and X""" model = sm.OLS(Y, X) model = model.fit() return model
dcc86cab7fe15400130febd36d5aa8139a68c64f
15,836
def compute_modularity_per_code(mutual_information): """Computes the modularity from mutual information.""" # Mutual information has shape [num_codes, num_factors]. squared_mi = np.square(mutual_information) max_squared_mi = np.max(squared_mi, axis=1) numerator = np.sum(squared_mi, axis=1) - max_squ...
5c81b583c6313818da435dd367a3d53933025227
15,837
def _CheckSemanticColorsReferences(input_api, output_api): """ Checks colors defined in semantic_colors_non_adaptive.xml only referencing resources in color_palette.xml. """ errors = [] color_palette = None for f in IncludedFiles(input_api): if not f.LocalPath().endswith('/semantic_colors_non_adaptiv...
63243cbdea3ad1ae4bc50d856c97350ffafc1407
15,838
import logging def post_new_attending(): """Posts attending physician information to the server This method generates the new attending physician’s dictionary with all of his/her information, then validates that all of the information is the correct type. If the validation stage is satisfied, the...
18ddcb3bfcc601a22abccac7828ed6ac36368a33
15,839
def submitFeatureWeightedGridStatistics(geoType, dataSetURI, varID, startTime, endTime, attribute, value, gmlIDs, verbose, coverage, delim, stat, grpby, timeStep, summAttr, weighted, wfs_url, outputfname, sleepSecs, async=False): """ ...
ab6f1cbeee1943f75aa16c9153d2a317113d2398
15,840
def fetch_words(url): """ Fetch a list of words from a URL Args: url: the url of any text document (no decoding to utf-8 added) Returns: A list of strings containing the words in the document """ with urlopen(url) as story: story_words = [] for line in s...
6679425f5f3680bd0b47888d59530a55b4c23443
15,841
def generate_fgsm_examples(sess, model, x, y, X, Y, attack_params, verbose, attack_log_fpath): """ Untargeted attack. Y is not needed. """ fgsm = FastGradientMethod(model, back='tf', sess=sess) fgsm_params = {'eps': 0.1, 'ord': np.inf, 'y': None, 'clip_min': 0, 'clip_max': 1} fgsm_params = overr...
7b682622f843dd2c5d421c3d52b15e3a204edb0a
15,842
def s3_bucket_for(bucket_prefix, path): """returns s3 bucket for path""" suffix = s3_bucket_suffix_for(path) return "{}-{}".format(bucket_prefix, suffix)
a59145474d2965a9e5f98d4728a6ac90d0d42cdf
15,843
def regrid_create_operator(regrid, name, parameters): """Create a new `RegridOperator` instance. :Parameters: regrid: `ESMF.Regrid` The `ESMF` regridding operator between two fields. name: `str` A descriptive name for the operator. parameters: `dict` ...
1c44dbe1c4826ee566cfb6b95ac704c9af19fc30
15,844
def _decode_hmc_values(hmc_ref): """Decrypts any sensitive HMC values that were encrypted in the DB""" if hmc_ref is not None: hmc_ref = jsonutils.to_primitive(hmc_ref) #Make sure to DeCrypt the Password after retrieving from the database ## del two lines by lixx #if hmc_ref.get(...
7e1b33265811d79f245853cb016e5acd45627028
15,845
import logging def dtensor_shutdown_tpu_system(): """Shutdown TPU system.""" @def_function.function def _shutdown_tpu_system(): return gen_dtensor_ops.shutdown_tpu_system() success = _shutdown_tpu_system() if context.is_tfrt_enabled() else True if success: logging.info("TPU system shut down.") e...
23140407222646fd9adb845ae5e04ca4a3a9cc5a
15,846
import json import math def edit_comment(request): """ Edit an existing comment """ response = {"status": "success", "data": {}} if "char_id" in request.POST: char_id = request.POST["char_id"] else: response["status"] = "fail" response["data"]["mess...
b56f0b3f3c0d0635b4faa9a06320bc4b715ea0d1
15,847
import sys def aws_get_size(size): """ Get Node Size - Ex: (cmd:<size>)""" conn = util_get_connection() sizes = [i for i in conn.list_sizes()] if size: for i in sizes: if str(i.ram) == size or i.id == size: print >> sys.stderr, ' - '.join([i.id, str(i.ram), str(i.pr...
7ed1868d4512e660d94d474a907b8b4490123b51
15,848
import torch def make_positions(tensor, padding_idx, onnx_trace=False): """Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. """ # The series of casts and type-conversions here are carefully # balanced to both work with ...
e5d117d64669f514b5cab4ad08ec526dd421493e
15,849
import warnings def taubin_curv(coords, resolution): """Curvature calculation based on algebraic circle fit by Taubin. Adapted from: "https://github.com/PmagPy/PmagPy/blob/2efd4a92ddc19c26b953faaa5c08e3d8ebd305c9/SPD/lib /lib_curvature.py" G. Taubin, "Estimation Of Planar Curves, Surfaces And Nonplana...
f3728528dbec5681b3915683af22b8e9838e73ce
15,850
def periodic_general(box: Box, fractional_coordinates: bool=True, wrapped: bool=True) -> Space: """Periodic boundary conditions on a parallelepiped. This function defines a simulation on a parallelepiped, $X$, formed by applying an affine transformation, $T$, to the unit...
35dc501b0d5d897fb4e68d41d4e83dc6727a5feb
15,851
import hmac def calculate_mac(mac_type, credentials, options, url_encode=False): """Calculates a message authentication code (MAC).""" normalized = normalize_string(mac_type, options) digestmod = module_for_algorithm(credentials['algorithm']) result = hmac.new(credentials['key'], normalized, digestmod...
0701dbe3881ab500a70f3895af64d2ca6cb2905d
15,852
import math def run(): """ Test Case - Fbx mesh group Import scaling in Atom: 1. Creates a new level called MeshScalingTemporaryLevel 2. Has a list of 12 meshes, which it will do the following for each one: - Create an entity and attach the mesh to it. - Sets it with an initial offset ...
fb7c5194d755e277e14f778c6fe52f9c5d1a36be
15,853
def get_prime(num_dict): """获取字典里所有的素数""" prime_dict = {} for key, value in num_dict.items(): if value: prime_dict.update({key: key}) return prime_dict
49c62ae43bfe5af15f191cd8d831e82ae56c766d
15,854
def get_shared_keys(param_list): """ For the given list of parameter dictionaries, return a list of the dictionary keys that appear in every parameter dictionary >>> get_shared_keys([{'a':0, 'b':1, 'c':2, 'd':3}, {'a':0, 'b':1, 'c':3}, {'a':0, 'b':'beta'}]) ['a', 'b'] >>> get_shared_keys([{'a':0, 'd':3}, {'a':0...
0f6aa0df4d61ba166ac7d660be80a98fdbc29080
15,855
def labeledTest(*labels): """This decorator mark a class as an integrationTest this is used in the test call for filtering integrationTest and unittest. We mark the difference by the usage of service dependency: * An unittest can run without additional services. * An integration test need additi...
4cb5adab516b19517066104d547d8efb0ae90cbd
15,856
def birth(sim): """Similar to create agent, but just one individual""" age = 0 qualification = int(sim.seed.gammavariate(3, 3)) qualification = [qualification if qualification < 21 else 20][0] money = sim.seed.randrange(20, 40) month = sim.seed.randrange(1, 13, 1) gender = sim.seed.choice(['...
c44323bb36b5807e4b25a12bb739150bd70e1b98
15,857
def offer_better_greeting(): """Give player optional compliments.""" player = request.args["person"] # if they didn't tick box, `wants_compliments` won't be # in query args -- so let's use safe `.get()` method of # dict-like things wants = request.args.get("wants_compliments") nice_things...
9f65f9a1169262020f6ec227d44e0160a904f00f
15,858
def get_trip_length(grouped_counts): """ Gets the frequency of the length of a trip for a customer Args: grouped_counts (Pandas.DataFrame): The grouped dataframe returned from a get_trips method call Returns: Pandas.DataFrame: the dataframe co...
974bb0fc7f0430d0e6605857dba22f7b036e3945
15,859
def extract_begin_end(data): """ Finds nif:beginIndex and nif:endIndex values. :param data: Data sent by the client. :return: Begin index and end index, -1 if error. """ try: begin = data.split("nif:beginIndex")[1].split("\"")[1] end = data.split("nif:endIndex")[1].split("\"")[1] ...
d5f5ce211f645f10d6a0aed1c6446963f0c3fe3e
15,860
def setup_parameters(): """ Helper routine to fill in all relevant parameters Note that this file will be used for all versions of SDC, containing more than necessary for each individual run Returns: description (dict) controller_params (dict) """ # initialize level parameters...
6cadf729f8f796c6b07c94bf8b74913e6a893799
15,861
def get_operation(op, inplanes, outplanes, stride, conv_type): """Set up conv and pool operations.""" kernel_size = Ops.ops_to_kernel_size[op] padding = [(k - 1) // 2 for k in kernel_size] if op in Ops.pooling_ops: if inplanes == outplanes: return nn.AvgPool2d(kernel_size, stride=str...
f561db9c230236f3ead248e04cae198dbd9d4415
15,862
def encode( structure_klifs_ids, fingerprints_filepath=None, local_klifs_download_path=None, n_cores=1 ): """ Encode structures. Parameters ---------- structure_klifs_ids : list of int Structure KLIFS IDs. fingerprints_filepath : str or pathlib.Path Path to output json file....
7b5d3400455bdffc25e88cc07f58292f56ac6e12
15,863
def log_like_repressed(params, data_rep): """Conv wrapper for log likelihood for 2-state promoter w/ transcription bursts and repression. data_rep: a list of arrays, each of which is n x 2, of form data[:, 0] = SORTED unique mRNA counts data[:, 1] = frequency of each mRNA count Not...
8451de8f1c578c8343bd1c91d1dc0326b51cc5a3
15,864
def freq_mask(spec, F=30, num_masks=1, pad_value=0.): """Frequency masking Args: spec (torch.Tensor): input tensor of shape `(dim, T)` F (int): maximum width of each mask num_masks (int): number of masks pad_value (float): value for padding Returns: freq masked te...
714dac7127e4dd1e790df016296321f97cfe37c7
15,865
def prepare_file_hierarchy(path): """ Create a temporary folder structure like the following: test_find_dotenv0/ └── child1 ├── child2 │   └── child3 │   └── child4 └── .env Then try to automatically `find_dotenv` starting in `child4` ...
25b66a7bc728f8f4b90cd9d8e678c914d2d60be9
15,866
def cmd2dict(cmd): """Returns a dictionary of what to replace each value by.""" pixel_count = cmd[cmd.shape[0] - 1, cmd.shape[1] - 1] scaling_dict = dict() for i in range(0, cmd.shape[0]): scaling_dict[cmd[i, 0]] = round( ((cmd[i, 1] - cmd[0, 1]) / (pixel_count - cmd[0, 1])) * 255 ...
17f28fdcc5497c7d8d6aa55bbc61460e988586eb
15,867
def cached_part(query, cache=None): """Get cached part of the query. Use either supplied cache object or global cache object (default). In the process, query is into two parts: the beginning of the query and the remainder. Function tries to find longest possible beginning of the query which is cache...
c1b8d9589b12171ae11e2f49911142252f54d9cd
15,868
def exist_key(bucket: str, key: str) -> bool: """Exist key or not. Args: bucket (str): S3 bucket name. key (str): Object key. Returns: bool: Exist or not. """ try: s3.Object(bucket, key).get() except s3.meta.client.exceptions.NoSuchKey: return False ...
1e47467c85d0461d76f0d562a2ee9c7cff5dbf4e
15,869
import os import fnmatch def load_all_files(dir): """Returns all of the csharp source files.""" result = [] for root, dirnames, filenames in os.walk(dir): if 'obj\\' not in root and 'bin\\' not in root: for name in fnmatch.filter(filenames, '*.cs'): result.append(Source...
5b829d588053f1a464edf4537aff168ab9f801a5
15,870
def calculate_bleu_score(candidate_file: str, reference_file: str) -> float: """ Calculates the average BLEU score of the given files, interpreting each line as a sentence. Partially taken from https://stackoverflow.com/a/49886758/3918865. Args: candidate_file: the name of the file that contain...
00e6f6a852171f34b92598193fe1b08c60ba328b
15,871
def _read_id_not_in_dict(read_ids, read_dict): """Return True if all read_ids in a list are not in the read_dict keys, otherwise False""" for read_id in read_ids: if read_id not in read_dict.keys(): return True return False
3a0e0926ed33f65cc67139311af1c860f3e371ae
15,872
def generate_spectra_products(dataset, prdcfg): """ generates spectra products. Accepted product types: 'AMPLITUDE_PHASE_ANGLE_DOPPLER': Makes an angle Doppler plot of complex spectra or IQ data. The plot can be along azimuth or along range. It is plotted separately the module an...
ba279b7331fda0fdcb2ef506e91d13bd11f37d2f
15,873
def odds_or_evens(my_bool, nums): """Returns all of the odd or even numbers from a list""" return_list = [] for num in nums: if my_bool: if num % 2 == 0: return_list.append(num) else: if num % 2 != 0: return_list.append(num) re...
02b3b12acbaae10b2b0e05eec059f6571c576e80
15,874
import numpy def local_mass_diagonal(quad_data, basis): """Constructs the elemental mass matrix, diagonal version Arguments: quad_data - Quadrature points and weights basis - Basis and respective derivatives Returns: Mass matrix M, where m_ii = \int_k psi_i psi_i """ retu...
ffaf34df758e73dea0db3ecb66de658991d8de58
15,875
def create_saved_group(uuid=None): """Create and save a Sample Group with all the fixings (plus gravy).""" if uuid is None: uuid = uuid4() analysis_result = AnalysisResultMeta().save() group_description = 'Includes factory-produced analysis results from all display_modules' sample_group = Sa...
7a9929518b44f6266f32300177385040b3da41c0
15,876
import copy def words_to_indexes(tree): """Return a new tree based on the original tree, such that the leaf values are replaced by their indexs.""" out = copy.deepcopy(tree) leaves = out.leaves() for index in range(0, len(leaves)): path = out.leaf_treeposition(index) out[path] = i...
99e4ad2aa1d318af21d934aee2128b8d7b51a99f
15,877
def get_stoplist_names(): """Return list of stoplist names""" config = configuration() return [name for name, value in config.items('stoplists')]
a93dec87fe840a1fab9d63527e7b54ae8a1c7cf5
15,878
def any_(criterions): """Return a stop criterion that given a list `criterions` of stop criterions only returns True, if any of the criterions returns True. This basically implements a logical OR for stop criterions. """ def inner(info): return any(c(info) for c in criterions) return in...
600e7c1516cba6f0cd73812bcd43d5e194aa33d2
15,879
def validate_basic(params, length, allow_infnan=False, title=None): """ Validate parameter vector for basic correctness. Parameters ---------- params : array_like Array of parameters to validate. length : int Expected length of the parameter vector. allow_infnan : bool, opti...
c3567a7f08656c3b815eded0a6788d904b5820a5
15,880
import torch def unsorted_segment_sum(data, segment_ids, num_segments): """ Computes the sum along segments of a tensor. Analogous to tf.unsorted_segment_sum. :param data: A tensor whose segments are to be summed. :param segment_ids: The segment indices tensor. :param num_segments: The number of ...
7d8686d35afab975bff05d3cda50d1ceae537ab9
15,881
def create_parameters(address: str) -> dict: """Create parameters for address. this function create parameters for having request from geocoder and than return dictionary of parameters Args: address (str): the address for create parameters Returns: dict: takes the api key and Geoc...
9ad1723cf2bec66e366e83b814ee746cdddf8289
15,882
import re def standardizeName(name): """ Remove stuff not used by bngl """ name2 = name sbml2BnglTranslationDict = { "^": "", "'": "", "*": "m", " ": "_", "#": "sh", ":": "_", "α": "a", "β": "b", "γ": "g", " ": "", ...
33caf35feb0c9dcc042add501a4470b1ccbd3b1c
15,883
def _learning_rate_decay(hparams, warmup_steps=0): """Learning rate decay multiplier.""" scheme = hparams.learning_rate_decay_scheme warmup_steps = tf.to_float(warmup_steps) global_step = tf.to_float(tf.train.get_or_create_global_step()) if not scheme or scheme == "none": return tf.constant(1.) tf.log...
4d171ef2cb13d2f103ac722be12cd594b6533c60
15,884
import math import os def new_model(save_dir, integer_tokens, batch_size=128, vocab_size=50000, embedding_size=128, num_negative=64, num_steps=100001, num_skips=2, skip_window=1): """ Create a new Word2Vec model with token vectors generated in the 'tokens' step....
40371578558d11dcd9e198f8b02503b3b3cdbe5d
15,885
import re def Register_User(): """Validates register form data and saves it to the database""" # Check if the fields are filled out if not (request.form['username'] and request.form['email'] and request.form['password'] and request.form['passwordConf']): return redirect(url_for('Register', messag...
6a3ed4e99436845791d8025014f4fa4ddbaec86e
15,886
def extreme_rank(df, col, n, bottom=True, keep=[]): """ Calculate the n top or bottom of a given series """ t = df[list(keep)+[col]].sort_values(col, ascending=bottom).iloc[:30] count = t['NO_MUNICIPIO'].value_counts() count.name = '#' perc = t['NO_MUNICIPIO'].value_counts(nor...
976395ceb26f72300cbc24b9cb849b0e47f45ba8
15,887
def ss_octile(y): """Obtain the octile summary statistic. The statistic reaches the optimal performance upon a high number of observations. According to Allingham et al. (2009), it is more stable than ss_robust. Parameters ---------- y : array_like Yielded points. Returns ----...
a38256c3fa3e2d3c5d756883524d65a48b0585f5
15,888
def englishToFrench(englishText): """Translates English to French""" model_id='en-fr' fr_text = language_translator.translate( text=englishText, model_id=model_id).get_result() return(fr_text['translations'][0]['translation'])
f1ebb6195d09230c1bac2b4351b0157813e6ca80
15,889
def calc_out_of_plane_angle(a, b, c, d): """ Calculate the out of plane angle of the A-D vector to the A-B-C plane Returns the value in radians and a boolean telling if b-a-c are near-collinear """ collinear_cutoff = 175./180. collinear = 0 if abs(calc_angle(b, a, c)) > np.pi ...
e24c70e210cb8a454af07a1757864b9c241acaff
15,890
def compute_distances(X, Y): """ Computes the Mahalanobis distances between X and Y, for the special case where covariance between components is 0. Args: X (np.ndarray): 3D array that represents our population of gaussians. It is assumed that X[0] is the 2D matrix contai...
da994051b2eb4cc614368ed2a035d7a8bf9dcade
15,891
def op_item_info(): """Helper that compiles item info spec and all common module specs :return dict """ item_spec = dict( item=dict( type="str", required=True ), flatten_fields_by_label=dict( type="bool", default=True ), ...
5bc4d3ff959e9642304dff31b910ea8a6c8a9d52
15,892
import collections def unpack_condition(tup): """ Convert a condition to a list of values. Notes ----- Rules for keys of conditions dicts: (1) If it's numeric, treat as a point value (2) If it's a tuple with one element, treat as a point value (3) If it's a tuple with two elements, tr...
c07e651031850896d46a94e6060c79a955ad10fd
15,893
import logging def run(doc, preset_mc: bool): """Create Graph through classfication values.""" mc = doc._.MajorClaim adus = doc._.ADU_Sents if isinstance(mc, list): mc = mc[0] if mc == []: mc = adus.pop(0) elif not mc: mc = adus.pop(0) relations = compare_a...
bd1907bd452c78f2fb7f262af173c4743e1af725
15,894
from aiida.common.datastructures import wf_data_types from aiida.orm.workflow import Workflow from aiida.backends.djsite.db import models from aiida.djsite.db import models def get_wfs_with_parameter(parameter, wf_class='Workflow'): """ Find workflows of a given class, with a given parameter (which must be a ...
7ae1c11b9b6495341da853d67d3d38df2c7838cd
15,895
import glob import os def find_checkpoint_in_dir(model_dir): """tf.train.latest_checkpoint will find checkpoints if 'checkpoint' file is present in the directory. """ checkpoint_path = tf.train.latest_checkpoint(model_dir) if checkpoint_path: return checkpoint_path # tf.train.latest_c...
99eca445bae058692068983a12375cae8fb6478d
15,896
def map_iou(boxes_true, boxes_pred, scores, thresholds = [0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75]): """ Mean average precision at differnet intersection over union (IoU) threshold input: boxes_true: Mx4 numpy array of ground true bounding boxes of one image. bbox format: (x1...
b33f6acf90a24ac473d36de4ceb06563bc1523f6
15,897
def draw_output_summary(model): """ reads the data saved in the model class and depending on this data chooses a visualization method to present the results with the help of draw_optimization_overview """ if 'time_series' in model.log: # no optimization has happend. # hence...
c996bf588f0aa31f32e80d80d352e6a81203a84f
15,898
def general_spline_interpolation(xs, ys, p, knots=None): """ NOTE: SLOW SINCE IT USES B() xs,ys: interpolation points p: degree knots: If None, use p+1-regular from xs[0] to slightly past x[1] returns cs, knots """ # number of interpolation points (and also control point...
fce53b173b6e8234d0c35418ec1455793a62fc61
15,899