content
stringlengths
22
815k
id
int64
0
4.91M
def db_retry(using=None, tries=None, delay=None, max_delay=None, backoff=1, jitter=0, logger=logging_logger): """Returns a retry decorator. :param using: database alias from settings.DATABASES. :param tries: the maximum number of attempts. -1 means infinite. None - get fr...
38,000
def A000142(start: int = 0, limit: int = 20) -> Collection[int]: """Factorial numbers: n! = 1*2*3*4*...*n (order of symmetric group S_n, number of permutations of n letters). """ sequence = [] colors = [] x = [] for i in range(start, start + limit): sequence.append(factorial(i)) ...
38,001
def default(nvars): """ Generate default problem structure for IDW-RBF Global Optimization. problem=idwgopt.default(n) generate a default problem structure for a an optimization with n variables. (C) 2019 by A. Bemporad. """ import idwgopt.idwgopt_default as idwgopt_default problem = i...
38,002
def convex_hull(*args): """ Returns a Polygon representing the convex hull of a set of 2D points. Notes: ====== This can only be performed on a set of non-symbolic points. Example: ======== >>> from sympy.geometry import Point >>> points = [ Point(x) for x in [(1,1), (1...
38,003
def sync_gcp_buckets(neo4j_session, storage, project_id, gcp_update_tag, common_job_parameters): """ Get GCP instances using the Storage resource object, ingest to Neo4j, and clean up old data. :type neo4j_session: The Neo4j session object :param neo4j_session: The Neo4j session :type storage: The...
38,004
def find_namespaces(tree: ElementTree) -> Dict[str, str]: """ Finds the namespaces defined in the ElementTree of an XML document. It looks for namespaces defined in the root element of the XML document. To avoid namespaces being left out, they shall all be defined in the root element of an XML document,...
38,005
def filterStories(stories, triggerlist): """ Takes in a list of NewsStory instances. Returns: a list of only the stories for which a trigger in triggerlist fires. """ filteredStories = [] for story in stories: for trig in triggerlist: if trig.evaluate(story) and story not in...
38,006
def lcs(a, b): """ Compute the length of the longest common subsequence between two sequences. Time complexity: O(len(a) * len(b)) Space complexity: O(min(len(a), len(b))) """ # This is an adaptation of the standard LCS dynamic programming algorithm # tweaked for lower memory consumption. ...
38,007
def save(config, filename="image.img", host=None): """Save the Image File to the disk""" cmd = DockerCommandBuilder(host=host).save(config.getImageName()).set_output(filename).build() return execute(cmd)
38,008
def klass_from_obj_type(cm_json: Dict) -> Any: """Get reference to class (n.b. not an instance) given the value for a key 'obj_type' in the given json dict""" module_name, klass_path = cm_json['obj_type'].rsplit('.', 1) # @todo make this load from file if not available: http://stackoverflow.com/questions/67...
38,009
def test_sub_save_from_dict(empty_subclass_ConfigurationParser): """ Test the not supported of load_into_dict. """ with pytest.raises(NotImplementedError): conf = empty_subclass_ConfigurationParser("here") conf.save_from_dict(conf)
38,010
def set_ade_bldgelements(tz, tzb_dict, tzb_dict_openings, layer_dict, material_dict, constr_dict, tz_factor=1): """Trying to set Rooftop / with Layers/ Materials""" # TODO: Do something nice for Air and other gasses as Materials for key, value in tzb_dict.items(): if value[0] == "roof": ...
38,011
def to_sqlite(): """ get word info in json file from word name """ create_table() for file in os.listdir(JSON_PATH): if file.endswith('.json'): word = get_word(file) print('inserting ' + word + ' data into db') path = os.path.join(JSON_PATH, file) json = readjson(path) insert(replace_url(json)) ...
38,012
def lines2bars(lines, is_date): """将CSV记录转换为Bar对象 header: date,open,high,low,close,money,volume,factor lines: 2022-02-10 10:06:00,16.87,16.89,16.87,16.88,4105065.000000,243200.000000,121.719130 """ if isinstance(lines, str): lines = [lines] def parse_date(x): return arrow.get(...
38,013
def pgd_linf_untargeted(model, X, y, epsilon=0.1, alpha=0.01, num_iter=20, randomize=False): """ Construct FGSM adversarial examples on the examples X""" if randomize: delta = torch.rand_like(X, requires_grad=True) delta.data = delta.data * 2 * epsilon - epsilon else: delta = torch.z...
38,014
def cal_NB_pvalue (treatTotal,controlTotal,items): """calculate the pvalue in pos of chromosome. """ pvalue = 1 (treatCount,controlCount,pos)=items pvalue = negativeBinomail(treatCount,treatTotal,controlCount,controlTotal) return (pvalue,treatCount,controlCount,pos)
38,015
def handle_watches(connection, author): """Return an array of watches for the author.""" database = connection['test'] collection = database['watches'] watches = [] # this should not except for post in collection.find({"author" : ObjectId(author)}): watches.append(cleanup_watc...
38,016
def sizebinned_EChists(labels_pred, labels_true, runlabel, memberbins=[], nbins=15,alpha=0.7, lw=3,figsize=(15,10)): """ For a given set of true and predicted labels, plot the distributions of effi...
38,017
def new_mm(*args, figsize, **kwargs): """Wrapper for plt.subplots, using figsize in millimeters :rtype: figure, axes """ return plt.subplots(*args, figsize=(figsize[0] / 25.4, figsize[1] / 25.4), **kwargs)
38,018
def compute_center_of_mass(coordinates, masses): """ Given coordinates and masses, return center of mass coordinates. Also works to compute COM translational motion. Args: coordinates ({nparticle, ndim} ndarray): xyz (to compute COM) or velocities (COM velocity) masses ({nparticle,} arr...
38,019
def chars_count(word: str): """ :param word: string to count the occurrences of a character symbol for. :return: a dictionary mapping each character found in word to the number of times it appears in it. """ res = dict() for c in word: res[c] = res.get(c, 0) + 1 return res
38,020
def do_expressiondelete(**kwargs): """ Worker to remove expression from engine proexpobj: expression object profileexplist: expression list object return 0 if expression deleted """ proexpobj = kwargs.get('proexpobj') profileexplist = kwargs.get('profileexplist') if profileexplist....
38,021
def read_csv_as_nested_dict(filename, keyfield, separator, quote): """ Inputs: filename - name of CSV file keyfield - field to use as key for rows separator - character that separates fields quote - character used to optionally quote fields Output: Returns a dictionary of...
38,022
def msgpackb(lis): """list -> bytes""" return create_msgpack(lis)
38,023
def prepare_compute_target(experiment, source_directory, run_config): """Prepare the compute target. Installs all the required packages for an experiment run based on run_config and custom_run_config. :param experiment: :type experiment: azureml.core.experiment.Experiment :param source_dire...
38,024
def streaming_ndarray_agg( in_stream, ndarray_cols, aggregate_cols, value_cols=[], sample_cols=[], chunksize=30000, add_count_col=False, divide_by_count=False, ): """ Takes in_stream of dataframes Applies ndarray-aware groupby-sum or groupby-mean: treats ndarray_cols as ...
38,025
def get_cropped_source_data( stack_list: List[str], crop_origin: np.ndarray, crop_max: np.ndarray ) -> np.ndarray: """ Read data from the given image files in an image stack :param List[str] stack_list: List of filenames representing images in a stack :param np.ndarray crop_origin: Origin of region...
38,026
def test_plot_data(): """ Test the plot data produced for a driven control. """ _rabi_rates = [np.pi, 2 * np.pi, np.pi] _azimuthal_angles = [0, np.pi / 2, -np.pi / 2] _detunings = [0, 1, 0] _durations = [1, 1.25, 1.5] driven_control = DrivenControl( rabi_rates=_rabi_rates, ...
38,027
def valid_random_four_channel_images() -> str: """ Make a folder with 5 valid images that have 4 channels. :return: path to the folder """ # use .png because that supports 4 channels return make_folder_with_files('.png', file_type='image', resolution=(300, 300), n_files=6, channels=4)
38,028
def append_pauli_measurement(pauli_string: QubitPauliString, circ: Circuit) -> None: """Appends measurement instructions to a given circuit, measuring each qubit in a given basis. :param pauli_string: The pauli string to measure :type pauli_string: QubitPauliString :param circ: Circuit to add measu...
38,029
def build_template(spec) -> Template: """Build a template from a specification. The resulting template is an object that when called with a set of bindings (as produced by a matcher from `build_matcher`), returns an instance of the template with names substituted by their bound values. This is a g...
38,030
def flatten_objective(expr): """ - Decision variable: Var - Linear: sum([Var]) (CPMpy class 'Operator', name 'sum') wsum([Const],[Var]) (CPMpy class 'Operator', name 'wsum') """ if __is_flat_var(expr): return (expr, [])...
38,031
def list_chunks(list_, chunk_size=CHUNK_SIZE): """Yield successive chunk of chunk_size from list.""" for index in range(0, len(list_), chunk_size): yield list_[index:index + chunk_size]
38,032
def create_app() -> Flask: """Create flask app.""" app_settings = os.getenv('APP_SETTINGS') app.config.from_object(app_settings) db.init_app(app) migrate.init_app(app, db) register_blueprints(app) app.register_error_handler(400, handle_validation_errors) app.register_error_handler(404,...
38,033
def roll(y, z): """Estimate angular roll from gravitational acceleration. Args: y, z (float, int, array-like): y, and z acceleration Returns: (float, int, array-like): roll """ return np.arctan2(y, z) * 180/np.pi
38,034
def eq_to_az_za(ra, dec, lst, latitude=HERA_LATITUDE): """ Convert equatorial (RA/Dec) coordinates to azimuth and zenith angle. Basic expression from http://star-www.st-and.ac.uk/~fv/webnotes/chapter7.htm Parameters ---------- ra, dec : array_like, float RA and Dec in radians. ...
38,035
def log_cc(image, sigma, threshold): """Find connected regions above a fixed threshold on a LoG filtered image. Parameters ---------- image : np.ndarray Image with shape (z, y, x) or (y, x). sigma : float or Tuple(float) Sigma used for the gaussian filter (one for each dimension). I...
38,036
def check_valid_move(grid: np.ndarray, current_position: tuple, move: tuple) -> bool: """ Checking if move is valid for the current position in provided grid :param grid: validated array of a grid :param current_position: current position :param move: move in tuple form :return: True or False ...
38,037
def check_valid_game(season, game): """ Checks if gameid in season schedule. :param season: int, season :param game: int, game :return: bool """ try: get_game_status(season, game) return True except IndexError: return False
38,038
def console(session_console): """Return a root console. Be sure to use this fixture if the GUI needs to be initialized for a test. """ console = session_console assert libtcodpy.console_flush() == 0 libtcodpy.console_set_default_foreground(console, libtcodpy.white) libtcodpy.console_set_def...
38,039
def conv(out_channels, kernel_size, stride=2, padding=1, batch_norm=True): """Creates a convolutional layer, with optional batch normalization. """ layers = [] conv_layer = Conv2D(out_channels, kernel_size, strides = stride, padding = 'same', use_bias = False, data_format = "channels_first") # bias ...
38,040
def test_get_titles_suptitle(pt_line_plt): """Check that the correct suptitle gets grabbed from a figure with 2 subplots""" assert "My Figure Title" == pt_line_plt.get_titles()[0] plt.close()
38,041
def t90_from_t68(t68): """ ITS-90 temperature from IPTS-68 temperature This conversion should be applied to all in-situ data collected between 1/1/1968 and 31/12/1989. """ return t68 / 1.00024
38,042
def prettify(elem): """Return a pretty-printed XML strong for the Element. """ rough_string = ElementTree.tostring(elem, "utf-8") reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=" ")
38,043
def heap_sift_down(collection, start, n = None): """ Sifts down a collection which is desired to be in a heap format. Arguments: collection: The heapified collection to sift down. start: The start index to begin the sift from. n: The maximum non-inclusive limit of how far to go into the collect...
38,044
def course_search(search_str, include_inactive=False, debug=False): """ Parse search string to get institution, discipline, and catalog_number, then find all matching courses and return an array of catalog entries. Search strings by example qns csci * All CSCI courses at QC * csci 101 CSC...
38,045
def _pad( s: str, bs: int, ) -> str: """Pads a string so its length is a multiple of a specified block size. :param s: The string that is to be padded :type s: str :param bs: The block size :type bs: int :returns: The initial string, padded to have a length that is a m...
38,046
def get_json(headers) -> str: """Construct a str formatted like JSON""" body: dict = {} for key, value in headers.items(): body[key] = value return json.dumps(body, indent=2)
38,047
def get_targets(units, assembly_basename, outdir, extensions = ['.fasta.dammit.gff3', '.fasta.dammit.fasta'], se_ext = ['se'], pe_ext = ['pe']): """ Use the sample info provided in the tsv file to generate required targets for dammit """ dammit_dir = assembly_basename + ".fasta.dammit" outdir = ...
38,048
def is_jsonable_object(obj: Any) -> bool: """ Return `True` if ``obj`` is a jsonable object """ cls = obj if isinstance(obj, type) else type(obj) return isinstance(getattr(cls, PHERES_ATTR, None), ObjectData)
38,049
def Dir(obj): """As the standard dir, but also listup fields of COM object Create COM object with [win32com.client.gencache.EnsureDispatch] for early-binding to get what methods and params are available. """ keys = dir(obj) try: ## if hasattr(obj, '_prop_map_get_'): ## k...
38,050
def image_classify(request): """ Image classification """ if request.method == 'POST': # Get upload image img = request.FILES.get('img', None) if img: return JsonResponse(dict(name=img.name, size=img.size)) else: return JsonResponse(dict(code=401, msg='Ba...
38,051
def test_non_issue(): """ Test issue """ inp = b'console.write((f++)/ 4 + 3 / 2)' exp = b'console.write((f++)/4+3/2)' assert py_jsmin(inp) == exp assert py_jsmin2(inp) == exp assert c_jsmin(inp) == exp inp = inp.decode('latin-1') exp = exp.decode('latin-1') assert py_jsmin(inp) == ...
38,052
def calculate_performance_indicators_V1(df): """Compute indicators of performances from df of predictions and GT: - MAE: absolute distance of predicted value to ground truth - Accuracy: 1 if predicted value falls within class boundaries Note: Predicted and ground truths coverage values are ratios betwee...
38,053
def PH2_Calc(KH2, tH2, Kr, I, qH2): """ Calculate PH2. :param KH2: hydrogen valve constant [kmol.s^(-1).atm^(-1)] :type KH2 : float :param tH2: hydrogen time constant [s] :type tH2 : float :param Kr: modeling constant [kmol.s^(-1).A^(-1)] :type Kr : float :param I: cell load current...
38,054
def log_transform(image): """Renormalize image intensities to log space Returns a tuple of transformed image and a dictionary to be passed into inverse_log_transform. The minimum and maximum from the dictionary can be applied to an image by the inverse_log_transform to convert it back to its f...
38,055
def parse_cpu(website: BeautifulSoup, product_id: int) -> Optional[CPU]: """Parses the given Intel ARK website for a CPU.""" # thanks for making accessing so easy btw. # a simple string used for identification of the CPU raw = website.find(attrs={"data-key": "ProcessorNumber"}) if raw is None: ...
38,056
def send_email(to, subject, html_content): """ 根据传入的数据发送邮件 Args: to: 邮件接收人地址 subject: 邮件主题 html_content: 邮件内容 """ user = configuration.get("mail", "user") password = configuration.get("mail", "password") smtp_server = configuration.get("mail", "ser...
38,057
def test_inservice_water(create_test_net): """ :param create_test_net: :type create_test_net: :return: :rtype: """ net = copy.deepcopy(create_test_net) pandapipes.create_fluid_from_lib(net, "water") pandapipes.pipeflow(net, iter=100, tol_p=1e-7, tol_v=1e-7, friction_model="nikurad...
38,058
def create_result_dict( begin_date: str, end_date: str, total_downloads: int, downloads_per_country: List[dict], multi_row_columns: dict, single_row_columns: dict, ) -> dict: """Create one result dictionary with info on downloads for a specific eprint id in a given time period. :param b...
38,059
def test_label_relaxation(dataset): """ Simple label relaxation test. """ X, y_true = dataset[0], dataset[1] clf = LabelRelaxationNNClassifier(lr_alpha=0.1, hidden_layer_sizes=(128,), activation="relu", l2_penalty=1e-8, learning_rate=1e-1, momentum=0.0, epochs=...
38,060
def batch_parse_table( project_id="YOUR_PROJECT_ID", input_uri="gs://cloud-samples-data/documentai/form.pdf", destination_uri="gs://your-bucket-id/path/to/save/results/", timeout=90, ): """Parse a form""" client = documentai.DocumentUnderstandingServiceClient() gcs_source = documentai.type...
38,061
def getConcentricCell(cellNum, matNum, density, innerSurface, outerSurface, universe, comment): """Create a cell which has multiple components inside a cell.""" uCard = '' if type(universe) is int: uCard = 'u=' + str(universe) listType = [] if type(innerSurface) == type(listType): ne...
38,062
def is_downloaded(folder): """ Returns whether CIFAR has been downloaded """ return os.path.isdir(folder) and len(glob(os.path.join(folder, '*'))) == 8
38,063
def show_users(self, privilege, grant_target_name, user_name, node=None): """Check that user is only able to execute `SHOW USERS` when they have the necessary privilege. """ exitcode, message = errors.not_enough_privileges(name=user_name) if node is None: node = self.context.node with Scen...
38,064
def process_swapped_tree(region=settings.PRIMARY_REGION): """This enables to populate data to a tree that is active only within transaction, and not visible from within the app. Thanks to this we can add data and make the tree visibly active only as a very last step. This is like making the tree write-a...
38,065
def main(): """Validates individual trigger files within the raidboss Cactbot module. Current validation only checks that the trigger file successfully compiles. Returns: An exit status code of 0 or 1 if the tests passed successfully or failed, respectively. """ exit_status = 0 ...
38,066
def weight_compression(weights, bits, axis=0, quantizer=None): """Creates an in, out table that maps weight values to their codebook values. Based on the idea presented by https://arxiv.org/pdf/1911.02079.pdf Arguments: weights: Numpy array bits: Number of bits to compress weights to. This will res...
38,067
def ig_request_set_account(mock, data="mock_set_account.json", fail=False): """Mock set account response""" mock.put( "{}/{}".format(IG_BASE_URI, IG_API_URL.SESSION.value), json=read_json("{}/{}".format(TEST_DATA_IG, data)), status_code=401 if fail else 200, )
38,068
def noncoherent_dedispersion(array, dm_grid, nu_max, d_nu, d_t, threads=1): """ Method that de-disperse dynamical spectra with range values of dispersion measures and average them in frequency to obtain image in (t, DM)-plane. :param array: Numpy 2D array (#freq, #t) with dynamical spectra. ...
38,069
def run_systemd_image(image_name, container_name): """ Run docker image with systemd Image named image_name should be built with build_systemd_image. Container named container_name will be started. """ subprocess.check_call([ 'docker', 'run', '--privileged', '--mount', ...
38,070
def parse_cstring(stream, offset): """ parse_cstring will parse a null-terminated string in a bytestream. The string will be decoded with UTF-8 decoder, of course since we are doing this byte-a-byte, it won't really work for all Unicode strings. TODO: add proper Unicode support ...
38,071
def ParseLabelTensorOrDict(labels): """Return a tensor to use for input labels to tensor_forest. The incoming targets can be a dict where keys are the string names of the columns, which we turn into a single 1-D tensor for classification or 2-D tensor for regression. Converts sparse tensors to dense ones. ...
38,072
def showCallGraph(pyew, doprint=True, addr=None): """ Show the callgraph of the whole program """ dot = CCallGraphGenerator(pyew) buf = dot.generateDot() if doprint: showDotInXDot(buf) return buf
38,073
def main(argv=None): # pylint: disable=unused-argument """ Main entry point """ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S-%f") outdir = FLAGS.outdir + '/results_' + timestamp + '/' os.mkdir(outdir) model = TrainRunner(outdir) try: model.run() except Exception as e...
38,074
def cleaning_dataset(): """Clean dataset by replacing missing values""" print("Nettoyage des données nulles...", end="\r") df['ph'] = df['ph'].fillna(df['ph'].mean()) # remplacer les valeurs manquantes par la moyenne (distribution normale) df['Sulfate'] = df['Sulfate'].fillna(df['Sulfate'].mean()) # rem...
38,075
def test_export_ctf(): """Test that CTFd can properly export the database""" app = create_ctfd() with app.app_context(): register_user(app) chal = gen_challenge(app.db, name=text_type('🐺')) chal_id = chal.id hint = gen_hint(app.db, chal_id) client = login_as_user(ap...
38,076
def make_template(center, data): """Make templated data.""" if isinstance(data, dict): return {key: make_template(center, val) for key, val in data.items()} if isinstance(data, list): return [make_template(center, val) for val in data] env = get_env(center) return env.from_string(s...
38,077
def get_sequana_adapters(type_, direction): """Return path to a list of adapters in FASTA format :param tag: PCRFree, Rubicon, Nextera :param type_: fwd, rev, revcomp :return: path to the adapter filename """ # search possible types registered = _get_registered_adapters() if type_ not ...
38,078
def board_str(board): """ String representation of the board. Unicode character for the piece, 1 for threat zone and 0 for empty zone. """ mat = '' for row in board: for squ in row: if squ > 1: mat += '%s ' % chr(squ) else: mat +=...
38,079
def concatenate_corpus(files, output): """Concatenates individual files together into single corpus. Try `bachbot concatenate_corpus scratch/*.utf`. """ print 'Writing concatenated corpus to {0}'.format(output.name) for fp in files: with open(fp, 'rb') as fd: output.write(''.joi...
38,080
async def test_turn_off_invalid_camera(opp, demo_camera): """Turn off non-exist camera should quietly fail.""" assert demo_camera.state == STATE_STREAMING await common.async_turn_off(opp, "camera.invalid_camera") await opp.async_block_till_done() assert demo_camera.state == STATE_STREAMING
38,081
def build_pubmed_url(pubmed_id) -> str: """ Generates a Pubmed URL from a Pubmed ID :param pubmed_id: Pubmed ID to concatenate to Pubmed URL :return: Pubmed URL """ return "https://pubmed.ncbi.nlm.nih.gov/" + str(pubmed_id)
38,082
def create_build_job_query(user, time_frame, local=False): """Create the query to get build jobs from graylog Args: user(str): Fed ID time_frame(int): Graylog search period in hours local(bool): If True also search string for local builds Returns: str: Query string for a gr...
38,083
def convert_to_json(payload_content): """Convert the OPC DA array data to JSON (Dict) and return the aggregated JSON data.""" try: json_response = {} for t in payload_content: # tuple in payload_content temp = {} key = t[0].replace(".", "-").replace("/", "_") ...
38,084
def mount_glusterfs(volume, target_path): """Mount Glusterfs Volume""" if not os.path.exists(target_path): makedirs(target_path) # Ignore if already mounted if os.path.ismount(target_path): logging.debug(logf( "Already mounted", mount=target_path )) ...
38,085
def unites(value=32767): """ Restock all resistance messages. """ invoker = spellbook.getInvoker() value = min(value, 32767) invoker.restockAllResistanceMessages(value) return 'Restocked %d unites!' % value
38,086
def gif_summary(name, tensor, max_outputs, fps, collections=None, family=None): """Outputs a `Summary` protocol buffer with gif animations. Args: name: Name of the summary. tensor: A 5-D `uint8` `Tensor` of shape `[batch_size, time, height, width, channels]` where `channels` is 1 or 3. ...
38,087
def fFargIm(k,phi, x): """Imaginary part of the argument for the integral in fF() """ theta=phi*x return (1/np.sqrt(1-k*k*np.sin(theta)**2)).imag
38,088
def load_compilers() -> None: """ Imports all tests in the plugins/packages directory, to allow for Compiler instance discoveries """ for package in os.listdir(PLUGINS_PATH): if os.path.isdir(os.path.join(PLUGINS_PATH, package)) and package != "__pycache__": for test_file in os.listd...
38,089
def write_version_py(filename='pypint/version.py'): """Taken from numpy/setup.py """ cnt = """# coding=utf-8 # THIS FILE IS GENERATED FROM PYPINT SETUP.PY short_version = '%(version)s' version = '%(version)s' full_version = '%(full_version)s' git_revision = '%(git_revision)s' git_tag = '%(git_tag)s' git_com...
38,090
def deprecated(func): """Prints a warning for functions marked as deprecated""" def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) # turn off filter warnings.warn('Call to deprecated function "{}".'.format(func.__name__), category=Deprecatio...
38,091
def _simulate_dataset( latent_states, covs, log_weights, pardict, labels, dimensions, n_obs, update_info, control_data, observed_factor_data, policies, transition_info, ): """Simulate datasets generated by a latent factor model. Args: See simulate_data ...
38,092
def run_daemon(ctx, config, type_): """ Run daemons for a role type. Handle the startup and termination of a a daemon. On startup -- set coverages, cpu_profile, valgrind values for all remotes, and a max_mds value for one mds. On cleanup -- Stop all existing daemons of this type. :param ctx: C...
38,093
def has_user_data(node: hou.Node, name: str) -> bool: """Check if a node has user data under the supplied name. :param node: The node to check for user data on. :param name: The user data name. :return: Whether or not the node has user data of the given name. """ return _cpp_methods.hasUserDat...
38,094
def to_parquet(path, df, compression=None, write_index=None, has_nulls=None, fixed_text=None, object_encoding=None, storage_options=None): """ Store Dask.dataframe to Parquet files Notes ----- Each partition will be written to a separate file. Parameters ---------- path ...
38,095
def load_ptsrc_catalog(cat_name, freqs, freq0=1.e8, usecols=(10,12,77,-5), sort=False): """ Load point sources from the GLEAM catalog. Parameters ---------- cat_name : str Filename of piunt source catalogue. freqs : array_like Array of frequencies to evaluate point sour...
38,096
def create(): """ Create a new experiment record and the container associated with it. """ # Process form submission if flask.request.method == 'POST': experiment_id = flask.request.form['experiment_id'] container = experiment_id # TODO validate container name # htt...
38,097
def get_model(): """ Reference : http://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf I have added dropout layers to reduce overfitting """ model = Sequential() # Normalization and zero centering. model.add(Lambda(lambda x: x / 255.0 - ...
38,098
def ser_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed): """ This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is the isotropic undecimated wavelet transform implemented for a single CPU core. INPUTS: in1 (no...
38,099