content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_feature(feature_name, example): """Gets Tensorflow feature by name. Args: feature_name: The name of the feature. example: A Tensorflow example. Returns: The Tensorflow feature with the given feature name in the example. Raises: ValueError: If the given feature name is ...
80e35d7e1fe15e7a455123cbd139139dd977f216
36,700
def fcn_VR_FMS(r_div_R): """ Transversal velocity factor of FMS in Eq. (31) in [2] """ return (1/4.)*(3.*r_div_R - r_div_R**3.0 + 2.0)
9a1a4dd8acfe0af910677c30e1a98b5e8f765e20
36,701
import warnings def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" # C.f. http://wiki.python.org/moin/PythonDecoratorLibrary def newFunc(*args, **kwargs): warnings.warn("Cal...
44641d06b0e68652723c4de4ad8dfb7cc6f8f5ee
36,702
import collections def ss_inference(model, img, ori_shape, is_slide, base_size, stride_size, crop_size, num_classes, rescale_from_ori=False): """ Single-scale inferenc...
6be64a12a1760cc069be292e3fd603725c6f97e1
36,703
def temperature(wair,pres,entr=None,temp=None,airf=None,dhum=None, chkvals=False,chktol=_CHKTOL,airf0=None,temp0=None,dhum0=None, chkbnd=False,mathargs=None): """Calculate icy air temperature. Calculate the temperature of icy air. :arg float wair: Total dry fraction in kg/kg. :arg floa...
9d90016c71c888fc824485bc00ffbca82e35ac45
36,704
def check_gnn_get_sampled_neighbors(method): """A wrapper that wraps a parameter checker around the GNN `get_sampled_neighbors` function.""" @wraps(method) def new_method(self, *args, **kwargs): [node_list, neighbor_nums, neighbor_types, _], _ = parse_user_args(method, *args, **kwargs) che...
1af65d6db1c79516617179b7e1ccc935c0a29e8c
36,705
def bound(x, lower, upper): """ Bound x between lower and upper, where x is a numpy array. """ # Lower bound. y = np.where(x < lower, lower, x) # Upper bound. z = np.where(y > upper, upper, y) return z
1ec35b81cb5571544278a1f2f07681b1b0bad2a3
36,706
def esc(code: int) -> str: """ Converts the integer code to an ANSI escape sequence :param code: code :return: escape sequence """ return f"\033[{code}m"
6bdc0679ba9b480220bc088bd09d6356dd539f1f
36,707
import math def compare( line1, line2, method='frechet_dist', precision=6, clip=True, clip_max=0.5 ): """ Compute similarity between two (Multi)LineStrings. Returns value 0.0 (completely dissimilar) to 1.0 (completely similar) Based on Frechet dista...
e45eef23eb844bfdec11b720a84a82ebdab53b47
36,708
def Phi_gradient(x: np.ndarray, mu: np.ndarray, Sigma: np.ndarray) -> np.ndarray: """ Compute gradient of CDF of multivariate Gaussian distribution. :param x: Location where the gradient is evaluated. :param mu: Mean of the multivariate Gaussian. :param Sigma: Covariance of the multivariate Gaussia...
b7b96efcef75a137cf2fd439d0971a1aeca6cadc
36,709
def list_files(directory, extension): """ List files with specified suffixes in the directory (exclude subdirectories) """ file_list = listdir(directory) included_list = [] for f in file_list: for ext in extension: if f.endswith('.' + ext): included_list.append(f)...
967e0a9472d26470af6f326f8ac3f598ed17953f
36,710
import logging def generate_reference(nodal_position, mesh, image, settings, image_id=None): """ Generates a Reference object The Reference object contains all internals that will be used during the correlation procedure. Parameters ---------- nodal_position : ndarray 2D array with floa...
4e6d6addd86ada8af5a1c8bfb25605dc46a009c3
36,711
from typing import Literal def _estimate_df_regression( y: Float64Array, trend: Literal["n", "c", "ct", "ctt"], lags: int ) -> RegressionResults: """Helper function that estimates the core (A)DF regression Parameters ---------- y : ndarray The data for the lag selection trend : {"n","...
c4b9589bf9dc597756b96828aaf35d0d65407558
36,712
def list_streams(region_name='us-west-2', Limit=10): """ Executes Kinesis.Client.describe_stream_summary function """ client = boto3.client('kinesis', region_name=region_name) result = client.list_streams(Limit=Limit) streams = [] if 'StreamNames' in result: for st in result['Stream...
85bfa452fea0d5350d79b3dd7a9b39fe1cec13e0
36,713
import copy def as_json_object(element: YAMLRoot, contexts: CONTEXTS_PARAM_TYPE = None, inject_type = True) -> JsonObj: """ Return the representation of element as a JsonObj object :param element: element to return :param contexts: context(s) to include in the output :param inject_type: if True (d...
d60af09b906274128a22577a25da64e146d0068a
36,714
import torch def floor_divide(input_, other): """Wrapper of `torch.floor_divide`. Parameters ---------- input_ : DTensor The first operand. other : DTensor The second operand. """ return torch.floor_divide(input_._data, other._data)
eaf842f24e6a3b07e65cb69bde3a50ed7ef9a26d
36,715
def firstTokenPredicate(field): """Finds first word/token in the field. Examples: .. code:: python > print(firstTokenPredicate('John Woodward')) > ('John',) """ first_token = start_word(field) if first_token: return first_token.groups() else: return ()
362f831d6dc0c8510eca21e0032533cc259867cd
36,716
def penalty_of_soft_constraint_1(schedule: Schedule, schedule_param: ScheduleParam, unit_penalty, _inspect=False): """ 1. Instructors should only take certain courses they are are assigned to. """ violation_count = 0 for c in schedule.classes: if c.section.course.idx not in c.instructor.assi...
21102097d14690b95124b5b17224fced2f53a46a
36,717
from statsmodels.tsa.arima_model import ARIMA def run_arima_model(df, ts, p, d, q): """ Run ARIMA model """ # fit ARIMA model on time series model = ARIMA(df[ts], order=(p, d, q)) results_ = model.fit(disp=-1) # get lengths correct to calculate RSS len_results = len(results_.fittedvalues) ts...
f26698de1630774ac29ba5eafb5f66a76fb5db37
36,718
def is_type_bitfld(*args): """is_type_bitfld(type_t t) -> bool""" return _idaapi.is_type_bitfld(*args)
a34fa715f619da8d65a389064461e5aaff6c243f
36,719
import sys def query_av_summary_rpt(transaction_id, uploaded_file_name="", web_server_ip="127.0.0.1", web_server_port="80"): """ Query the 'AV summary report', for the specified 'server transaction_id' OR 'uploaded_file_name' value. (If a transac...
51451c62a916cf6a9cb239af827db47614d312b9
36,720
def get_arxiv_categories(arxiv_id=None, title=None, doi=None): """ Return a list of arxiv categories based on the specified arXiv identifier and/or title and/or doi. The identifier and title (if given) are both forwarded to the arXiv api. First element of the returned list is the primary category. ...
a4b5aeccb9a082cbde7d2e55bf6bd8c1c8d4e7af
36,721
def set_token(key, token_name, token_value=None): """ Set a token. Overwrites the existing token for a given key, if one exists. If a token value is not specified, a random value is generated. Args: key: the unique identifier object token_name: the name of the token to set ...
db71bb4bece60853d98c09b2fe9009798ab6990b
36,722
def get_custom_annotations_for_alias(data_type): """ Given a Stone data type, returns all custom annotations applied to it. """ # annotations can only be applied to Aliases, but they can be wrapped in # Nullable. also, Aliases pointing to other Aliases don't automatically # inherit their custom ...
17cd8e2b81b376c587f492d27e88c47f31d5d12b
36,723
import base64 import requests def getToken(): """ Method that generates and retrieves a temporary API access token for Reveal(x) 360 authentication. Returns: str: A temporary API access token """ auth = base64.b64encode( bytes(TARGET_ID + ":" + TARGET_SECRET, "utf-8") )...
a58c03e08caba2ed18264c54bd821a23bcc9206d
36,724
def valid_units(span, data): """Validate and update data units.""" units = [t.lower_ for t in span if t.ent_type_ in UNIT_ENTS] if units: units = REPLACE.get(units[0], units[0]) # Remove bad units if units not in ('m', 'ft'): return False data['elev_units'] = u...
5957412769c7941da600a6e09ed153bfe593791d
36,725
def win_active_by_handle(handle): """ :param handle: :return: """ ret = AUTO_IT.AU3_WinActiveByHandle(HWND(handle)) return ret
bb6d89dab59954ef0b59b941127ced1f6d908c49
36,726
from typing import cast def set_title_str(title: str) -> str: """Get the required string, including ANSI escape codes, for setting window title for the terminal. :param title: new title for the window :return: string to write to sys.stderr in order to set the window title to the desired test """ ...
0b9825198570bf50716b457142f6cad27278e3f7
36,727
def two_sum_ver2(nums: list, target: int) -> list: """Use dictionay""" # Save numbers and indexes num_idx = {} for i, num in enumerate(nums): num_idx[num] = i # Search an index using a key target - num for i, num in enumerate(nums): if target - num in num_idx and i != num_idx[ta...
9b15fb92fa42adc3802db40526af408899edf835
36,728
def _GetAndValidateCmekKeyName(args): """Parses the CMEK resource arg, makes sure the key format was correct.""" kms_ref = args.CONCEPTS.kms_key.Parse() if kms_ref: _ShowCmekPrompt() return kms_ref.RelativeName() else: # Check for partially specified disk-encryption-key. for keyword in [ ...
8238d1e0e802170d96ec3e96af7e11f14a1e2314
36,729
import torch def test_get_and_verify_covars_input_with_dependencies_fails(tmp_observe_class, covariates, kwarg_covariates, monkeypatch): """ test _get_and_verify_covars_input which depends on _read_covars_manual_input and _validators.Validators.__validate_num_covars. monkeypatch the user input (when neede...
ec8200de7a14beb662e3eaa3e95b9af4285b5771
36,730
async def clone_projectversion(request): """ Clone a project version. --- description: Clone a project version. tags: - ProjectVersions parameters: - name: project_id in: path required: true type: string - name: projectversion_id i...
38f4ede88f661a4ab829929ba5bdb4e5a8bbcede
36,731
def callback_tag(dataset, data_element, pattern): """ Called from the dataset 'walk' recursive function, will anonymize all the tag 'tag'.""" tag, action = pattern if tag in dataset: tag_repr = repr(data_element.tag)[1:-1].replace(" ", "") value = data_element.value anon_value = ...
25fe638cfd13a3515b0d11ab086e5b03feb8747a
36,732
import json async def bookshelf_read(request): """ Book has now been read. """ payload = await request.content.read() # create an event from this request payload = json.loads(payload.decode('utf-8')) event = make_event(name="book-read", payload=payload) await send_event(b"bookshelf",...
0f8c51be3531931241fc0ed797c978e32e234a3b
36,733
def _repr_unicode(dumper, data): """Fix yaml str representation.""" data = data.encode('ascii', 'ignore').decode() # XXX:Is this the best way? if '\n' in data: return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') else: return du...
4baf9aa67941179909719844c78651b62dce0abe
36,734
def get_paper_data(paper_name): """Gets paper code and paper type based on paper name""" split = paper_name.split("_") code = split[-1] paper_type = split[-2] if len(split) == 5: code = split[-2] + split[-3] paper_type = split[-1] elif len(split) == 3: code = "00" ...
7f5804241a3f97b2c0ea534a4f030841e7c86e3b
36,735
def create_macrobe(): """Create VFDBlToolResult with randomized field data.""" packed_data = create_values() return MacrobeToolResult(macrobes=packed_data).save()
b5ce9689ab2cffa0a0397dd5d9d1612bc0e871ec
36,736
import os def toLongPathSafe(path): """Converts the specified path string to a form suitable for passing to API calls if it exceeds the maximum path length on this OS. @param path: A path. Can be None/empty. Can contain ".." sequences. @return: The passed-in path, absolutized, and possibly with a "\\?\" pre...
dbbb39e9f5c1ad3fc02883af771c26b532901f28
36,737
import os import sys def test_can_run_as_admin(): """ A simple test function; check if we're admin, and if not relaunch the script as admin. """ if not isUserAdmin(): print("You're not an admin.", os.getpid(), "params: ", sys.argv) # rc = runAsAdmin(["c:\\Windows\\notepad.exe"]) ...
553e29274ca67ea5ce286fd27dab5c58c721d6a9
36,738
def handler_add_channel(): """Add a channel. .. :quickref: Media; Add a channel. :json string name: The name of the new channel :json string link: The link to fetch the channel from :status 200: The channel was correctly inserted :status 400: The provided JSON is invalid or there is a data...
f6a675a07ed0d0ddc332d11b634f1d4f533c1d5f
36,739
from typing import List from typing import Sequence from typing import Dict from typing import Union from typing import Optional import sys def distance_pattern_strings( sequences: List[Sequence], pattern: Sequence, ) -> Dict[str, Union[List[Optional[Sequence]], int]]: """Calculates the sum of distances b...
701e557692a8ab955818499a3a35c81d6b4852c4
36,740
import os import shutil def lulesh_caliper_json(data_dir, tmpdir): """Builds a temporary directory containing the lulesh JSON file.""" cali_json_dir = os.path.join(data_dir, "caliper-lulesh-json") cali_json_file = os.path.join(cali_json_dir, "lulesh-annotation-profile.json") shutil.copy(cali_json_fil...
742f496f0466ad55c64878ad7d4c0d5d60594fc3
36,741
from re import X def is_struct_field_address(xpr: X.XXpr, astree: AbstractSyntaxTree) -> bool: """Return true if the expression is the address of a known struct.""" if xpr.is_int_constant: return astree.is_struct_field_address(xpr.intvalue) return False
95536d96f56ab04ff012f2576d89fb4b4db5e2f6
36,742
def get_scanner(hass, config): """Validate the configuration and return an ASUS-WRT scanner.""" scanner = AsusWrtDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None
9748db0ba1f6555b478f000634661e07777de0c1
36,743
def remove_vulgarity_id(sentence): """remove_vulgarity_id Removes uncivilised words in Bahasa Indonesia Prevent words such as "anjir", "babi" etc to be included in natual language generation tasks :param sentence: An input string :type sentence: str :return: A string where common swear words i...
edeb76e102ab4b19d0b27e7b6352b2be40afe1d7
36,744
from typing import List def str_class(s: str) -> str: """Expand a string of character ranges. Example: str_class("a-cx0-9") = "abcx0123456789" """ i = 0 n = len(s) ret: List[str] = [] while i < n: if i + 2 < n and s[i+1] == '-': start = ord(s[i]) end = ord(...
21bbd7b46a964f20377b4f98b203b6bf0ad210c2
36,745
def activate_boolean_map(bool_map): """ Performs activation on a single boolean map. """ # use the boolean map as a mask for flood filling activation = np.array(bool_map, dtype=np.uint8) mask_shape = (bool_map.shape[0] + 2, bool_map.shape[1] + 2) ffill_mask = np.zeros(mask_shape, dtype=...
3fb11188386ae79bb501aeee5c3da8e1c5142c69
36,746
def migrate(migrator, database, fake=False, **kwargs): """Write your migrations here.""" @migrator.create_model class CommentReportLog(pw.Model): rid = pw.ForeignKeyField( db_column="id", model=migrator.orm["sub_post_comment_report"], field="id" ) action = pw.IntegerFiel...
58f7938b17fc2eb797d685d335c991213e91faea
36,747
def adjust_verbs(sentence, conjugator, lemmatizer): """adjusts verbs in sentences to their respective plural form""" tagged = pos_tag(word_tokenize(sentence)) adjusted = [] for t in tagged: if t[1] == 'VBZ': lem = lemmatizer.lemmatize(t[0], pos="v") if lem == 'go': ...
472543ec45d3501ec232b21c47ce6285800f26e4
36,748
def hexstr2int(hexstr): """ Convert string of hex values to list of integers. example: "1a 1b 1c 1d" => [26, 27, 28, 29] """ return [int(x, 16) for x in pairwise(hexstr.replace(" ", ""))]
4833ec873e4969314a4ebb8029f1e95f1e3619d2
36,749
def getlength(): """retrieves the length of every document and stores in a dictionary""" le={} o = open("lengths.txt", 'r') for line in o: li=line.strip().split(' ') le[li[0]]=li[1] o.close() return le
07495647e9614c35af830bcba520cc2f66488824
36,750
def vib_energy_diagram( quant_nums, vibrations, maxV=2, maxE=3000.0, useFull=True, image=None, imagesize=0.1 ): """ Function that will generate a vibrational energy diagram. This function wraps the make_elevel_plot function! Input arguments are quant_nums: A 2D numpy array of ...
4a6d9f7516388245975b183d803cb8a54866251a
36,751
import math import itertools def generate_guide_stars(catalog): """Generate a catalog with the angular distance of all stars combinations""" guide_stars = {} FOV_h = 14.455 * math.pi/180 FOV_v = 10.94 * math.pi/180 FOV_diag = math.sqrt(FOV_h**2 + FOV_v**2)/2 for a, b in itertools.combinat...
92484ed03e5ba7ae59d20dbf9680700bc894f3da
36,752
def create_loaders(full, batch_size, val_split, shuffle=True, min_val=1): """Split full dataset into training and validation :param torch.utils.data.Dataset full: Entire dataset :param int batch_size: Number of samples per batch :param float val_split: Percent of full dataset to use for validation ...
023f324d334052e41e9467b020a0a605b3bb77d3
36,753
def sd_features_length(self): """features_length for SubDataset Args: self (SubDataset): """ return self._dataset.features.features_length()
da46ce72e10f392e3207cbfa997c111f045da65b
36,754
from typing import List from typing import Tuple def filter_edges(nodes:List[int], edges: List[Tuple[int,int,int]]) -> List[Tuple[int,int,int]]: """Filter the edges of a subgraph. Parameters ---------- nodes: list containing the nodes edges: list containing the edges of the original graph Re...
50cf2986a5afa4748cf9b8505fc992f7b7f97db1
36,755
def get_shared_symmetry_operations(struc, pointops, tol=0.1): """ Get all the point group operations shared by a pair of atomic sites in the form [[point operations of site index 1],[],...,[]] Args: struc: Pymatgen structure pointops: list of point group operations from get_site_symmetr...
577e5d5a74d0b83202cf22e8524429c0a1ac4635
36,756
def flatten(node: ir.Node) -> ir.Node: """Flattens an node if possible. Flattens an node if it is: + a singleton BinaryOp; or + a compound BinaryOp with reduction operators; or + a compound Operand; or + a Unary with an identity operator. An Operand is a compound Operand if and only if its attr ...
022b8f97a43e7bd8190445fed71cf2e5114b5450
36,757
import math def is_primes(n) : """return 'True' if 'n' is a prime number. False otherwise""" b =[] if n==1: return False # 1 is not a prime if n==2: return True if n > 2 and n % 2 ==0: return False max_divisor = math.floor(math.sqrt(n)) for i in rang...
8054efd19b2e6a3b0e1de896865ae7e36e1d9125
36,758
import six def _generate_waveform_name_dict(): """Maps _WAVEFORM_DEFS -> _WAVEFORM_NAMES. _WAVEFORM_NAMES is a sparse map of the following keys: "id:device:channel" -> name "id:device:" -> name "id::channel" -> name "id:" -> name """ data = {} for waveform in _WAVEFORM_DEFS: for key, ...
1c9618dd7e49fc94f3ebdc84b954f946d23833d3
36,759
import json def generate_gcode(*args): """ generate gcode for heightmap in a given orientation note: [toBeImproved]heightmap passed as formatted string isnt a good way to structure the code """ arg = args[0][0] orientation = args[0][1] global diameter, step, feed comman...
91308d0b0230b2e314b63e93c7a1cf60485de60b
36,760
def dense_rank_based_voting(score_df, level, column='score'): """ The amount of vote each program component (corresponding to a row in `score_df`) cast is defined by the inverse of the dense rank of its suspiciousness score, which is stored in the column `column` of `score_df`. Then, the total v...
3fdbcbe8fb92e0668f9ea5f5548cebbf32a676bb
36,761
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradien...
c85b0e6a5d94df6a116c7fb389f3633d3c1a2b64
36,762
def power_spectral_density(signal, window, overlap, fmin, fmax, fs, average=True): """Compute PSD using welch method Parameters ---------- signal : array of shape (n_samples,) The signal to compute the PSD on. window : int Length of the segments. overlap : float proporti...
f8051bcb34dfc9fc4535471394357b39896dc304
36,763
def GetStatus(issue): """Get the status of an issue, whether it is explicit or derived.""" return issue.status or issue.derived_status or ''
4f51142dc4e55adaa27eaf3f3e7e748a49d45df2
36,764
def set_safe_attr(instance, attr, val): """Sets the attribute in a thread safe manner. Returns if new val was set on attribute. If attr already had the value then False. """ if not instance or not attr: return False old_val = getattr(instance, attr, None) if val is None and old_val...
92f657a8e8919b47db6f38a31d4c1cad5bea4c93
36,765
def receives(func): """ Decorate a method to enable method mocking """ def call_receiver(*kargs, **kwargs): receiver = Receiver() kwargs['receive'] = receiver result = func(*kargs, **kwargs) receiver.finalize() return result return call_receiver
1505b82e3cdb2d3a2a74fc8b295ee39acc65c33b
36,766
import tempfile import os def upload(): """Recieve a perun tarball, store it in a temporary file and process it.""" # Create a tempfile to write the data to. delete=False because we will # close after writing, before processing, and this would normally cause a # tempfile to disappear. file = temp...
ffce91a899ee914a4315d9313c9731a91d65b656
36,767
import argparse def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Faster R-CNN demo') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=3, type=int) parser.add_argument('--cpu', dest='cpu_mode', ...
29c045ca2a4215e02fe24da6d80dac9e45d1310b
36,768
def left_hash(msg, func="HS256"): """ Calculate left hash as described in https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken for at_hash and in for c_hash :param msg: The message over which the hash should be calculated :param func: Which hash function that was used for the ID to...
6e9732bd511173770e9bfbb81d77607e8b1be32c
36,769
def xbin_ybwt(x, y, xbins, Nmin=1): """ Take x,y pairs. Bin in x, find biweight location and scale Input: x and y, xbins Nmin : default 1 minimum number of points per bin to be used (otherwise nan) Return: xbins centers, yloc, yscale """ assert len(x) == len(y) ...
af6938bd58c1cc2a0852e52fa9f5137b73b48f7d
36,770
def get_container_runtime_module(): """check what container runtime is running and return a handle to it""" # TODO THIS LOCKS SSH CLIENT TO CONTROLLER ssh_client = topology.list_openstack_nodes(group='controller')[ 0].ssh_client if docker.is_docker_running(ssh_client=ssh_client): ret...
bf9bea2dac5d1011e909c2be9911147ef83fda81
36,771
def render_body_keypoints(img: np.array, body_keypoints: np.array) -> np.array: """ Render OpenPose body keypoints on input image. Args: img (np.array): Input image of shape (H, W, 3) with pixel values in the [0,255] range. body_keypoints (np.array): Keypoint array ...
d52d79bb316647a538a8225a38498d0160cf29c1
36,772
import asyncio def create_app(): """ 建立web应用 url: http://flask.pocoo.org/docs/1.0/quickstart/ :return: """ flask_app = Flask(__name__) with flask_app.app_context(): # 项目内部配置 mongodb_base = MongodbManager.get_mongo_base( mongodb_config=Config.MONGODB_CONFIG ...
6a2f995254d23dc41422282c204e8e435cdbd9ed
36,773
import json def update_status_config(milestones_content): """Convert the JSON milestones from GitHub to a simple dict.""" milestones = json.loads(milestones_content) # Test that GitHub milestones and local definitions are equivalent status_names = sorted(STATUSES.keys()) milestone_names = sorted([...
d0c8a4b1591735970bcab9c76fdc22135171b41d
36,774
def getNjuClassesUrl(date=date.today()): """url of classes information""" return 'https://wx.nju.edu.cn/njukb/wap/default/classes?date={}'.format(str(date))
535cf2e7ad176464d5db07c5bf32812abfd3e6ec
36,775
def sg_to_brix(sg): """ Specific Gravity to Degrees Brix :param float sg: Specific Gravity :return: Degrees Brix :rtype: float Source: * http://en.wikipedia.org/wiki/Brix * http://www.brewersfriend.com/brix-converter/ """ if sg > 1.17874: raise SugarException(u"Above 4...
4a097fd7898368a7608ae0a76181f6d090b2cf17
36,776
import os def trigger_renditions_bucket_event(data, context): """Background Cloud Function to be triggered by Cloud Storage. This function retrieves a source video and triggers the generation of renditions by means of an http asynchronous call to the create_renditions_http function Args:...
fb850dbf1b445661bc29f169992001db094d3b1d
36,777
def detect_peaks(x, mph=None, mpd=1, threshold=0, edge='rising', kpsh=False, valley=False, show=False, ax=None): """Detect peaks in data based on their amplitude and other features. Parameters ---------- x : array-like 1D vector with data mph : {None, number}, optional (def...
e6a73fc30b1973f921195e676b43cc0d82b3ab5c
36,778
import numpy def HarmonicOscillatorsSample(N_k=[100, 100, 100], O_k = [0, 1, 2], K_k = [1, 1, 1], seed=None): """ Generate samples from 1D harmonic oscillators with specified relative spacing (in units of std devs). OPTIONAL ARGUMENTS N_k (list or numpy.array of nstates) - number of samples per state O...
b83a28f22703113908910c84655f2a8ed2321af5
36,779
def genkeys(e, bit): """ Generates keys for rsa. Parameters: e (int): public key bit (int): bit length of primes Outputs: n (int): modulus e (int): public key d (int): private key """ lam=0 while np.gcd(e, lam) != 1: p=genprime(bit) q=genprime(bit) ...
788f0f51cea7c72a0715565e04b3f59677d62db8
36,780
def get_xml_subelement(xml_elem, subelement, attribute=None, multi=False, convert=None, default=None, quiet=False): """ Return the text or attribute of the specified subelement === PARAMETERS === xml_elem : search the children nodes of this element subelement: name of the subelement whose text wil...
574880a2bfb7a6203b5079ec38ebc0d9af41cb07
36,781
def sub_env_var(uri, envvars): """Substitute any environment variables found""" match = ENVVAR_RE.search(uri) if not match: # no environment variable in uri return uri old = match.group(1) envvar = match.group(2) if not envvar in envvars: print(f'Undefined environment variable {...
273244d13662f6f5bc6ceeef181b9f044020f81b
36,782
def filter_intensity_jumps(i0,winsz=20,num_quantiles=2,quantile=0.5): """ Identify locations in the trajectory where the intensity jumps significantly Parameters ---------- i0 : numpy.ndarray Dot intensity time series. winsz : int Window size for creating the trendl...
1cd0d69cd88fe78b6ba6e171c84c5dccb50d0074
36,783
def str_to_tn(str_): """Fully parses str_. A full parse might not be necessary. Both blocks and the nodes can be (and probably should be) parsed lazily. """ lines = str_.split(NODE_BREAK) return get_blocks(lines)
7e8a23a4a3010f5eef3b5226456d42f19078acfc
36,784
import os def read_multiple_files(files): """read multiple L1-related files and return dictionary of executed read-in class instances Args: files: list of files to read in Returns: dictionary with keys brt, blb, irt, met, hkd containing list with all read-in class instances for the ...
3abd6e688621d492eff82bf4a949918c1949a822
36,785
from typing import List def parse_with_semantics(text: str, semantics: type=None) -> List[base.StatementObject]: """Parse a file with given semantics.""" return lang.parse(text, semantics=semantics())
10c3b93df0b501733bbae5208c2a46ef4fa5217e
36,786
def get_object_expiry_time(storage_url, auth_token, container, name): """Return in seconds the header x-expiry-at for the given object.""" cont = client.head_object(storage_url, auth_token, container, name) return cont.get('x-delete-at', '')
0a5a3f3ba2f14cb6737d52907f08e26e98b83935
36,787
def file(input_file): """Import colorscheme from json file.""" data = util.read_file_json(input_file) if "wallpaper" not in data: data["wallpaper"] = "None" if "alpha" not in data: data["alpha"] = "100" return data
053bc45f11f3995e8b07c85febd1aeb1d9f20686
36,788
import requests import html def find_artists(artist): """ Searches and returns the first page results of AZLyrics artists. :param artist: string with the name of the artist :return: list of dicts with artist and url strings """ r = requests.get("https://search.azlyrics.com/search.php", ...
d691eec62807c9201f05ccdda6b7f5b78960adee
36,789
def l_model_forward(x, parameters): """ Forward propagation of deep learning. @param x: input x, numpy arrays @param parameters: @return: output aL and caches for following calculations, numpy arrays and indexes """ caches = [] a = x l_total = len(parameters) // 2 # number of layer...
bb689ff9dc7488215311f8ef97c6cc89503035ff
36,790
def get_work_value(block_hash, work, as_hex=False): """ Get the proof-of-work value. The work value must be equal to or higher than the work difficulty to be considered valid. """ validate_block_hash(block_hash) parse_work(work) reversed_work = bytearray(unhexlify(work)) reversed_wor...
b818623f9a00d4a9ff52dfd24d822e7a0414bfdb
36,791
def total_loss(output, target, loss='mse', only_nodes=False, only_graph=False): """ returns the average of the average losses of each task """ assert not (only_nodes and only_graph) if only_nodes: nodes_loss = get_loss(loss, output[0], target[0]) return nodes_loss elif only_graph: ...
f39efeba4fae9dd397c2c9ea36d1ece865721e67
36,792
def parse_mem_str_to_gbsize(strmem): """ String like 845 MB 677.8 MB to GB size :param strtime: :return: """ strmem = strmem.strip() if strmem.endswith('MB'): memgb = float(strmem[:-2]) / 1024 elif strmem.endswith('GB'): memgb = float(strmem[:-2]) elif strmem.endswit...
fd7d96c25b446a1c5ff94694908a9c355e340780
36,793
def Emonet_extend(num_classes): """ This model is optional and bigger than the previous one. Practically, this model is less useful than the first one therefore is not called by the application. Use only for experimental purposes """ emonet = Sequential() """ Convolution and Maxpool layers:...
7a22fe1f1107d0b27545a3046c35f5a661930227
36,794
import os def generate(provider, context, **kwargs): # pylint: disable=W0613 """Generate an EKS auth_map for worker connection. Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.context.Context`): context instance Retur...
04d90151cb257d341db5a8994ee46c62eb85241d
36,795
def isListController(obj): """ Evaluates if the supplied object is a list controller. :type obj: pymxs.runtime.MXSWrapperBase :rtype: bool """ return pymxs.runtime.classOf(obj) in LIST_TYPES
7d2285cb07744fd31aedd857c1691cda8b3e1f2a
36,796
def genomic_del1(): """Create test fixture containing params for genomic del VD.""" params = { "id": "normalize.variation:NC_000003.12%3Ag.10149811del", "type": "VariationDescriptor", "variation_id": "", "variation": dict(), "molecule_context": "genomic", "structu...
12083300ee1115bc65ef0a9c4494b9918ac16ad9
36,797
def civic_vid258(): """Create a test fixture for CIViC VID258.""" return { "id": "civic.vid:258", "type": "VariationDescriptor", "label": "A222V", "value_id": "ga4gh:VA.V5IUMLhaM8Oo-oAClUZqb-gDPaIzIi-A", "value": { "location": { "interval": { ...
ee725d2c4601ce400abf1cf9da3d5eaaa7ba5bda
36,798
def get_continuous_ts(finger, max_nans=30): """ Split TS where n consecutive nans bigger than max_nans. 1D only""" gaps = np.isnan(finger) assert(np.all(gaps[0,:] == gaps[1,:])), "Finger x, y dim not equal. Check!" # Use one axis (x,y) gaps = gaps[0,:] seg, n_seg = label(gaps) for s in ran...
7f1e05ab8757078b28b9b74abc6337f821a50b3c
36,799