content
stringlengths
22
815k
id
int64
0
4.91M
def saveMLResults(N, xDf, yDf, modelList, workingDir, numFeatures, printResults=True): """ inputs: N - int - the number of times the model should be trained and evaluated. xDf - pandas dataframe - the rows represent the data points, the columns represent the features. These ...
71,100
def main(args=None): """ """ if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser( prog="dbclean", usage="%(prog)s dbname collection [-ft] [-d k1 ...] [-r kold:knew ... ] [-v] [-h]", description="MsPASS program to fix most errors detected by dbverify", ) ...
71,101
def PullToBrepFace1(thisCurve, face, tolerance, multiple=False): """ Pulls this curve to a brep face and returns the result of that operation. Args: face (BrepFace): A brep face. tolerance (double): A tolerance value. Returns: Curve[]: An array containing the resulting curves a...
71,102
def clone_file_path(filename, target_dir, suffix=""): """ Create same file in different directory [Including sub dirs] :param filename: str, Filename to clone :param target_dir: Target dir :param suffix: Suffix to use for renaming :return: str, New file absolute path """ # Get basename ...
71,103
def try_expanding_enum_to_union(typ: Type, target_fullname: str) -> ProperType: """Attempts to recursively expand any enum Instances with the given target_fullname into a Union of all of its component LiteralTypes. For example, if we have: class Color(Enum): RED = 1 BLUE = ...
71,104
def medfilereader(filename, varsToExtract = 'all', sessionToExtract = 1, verbose = False, remove_var_header = False): """ Reads in Med Associates file stored as single column and returns variables as lists. Args: filename - file to be read i...
71,105
def sieve_of_eratosthenes(n): """Generate a list of all prime numbers between 1 and 'n' using optimised Sieve of Eratosthenes algorithm""" list_of_primes = []; # Initialise list with all EVEN items as False list_of_numbers = [True, False] * int(n / 2) # Add the last item as True in case of ODD n ...
71,106
def get_label(node_name): """ Function that returns the label of a specific docker node (eg. label can be loc=edge). Args: node_name: name of the docker node Returns: dictionary of the label: dict["label"] = "value" """ return_dict = {} cmd = "sudo docker node inspect -f '{{ range $k, $v...
71,107
def save_model_parameters( model: Module, *, model_name: str, save_directory: Path, optimiser: Optional[Optimizer] = None, config_file_path: Optional[Path] = None, ) -> None: """ :param optimiser: :param model: :param save_directory: :param config_file_path: :param model...
71,108
def test_generate_ticket(user): """Test a ticket from a valid user and a spam bot.""" ticket = generate_ticket(user['request'], user['form'], score=user['score']) assert ticket == user['expected_output']
71,109
def product_vector4_4x4(vector,matrix): """mulipli le vector 4 par une matrice care de 4""" x = matrix[0][0]*vector[0] + matrix[0][1]*vector[1] + matrix[0][2]*vector[2] + matrix[0][3]*vector[3] y = matrix[1][0]*vector[0] + matrix[1][1]*vector[1] + matrix[1][2]*vector[2] + matrix[1][3]*vector[3] z = matrix[2][0]*vec...
71,110
def ghostnet(**kwargs): """ Constructs a GhostNet model """ cfgs = [ # input e.g. 512 x 512 # k, t, c, SE, s # stage1 [[3, 16, 16, 0, 1]], # 256 x 256 # stage2 [[3, 48, 24, 0, 2]], [[3, 72, 24, 0, 1]], # 128 x 128 # stage3 ...
71,111
def fatality(path): """Drunk Driving Laws and Traffic Deaths a panel of 48 observations from 1982 to 1988 *number of observations* : 336 *observation* : regional *country* : United States A dataframe containing : state state ID code year year mrall traffic fatality rate (deat...
71,112
def soft_normal(v, alpha): """ソフト正規化関数""" v_norm = np.linalg.norm(v) softmax = v_norm + 1 / alpha * np.log(1 + np.exp(-2 * alpha * v_norm)) return v / softmax
71,113
def test_critical_root(caplog): """ emits a log with critical level into root logger. """ caplog.clear() message = 'this is a critical root log.' caplog.set_level(logging.CRITICAL) logging_services.critical(message) assert caplog.records is not None and len(caplog.records) > 0 asser...
71,114
def wrap_decoder(trg_vocab_size, max_length, n_layer, n_head, d_key, d_value, d_model, d_inner_hid, prepostprocess_dropout, attention_dropout, relu_dr...
71,115
def eval_feature_detail(Info_Value_list,out_path=False): """ format InfoValue list to Dataframe :param Info_Value_list: Instance list of Class InfoValue :param out_path:specify the Dataframe to csv file path ,default False :return:DataFrame about feature detail """ rst = Info_Value_list ...
71,116
def find_xlcxx(conf): """ Detects the Aix C++ compiler """ cxx = conf.find_program(['xlc++_r', 'xlc++'], var='CXX') conf.get_xlc_version(cxx) conf.env.CXX_NAME = 'xlc++'
71,117
def evaluate_metric_once(scenario, metric, seeds): """Runs one evaluation of metric by running a roll out of scenario with each random seed in seeds. """ runner = FindResourceOrThrow( "drake/examples/acrobot/spong_sim_main_cc") env_tmpdir = os.getenv("TEST_TEMPDIR") or os.getenv("TMPDIR") or...
71,118
def get_answer_phrase(question, sentence): """ Given a question and the sentence with an answer, extract the answer. :param question: Question asked of us. :param sentence: Sentence with question in it. :return: string phrase of answer """ # Tokenize question for W-word q_toks = nltk.wo...
71,119
def get_search_queries(phrase): """Return querysets to lookup different types of objects. Args: phrase (str): searched phrase """ return { 'skills': _search_skills(phrase), 'users': _search_users(phrase), 'tasks': _search_orders(phrase)}
71,120
def unit_test_brighteon(): """Unit test for brighteon.""" run_download_and_cut( "https://www.brighteon.com/f596cc8b-4b52-4152-92cb-39dadc552833", "10:47", "11:07", "health_ranger_report", )
71,121
def add_layout(self): """ Returns a dash layout for the bucketing app. """ column_options = [{"label": o, "value": o} for o in self.X_prebucketed.columns] navbar = dbc.NavbarSimple( children=[ dbc.Button("AUC: t.b.d.", color="primary", className="mr-1", id="menu-model-performanc...
71,122
def systems_status_req_handler(req, req_body, sn): """Handle save requests for systems status.""" content_length = req.headers.get("Content-Length", "") if content_length == 0: logger.debug("Status check") else: req_body_text = None content_type = req.headers.get("Content-Type", ...
71,123
def sortclosestpoints(pt0, pts): """return pt index in pts sorted by increasing distance from pt0 Note: cartesian distance """ x1, y1 = pt0 x2, y2 = np.array(pts).T diffx = x1 - x2 diffy = y1 - y2 dist = np.hypot(diffx, diffy) sortedindices = np.argsort(dist) sortedistances ...
71,124
def prune_properties(document, paths): """Prune given properties from a document. This assumes properties will always have an object (dict) as a parent. The function modifies the document in-place, but also returns the document for convenience. (The return value may be ignored.) """ for path in...
71,125
def HT_DCPERIOD(df): """ 函数名:HT_DCPERIOD 名称: 希尔伯特变换-主导周期 简介:将价格作为信息信号,计算价格处在的周期的位置,作为择时的依据。 [文库文档](https://wenku.baidu.com/view/0e35f6eead51f01dc281f18e.md) NOTE: The ``HT_DCPERIOD`` function has an unstable period. python API real=HT_DCPERIOD(close) :return: """ close = d...
71,126
def parse_dataset_configs(root: str): """ Parse dataset configuration file Args: root(str): (absolute, expanded) path to dataset root directory Returns: ConfigParser Raises: FileNotFoundError: configuration file does not exists """ cfg_path = os.path.join(r...
71,127
def exp(str_in, expansion): """exp(): """ return perm(str_in, expansion)
71,128
def compat_tee(iterable): """Return two independent iterators from a single iterable. Based on http://www.python.org/doc/2.3.5/lib/itertools-example.html """ # Note: Using a dictionary and a list as the default arguments here is # deliberate and safe in this instance. def gen(next, data={}, cnt...
71,129
def uint8(image:'np.ndarray')->'np.ndarray': """Convert to uint8 Args: image('np.ndarray'): Returns: Raises: """ # Change range 0-1 to 0-255 and change type to uint8 return (image*255).astype(np.uint8)
71,130
def _p(pp, name): """ make prefix-appended name """ return '%s_%s'%(pp, name)
71,131
def submit_cli(json_file, json): """ Submits a one-time run. The specification for the request json can be found https://docs.databricks.com/api/latest/jobs.html#runs-submit """ json_cli_base(json_file, json, submit_run)
71,132
def map_to_parent(t_class, parents_info_level): """ parents_info_level: {<classid>: [parent]}, only contains classid that has a super-relationship """ if t_class in parents_info_level: assert len(parents_info_level[t_class]) < 2, f"{t_class} has two or more parents {parents_info_level[t_class]}...
71,133
def _get_mtime(c: FTPClient, path: str) -> Optional[int]: """Returns timestamp of last modification""" try: mdtm = cast(ftplib.FTP, c).sendcmd("MDTM " + path) # mdtm-response = "213" SP time-val CRLF (e.g. '20180101203000') # some FTP servers response include the milliseconds (e.g. '2018...
71,134
def argParse(): """Parses commandline args.""" desc='Scrape the doxygen generated xml for docstrings to insert into python bindings' parser = ArgumentParser(description=desc) parser.add_argument("function", help="Operation to perform on docstrings", choices=["scrape","sub","copy"]) parser.add_...
71,135
def get_temp_entity_table_name() -> str: """Returns a random table name for uploading the entity dataframe""" return "feast_entity_df_" + uuid.uuid4().hex
71,136
def _sort_mixed(values) -> np.ndarray: """order ints before strings in 1d arrays, safe in py3""" str_pos = np.array([isinstance(x, str) for x in values], dtype=bool) nums = np.sort(values[~str_pos]) strs = np.sort(values[str_pos]) return np.concatenate([nums, np.asarray(strs, dtype=object)])
71,137
def lpmm2lpph(lpmm, n, pixelPitch): """Convert resolution specified in Line-Pair per Milli Meters (LPMM) to Line-Pair per Picture Height (LPPH) Parameters ---------- lpmm : float resolution in terms of Line-Pair per Milli-Meters (LPMM) n : integer Number of pixels in the picture...
71,138
def isPalindrome1(s, indent): """Return True if s is a palindrome and False otherwise.""" print indent, "isPalindrome called with", s if len(s) <= 1: print indent, "About to return True from base case" return True else: ans = s[0] == s[-1] and isPalindrome1(s[1:-1], indent...
71,139
def _parse_gcs_url(gsurl: str) -> Tuple[str, str]: """ Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a tuple containing the corresponding bucket and blob. """ parsed_url = urlparse(gsurl) if not parsed_url.netloc: raise AirflowException('Please provide a bucket name') ...
71,140
def check_style(po_files: Iterable[str], no_wrap=False, quiet=False, diff=False) -> int: """Check style of given po_files. Prints errors on stderr and returns the number of errors found. """ errors = 0 for po_path in tqdm(po_files, desc="Checking wrapping of po files", disable=quiet): try: ...
71,141
def load_aliases(): """ Load ThumbnailOption as easy-thumbnails aliases """ def _load_aliases(): try: from cmsplugin_filer_image.models import ThumbnailOption except ImportError: from filer.models import ThumbnailOption thumbs = ThumbnailOption.objects.all...
71,142
def RunCMake(context, extraArgs=None, stages=None): """Invoke CMake to configure, build, and install a library whose source code is located in the current working directory.""" srcDir = os.getcwd() instDir = context.instDir buildDir = context.buildDir if 'clean' in stages and os.path.isdir(bu...
71,143
def transformation_task(df): """Tranform original dataset. :param_df: Input Dataframe. :return: Transformed DataFrame. """ ##Prepare dataframes spark.sql('use xxx_usercrypto_db') ##create staging table # spark.sql('drop table if exists stg_users') # df.write.saveAsTable('stg_users')...
71,144
def join_with(items, separators): """Generate a series of items, with separators taken from a second series. The number of separators consumed will be one fewer than the number of items. items[0], separators[0], items[1], separators[1], ..., separators[n-2], items[n-1] Args: items: An iterabl...
71,145
def save_as_images(obj, file_name='output'): """ Convert and save an output tensor from BigGAN in a list of saved images. Params: obj: tensor or numpy array of shape (batch_size, channels, height, width) file_name: path and beggingin of filename to save. Images will b...
71,146
def main() -> None: """Main function.""" set_size = 5 start_time = time.time() prime_pairs_sets = get_prime_pairs_sets(set_size) prime_pairs_set = next(prime_pairs_sets) end_time = time.time() print(f'The lowest sum for a set of {set_size} primes for which any two primes ' \ f'conc...
71,147
def is_weight_node(node): """ Check if the node is weight type. Args: node (Node): The node object. Returns: bool, if the node is weight type. """ if node.type == NodeTypeEnum.PARAMETER.value: full_name = node.full_name.lower() weight_flag = False if ful...
71,148
def dict_to_qbody(d, prefix=''): """ Generates a string representing a query body from an AST dict. :param d: AST dict :param prefix: needed in case it will recurse """ if type(d) is not dict: return '' s = '' iprefix = prefix + '\t' args = '' for k, v in d.items(): ...
71,149
def test_get_node_configs(): """ Case: get node configurations. Expect: node public key and address are returned. """ runner = CliRunner() result = runner.invoke(cli, [ 'node', 'get-configs', '--node-url', DEV_CONSENSUS_GENESIS_NODE_IP_ADDRESS_FOR_TESTING, ]) ...
71,150
def tftpassert(condition, msg): """This function is a simple utility that will check the condition passed for a false state. If it finds one, it throws a TftpException with the message passed. This just makes the code throughout cleaner by refactoring.""" if not condition: raise TftpExceptio...
71,151
def has_setter(obj, attr): """True if an attribute has an associated setter. Parameters ---------- obj : object Any class instance. attr : str Name of the attribute to check. """ _check_is_attr_name(attr) return True if has_property(obj, attr) and \ g...
71,152
def appendCommonOptions(parser): """ Append common options shared by all sub commands. This function can be called by an other module to fetch options of Gapy. :param parser: :type parser: argparse.ArgumentParser """ # Chip # parser.add_argument('--chip', # help = 'Target chip...
71,153
def FC_CRF(pred, im, NLABELS, RESIZE_FACTOR= 5, DELTA_COL= 5, DELTA_SIZE= 5, n_steps=10, CERTAINTY= 0.7, mode= "multilabel"): """ Fully Connected Conditional Random Fields See: 1- https://github.com/lucasb-eyer/pydensecrf (./examples/Non RGB Example.ipynb) 2- http://warmspring...
71,154
def convert_to_samples(c, deg, boundary_condition='Mirror', in_place=False): """ Convert interpolation coefficients into samples In the input array, the signals are considered along the first dimension (1D computations). """ n = c.shape[0] if n == 1: return c kerlen = int(2 * m...
71,155
def firwin2(numtaps, freq, gain, nfreqs=None, window='hamming', nyq=1.0, antisymmetric=False): """ FIR filter design using the window method. From the given frequencies `freq` and corresponding gains `gain`, this function constructs an FIR filter with linear phase and (approximately) th...
71,156
def run_notebook_or_python(clname, path, params): """원격 노트북 인스턴스에서 노트북 또는 파이썬 파일 실행. Returns: tuple: (stdout, exit_code) """ info("run_notebook_or_python: {} - {}".format(clname, path)) check_cluster(clname) clinfo = load_cluster_info(clname) dask = 'type' in clinfo and clinfo['ty...
71,157
def demo_func(): """ summary description""" pass
71,158
def remove_raw_object(cls): """ Decorator. If a Record class is decorated, raw_object will be removed once all mark properties are cached. """ cls.remove_raw_object = True return cls
71,159
def cancel_all_open_orders(ses): """Cancels all open orders""" cancel_params = {'all': 1} response = ses.post(base_url + '/commands/cancel', params=cancel_params) _validate_response(response) status = response.json() cancelled = status['cancelled_order_ids'] print('Cancelled orders:...
71,160
def validate_experiment_file_existance(args): """Warn if experiment metadata files are missing Parameters ---------- args : argparse.Namespace parsed arguments as generated by argparse.parse_args Returns ------- bool True if we have required arguments """ can_contin...
71,161
def change_user_password(): """ User-friendly function to be used on first boot for changing user passwords """ usernames = get_nonroot_nonsystem_users() if len(usernames) == 0: logger.warning("Can't detect any users! Changing root password instead") usernames = ["root"] for name...
71,162
def columnOfMatrix(matrix, i): """ Метод для получения i-го столбца матрицы """ return [row[i] for row in matrix]
71,163
def run_wall_clock_test(optimizer, problem, num_steps, dataset=datasets.EMPTY_DATASET, seed=None, logdir=None, batch_size=None): """Runs optimization with the given paramet...
71,164
def p_list_formatter(primer_list): """ Reformat the primer list (remove unnecessary characters from biopython2 output). Args: primer_list (list): list from list_from_gen output Returns: primer_dimers (list): list with unnecessary chars removed. """ reformat_p_list = [] primer...
71,165
def fullpath(dataset): """ return absolute path to dataset dataset is an array as returned by CURDATA() """ dat = dataset[:] # make a copy because I don't want to modify the original array if len(dat) == 5: # for topspin 2- dat[3] = join(normpath(dat[3]), 'data', dat[4], 'nmr') f...
71,166
def edit_meeting(request, club_name, meeting_id): """Edit details of meeting""" current_club = Club.objects.get(club_name=club_name) meeting = Meeting.objects.get(id=meeting_id) form = MeetingForm(instance=meeting) if request.method == 'POST': form = MeetingForm(request.POST, instance=meetin...
71,167
def parse_mulplt(path): """ Parses MULPLT.DEF file and returns list of lists like: [station, channel type (e.g. SH), channel (E, N or Z)]. """ data = [] with open(path, "r") as f: lines = f.readlines() tag = "#DEFAULT CHANNEL" for line in lines: if line[:len(tag)...
71,168
def status(): """Status check for server""" return "Running...\n"
71,169
def parse(report_file: str, summary_file: str) -> dict: """ Check input file is an accepted file, then select the appropriate parsing method. Args: report_file (str): An Ariba report file of clusters which passed filtering. summary_file (str): A summary file of the report Returns: ...
71,170
def load_sim(filename): """Load a saved simulation""" with open(filename, "rb") as f: sim = pickle.load(f) return sim
71,171
def _repr_rule(iptc_rule, ipv6=False): """ Return a string representation of an iptc_rule """ s = '' if ipv6==False and iptc_rule.src != '0.0.0.0/0.0.0.0': s += 'src {} '.format(iptc_rule.src) elif ipv6==True and iptc_rule.src != '::/0': s += 'src {} '.format(iptc_rule.src) if ipv6==...
71,172
def mock_imap_ups_out_for_delivery_html(): """Mock imap class values.""" with patch( "custom_components.mail_and_packages.helpers.imaplib" ) as mock_imap_ups_out_for_delivery: mock_conn = mock.Mock(spec=imaplib.IMAP4_SSL) mock_imap_ups_out_for_delivery.IMAP4_SSL.return_value = mock_c...
71,173
def CV_IS_SEQ_CLOSED(*args): """CV_IS_SEQ_CLOSED(CvSeq seq) -> int""" return _cv.CV_IS_SEQ_CLOSED(*args)
71,174
def default_file(filename=''): """Discard any path components then search for file in system paths.""" filename = os.path.basename(filename) if filename in ['..','.','',None]: # special cases return None # check return value ret = filename # first try filename as provided in cwd if os.p...
71,175
def display_logs(output: str): """If want to display check of logs (not tested). Also log images from readme and example log are generated here. Args: output (str, optional): "console" or "example.log". Defaults to "console". """ if output == "console": mylogging.config.OUTP...
71,176
def add_padding_0_bits(bits_string: str, required_length: int) -> tuple: """ Adds 0 to bits string. Returns tuple - (bits string with padding, number of added 0s) """ extra_0_bits_count = 0 while len(bits_string) < required_length: bits_string += '0' extra_0_bits_count += 1 r...
71,177
def get_sheet(filename): """ Open workbook and return first worksheet as object Args: filename: local file name Returns: Worksheet object """ wb = load_workbook(filename) return wb.worksheets[0]
71,178
def version_cli(): """Manage Minecraft versions.""" pass
71,179
def object_clearance(): """ Check for two Objects Clearance distance: Quick measurements between parallel faces and similarly placed objects Original code from: Bill 03/2015 Adapted to WF by : Rentlau_64 03/2015 """ global verbose msg = verbose m_actDoc = get_ActiveDocument(info=m...
71,180
def readlasfile(lasfile): """ Run a PDAL pipeline. Input is a JSON declaration to deliver to PDAL. Output is a labelled numpy array. Data are filtered to compute height above ground using nearest ground point neighbours (TIN method arriving soon) and sort by morton order. Any unused dimensions are also...
71,181
def ssh_to_host(hostname, remote_command=None): """Compose cmd string of ssh and execute Uses Ansible to parse inventory file, gets ssh connection options :param hostname: str. Hostname from inventory """ workspace_manager = CoreServices.workspace_manager() workspace = workspace_manager.get_ac...
71,182
def avgpool_4x4(inputs, downsample=False): """ avgpool_4x4 """ return avgpool_base(inputs, (4, 4), downsample)
71,183
def str_data(group, field, default=''): """ Retrieve value of field as a string, with default if field is missing. """ if field in group: data = group[field][0] if data.ndim > 0: value = [_s(v) for v in data] else: value = _s(data) return value ...
71,184
def filter_attributes(func): """Filters and removes attributes from User Dictionary objects depending on test requirements.""" @wraps(func) def filter_attributes_wrapper(*args, **kwargs): # Get generated users. users = func(*args, **kwargs) # If only single user (dict), treat as a ...
71,185
def mask_source_centers(array, fwhm, y, x): """ Creates a mask of ones with the size of the input frame and zeros at the center of the sources (planets) with coordinates x, y. Parameters ---------- array : array_like Input frame. fwhm : float Size in pixels of the FWHM. y, x...
71,186
def flip_es_aliases(): """Flip elasticsearch aliases to the latest version""" with cd(env.code_root): sudo('%(py3_virtualenv_root)s/bin/python manage.py ptop_es_manage --flip_all_aliases' % env)
71,187
def test_field_descriptor_abuse(): """Test field descriptor abuse.""" desc = FieldTest.__dict__['PublicField'] with pytest.raises(TypeError): desc.__get__(0, 0) with pytest.raises(TypeError): desc.__set__(0, 0)
71,188
def all_structures(data): """ Calculates all structures for the principal component projections. Runs k-means a number of times and saves the result with lowest distortion. :param data: Data set. """ images, pc_projections, pcs = data.pca.load() pc_projections_truncated = pc_projections[:,...
71,189
def clear_data_directory(): """ Clears entire data directory except for Tableau folder Directory path : module_progress/data """ root = os.path.dirname(os.path.abspath(__file__))[:-4] data_path = Path(f"{root}/data") for subdir in os.listdir(data_path): path = data_path / subdir ...
71,190
def IsInstance(type_): """Returns a function which can be used to check whether or not a value is of the given type.""" def Do(item): return isinstance(item, type_) return Do
71,191
def run_explainer(client, config, output, _): """Run explain commands. Args: client (iam_client.ClientComposition): client to use for requests. config (object): argparser namespace to use. output (Output): output writer to use. _ (object): Unused. """ ...
71,192
def random_proof_tree(rules_dict: RulesDict, root: int) -> Node: """Return random tree found by breadth first search.""" seen: Set[int] = set() root_node = Node(root) queue = deque([root_node]) while queue: v = queue.popleft() rule = choice(list(rules_dict[v.label])) if not (...
71,193
def PCreate (name, uvData, err): """ Create the parameters and underlying structures of a set of images. * name = Name to be given to object * uvData = Python uv data from which the image mosaic will be derived Most control parameters are in InfoList member * err = Pyt...
71,194
def add_log_stream_handler(log: logging.Logger) -> None: """ Creates and adds a handle for logging information to a stream. """ handler = logging.StreamHandler() handler.setLevel(logging.ERROR) formatter = logging.Formatter('%(funcName)s: %(message)s\n') handler.setFormatter(formatter) log.addHandler(handler)
71,195
def curret_platform() -> str: """Get current platform name by short string.""" if sys.platform.startswith('linux'): return 'linux' elif sys.platform.startswith('darwin'): return 'mac' elif sys.platform.startswith('win'): if sys.maxsize > 2 ** 31 - 1: return 'win64' ...
71,196
def test_variable_selection_lasso(): """Test basic functionality of UoI_Lasso and that it finds right model""" X, y, w = make_regression(coef=True, random_state=1) lasso = UoI_Lasso(comm=MPI.COMM_WORLD) lasso.fit(X, y) true_coef = np.nonzero(w)[0] fit_coef = np.nonzero(lasso.coef_)[0] assert...
71,197
def active_subspace(df, weights): """ TODO: docs """ df, M, m = process_inputs(df) # compute the matrix C = np.dot(df.transpose(), df * weights) return sorted_eigh(C)
71,198
def get_nq_report(complete_text): """ Given the complete submission text for an N-Q filing, parse the document and return its respective ReportNQ DTO object. """ lines = complete_text.split('\n') series_list = get_series_list(lines) accepted_date = get_accepted_date(lines) ...
71,199