content
stringlengths
22
815k
id
int64
0
4.91M
def group(spanins, prob_threshold, scope, valid_relation_set, mode): """ for each unary instance that is classified as being in a relation, get the other argument which is also classifier as being in the same relation but different role ner1/2: list of unary instances """ assert scope in ...
5,342,000
def simulate_until_target_substate_or_max_t( _simulate_until_attractor_or_target_substate_or_max_t, initial_state, perturbed_nodes_by_t, predecessor_node_lists, truth_tables): """ Perform simulation to figure whether it reaches target substate. Does not return states of simulations that don...
5,342,001
def test_generate_holiday_events3(): """Tests generate_holiday_events pre_post_num_dict parameter""" # Tests pre_post_num_dict countries = ["UnitedStates", "India"] year_start = 2019 year_end = 2020 holidays_to_model_separately = [ "New Year's Day", "Diwali", "Columbus Da...
5,342,002
def query_snpedia_online(rsid): """ @param soup: @param rsid: """ rsid = rsid.capitalize() url = "https://bots.snpedia.com/index.php" rsid_url = f"{url}/{rsid}" page = requests.get(rsid_url) soup = BeautifulSoup(page.content, "html.parser") columns, genotypes = parse_snpedia...
5,342,003
def test_warning_monitor_should_pass_disabled(make_data): """WarningCount should pass if the limit is negative.""" data = make_data({SPIDERMON_MAX_WARNINGS: -1}) runner = data.pop("runner") suite = new_suite() data["stats"]["log_count/WARNING"] = 99999 runner.run(suite, **data) assert runne...
5,342,004
async def get_session(client_id: str, client_secret: str) -> AuthToken: """ Use the Authorization Code Grant flow to get a token. This opens a browser tab. """ refresh_token_file = os.path.join(config.config_dir(), '.refresh.token') base_url = 'https://bitbucket.org/site/oauth2' # If we ha...
5,342,005
def lower(value: str): # Only one argument. """Converts a string into all lowercase""" return value.lower()
5,342,006
def main(): """This function implements the command-line interface.""" # Parse input configuration. year = argv[2] assert year in ("dry_run", "dev", "2016", "2017") config = argv[1].split('-', 8) technique_string = config[0] assert technique_string in ("hard_terms", "soft_terms", "hard_topic...
5,342,007
def validate_oidc(): """Demonstrates how an access token is validated""" token = request.headers['Authorization'].split(' ')[1] message = check_oidc_token(token) pprint.pprint(message) return jsonify({ 'success': message['success'] })
5,342,008
def merge(a, b, path=None): """From https://stackoverflow.com/a/7205107""" if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge(a[key], b[key], path + [str(key)]) elif a[key] == b[key]: ...
5,342,009
def norm_sq(f,alpha,n,L_mat_long,step): """ This function is the log-likelihood functional with the squared L2 norm of \hat{f_\beta} as the regularization term. """ L_mat=L_mat_long.reshape(n,len(f)) f[f <=0] = 1e-6 val=np.log(np.dot(L_mat,f)) return -sum(val)/n+ alpha*step**2*sum(f**2)
5,342,010
def get_applications(device_id: str = None, rpc_channel: InstrumentServer = None): """ 获取手机应用列表 :param device_id: :param rpc_channel: :return: """ if not rpc_channel: _rpc_channel = init(device_id) else: _rpc_channel = rpc_channel application_list = _rpc_channel.call(...
5,342,011
def test_get_notification_id(): """ """ single_notification = notifications.get_notifications( TOKEN, customerid=CUSTOMERID, limit=1) check_id = '-'.join(single_notification[0]['_id'].split('-')[0:2]) result = notifications.get_notifications( TOKEN, customerid=CUSTOMERID, check_id=...
5,342,012
def open_mfdataset(files, use_cftime=True, parallel=True, data_vars='minimal', chunks={'time':1}, coords='minimal', compat='override', drop=None, **kwargs): """optimized function for opening large cf datasets. based on https://github.com/pydata/xarray/issues/1385#issuecomment-561920115 ...
5,342,013
def wls_sparse(X, y, w=1., calc_cov=False, verbose=False, **kwargs): """ Parameters ---------- X y w calc_cov verbose kwargs Returns ------- """ # The var returned by ln.lsqr is normalized by the variance of the error. To # obtain the correct variance, it needs...
5,342,014
def _paginate(api, paginated_object): """ The autogenerated client does not support pagination. This function returns a generator over all items of the array that the paginated object `paginated_object` is part of. """ yield from paginated_object.values typename = type(paginated_object).__name__...
5,342,015
def register_module(): """Registers this module for use.""" def on_module_disable(): tags.Registry.remove_tag_binding(MathTag.binding_name) def on_module_enable(): tags.Registry.add_tag_binding(MathTag.binding_name, MathTag) global_routes = [ (RESOURCES_URI + '/.*', tags.Resou...
5,342,016
def sobel_gradients(source: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """ Computes partial derivations to detect angle gradients. """ grad_x = generic_filter(source, np.matrix([ [1, 0, -1], [2, 0, -2], [1, 0, -1]] )) grad_y = generic_filter(source, np.matrix([ ...
5,342,017
def flat_dict(d, prefix=""): """ Loop through dictionary d Append any key, val pairs to the return list ret Add the prefix to any key param Recurse if encountered value is a nested dictionary. """ if not isinstance(d, Mapping): return d ret = {} for key, val in d.items(): ...
5,342,018
def feature_normalization(train, test): """Rescale the data so that each feature in the training set is in the interval [0,1], and apply the same transformations to the test set, using the statistics computed on the training set. Args: train - training set, a 2D numpy array of size (num_instanc...
5,342,019
def _get_filehandler_with_formatter(logname, formatter=None): """ Return a logging FileHandler for given logname using a given logging formatter :param logname: Name of the file where logs will be stored, ".log" extension will be added :param formatter: An instance of logging.Formatter or None if th...
5,342,020
def extract_and_save(file_path: str, start: int = 0, stop: int = -1, interval: int = 1): """Extract frames and then save them to a directory. Args: file_path (str): [description] start (int, optional): [description]. Defaults to 0. stop (int, optional): [description]. Defaults to -1. ...
5,342,021
def gen_data_tensors( df: pd.DataFrame, lag: int = 6, batch_size: int = 32, validation_ratio: float = 0.2 ) -> (DataLoader, DataLoader, TensorDataset, TensorDataset): """ Primary goal: create dataloader object. """ x_train, y_train = generate_supervised(df, lag=lag) # Transform DataF...
5,342,022
def staff_for_site(): """ Used by the Req/Req/Create page - note that this returns Person IDs """ try: site_id = request.args[0] except: result = current.xml.json_message(False, 400, "No Site provided!") else: table = s3db.hrm_human_resource ptable = ...
5,342,023
def element_z(sym_or_name): """Convert element symbol or name into a valid element atomic number Z. Args: sym_or_name: string type representing an element symbol or name. Returns: Integer z that is a valid atomic number matching the symbol or name. Raises: ElementZError: if the symb...
5,342,024
def to_int(s: str) -> Tuple[bool, int]: """Convert a string s to an int, if possible.""" try: n = int(s) return True, n except Exception: return False, 0
5,342,025
def out2garf(outcar='OUTCAR', poscar='POSCAR', nframes=100, intv=5,\ refstructure=['POSCAR', '0.0'], samplename='POSCAR'): """ """ # read POSCAR fname, scaling, lattice, \ symbols, numbers, atoms, refpos, fixes = read_poscar(poscar) natoms = np.sum(numbers) lx, ly, lz, alpha...
5,342,026
def simple_computation(maximum_terms:int=None, configuration_of=None): """ Simple 4-operand computations 移除了分数项,因为除法运算会表示为分数 禁用了括号(random_term的expression参数),因为会导致溢出 :return: Problem object """ if not configuration_of: configuration_of = 'simple_computation' func_config = combine_...
5,342,027
def add_torrents_from_folder(path, transmission_url, torrentleech_username, torrentleech_password, torrentleech_rss_key): """Console script for media_server_utils.""" core.add_torrents_from_folder(path, transmission_url, torrentleech_username, torrentleech_password, torrentleech_rss_key) return 0
5,342,028
def cut_graph(G, w): """ Cut a graph down to a given depth Inputs: - G Input graph - w Depth to cut to Output: - cut_G Cut graph """ # Copy the initial graph and get the number of nodes cut_G = G.copy() N = len(G.nodes) # Check all ...
5,342,029
def archive_filter_search(articles_qs): """ gets the qs and filters and sends back to the hook for rendering. """ return articles_qs.exclude(updates__article__stage=STAGE_PUBLISHED)
5,342,030
def init_plotscript(config, markets: List, startup_candles: int = 0): """ Initialize objects needed for plotting :return: Dict with candle (OHLCV) data, trades and pairs """ if "pairs" in config: pairs = expand_pairlist(config['pairs'], markets) else: pairs = expand_pairlist(con...
5,342,031
def get_one(data: List[LogEntry], filterfun: Callable) -> LogEntry: """Get a single entry and assert that after filtering only a single entry remains.""" filtered = list(filter(filterfun, data)) if len(filtered) != 1: raise ValueError(f"Entries not unique after filtering: {filtered}") return...
5,342,032
def parse_ignorelist(f): # type: (IO[Text]) -> Tuple[Ignorelist, Set[Text]] """ Parse the ignorelist file given by `f`, and return the parsed structure. :returns: a tuple of an Ignorelist and a set of files that are completely skipped by the linter (i.e. have a '*' entry). """ da...
5,342,033
async def async_setup_entry(opp, config_entry, async_add_entities): """Add binary sensors for a config entry.""" broker = opp.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] sensors = [] for device in broker.devices.values(): for capability in broker.get_assigned(device.device_id, "binary_sens...
5,342,034
def create(env_name: str, episode_length: int = 1000, action_repeat: int = 1, auto_reset: bool = True, batch_size: Optional[int] = None, **kwargs) -> Env: """Creates an Env with a specified brax system.""" env = _envs[env_name](**kwargs) if episode_length is ...
5,342,035
def from_software_version(software_version): """ Returns the product version dependant limits_constants. This is based on the running software version on the product and can change based on up when you ask a cluster if upgrading. Args: software_version: (str) software version ex "3.1.2.0" o...
5,342,036
def _from_parse_feature(parse_feature): """Convert a single feature spec to a ColumnSchema.""" # FixedLenFeature if isinstance(parse_feature, tf.FixedLenFeature): representation = FixedColumnRepresentation(parse_feature.default_value) return ColumnSchema(parse_feature.dtype, parse_feature.shape, ...
5,342,037
def conditional_patch_resource( service_account_json, base_url, project_id, cloud_region, dataset_id, fhir_store_id ): """ If a resource is found based on the search criteria specified in the query parameters, updates part of that resource by applying the operations specified in a JSON Patch documen...
5,342,038
def setup_virtualenvs(recreate_virtualenvs=False): """ Setup Python virtual environments for all the registered or the provided pack. """ LOG.info("=========================================================") LOG.info("########### Setting up virtual environments #############") LOG.info("=======...
5,342,039
def cal_big_F(p, f): """ calculate finite strain big F for linearized form not fully tested :param p: pressure :param f: small f :return: big F """ return p / (3. * f * np.power((1. + 2. * f), 2.5))
5,342,040
def multiply_aug(data_aug: List[str], factor: int) -> List[str]: """ The original idea here was to use to to speed up some vasp calculations for supercells by initializing the entire CHGCAR file. The current code does not deal with transformation of the Augemetation charges after regridding. This i...
5,342,041
def _parse_instance_chain(chain_str): """ 返回对象链解析出来的实例对象。""" chain = chain_str.split('.') instance_name = chain.pop(0) attr = session['instances'][instance_name] for attr_name in chain: attr = getattr(attr, attr_name) return attr
5,342,042
def epochs_lists( draw, start_time=math.inf, max_epochs=5, min_deme_size=FLOAT_EPS, max_deme_size=FLOAT_MAX, ): """ A hypothesis strategy for creating lists of Epochs for a deme. :param float start_time: The start time of the deme. :param int max_epochs: The maximum number of epochs...
5,342,043
def mlp_layers(nch_input, nch_layers, b_shared=True, bn_momentum=0.1, dropout=0.0): """ [B, Cin, N] -> [B, Cout, N] or [B, Cin] -> [B, Cout] """ layers = [] last = nch_input for i, outp in enumerate(nch_layers): if b_shared: weights = torch.nn.Conv1d(last, outp, 1...
5,342,044
def get_imagenet_iterator(root, batch_size, num_workers, data_shape=224, dtype="float32"): """Dataset loader with preprocessing.""" train_dir = os.path.join(root, "train") train_transform, val_transform = get_imagenet_transforms(data_shape, dtype) logging.info("Loading image folder %s, this may take a b...
5,342,045
def path_content_to_string(path): """Convert contents of a directory recursively into a string for easier comparison.""" lines = [] prefix_len = len(path + sep) for root, dirs, files in walk(path): for dir_ in dirs: full_path = join(root, dir_) relative_path = full_path[p...
5,342,046
def get_evts(rslt, a_params): """Return start and end times of candidate replay events.""" # get PC firing rates ## PC spks spks_pc = rslt.spks[:, :rslt.p['N_PC']] ## smoothed instantaneous firing rate avg'd over PCs fr_pc = smooth(spks_pc.sum(axis=1) / (rslt.dt * rslt.p['N_PC']), a_params[...
5,342,047
def plot_many_saliency_maps( saliency_matrix, axes_objects_2d_list, colour_map_object, max_absolute_contour_level, contour_interval, line_width=2): """Plots 2-D saliency map for each predictor. M = number of rows in grid N = number of columns in grid C = number of predictors :param...
5,342,048
def get_threatfeed_command(client: Client, threatfeed_id: int = None): """ Retrieves the current list of threatFeed objects already configured in the system :param threatfeed_id: The id of the ThreatFeed object. :param client: Vectra Client """ raw_response = client.http_request(url_suffix=f'th...
5,342,049
def email_subscribe_pending_confirm(hexdomain): """Send a confirmation email for a user.""" domain = tools.parse_domain(hexdomain) if domain is None: flask.abort(400, 'Malformed domain or domain not represented in hexadecimal format.') hide_noisy = bool(flask.request.form.get('hide_noisy')) ...
5,342,050
def main(): """ Do some stuff """ args = get_args() si = vmware_lib.connect(args.host, args.user, args.password, args.port, args.insecure) content = si.RetrieveContent() if args.folder: folder = vmware_lib.get_obj(content, [vmware_lib.vim.Folder], args.folder) for vm in fol...
5,342,051
def create_zip_hsa_hrr_crosswalk(): """Creates the crosswalk table from ZIP to HSA and from ZIP to HRR from source.""" zipped_csv = ZipFile(BytesIO(requests.get(ZIP_HSA_HRR_URL).content)) zip_df = pd.read_csv(zipped_csv.open(ZIP_HSA_HRR_FILENAME)) # Build the HSA table hsa_df = zip_df[["zipcode18",...
5,342,052
def set_state(state='stop', profile_process='worker'): """Set up the profiler state to 'run' or 'stop'. Parameters ---------- state : string, optional Indicates whether to run the profiler, can be 'stop' or 'run'. Default is `stop`. profile_process : string whether to profil...
5,342,053
def getTrackIds(sp, username, playlist, offset=0): """ Returns the ids of the tracks contained in a playlist :param sp: A spotipy.Spotify object to be used for the request. :param username: The username of the user who's playlists you want the retrieve. :param playlist: Na...
5,342,054
def children_of_head(element: Element): """ get children element of body element :param element: :return: """ if element is None: return [] body_xpath = '//head' body_element = element.xpath(body_xpath) if body_element: body_element.__class__ = Element return ...
5,342,055
def network(name, nodes): """nodes: [ NodeMeta, ... ]""" return NetworkMeta(name=name, nodes=nodes)
5,342,056
def condensed_to_cosine(condensed_format): """Get mhd direction cosine for this condensed format axis""" axis = Axis.from_condensed_format(condensed_format) return permutation_to_cosine(axis.dim_order, axis.dim_flip)
5,342,057
def get_plants_for_species(item): """Get list of plants for a species.""" if item is None or not item or item['name'] is None: return @cached('species_list_{}.json'.format(item['name']), directory='../../data/wikipedia') def get(): def table(dom): # We need to sw...
5,342,058
def check_password_hash(password, password_hash, salt, N=1 << 14, r=8, p=1, buflen=64): """ Given a password, hash, salt this function verifies the password is equal to hash/salt. Args: - ``password``: The password to perform check on. Returns: - ``bool`` """ candidate_hash = gen...
5,342,059
def _dB_calc(J_field, x, y, z): """ Calcualtes the magnetic field at a point due to a current. Args: J_field (VectorField): Vector field describing the current that the magnetic field is generated from. x: The x coordinate of the point in the magnetic field. y: The y coordinate of the point in the magnet...
5,342,060
def fixture_handler() -> Generator[MagicMock, None, None]: """Mock all calls, assert calling correct handler""" with patch.object(api, "handler") as handler: handler.get_all_characters = MagicMock() handler.get_inventory = MagicMock() handler.character_search = MagicMock() yield ...
5,342,061
def make_change(amount, denominations, index=0): """ Write a function that, given: 1. an amount of money 2. a list of coin denominations computes the number of ways to make the amount of money with coins of the available denominations. >>> make_change(amount=4, denominations=[1,2,3]) 4 ...
5,342,062
def _CaptureStdErr(result_holder, output_message=None, raw_output=None): """Update OperationResult either from OutputMessage or plain text.""" if not result_holder.stderr: result_holder.stderr = [] if output_message: if output_message.body: result_holder.stderr.append(output_message.body) if out...
5,342,063
def create_mpl_subplot(images, color=True): """create mpl subplot with all images in list. even when the color is set to false it still seems to :param images: the list of images to plot :type images: cv2 image :param color: whether to plot in color or grayscale, defaults to True :type color: ...
5,342,064
def filter_subclasses(superclass, iter): """Returns an iterable of class obects which are subclasses of `superclass` filtered from a source iteration. :param superclass: The superclass to filter against :return: An iterable of classes which are subclasses of `superclass` """ return filter(lambda kl...
5,342,065
def get_database_table_column_name(_conn: psycopg2.extensions.connection, _table: str) -> list: """ Taken from: https://kb.objectrocket.com/postgresql/get-the-column-names-from-a-postgresql-table-with-the-psycopg2-python-adapter-756 # noqa defines a function that gets...
5,342,066
def retry(*exceptions, retries=3, cooldown=5, verbose=True): """ Decorate an async function to execute it a few times before giving up. Hopes that problem is resolved by another side shortly. Args: exceptions (Tuple[Exception]) : The exceptions expected during function execution retries ...
5,342,067
def process_student(filename_or_URL): """calls mark_student on one student HTML file Creates a BeautifulSoup object and calls mark_student. If the filename_or_URL starts with "https://", attempt to get Firefox cookies before reading from the URL. Parameters: ---------- filename_or_URL: ei...
5,342,068
def find_CH2OH_in_chain(atoms, cycles): """ this function finds terminal CH2OH that C is not in a cycle H ' O(6) ' H ' / R---C(5)---H """ end_carbon_indices = [] end_carbon_indices_atom_list...
5,342,069
def get_gradient_descent_query(COO=True, parameter=None): """ Generates the query for solving the logistic regression problem :param COO: boolean indicating if the data are in the C00 format :param parameter: dictionary containing number of iterations, features, regularization parameter and step width ...
5,342,070
def keep_point(p, frame): """ p: TrackedPoint instance frame: image (numpy array) """ if not p.in_bounds(): return False if p.coasted_too_long(): return False if p.coasted_too_far(): return False return True
5,342,071
def sqrt(node: NodeWrapper, params: Dict[str, np.ndarray], xmap: Dict[str, XLayer]) -> List[XLayer]: """ONNX Sqrt to XLayer Sqrt conversion function""" logger.info("ONNX Sqrt -> XLayer Sqrt") assert len(node.get_outputs()) == 1 name = node.get_outputs()[0] bottoms = node.get_input...
5,342,072
def get_testcase_desc(suite, testcase_name): """ Return the description of the testcase with the given name of the given testsuite. Remove trailing line returns if applicable, they look nasty in the reports (text and otherwise) """ desc = getattr(suite, testcase_name).__doc__ return str...
5,342,073
def slave_freq_one_pc(args): """Wrapper to be able to use Pool""" return args, freq_one_pc(*args)
5,342,074
def base10_to_base26_alph(base10_no): """Convert base-10 integer to base-26 alphabetic system. This function provides a utility to write pdb/psf files such that it can add many more than 9999 atoms and 999 residues. Parameters ---------- base10_no: int The integer to convert to base-26...
5,342,075
def train(model, X, y, name: str): """ train a model on the given training set and optionally save it to disk :param model: the model to train :param X: the sample images, list of numpy arrays (greyscale images) :param y: the target labels, list of strings (kanji) :param name: name of the model ...
5,342,076
def create_heterodyne_parser(): """ Create the argument parser. """ description = """\ A script to heterodyne raw gravitational-wave strain data based on the \ expected evolution of the gravitational-wave signal from a set of pulsars.""" parser = BilbyArgParser( prog=sys.argv[0], d...
5,342,077
def run_phage_boost(genecalls, model_file, verbose): """ Run phage boost :param model_file: The model file that is probably something like model_delta_std_hacked.pickled.silent.gz :param genecalls: The pandas data frame of gene calls :param verbose: more output :return: """ # rolling par...
5,342,078
def get_wishlist_confirmation_time(): """Return whether user can confirm his wishlist or not No request params. """ try: confirmation_time = g.user.get_wishlist_confirmation_time() can_confirm = datetime.now() - confirmation_time > timedelta( days = 1 ) if confirmation_time is not None ...
5,342,079
def logInfo(msg): """ info """ log_msg("INFO", msg)
5,342,080
def get_bprop_npu_clear_float_status(self): """Grad definition for `NPUClearFloatStatus` operation.""" def bprop(x, out, dout): return (zeros_like(x),) return bprop
5,342,081
def path_to_filename(path, with_suffix=True): """Get filename from path. Parameters ========== path : str Path to retrieve file name from e.g. '/path/to/image.png'. with_suffix : bool Whether to include the suffix of file path in file name. Returns ======= str ...
5,342,082
def encode3(Married): """ This function encodes a loan status to either 1 or 0. """ if Married == 'Yes': return 1 else: return 0
5,342,083
def pool_init_price(token0, token1, tick_upper, tick_lower, liquidity_delta, token0_decimals, token1_decimals): """ TODO: finish documentation :param token0: :param token1: :param tick_upper: :param tick_lower: :param liquidity_delta: Can get from etherscan.io using the t...
5,342,084
def rle_encoding(img, mask_val=1): """ Turns our masks into RLE encoding to easily store them and feed them into models later on https://en.wikipedia.org/wiki/Run-length_encoding Args: img (np.array): Segmentation array mask_val (int): Which value to use to create the RLE Returns: ...
5,342,085
def alt(*ops, priority=False, default=_Undefined): """ alt(*ops, priority=False, default=Undefined) Returns an awaitable representing the first and only channel operation to finish. Accepts a variable number of operations that either get from or put to a channel and commits only one of them. If no...
5,342,086
def make_class_dictable( cls, exclude=constants.default_exclude, exclude_underscore=constants.default_exclude_underscore, fromdict_allow_pk=constants.default_fromdict_allow_pk, include=None, asdict_include=None, fromdict_include=None, ): """Make a class dictable Useful for when the ...
5,342,087
def async_request_config( hass, name, callback=None, description=None, description_image=None, submit_caption=None, fields=None, link_name=None, link_url=None, entity_picture=None, ): """Create a new request for configuration. Will return an ID to be used for sequent cal...
5,342,088
def get_latest_active_table_version( namespace: str, table_name: str, *args, **kwargs) -> Optional[TableVersion]: """ Gets table version metadata for the latest active version of the specified table. Returns None if no active table version exists for the given table. """ ...
5,342,089
def get_blueprint_docs(blueprints, blueprint): """Returns doc string for blueprint.""" doc_string = blueprints[blueprint].__doc__ return doc_string
5,342,090
def check_capability( instance: Any, # pylint: disable=W0613 attribute: attr.Attribute, value: Union[str, List[str]], ) -> None: """Validator that ensures capability has a valid input. Parameters ---------- instance : Any A class object. attribute : attr.Attribute The a...
5,342,091
def getColorPalatte(image, num, show_chart=False): """ Returns the most prevelent colors of an image arguments: image - image to sample colors from num - number of colors to sample show_chart - show a visual representation of the colors selected """ modified_image = np.array(image) ...
5,342,092
def run_classifier(data,labels, shuffle=False,nfolds=8,scale=True, clf=None,verbose=False): """ run classifier for a single dataset """ features=data if scale: features=sklearn.preprocessing.scale(features) if shuffle: numpy.random.shuffle(labels) if not clf...
5,342,093
def merge_sort(linked_list): """ Sorts a linked list in ascending order - Recursively divide the linked list into sublist containing a single node - Repeatedly merge the sublist to produce sorted sublist until one remains Returns a sorted linked list Takes O(kn log n) time """ if...
5,342,094
def is_binary(file_path): """ Returns True if the file is binary """ with open(file_path, 'rb') as fp: data = fp.read(1024) if not data: return False if b'\0' in data: return True return False
5,342,095
def convert_host_names_to_ids(session, instanceList): """Look up ID of each instance on Amazon. Returns a list of IDs.""" idList = [] for i in instanceList: instId = aws.instanceid_lookup(session, i) if instId is not None: idList.append(instId) return idList
5,342,096
def plotants(vis, figfile): """Plot the physical layout of the antennas described in the MS. vis (str) Path to the input dataset figfile (str) Path to the output image file. The output image format will be inferred from the extension of *figfile*. Example:: from pwkit.environmen...
5,342,097
def handle_over_max_file_size(error): """ Args: error: Returns: """ print("werkzeug.exceptions.RequestEntityTooLarge" + error) return 'result : file size is overed.'
5,342,098
def main(): """main""" parser = argparse.ArgumentParser() parser.add_argument("--cuda", action="store_true") parser.add_argument("--num_cuda", type=int, default=1) parser.add_argument("--modality_name", nargs="+", default=["mmt"]) parser.add_argument("--data_save", type=s...
5,342,099