content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def mul_param(arr_t, param_dtype): """ Returns a scaling transformation with a dynamic parameter (1 output, 1 input, 1 scalar): ``output = input * param``. """ return Transformation( [Parameter('output', Annotation(arr_t, 'o')), Parameter('input', Annotation(arr_t, 'i')), Par...
59a2959f514d1facf934d295b371a49cf99a9b7c
3,611,100
def plotApprox3D(kernel, parameter, lD, uD, name=None): """Draws a 2-dimensional kernel summation function of the form in between the squared domain from lD to uD Parameters ---------- kernel : IKernelBase object that implements the IKernelBase interface parameter : numpy array ...
0cd9c625cb454f2cd8cad72513cc31efec4c5981
3,611,101
from datetime import datetime def GetDateAndTime(): """Obtain date and time.""" return datetime.datetime.utcnow().isoformat() + "Z"
4261f2b20d38b483d9fa528bfd7d59bb01cc7e86
3,611,102
from sklearn.feature_selection import VarianceThreshold def get_columns_by_variance(X, y, threshold=0.0): """ Method to fetch columns based on threshold variance """ selector = VarianceThreshold(threshold).fit(X, y) return X.columns[selector.get_support()]
3b82a549b328d0a7b043b7fa982c9a7887f08519
3,611,103
from typing import Tuple from typing import List def split_outputs_per_head(outputs: Tuple[NDArray], heads: list) -> List[List[NDArray]]: """ Split outputs into outputs per head :param outputs: list of all outputs :param heads: list of all heads :return: list of outputs for each head """ h...
446a507a82602b932c257c05aff4128dc0158075
3,611,104
def get_neighbors(glycan, glycans, libr = None, graphs = None): """find (observed) biosynthetic precursors of a glycan\n | Arguments: | :- | glycan (string): glycan in IUPAC-condensed format | glycans (list): list of glycans in IUPAC-condensed format | libr (list): library of monosaccharides; if you have on...
c0e1e767a519c3a4959a986d787ee438d051cec9
3,611,105
from statistics import mean import torch def get_saliency_from_feat_list(feat_list, model, device, got_tensors=True, sal_type=1): """ Given a features list from one instance, get saliencies of this instance. Return list of saliencies. n_class...
8e27e2c349f563d89c1b67a3e804797395fc4c08
3,611,106
def vjp_maker_solve_Hz_source(Hz, info_dict, eps_vec, source, iterative=False, method=DEFAULT_SOLVER): """ Gives vjp for solve_Hz with respect to source """ A = make_A_Hz(info_dict, eps_vec) def vjp(v): return 1j * info_dict['omega'] * sparse_solve(A.T, v, iterative=iterative, method=method) ...
3d4971c70898c42670e7bc607d1f69d5cf77c83d
3,611,107
def _update_state_dict_according_to_operation(state_dict, operation, qubit_indexes, merge_strings=None): """ Updates the keys of the state_dict according to the operation being applied to the circuit Args: state_dict: A dictionary wi...
a85c74c70d205ef64e5b53fffeff596f4540fc26
3,611,108
def run_cmd(command, verbose=True, shell='/bin/bash'): """internal helper function to run shell commands and get output""" process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell) output = process.stdout.read().decode().strip().split('\n') if verbose: # return full outp...
a8eb07d1ac96037d06926e2ad5290b3c1847cafe
3,611,109
def _strip_version(version): """Strip trailing characters that aren't digits or '.' from version names. Some OS versions look like "9.0gm", which is not useful for select() statements. Thus, we strip the trailing "gm" part. Args: version: the version string Returns: The version with trailing letter...
483851b67347c2e23d1c625fc7bb925664f8e1e1
3,611,110
import os def list_from_env(key, default=""): """ Splits a string in the format "a,b,c,d,e,f" into ['a', 'b', 'c', 'd', 'e', 'f', ] """ try: val = os.environ.get(key, default) return val.split(',') except (KeyError, ValueError): return []
74bf225d69990f7c649f446293722955d75a4490
3,611,111
def calculate_head_direction_from_leds(positions, return_as_deg=False): """ Calculates head direction based on X and Y coordinates with two LEDs. Parameters ---------- positions : (N, 2) array_like N samples of observations, containing X and Y coordinates return_as_deg : bool R...
82b5e6e6b531b8c60af3f4f0f28edf6c918a56a3
3,611,112
import itertools def GridGraph(dim_list): """ Returns an n-dimensional grid graph. INPUT: - ``dim_list`` - a list of integers representing the number of nodes to extend in each dimension. PLOTTING: When plotting, this graph will use the default spring-layout algorithm, unless a po...
5f389833c006162ba7e9d5f2fa03b60e87045d69
3,611,113
def calculate_turn(state: str): """ Calculates which player's turn it is given board state. """ num_black = 0 num_white = 0 for cell in state: if cell in cellState.black_pieces: num_black += 1 elif cell in cellState.white_pieces: num_white += 1 return ...
00767d45ffdcd44de87f900f583e13e33df84080
3,611,114
from datetime import datetime def set_token_in_cookie(res): """Cookieへのトークンの保存 一度送られてOKだったトークン情報はCookieに入れてブラウザからのアクセスに対応する。 """ if request.endpoint == 'login': return res token = read_token() if token: max_age = 60 * 60 * 24 * 1 expires = int(datetime.now().timestamp(...
3b3d64a3119468f17b9b4864242b90a0f5217392
3,611,115
def PrayerTimes(method=CalculationMethod.MWL, asr=AsrMethod.STANDARD) -> GeneralMethod: """Generates an object that can be used to generate prayer times. Args: method (CalculationMethod): Method to use for general calculations. Defaults to CalculationMethod.MWL. asr (AsrMethod): Met...
e88e57a5dd1eba8d52318bd6c19a4caff373093a
3,611,116
import os def is_header_file(filename): """Return True if "filename" is a header file. >>> is_header_file('foo.c') False >>> is_header_file('foo.h') True >>> is_header_file('foo.h++') True """ extension = os.path.splitext(filename)[1] return extension.lower() in HEADER_EXTE...
bfcca42d76b05c871486a7179a8523541197e91b
3,611,117
def change_vpsa_cache(session, vpsa_id, quantity, return_type=None, **kwargs): """ Sets the quantity of additional cache groups for a VPSA. The quantity of cache groups that comes with the base engine is not included in this calculation. For example, if the engine comes with 2 cache groups, passin...
ec5dcf6ac108853c5f62b55cdaba5a9c2cc7dfc8
3,611,118
def parse_radius(radius): """ Method for parsing min/max radius argument :param radius: point radius :type: str, numeric, or None :returns: min or max radius :type: float or None """ err_msg = "Invalid radius: (%s) must be a positive float." % (radius) radius = str_to_float(radius, e...
fff4cd876a49b6120384fd4176d49b84f765d2ea
3,611,119
import json import base64 def export_package(): """Export package as JSON.""" package_doc = frappe.get_single("Package Publish Tool") package = [] for doctype in package_doc.package_details: filters = [] if doctype.get("filters_json"): filters = json.loads(doctype.get("filters_json")) docs = frappe.ge...
0d3445ee5aacbcc62058b5c9795c7c1633fd41d8
3,611,120
from typing import List def station_reindex(stations: List[dict]) -> List[dict]: """ reindexes the opnnem formatted facilities from a list to a dict keyed by duid """ stations_return = {} for station_code, station in stations.items(): facs = [] if "facilities" in sta...
d0c8fad568120b8b111a2153241a75bfff6675a5
3,611,121
def load_jcmod(eid, params): """ Basically trying to dynamically load the correct job controller (perform a 'from typejobcontroller import TypeJobController') """ # build with a known naming convention module_name = params['run']['scheduler'] + "jobcontroller" class_name_cc = param...
ff7cc4f1e3ad04704e4edec4ef6aaaab8acfca09
3,611,122
def config_entry_fixture(hass, config): """Define a config entry fixture.""" entry = MockConfigEntry(domain=DOMAIN, data=config) entry.add_to_hass(hass) return entry
d7174ca251821e4b281db23540d28ce0bb228b09
3,611,123
from DBReleaseHandler import DBReleaseHandler def processDBRelease(inputFiles, inFilesGuids, realDatasetsIn, dispatchDblock, dispatchDBlockToken, prodDBlockToken, workdir, jobPars): """ remove any DBRelease files from the input file list and send back instruction to move the created DBRelease file to job dir """ ...
838fb977b2380463002f59e725d00fcbd8ec2af4
3,611,124
from typing import Dict from typing import Any def radar_analysis_status_command(client: PolarisClient, args: Dict[str, Any]): """ Check the Radar Event for updates. :type client: ``PolarisClient`` :param client: Rubrik Polaris client to use :type args: ``dict`` :param args: arguments obtain...
7eca1158e59c37d995b54b901a1c8391df7e31b1
3,611,125
import json def create_vote(user_id: str) -> FlexSendMessage: """投票創建確認 Args: user_id (str): 使用者 ID Returns: FlexSendMessage: 投票創建確認 """ with open("line/model/create_vote.json") as json_file: contents = json.load(json_file) contents["footer"]["contents"][0]["action"][...
1691cbcf6720bd725c787b306911bd0015530f15
3,611,126
def followRedirects(categories): """If a category is a redirect, replace the category with the target.""" result = [] for cat in categories: categoryPage = pywikibot.Page(pywikibot.Site(u'commons', u'commons'), cat, ns=14) if categoryPage.isCategoryRedir...
ea78ab12b5ab7322f3f04444c1e2f551e8cd1746
3,611,127
def ncdf(x): """Cumulative normal dist'n.""" global rt2 return 1.0 - 0.5*erfcc(x/rt2)
a411624d85db6edcf507c41a5bc769f03240bba1
3,611,128
from unittest.mock import patch import builtins def patch_input(**kwargs): """A helper to provide mocked cm patching input function which was renamed in PY3""" return patch.object(builtins, 'input', **kwargs)
1f70b4b3507f914c5546fa823d6de084b3be8870
3,611,129
def hash_1(): """ Test hash 1""" return "73bef2ac39be261ae9a06076302c1d0af982e0560e88ac168980fab6ea5dd9c4"
e6aef2a19657e727778ac117ec75d75cf5c4944a
3,611,130
def is_sequence(obj) -> bool: """ Return True if obj is a generic sequence type, like a list or tuple. """ return isinstance(obj, (list, tuple, set, DictKeySet, DictValueSet))
7a65363e2c6933ccd88005a291fc75d4f2947021
3,611,131
def adjust_learning_rate(optimizer, epoch, lr, epochs_for_decay): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" new_lr = lr * (0.1 ** (epoch // epochs_for_decay)) print('Changing learning rate in ', new_lr) for param_group in optimizer.param_groups: param_group['lr...
b19195f2cdf1fc30d63442770aeb0a9dc867b99e
3,611,132
def _RGB2sRGB(RGB): """ Convert the 24-bits Adobe RGB color to the standard RGB color defined in Web Content Accessibility Guidelines (WCAG) 2.0 see https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef for more references :param RGB: The input RGB color or colors shape== ... x 3 (R,...
c2c5c25d64cc7b0cb9b004846b72aecada7c5d85
3,611,133
def find_meeting_point(river_1, river_2): """ Find the first meeting point of two rivers """ meeting_points = [] while not meeting_points: points_1 = [] points_2 = [] for _ in range(10000): points_1.append(next(river_1)) points_2.append(next(river_2)) ...
22763dc4d88e7261eb3f67f910379a0791bf9fc4
3,611,134
def _is_physical_entity(pe): """Return True if the element is a physical entity""" val = isinstance(pe, _bp('PhysicalEntity')) or \ isinstance(pe, _bpimpl('PhysicalEntity')) return val
e156efb1336d3ec31290a66e49da8f542b3a5c46
3,611,135
from typing import Callable def time_function(func: Callable) -> Callable: """ Decorator/wrapper function. Make a function print how long it took to call whenever it is called. Parameter: function func: any arbitrary function Returns: function timed_func: same function, but now ...
a34f2ef91530b4f9c6811cda8b456baa887177cd
3,611,136
def paragraphs(text): """ Add line breaks to text to implement line breaks """ if isinstance(text, SafeData): return text text = escape(text) return mark_safe('<p class="no-margin">{}</p>'.format(text.replace('\n', '</p>\n<p class="no-margin">')))
66311b52330fd0bbbaedcb004be5dc6fc22eec92
3,611,137
def countChrom(ls_chrom): """ Counts how often the different chromosomes are present in the list and returns this as a list. """ count = [] for i in LS_CHECK: count.append(ls_chrom.count(i)) return count
85b3562ee42aaabab8361dad2899e49db709d6be
3,611,138
from datetime import datetime def tacacs_auth_lockout(username: str, report_failure: bool = False) -> bool: """ Upon a TACACS authentication failure, as seen by Netmiko, update a dict in Redis that holds failures for this user. And if we've exceeded 10 failures in 10 minutes, lock this user out of the API...
258e9d97dba76953dfbe104618083f9614c3b059
3,611,139
from typing import Optional from typing import Dict from typing import Union from typing import List from typing import Tuple from typing import Sequence def fold(x: VariableLike, dim: str, sizes: Optional[Dict[str, int]] = None, dims: Optional[Union[List[str], Tuple[str, ...]]] = None, ...
6002cc2104dd74287062fa4a18e3ee60eb1a5061
3,611,140
def _l1m_objective(a,X,*args): """ Optimization objective for l1median """ return(np.sum(np.apply_along_axis(_euclidnorm,1,_diffmat_objective(a,X))))
6275dce7ac6a3810149ee2ef13346155fe50aa87
3,611,141
def _new_x_concatenated_sequence( duration=1.0, concatenation_order=None, pre_post_rotation=False, **kwargs ): """ Creates X-Concatenated Dynamic Decoupling Sequence. Concatenation of base sequence C(\tau/2)XC(\tau/2)X Parameters ---------- duration : float, optional defaults to Non...
77a4d639acd74e2e93ad956cb2afe4a03745821a
3,611,142
def addData2matrix(X_train: modALinput, X_new, X_idx, symmetrical) -> modALinput: """ Adds the new data to a sparse matrix Args: X_train: Training data in sparse format matrix X_new: Value of new data to be added to training set X_idx: Set of form (sparse_coordinate, row_idx, col_id...
6782a3d678ea6c752a128428a16def4300ff80a8
3,611,143
def load_people(path): """Loads a list of people from the path and assigns each default score.""" people = [] with open(path, 'r') as people_file: for line in people_file.readlines(): people.append(Person(line.strip())) return people
e48050594432ad1567633a81627469f092b02b38
3,611,144
import aiohttp async def test_set_audio(aresponses: ResponsesMockServer) -> None: """Test setting display properties.""" async def response_handler(request: aiohttp.ClientResponse) -> Response: """Response handler for this test.""" data = await request.json() assert data == { ...
ca7d0b5dee9fa366c4d51fc01f212984eff94e9f
3,611,145
import io def pathway_genes(pathway: str) -> set: """Returns genes for a given pathway in KEGG""" kgml = _get(pathway, form='kgml').text # Wrap text in a file handle for KGML parser f = io.StringIO(kgml) k = KGML_parser.read(f) genes = set() for gene in k.genes: for x in gene.nam...
2357ff501998711984362214183a4777e0afb806
3,611,146
def get_availability_domains(identity_client, compartment_id): """ Gets the list of AvailabilityDomain for the specified compartment. :param network_client: OCI VirtualNetworkClient client :type network_client: oci.core.VirtualNetworkClient :param compartment_id: The OCID of the compartment to che...
ac13aa820309fbc5a627d87c778b6e004d7def73
3,611,147
import os def get_dca_output_file_path(output_dir, msa_file_name, prefix='', postfix=''): """Locates the file path to which DCA ouput can be written. Parameters ----------- output_dir : str DCA computation related output directory. msa_file_name : str Name of the a...
0c2fce86749cc401c2bcf5673ff9a168e673579f
3,611,148
def method_authorizations(*scopes: str) -> dict: """ Return method security. Contains only one OAuth2 security. :param scopes: All scope names that should be available (as string). """ return {"security": [{"oauth2": scopes}]}
4bf2f93715b9798ef20119288178d69b3907e85e
3,611,149
def glGetProgramiv( baseOperation, program, pname, params=None ): """Will automatically allocate params if not provided""" if params is None: params = arrays.GLintArray.zeros( (1,)) baseOperation( program, pname, params ) return params[0] else: baseOperation( program,pname, p...
71c7a992e8eb84485c394c77caf29af780dc6d20
3,611,150
def get_aoi_dir(aoi_name): """get the result dir associated with the aoi name""" aoi_dir = result_dir.joinpath(aoi_name) aoi_dir.mkdir(exist_ok=True) return aoi_dir
21da45b9bf6dcabbae487a94127675dc8f43e311
3,611,151
def dhcpcap_maker(request): """ return a function which creates initialized dhcpcap instances. """ def maker(): dhcpcap = DHCPCAP(client_mac="00:01:02:03:04:05", iface='eth0', xid=900000000) return dhcpcap return maker
ca1e353cde2e684bf3151125ff188118fc0c1491
3,611,152
def validate(config_dir): """ Reads config.json in the config_dir and prepopulates with default values. Ensures that all configured values are of the appropriate types. Returns (config, message to report if error). Returns None if something is wrong with the config it read. """ config = rea...
496e7ad8b2b7c64ecf3d7b68b521ce048c3cb2f1
3,611,153
def _split(X: TData) -> XData: """Split dict into elements.""" Xcon = _make_mask(X["con"], X["con_mask"]) if "con" in X else None Xcat = _make_mask(X["cat"], X["cat_mask"]) if "cat" in X else None return XData(Xcon, Xcat, X["indices"], X["coords"])
459f0477776e343f59c0b45f5c7030f3facc5e31
3,611,154
def get_address(address): """ Request information about a bitcoin address :param str address: an address hash/id :return: an instance of Address class """ resource = f'address/{address}' response = util.call_api(resource) return Address(response)
dd6a1961954bccebcbb9b74d07d18973345ee4df
3,611,155
def loadRectilinearGrid(filename): """Load a ``vtkRectilinearGrid`` object from file.""" reader = vtk.vtkRectilinearGridReader() reader.SetFileName(filename) reader.Update() return reader.GetOutput()
48aaed3d50d24ee83450831cf9047bb89ca592be
3,611,156
def update_rule(request): """ Tags: rules --- Update a rule given its UUID The expected request body is the same as for the `add_rule` endpoint. The difference is that none of the parameters are required. Only the specified parameters will be updated, leaving the rest unchanged. READ p...
02aa4beb8234231a46242a07e0ffe6357c2ec966
3,611,157
def process_properties(adapter, params): """ Process the properties specified in the 'properties' module parameter, and return a dictionary (update_props) that contains the properties that can be updated. The input property values are compared with the existing resource property values and the retur...
5d802fa8f53a094ffad2d1226761c65a33b5404f
3,611,158
def horizontal_dominoes_removed(r, s): """ Returns all partitions obtained from a rectangle of width s and height r by removing horizontal dominoes. EXAMPLES:: sage: sage.combinat.crystals.kirillov_reshetikhin.horizontal_dominoes_removed(2,2) [[], [2], [2, 2]] sage: sage.combin...
e410c4c77399db5264fe464e98419eaf47a6dc89
3,611,159
def load_entities(geobase_file): """Returns list of GeoEntity tuples for geobase entities.""" # Identifier string to GeoEntity tuple. identifiers_to_entities = {} with gfile.GFile(geobase_file, "r") as inputfile: for line in inputfile: # line = line.decode("latin1") if line.startswith("state"):...
edf78d592893050a070e3662935c2ab7efe8cccc
3,611,160
from datetime import datetime def kurtosis(pos: TimeSeriesInterface, lookback: str, date: datetime = None, **kwargs) -> float: """ Compute the kurtosis of the returns distribution from a TimeSeries object :param pos: TimeSeries Object (Portfolio, Position, Pandas DataFrame/Series :param lookback: Str...
775d730a457fcfbda9f31f9648b3906cee7edc56
3,611,161
def session(dsn='postgres:///b2', echo=False): """SQLAlchemy session""" engine = create_engine(dsn, echo=echo) Session = sessionmaker(bind=engine) return Session()
09bbfb11e880345f435781ff261370f7d533df39
3,611,162
def _variable_on_cpu(name, shape, initializer, use_fp16=False): """Helper to create a Variable stored on CPU memory. Args: name: name of the variable shape: list of ints initializer: initializer for Variable Returns: Variable Tensor """ with tf.device('/cpu:0'): dtype = tf.float16 if use_f...
554e00c66d0854f04e82f302df9c3bfb9fa688dc
3,611,163
def get_db_uri(): """ Get the current DB URI. :return: The DB URI. """ global _db_uri if _db_uri is not None: return _db_uri elif env.get_env(_DB_URI_ENV_VAR) is not None: return env.get_env(_DB_URI_ENV_VAR) else: return DEFAULT_SUBMARINE_JDBC_URL
45bceb06d8d6fe7208b8476ddadbfec5e6da1282
3,611,164
import time import pickle def pickle_loader(pkl_path): """Read from a pkl file.""" tic = time.time() logger.debug('loading features from %s', pkl_path) with open(pkl_path, 'rb') as f: data = pickle.load(f, encoding='latin1') logger.debug('done in {:.3f}s'.format(time.time() - tic)) return data
92942b32be6f5a1a959aec78794fefbe266239b8
3,611,165
import io import PIL def _open_file(full_path: str) -> tuple: """Read an image path, load the image and encoded in bytes""" with tf.io.gfile.GFile(full_path, 'rb') as fid: encoded_file = fid.read() encoded_file_io = io.BytesIO(encoded_file) image = PIL.Image.open(encoded_file_io) return im...
7f1e60a9973a4f7184189e5cf0453efc884fd865
3,611,166
def full2sparse_clipped(vec, topn, eps=1e-9): """Like :func:`~gensim.matutils.full2sparse`, but only return the `topn` elements of the greatest magnitude (abs). Parameters ---------- vec : numpy.ndarray Input dense vector topn : int Number of greatest (abs) elements that will be pre...
a5b2c526839e6cde73ad2380cf9bef438664e2eb
3,611,167
def lfsfiles(context, mapping): """List of strings. All files modified, added, or removed by this changeset.""" ctx = context.resource(mapping, b'ctx') pointers = wrapper.pointersfromctx(ctx, removed=True) # {path: pointer} files = sorted(pointers.keys()) def pointer(v): # In the file...
4526fa92f686c1af7b1563f38e1e85aa09df9696
3,611,168
import copy def _open(input_op_node: cc_dag.OpNode, output_name: str, target_party: int): """ Define Open operation. :param input_op_node: Parent node for the node returned by this method. :param output_name: Name of returned Open node. :param target_party: ID of party that will receive outputs o...
199cb47822e6891b1421baa20d93d779cdf55d9e
3,611,169
def loss(z, y, loss_function, isbinary=None): """ Calculates the loss given the loss function used. Parameters ---------- z : ndarray Array containing logits. y : ndArray Array containing labels. loss_function : str Name of loss function. isbinary : bool ...
ee92e1a9e426155aba8f36d37f1149c08730902d
3,611,170
def file_to_save(_x): """Definition of argument type for learner save data file, a string with a pathname of a file.""" return _x
e67821fa7a273d41f5a69c0577b3e9ace0955e20
3,611,171
def mmd_x_xsqred(x, y): """ Maximum mean discrepancy with squared kernel This will distinguish mean and variance see https://stats.stackexchange.com/questions/276497/maximum-mean-discrepancy-distance-distribution Parameters ---------- x : list of ints y : list of ints Returns ---...
be182455ee471b085acdf3a57de87f383d5f38a1
3,611,172
def deltas_to_dfs(deltas): """Transform deltas to displacement fields. Parameters ---------- deltas : np.ndarray The array with deltas. Has to have shape (n_dfs, 2, height, width). Returns ------- dfs : list The resulting displacement fields. """ dfs = [Displacement...
3b6600539994744da7ac818240fb1afd05ace09b
3,611,173
import os import logging def find_mask_to_sol_exe(): """find the pf_mask_to_pfsol or mask-to-pfsol utility on the system Returns ------- pf_mask_to_sol_path : tuple tuple of (path to executable, depth/z-bottom flag for argument) or None if no executable was found """ pf_mask_to_sol_pa...
201ca26c49b4afff2bc79b70216de407876d753a
3,611,174
from typing import Optional from typing import List import os def show_indices( indices: list, interval: str = "1d", start_date: int = None, end_date: int = None, column: str = "Adj Close", returns: bool = False, store: bool = False, raw: bool = False, external_axes: Optional[List[...
7ca5bbefb0de604f27e65dba6f894129ec7e2e9b
3,611,175
def vector_tile(vec, reps: int): """Turn a 1d vector into a 2d matrix by tiling on the leading dimension. Casadi represents vectors as D x 1 array, so needs to be treated differently. For casadi: [D x 1 ] vector -> [N x D] array For numpy/jax: [D, ] vector -> [N x D] array """ if lnp.get_back...
495afeacfff013f9bce361015053f03e5f19089d
3,611,176
import requests import json def list_tags(image, cli=False): """ Return a list of tags of a given Docker Hub image. Example: In : list_tags('google/debian') Out: ['jessie', 'wheezy'] In : list_tags('python') Out: ['31', 'rawhide', '30', '29', 'latest' ...] """ if cli: prin...
aefa058e32b72911a0b97619edeee119914440b7
3,611,177
from pathlib import Path from typing import Tuple from typing import Optional import os import subprocess def get_package(package_file: Path) -> Tuple[Path, Optional[Path], Optional[int]]: """Unpack unprocessed coverage data files from package_file to a temporary directory and return directory name, build dir...
178fe958d6f83a642bee29138723e0357dab90cc
3,611,178
import warnings from datetime import datetime from pathlib import Path def mt_metrics( stack, out_prefix, metrics, rescale_to_datatype, to_power, outlier_removal, datelist ): """ :param stack: :param out_prefix: :param metrics: :param rescale_to_datatype: :param to_power: ...
26063461aaa0c824330ae5aba6378b55e4c5de37
3,611,179
import os import sys import traceback import platform def show_last_exception(): """Display the last Python exception.""" def _show_code_line(fname, idx): fname = os.path.expanduser(os.path.expandvars(fname)) with open(fname, "r") as f: __data = f.readlines() return __data...
1b9e73bf241eacca879b521c6ce3563393ca9fa7
3,611,180
def create_blank(width, height, rgb_color=(0, 0, 0)): """Create new image(numpy array) filled with certain color in RGB ref: https://stackoverflow.com/questions/4337902/how-to-fill-opencv-image-with-one-solid-color author: Kimmo usage: import cv2 import numpy as np ...
50655136d34ccaea35cda35a2b28324dcad9a9d6
3,611,181
def mutate(proposed_graphs, graphs, part_importance_estimator=None, feasibility_estimator=None): """mutate.""" mutated_proposed_graphs = [] mutated_proposed_graphs += perturb( proposed_graphs, NeighborhoodNodeLabelMutation(n_nodes=None).fit(graphs), part_importance_estimator, ...
1e929b35f862cc489f97f14685360f89d2806194
3,611,182
def get_slurm_script_gpu(output_dir, command): """Returns contents of SLURM script for a gpu job.""" return """#!/bin/bash #SBATCH -N 1 #SBATCH --ntasks-per-node=1 #SBATCH --ntasks-per-socket=1 #SBATCH --gres=gpu:tesla_p100:1 #SBATCH --cpus-per-task=4 #SBATCH --mem=64000 #SBATCH --output={}/slurm_%j.out #SBATCH...
3f9d587c2943cd821d000fab419d3591440c4d3d
3,611,183
def tensor_extend(x, y): """Extending tensor with new_slice. new_slice.shape should be same as tensor.shape[1:] Args: x (Tensor): tensor to be extended y (Tensor): the tensor which will be appended to `x` Returns: the extended tensor. Its shape is (x.shape[0]+1, x.shape[1:]) ...
df0a3c3ab9aa636621783907e3ef1bdccf3fd79a
3,611,184
import os def github_token(): """Return the Github token to use for real tests.""" if not 'GH_TOKEN' in os.environ: raise RuntimeError('GH_TOKEN must be defined for this test') return os.environ['GH_TOKEN']
55ee21f019601e0bb9ac7a890cfcf37fdc932ffd
3,611,185
def boxSnap(n, shape, usegrid=False, randomness=0.): """ Initialize snap shot with n randomly placed gas particles inside a box. if usegrid=True, a grid is used to seed the particle positions (see grid()) n can then be [nx, ny, nz, ...] to specify the resolution along each dimension. Otherwise...
cc430d7d110b7efbb1a9bc735a77b749205811a3
3,611,186
from typing import OrderedDict def extract_i3_detector_status(frame): """Extract (most, maybe?) items found in a I3Detector frame. Parameters ---------- frame : icecube.icetray.I3Frame Must contain key "I3DetectorStatus", whose value is an ``icecube.dataclasses.I3DetectorStatus`` obje...
a31351de3a2fffa5d93b69533ac41875675024ed
3,611,187
def strobe_color(brightness=100): """ Rapid flashing colors. :param int brightness: The brightness of the transition. :returns: An infinite Flow consisting of 6 transitions. :rtype: Flow """ return Flow( count=0, action=Action.recover, transitions=transitions.strobe_color(brightnes...
e666e53713a3a6e32503e00eb9f0ffa9500399d8
3,611,188
import uuid import six def create_uuid3(namespace, name): """ Return new UUID based on a hash of a UUID namespace and a string. :param namespace: The namespace :param name: The string :type namespace: uuid.UUID :type name: six.text :return: :rtype: uuid.UUID """ return uuid.uui...
1a6898f80849a11f643a58798adc8a165e3b0e8d
3,611,189
def download_video(data: DownloadData, use_temp: bool=False): """ Downloads a video with data. Returns destination """ if use_temp: dest = None else: dest = data['video_path'] logger.debug(f'downloading "{data["url"]}" to "{dest}"') obj = SmartDL( data['...
116e1bd4cc410229da8cd79c47408418218e771e
3,611,190
def build_roi_extractor(cfg): """Build RoI feature extractor.""" if cfg['type'] in NECKS._module_dict.keys(): return ROI_EXTRACTORS.build(cfg) else: return MMDET_ROI_EXTRACTORS.build(cfg)
9ad5d7edc1395cc702beb00091ae8aec782ed716
3,611,191
import time def deterministic(pred, obs, forecast_type="continuous", aggregating_dim=None, skip_na=True, thr=0.000001): """Compute deterministic skill metrics.""" # Check if not isinstance(forecast_type, str): raise TypeErr...
b95c85624429f60990e784d8656a0214f8c0c501
3,611,192
def asy_add_ucb_for_boca(mfgp, fidel_to_opt, anc_data): """ Asynchronous Add UCB. """ return _add_ucb_for_boca(mfgp, fidel_to_opt, None, anc_data)
def0e7dcf50ac660573e2645afb17490711b43e3
3,611,193
def patch_twitter_add_list_users(value): """Return a function decorator which patches the TwitterClient.add_users_to_list method.""" return patch_twitter_client_method("add_users_to_list", value)
fab0da1bc2e682d3e7bb3a3c6b031b255983de21
3,611,194
def sbol_ribozyme (ax, type, num, start, end, prev_end, scale, linewidth, opts): """ Built-in SBOL ribozyme renderer. """ return stick_figure(ax,type,num,start,end,prev_end,scale,linewidth,opts)
b391524534ee7ced11cf536090a8f88cadc5eefa
3,611,195
import urllib.parse import httplib2 import os, os.path import json import xml.etree.ElementTree as etree def get_geojson(params): """ This function accepts a dictionary of parameters and returns a GeoJSON representation of the requested layer. This takes a format similar to the following example: { ...
1cad40a4c28f1ff3de1df75b04d626b5bfad1471
3,611,196
def buildTypeTree(cls:type) -> dict: """ Return a tree of subclasses of a class Arguments: cls (type): Class from which to return descendants Returns: dict: Dict of all subclasses Example: buildTypeTree(MainClass) returns: { MainClass.SubClass1: { MainClass.SubClass1.SubClass11: {}, MainC...
7937df4d9643f20c3e5379f84ef36a28226707ba
3,611,197
def add_at(a, indices, b): """Add the elements of `b` to the locations in `a` specified by `indices`. Allows adding to an element of `a` repeatedly. """ value = a.array.copy() np_add_at(value, indices, b.array) local_gradients = [ (a, lambda path_value: path_value), (b, lambda pa...
46246ddca7e9ed2b6c7d7d5d1c5d4d1550c8c13d
3,611,198
import socket import logging import os import errno def create_connection(host, port=9000, timeout=None, connect_timeout=None, **options): """ connect to ws://host:port and return websocket object. Connect to ws://host:port and return the WebSocket object. Passing optional timeout parameter will set ...
47edc5c611e838e7a518ba37f0c34431ff806b82
3,611,199