content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def tab_listtable_details(p_engine, p_format, rulesetname, envname, metaname): """ List details of tables/file from ruleset param1: p_engine: engine name from configuration param2: p_format: output format param3: rulesetname: ruleset name to display metadata from param4: envname: environemnt nam...
f928d5d31ce59f1669c20080c8c18b239c1630aa
36,424
def setup_system_tomograph(n_shots: np.int, n_rays: np.int, n_grid: np.int) -> (np.ndarray, np.ndarray): """ Set up the linear system describing the tomographic reconstruction Arguments: n_shots : number of different shot directions n_rays : number of parallel rays per direction n_grid : n...
c3ba41db44972056023c9938444bb9e53d4220eb
36,425
from bs4 import BeautifulSoup def parse_markdown_to_html_table(): """ Parse README.md, convert to HTML, return table """ readme = open("README.md", 'r').read() html = markdown2.markdown(readme, extras=['tables']) soup = BeautifulSoup(html, 'html.parser') table = soup.find("table") return table
dad43919c302b1124edac41a442e782c052de0b0
36,426
def get_relation_priority(relation: Relation) -> int: """This function helps resolve conflicts when multiple conditions apply to the same factor transition. """ if isinstance(relation, And): priorities = [get_relation_priority(rel) for rel in relation.relations] priority = sum(prior...
bcde2220ddab1c75d316fbfa89c3e406275275fd
36,427
def _int_size_to_type(size): """ Return the Catalyst datatype from the size of integers. """ if size <= 8: return ByteType if size <= 16: return ShortType if size <= 32: return IntegerType if size <= 64: return LongType return None
f80231a841461557fb79dc3bbd3ff1c1a77b5016
36,428
def Coordinate(coord: str) -> Coord: """Converts a coordinate string into float tuple""" try: split = coord.split(",") return Coord(lat=Latitude(split[0]), lon=Longitude(split[1]), repr=coord) except Exception as exc: raise Invalid(f"{coord} is not a valid coordinate pair") from exc
9bb79d4975427f31474aa97dde5004bc44133fda
36,429
def getCollateralRepayQuote(coin, collateralCoin, amount, recvWindow=""): """# Get Collateral Repay Quote (USER_DATA) #### `GET /sapi/v1/futures/loan/collateralRepay (HMAC SHA256)` Get quote before repay with collateral is mandatory, the quote will be valid within 25 seconds. ### ### Parameters: Name |Type |Manda...
37d91a220af05098b481adb55d2499cf8179d99e
36,430
import string import re def _remove_duplicate_punctuation(text: str) -> str: """ Remove duplicate punctuation, which may have been a feature of gazette design. """ pattern = f"([{string.punctuation}])" + "{1,}" pattern = re.compile(pattern) text = re.sub(pattern, r"\1", text) return te...
8aacab404a8fe4c3b4feda899231d65967d91973
36,431
def coeffs_mydft(x, order): """Use DFT.""" coeffs = [my_dft(x, 0)] for k in range(1, order+1): coeffs.extend([my_dft(x, k), my_dft(x, -k)]) coeffs = np.array(coeffs) / len(coeffs) return coeffs
b53980556e407424ea492317cf8c28469c61c0de
36,432
def parse_employee_info(record_list): """ Parses the employee record information Example input: [('3c7ca263-9383-4d61-b507-2c8bd367567f', 123456, 'Austin', 'Grover', <memory at 0x11059def0>, True, 1, '00000000-0000-0000-0000-000000000000', datetime.datetime(2020, 2, 23, 16, 53, 25, 531305))] Args...
a0c4e9fb57bc452119f362525e9c16f516911922
36,435
from typing import Union from typing import Tuple from typing import Callable def make_request( schema: Schema, request_url: str, endpoint_name: str, method: str, body: Union[Tuple[str, str], None], after_error_occurred: Callable[[ErrorMessage], None] = None, before_request_send: Union[Cal...
7181a15a5dafa0c85d986edf2bd2ca2f497ab21b
36,436
import math def gas_release_rate(P1, P2, rho, k, CD, area): """ Gas massflow (kg/s) trough a hole at critical (sonic) or subcritical flow conditions. The formula is based on Yellow Book equation 2.22. Methods for the calculation of physical effects, CPR 14E, van den Bosch and Weterings (Eds.), 1996 ...
8749b85457e3f9e24e08f2a9f5f059066e3518b8
36,437
import copy def kube_rootca_update_start(token, force=False, alarm_ignore_list=None): """ Ask System Inventory to start a kube rootca update """ api_cmd_payload = dict() api_cmd_payload['force'] = force if alarm_ignore_list is not None: api_cmd_payload['alarm_ignore_list'] = copy.copy(...
886d708c6fb45d96d89613b391c5bc11136b54e7
36,438
def email2words(email): """Return a slightly obfuscated version of the email address. Replaces @ with ' at ', and . with ' dot '. """ return email.replace('@', ' at ').replace('.', ' dot ')
cd8dff104ace7eaad00164ba1161d1c49ce4a0e3
36,439
import requests from typing import Union from typing import Any import json def read_response_body(response: requests.Response) -> Union[dict[str, Any], str]: """ Read response body as a ``dict`` if possible, else as a ``str`` """ body = response.content.decode('utf-8') try: body = json.loads(body...
bac5aee7ac68287826e56cd86cfbc28ce4767768
36,440
import random def _augment_gain(audio, low=0.25, high=1.25): """Applies a random gain between `low` and `high`""" g = random.uniform(0.25, 1.25) return audio * g
e29aab98511168ce8fddb62c65a287f68fbc0e4e
36,441
def gaussfit(data, err=None, params=(), autoderiv=True, return_error=False, circle=False, fixed=np.repeat(False, 7), limitedmin=[False, False, False, False, True, True, True], limitedmax=[False, False, False, False, False, False, True], usemoment=np.array([], dtype='b...
882653f8186f4ec9c92a4236bfec4343edeb6c5e
36,442
def check_level_number(tags: Tags, level: float) -> bool: """Check if element described by tags is no the specified level.""" if "level" in tags: if level not in parse_levels(tags["level"]): return False else: return False return True
752e030fd52ed7bf8603e18c6d221b3a4be8daa4
36,443
def read_eof_file(file): """wrapper for parse_eof to return a dictionary""" D = dict() potc,rforcec,zforcec,densc,potS,rforces,zforces,denss = parse_eof(file) D['potC'] = potc D['rforceC'] = rforcec D['zforceC'] = zforcec D['densC'] = densc D['potS'] = pots D['rforceS'] = rforces ...
461cdad86e8782a1742e61c10a74108f3c56685e
36,444
import glob def test_train(args): """Trains the model.""" if args.verbose: tf.logging.set_verbosity(tf.logging.INFO) # Create input data pipeline. with tf.device("/cpu:0"): train_files = glob.glob(args.train_glob) if not train_files: raise RuntimeError( "No training images found ...
aa5105598329d95cc2626d2fdce18841aa733ce9
36,445
def protocol_store(sql_engine: SQLEngine) -> ProtocolStore: """Return a `ProtocolStore` linked to the same database as the subject under test. `ProtocolStore` is tested elsewhere. We only need it here to prepare the database for our `AnalysisStore` tests. An analysis always needs a protocol to link to....
225b9cba534a2c64aff2e8b7d22f6f3c304c03dd
36,446
import traceback def session_wrapper(addressed=True): """Allow to differentiate between addressed commands and all messages.""" def real_session_wrapper(func): """Wrap a telethon event to create a session and handle exceptions.""" async def wrapper(event): if addressed: ...
c5852f3eaab335630ecba04c62552f2376d936a3
36,447
from typing import Union from typing import Callable def _get_callable_str(*, callable_: Union[Callable, str]) -> str: """ Get a callable string (label). Parameters ---------- callable_ : Callable or str Target function or method or property or dunder method name. Returns -------...
2b968e3f5ff79701e6f63bb75548ecb228ec5ed7
36,448
def pad_lr(x, fsize, fshift): """Compute left and right padding """ m = num_frames(len(x), fsize, fshift) pad = (fsize - fshift) t = len(x) + 2 * pad r = (m - 1) * fshift + fsize - t return pad, pad + r
409f2cb0b7604d54be5e60ec7923160493cfcf75
36,449
import tarfile def setup_routes(): """Setup dispatcher routes (i.e. URL paths)""" root = CherryTarball() d = cherrypy.dispatch.RoutesDispatcher() d.connect('main', '/', controller=root) # This enumerates the tarball and connects each file within to a URL in the dispatcher tar = tarfile.open(ta...
08ebf1040c852a6d9252a0635b4db37bcb0041a4
36,450
def check_voicehat_is_first_card(): """Check that the voiceHAT is the first card on the system.""" cards = get_sound_cards() return 0 in cards and VOICEHAT_ID in cards[0]
525e0a976b1fe047b0e08a53ade7fc31b755875b
36,451
def removeVM(vm): """Removes virtual machine. NOTE: This operation is undo-able. @param vm: Virtual machine's name.""" return defer.maybeDeferred( _getController().removeVM, vm)
927d92301cad20d133244dc002b90ac8da77b7a5
36,453
import itertools def probablePosition(board): """ |x-pos_x|<3, |y-pos_y|<3 :param board: the current board state :return: position: all position may be considered """ probable_list = [] for (pos_x, pos_y) in itertools.product(range(pp.width), range(pp.height)): if n...
d4d603a731661b795a1cbc6cd0cae3086f1352d8
36,454
from typing import Tuple from typing import List def get_user_group_perms( user_or_group: UserOrGroup, obj: models.Model ) -> Tuple[PermissionList, List[Tuple[int, str, PermissionList]]]: """Get permissions for the user/group on the given model. This method is only used in Resolwe views and expects permi...
61e1b5d3eea1c5cf103c1d9954899fef6d65336a
36,455
def update_button(first_color, second_color, _button_state): """Updates button, and changes color depending on if the mouse is hovering over button. Returns if the mouse is hovering over button or not""" _mouse_hover = False # noinspection PyChainedComparisons if mouse[0] > 4 and mouse[0] < 381 and ...
79d17afa5836588a587ec12bd83297a26cace385
36,456
import yaml def get_configmap_fields_from_yaml(file) -> {}: """ Parse yaml file and return a dict of ConfigMap data fields. :param file: an absolute path to a file :return: {} """ with open(file) as f: dep = yaml.load(f) return dep['data']
08eef30d0d8e79824adefd36f5c753ba76b504ef
36,457
def addfella(): """ This endpoint is for adding fellas to the application. Loadbalancer decids to go for which instances and based on that fella is added to it. """ instance_id = os.getenv("CF_INSTANCE_INDEX") print 'Instance Id ****************%s'%instance_id fella_count = int(db.hg...
42ad81f91f6150f23bb7979ca227081203791ac0
36,458
def join_race_and_gender(c_id_string, artist_df): """ takes in a string of c_id(s), ex: "8210" or "8210, 5670" returns a total count of male, female, white, black, asian, aian, mix, hispanic """ male = 0 female = 0 white = 0 black = 0 asian = 0 aian = 0 mix = 0 hispanic =...
3793049d85a12d77058f9574be34b197b5a84760
36,459
def get_average(pixel, date, dataset): """ Return an N month average in the given dataset. """ N = 24 vals = [] bad_cnt = 0 # generate lists of month numbers and values for i in range(N): try: vals.append(dataset[date][pixel]) except KeyError: bad...
b436256c68dbc7b8dc3715ac337939dd54f1b6df
36,460
import re def to_mb(s): """Simple function to convert `disk_quota` or `memory` attribute string values into MB integer values. """ if s is None: return s if s.endswith('M'): return int(re.sub('M$', '', s)) elif s.endswith('G'): return int(re.sub('G$', '', s)) * 1000 ...
870f276552ef90bbd5034551ea8ade0f5160491b
36,461
from typing import Union from typing import NoReturn import re def get_pattern(plate: str) -> Union[str, NoReturn]: """ Given a string that represents a plate, tries to return its pattern. If the plate is not valid, raises a PlateNotValidException """ if not valid_plate(plate): raise P...
0037aa3b64589def6df9aab32935fe8f666657da
36,462
def Select(combinations, loads, max_number_of_workers): """This method selects the optimal combination of appointments. This method uses Mixed Integer Programming to select the optimal mix of appointments. """ solver = pywraplp.Solver('Select', pywraplp.Solver.CBC_MIXED_INTEGER_PRO...
80c375f0690effdaa631d5b9da8ba79d2fc0d9e1
36,463
def voter_stop_opposing_save_doc_view(request): """ Show documentation about voterStopSupportingSave """ url_root = WE_VOTE_SERVER_ROOT_URL template_values = voter_stop_opposing_save_doc.voter_stop_opposing_save_doc_template_values(url_root) template_values['voter_api_device_id'] = get_voter_api...
2371bf6b7ebbf863256e71294810cef8c47c0762
36,464
from datetime import datetime def first_date_in_time_dimensions() -> datetime.date: """The first date that should appear in time dimensions""" return datetime.date.today() - datetime.timedelta(days=365)
cc0f626bba0cd5b650beb1c0e6ccea2b2f697260
36,465
def length_left(lumber): """ Convenience function for calculating the length left in a piece of lumber :param lumber: a piece of Lumber :return: length remaining """ return lumber.length_left()
57dfd5e160abdc086759dd41df013181f1217f9d
36,466
def create_spawn_point_prefab(team): """Return a team-specific spawn-point prefab.""" prefab = { "name": "spawn_point", "components": [ { "component": "StateManager", "kwargs": { "initialState": "playerSpawnPoint", "stateConfigs":...
7874a6fa184b469acc836b9a965a35a33b4bd9ba
36,467
def FindOrBuildDpa(dpas, options, grants): """Find or build DPA for simulation purpose. If several DPA, select the one with most grants around (but DPA simulation options always override the logic). """ if options.dpa: dpa_kml_file = options.dpa_kml or None dpa = dpa_mgr.BuildDpa(options.dpa, None, p...
b931b29b2b475fbdf520b4fe76b65269e511623c
36,468
def register(request): """ A view that renders the register page for new users. This can only be access by users that are not currently signed in. **Context** ``form`` Registration form for new users **Templates:** `base/register.html` ...
df5ee67de73f253934cf28d0c2032c9022a1dc50
36,469
def masked_softmax_cross_entropy(preds, labels, mask): """Softmax cross-entropy loss with masking.""" loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.reduce_mean(mask) loss *= mask fin_loss=tf.reduce_mean(loss) var...
2c05bfe1e6cc68fab156fbeeab08299aaaf5bf6e
36,470
def find_matching_paren_pair(s): """ Find the first matching pair of parentheses and return their positions """ paren_level = -1 open_pos = 0 for i in range(0, len(s)): if s[i] == "(": paren_level += 1 if paren_level == 0: open_pos = i elif...
c50ce61ca96f1babb951d2c1051461be8633d783
36,471
import copy def copy_mol(mol: Chem.rdchem.Mol) -> Chem.rdchem.Mol: """Copy a molecule and return a new one. Args: mol: a molecule to copy. """ return copy.deepcopy(mol)
a4ecabefcf5b8fc19961d5de912c3f055b5eb690
36,472
import logging def convert_sync_bn(config, model): """ Convert the BatchNorm layers in the model to the SyncBatchNorm layers. For SyncBatchNorm, we support two sources: Apex and PyTorch. The optimized SyncBN kernels provided by apex run faster. Args: config (AttrDict): configuration file...
5795bdc269a8b44c324298ebaba156a80a098c70
36,473
from . import nodes def _(dbmodel, backend): """ get_backend_entity for DummyModel DbNode. DummyModel instances are created when QueryBuilder queries the Django backend. """ djnode_instance = djmodels.DbNode( id=dbmodel.id, node_type=dbmodel.node_type, process_type=dbmodel....
b8b5ebb1f0c669cd9b7aa6848476cad65cfc9825
36,474
def update_job(function): """Decorator to update Task with result.""" @wraps(function) def wrapper(task_id, *args, **kwargs): task = Task.objects.get(id=task_id) task.status = Task.STATUS[1][0] task.save() try: result = function(*args, **kwargs) task....
ac8034db39f35e29c3c61da1912087b30158b44f
36,475
def checkLogin(): """ Check if user is logged in """ if current_user.is_authenticated: return {"authenticated": True, "user": current_user.username} else: return {"authenticated": False}
7c7d7f4ee05b036e50ce8462dd9e01751c044235
36,476
from typing import Tuple from typing import Any from typing import Optional def _load_checkpoint( checkpoint: Checkpoint, trainer_name: str ) -> Tuple[Any, Optional[Preprocessor]]: """Load a Ray Train Checkpoint. This is a private API. Args: checkpoint: The checkpoint to load the weights and...
0962a863b1759bdbff31d035c33d7106de4b14f2
36,477
def aoa_music_1D(steering_vec, rx_chirps, num_sources): """Implmentation of 1D MUltiple SIgnal Classification (MUSIC) algorithm on ULA (Uniformed Linear Array). Current implementation assumes covariance matrix is not rank deficient and ULA spacing is half of the wavelength. .. math:: P_{} (\\t...
376adf8efea651fb915925e936c19e9741c45e0c
36,478
def IsMerge(op): """Return true if `op` is a Merge.""" return op.type == "Merge" or op.type == "RefMerge"
8b5c7373cd698d23bd1b0df78a5986dded8960ec
36,479
import re def book_info(td): """given a BeautifulSoup <td> Tag representing a book, extract the book's details and return a dict""" title = td.find("div", "thumbheader").a.text by_author = td.find('div', 'AuthorName').text authors = [x.strip() for x in re.sub("^By ", "", by_author).split(",")] ...
aad47098c8b1ea4c3f6ac1b55d3197b14c94d173
36,481
def find_groups(groups=None, name=None, gid=None, member=None): """ Return groups that match the specified values. Returns an empty list if no groups match. 'member' can be an array and is allowed to be a subset of the 'members' array associated with a group, i.e. if member == ['a', 'b'] and a giv...
f08409c973408742405b5320e43128cafcc56574
36,482
def btran_helper(eta_list, a): """ Helper function for the Btran method. :param eta_list: Eta vectors list. :param a: Vector a. :return: The resulting vector. """ if len(eta_list) == 1: return a.dot(np.linalg.inv(eta_list[0])) z = btran_helper(eta_list[1:], a) return z.dot(np...
f10b7e1bf8b143b15521f8db99af8ff3ece8be42
36,483
from joblib import Parallel, delayed from psutil import cpu_count from multiprocessing import cpu_count from scipy.stats import spearmanr def permutation_spearman(xvals, yvals, trials=1e5, normalize=True, doparallel=True): """ given a list of xvals and yvals, returns a p-value that is the fraction of the ...
dce8b6f72aa937c62304fe8852f57ad0d2b3cdf8
36,484
def to_binary(n): """Convert integer n to binary form.""" if n == 0: return zero elif n == 1: return one elif n % 2 == 0: return bit0(to_binary(n // 2)) else: return bit1(to_binary(n // 2))
6c04e15a9458ca285ab0e73ac27e4a3c7c552699
36,485
import requests def get_short_interest_days_to_cover(sort_field: str) -> pd.DataFrame: """Get short interest and days to cover. [Source: Stockgrid] Parameters ---------- sort_field : str Field for which to sort by, where 'float': Float Short %%, 'dtc': Days to Cover, 'si': Short Inter...
edf8823cb96a31b07b359591337f196b47959583
36,486
import logging def with_setup_factory(setup_funcs=(), teardown_funcs=(), post_initialize=()): """Create different kinds of `@with_setup` decorators to properly initialize and teardown things necessary to run test functions `setup_funcs` - a list of functions that do things before a...
80fd54fb63ac494ad727860422a6cf8e6a1d7389
36,487
def grab_stat_entries(stat_file_name,name): """ stat_file_name: .stat.h5 file name, name: ex. gofr """ stat_file = h5py.File(stat_file_name) data = [] # find entry and extract data for estimator in stat_file.keys(): if estimator != name: continue # end if ent...
ad9a49207a334cbbd791a23b66453ed666e49df5
36,488
def exception_handler(exc, context): """ 自定义异常处理 """ # 调用drf框架原生的异常处理方法 response = drf_exception_handler(exc, context) if response is None: view = context['view'] if isinstance(exc, DatabaseError) or isinstance(exc, RedisError): # 数据库异常 logger.error('[%s]...
5f2b5168f7f87d4cef5055f0620b328e7df63cd6
36,490
def can_view_email(user, obj=None): """ View staff emails or your own. """ return obj.is_staff or obj == user
632412669bc163ce6316a3fd6891ba3930405e8c
36,491
def calculateMatchValueWithRanges(incompleteObject, knownObject): """Calculate an integer match value, scoring +1 for each match""" matchvalue = 0 for catkey, catval in incompleteObject.items(): if (catkey == 'cats' or catkey=='trees'): if catval > knownObject[catkey]: ma...
6f9cf701eca03ee41266d0001da02072072c5191
36,492
import uu def relativistic_waveshift(dv, units='km/s'): """ Relativistic offset in wavelength default is dv in km/s :param dv: float or numpy array, the dv values :param units: string or astropy units, the units of dv :return: """ # get c in correct units # noinspection PyUnresolve...
f139eec659c178679a35fe6b18d81d1fd6b91acb
36,493
def divisors(integer): """ Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime' (null in C#) (use Either S...
6fccf9c5ec49f8ddd852b5aad071f187739e5f0b
36,494
def hex_to_binary_str(pdq_hex): """ Convert a hexadecimal string to a binary string. Requires input string to be length BITS_IN_PDQ / 4. """ assert len(pdq_hex) == BITS_IN_PDQ / 4 # padding to 4 bindigits each hexdigit result = "".join(bin(int(c, 16))[2:].zfill(4) for c in pdq_hex) assert le...
906250590a9c19097babae1c2e8bde088cc94aff
36,495
def hinge_loss(psample, qsample): """Point-wise hinge loss.""" loss = tf.nn.relu(1.0 - psample) + tf.nn.relu(1.0 + qsample) return loss
4f174601e8fdce5fa65b621de962744e4def2f5c
36,496
from re import L def l_spin(pdgid): """ Returns the orbital angular momentum L as 2L+1. Notes ----- - This is valid for mesons only. None is returned otherwise. - Mesons with PDGIDs of the kind 9XXXXXX (N=9) are not experimentally well-known particles and None is returned too. """ ...
8b5b6c332d7a52655d05f5877cbe101b72926c94
36,497
def with_metaclass(meta: type, *bases) -> type: """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): # type: ignor...
629e2dce944b4338357843b1233b432257ab1de8
36,498
from re import A def mod(a: protocols.SupportsMod[A, B], b: A) -> B: """ Return `a % b`, for _a_ and _b_. Example: >>> mod(2)(3) 2 Args: a: left element of % expression b: right element of % expression Return: a modulo b """ return a % b
bb6ef1dba0891b9ca5fa54205f86c65faa823513
36,499
def ParseNetworks(value, project, version): """Build a list of PolicyNetworks or ResponsePolicyNetworks from command line args.""" if not value: return [] registry = api_util.GetRegistry(version) networks = [ registry.Parse( network_name, collection='compute.networks', pa...
c0d69dca0cee276d944585dec89190bb46bb089a
36,501
def do_something_bar(): """ bar! --- responses: 200: description: Success """ return do_something()
0d0e55c4a12652ad941e57f339f2a9cfb942b3d9
36,502
from datetime import datetime def login(): """用户登录接口 eg: { "username": "liuli", "password": "liuli" } Token Demo: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTYyNzc1MDQ1OCwianRpIjoiNzJjZjZkYzYtZDE5NS00NGRhLTg2NWUtNmNhZmY3MTdkMjMwIiwidHlwZSI6ImFjY2VzcyIsIn...
d54113e4d6b671f2f18117b1846d55d331dad36d
36,503
import re def fraction_to_word(aText, fractions): """Spell out fractions written with a '/'. """ aText = re.sub(r"1/2", fractions[0], aText) aText = re.sub(r"1/3", fractions[1], aText) aText = re.sub(r"2/3", fractions[2], aText) aText = re.sub(r"1/4", fractions[3], aText) aText = re.sub(r"3/4"...
15a99870f2161a354aa69fadc484435b9d37d477
36,504
def create_message_context_properties(message_type, message_id, source, identifier, is_cloud_event_format) -> dict: """Create message context properties dict from input param values.""" return { 'type': message_type, 'message_id': message_id, 'source': source, 'identifier': ident...
c5edd78abb5e584089456f4d50a656ce46a7666c
36,505
import threading import time def run_continuously(interval=1): """Continuously run, while executing pending jobs at each elapsed time interval. @return cease_continuous_run: threading.Event which can be set to cease continuous run. Please note that it is *intended behavior that...
b20790efae0a85b5bca9e3800a4025a6310c67ab
36,506
def remove_holes(mask): """ This method removes holes inside the the binary mask by assigning '1' to all regions that are not reachable from the mask corners :param mask: mask to process :return: mask with connected components without holes """ height, width = mask.shape postprocessed...
83a5eca955bde060542d7fbfcc32f64b17756b4a
36,507
def get_search_space(max_len, channel_range, search_space=[], now=0): """ Recursive. Get all configuration combinations :param max_len: max of the depth of model :param channel_range: list, the range of channel :param search_space: search space :param now: depth of model :return: ""...
eeffb0c9caee726edce71fd38aa9253080af6a0d
36,508
def create_gtf_file(input_file, output_file): """Create pseudo gtf file for all probes sequences `input_file`: A manifest csv file that contain probe information `output_file`: A pseudo gtf file that serve for annotation """ print colored("Stage 3: Creating custom gtf file from manifest file ...", "...
f53046c26608f1e72b8744da3bcf19309a1aea38
36,509
def remove_observations(acyclic_graph): """ Remove all observations from a symplectic acyclic_graph. """ result = acyclic_graph.copy() RemoveObservations().optimize_acyclic_graph(result) return result
a4cdcf1e00b72b33f974c761ea93b3ff3c56225a
36,511
def contours_by_Imax(data, minI_factor=8., cl_factor=1.2, num_contours=10): """Calculate the contours for the plot base on the maximum intensity.""" maxI = data.max() minI = maxI / minI_factor return [minI * cl_factor ** x for x in range(num_contours)]
c214c37ba0c924051d6b410f7237262a81c3087e
36,512
import msgpack def test_default_func_nested_str(): """ packb() default function nested str """ ref = Custom() def default(obj): return str(obj) assert ormsgpack.packb({"a": ref}, default=default) == msgpack.packb( {"a": str(ref)} )
2b09bd8fd5a767f0360f18bf19e9a1e18f2fe635
36,513
def getActivityRelations(URI): """Returns a list of activity flows that are *input of* and *output of* the specified activity. .. :quickref: Flows list query; Get list of flows related to a specified activity. **Example request**: .. sourcecode:: http GET /v1/activities/get_rel...
71e976e5c5d3e2a51ba021dcbe5f5e0f4062da4c
36,514
def make_wsgi_app(root_factory, includeme, registry=None, **settings): """Create and return a WSGI application.""" configurator_cls = pyramid_config.Configurator # Initialise a ``Configurator`` and apply the package configuration. if registry: config = configurator_cls(registry=registry) ...
fd1c648dbed1d3ab4e059e29744e3addb1c4b581
36,515
def wrench2msg(wrench): """ Converts a 6x1 wrench vector into a geometry_msgs/Twist message :type twist: numpy.array :param twist: 6x1 wrench matrix :rtype: geometry_msgs.msg.Wrench :return The ROS Wrench message """ wrench2=np.reshape(wrench, (6,)) return Wrench(Vector3(wrench2...
191101a0a223533aa98a2b15fd8b6049d580dd31
36,516
def get_fuzz_target_weights(): """Get a list of fuzz target weights based on the current fuzzer.""" # No work to do if this isn't fuzz task. Weights are only required if a # fuzzer has not yet been selected. task_name = environment.get_value('TASK_NAME') if task_name != 'fuzz': return None job_type = e...
47f6fae591d91e4a9d90d10971be24f509f62ac0
36,517
def measure_network_density(streets_for_networkd_prj, gross_city_blocks_prj): """ Adds network density (m/ha.) onto a gdf of gross urban blocks Requires a gdf of streets to overlay with the gross city blocks. Streets that are within a gross urban blocks (i.e. do not coincide with its perimeter) hav...
02ac06ef5fcb10576f30e16fd37acc1246b16535
36,518
def param_size(model, *args, **kwargs): """Return size of model parameters.""" val = 4 * param_count(model, format=False) return format_value(val, *args, binary=True, **kwargs) if format else val
76e747f292d9cead36c990f6c2e5e05787c88710
36,519
def resolve_source(ctx_file): """Resolve best URL from acquisition.""" # get settings # read in context with open(ctx_file) as f: ctx = json.load(f) ''' settings_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'settings.json') with open(settings_file) as f: ...
233a60c4044d396fade5dd98495682a21adbce52
36,520
import logging from datetime import datetime import pytz def now(update: Update , context : CallbackContext, lang) -> int: """ Thhis functions implements the quick search, after checking if the campus is in the preferences of the user call the end_state function, otherwise return to the initial_state ...
70bed261b912067ebdb8889420b161c960aa4e33
36,521
def __analyze_function(input_str: str) -> str: """ transfer the syntax from python to the math -- adding auto "*" sign between signed variables :param input_str: ~ :return: the modified input str """ var_element = [] # the variables and element which used in the input_str. it contains all the e...
d731f74c46ff1c5ad478f2f60c04a642c248ec20
36,522
import json def jsonNodeToAvroType(x): """Convert a Python-encoded Avro type into a titus.datatype.AvroType. :type x: dicts, lists, strings, numbers, ``True``, ``False``, ``None`` :param x: Avro type in Python form :rtype: titus.datatype.AvroType :return: AvroType object """ return schem...
1f99b9ddc583c6206fa48eef5f8f181629a51511
36,523
def wordfreq_viz( word_cnts: pd.Series, nrows: int, plot_width: int, plot_height: int, wordfreq: WordFrequency, ) -> Figure: """ Visualize the word frequency bar chart """ col = word_cnts.name df = word_cnts.to_frame() df["pct"] = df[col] / nrows * 100 tooltips = [ ...
d1ead2591bd07256f6ff05d55595aa2666dcfb9b
36,524
import json def scatter(): """Fake endpoint.""" if 'override' in request.args: with open('{}/examples/overrides.json'.format(cwd), 'r') as jsonfile: return jsonfile.read() return json.dumps({ "bar1": [1, 2, 30, 12, 100], "bar2": rr_list(max_range=40), "bar3": rr...
bd45a84977e6ec2888f2d71d8e416c3c613e1e60
36,525
def default_crop() -> Crop: """ Set Tea as the default crop. """ try: # Check whether Tea Object exists in Crop Model crop = Crop.objects.get(name="Tea") except Crop.DoesNotExist: crop_data = {} crop_data["name"] = "Tea" crop_data["initial_moisture"] = "69" ...
8ea868dbb82767d3207a3a8283166a14edec3019
36,526
def get_item(id: str): """ get any specific item """ item = item_service.get_item(id) if not item: raise HTTPException(status_code=404, detail="Item not found.") return item
0274904ff1f4033dd9652693152e82a4d16d951e
36,527
from functools import reduce import operator def get_nested_value(the_map, dot_separated_key): """Give a nested dictionary map, get the value specified by a dot-separated key where dots denote an additional depth. Taken from stack overflow (http://stackoverflow.com/a/12414913). """ keys = dot_separate...
082d199adc51376592bd215ab32a309807e6089e
36,528
def cxSet(ind1, ind2): """Apply a crossover operation on input sets. The first child is the intersection of the two sets, the second child is the difference of the two sets. """ temp = set(ind1) # Used in order to keep type ind1 &= ind2 # Intersection (inplace) ind2 ^= temp # Symmetric Di...
8c64c6f9a219454288556109d1f99935937c40a3
36,530
def preprocess(self, im, allobj = None): """ Takes an image, return it as a numpy tensor that is readily to be fed into tfnet. If there is an accompanied annotation (allobj), meaning this preprocessing is serving the train process, then this image will be transformed with random noise to augment training data, us...
52972b7b4b75d74cc6d9730a5299cb9005fa4159
36,531