content
stringlengths
22
815k
id
int64
0
4.91M
def main(): """Command line execution of this building block. Please check the command line documentation.""" parser = argparse.ArgumentParser(description='This class is a wrapper for an associations call of teh DisGeNET database REST API.', formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width...
5,327,800
def app(): """Required by pytest-tornado's http_server fixture""" return tornado.web.Application()
5,327,801
def is_bound_builtin_method(meth): """Helper returning True if meth is a bound built-in method""" return (inspect.isbuiltin(meth) and getattr(meth, '__self__', None) is not None and getattr(meth.__self__, '__class__', None))
5,327,802
def normalize(adj): """Row-normalize sparse matrix""" rowsum = np.array(adj.sum(1)) r_inv = np.power(rowsum, -1).flatten() r_inv[np.isinf(r_inv)] = 0. r_mat_inv = np.diag(r_inv) mx = r_mat_inv.dot(adj) return mx
5,327,803
def put_bucket_policy(Bucket=None, ConfirmRemoveSelfBucketAccess=None, Policy=None): """ Applies an Amazon S3 bucket policy to an Amazon S3 bucket. If you are using an identity other than the root user of the AWS account that owns the bucket, the calling identity must have the PutBucketPolicy permissions on the...
5,327,804
def get_recommendation_and_prediction_from_text(input_text, num_feats=10): """ Gets a score and recommendations that can be displayed in the Flask app :param input_text: input string :param num_feats: number of features to suggest recommendations for :return: current score along with recommendations...
5,327,805
def set_title(title, uid='master'): """ Sets a new title of the window """ try: _webview_ready.wait(5) return gui.set_title(title, uid) except NameError: raise Exception('Create a web view window first, before invoking this function') except KeyError: raise Except...
5,327,806
def FK42FK5MatrixOLDATTEMPT(): """ ---------------------------------------------------------------------- Experimental. Create matrix to precess from an epoch in FK4 to an epoch in FK5 So epoch1 is Besselian and epoch2 is Julian 1) Do an epoch transformation in FK4 from input epoch to 1984 January 1d 0h 2) Apply...
5,327,807
def _lg_undirected(G, selfloops=False, create_using=None): """Return the line graph L of the (multi)graph G. Edges in G appear as nodes in L, represented as sorted tuples of the form (u,v), or (u,v,key) if G is a multigraph. A node in L corresponding to the edge {u,v} is connected to every node corresp...
5,327,808
def get_utxo_provider_client(utxo_provider, config_file): """ Get or instantiate our blockchain UTXO provider's client. Return None if we were unable to connect """ utxo_opts = default_utxo_provider_opts( utxo_provider, config_file ) try: utxo_provider = connect_utxo_provider( utxo_opts ) ...
5,327,809
def metadata( sceneid: str, pmin: float = 2.0, pmax: float = 98.0, hist_options: Dict = {}, **kwargs: Any, ) -> Dict: """ Return band bounds and statistics. Attributes ---------- sceneid : str CBERS sceneid. pmin : int, optional, (default: 2) ...
5,327,810
def size_to_string(volume_size): # type: (int) -> str """ Convert a volume size to string format to pass into Kubernetes. Args: volume_size: The size of the volume in bytes. Returns: The size of the volume in gigabytes as a passable string to Kubernetes. """ if volume_size >=...
5,327,811
def compute(model_path: Path = typer.Argument(..., exists=True, file_okay=True, dir_okay=False)): """Compute vertices/edge data from blender model.""" model_path = Path(model_path) script_path = Path(__file__).parent / "compute.py" assert script_path.exists(), "Failed to find script path." data_path...
5,327,812
def argToDic(arg): """ Converts a parameter sequence into a dict. Args: arg (string): specified simulation parameters.""" params = dict() options = arg.split("_") if "=" in options[0]: params["mode"] = "" else: params["mode"] = options.pop(0) # parse arguments ...
5,327,813
def run_pack(): """ run package nuke project plugin :return: """ wgt = nuke2pack.PackageDialog() wgt.exec_()
5,327,814
def test_handler_review_submitted_with_mention(monkeypatch): """ handler_issue_pr_mentioned にサンプル入力を入れて動作確認 """ mentioned_header_path = SCRIPT_PATH.parent / "testdata/review-submitted-header.json" mentioned_body_path = SCRIPT_PATH.parent / "testdata/review-submitted-body-with-mention.json" header = json...
5,327,815
def _installed_snpeff_genome(config_file, base_name): """Find the most recent installed genome for snpEff with the given name. """ data_dir = _find_snpeff_datadir(config_file) dbs = [d for d in sorted(glob.glob(os.path.join(data_dir, "%s*" % base_name)), reverse=True) if os.path.isdir(d)] ...
5,327,816
def geth2hforplayer(matches,name): """get all head-to-heads of the player""" matches = matches[(matches['winner_name'] == name) | (matches['loser_name'] == name)] h2hs = {} for index, match in matches.iterrows(): if (match['winner_name'] == name): if (match['loser_name'] not in h2hs)...
5,327,817
def test_best_codeblocks_have_no_lint_errors(lint_codeblock, best_codeblock): """Test that "best" codeblocks do not fail to lint.""" result = lint_codeblock(best_codeblock) assert result, result.output
5,327,818
def cli(): """A unified CLI for the PHYLUCE software package.""" pass
5,327,819
def backtracking_solver( starting_event: Event, **kwargs) -> FiniteSequence: """Compose a melodic sequence based upon the domain and constraints given. starting_event: Event dictate the starting pitch. All subsequent events will be of similar duration. constraints - list of constra...
5,327,820
def banner_print(msg, color='', width=60, file=sys.stdout): """Print the message as a banner with a fixed width.fixed Args: msg: The message to print. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any set of ...
5,327,821
def _save_conf_file(cfg): """ Given a ConfigParser object, it saves its contents to the config file location, overwriting any previous contents """ conf_path = _locate_conf_file() f = open(conf_path, "w") cfg.write(f) f.close() # Make sure it has restricted permissons (since it tends...
5,327,822
def jdos(bs, f, i, occs, energies, kweights, gaussian_width, spin=Spin.up): """ Args: bs: bandstructure object f: final band i: initial band occs: occupancies over all bands. energies: energy mesh (eV) kweights: k-point weights gaussian_width: width of gau...
5,327,823
def findConstantMetrics(inpath): """ Simple function that checks which metrics in a dictionary (read from a CSV) are constant and which change over time. As a reference, the first record read from the file is used :param inpath: The path to the CSV file that must be analyzed :return: The list of me...
5,327,824
def scoreGold(playerList, iconCount, highScore): """Update each players' score based on the amount of gold that they have collected. Args: playerList: A list of all PlayerSprite objects in the game. iconCount: A list of integers representing how many times each player has gained points from the...
5,327,825
def make_clone(dst_res, settings, interp_soilthick, M_method, M_minmax, directory_in, directory_out, clonefile, logger): """ Creates maps for wflow model (staticmaps). Parameters: dst_res : [float] resolution of output maps settings : [string] path to settings file interp_soilt...
5,327,826
def image_2d_transformer(pretrained=False, **kwargs): """ modified copy from timm DeiT base model @ 384x384 from paper (https://arxiv.org/abs/2012.12877). ImageNet-1k weights from https://github.com/facebookresearch/deit. """ model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads...
5,327,827
def removeAPIs(): """ This function will remove all created APIs from API Manager (apis in multiple tenants) :return: None """ global tenant_config_details remove_count = 0 # iterate for each API with open(abs_path + '/../../data/runtime_data/api_ids_multi_tenant.csv', 'r') as f: ...
5,327,828
def addOnScriptSave(call, args=(), kwargs={}, nodeClass='Root'): """Add code to execute before a script is saved""" _addCallback(onScriptSaves, call, args, kwargs, nodeClass)
5,327,829
def create_fourier_heatmap_from_error_matrix( error_matrix: torch.Tensor, ) -> torch.Tensor: """Create Fourier Heat Map from error matrix (about quadrant 1 and 4). Note: Fourier Heat Map is symmetric about the origin. So by performing an inversion operation about the origin, Fourier Heat Ma...
5,327,830
def get_cluster_credentials(DbUser=None, DbName=None, ClusterIdentifier=None, DurationSeconds=None, AutoCreate=None, DbGroups=None): """ Returns a database user name and temporary password with temporary authorization to log in to an Amazon Redshift database. The action returns the database user name prefixed w...
5,327,831
def test_connection(client): """ test `/api/ping` - Check connection :param client: cope app client :return: Passed status if code is similar """ response = client.get("/api/ping") assert response.status_code == 200 assert response.json["Ping"] == "Pong"
5,327,832
def _sc_print_ ( sc ) : """Print the Status Code >>> st = ... >>> print st """ BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = list ( range ( 8 ) ) ## from ostap.logger.logger import colored_string if sc.isSuccess () : return colored_string( 'SUCCESS' , WHITE , GREEN ...
5,327,833
def test_no_invalid_formats(locale): """ For each locale, for each provider, search all the definitions of "formats" and make sure that all the providers in there (e.g. {{group}}) are valid and do not emit empty strings. Empty strings are allowed only if the group is not surrounded by spaces. This i...
5,327,834
def get_state_name(state): """Maps a mongod node state id to a human readable string.""" if state in REPLSET_MEMBER_STATES: return REPLSET_MEMBER_STATES[state][0] else: return 'UNKNOWN'
5,327,835
def _get_platform_information(): """Return a dictionary containing platform-specific information.""" import sysconfig system_information = {"platform": sysconfig.get_platform()} system_information.update({"python version": sys.version_info}) if sys.platform == "win32": system_information.upd...
5,327,836
def compute_resilience(ugraph, attack_order): """ Alias to bfs or union find :param ugraph: :param attack_order: :return: """ if USE_UF: return uf.compute_resilience_uf(ugraph, attack_order) else: return bfs_visited.compute_resilience(ugraph, attack_order)
5,327,837
def NumericalFlux(b, r, c): """Compute the flux by numerical integration of the surface integral.""" # I'm only coding up a specific case here assert r <= 1, "Invalid range." if b < 0: b = np.abs(b) # No occ if b >= 1 + r: return 1 # Get points of intersection if b > 1 ...
5,327,838
def build_volume_from(volume_from_spec): """ volume_from can be either a service or a container. We want to return the container.id and format it into a string complete with the mode. """ if isinstance(volume_from_spec.source, Service): containers = volume_from_spec.source.containers(stopped...
5,327,839
def generate_peripheral(csr, name, **kwargs): """ Generates definition of a peripheral. Args: csr (dict): LiteX configuration name (string): name of the peripheral kwargs (dict): additional parameterss, including 'model' and 'properties' Returns: stri...
5,327,840
def export_file(isamAppliance, instance_id, component_id, file_id, filepath, check_mode=False, force=False): """ Exporting the transaction logging data file or rollover transaction logging data file for a component """ if os.path.exists(filepath) is True: logger.info("File '{0}' already exists....
5,327,841
def map_vocabulary(docs, vocabulary): """ Maps sentencs and labels to vectors based on a vocabulary. """ mapped = np.array([[vocabulary[word] for word in doc] for doc in docs]) return mapped
5,327,842
def export_to_jdbc(self, connection_url, table_name): """ Write current frame to JDBC table Parameters ---------- :param connection_url: (str) JDBC connection url to database server :param table_name: (str) JDBC table name Example ------- <skip> >>> from sparktk import T...
5,327,843
def mobilenetv3_large_minimal_100(pretrained=False, **kwargs): """ MobileNet V3 Large (Minimalistic) 1.0 """ # NOTE for train set drop_rate=0.2 model = _gen_mobilenet_v3('mobilenetv3_large_minimal_100', 1.0, pretrained=pretrained, **kwargs) return model
5,327,844
def setup(upgrade=False): """ Setup virtualenv on the remote location """ venv_root = ctx('virtualenv.dirs.root') venv_name = ctx('virtualenv.name') venv_path = os.path.join(venv_root, venv_name) py = 'python{}'.format(ctx('python.version')) env.venv_path = venv_path if not fabtools...
5,327,845
async def remove(req): """ Remove a label. """ label_id = int(req.match_info["label_id"]) async with AsyncSession(req.app["pg"]) as session: result = await session.execute(select(Label).filter_by(id=label_id)) label = result.scalar() if label is None: raise Not...
5,327,846
def create_from_triples( triples_file, out_file, relation_name = None, bidirectional = False, head_prefix = PREFIXES["default"], tail_prefix = PREFIXES["default"] ): """Method to create an ontology from a .tsv file with triples. :param triples_file: Path for...
5,327,847
def get_identity(user, identity_uuid): """ Given the (request) user and an identity uuid, return None or an Active Identity """ try: identity_list = get_identity_list(user) if not identity_list: raise CoreIdentity.DoesNotExist( "No identities found for use...
5,327,848
def same_strange_looking_function(param1, callback_fn): """ This function is documented, but the function is identical to some_strange_looking_function and should result in the same hash """ tail = param1[-1] # return the callback value from the tail of param whatever that is return callback...
5,327,849
def put_output(dir_in, opts, Flowcell, Lane): """Uses shutil to move the output into galaxy directory""" seq1_name = '%(code)s_%(Flowcell)s_s_%(lane)s_fastq.txt'%\ ({'code': 'R1samplecode123','Flowcell':Flowcell, 'lane':Lane}) seq2_name = '%(code)s_%(Flowcell)s_s_%(lane)s_fastq.txt'%\ ...
5,327,850
def __extractFunction(text, jsDoc, classConstructor): """ Extracts a function depending of its pattern: 'function declaration': function <name>(<parameters>) { <realization> }[;] 'named function expression': <variable> = function <name>(<...
5,327,851
def vocabulary_size(tokens): """Returns the vocabulary size count defined as the number of alphabetic characters as defined by the Python str.isalpha method. This is a case-sensitive count. `tokens` is a list of token strings.""" vocab_list = set(token for token in tokens if token.isalpha()) return ...
5,327,852
def max_iteration_for_analysis(query: Dict[str, Any], db: cosem_db.MongoCosemDB, check_evals_complete: bool = False, conv_it: Optional[Tuple[int, int]] = None) -> Tuple[int, bool]: """ Find the first iteration that meet...
5,327,853
async def show_token(root: Root) -> None: """ Print current authorization token. """ root.print(await root.client.config.token(), soft_wrap=True)
5,327,854
def getMatirces(Dynamics, Cost): """ This functions takes the dynamics class as input and outputs the required matrices and cvxpy.variables to turn the covariance steering problem into a finite dimensional optimization problem. """ Alist = Dynamics.Alist Blist = Dynamics.Blist Dlist = Dy...
5,327,855
def get_transit_boundary_indices(time, transit_size): """ Determines transit boundaries from sorted time of transit cut out :param time (1D np.array) sorted times of transit cut out :param transit_size (float) size of the transit crop window in days :returns tuple: [0...
5,327,856
def example_3(): """Loads into tempory storage' """ from urllib.error import HTTPError from time import time import gc def cleanup(path): # Clean up the temp folder to remove the BerkeleyDB database files... for f in os.listdir(path): os.unlink(path + "/" + f) ...
5,327,857
def decode_gbe_string(s): """This helper function turns gbe output strings into dataframes""" columns, df = s.replace('","',';').replace('"','').split('\n') df = pd.DataFrame([column.split(',') for column in df.split(';')][:-1]).transpose().ffill().iloc[:-1] df.columns = [c.replace('tr_','') for c in co...
5,327,858
def get_scihub_namespaces(xml): """Take an xml string and return a dict of namespace prefixes to namespaces mapping.""" nss = {} matches = re.findall(r'\s+xmlns:?(\w*?)\s*=\s*[\'"](.*?)[\'"]', xml.decode('utf-8')) for match in matches: prefix = match[0]; ns = match[1] if prefix =...
5,327,859
def validate_args(args: Namespace) -> None: """ Validate the command line arguments Parameters ---------- args: :class:`~argparse.Namespace` Parsed command line arguments Raises ------ :class:`~montreal_forced_aligner.exceptions.ArgumentError` If there is a problem with...
5,327,860
def insert_df_to_table(df, table): """ Using cursor.executemany() to insert a dataframe Modified from: https://stackoverflow.com/a/70409917/11163214 """ conn = connect_to_postgres() cursor = conn.cursor() # Create a list of tuples from the dataframe values tuples = list(set([tuple(x) fo...
5,327,861
def test_server_options(mocker, server_opt): """ Test that the internal numbers of homogeneous programs are stored. WARN: All in one test because it doesn't work when create_server is called twice. """ # test attributes assert server_opt.parser is None assert server_opt.program_class == {} a...
5,327,862
def valid_verify_email(form, email): """ Returns true if "email" is equal the first email """ try: if(form.email.data!=form.email_verify.data): raise ValidationError('Email address is not the same') if models.Account.pull_by_email(form.email.data) is not None: pri...
5,327,863
def _computePolyVal(poly, value): """ Evaluates a polynomial at a specific value. :param poly: a list of polynomial coefficients, (first item = highest degree to last item = constant term). :param value: number used to evaluate poly :return: a number, the evaluation of poly with value """ #return numpy.polyval...
5,327,864
def schedule_job( client: scheduler_v1.CloudSchedulerClient, project_id: str, location_id: str, timezone: str, schedule: str, path: str, ) -> None: """ Schedules the given job for the specified project and location """ # Create a Job to schedule target = AppEngineHttpTarget(relative_...
5,327,865
def fix_e26(source): """Format block comments.""" if '#' not in source: # Optimization. return source string_line_numbers = multiline_string_lines(source, include_docstrings=True) fixed_lines = [] sio = StringIO(source) for (line_...
5,327,866
def graph_distance(tree, node1, node2=None): """ Return shortest distance from node1 to node2, or just update all node.distance shortest to node1 """ for node in tree.nodes(): node.distance = inf node.back = None # node backwards towards node1 fringe = Queue([node1]) while fri...
5,327,867
def trunicos(b): """Return a unit-distance embedding of the truncated icosahedron graph.""" p0 = star_radius(5)*root(1,20,1) p1 = p0 + root(1,20,1) p2 = mpc(b, 0.5) p3 = cu(p2, p1) p4 = cu(p3, p1*root(1,5,-1)) p5 = cu(p4, p2*root(1,5,-1)) return (symmetrise((p0, p1, p2, p3, p4, p5), "D5"...
5,327,868
def histogram2d( x1: torch.Tensor, x2: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10 ) -> torch.Tensor: """Function that estimates the 2d histogram of the input tensor. The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter. ...
5,327,869
def test_bond_explicit_ji(pcff): """Simple test of known bond parameters, ordered backwards""" i = "c" j = "h" ptype, key, form, parameters = pcff.bond_parameters(i, j) ptype2, key2, form, parameters2 = pcff.bond_parameters(j, i) assert ptype2 == "explicit" assert key2 == ("c", "h") asse...
5,327,870
def empty_iterator() -> typing.Iterator: """ Return an empty iterator. :return: an iterator :Example: >>> from flpy.iterators import empty_iterator, It >>> It(empty_iterator()).collect() ItA<[]> """ yield from ()
5,327,871
def update(Q, target_Q, policy, target_policy, opt_Q, opt_policy, samples, gamma=0.99): """Update a Q-function and a policy.""" xp = Q.xp obs = xp.asarray([sample[0] for sample in samples], dtype=np.float32) action = xp.asarray([sample[1] for sample in samples], dtype=np.float32) reward =...
5,327,872
def test_profile_increment() -> None: """Test the profile_increment method.""" m = MixpanelTrack( settings={ "mixpanel.profile_properties": "pyramid_mixpanel.tests.test_track.FooProfileProperties" }, distinct_id="foo", ) m.profile_increment(props={FooProfilePropertie...
5,327,873
def test_plot_generic_string_argument(): """do not see real use-case, beyond title, which is escaped in other ways. """ with autogpy.Figure("test_plot", file_identifier="figtest") as fig: fig.plot(XX_test_linspace, test_arg__s="2") fcontent = fig.get_gnuplot_file_content() assert 'test_arg ...
5,327,874
def error_heatmap(alloc_df, actual_df, demand_columns, region_col="pca", error_metric="r2", leap_exception=False): """ Create heatmap of 365X24 dimension to visualize the annual hourly error. Uses the output of `allocate_and_aggregate` function as input along with actual demand data to plot the annual ...
5,327,875
def webhooks_v2(request): """ Handles all known webhooks from stripe, and calls signals. Plug in as you need. """ if request.method != "POST": return HttpResponse("Invalid Request.", status=400) event_json = json.loads(request.body) event_key = event_json['type'].replace('.', '_') ...
5,327,876
def nth(iterable, n, default=None): """ Returns the nth item or a default value :param iterable: The iterable to retrieve the item from :param n: index of the item to retrieve. Must be >= 0 :param default: the value to return if the index isn't valid :return: the nth item, or the default value i...
5,327,877
def _dict_items(typingctx, d): """Get dictionary iterator for .items()""" resty = types.DictItemsIterableType(d) sig = resty(d) codegen = _iterator_codegen(resty) return sig, codegen
5,327,878
def send_messages(connection, topic, input): """Read messages from the input and send them to the AMQP queue.""" while True: try: body = pickle.load(input) except EOFError: break print('%s: %s' % (body.get('timestamp'), body.get('event...
5,327,879
def odd_desc(count): """ Replace ___ with a single call to range to return a list of descending odd numbers ending with 1 For e.g if count = 2, return a list of 2 odds [3,1]. See the test below if it is not clear """ return list(reversed(range(1,count*2,2)))
5,327,880
def validate_log_row(columns): """ :param columns: (name, email, datetime) tuple """ assert len(columns) == 3 for i in [0, 1]: try: # For Python 2.x assert isinstance(columns[i], basestring) except NameError: assert isinstance(columns[i], str) ...
5,327,881
def retrieval_score(test_ratings: pd.DataFrame, recommender, remove_known_pos: bool = False, metric: str = 'mrr') -> float: """ Mean Average Precision / Mean Reciprocal Rank of first relevant item @ N """ N = recommender.N user_scores = [] ...
5,327,882
def test_dump_load_keras_model_with_dict(tmpdir, save_and_load): """Test whether tensorflow ser/de-ser work for models returning dictionaries""" class DummyModel(tf.keras.Model): def __init__(self): super().__init__() def _random_method(self): pass def call(sel...
5,327,883
def stemmer_middle_high_german(text_l, rem_umlauts=True, exceptions=exc_dict): """text_l: text in string format rem_umlauts: choose whether to remove umlauts from string exceptions: hard-coded dictionary for the cases the algorithm fails""" # Normalize text text_l = normalize_middle_high_german( ...
5,327,884
def test_queue_trials(start_connected_emptyhead_cluster): """Tests explicit oversubscription for autoscaling. Tune oversubscribes a trial when `queue_trials=True`, but does not block other trials from running. """ cluster = start_connected_emptyhead_cluster runner = TrialRunner() def creat...
5,327,885
def get_bboxes(outputs, proposals, num_proposals, num_classes, im_shape, im_scale, max_per_image=100, thresh=0.001, nms_thresh=0.4): """ Returns bounding boxes for detected objects, organized by class. Transforms the proposals from the region proposal network to bounding box predictions ...
5,327,886
def air_transport_per_year_by_country(country): """Returns the number of passenger carried per year of the given country.""" cur = get_db().execute('SELECT Year, Value FROM Indicators WHERE CountryCode="{}" AND IndicatorCode="IS.AIR.PSGR"'.format(country)) air_transport = cur.fetchall() cur.close() ...
5,327,887
def outside_range(number, min_range, max_range): """ Returns True if `number` is between `min_range` and `max_range` exclusive. """ return number < min_range or number > max_range
5,327,888
def is_string_constant(node): """Checks whether the :code:`node` is a string constant.""" return is_leaf(node) and re.match('^\"[^\"]*\"$', node) is not None
5,327,889
def test_show_dimensions(capsys, nc_dataset): """show_dimensions prints dimension string representation """ nc_dataset.createDimension('foo', 42) nc_tools.show_dimensions(nc_dataset) out, err = capsys.readouterr() assert out.splitlines()[0] == ( "<class 'netCDF4._netCDF4.Dimension'>: nam...
5,327,890
def is_list_type(t) -> bool: """ Return True if ``t`` is ``List`` python type """ # print(t, getattr(t, '__origin__', None) is list) return t == list or is_pa_type(t, pa.types.is_list) or ( hasattr(t, '__origin__') and t.__origin__ in (list, List) ) or ( isinstance(t, dict) and i...
5,327,891
def get_measure_of_money_supply(): """ 从 Sina 获取 中国货币供应量数据。 Returns: 返回获取到的数据表。数据从1978.1开始。 Examples: .. code-block:: python >>> from finance_datareader_py.sina import get_measure_of_money_supply >>> df = get_measure_of_money_supply() >>> print(df.iloc[0][df.c...
5,327,892
def p_parametro(production): """parametro : tipo DOIS_PONTOS ID | parametro ABRE_COL FECHA_COL """ node = Parametro() first_name = production[1].id if first_name == "TIPO": node.insert_node_below(production[1]) node.insert_node_below(Token(identifier=':')) n...
5,327,893
def getallbdays_ml(): """Reads all the saved files and parses all birthdays. If parsing is unsuccessful, writes the line into a file.""" # Open up the file to write failed lines failfile = u'./data-failedlines-v2.dat' failedlines = codecs.open(failfile, 'w', 'utf-8') fails = 0 # Open up...
5,327,894
def create_all(): """Create the complete TkinterPmwDemo.""" root = Tk() Pmw.initialise(root) root.title('Tkinter/Pmw Demo') # tk_strictMotif changes the file dialog in Tk's OpenFile etc. #root.tk_strictMotif(1) #Pmw.initialise(root,fontScheme='pmw1') #import scitools.misc; scitools.misc....
5,327,895
def _SparseMatrixAddGrad(op, grad): """Gradient for sparse_matrix_add op.""" # input to sparse_matrix_add is (a, b, alpha, beta) # with a, b CSR and alpha beta scalars. # output is: alpha * a + beta * b # d(a*A + b*B)/dA . grad = a * grad # May have gotten the transposes wrong below. # d(a*A + b*B)/da ....
5,327,896
def download( filename, data, contentType=None, sessionId="current_session", pageId="current_page", ): """Downloads data from the gateway to a device running a session. Args: filename (str): Suggested name for the downloaded file. data (object): The data to be downloaded. Ma...
5,327,897
def make_inverter_path(wire, inverted): """ Create site pip path through an inverter. """ if inverted: return [('site_pip', '{}INV'.format(wire), '{}_B'.format(wire)), ('inverter', '{}INV'.format(wire))] else: return [('site_pip', '{}INV'.format(wire), wire)]
5,327,898
def test_encodes_semantic_meaning(): """ Check if the distance between embeddings of similar sentences are smaller than dissimilar pair of sentences. """ docs = DocumentArray( [ Document(id="A", text="a furry animal that with a long tail"), Document(id="B", text="a d...
5,327,899