content
stringlengths
22
815k
id
int64
0
4.91M
def load_bbbp_dataset(data_path, task_names=None, featurizer=None): """Load bbbp dataset ,process the classification labels and the input information. Description: The data file contains a csv table, in which columns below are used: Num:number name:Nam...
5,344,700
def execute(connection, cmdline, **kwargs): """generic function to execute command for device | Parameters: | connection (Adaptor): connection of device | cmdline (str): command line | kwargs (dict): additional keyword arguments for command line execution | Returns: | str: ou...
5,344,701
def json_to_numpy_mask(shapes, width, height): """Converts JSON labels with pixel classifications into NumPy arrays""" img = Image.new("L", (width, height), 0) for shape in shapes: if shape["label"] == "barrel": barrel_lst = [tuple(i) for i in shape["points"]] ImageDraw.Draw(...
5,344,702
def create_record(input_path, wdl_location, non_static_inputs, assay_name): """Create sample records for mongo insert Arguments: input_path {[type]} -- [description] wdl_location {[type]} -- [description] non_static_inputs {[type]} -- [description] assay_name {[type]} -- [descri...
5,344,703
def test_p2ps_wildcard_p2ps(dev): """P2PS wildcard SD Probe Request/Response""" p2ps_wildcard = "org.wi-fi.wfds" adv_id = p2ps_advertise(r_dev=dev[0], r_role='1', svc_name='org.foo.service', srv_info='I can do stuff') adv_id2 = p2ps_advertise(r_de...
5,344,704
def _format_call(value: ast3.Call, context: types.Context) -> typing.Text: """Format a function call like 'print(a*b, foo=x)'""" try: return _format_call_horizontal(value, context) except errors.NotPossible: return _format_call_vertical(value, context)
5,344,705
def get_tags(repo_dir): """ _get_tags_ returns a list of tags for the given repo, ordered as newest first """ repo = git.Repo(repo_dir) tags_with_date = { tag.name: tag.commit.committed_date for tag in repo.tags } return sorted(tags_with_date, key=tags_with_date.get...
5,344,706
def readh5(filename, GroupName=None): """ Read the HDF5 file 'filename' into a class. Groups within the hdf5 file are by default loaded as sub classes, unless they include a _read_as attribute (see sharpy.postproc.savedata). In this case, group can be loaded as classes, dictionaries, lists or tuples...
5,344,707
def test_full_x_remove_z_default_4(init_full_x_remove_z_default_4, create_db_instance): """Test if full x removed z (default 4) is properly initialized and can fetch from 1 of its 3 parents """ experiment = EVCBuilder().build_view_from({'name': 'full_x_remove_z_default_4'}) pairs = get_name_value_p...
5,344,708
def calc_E_E_hs_d_t(W_dash_k_d_t, W_dash_s_d_t, W_dash_w_d_t, W_dash_b1_d_t, W_dash_b2_d_t, W_dash_ba1_d_t, theta_ex_d_Ave_d, L_dashdash_ba2_d_t): """1時間当たりの給湯機の消費電力量 (kWh/h) (1) Args: W_dash_k_d_t(ndarray): 1時間当たりの台所水栓における太陽熱補正給湯負荷 (MJ/h) W_dash_s_d_t(ndarra...
5,344,709
def set_cookie(cookie): """ Set a new (or updated) cookie. :param cookie: the cookie item, as a cookie.Cookie named tuple. """ krait.extra_headers.append(("set-cookie", str(cookie)))
5,344,710
def addCasingInformation(sentences): """Adds information of the casing of words""" for sentenceIdx in range(len(sentences)): sentences[sentenceIdx]['casing'] = [] for tokenIdx in range(len(sentences[sentenceIdx]['tokens'])): token = sentences[sentenceIdx]['tokens'][tokenIdx] ...
5,344,711
def best_promo(order): """ 选择可用的最佳折扣 """ return max(promo(order) for promo in promos)
5,344,712
def random_joint_positions(robot): """ Generates random joint positions within joint limits for the given robot. @type robot: orpy.Robot @param robot: The OpenRAVE robot @rtype: np.array @return: """ # Get the limits of the active DOFs lower, upper = robot.GetActiveDOFLimits() positions = lower + n...
5,344,713
def plot_gas_driven_models(axes): """ Plots the gas-driven starburst models in the top row of panels. Parameters ========== axes :: list The 1-D list of matplotlib axes """ visuals.plot_output_3axes(axes, "../../simulations/sudden_2Gyr_5e9Msun", "crimson", "Sr") visuals.plot_output_3axes(axes, "../../simul...
5,344,714
def cli(sqlplus, user, host, password, database, version, prompt, logfile, login_path, auto_vertical_output, table, csv, warn, execute, filename, okclirc): """An Oracle-DB terminal client with auto-completion and syntax highlighting. \b Examples: - okcli -u my_user -h my_host....
5,344,715
def test_cancel_examples(example): """ We can't specify examples in test_fuzz_cancel (because we use data, see https://hypothesis.readthedocs.io/en/latest/data.html#interactive-draw), so we have this here for explicit examples. """ stream_req, stream_resp, draws = example def draw(lst): ...
5,344,716
def fetch_pickle(filename): """ Fetches any variable saved into a picklefile with the given filename. Parameters: filename (str): filename of the pickle file Returns: variable (any pickle compatible type): variable that was saved into the picklefile. """ with open(f...
5,344,717
def check_clockwise(poly): """Checks if a sequence of (x,y) polygon vertice pairs is ordered clockwise or not. NOTE: Counter-clockwise (=FALSE) vertice order reserved for inner ring polygons""" clockwise = False if (sum(x0*y1 - x1*y0 for ((x0, y0), (x1, y1)) in zip(poly, poly[1:] + [poly[0]]))) <...
5,344,718
def bookList(request): """测试""" # 查询书籍信息:使用默认的管理器对象 : 在管理器上调用过滤器方法会返回查询集 # book_list = BookInfo.objects.all() # 查询书籍信息:使用自定义的管理器对象 # book_list = BookInfo.books.all() # 以下代码演示,自定义管理器的类给模型类新增初始化方法: 类比books.all() # book1 = BookInfo.books.create_model('zxc') # book2 = BookInfo.books.creat...
5,344,719
def format_stats(stats): """Format statistics for printing to a table""" result = '' for key, value in stats.items(): result += f'{key} - {value}\n' return result[:-1]
5,344,720
def imcrop(img, bboxes, scale=1.0, pad_fill=None): """Crop image patches. 3 steps: scale the bboxes -> clip bboxes -> crop and pad. Args: img (ndarray): Image to be cropped. bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes. scale (float, optional): Scale ratio of...
5,344,721
def start_dhcp_servers(config): """Start DHCP server.""" # start dhcp servers for device in config.board["devices"]: if "options" in device and "no-dhcp-server" in device["options"]: continue if "options" in device and "dhcp-server" in device["options"]: getattr(confi...
5,344,722
def timestamp2str(ts): """ Converts Timestamp object to str containing date and time """ date = ts.date().strftime("%Y-%m-%d") time = ts.time().strftime("%H:%M:%S") return ' '.join([date, time])
5,344,723
def define_class_functions(processes, stages, progress): """ Define and return class of unit tests for stand-alone functions for the given configuration. """ class Test_functions(TestCase): def test_mapreduce(self): logger = log() if progress else None result = mr4mp....
5,344,724
def is_homescreen(): """ description: Check homescreen is displayed usage: ui_utils.is_homescreen() tags: ui, android, homescreen """ pass
5,344,725
def concept(*reference): """Reference to a semantic concept. Parameters ---------- *reference : :obj:`str` Keys pointing to the ruleset defining this concept in the rules file of an ontology. Returns ------- :obj:`CubeProxy` A textual reference to the concept that can be solved by ...
5,344,726
async def handle_spam(message: "Message", trigger_type: str, trigger: str) -> None: """ Handle the booru spam request Args: message: Discord message object related to this request trigger_type: the trigger type that called this function ('author', 'first_word', or 'contains') trigge...
5,344,727
def collate_tensors(batch, stack_tensors=torch.stack): """ Collate a list of type ``k`` (dict, namedtuple, list, etc.) with tensors. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: batch (list of k): List of rows of type ``k``. s...
5,344,728
def plot_single_loc(lon_pt, lat_pt, extent_lst, lon, lat, save_loc=None, title=None, ): """ Plot a single point on a map Parameters: lon_pt (int) : longitude idx lat_pt (int) : latitude idx extent_lst (list) : plotting region ...
5,344,729
def show_lsb(image_path, n): """Shows the n least significant bits of image""" start = time() image = Image.open(image_path) # Used to set everything but the least significant n bits to 0 when # using bitwise AND on an integer mask = ((1 << n) - 1) color_data = [(255 * ((rgb[0] & mask) + (...
5,344,730
def build_boundaries_layers(cyt_coord, nuc_coord, rna_coord): """ Parameters ---------- cyt_coord : np.ndarray, np.int64 Array of cytoplasm boundaries coordinates with shape (nb_points, 2). nuc_coord : np.ndarray, np.int64 Array of nucleus boundaries coordinates with shape (nb_point...
5,344,731
def itersubclasses(cls, _seen=None): """ Generator over all subclasses of a given class, in depth first order. >>> class A: pass >>> class B(A): pass >>> class C(A): pass >>> class D(B,C): pass >>> class E(D): pass >>> >>> for cls in itersubclasses(A): ... print(cls.__name__...
5,344,732
def predicted_actual_chart(actual, predicted, title="Predicted vs Actual Values"): """Predicted vs actual values curve.""" source = pd.DataFrame({"x": actual, "y": predicted}) scatter = scatter_chart(source, "Actual", "Residual", title=title) vmin = source.min().min() vmax = source.max().max() ...
5,344,733
def swapSeries(keypoints_array,v,c,pers1,pers2,start,end): """helper function for swapping sections of time series. This is useful because openpose isn't consistent in labelling people so we need to rearrange things. Args: keypoints_array: all the data. v: which video? - specifies first d...
5,344,734
def load_vgg(sess, vgg_path): """ Load Pretrained VGG Model into TensorFlow. :param sess: TensorFlow Session :param vgg_path: Path to vgg folder, containing "variables/" and "saved_model.pb" :return: Tuple of Tensors from VGG model (image_input, keep_prob, layer3_out, layer4_out, layer7_out) """...
5,344,735
def run(): """Runs the development server.""" db.create_all() app.run(use_reloader=True, threaded=True, host='0.0.0.0', port=8080)
5,344,736
def interpolate(R1,R2,u): """Interpolate linearly between the two rotations R1 and R2. """ R = mul(inv(R1),R2) m = moment(R) angle = vectorops.norm(m) if angle==0: return R1 axis = vectorops.div(m,angle) return mul(R1,rotation(axis,angle*u))
5,344,737
def _iterate_list(element, sign, other_states, output_splitter, state_fields=True): """ Used in the splitter2rpn to get recursion. """ for i, el in enumerate(element): _ordering( deepcopy(el), i, current_sign=sign, other_states=other_states, ou...
5,344,738
def insertion_sort(items): """Sort given items by taking first unsorted item, inserting it in sorted order in front of items, and repeating until all items are in order. Running time: O(n^2) Memory usage: O(1)""" for i in range(1, len(items)): j = i while j > 0 and items[j-1] > items...
5,344,739
def plot_spikes( spikes: dict, ax: plt.Axes = None, markersize: int = None, color: tp.Union[str, tp.Any] = "k", ) -> plt.Axes: """Plot Spikes returned by NeuroDriver's OutputRecorder""" if ax is None: fig = plt.gcf() ax = fig.add_subplot() for n, (name, ss) in enumerate(spik...
5,344,740
def restore(modeladmin, request, queryset, all_fields=False): """ Action to cancel changes :param modeladmin: Administration class :param request: HTTP request :param queryset: All the entities selected :param all_fields: Also restore data that cannot be edited? :return: None """ fai...
5,344,741
def boardToString(board): """ return a string representation of the current board. """ # global board # b = board rg = range(board.size()) s = "┌────┬────┬────┬────┐\n|"+"|\n╞════╪════╪════╪════╡\n|".join( ['|'.join([getCellStr(board, x, y) for x in rg]) for y in rg]) s = "\n" + s ...
5,344,742
def create_data_ops(batch_size, num_elements_min_max): """Returns graphs containg the inputs and targets for classification. Refer to create_data_dicts_tf and create_linked_list_target for more details. Args: batch_size: batch size for the `input_graphs`. num_elements_min_max: a 2-`tuple` of `int`s whic...
5,344,743
def compute_file_path(data_path, path, command): """Return the computed file path for mocked data Keyword arguments: data_path -- the path of the folder that contains the subbed data path -- the URL path command -- the HTTP verb """ return os.path.realpath( os.path.join( ...
5,344,744
def location_matches(stmt): """Return a matches_key which takes geo-location into account.""" if isinstance(stmt, Event): context_key = get_location(stmt) matches_key = str((stmt.concept.matches_key(), context_key)) elif isinstance(stmt, Influence): subj_context_key = get_location(st...
5,344,745
def _submit_to_measurement_sets_api(measurement_set, patch_update): """Send the submission object to the appropriate API endpoint.""" # TODO: Add a separate method to validate submission without sending it. # Attempt to find existing measurement sets if any exist. try: matching_submission = get_...
5,344,746
def parse_files(files, options): """Build datastructures from lines""" lines = [] for line in finput(files, openhook=compr): if (type(line) is bytes): line = line.decode('utf-8') lines.append(line.rstrip().split("|")) db = {} db['rp'], db['users'], db['msgprof'], db['logins'] = {}, ...
5,344,747
def resize_preserving_order(nparray: np.ndarray, length: int) -> np.ndarray: """Extends/truncates nparray so that ``len(result) == length``. The elements of nparray are duplicated to achieve the desired length (favours earlier elements). Constructs a zeroes array of length if nparray is emp...
5,344,748
def push(service, key, data): """Push Called to push data to the sync cache Args: service (str): The name of the service using the sync key (mixed): The key to push the data onto data (mixed): The data to be pushed Returns: bool|string """ # Make sure the service and key are strings if not isinstance...
5,344,749
def load_zipcar_test(tests_folder,test_name): """ Loads and runs a specific strong controllability test from the Zipcar benchmarks. """ folder = os.path.abspath(os.path.expanduser(tests_folder)) tcs = load_pickle_file(os.path.join(folder,test_name)) counts=[0,0,0] for tc in tcs: if ...
5,344,750
def cli( config_file: str, stmgr_type: str, name: str, rootpath: str, tunnelhost: str, hostport: str, port: int, verbose: bool, ) -> None: """ A HTTP service for serving data about clusters. The statemanager's config from the given config file can be overrided using options on t...
5,344,751
def get_args(): """Get all parsed arguments.""" parser = argparse.ArgumentParser(description="CLASP training loop") # data parser.add_argument("--id", type=str, help="run id") parser.add_argument("--path-data-train", type=str, help="path preprocessed ...
5,344,752
def nst_list2(ctx, filter): """list all Network Slice Templates (NST) in the system""" nst_list(ctx, filter)
5,344,753
def omniidlArguments(args): """omniidlArguments(list) Set default omniidl arguments for importIDL() and importIDLString(). e.g. omniidlArguments(["-I/my/include", "-DMY_DEFINE"])""" global _omniidl_args if type(args) is not types.ListType: raise TypeError("argument must be a list of strings") ...
5,344,754
def get_db_filenames(database_name): """ This is used to populate the dropdown menu, so users can only access their data if their name is in the user column""" con = sql.connect(database_name) c = con.cursor() names_list = [] for row in c.execute( """SELECT Dataset_Name FROM master_t...
5,344,755
def _pull_live_data_from_staging(): """ Marginally different from _pull_data; uses remote variables for local paths etc., as the local environment is presumed to be staging server. """ if env['host'] == PRODUCTION_HOST_2: # No need to pull data twice return filename = "{}-{}.sql".fo...
5,344,756
def test_empty_packages(): """ Test with empty package list """ w = TcpWrappersFacts(daemon_lists=[DaemonList(value=["ALL"])]) p = [] d = [("openssh", ["sshd"])] packages = config_affects_daemons(w, p, d) assert not packages
5,344,757
def Calculate(values, mode=0, bin_function=None): """Return a list of (value, count) pairs, summarizing the input values. Sorted by increasing value, or if mode=1, by decreasing count. If bin_function is given, map it over values first. """ if bin_function: values = list(map(bin_function,...
5,344,758
def getToday(format=3): """返回今天的日期字串""" t = time.time() date_ary = time.localtime(t) if format == 1: x = time.strftime("%Y%m%d", date_ary) elif format == 2: x = time.strftime("%H:%M", date_ary) elif format == 3: x = time.strftime("%Y/%m/%d", date_ary) elif format == 4...
5,344,759
def _get_referenced(body, start, end, no_header, clean, as_xml, as_list): """Retrieve data from body between some start and end.""" if body is None or start is None or end is None: return None content_list = body.get_between( start, end, as_text=False, no_header=no_header, clean=clean ) ...
5,344,760
def info(filepath: str) -> AudioMetaData: """Get signal information of an audio file. Args: filepath (str): Path to audio file Returns: AudioMetaData: meta data of the given audio. """ sinfo = torch.ops.torchaudio.sox_io_get_info(filepath) return AudioMetaData(sinfo.get_sample_...
5,344,761
def _override_regex_to_allow_long_doctest_lines(): """Allow too-long lines for doctests. Mostly a copy from `pylint/checkers/format.py` Parts newly added are marked with comment, "[PYTA added]: ..." """ def new_check_lines(self, lines, i): """check lines have less than a maximum numb...
5,344,762
def writevrt(out_csv,srs='EPSG:4326',x='field_1',y='field_2'): """ Write out a vrt to accompany a csv of points """ out_vrt = os.path.splitext(out_csv)[0]+'.vrt' out_csv = os.path.split(out_csv)[-1] f = open(out_vrt, 'w') f.write('<OGRVRTDataSource>\n') f.write(' <OGRVRTLayer name="%s"...
5,344,763
def register_coco_instances(name, metadata, json_file, image_root): """ Register a dataset in COCO's json annotation format for instance detection, instance segmentation and keypoint detection. (i.e., Type 1 and 2 in http://cocodataset.org/#format-data. `instances*.json` and `person_keypoints*.json`...
5,344,764
def handle(*, artifacts: oa_types.SimplePropertyArtifacts) -> types.TColumn: """ Handle a simple property. Args: artifacts: The artifacts of the simple property. Returns: The constructed column. """ return facades.sqlalchemy.simple.construct(artifacts=artifacts)
5,344,765
def rollout_representation(representation_model, steps, obs_embed, action, prev_states, done): """ Roll out the model with actions and observations from data. :param steps: number of steps to roll out :param obs_embed: size(time_steps, batch_size, n_agents, embedding_size) :param act...
5,344,766
def argparser(): """parse arguments from terminal""" parser = argparse.ArgumentParser() parser.add_argument('-v', '--video', dest='video') parser.add_argument('-c', '--config', dest='config', default=CONFIG_FILE) parser.add_argument('-o', '--output', dest='output') return parser
5,344,767
def generate_random_ast(schema, rng): """End-to-end simulator for AST of Core DSL.""" distributions = [schemum[1] for schemum in schema] partition_alpha = rng.gamma(1,1) partition = generate_random_partition(partition_alpha, len(distributions), rng) row_dividers = [generate_random_row_divider(rng) f...
5,344,768
def ngmlrmap_bam_in(in_fn, ref_fa, out_bam, nproc=4): """Call ngmlr to map in_fn to reference fasta and output to out_bam""" cmd = indep.ngmlrmap_bam_in_cmd( in_fn=in_fn, ref_fa=ref_fa, out_bam=out_bam, nproc=nproc) execute_as_bash([cmd], realpath('%s.ngmlrmap.bash' % out_bam))
5,344,769
def _opcode_to_string(opcode): """Return the printable name for a REIL opcode. Args: opcode (reil.Opcode): The opcode to provide in printable form. Returns: A string representing the opcode. """ return _opcode_string_map[opcode]
5,344,770
def get_shot(shot): """Retrieves shot object from database and returns as dictionary. Raises exception if shot is not found. """ return __get_conn().get_entity(__table_name(), shot['PartitionKey'], shot['RowKey'])
5,344,771
def report_value_count(data_frame: pd.DataFrame, column: str, digits: int = 2) -> str: """ Report the number and percentage of non-empty values in the column. Parameters ---------- data_frame : pandas.DataFrame A data frame with one or more columns. column : str The name of the ...
5,344,772
def input_fn(is_training, data_dir, batch_size, num_epochs=1, num_parallel_calls=1, multi_gpu=False): """Input_fn using the tf.data input pipeline for CIFAR-10 dataset. Args: is_training: A boolean denoting whether the input is for training. data_dir: The directory containing the input data. ...
5,344,773
def getWinners(players, game): """ Return a list of winners :param players: :param game: :return: """ # get score for each player for i in range(0, len(game.players)): game.players[i].credits = scoreFor(i, game) currentPlayer = whoseTurn(game) # add 1 to players who ha...
5,344,774
def pprint(data): """Print Json in pretty human readable format. There's a standard module pprint, can pretty print python dict and list. But it doesn't support sorted key, and indent doesn't looks good. Usage:: >>> from dataIO import js >>> js.pprint({"a": 1, "b": 2}) { ...
5,344,775
def read_xsf(filepath): """ :param filepath filepath of the xtd file :return cell and atoms need to build the pymatflow.structure.crystal object """ a = ase.io.read(filepath, format='xsf') cell = a.cell.tolist() atoms = [] for i in range(len(a.arrays['numbers'])): for it...
5,344,776
def elina_abstract0_bound_linexpr(man, a, linexpr): """ Returns the ElinaInterval taken by an ElinaLinexpr0 over an ElinaAbstract0. Parameters ---------- man : ElinaManagerPtr Pointer to the ElinaManager. a : ElinaAbstract0Ptr Pointer to the ElinaAbstract0. linexpr : Eli...
5,344,777
def load_papertext(train_rate=0.8, dev_rate=0.1, test_rate=0.1, max_length=50, download_from_label_studio=True): """ Aspect Base sentiment analysis :param kind: 是加载papertext数据,还是dem8的数据 :return: :rtype: """ export_dir = "/opt/nlp/data/papertext/" if download_from_label_studio: js...
5,344,778
def printhelp(): """ print the document options for the simba3d command line utility """ print('Create a random initialization') print('[options] -o <result files>') print('\t-o or --output-files <result_file_name.csv> csv filename') print('[Options]') print('-n or --number-of-n...
5,344,779
def set_log_level_for_all_handlers(logger, level=logging.DEBUG): """ Set a log level for all the handlers on the provided logger. """ logger.setLevel(level) handlers = logger.handlers for handler in handlers: handler.setLevel(level) return logger
5,344,780
def _load_cmake_spec(): """Load and return the CMake spec from disk""" try: with open(CMAKE_SPEC_FILE()) as fp: return json.load(fp) except (OSError, IOError, ValueError): return None
5,344,781
def compare_ask_ai_question(): """ compare_ask_ai_question(): Ask a one questions to many product (GPT-3) """ try: id_token = request.headers['Authorization'] claims = auth.verify_id_token(id_token) uid = claims['uid'] data = request.json['data'] question = d...
5,344,782
def close_forecast_files(exporter): """Close the files associated with a forecast exporter. Finish writing forecasts and close the output files opened by a forecast exporter. Parameters ---------- exporter : dict An exporter object created with any initialization method implemented ...
5,344,783
def read(): """ Read temperature :return: temperature """ # global ds18b20 location = '/sys/bus/w1/devices/' + ds18b20 + '/w1_slave' tfile = open(location) text = tfile.read() tfile.close() secondline = text.split("\n")[1] temperaturedata = secondline.split(" ")[9] temper...
5,344,784
def wine(root): """Title of Database: Wine recognition data Updated Sept 21, 1998 by C.Blake : Added attribute information These data are the results of a chemical analysis of wines grown in the same region in Italy but derived from three different cultivars. The analysis determined the qua...
5,344,785
def ddpg(env_fn, ac_kwargs=dict(), seed=0, cuda=True, train_interval=100, train_steps=50, steps_per_epoch=5000, epochs=200, replay_size=int(1e6), gamma=0.99, hidden_size=64, polyak=0.01, pi_lr=1e-4, q_lr=1e-3, batch_size=64, start_steps=1000, act_noise=0, param_noise=0.2, max_ep_len=1000, log...
5,344,786
def setup(bot): """ Mandatory function to add the Cog to the bot. """ bot.add_cog(GeneralDebugCog(bot))
5,344,787
def test_setter_with_models(): """Assert that an error is raised when there are models.""" atom = ATOMClassifier(X_bin, y_bin, random_state=1) atom.run("LR") with pytest.raises(PermissionError, match=r".*not allowed to change the data.*"): atom.X = X_class
5,344,788
def initialize_scenario_data(): """Will initialize the Scenario Data. :return an empty ScenarioData named tuple :rtype ScenarioData """ actors = {} companies = {} scenario_data = ScenarioData(actors, companies) return scenario_data
5,344,789
def dynamicMass(bulk_density, lat, lon, height, jd, velocity, decel, gamma=1.0, shape_factor=1.21): """ Calculate dynamic mass at the given point on meteor's trajectory. Either a single set of values can be given (i.e. every argument is a float number), or all arguments must be numpy arrays. ...
5,344,790
def traverse_tuple(t:tuple,mut:Mutator)->None: """ Traverse an arbitrary Python tuple. Forbids changing items. """ assert isinstance(t,tuple) for i in range(len(t)): x=mut(i,t[i]) assert x==t[i], "Can't change tuple item" if isinstance(t[i],list): scanref_list(t[i]) elif isinstance(t[i],dict...
5,344,791
def input_fn_tfrecords(files_name_pattern, num_epochs, batch_size, mode): """ Input functions which parses TFRecords. :param files_name_pattern: File name to TFRecords. :param num_epochs: Number of epochs. :param batch_size: Batch size. :param mode: Input function mode. :return: features and...
5,344,792
def validate(number): """Check if the number provided is a valid RUC number. This checks the length, formatting, check digit and check sum.""" number = compact(number) if len(number) != 13: raise InvalidLength() if not number.isdigit(): raise InvalidFormat() if number[:2] < '01' ...
5,344,793
def parse_raw(data: bytes) -> dict: """ Parse the contents of an environment retrieved from flash or memory and provide an equivalent dictionary. The provided *data* should being at the start of the variable definitions. It **must not** contain the ``env_t`` metadata, such as the CRC32 word and...
5,344,794
def _list_registered_paths() -> List[str]: """List available paths registered to this service.""" paths = [] for rule in application.url_map.iter_rules(): rule = str(rule) if rule.startswith("/api/v1"): paths.append(rule) return paths
5,344,795
def plot_signals(data_dir, save_dir, plot_type): """ Plot signals in the correct format to generate the bottleneck features. For the signals database the records are plotted stacked, this is, one below the other. For the recurrence the signals are plotted in a 3x3 grid. Note that to maintain a...
5,344,796
def input_fn(request_body, request_content_type): """An input_fn that loads a pickled numpy array""" if request_content_type == "application/python-pickle": array = np.load(BytesIO(request_body), allow_pickle=True) return array else: raise Exception("Please provide 'application/pytho...
5,344,797
def game(x_train, x_test, y_train, y_test, algo='rf', show_train_scores=True): """Standard Alogrithms fit and return scores. * Default Random State is set as 192 when posible. * Available models - dc, rf, gb, knn, mc_ovo_rf, mc_ova_rf """ if algo is 'dc': clf = clf = DummyClassifier(strateg...
5,344,798
def get_convolutional_model(vocab_size: int, input_length: int, num_classes: int, embedding_size: int=300, model_size: str='small' ) -> Model: """Create a character convolution...
5,344,799