content
stringlengths
22
815k
id
int64
0
4.91M
def handle_effect_results(permutation_result): """Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataFr...
79,900
def _model_train_forest(df,tag,test=False): """ example funtion to train model The 'test' flag when set to 'True': (1) subsets the data and serializes a test version (2) specifies that the use of the 'test' log file """ ## start timer for runtime time_start = time.time() ...
79,901
def get_one_carrot_input(): """ Obtains pre-defined testing base astar that is assured not to fail """ args = g08.get_args() args.a_estrella = True args.vision = 2 args.zanahorias = 2 args.tablero_inicial = "_generated_inputs_/4x4(1).txt" result = g08.get_result(algorithm="AStar", ar...
79,902
def apply_repeat_three_optimization(moves): """ R, R, R --> Ri """ changed = False i = 0 while i < len(moves) - 2: if moves[i] == moves[i+1] == moves[i+2]: moves[i:i+3] = [_invert(moves[i])] changed = True else: i += 1 if changed: apply_rep...
79,903
def CheckGlobalStatic(filename, clean_lines, linenum, error): """Check for unsafe global or static objects. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors ...
79,904
def canvas_pull ( canvas , ratio = 0.80 , left_margin = 0.14 , right_margin = 0.05 , bottom_margin = 0.14 , top_margin = 0.05 , hSpacing = 0.0 , vSpacing ...
79,905
def soft_threshold(X, thresh): """Proximal mapping of l1-norm results in soft-thresholding. Therefore, it is required for the optimisation of the GFGL or IFGL. Parameters ---------- X : ndarray input data of arbitrary shape thresh : float threshold value Returns -------...
79,906
def iteration(data: dict, args: argparse.Namespace, it: int) -> dict: """Perform self-learning iteration. See Vulic et al, 2019, for details.""" # (1) update embeddings from in-dictionary terms data['dico'].update_embeddings(data['src'], data['trg']) # (2) solve procrustes for in-dictionary terms ...
79,907
def write_prophage_information(self): """ Write the full ORF table :param self: the data object :return: """ log_and_message("Writing prophage_information.tsv output file", c="GREEN", stderr=True, quiet=self.quiet) with open(os.path.join(self.output_dir, self.file_prefix + "prophage_informa...
79,908
def _add_labels_above(ax0, fig, flowdim, raindim): """ matplotlib.axes -> None """ bbox = ax0.get_position() rainlabel = ax0.text(bbox.x0 + bbox.width, bbox.y0 + bbox.height, r"Rain ($mm$)", transform=fig.transFigure, verticalal...
79,909
def _to_ffmpeg_time(n): """ Format number of seconds to time expected by FFMPEG. n: int Time in seconds to format. returns: Formatted time in FFMPEG format. """ m, s = divmod(n, 60) h, m = divmod(m, 60) return '%d:%02d:%09.6f' % (h, m, s)
79,910
def compute_similarity(network, feature_matrix): """ Builds a weighted graph, where each edge (u, v, sim) is constructed by computing the Jaccard similarity (sim) of the attributes of nodes u and v. For the sake efficiency, a vectorized implementation is used :param network: The network :param f...
79,911
async def paginate(ctx): """Paginator test command.""" p = Paginator(ctx) embeds = (discord.Embed(color=0xff0000, title='Embed #1', description='Test starts here'), discord.Embed(color=0x00ff00, title='Embed #2', description='Second embed...'), discord.Embed(color=0x0000ff, title='Embed #...
79,912
def fillDamage(): """ Realiza una cantidad de damages y los RELACIONA CON una factura """ reparaciones = ["aceite", "motor", "turbina", "Ala", "Asientos", "Baño atacasdo" , "Combustible", "Llantas"] contadorIdDaño = 0 for i in range(0, 100): for j in range(0, random.rand...
79,913
def vxxxxx(p, vmass, nhel, nsv): """ Defines a vector wavefunction. nhel=4 is for checking BRST. Input momenta have shape (num events, 4). Parameters ---------- p: tf.Tensor, vector boson four-momenta of shape=(None,4) vmass: tf.Tensor, boson mass of shape=() nhel: tf.Tensor...
79,914
def test_display(): """Display method returns string of data in the list in order.""" from linked_list import LinkedList ll = LinkedList() for i in range(1, 11): ll.push(i) assert ll.display() == '(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)'
79,915
def test_list_float_length_2_nistxml_sv_iv_list_float_length_3_1(mode, save_output, output_format): """ Type list/float is restricted by facet length with value 7. """ assert_bindings( schema="nistData/list/float/Schema+Instance/NISTSchema-SV-IV-list-float-length-3.xsd", instance="nistDa...
79,916
def find_properties_object(path: List[str], field: str, properties) -> Dict[str, Dict]: """ This function is trying to look for a nested "properties" node under the current JSON node to identify all nested objects. @param path JSON path traversed so far to arrive to this node @param field is the cu...
79,917
def get_nodes(lines): """ Return node register IDs provided lines from a trace file. :param lines: The lines from the trace file to be searched. """ nodes = [] for line in lines: found = re_node_register.search(line) if found: node_id = found.group(2) ...
79,918
def build_arg_parser(): """ Builds a standard argument parser with arguments for talking to vCenter -s service_host_name_or_ip -o optional_port_number -u required_user -p optional_password """ parser = argparse.ArgumentParser( description='Standard Arguments for talking to vCen...
79,919
def are_infinity_coordinates(coordinates_value): """ To check whether the coordinates are infinite. Parameters ---------- coordinates_value: np.array, or list x and y coordinates you want to check. Returns ---------- bool Are coordinates infi...
79,920
def get_twitter_api_keys(sport: str, area: str): """Load twitter api keys. API keys for twitter account for a sport + area must be defined in an environment variable. E.g. keys for latu updates in oulu must be defined in env var LATUBOT_KEYS_LATU_OULU. The value of the env var must contain 4 value...
79,921
def assemble_pysb(stmts, data_genes, out_file): """Return an assembled PySB model.""" base_file, _ = os.path.splitext(out_file) #stmts = ac.load_statements('%s.pkl' % base_file) stmts = preprocess_stmts(stmts, data_genes) # Make a SIF model equivalent to the PySB model # Useful for making direc...
79,922
def read_cam_from_json(path): """generates a Camera object from a json file""" with open(path) as f: config = json.load(f) intrinsic = config['intrinsic'] coefficients = [intrinsic['k1'], intrinsic['k2'], intrinsic['k3'], intrinsic['k4']] cam = Camera( rotation=SciRot.from_quat(con...
79,923
def get_angle_encoding_model(theta, neural_data, ang_bin_edges, speed=None, min_speed=None, max_speed=None, data_type='spikes', n_xval=5): """ :param theta: array n_samps of angles in radians :param neural_data: array n_units x n_samps of firing rates :param ang_bin_edg...
79,924
def optimize(solver, func, maximize=True, max_evals=0, pmap=map, decoder=None): """Optimizes func with given solver. :param solver: the solver to be used, for instance a result from :func:`optunity.make_solver` :param func: the objective function :type func: callable :param maximize: maximize or mi...
79,925
def plot_adj(adj, save_path): """ Plot adjacency matrix as image """ plt.figure(figsize=(7, 5)) sns.heatmap(adj, fmt='g') plt.ylabel('Features') plt.xlabel('Features') plt.tight_layout() plt.savefig(save_path) # plt.show() plt.clf() plt.close()
79,926
def uninstall_callback(): """Hipchat will hit this endpoint when the integration has been uninstalled by the end user.""" redirect_url = request.args.get('redirect_url') installable_url = request.args.get('installable_url') logging.info("Getting installable info from %s", installable_url) installat...
79,927
def win_main(): """ start gui application """ app = Win() app.run()
79,928
def test_virtualbox_repo_exists(host): """ Tests if Debian Family repo file exists for virtualbox. """ assert host.file(DEBIAN_REPO_FILE).exists
79,929
def distros(ctx, opts, package_format): """List available distributions.""" click.echo( 'Getting list of distributions ... ', nl=False ) context_msg = 'Failed to get list of distributions!' with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with spinner(): ...
79,930
def visualize_transform(samples, sample_names, logdensities, logdensity_names, npts=100, memory=100, device="cpu", low=LOW, high=HIGH): """Produces visualization for the model density and samples from the model.""" n_samples = len(samples) n_logdensities = len(logdensities) assert n_samples == len(s...
79,931
def normalized_uri(root_dir): """ Attempt to make an LSP rootUri from a ContentsManager root_dir Special care must be taken around windows paths: the canonical form of windows drives and UNC paths is lower case """ root_uri = pathlib.Path(root_dir).expanduser().resolve().as_uri() root_u...
79,932
def _serialize(selector: str, class_name: str, values: Dict[str, Any]): """Serializes message using the selector and defined class name.""" package_name = _find_package_name(selector) class_object = getattr(importlib.import_module(package_name), class_name) proto_message = class_object() _parse_dict...
79,933
def describe_db_subnet_groups(DBSubnetGroupName=None, Filters=None, MaxRecords=None, Marker=None): """ Returns a list of DBSubnetGroup descriptions. If a DBSubnetGroupName is specified, the list will contain only the descriptions of the specified DBSubnetGroup. For an overview of CIDR ranges, go to the Wiki...
79,934
def download_prs(source_url, source, credentials): """ INPUT: source_url: the root url for the GitHub API source: the team and repo '<team>/<repo>' to retrieve prs from OUTPUT: retrieved prs sorted by their number if request was successful. False otherwise """ url = source_url + "rep...
79,935
def align(fh, transl=True): """ Translate and align pangenome cluster fasta file """ align_exe = MuscleCommandline( r'C:\Users\matthewwhiteside\workspace\b_ecoli\muscle\muscle3.8.31_i86win32.exe', clwstrict=True) # Align on stdin/stdout proc = subprocess.Popen(str(align_ex...
79,936
def calc_q_max_FC(region, mode, A_HCZ, R_type): """ファンコンベクターの最大能力 Args: region(int): 省エネルギー地域区分 mode(str): 運転モード 'い', 'ろ', 'は' A_HCZ(float): 暖冷房区画の床面積 R_type(string): 居室の形式 Returns: ndarray: ファンコンベクターの最大能力 """ # 付録Mに定める放熱器の最大能力 q_max_rad に等しいものとする return appendix...
79,937
def _pop_funclist(f): """_pop_funclist(f) -> list or None Evaluates and returns a list constant defined at the beginning of a function. If the function doesn't begin with a list, or the list refers to parameters or other locals, a None is returned. The returned list is removed from the function cod...
79,938
def levenshtein_message_distance(m1, m2): """ Use python-levenshtein package to calculate edit distance """ return levenshtein.distance(m1,m2)
79,939
def gen_task1() -> np.ndarray: """Task 1: return constant symbol.""" seq = rand_syms() return np.concatenate(([1], seq, [2]))
79,940
def read_pfam_output(pfam_out_file): """Read the output of PFAM scan.""" cols = ["seq_id", "alignment_start", "alignment_end", "envelope_start", "envelope_end", "hmm_acc", "hmm_name", "type", "hmm_start", "hmm_end", "hmm_length", "bit_score", "E-value", "significance", "clan"...
79,941
def merge_consecutive_timestamps(timestamps): """ Merges consecutive timestamps in a list if they're less than 2 seconds apart Example: [(0,5), (5,10), (20,30)] gets combined into [(0,10),[20,30] """ result = [] i = 0 while i < len(timestamps): (start, end) = timestamps[i] #...
79,942
def PadToCentered(tensor: torch.Tensor, length: int, dimension: int, fill=0.0)-> torch.Tensor: """ Pads a tensor along the indicated dimension to a particular length, embedding the initial tensor in the center. :param tensor: the tensor to pad :param length: How long the tensor will need to be ...
79,943
def _compute_cp(obs_result, obs_norm, infos, expert_plot=False): """Compute the closure phases array (across the cube) and averaged cp using the normalized bispectrum (see _normalize_all_obs()). Note that for the CP, the extracted quantities are computed after the normalisation.""" bs = obs_norm["bs"] ...
79,944
def add_sampledata_times(samples, sites_time): """ Return a tsinfer.SampleData file with estimated times associated with sites. Ensures that each site's time is at least as old as the oldest historic sample carrying a derived allele at that site. :param tsinfer.formats.SampleData samples: A tsinfer...
79,945
def convert_uint16_to_array(value): """ Convert a number into an array of 2 bytes (LSB). """ return [ (value >> 0 & 0xFF), (value >> 8 & 0xFF) ]
79,946
def putenv(key, value): """Like `os.putenv` but takes unicode under Windows + Python 2 Args: key (pathlike): The env var to get value (pathlike): The value to set Raises: ValueError """ key = path2fsn(key) value = path2fsn(value) if is_win and PY2: try: ...
79,947
def getPublishersBooksIDs(publisher, base=ALEPH_DEFAULT_BASE): """ Get list of :class:`DocumentID` objects of documents with given `publisher`. Args: publisher (str): Name of publisher which will be used to search Aleph. base (str, optional): base on which will be search performed. Defa...
79,948
def czt(x, m=None, w=1.0, a=1, axis=-1): """ Compute the frequency response around a spiral. Parameters: ---------- x: array The set of data to transform. m: int The number of points desired. Default is the length of the input data. a: complex The starting point in the com...
79,949
def gettitle(): """Return title string to be used in the timeline""" return "%s [ %s, %s - %s ]" % ( params['TIMELINE.pretitle'], params['TIMELINE.title'], gettimelinestartdate().toString(), gettimelineenddate().toString())
79,950
def refresh_token(token) -> dict or None: """ JWT access token refresh method. Args: token: payload containing jwt access token to refresh and refresh token. Returns: refreshed jwt token payload. """ user = token['user'] user_refresh_token = token['refresh_token'] try:...
79,951
def scntl_read(root): """ Read and interpret the :ref:`control file ".scntl" <Control>`. Args: root (str): root name for the control file Returns: dict[dict]: dictionary of all dictionaries obtained from all the control blocks Todo: Error checking with !TRA and !RADIAL doe...
79,952
def resume(): """ Resume a paused timer, re-activating it. Subsequent time accumulates in the total. Returns: float: The current time. Raises: PausedError: If timer was not in paused state. StoppedError: If timer was already stopped. """ t = timer() if f.t.stop...
79,953
def encode_side(side): """ Return side index by letter :param side: 'n' | 'o' | 's' | 'w' :return: 0 | 1 | 2 | 3 """ if side and isinstance(side, str): side = str.lower(side) else: raise SideValueError side_list = ['n', 'o', 's', 'w'] try: retur...
79,954
def mmr_df_filter(df, years, start_date, end_date): """Return dataframe filtered by given years, start_date and end_date. df is mmr dataframe (mandatory) years is a list of Workout_date years to include in plot (mandatory) e.g. years=[2020, 2021] - if no value is given (years=No...
79,955
def loggedReactor(reactor): """ Construct and return a wrapper around the given C{reactor} which provides all of the same interfaces, but which will log all traffic over outgoing TCP connections it establishes. """ bases = [] for iface in providedBy(reactor): if iface is IReactorTCP:...
79,956
async def stop_task(context: tanjun.abc.Context, source: str, db: Database): """Stop a scheduled task. Args: context (tanjun.abc.Context): Slash command specific context. source (str): Alias of the third-party content provider. db (Database): An instance of `dayong.operations.Database`....
79,957
def agent(ctx, force=False): """ Generate keys for agent. """ userkeys_path = os.path.join(ctx.obj['app_dir'], 'user-keys.yml') if not os.path.exists(userkeys_path): click.echo('You should set user keys first.', err=True) return with open(userkeys_path, 'rb') as userkeys_file: ...
79,958
def test_list_date_max_length_4_nistxml_sv_iv_list_date_max_length_5_2(mode, save_output, output_format): """ Type list/date is restricted by facet maxLength with value 10. """ assert_bindings( schema="nistData/list/date/Schema+Instance/NISTSchema-SV-IV-list-date-maxLength-5.xsd", instan...
79,959
def test_good_clipc_0(client, user, db_setup, tag_data): """clipc is a character field that contains the concatinated clips observed on a fish when captured. Clip code '0' is used to indicate the absence of other clips and should be acceptable as a valid clip when the form is processed. """ r...
79,960
def heatmap(df, z_score=None, title='', figsize=(5,5), cmap='RdBu_r', xticklabels=True, yticklabels=True, ofname=None, **kwargs): """Visualize the dataframe. :param df: DataFrame from expression table. :param z_score: z_score axis{0, 1}. If None, don't normalize data. :param title: gene se...
79,961
def hash_io( io: Union[BinaryIO, IO[bytes]], types: Set[HashType], chunk_size: int = DEFAULT_CHUNK_SIZE, ) -> Dict[HashType, str]: """Calculate the requested hash types for some given binary IO instance. >>> from io import BytesIO >>> from brut.hasher import hash_io, HashType >>> hash_io(By...
79,962
def load_all_gfx(directory, colorkey=(255,0,255), accept=(".png",".jpg",".bmp")): """ Load all graphics with extensions in the accept argument. If alpha transparency is found in the image the image will be converted using convert_alpha(). If no alpha transparency is detected image will be converte...
79,963
def process_head_element_content(placeholder_storage, markup): """ Process content for elements inside <head>. Processes CMD syntax which does not produce new elements, i.e. escapes, line continuations, and whitespace, and then protects the content with a placeholder. """ markup = process_escapes(pl...
79,964
def test__inRange(): """Test _inRange.""" # --------------------------------- # N-Dimensional rng = [[0, 1], [10, 11]] # standard (lbi=True, ubi=False) assert (_inRange(z, rng) == np.array([[True, False], [True, False]])).all() # going through options assert ( _inRange(z, rn...
79,965
def central_derivative(xs, ys): """ central derivative at x[1] """ return (ys[2]-ys[0])/(xs[2]-xs[0])
79,966
def print_from_tests(pav_cfg, tests, outfile, json=False): """Print the statuses given a list of test objects or a single test object. :param dict pav_cfg: Base pavilion configuration. :param Union(test_run.TestRun,list(test_run.TestRun) tests: Single or list of test objects. :param bool json: ...
79,967
def plot_boxplot(data, ylabel, title, log_scaling=True): """ Args: data: Dict of list of numbers. """ fig, ax = plt.subplots(1, 1, figsize=(8, 6), dpi=300) plt.xticks(rotation=90) ax.boxplot(data.values(), labels=data.keys()) ax.set_ylabel(ylabel) ax.set_title(title) if log...
79,968
def submit_dataframe_operation(comms, coroutine, df_list, extra_args=()): """Submit an operation on a list of Dask dataframe Parameters ---------- coroutine: coroutine The function to run on each worker. df_list: list of Dask.dataframe.Dataframe Input dataframes extra_args: tupl...
79,969
def test_angular_size(): """ Test a FlatLambdaCDM cosmology with omega_matter = 1""" cosmology = FlatLambdaCDM(Om0=1.0, H0=70.0) # Test that a scalar input gives a scalar output scalar_radius = 1.0 * units.kpc scalar_redshift = 1.0 angular_size = size.angular_size(scalar_radius, scalar_redshift...
79,970
def test_goodsounds_df_collect(goodsounds_root): """Test that an input folder with files in rwc format is correctly converted to a dataframe.""" goodsounds_df = goodsounds.collect(goodsounds_root) helpers.__test_df_has_data(goodsounds_df) helpers.__test_pd_output(goodsounds_df, goodsounds.NAME) ...
79,971
def encode(message: Union[str, bytes]) -> bytes: """Encodes a message (str or bytes) to zbase32.""" if isinstance(message, str): message = message.encode('ASCII') elif not isinstance(message, bytes): raise TypeError("message must be string or bytes") barr = _message_to_bitarray(message)...
79,972
def linear_adjoint(fun: Callable, *primals) -> Callable: """Conjugate transpose a function that is promised to be linear. :func:`scico.linear_adjoint` differs from :func:`jax.linear_transpose` for complex inputs in that the conjugate transpose (adjoint) of `fun` is returned. :func:`scico.linear_adjoint...
79,973
def parse_sra(path_to_config): """ Parses genetorrent config file. Returns list of samples: [ [id1, id1 ], [id2, id2], ... ] Returns duplicate of ids to follow UUID/URL standard. """ samples = [] with open(path_to_config, 'r') as f: for line in f.readlines(): if not line.iss...
79,974
def queryTagHistory( paths, # type: List[String] startDate=None, # type: Optional[Date] endDate=None, # type: Optional[Date] returnSize=-1, # type: Optional[int] aggregationMode="Average", # type: Optional[String] returnFormat="Wide", # type: Optional[String] columnNames=None, # type:...
79,975
def hard_sigmoid(tensor: torch.Tensor, inplace: bool = False) -> torch.Tensor: """ Applies HardSigmoid function element-wise. See :class:`torchlayers.activations.HardSigmoid` for more details. Arguments: tensor : Tensor activated element-wise inplace : Whether o...
79,976
def define_ns_gnn_encoder(gnn_name): """ return specified model class for GNNs with node-sampling. """ if gnn_name == 'gat': return SamplingGAT elif gnn_name == 'sage': return SAGE elif gnn_name == 'mpnn': return SamplingMPNN else: raise NotImplementedError("n...
79,977
def egaussian(p, x, y, e=None): """ Compute the deviation between the values y and the gaussian defined by p, x: p is a three- or four-component array, list, or tuple. Returns: y - p3 - p0/(p1*sqrt(2pi)) * exp(-(x-p2)**2 / (2*p1**2)) if an error array, e (typ. one-sigma) is entered, the returned va...
79,978
def timing(f): """Wrapper for functions to measure time""" def wrap(*args, **kwargs): time1 = time.time() ret = f(*args, **kwargs) time2 = time.time() logger.debug('%s took %0.3f ms ~ %0.3f min ~ %0.3f sec' % (f, (time2-time1)*1000.0, ...
79,979
def prioritize_results(inbound_dataframe, today_value) -> object: """Prioritize results by due date and write to a CSV file.""" inform("Prioritizing") # sort by due-date for prioritization to be compliance against DHS inbound_dataframe = inbound_dataframe.sort_values(by='dueDate') inform("Writing pr...
79,980
def plot_s2p_raw(trialobj, cell_id): """ :param trialobj: :param cell_id: """ plt.figure(figsize=(50, 3)) plt.plot(trialobj.baseline_raw[trialobj.cell_id.index(cell_id)], linewidth=0.5, c='black') plt.xlim(0, len(trialobj.baseline_raw[0])) plt.show()
79,981
def manage_save_dialog(qtbot, fname, directory=LOCATION): """ Manage the QFileDialog when saving. You can use this with QTimer to manage the QFileDialog. Before calling anything that may show a QFileDialog for save call: QTimer.singleShot(1000, lambda: manage_save_dialog(qtbot)) """ top_lev...
79,982
def delete_locations_by_location_type( client: SymphonyClient, location_type: LocationType ) -> None: """Delete locatons by location type. :param location_type: LocationType object :type location_type: :class:`~pyinventory.common.data_class.LocationType` :raises: `pyinvento...
79,983
def _get_html_tree(html_content: str) -> Optional[lxml.html.HtmlElement]: """Obtain the HTML parse tree for the given HTML content. Args: html_content: The content to parse. Returns: The corresponding HTML parse tree. """ html_content = html_content.strip() if not html_content:...
79,984
def get_county_by_id(ct_fips): """County in GeoJSON, by id""" log.debug("entering get_county_by_id() IP=%s" % get_ip()) con = get_db_con() sql = "SELECT s.ct_fips, s.ct_name, s.sq_mi, s.pop, s.pop_male / s.pop as pct_male, s.pop_female / s.pop as pct_female, s.pop_sm, " \ "chr.hs_graduate as chr...
79,985
def get_int(prompt: str | None = None, min_value: int | None = None, max_value: int | None = None, condition: Callable[[int], bool] | None = None, default: int | None = None) -> int: """Gets an int from the command line. :param prompt: Input prompt. :param mi...
79,986
def display_result(result, grouped=False): """ display distributions ids by plugins or by distributions :param result: map of distributions ids by plugins :param grouped: if we display grouped by distributions or by plugins """ GROUPS = ['Cloudera', 'MAPR', 'EMR', 'PIVOTAL_HD', 'HDP', 'MICROSOFT...
79,987
def _normalize_array(array_data: Array, normalizer: Tuple[Array, Array]) -> Array: """Helper function for normalize_graph().""" shift, scale = normalizer return (array_data - shift) / scale
79,988
def linear_gauss_policy_fit_with_prior(train_data, prior_mean, prior_cov, niw_prior_m, niw_prior_n0, cov_reg, action_size, observation_size): """ @brief: pi = p_x.dot(x) + f_c, cov(f) = f_cov """ cov_reg_matrix = np.zeros([action_...
79,989
def get_action_dict_junc(observation_builder, obs): """ Takes an agent handle and returns next action for that agent following shortest path: - if agent status == READY_TO_DEPART => agent moves forward; - if agent status == ACTIVE => pick action using shortest_path.py() fun available in prediction utils...
79,990
def Build_Meshes(dEntities): """We create a mesh here using a VertexArray for a chunk that's on the screen. This only is meant to be for chunk's in relation to their position on the screen. Chunks off the screen don't need to have their meshes updated for no reason, but they can still have their data loaded bef...
79,991
def scan(file, blocksize=10000): """Get the number of molecules in an sd file""" pat = re.compile("^[$][$][$][$]", re.MULTILINE) text = file.read(blocksize) count = 0 while text: g = pat.findall(text) count += len(g) if text[-1] == "$" and text[-4]!='$': next = t...
79,992
def testGLIFFileName(rangeName, toFile=None): """ test on glif file name """ # support both UFO2 as UFO3 try: # UFO3 ufoLib from fontTools.ufoLib.filenames import userNameToFileName def nameToFileName(name): return userNameToFileName(name) except: # U...
79,993
def main(ckpt_root, source_data_root, csv_filename, net_names, methods, modes, loss_funcs, ): """generate .csv files used as source data for figures corresponding to experiments carried out with stimuli generated by searchstims library Paramete...
79,994
def Checksum(bbytes: bytes, length: int) -> bytes: """Checksum Create checksum of [length] bytes from the 256 bit hash of the byte slice. Returns the lower [length] bytes of the hash Errors if length > 32.""" hash = ComputeHash256Array(bbytes) return hash[len(hash)-length:]
79,995
def execute_gcode(ip: str, port: int, serial_ids: Tuple[int, int], filepath: str) -> None: """ Executing G-Code commands from a file. :param ip: :param port: :param serial_ids: :param filepath: :return: """ logging.info(f'Reading G-Code from "{filepath}".') with open(filepath, 'r...
79,996
def showAllConciseHw(deviceList): """ Display critical Hardware info for all devices in a concise format @param deviceList: List of DRM devices (can be a single-item list) """ global PRINT_JSON if PRINT_JSON: print('ERROR: Cannot print JSON/CSV output for concise hardware output') s...
79,997
def init() -> None: """ Opens the interactive UI """ print( "You will now be redirected to Opta's Yaml Generation UI. If the browser doesn't open, please follow the link: " "`https://app.runx.dev/yaml-generator`" ) webbrowser.open("https://app.runx.dev/yaml-generator")
79,998
def peters_g(n, e): """ Compute g(n, e) from Peters and Mathews (1963) Eq.20 ### Parameters: n (`int/array`): Harmonic(s) of interest e (`float/array`): Eccentricity ### Returns: g (`array`): Relative power of gravitational radiation at the nth harmonic """...
79,999