content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_key(h5, songidx=0): """ Get key from a HDF5 song file, by default the first song in it """ return h5.root.analysis.songs.cols.key[songidx]
94524a97ccd6013db5228a7d20bd2435b4e781b8
3,625,809
import typing def get_driver_for_browser( browser: str = "Chrome", ) -> typing.Union[webdriver.Firefox, webdriver.Chrome]: """get_driver_for_browser Args: browser: Browser Name required for Test. Support "Firefox" and "Chrome". Defaults to Chrome. Returns: Based on user-provide...
2bc12f2871174ab1a22b2c1523d628fb4676e72b
3,625,810
import requests import json def get_dev_vlans(devId): """Function takes input of devID to issue RESTUL call to HP IMC :param devId: requires devId as the only input parameter :return: list dictionaries of existing vlans on the devices. Device must be supported in HP IMC platform VLAN manager module ""...
6f05eb52c2ac5e272b2e1bc1227a110c57a83334
3,625,812
def read_create_database_object(path: str, filename: str, data_dict: dict): """ Returns a dataframe based on existing files or by creating a new one :param path: str :param filename: str :param data_dict: dict :return: df """ try: # check if an excel file is available df = pd.read_excel(path + ...
f867456b14f88621351339a774bb363feebad37e
3,625,813
import torch def reset_replicate(ridx, assign_obj, reg_out, max_steps=10, accept_tol=1e-3): """Re-initialize a given replicate by cooperative re-initialization (CoRe). On each iteration, we first find the best candidate from the set of all rk clusters to add to the current replicate. We then find the best of th...
a23b393f62b5dd3d95dcca2ca2ee450bb2f55075
3,625,814
import re def get_vulnerability(vulnerability_name_file, logger=structlog.get_logger()): """ Parse name of threat from given parameter(file) :param vulnerability_name_file: string to parse from :param logger: logger for the method :return: name of threat """ pattern = r'^\d{4}-\d{2}-\d{2}-...
68bcc0fa5d56d5682413c6dfd8592063652cd40e
3,625,815
def t2d(twt, data, td_depth, td_twt, target_depth): """ Convenience function for converting a well log from depth to time given time-depth pairs. This function both converts from time to depth and resamples the log data to a regular sampling rate in depth. """ f1 = interp1d(td_twt, td_depth, k...
501f42408a517ba39e726dee893dac8e69252505
3,625,816
from numpy import asarray, mean def r_precision(r): """Score is precision after all relevant documents have been retrieved Relevance is binary (nonzero is relevant). >>> r = [0, 0, 1] >>> r_precision(r) 0.33333333333333331 >>> r = [0, 1, 0] >>> r_precision(r) 0.5 >>> r = [1, 0, 0...
37467e1e02284e16a82a3dad6e0e5c14a0afcad3
3,625,817
def vector_to_symmetric_mat_4(vec): """Builds a symmetric 4x4 matrix using the elements specified in a vector. The elements are copied first to the first row, in order, then to the second row, starting from the element on the diagonal, and so on. """ A = np.zeros((4, 4)) # Fill the top-right tr...
8155c0a03617ce199f5de3148f9181592ed5f0ec
3,625,818
def list_tags_containing(s): """return list of tag records wherein tag's name contains substring s: str, substring to search for """ cue(records) req("TAG", lambda tag: s in tag) srt(CREATED) return val()
27dbb15ddedd145b181fd97327620dc0e4c5ad03
3,625,819
import functools def accepts(*types): """ Checks argument types. """ def decorator(f): assert len(types) == f.__code__.co_argcount @functools.wraps(f) def wrapper(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), "The input arg...
26dd256b466659400898972eea0a19391433be87
3,625,821
def is_void_pointer( type ): """returns True, if type represents C{void*}, False otherwise""" return is_same( type, cpptypes.pointer_t( cpptypes.void_t() ) )
504b81728b7e99311fcce1dcd83f0f326bdc3850
3,625,822
def pass_down(L,L1,map): """map maps L into L1.Populate L1 with values in L""" ## print len(L),len(L1),len(map),max(map) ## print sumsize(L) ## print sumsize(L1) for j in range(len(map)): if L[j] == -1: continue assert L1[map[j]] == -1 or L1[map[j]] == L[j], 'L...
6896de91a37a29d1f0e360f410d83065b7434fc7
3,625,823
def parse_correctness_stats(filename): """ Parse the results returned from get_Correctness.sh """ results = [] stats_file = open(filename, 'r') line = stats_file.readline() while not line.startswith('Reference:'): line = stats_file.readline() # Add Reference bases. result...
8ac0ff9307169726597bd6bce632560faaed6b3b
3,625,824
def are_equal_pyxb(a_pyxb, b_pyxb): """Normalize and compare PyXB objects for equality. Args: a_pyxb: PyXB object b_pyxb: PyXB object PyXB objects to compare for equality. Returns: bool: ``True`` if the PyXB objects are semantically equivalent. """ return are_equal_xml(a...
104bdf1e07aabfcf1e58c1c2c526a0868f501a62
3,625,825
def compute_misses(n_misses, n_subj): """ This function computes descriptive statistics of missed trials :param n_misses: Number of missed trials :param n_subj: Number of participants :return: n_misses_min: Minimum of misses n_misses_max: Maximum of misses n_misses_mean: Mean ...
ad342d4439486db27bbcc48f3f1dd9f601a23be6
3,625,826
def courses_(): """ Render form to register a student to a course, then save the IDs of the student and course to StudentCourses table :return: redirection to student homepage if successful, else html for course form """ return_403('lecturer_id') form = CourseForm() form.reg_num.data = Stude...
922a48eb5283e1c855186f8210b3dbd43e685a14
3,625,827
def three_phase_to_ground(distgrid,node_name,Df=False, zc=0+0j): """ Calculates the three-phase-grounded short circuit Parameters ---------- distgrid: mygrid.grid.DistGrid node_name: str The name of node fault fs: str Designates which phases participate in the short circuit Options: 'Iab', 'Iac', 'Ibc' a...
e0d1bf58bbaa63e840610f5150b0181c3735559d
3,625,828
def _get_sender(*sender_params, **kwargs): """ Utility function acting as a Sender factory - ensures senders don't get created twice of more for the same target server """ notify_func = kwargs['notify_func'] with _sender_instances_lock: existing_sender = _sender_instances.get(sender_para...
2411e35ca0d0399446beb3cbc1033882b3fd99f6
3,625,829
def whereSubseq(conditionFunc, seq, length, overlap=False): """ >>> a = [1, 3, 2, 3, 2] >>> b = [1, 2] >>> whereSubseq(lambda seq: seq == b, a, 2) [] >>> c = [3, 2] >>> whereSubseq(lambda seq: seq == c, a, 2) [1, 3] >>> whereSubseq(lambda seq: sum(seq) < 8, a, 3) [0] >>> whereSubseq(lambda seq: sum(seq) < 8,...
f25ded43f91b4ecc05fa28e81095996f4d036418
3,625,831
import math def bearing(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """Calculate bearing from lat1/lon2 to lat2/lon2 Arguments: lat1 {float} -- Start latitude lon1 {float} -- Start longitude lat2 {float} -- End latitude lon2 {float} -- End longitude Retu...
9148bc2726247cedf8a7de7279dac47316f2864f
3,625,832
import threading def get_thread_uuid(thread=None): """ Assigns and returns a UUID to our thread, since thread.ident can be recycled. The UUID is used in mapping child threads to their parent threads. """ if not thread: thread = threading.current_thread() ident = thread.ident try: ...
5d488dffab783fd42512ea0861efd14c8d47f20f
3,625,833
def juggle_axes(xs, ys, zs, zdir): """ Reorder coordinates so that 2D xs, ys can be plotted in the plane orthogonal to zdir. zdir is normally x, y or z. However, if zdir starts with a '-' it is interpreted as a compensation for rotate_axes. """ if zdir == 'x': return zs, xs, ys elif ...
5ca9cbc3557f8ceea92524d5ddc76da86e4da0eb
3,625,835
import torch def compute_loss_function(pz, z, pys, ys, ldj, args): """ Computes the cross entropy loss function while summing over batch dimension, not averaged! :param x_logit: shape: (batch_size, num_classes * num_channels, pixel_width, pixel_height), real valued logits :param x: shape (batchsize, n...
b310306c69051fc9b2f6664fd227f42fd39c9462
3,625,836
import re def _filterargs(source): """Juice from a source file the four args needed by decoder.""" argsregex = (r"}\('(.*)', *(\d+), *(\d+), *'(.*)'\." r"split\('\|'\), *(\d+), *(.*)\)\)") args = re.search(argsregex, source).groups() try: return args[0], args[3].split('|'), in...
9b719e156a7740ebce7683489d4182f937ca2de8
3,625,837
def get_title(reg_doc): """ Extract the title of the regulation. """ parent = reg_doc.xpath('//PART/HD')[0] title = parent.text return title
744759addf0cea3ba6cc3dadad05d535b66b20d6
3,625,838
import requests import json def requires_auth(permission=None): """ Decorator which checks if the user is logged in and has the requested permission, and give the user to the function """ # Define the decorator def decorator(f): # Define the decorated function def decorated(): ...
cd53c09c537920538737a8ab956ca08746e9f0e8
3,625,839
from pathlib import Path import re def load_dataset(img_path, txt_path, img_shape=(64, 64, 3), split_rate=0.1): """ Function: load_dataset Input: img_path: image directory path, txt_path: caption directory path, img_shape: image shape array Output: NumPy array """ print('Acquiring images & labels...'...
c16376d4b9bbef5a7daedb42e2ec4519ea7168c6
3,625,840
import random import requests def get_rising_submissions(subreddit): """Connects to the Reddit API and queries the top rising submission from the specified subreddit. Parameters ---------- subreddit : str The name of the subreddit without forward slashes. Returns ------- ...
115edc8986acdefbb232218d237bcba7320db9a0
3,625,841
def print_last_rows(): """ Get the last rows from the sheet. Return the last row in the worksheet which contains data. """ global last_row_index global worksheet last_row = None count=int(config['INTERFACE']['DisplayRows']) row_index_from = last_row_index - count if (last_row_inde...
d1288b9b33e300ce15620c05f9db3b841ef6c01a
3,625,842
def _OpenFileInSplitIfNeeded( filepath ): """Ensure that the supplied filepath is open in a visible window, opening a new split if required. Returns the buffer number of the file and an indication of whether or not a new split was opened. If the supplied filename is already open in a visible window, return jus...
4e6b842bb629679dfed73154c64c52346f26b071
3,625,843
import uuid def sqlalchemy_instance_model_extra(sqlalchemy_session_factory): """ Create session-wide database. """ sqlalchemy_session = sqlalchemy_session_factory() # Instances instance_1 = InstanceModel(id=str(uuid.uuid4()), class_path='tests.unit_tests.agents....
b99f65a36e7c87a765cd5533e0e940779d4794c3
3,625,845
from re import A from typing import Optional def index(_linked_list : LinkedList[A], idx : int) -> Optional[A]: """ The element at index idx """ assert idx >= 0 if _linked_list.content is None: return None head = _linked_list.content[0] tail = _linked_list.content[1] if idx == 0: ...
13090340b0e9a2dc64a80041546cffd4cfd397b5
3,625,846
def fetch(input_file: str): """Simulates a real API call.""" with open(input_file, 'r') as f: json = f.read() pb = json_format.Parse(json, gtfs_realtime_pb2.FeedMessage()) return pb.SerializeToString()
8270cacb189335dea805b1c6087dfa7b0b36bde0
3,625,847
def E_float2(y, _): """Numerically stable implementation of Muller's recurrence.""" return 8 - 15/y
4e8801465994afcb554e048897ec1ff903385bbe
3,625,849
import copy def perturbate_single(init_dict, label, value=None): """Perturbate a single parameter and fix all other parameters for estimation. We also set the bounds for the perturbed parameter to its default bounds. This increases the scope for perturbations. """ old_dict = copy.deepcopy(init_di...
3b181f60af23a63733edab539732820682b0592e
3,625,851
def compute_packet_csum(pkt): """Computes the checksum for the given GDB packet""" csum = 0 for x in pkt: csum += x csum = csum & 0xFF return csum
29eef2afd1b33ab80013ce7fcd46c3b11c9f639b
3,625,852
def new_headers() -> list: """Return list of new headers with clean names.""" return [ "date", "Rohs FB1", "Rohs FB2", "Rohs gesamt", "TS Rohschlamm", "Rohs TS Fracht", "Rohs oTS Fracht", "Faulschlamm Menge FB1", "Faulschlamm Menge FB2", ...
c81c38e8521f159f0bbf29b3a32adeaa13d4c38f
3,625,853
def state_to_dictionary(state_tuple): """Flatten model state into a dictionary with string keys.""" flattened = {} for state_number, state_value in enumerate(nest.flatten(state_tuple)): prefixed_state_name = "{}_{:02d}".format(feature_keys.State.STATE_PREFIX, state...
120625257d2f504d1b91e2a8e323a015d406ab4a
3,625,854
import torch def add_decomposed_rel_pos(attn, q, rel_pos_h, rel_pos_w, q_size, k_size): """ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 Args: ...
bba5d66dd346108dae992745447e9995335a875e
3,625,855
import copy def gcc(rdg, tau_threshold=2, **kwargs): """Surface detection from relative time delay obtained through generalized cross-correlation of each contiguous range lines Parameters ---------- rdg: 2d-array radargram Return ------ """ #--------------- # ...
ecaf1f234f64e71113c6ab0f0a7596d164e543a0
3,625,856
import hashlib import io def calc_file_md5(filepath, chunk_size=None): """ Calculate a file's md5 checksum. Use the specified chunk_size for IO or the default 256KB :param filepath: :param chunk_size: :return: """ if chunk_size is None: chunk_size = 256 * 1024 md5sum = has...
8f391ade85a5b69ca63d8adb3eff6ff6af7a08e3
3,625,857
def calculate_pct_poi_msgs(series): """calculates the percentage of a potential POI's total messages that are to or from a POI Args: series (pandas.core.series.Series): data series associated with a single POI Returns: [pandas.core.series.Series]: data series with the added POI mess...
857e23204e6eab5db36f23d583613dd19bc7ffd4
3,625,859
import re def version(): """ Get the Vagrant version. """ with settings(hide('running', 'warnings'), warn_only=True): res = local('vagrant --version', capture=True) if res.failed: return None line = res.splitlines()[-1] version = re.match(r'Vagrant (?:v(?:ersion )?)?(.*)', ...
1167d80b5bf1839c7e156596b6d11b3a6c85a93b
3,625,861
def aggrmem(mems): """Aggregates memory information returned from keymem(). If mems is a dict, uses its values() only. If mems is a list, uses it directly. Returns a single memory structure, formatted just like keymem(): - keys: list of key names - types: list of types, corresponding to ...
687f276c459f1ab5dc29cdc4af6efa698aed9a72
3,625,862
def create_ir(): """ Read out the ir to compare it before and after adding a flag from the pass to the sequence or work with its returnings. """ complete_ir = mktemp("-p", local.cwd) complete_ir = complete_ir.rstrip('\n') return complete_ir
572f2db3033f5db58d7b738615bffbf34b15d25d
3,625,863
def _dist_obs_oracle(oracle, query, trn_list): """A helper function calculating distances between a feature and frames in oracle.""" a = np.subtract(query, [oracle.f_array[t] for t in trn_list]) return (a * a).sum(axis=1)
affd188fccdaef543521c209386cda1da147347d
3,625,864
import requests from datetime import datetime def bond_zh_hs_cov_daily(symbol: str = "sz123111") -> pd.DataFrame: """ 新浪财经-债券-沪深可转债的历史行情数据, 大量抓取容易封 IP http://vip.stock.finance.sina.com.cn/mkt/#hskzz_z :param symbol: 沪深可转债代码; e.g., sh010107 :type symbol: str :return: 指定沪深可转债代码的日 K 线数据 :rtyp...
288113406d9d564ebaf68a75f4c46bb88ad9e3db
3,625,865
def predict_m(m, f, g, c0, alpha, B, pv, e, mu, R, eta): """ Calculate a predicted m given an input m. The idea is that we can iterate until they match. Inputs: parameters, m Outputs: predicted m predicted establishment fraction predicted mutation rate predicted mean time ...
234b153984f8a4cd6b03fa61c48bdab16411eca3
3,625,866
def msg_encoder( encoding=None ): """ 返回一个 with a pair of functions to encode/decode 消息 的命名元组。 如果 encoding 为None , 将返回 a pass through function 。 """ Codec = namedtuple( 'Codec', ['enc','dec'] ) if encoding in (None,False): l = lambda x : unicode(x) return Codec(l,l) else: ...
45b9351b6961aaaa035a3152c3ea1fc8d3e99a80
3,625,867
def is_dataframe_column_numeric(dataset : pd.DataFrame, column : str) -> bool: """ Return True if column in dataset is float or int (numeric), otherwise False Parameters ---------- dataset : pandas.DataFrame the dataframe that contains at least the column "column" column : str n...
86555bcc4245a8d02f8c89fbb487296e15e07b27
3,625,868
import struct def dylan_string(value): """Assuming value is a Dylan string, return it as a Python str""" if dylan_is_byte_string(value): return dylan_byte_string_data(value).decode('utf-8') elif dylan_is_unicode_string(value): data = dylan_unicode_string_data(value) (int_size, data_format) = target_...
1d4de456907245a34f4bd081aacbdb4a2bc7daed
3,625,869
def read_CUB(train_list_file, test_list_file): """ Reads and parses examples from CUB dataset """ img_height = 227 img_width = 227 num_val_img = 500 # you can change the number of validation images here train_img = [] train_label = [] test_img = [] test_label = [] train_img, tra...
06caf4b58ca108b29f87031c0b62072962009639
3,625,870
def mediatailor_configuration_ddb_items(region): """ Retrieve and format MediaTailor configuration for cache storage. """ items = [] for config in mediatailor_configurations(region): arn = config["PlaybackConfigurationArn"] service = "mediatailor-configuration" items.append(n...
cce7cf86ff04a811f7afd8500cc97f9d22146264
3,625,871
def parse_user_input(req): """Helper function to parse the information received by spark.""" http_method = None if req.method == "GET": fake_json = { "roomType": "direct", "created": "2016-12-02T23:27:30.199Z", "personId": "Y2lzY29zcGFyazovL3VzL1BFT1BMRS82NmVjMDkyNi0zO...
cb71c846e17045f955ba19ef2b64b458626af163
3,625,872
from typing import Tuple def network_to_bandwidth_range(network_type: NetworkType, network_speed: NetworkSpeed) -> Tuple[int, int]: """ Returns the (low, high) bandwidth range in kbps for the given network type """ network_bandwidth_map = { NetworkType.WIRED: {NetworkSpeed.FAST: (48000, 96000), Networ...
156e30f435f14fcd06e23d873fb3b2d338f72db7
3,625,874
def hex_to_uint(hex_string: str) -> Uint: """ Convert hex string to Uint. Parameters ---------- hex_string : The hexadecimal string to be converted to Uint. Returns ------- converted : `Uint` The unsigned integer obtained from the given hexadecimal string. """ r...
d9c66d44cc420678c5db90bdeb79e29c0077abe0
3,625,876
import struct def _read_int(f, b): """ Read an integer of a specified number of bytes from the filestream f """ if b == 1: return struct.unpack('<B', f.read(b))[0] elif b == 2: return struct.unpack('<H', f.read(b))[0] elif b == 4: return struct.unpack('<I', f.read(b))[0...
36bcc2ccd4edd61fd9c6a438c3a069e699b7b17a
3,625,877
def order_auditable_fields_at_end(field): """ Sort Condition for Auditable Fields :param field: :return: """ if field in AUDITABLE_FIELDS: return 2 if field == LAST_FIELD else 1 return 0
2f08b0b62081fd3ba323fe8a0e6a70aea832b534
3,625,878
def led_pwm_handler(frequency=None, duty_cycle=None): """ Change PWM frequency and/or duty cycle for LED. Optional arguments: - frequency (float): Change to frequency in Hz. - duty_cycle (float): Change to duty cycle in percent. """ ret = {} if frequency != None: led_pwm.C...
6bd092b38b34a587a1809b23223e9d21f20d8037
3,625,879
def get_module_list(username, bk_biz_id, kwargs=None): """ @summary: 查询模块 @param kwargs: @param username: 执行用户名 @param bk_biz_id: 业务id @return: [{'bk_module_id':'', 'bk_module_name':''}...] """ client = get_client_by_user(username) params = { "bk_biz_id": bk_biz_id, } ...
a7653de4f8bdb30c725962d0c57d7fa06300b480
3,625,880
def _visualize_feature_correlations(feature_correlations, figsize=(16,12), cmap="coolwarm", annot=True, fmt=".2f", linewidths=.05): """ Visualizes the feature correlations of a training dataset or feature group in the featurestore Args: :feature_correlations: th...
3a2a6c8783c543363bbfb13ddc4945c60654cf24
3,625,881
def select_modality(): """ modalityを選択する Returns: [str]]: selected_modality[0] ["CT", "XR", "ANGIO","PT"]のいずれかひとつ """ root = tk.Tk() root.title("Modalityを選択") root.geometry("400x300") M = tk.Label(text='') label1 = tk.Label(text="Modalityを選択") label1.pack(padx=5, pady=...
dcc00aea5fe23c34b9c2d9e02bb612eb7de37a79
3,625,883
def getMenuOption(): """Return the user's option""" return menu_option
d5af14bded520c180262e4381f05c506b376292b
3,625,885
def calc_transform(src, dst_crs=None, resolution=None, dimensions=None, src_bounds=None, dst_bounds=None, target_aligned_pixels=False): """Output dimensions and transform for a reprojection. Parameters ------------ src: rasterio.io.DatasetReader Data source. dst_crs: rast...
205615cef142c7d80d323e0ce5673d04506c247e
3,625,886
def get(remote_path, local_path=None): """ Download one or more files from a remote host. `~fabric.operations.get` returns an iterable containing the absolute paths to all files downloaded, which will be empty if ``local_path`` was a StringIO object (see below for more on using StringIO). This obje...
acd00ce91cb32a819767c9cc031106cd40e47f1e
3,625,888
def compare_equality(col_1, col_2): """ This function compare the equality of two columns and output an accuracy percentage """ return float(col_1.eq(col_2.values).mean())
adf6e6bb26988c7ee0211669881b2cd8331838da
3,625,889
def run_SEIR(E0, I0, R0, ds): """ Simulate SEIR model using forward euler integration. All states are defined as fractions of a population. All rates are discrete rates at the timescale of a signle simulation timestep. Parameters ---------- E0, I0, R0 : float Initial condition...
34b9775b31cc43604b593829251b210359e5676a
3,625,890
def segment_min(data, segment_ids, name=None): """ Segment min operator. This operator calculate the minimum elements of input `data` which with the same index in `segment_ids`. It computes a tensor such that $out_i = \\min_{j} data_{j}$ where min is over j such that `segment_ids[j] == i`. ...
4993d472fbf498c86126d3b5742a6029e3c1f691
3,625,891
def standardize(df, feature_list, exclude_list): """Fit and save StandardScaler and PCA """ # Exclude unnecessary columns df.drop(columns=exclude_list, inplace=True) # Fit and save standardizer standard_scaler = StandardScaler() # standard_scaler.fit(songs_df[feature_list]) standard_fea...
df3252f08df5167c94f9afc0288d28c7007c0426
3,625,892
def upgrade(options, version=None, repo_path=None): """Upgrade the database's current migration level. :param options: options dict :param version: version to upgrade (defaults to latest) :retval version number """ db_version(options, repo_path) # Ensure db is under migration control repo...
8cf0f27d884169ff44c2c90ba92d1fdaf6bc6650
3,625,894
def saveForwardState(old_s_tree, new_s_tree, s): """Saving the s_current as well as all its successors in the old_s_tree into the new_s_tree. Parameters ---------- old_s_tree : dict The old tree. new_s_tree : dict The new tree. s_current : :py:class:`ast_toolbox.mcts.AdaptiveStr...
1cf8aeac314c2f224a76d9c91c3bf1a8d54fd9df
3,625,895
def display_volume_group(): """ this function display the available physical volume :return: output variable that contains exit code and output string in tuple datatype """ cmd = "vgdisplay" output = sp.getstatusoutput(cmd) return output
6b26157369accffb02b9eb4d2944153384433214
3,625,896
def get_keyable_attributes(object_name=""): """ return an array of keyable attributes. :param object_name: :return: <list> keyable attributes found for this object. """ cnst_attr = Attributes(object_name, keyable=True) return cnst_attr.keyable.keys()
2fcc712f72836ba26cf6edf9f81204fec141d172
3,625,897
def find_pangrams(word_set, depth_max=6, current_words=None): """ Find minimal pangrams out of a set of words. Call with any iterable of words, and it returns a list of pangrams, if any, sorted by increasing letter count. You can set depth_max to control search depth if your word set calls for it. ...
1808f7e84136777d81f3dc0c18084e09efa520c1
3,625,898
from typing import Iterable def IncrementMetricsSpecsCounters(pipeline: beam.Pipeline, metrics_specs: Iterable[config.MetricsSpec]): """To track count of all metrics specs in TFMA.""" def _MakeAndIncrementCounters(_): for metrics_spec in metrics_specs: for metric in me...
f1c6e4cc60f89b8f48cd6df6f8688a924d444f5c
3,625,900
def make_random_circuit(n_rows, n_cols, depth): """Generate a random unparameterized circuit of fixed depth.""" return cirq.experiments.generate_boixo_2018_supremacy_circuits_v2_grid( n_rows=n_rows, n_cols=n_cols, cz_depth=depth - 2, # Account for beginning/ending Hadamard layers ...
79f3978cffcbdffe2d7e9cede7052fd4c513a2d2
3,625,901
def update_worker( *, db_session: Session = Depends(get_db), worker_id: int, worker_in: WorkerUpdate, ): """ Update a worker contact. """ worker = get(db_session=db_session, worker_id=worker_id) if not worker: raise HTTPException(status_code=204, detail="The worker with this ...
367ec0c6ee4047f1e1687150cbf834e872feb300
3,625,902
def save(filename, ax=None): """Save figure. Parameters ---------- filename : string The filepath into which the current figure will be saved. ax : `matplotlib.pyplot.Axes`, `None` by default The axis from which the plot to be saved derives. If left as `None`, `matplotlib.p...
c0ee2112d056270339eda604548be291b391464c
3,625,903
from typing import Callable from typing import Type def add_arg_type_after_self(t: Callable, arg_type: Type) -> Callable: """Add an argument with the given type to a callable type after 'self'.""" return Callable([t.arg_types[0], arg_type] + t.arg_types[1:], [t.arg_kinds[0], nodes.ARG_POS]...
aabd77204b7b7ab5849f69c07b545446f7893370
3,625,905
def extract_constraints(input_def): """ :param input_def: an input definition. :return: Constraint instances in respect to the constraint defined in the input definition. """ return [parse(c) for c in input_def.get(CONSTRAINT_CONST, [])]
c49944f559a28cc429f59bd925646748e661a24c
3,625,906
def load_italy_power_demand(split=None, return_X_y=False): """ Loads the ItalyPowerDemand time series classification problem and returns X and y Parameters ---------- split: None or str{"train", "test"}, optional (default=None) Whether to load the train or test partition of the problem....
2b37d4aa1035a936d5315308a262e40e41f677c7
3,625,907
def softmax(arr, axis=None): """softmax""" return np.exp(arr) / np.sum(np.exp(arr), axis=axis, keepdims=True)
202850edd408d835089601619be651ff978d052e
3,625,908
def get_target_project_select(site, project): """Return remote target project level selection HTML""" current_level = None try: rp = RemoteProject.objects.get( site__mode=SODAR_CONSTANTS['SITE_MODE_TARGET'], site=site, project_uuid=project.sodar_uuid, ) ...
0b15e03e6cdb907cc1eeca46eb64ef779c7386c0
3,625,909
def form_SelectWithOtherChoice(request): """ A basic select choice with input option """ schema = schemaish.Structure() schema.add('mySelect', schemaish.Integer()) options = [(1,'a'),(2,'b'),(3,'c')] form = formish.Form(schema, 'form') form['mySelect'].widget = formish.SelectWithOtherCh...
d55dc7f2ee30f50d86cdc3eb0f85c52cb33e5f51
3,625,910
def default_handler(request): """ The default handler gets invoked if no handler is set for a request type """ return alexa.respond(get_pool_weather_handler(request))
6616979f40106538b14d26cc82a63c827107b910
3,625,911
def check_ghi_limits_QCRad(ghi, solar_zenith, dni_extra, limits=None): """ Tests for physical limits on GHI using the QCRad criteria. Test passes if a value > lower bound and value < upper bound. Lower bounds are constant for all tests. Upper bounds are calculated as .. math:: ub = min + m...
f4c158a6358c618d291caa288ea36c0cf5ecc146
3,625,912
from typing import Callable def register(func: Callable, module: ModuleType, generate_lm=False) -> KscStub: """ Main Knossos entry point. The @register decorator transforms a TorchScript function into a KscAutogradFunction which implements the function and its derivatives. ``` @knosso...
555a70e36e5de0db4ad16c5da326dd03e6ceca0a
3,625,913
def endpoint_registry_contract(deploy_tester_contract): """Deployed SecretRegistry contract""" return deploy_tester_contract(CONTRACT_ENDPOINT_REGISTRY)
484bd3804b20a2d450149a52ca562f4e7284a599
3,625,915
def generate_input_with_unknown_words(file_path): """Reads the file with the given file_path. Replaces every first occurance of a (word, tag) pair with ("<UNK>", tag). Creates dictionary of all words encountered in following format: {(word, tag) : count}""" seen_tuples = [] label_matches = dict() file_lines = []...
21479c1953dc1779a28bc49a38de55c383513fbf
3,625,916
def get_file_at_commit(directory, commit, path): """ Get the contents of repository `path` at commit `commit` given the Git working directory `directory`. :param directory: Git working directory. :param commit: Commit ID :param path: In-repository path :return: File contents as bytes :r...
4abc4d352188ebf0a6cfac215fb506fa6e75017b
3,625,917
def three_body_force_en(env1, env2, d1, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """3-body single-element kernel between a force component and a local energy. Args: env1 (AtomicEnvironment): Local environment associated with the force component. env2 (AtomicEnvironment):...
8ca680d774ceb70de8923f53a88a4d9d87a91533
3,625,918
def include_silently(parser, token): """ Include template if it exists. If it doesn't exist then will not raise any exception. {% include_silently "mytemplate.html" %} """ try: tag_name, template_name = token.split_contents() except ValueError: raise template.TemplateSyntaxEr...
432024729e5e212e3bf9ce837f42f57e3ced6822
3,625,920
def parse_array(a, separator=' ', dtype=DEFAULT_FLOAT_DTYPE): """ Converts given string or array of strings to :class:`ndarray` class. Parameters ---------- a : unicode or array_like String or array of strings to convert. separator : unicode Separator to split the string with. ...
e8e737b4f224b16feb1037d1ad715f4db676a7d2
3,625,921
def dAdzmm_ron_s0_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled, gam_no_aeff): """ calculates the nonlinear operator for a given field u0 use: dA = dAdzmm(u0) """ M3 = uabs_nm2(u0,u0_conj,M2) M4 = dt*fftshift(ifft(fft(M3)*hf), axes = -1) # creates matrix M4 N = nonlin_ram_nm2(M1, Q, u0, M3...
e54853454952e2df7c71c51177da6ed9472d2e44
3,625,922
def run(): """Requirements for Task 1B""" # Build list of stations stations = build_station_list(False) #Find stations within the radius stations_in_radius = stations_within_radius(stations, (52.2053, 0.1218), 10) #function to print the station details in a parsable form def stations_in_r...
dbb4c45735de532d8ffe2429f8a7c8b4168db60f
3,625,923
def capsules_init(inputs, filter_size, stride, OUT, pose_shape, padding='VALID', add_reg=False, use_bias=True, name=None): """This constructs a primary capsule layer from a regular convolution layer.""" with tf.variable_scope(name): sum_list = [] num_filters = OUT * pose_shape[...
876e9d3daddde934c80fc5eebefe0ac85fc68517
3,625,924
def secure_erase_key( key_path ): """ 'Securely' erase a key at key_path. Fill it with random data first, flush the data, and then unlink it. Return True on success Return False on error. """ try: size = os.stat( key_path ).st_size except OSError, oe: log.error("Failed to stat %s"...
dde39b0814e0bf210d53bb1f07a3a16387b9ec92
3,625,925
def get_chamber_bills( session, chamber, page_size=None, page=None ) -> ChamberBillList: # noqa: E501 """get_chamber_bills Retrieving a list of bills # noqa: E501 :param session: Congress session :type session: str :param chamber: The chamber of Congress to query :type chamber: str :p...
e5ee8e215292790af0e0565148ff2b9c72712019
3,625,926
def from_nested_to_multi_index(X, instance_index=None, time_index=None): """Converts nested pandas DataFrame (with time series as pandas Series or NumPy array in cells) into multi-indexed pandas DataFrame. Can convert mixed nested and primitive DataFrame to multi-index DataFrame. Parameters ------...
b728854b5a04371e785d53419075575fd5d21370
3,625,927