content
stringlengths
22
815k
id
int64
0
4.91M
def plot_segments( dataframe: pd.DataFrame, segments: SyncPairs, together=False, separate=False ): """ Plot the segments of a reference signal dataframe :param dataframe: the dataframe :param segments: a SyncPairs instance that specifies the data to be drawn :param together: true to plot everyt...
5,288,800
def insert_xlnx_pragmas(lines): """Insert HLS pragmas for Xilinx program Replace the comments of "// hls_pipeline" and "// hls_unroll" with HLS pragmas For "// hls pipeline", find the previous for loop before hitting any "}". Insert "#pragma HLS PIPELINE II=1" below the for loop. For "// hls un...
5,288,801
def check_unboundness(A_times_delta_x): """Check if LP is unbounded """ if np.all(A_times_delta_x <= 0): logger.info('LP is unbounded') return True else: return False
5,288,802
def real_fourier_basis(n: int) -> Tuple[torch.Tensor, torch.Tensor]: """Make a Fourier basis. Args: n: The basis size Returns: An array of shape `(n_domain, n_funs)` containing the basis functions, and an array containing the spectral covariances, of shape `(n_funs, )`. """ ...
5,288,803
def to_output_type(array, output_type, order='F'): """Used to convert arrays while creating datasets for testing. Parameters ---------- array : array Input array to convert output_type : string Type of to convert to Returns ------- Converted array """ if out...
5,288,804
def _define_names(d_t, d_y, treatment_names, output_names): """ Helper function to get treatment and output names Parameters ---------- d_t: tuple of int Tuple of number of treatment (exclude control in discrete treatment scenario). d_y: tuple of int Tuple of number of outcome. ...
5,288,805
def scrape_lat_lon_fly(stationID): """ Add latitude, longitude and elevation data to the stationID that is inputted as the argument to the function. Boom. :param stationID: str a unique identifier for the weather underground personal weather station :return: (latitude,longitude,eleva...
5,288,806
def _add_standard_processes(process_registry: ProcessRegistry, process_ids: List[str]): """ Add standard processes as implemented by the openeo-processes-python project. """ def wrap(process: Callable): """Adapter to connect the kwargs style of openeo-processes-python with args/EvalEnv""" ...
5,288,807
def __num_children(self, vertex=None): """ Get the the number of children of the given vertices. If :attr:`vertex` is ``None``, the function will return the number of children of every non leaf node of the tree. :param vertex: a vertex index or a 1d array of vertex indices (default to ``np...
5,288,808
def parse_time_interval(time_start, time_end): """created time values for time_start and time_end, while time_end will be replaced with time_start+ a duration if the duration is given in time_end. The format of the duration is intuitive through the timeparse module. YOu can specify values such as +1d, +...
5,288,809
def _as_vw_string(x, y=None): """Convert {feature: value} to something _VW understands Parameters ---------- x : {<feature>: <value>} y : int or float """ result = str(y) x = " ".join(["%s:%f" % (key, value) for (key, value) in list(x.items())]) return result + " | " + x
5,288,810
def _read_header(f, header_param): """ Read and parse data from 1st line of a file. :param f: :func:`file` or :class:`~StringIO.StringIO` object from which to read 1st line. :type f: file :param header_param: Parameters used to parse the data from the header. Contains "delimiter" an...
5,288,811
def classifier_layer_fn(in_dim, out_dim, layer_name, fn=tf.nn.relu): """Build a function for a neural network classifier layer.""" with tf.name_scope(layer_name + '_vars'): weights, biases = classifier_variables(in_dim, out_dim) def nn_layer_ops(x): with tf.name_scope(layer_name + '_ops')...
5,288,812
def svn_client_revprop_get(*args): """ svn_client_revprop_get(char propname, svn_string_t propval, char URL, svn_opt_revision_t revision, svn_revnum_t set_rev, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t """ return apply(_client.svn_client_revprop_get, args)
5,288,813
def get_args(): """Gte cmomnda-lnei amguntsre""" parser = argparse.ArgumentParser( description="Let's change some vowels", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument("input", metavar="str", help="Text or a file") parser.add_argument( "-v"...
5,288,814
def do_action(view: View, defx: Defx, action_name: str, context: Context) -> bool: """ Do "action_name" action. """ if not defx._source: return True actions: typing.Dict[str, ActionTable] = defx._source.kind.get_actions() if action_name not in actions: return True...
5,288,815
def pen_down(): """ Pull the pen down – drawing when the turtle moving. """ _check_turtle() _turtle.pen_down()
5,288,816
def qinit(x,y): """ Dam break """ from numpy import where eta = where(x<10, 40., 0.) return eta
5,288,817
def parkinson_volatility(high_prices, low_prices, window, time_scale=1, plot=False): """ Estimando a volatilidade a partir dos preços de Alta e de Baixa Args: high (pd.DataFrame): série de preços de alta de uma ação low (pd.DataFrame): série de preços de baixa de uma ação window (in...
5,288,818
def assembleDomain(domain): """ This function sets up everything needed for the domain, meshing, and AuxiliaryVariables calculations (if any). It should always be called after defining and manipulating all the shapes to be attached to the domain. Parameters ---------- domain: proteus.Do...
5,288,819
def in_notebook(): """ Returns ``True`` if the module is running in IPython kernel, ``False`` if in IPython shell or other Python shell. """ return "ipykernel" in sys.modules
5,288,820
def test_write_shp(tmpdir): """ Just make sure this runs """ tmppath = tmpdir.strpath schema = { 'geometry': 'Point', 'properties': { 'STATUS': 'str', 'X': 'str', 'Y': 'str' } } data = ( { 'point': Point(0, 0), ...
5,288,821
def DatetimeToUTCMillis(date): """Converts a datetime object to milliseconds since the epoch in UTC. Args: date: A datetime to convert. Returns: The number of milliseconds since the epoch, in UTC, represented by the input datetime. """ return DatetimeToUTCMicros(date) / 1000
5,288,822
def main(): """ main method """ arsa()
5,288,823
async def _async_forward(async_chunks: AsyncIterable, out: Optional[Union[TeeCapture, IO[str]]] ) -> Optional[str]: """Prints/captures output from the given asynchronous iterable. Args: async_chunks: An asynchronous source of bytes or str. out: W...
5,288,824
def _try_parse_int(value: str): """ try parse integer from string param value: string to parse return int """ try: return int(value) except ValueError: raise ValueError("Cannot parse int from string")
5,288,825
def df_to_latex( df, col_aligns="", header="", caption="", bold_max_cols=None, na_rep="-", supertabular=False, midrule_after=None): """Converts a pandas dataframe into a latex table. :col_aligns: Optional format string for column alignments in...
5,288,826
def _gather_shape_rule(operand, indices, *, dimension_numbers, slice_sizes, unique_indices, indices_are_sorted, mode, fill_value): """Validates the well-formedness of the arguments to Gather. The code implements the checks based on the detailed operation semantics of ...
5,288,827
def tf_mixed_norm_solver(M, G, alpha_space, alpha_time, wsize=64, tstep=4, n_orient=1, maxit=200, tol=1e-8, log_objective=True, active_set_size=None, debias=True, return_gap=False, verbose=None): """Solve TF L21+L1 inverse solver with BCD an...
5,288,828
def load_friend_chains(chain, friend_chains, txt, nfiles=None): """Load a list of trees from a file and add them as friends to the chain.""" if re.search('.root?', txt) is not None: c = ROOT.TChain(chain.GetName()) c.SetDirectory(0) c.Add(txt) friend_chains.append(c) ...
5,288,829
def stddev(in_list): """ Calculates standard deviation of given list :param in_list: list of values :return: float rounded to 5 decimal places """ var = zvariance.variance(in_list) std_dev = sqrt(var) return round(std_dev, 5)
5,288,830
def test_to_graph_should_return_theme() -> None: """It returns a theme graph isomorphic to spec.""" """It returns an identifier graph isomorphic to spec.""" informationmodel = InformationModel() informationmodel.identifier = "http://example.com/informationmodels/1" informationmodel.theme.append("htt...
5,288,831
def h2o_H2OFrame_head(): """ Python API test: h2o.frame.H2OFrame.head(rows=10, cols=200) """ frame = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv"), col_types=["numeric","numeric","numeric","numeric","string"]) rowNum = randrange(1, frame.nrow) co...
5,288,832
def retrieve_single_timeseries(ticker, secs=60, ndays=5): """ Grabs data from Google finance. It retrieves the data for `ticker` at `secs` intervals for the most recent `ndays`. The fields it retrieves for each interval is (time, open price, close price, volume of trade) Parameters ---------- ...
5,288,833
async def test_controlled_load_forecast_sensor( hass: HomeAssistant, setup_general_and_controlled_load: Mock ) -> None: """Test the Controlled Load Forecast sensor.""" assert len(hass.states.async_all()) == 6 price = hass.states.get("sensor.mock_title_controlled_load_forecast") assert price asse...
5,288,834
def select_os(parsed_host: dict): """ Out of all suggested OSs for the given host from Nmap, select the most likely one using cosine similarity string matching. First a string of relevant information is created, second the OS whose information is the most similar to the matching string is returned. ...
5,288,835
def index_settings(shards=5, refresh_interval=None): """Configure an index in ES with support for text transliteration.""" return { "index": { "number_of_shards": shards, "refresh_interval": refresh_interval, "analysis": { "analyzer": { ...
5,288,836
def test_Run_patience_exceeded(): """Test that error is raised when patentience is set and exceeded.""" job = MockJob("name", 0, 10, sleep_time=5) with test.Raises(OSError): progress.Run(job, patience=2)
5,288,837
def create_gray_frame(frame): """Create and return an undistorted grayscale image""" h, w = frame.shape[:2] new_matrix, _ = cv2.getOptimalNewCameraMatrix(Pose.camera_matrix, Pose.dist_coeffs, (w, h), 1, (w, h...
5,288,838
def test_invalid_uri_connection(): """ Try to connect the InfluxDB instance to an influxdb database with an invalid uri Test if an CantConnectToInfluxDBException is raise """ db = InfluxDB('tqldjslqskjd', INFLUX_PORT, INFLUX_DBNAME) with pytest.raises(CantConnectToInfluxDBException): ...
5,288,839
def make_nan_inf_summary(df: pd.DataFrame, max_loss: float) -> pd.DataFrame: """ makes a summary fot the the amount of nan and infinity values in the given data frame will throw a ValueError if the percent of nan and inf is greater than the given threshold prints a summary of the nan's and inf of there ...
5,288,840
def test_value_check_success(records, pass_value, tolerance): """ Assert that value_check method execution succeed """ hook = BigQueryHookAsync() query = "SELECT COUNT(*) from Any" response = hook.value_check(query, pass_value, records, tolerance) assert response is None
5,288,841
def test_get_members(org): """Retrieve the members of the org and validate its formatting""" with requests_mock.Mocker() as mock: add_org_options(mock, DF.options()) add_org_members(mock, DF.members()) assert org.members == dict( member1=dict( role="owner" ...
5,288,842
def locate(phrase: str) -> None: """Locates an Apple device using icloud api for python. Args: phrase: Takes the voice recognized statement as argument and extracts device name from it. """ if not (target_device := device_selector(phrase=phrase)): support.no_env_vars() return ...
5,288,843
def choose_downloaded_komoot_tour(): """ Choose a previously downloaded tour. Tour can be passed to :func:`komoog.gpx.convert_tour_to_gpx_tracks` afterwards. """ tours = read_tours() for idx in range(len(tours)): print(f"({idx+1}) {tours[idx]['name']}") tour_id = int(input("To...
5,288,844
def get_data_hsla(obsid, targ): """ Given an HSLA observation ID, returns the spectral data. If a coadd-level spectrum, must supply the target name via the 'targ' parameter. :param obsid: The HSLA grism observation ID to retrieve the data from. :type obsid: str :param targ: The name of t...
5,288,845
def list_(limit: int = None, offset: int = None, siri_route_ids: str = None, siri_route__line_refs: str = None, siri_route__operator_refs: str = None, journey_ref_prefix: str = None, journey_refs: str = None, vehicle_refs: str = None, scheduled_start_time_from: datetime...
5,288,846
def registerPrompt() -> None: """ """ questions = [ { 'type': 'input', 'name': 'username', 'message': 'Enter your username:', 'validate': lambda val: val != '' }, { 'type': 'password', 'name': 'password', ...
5,288,847
def fit_cpmfgp_with_dataset(dataset, *args, **kwargs): """ Fits and returns a CPMFGP. """ config = dataset.config mfgp_fitter = cpgp.CPMFGPFitter(dataset.ZZ_train, dataset.XX_train, dataset.YY_train, fidel_space=config.fidel_space, domain=config.domain, fidel_space_kernel_ordering=config.fidel_space_order...
5,288,848
def run(outdir): """ Runs an experiment and stores result in outdir """ ''' Set up paths and start log ''' npzfile = os.path.join(outdir, 'result') npzfile_test = os.path.join(outdir, 'result.test') repfile = os.path.join(outdir, 'reps') repfile_test = os.path.join(outdir, 'reps.test') outfo...
5,288,849
def m67(tab=None,tab3=None,out='./') : """ M67 abundances """ gd=apselect.select(tab,badval='STAR_BAD') m67=np.array(apselect.clustmember(tab[gd],'M67',param=None,pm=True,dist=True)) m67=gd[m67] els=tab3['ELEM_SYMBOL'][0].astype(str) grid=[] for iel,el in enumerate(els) : fig,ax=...
5,288,850
def rigid_transform_graph(cellgraph, transform): """Update graph by applying rigid transform on every node of cellgraph. The original cellgraph is modified.""" print('Rigid transformation matrix') print(transform) for node, attr in cellgraph.nodes(data=True): pos = np.array([attr['x'], attr[...
5,288,851
def test_approach(approach: str, sample_no: int, func, args: tuple) -> str: """ For a given Sample #sample_no evaluates an approach by running func with provided args and logs run time """ res = f"{approach.capitalize()} Programming Approach for the Example #{sample_no}\n" start = time.time()+1 soln = f...
5,288,852
def call_command(cmd, verbosity="ERROR"): """ simple wrapper for call command """ p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) output, err = p.communicate("get output") rc = p.returncode if not rc == 0: raise Exception("{0} ==> command: {1}".format(err, " ".join(cmd))) return output
5,288,853
def train( images_path: str, texts_path: str, train_imgs_file_path: str, val_imgs_file_path: str, joint_space: int, num_layers: int, learning_rate: float, margin: float, clip_val: float, decay_rate: int, weight_decay: float, batch_size: int, prefetch_size: int, ep...
5,288,854
def walk(i, j): """ Walks through the String without crossing the boundaries, making sure that i < j-1 """ if i < j - 1: i += 1 # It is necessary to check again if i < j-1, after we incremented i if i < j - 1: j -= 1 return i, j
5,288,855
def run(configbase, filebase, options, progname): """ Command line tool to create and display ROs managed by the Overlay RO service. """ status = 0 # Create new Overlay RO and returns its URI with HTTP_Session(options.serviceuri) as rovsession: try: rovsession.doRequest(optio...
5,288,856
def equation_loglogw2(x, a, b, c, d, e): """Equation form for loglogw2 """ return exp(a + b * log(log(x+1)) + (sqrt(x) * (c/2)))
5,288,857
def converter_spark_em_pandas(df): """ Converte o dataframe Spark em Pandas, adicionando uma coluna de identificador unico e deterministico para cada linha da tabela """ data = df.toPandas() data["ID_REGISTRO_TABELA"] = data.apply( lambda row: uuid.uuid5( uuid.UUID('a658b648-167e-4d4c-8e09-6dfe7a7...
5,288,858
def kwargs_to_str(kwargs): """ Returns a string of the form '(kw1=val1, kw2=val2)'. """ if len(kwargs) == 0: return "" else: return "(" + ", ".join(f"{k}={v}" for k, v in kwargs.items()) + ")"
5,288,859
def get_crypt_key(): """ Lazily generate the crypt key and return it """ # pylint: disable=global-statement global __CRYPT_KEY__ if not __CRYPT_KEY__: __CRYPT_KEY__ = _get_system_uuid() return __CRYPT_KEY__
5,288,860
def index(): """ Parameters: ---------- None. Returns -------- A rendered version of index.html and a http response code 200 The function renders the index page for the app """ global core_module if not core_module: core_module = core_module() ...
5,288,861
def clear_temp_directory(clear_user_profile_directories=True): """Clear the temporary directories.""" temp_directory = environment.get_value('BOT_TMPDIR') remove_directory(temp_directory, recreate=True) os.chmod(temp_directory, 0777) if not clear_user_profile_directories: return user_profile_root_dire...
5,288,862
def main(args): """Preprocess the Microsoft text summarization dataset. Args: args: command line arguments. """ data_dir = args.raw_data_dir if not os.path.isdir(os.path.expanduser(data_dir)): raise Exception("Data directory not found.") num_of_tuning_sam = args.num_of_tuning num_of_vali...
5,288,863
def start(ctx, profile=None, logcat=False): """ Start kognitivo inside the current device (emulator or real device) """ import buildozer profile = profile or "" buildo = buildozer.Buildozer() buildozer_config = buildo.config buildo.config_profile = profile buildo._merge_config_profil...
5,288,864
def printdep(ctx): """Print dependencies of a var from reading meta. Recursive (will print deps of deps etc)""" vamdirs.recurse_dep(getdir(ctx), ctx.obj['file'], do_print = True)
5,288,865
def fpH(pH, c_Na, c_acide): """ Calcule la valeur de la fonction dont la racine correspond à l'équilibre de la solution. Entrée : pH c_Na (mol/L) c_acide (mol/L) Sortie : valeur de la fonction """ Ke = 10**(- pKe) ...
5,288,866
def test_get_clcalipso_fix(): """Test getting of fix.""" fix = Fix.get_fixes('CMIP6', 'IPSL-CM6A-LR', 'CFmon', 'clcalipso') assert fix == [Clcalipso(None), AllVars(None)]
5,288,867
def local_decomposition( x: ShareTensor, ring_size: int, bitwise: bool, seed_id_locations: str, node: Any, read_permissions: Dict[Any, Any], ) -> None: """Performs local decomposition to generate shares of shares. Args: x (ShareTensor) : input ShareTensor. ring_size (str...
5,288,868
def detect(source, config=None, path=None): """Analyze and detect minimum versions from source code. A default config will be used if it isn't specified. If path is specified, it will occur in errors instead of the default '<unknown>'. """ visitor = visit(source, config, path) if isinstance(visitor, SourceVis...
5,288,869
def run_server(port, sz, num_pkts, verbose=False): """Run TCP echo server.""" srv = mk_socket(True) # TODO: Pass interface rather than hard-code the default. srv.bind(('0.0.0.0', port)) srv.listen(BACKLOG) handlers = [] try: with srv: while True: cli, a...
5,288,870
def mxbulksniff(items, ignore_errors=True): """ Identify the email service provider of a large set of domains or emails, caching to avoid repeat queries. Returns a generator that yields one item at a time >>> [(i['query'], i['match']) for i in mxbulksniff( ... ['example.com', 'google.com', 'htt...
5,288,871
def set_coredump_network_config( host, username, password, dump_ip, protocol=None, port=None, host_vnic="vmk0", dump_port=6500, esxi_hosts=None, credstore=None, ): """ Set the network parameters for a network coredump collection. Note that ESXi requires that the dump...
5,288,872
def Verification(verification_list, value): """ Essa função verifica se algum jogador já venceu a partida, retorna um valor booleano que determina o próximo jogador. :param verification_list: :param value: :return bool: """ cont = 0 # define um contador. for i in DIM.WIN: # verifi...
5,288,873
def train_agent(env_config_path, agent_config_path, num_episodes): """train agent""" f1, f2 = open(env_config_path), open(agent_config_path) env_config, agent_config = json.load(f1), json.load(f2) env, agent = config(env_config, agent_config) evaluation = MyEvaluation(env, agent, output_dir='agents'...
5,288,874
def add_CRUD_pset(pset, sm, model_name): """Adds the ServerModel CRUD function to the Primitve Set Parameters ---------- pset : PrimitiveSet the primitive set for adding the controller functions sm : ServerModel the ServerModel with the CRUD functions model_name : str ...
5,288,875
def to_litres(gallons): """Convert US gallons to metric litres""" return 3.78541 * gallons
5,288,876
def fit_prior(n, p0=0.05): """ todo: check if there are similar magic numbers https://github.com/svpcom/hyperloglog/blob/master/hyperloglog/hll.py ... if p == 4: return 0.673 if p == 5: return 0.697 if p == 6: return 0.709 return 0.7213 / (1.0 + 1.079 / (1 << p)) """ return 4 -...
5,288,877
def get_nioshtic_wikidata_mapping(): """ Retrieves a mapping between NIOSHTIC and Wikidata identifiers from the Wikidata Query Service, query.wikidata.org @return dictionary {nioshtic: {identifier_label: value}} """ prefix = 'http://www.wikidata.org/entity/' q = ( 'select%20%3Fi%20...
5,288,878
def generate_labelled_sources(programs: Programs) -> Iterator: """For each program, yield its source with its labels in comment. Args: programs (Programs): A list of labelled programs. Yields: Iterator: The lines of the given programs, with their labels in comment. Note: This ...
5,288,879
def create_new_fabric_person_from_token(headers, check_unique=False): """ Extract info from identity token and create a FabricPerson entry for this person, including a new UUID. Return a PeopleLong based on that info. :param headers: request headers with cookie, ID token etc :param check_unique: che...
5,288,880
def set_requires_grad(nets, requires_grad=False): """ :param nets: list of networks :param requires_grad: :return: """ if not isinstance(nets, list): nets = [nets] for net in nets: if net is not None: for param in net.parameters(): param.require...
5,288,881
def _gsspp(X,p,n,fun=ss): """ Generalized Spatial Sign Pre-Processing for Centred Data """ return(np.multiply(X,fun(_norms(X),p,n)))
5,288,882
def distr_labeldata_unequal(label_data, num_workers): """ Idea: 1. For each label, distribute disproportionate allocation to workers. 2. Apply the worker's allocation to label_data and store in distr_labeldata, where the keys are workers and the values are the labeled data with X and Y. Inp...
5,288,883
def parse(elem): """ Traverse the json structure and return a dictionary with the following structure: { Bookmark Name: Bookmark Url } """ for obj in elem: if obj["type"] == "url": if obj["name"] in result: print(f"Error: duplicate {obj['name']} is overwritten!") ...
5,288,884
def random_conv_encode(k, generator_matrix, memory, p=0.5): """ Generates a random sequence of k-bits, each Bernoulli(p) and then encodes them convolutionally. Returns the original sequence, and the convolutionally encoded one, using the generator matrix and memory. """ message_bits = generate_random_binar...
5,288,885
def readJsonTextarea2(request): """JSONでの応答練習""" template = loader.get_template('practice/json-textarea2.html') # ---------------------------- # 1 # 1. host1/webapp1/templates/practice/json-textarea2.html を取ってきます # ...
5,288,886
def _smart_fusion_strategy(ents): """This strategy adds the entities scores if one entity occurs multiple times with the same tag, and afterwards applies the fusion strategy.""" deduplicated_ents = [] for idx, ent in enumerate(ents): next_ent = ents[idx + 1] if idx + 1 < len(ents) else None ...
5,288,887
def test_fft_2d_axis0(): """ FFt along axis=0 input array: --> fft (complex): 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 3 3 3 3 3 1 1 1 1 1 0 0 0 0 0 """ array = numpy.ones((3, 5)) result = fft(array, axis=0) assert result.dtype == complex assert ( resul...
5,288,888
def bayesian_regret(voters, winner): """ Calculate bayesian regret voters : array (a, n) Voter preferences; n-dimensional voter cardinal preferences for n issues. winner : array shape (n) Winner preferences for winner and `n`-dimensional issues. """ voters =...
5,288,889
def park(): """Park the watercolorbot's brush in the top-left corner.""" _make_cnc_request("park")
5,288,890
def run(process_class, *args, **inputs): """ Synchronously (i.e. blocking) run a workfunction or process. :param process_class: The process class or workfunction :param _attributes: Optional attributes (only for process) :param args: Positional arguments for a workfunction :param inputs: The li...
5,288,891
def get_pyramid(image, py_image): """Generate the scale pyramid for the image """ py_image.append(image) py_levels = 3 for level in range(py_levels): image = cv.pyrDown(image) py_image.append(image)
5,288,892
def savePQCCollection_pandas(db, filename): """ Save To Do: - Save the files in a tmp file - As it saves, creates a md5 of each file - Put everything together in a tar.bz2, including the md5 list - Delete the tmp file """ import os import tempfile...
5,288,893
def pointing_str2tuple(beamctldirarg): """ Convert a beamctl direction string into direction tuple Inverse of pointing_tuple2str(). Parameters ---------- beamctldirarg : str String with format 'angle1,angle2,refsys' Returns ------- dirtuple : tuple or None Directio...
5,288,894
def plotter(fdict): """ Go """ pgconn = get_dbconn('coop') ctx = get_autoplot_context(fdict, get_description()) station = ctx['station'] t1 = ctx['t1'] t2 = ctx['t2'] table = "alldata_%s" % (station[:2],) nt = NetworkTable("%sCLIMATE" % (station[:2],)) df = read_sql(""" SE...
5,288,895
def for_each_package_specs(ns, pkg_specs, info, func, repoid=None, just_on_installed=True): """ Iterate over package specification strings, find them on remote host, make them into ``LMI_SoftwareIdentity``, and pass them to given function. :param list pkg_specs: Package specification strings. ...
5,288,896
def save_data(tcube_data, psph_data, pcyl_data, params): """Save data to Parameters ---------- tcube_data : dictionary contains the keys 'x', 'y', 'z', 't'. xyz are 1D arrays, t is a 3D array. psph_data : dictionary contains the keys 'ksph', 'psph', 'perr', 'pnoise', 'nmodes', 'wr...
5,288,897
def cu_projection(param: str, date: date, cu_projections) -> int: """ Get the Columbia model's prediction of the param for the date """ scenario = cu_model_scenario(tuple([s for s in cu_projections.keys()])) quantile = cu_model_quantile() # Extract quantiles of the model distribution xs...
5,288,898
def dicthash(d:dict)->Hash: """ Calculate hashsum of a Python dict. Top-level fields starting from '_' are ignored """ string="_".join(str(k)+"="+str(v) for k,v in sorted(d.items()) if len(k)>0 and k[0]!='_') return md5(string.encode('utf-8')).hexdigest()
5,288,899