content
stringlengths
22
815k
id
int64
0
4.91M
def knn_assigned_text_sectors( run: Optional[Run] = None, clustered: bool = True, ): """the text sectors of the K nearest neighbours after reassignment""" run = run or get_run("ClusterReassignFlow") if clustered: return run.data.knn_assigned_text_sectors else: return run.data.knn...
59,900
def get_hashed_combo_path( root_dir: str, subdir: str, task: str, combos: Iterable[Union[List[str], Tuple[str, str]]], ) -> str: """ Return a unique path for the given combinations of models. :param root_dir: root save directory :param subdir: immediate subdirectory of root_di...
59,901
def arma_forecast(time_series, phis=array([]), thetas=array([]), mu=0., sigma=1., future_periods=20): """ Return forecasts for a time series modeled with the given ARMA model. Parameters ---------- time_series : ndarray of shape (n,1) The time series in question phis : ndarr...
59,902
def sign_assertion(root, cert1, cert2, key): """Sign the SAML assertion in the response using the IdP key""" try: print('[*] Signing the SAML assertion') assertion_id = root.find("{urn:oasis:names:tc:SAML:2.0:assertion}Assertion").get("ID") signer = XMLSigner(c14n_algorithm="http://www.w...
59,903
def snoop(handler, protocol=None): """Watch for SLP activity handler will be called with a dictionary of relevant attributes :param handler: :return: """ tracelog = log.Logger('trace') try: active_scan(handler, protocol) except Exception as e: tracelog.log(traceback...
59,904
def select_polynomial_degree(n_samples: int = 100, noise: float = 5): """ Simulate data from a polynomial model and use cross-validation to select the best fitting degree Parameters ---------- n_samples: int, default=100 Number of samples to generate noise: float, default = 5 N...
59,905
def remove(*name: str): """Remove a test with variadic argument. :param name: tests to remove """ if name in container: container.remove(remove) _reprint(**locals())
59,906
def poweriter(A,numiter): """ poweriter(A,numiter) Perform `numiter` power iterations with the matrix `A`, starting from a random vector, and return a vector of eigenvalue estimates and the final eigenvector approximation. """ n = A.shape[0] x = randn(n) x = x/norm(x,Inf) gamma = zeros(numiter) for k in range...
59,907
def check_linked_data(folders_target, folder_link, source_code_path="", is_pass=False): """Generate folder as hard linked of the given folder paths or provider main folder. :param folders_target: iterates all over the given folders :param folder_link: linked folders_to_share into into given path """ ...
59,908
def opendata_postal_codes_v1(db): """ API v1 data postal codes route. Example:: GET /api/v1/opendata/postal_codes .. note:: Filtering can be done through the ``filter`` GET param, according to JSON API spec (http://jsonapi.org/recommendations/#filtering). .. note:: ...
59,909
def get_valid_group(id, name): """ Returns a valid group object """ group = Group() group.id = id group.name = name return group
59,910
def test_permute_systems_m2_m2(): """Permute system for perm = [2,1] and dim = [2, 2].""" test_input_mat = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) expected_res = np.array([[1, 3, 2, 4], [9, 11, 10, 12], [5, 7, 6, 8], [13, 15, 14, 16]]) res = permute_systems(test_input...
59,911
def test_operator_aws_ec2_meta(monkeypatch, tmpdir): """Verify the operator call works successfully.""" monkeypatch.chdir(os.path.abspath(os.path.dirname(__file__))) context = cookiecutter('.', no_input=True, output_dir=str(tmpdir)) assert len(context['instance_types']) > 1
59,912
def svn_repos_authz_check_access(*args): """ svn_repos_authz_check_access(svn_authz_t authz, char repos_name, char path, char user, svn_repos_authz_access_t required_access, apr_pool_t pool) -> svn_error_t """ return _repos.svn_repos_authz_check_access(*args)
59,913
def mark_for_testing(**kwargs): """Mark module for testing.""" def decorator(cls): _MARKED_CLASSES.append(MarkedClass(cls, **kwargs)) return cls return decorator
59,914
async def test_receive_iter(subject: CanDriver, can_bus: Bus) -> None: """It should receive messages using iterator.""" m = [ Message( arbitration_id=0x1FFFFFFF, is_extended_id=True, is_fd=True, data=bytearray([1, 2, 3, 4]), ), Message( ...
59,915
def load_ref_system(): """ Returns propane as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" H 1.9131 -0.1215 1.0479 C 1.2683 -0.0636 0.1619 H 1.5702 0.8259 -0.4068...
59,916
def make_test_time_old() -> context.Time: """Generates unix timestamp for an old date.""" return test_context.TestTime(calendar.timegm(datetime.date(1970, 1, 1).timetuple()))
59,917
def get_stream_inventory_report_link_for_region(point: Point): """ Returns Fish Inventory Data Query (FIDQ) links for streams within this watershed area. """ point_3005 = transform(transform_4326_3005, point) # look up region that this point is in cql_filter = f"""INTERSECTS(SHAPE, {point_3...
59,918
def baymodel_data_with_missing_flavor(): """Generates random baymodel data with missing flavor :returns: BayModelEntity with generated data """ return baymodel_data(keypair_id=config.Config.keypair_id, image_id=config.Config.image_id)
59,919
def run_intcode(memory, input_list, instr_ptr=0, input_ptr=0, previous_output=None): """Run an Intcode program from memory""" output = previous_output while instr_ptr < len(memory): instruction = memory[instr_ptr] digits = list_digits(instruction) # extract opcode opcode_pai...
59,920
def evaluate_recovered_param(ck, tk, ck_hat, tk_hat, viz=False, figsize=None, fontsize=20, t_max=None): """ Compute L2 error for recovered amplitude and locations parameters. In this function, we simply sort in increasing time order. A better metric (in a later notebook) would compare pulses that...
59,921
def get_engine_sampler(processor_id: str, gate_set_name: str, project_id: Optional[str] = None) \ -> 'cirq.google.QuantumEngineSampler': """Get an EngineSampler assuming some sensible defaults. This uses the environment variable GOOGLE_CLOUD_PROJECT for the Engine project_id,...
59,922
def frequency_sampling_paragraph(thief_vocab, thief_probs, para_len=None): """Sample words according to a unigram frequency to build a paragraph.""" if para_len is None: # randomly choose a length from 75 to 500 para_len = np.random.randint(75, 500) assert len(thief_probs) == len(thief_vocab) bow_para ...
59,923
def cast_cadastro_cliente(): """ Função que acessa os itens do arquivo bd_cliente_rotativo em modo read e, faz o append dos dados para a lista_cadastro para iteração. :return: Condição que informa que não existe nenhum veiculo cadastrada para iterar """ try: with open('bd_cadastro_clien...
59,924
def load(dir_path, DB): """ Run the plugin loader on processed plugins :param dir_path: :param DB: """ log.info("Finding plugins in directory {0}".format(dir_path)) plugins = [os.path.join(dir_path, module_path) for module_path in os.listdir(dir_path)] log.info("F...
59,925
def test_gal_class(): """ In this test, we just want to ensure that the Galaxy class can be instantiated. Easiest test ever but still could be useful! """ gal = galaxy.Galaxy(0.5, -21.5, -20) assert(gal.x == 0.5) assert(gal.y == -21.5) #assert(gal.z == 142.4) assert(gal.mass == -20...
59,926
def generate_pool_name(**kwargs): """Generate a pool name. This function takes keyword arguments, usually the connection arguments and tries to generate a name for the pool. Args: **kwargs: Arbitrary keyword arguments with the connection arguments. Raises: PoolError: If the name c...
59,927
def cluster_domain_DBScan( x: np.ndarray, y: np.ndarray, time: np.ndarray, ) -> np.ndarray: """ return the cluster ID based on the given data using DBScan @param x: event position x vector @param y: event position y vector @param time: event TOA vector @returns: clustering results ...
59,928
def svcomp_frontend(input_file, args): """Generate Boogie code from SVCOMP-style C-language source(s).""" # enable static LLVM unroll pass args.static_unroll = True # attempt to rewrite bitwise ops into provided models args.rewrite_bitwise_ops = True # Modeling of strings must be turned on by default a...
59,929
def test_bias_hessian(random_vp=10): """Check correct backpropagation of bias Hessian and HVP.""" layer, x, out, loss = layer_with_input_output_and_loss() # Hessian of loss function w.r.t layer output output_hessian = batch_summed_hessian(loss, out) loss.backward() layer.backward_hessian(output_...
59,930
def retrofit_neural(X, in_edges, out_edges, k=5, n_iter=100, alpha=None, beta=None, tol=1e-2, lr=0.5, lam=1e-5, verbose=0, lr_decay=0.9, batch_size=32, patience=20): """ Retrofit according to the neural penalty function. Parameters ---------- X : np.arra...
59,931
def fake_create_test_db(self, verbosity=1, autoclobber=False): """Simplified version of BaseDatabaseCreation.create_test_db.""" test_database_name = self._get_test_db_name() if verbosity >= 1: test_db_repr = '' if verbosity >= 2: test_db_repr = " ('%s')" % test_database_name ...
59,932
def exportMaps(): """Exports the Map layers as JSON.""" mapsGroup = QgsProject.instance().layerTreeRoot().findGroup('Maps') if not mapsGroup: QMessageBox.information(None, 'QgsOpenScope', 'Couldn\'t find any Map layers.') return layers = list(map(lambda x: x.layer(), mapsGroup.children...
59,933
def value_from_choices_label(label, choices): """ Return the choices value for a given label """ # Search choices by label result = None for choices_value, choices_label in choices: if label == choices_label: result = choices_value # If search by label failed, check if we...
59,934
def find_nearest_kp_2d(pcl2d, kps2d): """ find nearest 2d distance keypoint for every point in pcl. :param pcl2d: [N,2] N points' xyz :param kps2d: [K,2] K points' xyz :return: nearest_kps2d [N,2] Nearest keypoint coordinate of every points. """ N, _ = pcl2d.shape K, _ = kps2d.shape ...
59,935
def get_trace_data_from_device(client): """Get the trace data using RPC from a Client""" data = b'' service = client.client.channel(1).rpcs.pw.trace.TraceService result = service.GetTraceData().responses for streamed_data in result: data = data + bytes([len(streamed_data.data)]) data...
59,936
def servedocs(ctx): """Compile the docs watching for changes.""" ctx.run(f"{PIPENV_RUN} watchmedo shell-command -p '*.rst' -c 'make -C docs html' -R -D .")
59,937
def make_word(parts, sub, i): """Replace a syllable in a list of words, and return the joined word.""" j = 0 for part in parts: for k in range(len(part)): if i == j: part[k] = sub return ' '.join(''.join(p for p in part) for part in parts) j +=...
59,938
def calc_anchors_pillar_center(proposals, l=7, h=7, w=7, anchor_offset=[0.5, 0.5, 0.5]): """ calc the proposals' center location of each grid proposals: [bs, 6]: [xmin, xmax, ymin, ymax, zmin, zmax] return: anchors_pillars: [batch_size, l, h, w, 3] """ proposal_unstack = tf.unstack(pro...
59,939
def acq_max(ac, gp, y_max, bounds, random_state, n_warmup=10000, n_iter=10): """ A function to find the maximum of the acquisition function It uses a combination of random sampling (cheap) and the 'L-BFGS-B' optimization method. First by sampling `n_warmup` (1e5) points at random, and then running ...
59,940
def number_negatives(seq): """Number of negative residues a protein sequence""" # Convert sequence to upper case seq = seq.upper() for aa in seq: if aa not in bootcamp_utils.aa.keys(): raise RuntimeError(aa + ' is not a valid amino acid.') # Count E's and D's, since these are t...
59,941
def validate_key_csr(privkey, csr=None): """Validate Key and CSR files. Verifies that the client key and csr arguments are valid and correspond to one another. This does not currently check the names in the CSR due to the inability to read SANs from CSRs in python crypto libraries. If csr is left ...
59,942
def dcmread_scale(fn): """Transform from path of raw pixel data to scaled one and inversing (if the case)""" dcm = dcmread(fn) return dcm_scale(dcm)
59,943
def parse(lines): """ Parse a list of lines from nose output. :param lines: list of nose error output lines. :returns: nose output augmented with specially formatted lines adapted to this plugin errorformat which will populate Vim clist. """ results = [] lines = iter(lines) fa...
59,944
def total_size(obj): """Returns the approximate total memory footprint an object.""" seen = set() def sizeof(current_obj): try: return _sizeof(current_obj) except Exception: # pylint: disable=broad-except # Not sure what just happened, but let's assume it's a reference. return struct.ca...
59,945
def attr_lt(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: attr_gt(attrname, 54) Only true if access_obj's attribute < the value given. """ return attr(accessing_obj, accessed_obj, *args, **{'compare':'lt'})
59,946
def format_col(df, col_name, rounding=0, currency=False, percent=False): """Function to format numerical Pandas Dataframe columns (one at a time). WARNING: This function will convert the column to strings. Apply this function as the last step in your script. Output is the formatted column. Parameters...
59,947
def client_send_msg_via_interface(iface, addr, msgname): """ This step actually build message (e.g. SOLICIT) with all details specified in steps like: Client sets (\w+) value to (\S+). Client does include (\S+). and others.. Message builded here will be send in step: Server must response wit...
59,948
def slice_signal(signal, window_size, stride=0.5): """ Return windows of the given signal by sweeping in stride fractions of window """ assert signal.ndim == 1, signal.ndim n_samples = signal.shape[0] offset = int(window_size * stride) slices = [] for beg_i, end_i in zip(range(0, n_s...
59,949
def create_mysql_oursql(username, password, host, port, database, **kwargs): # pragma: no cover """ create an engine connected to a mysql database using oursql. """ return create_engine( _create_mysql_oursql(username, password, host, port, database), **kwargs )
59,950
def post_primary(user: User, number: str) -> FluxData: """ view to mark one of the (verified) phone numbers of the logged in user as the primary phone number. Returns a listing of all phones for the logged in user. """ proofing_user = ProofingUser.from_user(user, current_app.private_userdb) ...
59,951
def does_nothing(profile): """ evaluate if the profile is just doing nothing to the loss. this allows to save some memory and compulation time and memory during the calculation :param profile: np.array of fm_profile_dtype or fm_profile_step_dtype profile :return: boolean : True i...
59,952
def pis_pasep(formatting: bool=True, data_only: bool=True) -> str: """Gere o código do PIS/PASEP aleatório.""" r = fordev_request( content_length=26, referer='gerador_de_pis_pasep', payload={ 'acao': 'gerar_pis', 'pontuacao': 'S' if formatting else 'N' } ...
59,953
def tab_clickable_evt() -> str: """Adds javascript code within HTML at the bottom that allows the interactivity with tabs. Returns ------- str javascript code in HTML to process interactive tabs """ return """ <script> function menu(evt, menu_name) { var i, tab...
59,954
def assert_rankings_plot(plot, names, balanced=10, with_avg=False): """Checks the layout of a rankings plot""" assert plot.layout.title.text == "Average Rankings" assert plot.layout.xaxis.title.text == "Trials ordered by suggested time" assert plot.layout.yaxis.title.text == "Ranking based on loss" ...
59,955
def search_accounts(client: Client, accounts: Tuple[str], date: str) -> None: """Search subjects with given accounts.""" click.echo(client.search_accounts(accounts, date=date, raw=True))
59,956
def urban_patches(built_up, transform): """Identify urban patches.""" built_up = binary_closing(built_up, iterations=int( 100 / transform.a), border_value=1) patch_geoms = [] for geom, value in shapes(built_up.astype('uint8'), connectivity=4, transform=transform): if value == 1: ...
59,957
def test_get_feature_names_empty_selection(selector): """Test that get_feature_names is only called for transformers that were selected. Non-regression test for #19550. """ ct = ColumnTransformer([("ohe", OneHotEncoder(drop="first"), selector)]) ct.fit([[1, 2], [3, 4]]) assert ct.get_feature_nam...
59,958
def delete_tumblelog_childern_signal(sender, instance, **kwargs): """This is a generic singal for deleting am object when a Tumblelog Entry is deleted. """ instance.content_object.delete()
59,959
def add_new_comp(mol, option=None, comp_id=None): """Function to add a new compound to the database given an RDKit molecule Takes an RDKit molecule. Option of LIG to return original smiles with the Compound object Returns a compound object for the RDKit molecule.""" # Neutralise and desalt compound ...
59,960
async def test_sensors(hass): """Test we get sensor data.""" await init_integration(hass) test_username_glucose_value = hass.states.get( "sensor.dexcom_test_username_glucose_value" ) assert test_username_glucose_value.state == str(GLUCOSE_READING.value) test_username_glucose_trend = has...
59,961
def get_resource_tokens(source, data_only=False, tokenize_variables=False): """Parses the given source to resource file tokens. Otherwise same as :func:`get_tokens` but the source is considered to be a resource file. This affects, for example, what settings are valid. """ lexer = Lexer(ResourceFile...
59,962
async def dawn_loop(game): """Dawn loop ----- Dawn : 15 seconds min 30 seconds max At intervals of 15 seconds (15, 30) """ # Start dawn await game.make_dawn() # Query for dawn actions for player in game.sitting_order: await player.role.ego_self.send_regular_d...
59,963
def aggregate_author_stance_preds(preds: np.ndarray) -> Dict[int, float]: """ describe what's going on """ max_pred_indices = np.argmax(preds, axis=1) max_pred_values = np.max(preds, axis=1) max_index_value_pairs = zip(max_pred_indices, max_pred_values) max_index_value_pairs = filter(lambda ...
59,964
def dict_to_tf_example(data, dataset_directory, label_map_dict, ignore_difficult_instances=False, image_subdirectory='JPEGImages'): """Convert XML derived dict to tf.Example proto. Notice that this function normalizes the b...
59,965
def load_prisoner_locations_from_file(filename): """ Load prisoner locations matching test NOMIS data """ csv_path = os.path.join(os.path.dirname(__file__), os.path.pardir, 'fixtures', filename) with open(csv_path) as f: csv_reader = csv.DictReader(f) prisoner_locations = list(csv_r...
59,966
def data_mnist(datadir='/tmp/', train_start=0, train_end=60000, test_start=0, test_end=10000): """ Load and preprocess MNIST dataset :param datadir: path to folder where data should be stored :param train_start: index of first training set example :param train_end: index of last train...
59,967
def validate_input_config(config): """Validate that the input source is valid""" input_manifest_s3_uri = config.get("inputManifestS3Uri") chain_from_job_name = config.get("chainFromJobName") if input_manifest_s3_uri and not chain_from_job_name: return None if not input_manifest_s3_uri and ...
59,968
def create_app(config=None, testing=False, cli=False): """Application factory, used to create application """ app = Flask('insta_pic') configure_app(app, testing) configure_extensions(app, cli) register_blueprints(app) @app.errorhandler(Exception) def error_handler(e): return j...
59,969
def test_cylinder_initialization(): """ This test case is for testing initialization of rigid cylinder and it checks the validity of the members of Cylinder class. Returns ------- """ # setting up test params start = np.random.rand(3) direction = 5 * np.random.rand(3) direction...
59,970
def get_cast_table(paths, player_data, blocklist): """ Create an aggregated CastTable from GamParse output file(s) :param paths: a list of paths to GamParse output :param player_data: a PlayerData object :param blocklist: a list of spells to be ignored :return: a CastTable object """ re...
59,971
def polygon_area(polygon): """ Get the area of a polygon which is represented by a 2D array of points. Area is computed using the Shoelace Algorithm. Args: polygon: 2D array of points. """ x = polygon[:, 0] y = polygon[:, 1] area = (np.dot(x, np.roll(y, -1)) - np.dot...
59,972
def isValidAutoIp(ip): """Checks an IPv4 or IPv6 address where "auto" is a valid value""" if ip != "auto": try: isValidIpv4(ip) except TypeError: isValidIpv6(ip) return True
59,973
def addScaleBar(ax, *args, **kwargs): """ Utility function to add a scalebar to a plot. Args: ax (`matplotlib.axes.Axes`): axes object to which to add the scale bar *args: arguments passed on to `.ScaleBar` **kwargs: key-word arguments passed on to `.ScaleBar` Returns: ...
59,974
def containsAny(seq, aset): """ Check whether sequence seq contains ANY of the items in aset. """ for c in seq: if c in aset: return True return False
59,975
def reverse_complement(string): """Returns the reverse complement strand for a given DNA sequence""" return(string[::-1].translate(str.maketrans('ATGC','TACG')))
59,976
def normal2color(normal, mask, dtype=np.uint8): """Conversion from 3D (x, y, z) surface normals to a color image representing surface normals. Args: normal (ndarray): Surface normals. The shape is H x W x 3. mask (ndarray): Mask with shape of H x W. The value must be 0 or 1. dtype (type...
59,977
def sample( rng: chex.PRNGKey, mean: chex.Array, C: chex.Array, sigma: float, popsize: int, ) -> chex.Array: """Jittable Gaussian Sample Helper.""" S = C + sigma ** 2 * jnp.eye(C.shape[0]) candidates = jax.random.multivariate_normal( rng, mean, S, (popsize,) ) # ~ N(m, S) - ...
59,978
def build_model(): """ build a MultiOutputClassifier model using GridSearch Input: None Output: cv_model (GridSearchCV): ML model """ pipeline = Pipeline([ ('features', FeatureUnion([ ('text_pipeline', Pipeline([ ('vect', CountVectorizer(...
59,979
def stackImages(_imgList, cols, scale): """ Stack Images together to display in a single window :param _imgList: list of images to stack :param cols: the num of img in a row :param scale: bigger~1+ ans smaller~1- :return: Stacked Image """ imgList = copy.deepcopy(_imgList) ...
59,980
def ellipsoid_fit(X): """fits an arbitrary ellipsoid to a set of points """ x = X[:, 0] y = X[:, 1] z = X[:, 2] D = np.array([ x * x + y * y - 2 * z * z, x * x + z * z - 2 * y * y, 2 * x * y, 2 * x * z, 2 * y * z, 2 * x, 2 * y, 2 * z, 1 - 0 * x ]) d2 = np.array(x * x + y ...
59,981
def same_genes(dictionary, sample_ids): """ update main AnnData object for list of samples so all contain the same list of genes Parameters ---------- dictionary : dict dictionary containing AnnData objects sample_ids : list list of sample IDs to compare against one ano...
59,982
def async_engine_from_config( configuration: Dict[str, Any], prefix: str = "sqlalchemy.", **kwargs: Any ) -> AsyncEngine: """Create a new AsyncEngine instance using a configuration dictionary. This function is analogous to the :func:`_sa.engine_from_config` function in SQLAlchemy Core, except that the ...
59,983
def mity_qual(AO, DP, p=0.002): """ Compute variant quality :param AO: (int) number of alternative reads :param DP: (int) total read depth :param p: (float) noise parameter. default=0.002 :return: (float) phred-scaled quality score >>> [mity_qual(x,10) for x in [1,2,3,4,5,6,7,8,9,10]] '...
59,984
def get_prompt_from_code(code_str): """Split ``code_str`` to a <prompt, completion> based on indents. Args: code_str (str): code str. Returns: <before, after> """ splits = list( split_before( code_str.splitlines(), lambda x: x and x[0].isspace(), max...
59,985
def mix_chroma(mixmap,chroma_list,illum_count): """ Mix illuminant chroma according to mixture map coefficient mixmap : (w,h,c) - c is the number of valid illuminant chroma_list : (3 (RGB), 3 (Illum_idx)) contains R,G,B value or 0,0,0 illum_count : contains valid illuminant nu...
59,986
def test_is_instance_false_error_with_exception(instance): """ Тест метода _is_instance() который вернет False, и в ошибке будет исключение. Этот метод "гасит" все исключения, но если оно случилось, то записывает информацию о нем в ошибку. """ # Убедимся что ошибок нет a...
59,987
def create_worker_dmatrix(*args, **kwargs): """ Creates a DMatrix object local to a given worker. Simply forwards arguments onto the standard DMatrix constructor, if one of the arguments is a dask dataframe, unpack the data frame to get the local components. All dask dataframe arguments must ...
59,988
def compute_melspec(y, params): """ Computes a mel-spectrogram and puts it at decibel scale Arguments: y {np array} -- signal params {AudioParams} -- Parameters to use for the spectrogram. Expected to have the attributes sr, n_mels, f_min, f_max Returns: np array -- Mel-spectrogr...
59,989
def _parse_seq(seq): """Get a primary sequence and its length (without gaps)""" return seq, len(seq.replace('-', ''))
59,990
def process_output_file(netblock_list, output_file_name, header_list): """Write the finalized netblocks to a CSV file. Args: netblock_list: A list of netblocks with identifying information. output_file_name: The filename to write the results to. header_list: A list containing the ...
59,991
def get_pkg_json(pkg): """ recieve json from pypi.org """ url = url_template.format(pkg_name=pkg) u = urllib.request.urlopen(url) resp = json.loads(u.read().decode('utf-8')) return resp
59,992
def train_step(vae_apply, vae_params, opt_state: OptState, opt_update: UpdateFn, batch: Batch, random_key: RandomKey) -> Tuple[Params, OptState, Array]: """A single step of training for the VAE.""" def params_loss(loc_params): scaled_ima...
59,993
def schedule_conv3d_winograd_weight_transform(attrs, outs, target): """Schedule conv3d_winograd_weight_transform""" with target: return topi.generic.schedule_conv3d_winograd_weight_transform(outs)
59,994
def requires_setting(section, attribute): """ Declare your settings needs this way, opt-in """ if not config.has_section(section): raise Exception("I require {} attribute in {} section, no such section in settings.ini file".format(attribute, section)) if not config[section].get(attribute): r...
59,995
def i_(indxs_old, indxs, k): """ Returns indexes of elements that were not enlarged in new enlarged array. :param indxs_old: Indexes (in original 1D array) of elements that won't be substituted in new enlarged 1D array. :param indxs: Indexes of elements in original 1D array that ...
59,996
def finalize(): """ finalize the rabit engine, call this function after you finished all jobs """ rbtlib.RabitFinalize() check_err__() unloadlib__()
59,997
def gsl_coerce_float(*args, **kwargs): """gsl_coerce_float(float x) -> float""" return _gslwrap.gsl_coerce_float(*args, **kwargs)
59,998
def get_one_user(id): """ USERS GET ONE """ cursor = mysql.connection.cursor() cursor.execute("SELECT * FROM users WHERE id = %s", (id)) data = cursor.fetchall() cursor.close() print(data) data_res = {"id": data[0][0], "name": data[0][1], "teamId": data[0][2]} message = {"mes...
59,999