content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def weighted_average(gini_or_entropy_left, left_cnt, gini__or_entropy_right, right_cnt): """ calculate weighted average for Gini index or Entropy :param right_cnt: count of total records on the right side of node :param left_cnt: count of total records on left side of node :param gini_or_entropy_le...
7914a0164427de4e9cebf7637dda670694f8df59
3,601,600
import torch def concat_entities(entities): """ Concat multiple graphs via concatenation of their entities tensors. Parameters ---------- entities: a list of graph tuples. Either [(v,e,c),...] or [(v,e),...] when the graph has no global attribute. Returns v,e,c - concatenated entities...
06d0619836d4cb8c977028ee0cdccd9075136c72
3,601,601
def format_filesize(num, suffix='B'): """ See: https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) ...
2647aad4f4e09d9253b34b4ec39f601a3a558717
3,601,602
def filter_out_installed_pkgs(event_out_pkgs, installed_pkgs): """Do not install those packages that are already installed.""" return {p for p in event_out_pkgs if (p.name, p.modulestream) not in installed_pkgs}
16fb8f68372fb070869a744b15ddce0ed6591887
3,601,603
import os import json def geocode_mapycz(queries, locality='', limit=1, lang='cs', cap=1000): """ Geocode places via Mapy.cz using Selenium. Parameters: queries (list): Places to be queried for geocoding locality (string): Locations to which limit geocoding limit (int): Number of matches to b...
394d9063db9187c221bc0fa602ead66120cb3228
3,601,604
def maxlinedev(x, y): """ Find the point of maximum deviation in the contour from a line joining two points on the contour. Input: x, numpy array of abscissas of the contour y, numpy array of ordinates of the contour Output: maxdev, maximum deviation idxmaxdev, index of the ...
37f666f17aa56a7c50dc7a55d7be567d179c8a27
3,601,605
def vcs_org_url(orgname=None): """ Returns VCS endpoint for orgs in general or the specified org """ url = VCS_URL_BASE + "/orgs" if orgname == None: return url return url + "/" + orgname
38be1c95082bbf0d61ed9039edd01043b2a99703
3,601,606
def stats_variance_2d(data, ddof=0, axis=1): """Pre compiled method to get 2d variance.""" a_a, b_b = data.shape if axis == 1: var = np.zeros(a_a) for i in range(a_a): var[i] = _stats_variance_1d_2d(data[i], ddof=ddof) return var else: var = np.zeros(b_b) ...
acca95077d43ae63f88fda26d4320cfbaa628b8f
3,601,607
def root(): """Root.""" return redirect(url_for('sender.create'))
d08d4a328d4832a7b48f75db761b2e49332e4efc
3,601,608
def add_roi_Xconv1fc_head(model, blob_in, dim_in, spatial_scale): """Add a X conv + 1fc head, as a reference if not using GroupNorm""" hidden_dim = cfg.FAST_RCNN.CONV_HEAD_DIM roi_size = cfg.FAST_RCNN.ROI_XFORM_RESOLUTION roi_feat = model.RoIFeatureTransform( blob_in, 'roi_feat', ...
560a391a189c4415da18ab01e3670ca1eb6b69f7
3,601,609
def ensure_str(s, encoding='utf-8', errors='strict'): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (text_type, binary_type)): raise TypeErr...
9f92e636351332f5cb84677fe7555186b21779f9
3,601,610
def query_database(database, username, password, hostname, query, port=3306): """ Input: database, username, passward, hostname: str Output: pd.Dataframe with display all columns """ conn = pymysql.connect(db=database, user=username, password=password, host=hostname, port=port) cur = conn.curs...
ba602979e4d6a1addb2cfc0be44ce9ab23e62549
3,601,611
import subprocess def dictFromPsrcat(sourceName): """Generate a dictionary from an entry in psrcat sourceName: str, psrcat source name returns: dict """ result = subprocess.run('%s -nonumber -nohead -c \'JNAME RAJD DECJD P0 P1 W50 S1400 DM RAJ DECJ\' %s'%(PSRCATBIN, sourceName), shell=True, stdou...
3ad9159b6b0b1f42e90c23f6d916440e4ce5f738
3,601,612
import os def is_using_wayland() -> bool: """Check if we are running on Wayland DE. Returns [bool] -- {True} if probably Wayland """ return "WAYLAND_DISPLAY" in os.environ
2c361ecdada0dfb55101cb0e06290d7033bcfbf1
3,601,613
def exposed_dbus_prop(name): """Exposed a property on DBus and cache locally""" local_key = '__%s' % (name,) def _getter(self, name): return self.__dict__[local_key] def _setter(self, name, value): self.__dict__[local_key] = value self.props_iface.Set( self.DBUS_NAM...
6458decc814d9a5c055a409c13ae46501f59c7cd
3,601,614
from typing import Union def get_generator_regulation_raise_term_3(data, trader_id, intervention) -> Union[float, None]: """Get R5RE term 3 in FCAS availability calculation""" # Parameters enablement_max = get_effective_enablement_max(data, trader_id, 'R5RE') energy_target = lookup.get_trader_solutio...
f3c9316d7b5b9779bb01b301d6ccea5b3cb94bf4
3,601,615
from cblaster.extract_clusters import get_sorted_cluster_hierarchies def binary( session, hide_headers=False, delimiter=None, key=len, attr="identity", decimals=4, sort_clusters=False, ): """Generates a binary summary table from a Session object.""" # prevent a circular import ...
3544af05a8f41a84e2d9147a8bdca81dc7da4cde
3,601,616
import sys def main(): """Produces an llvm-cov style JSON summary from a JaCoCo XML report.""" if len(sys.argv) != 3: sys.stderr.write('Usage: %s <path_to_jacoco_xml> <out_path_json>\n' % sys.argv[0]) return 1 with open(sys.argv[1], 'r') as xml_file: xml_report = xml_file.read(...
184cbcf4c8a5ddcd3a25be54f950bc9233ed0e8a
3,601,617
def decode_entities(html): """ Convert all HTML entities into their unicode representations. This functions processes following entities: * &XXX; * &#XXX; Example:: >>> print html.decode_entities('&rarr;ABC&nbsp;&#82;&copy;') →ABC R© """ def process_entity(matc...
70bf67af162d932f3200ce3b63fcc254826cd21d
3,601,618
from typing import Container def get_container() -> Container: """Returns container used for resolving and registering dependencies""" return _CURRENT_CONTAINER.get()
10ac514fbeaf9550d4e336f9b6be98e92bad5d8c
3,601,619
import tqdm def get_raw_downloads(in_file): """ Gets raw download statistics for each node (file, URL, IP) """ raw_downloads = {} with open(in_file, 'r') as f: for line in tqdm(f): line = line.rstrip() values = line.split('\t') if len(values) > 15: ...
795c2ede7f34c2add0d8c049398db50d8e78a7e8
3,601,620
def callbacks(cbs): """Decorator that attaches callbacks to a function. Callbacks should be defined as classes inheriting from abstract base class Callback that implement on_begin and on_end methods. This allows us to store states rather than just printing outputs or relying on global variables. Pa...
113e929fd6e34c17e16bad692ecae2bc0cbf71ea
3,601,621
def update_simulation(n_clicks, *args): """ Simulates the model for the current slider values and updates the subplots in the figure when the Run button is clicked. Reset the app when the Reset button is clicked. """ ctx = dash.callback_context if ctx.triggered: input_id = ctx.trigge...
8066682c4666a5264cc03b90756428ef8407de03
3,601,622
def get_itime_section_data(date, time): """ Get data for ITIME section Parameters ---------- time : int Time interval Returns ------- out : np.array Array of items See Also -------- np.array Examples -------- >>> l = get_itime_section_data(5) ...
6e2af095301bd8fce5b8f98d5b08351862d2b8f5
3,601,623
def delete_safe_member_command( client: Client, safe_name: str, member_name: str, ) -> CommandResults: """Remove a specific member from a safe. :param client: The client object with an access token :param safe_name: Name of the safe to which the safe member belongs. :param member...
3e2a2e3e4977596d61addccdaa39ebdea566e72a
3,601,624
def filter(datastream, src_field, pred): """ Filters out fields that yield a given criteria. :param datastream: input datastream :param src_field: field of list of fields to consider :param pred: predicate function. If `src_field` is one field, than `pred` is a function of one argument returning boo...
aa1362cc57aebdc6cb93e3cf307d87d403bd5714
3,601,625
def get_imts_periods(imtls): """ Returns a list of IMT strings and a list of periods. There is an element for each IMT of type Spectral Acceleration, including PGA which is considered an alias for SA(0.0). The lists are sorted by period. :param imtls: a set of intensity measure type strings :re...
5e0f9f5a3a3d416af04ac3f3f76c3d0bd793b495
3,601,626
def truedicts(all): """ Generates a pair of dictionairies containg all true tail and head completions. :param all: A list of 3-tuples containing all known true triples :return: """ heads, tails = {(p, o) : [] for _, p, o in all}, {(s, p) : [] for s, p, _ in all} for s, p, o in all: ...
03c126ff6cdc0cc14be1c64a91e8164e890c2f2d
3,601,627
import math def RotateXY(x, y, xc=0, yc=0, angle=0, units="DEGREES"): """Rotate an xy cooordinate about a specified origin x,y xy coordinates xc,yc center of rotation angle angle units "DEGREES" (default) or "RADIANS" """ x = x - xc y = y - yc # make angle clockwise (l...
68d24bfd5b2cf436b1ea37c0d4124f6cfa357e9f
3,601,628
def extract_zip_archive(zip_file_path, target_directory, allowed_file_extensions=None): """ Extract zip file and return file paths of content. Returns a tuple of extracted and invalid files:: extracted_files, invalid_files = extract_zip_archive(zip_file_path, target_directory, allowed_file_extensions) ...
1d68038d274fc15bf00f5a6683fa4e1ed0fd8fd9
3,601,629
def vectorize_tokens(tokens): """ Turns a file into a vector of indices (not a one-hot vector per token!). Automatically inserts start and end tokens. >>> from corpus import Token >>> vectorize_tokens([Token(value='var', type='Keyword', loc=None)]) (0, 86, 99) """ def generate(): ...
9f310c5038fff925f63cd80e833d51964506c7a0
3,601,630
def _extract_gpcrdb_residue_html(txt): """ Extracts the relevant lines for all residues from a GPCRdb html entry. Parameters ---------- txt : str Content (html) of the website with the GPCRdb entry. Returns ------- residue_html : list A list in which...
4621848f27b9cd24017ed5c49683bfc4b8a180e8
3,601,631
def _vrsqrt_newton(num_to_vrsqrt): """Calculate vrsqrt(num_to_vrsqrt) with newton's method.""" start_value = topi.rsqrt(num_to_vrsqrt) # use newton's method 3 times newton_res_1 = _newton(start_value, num_to_vrsqrt) newton_res_2 = _newton(newton_res_1, num_to_vrsqrt) newton_res_3 = _newton(new...
ebd24e70b62058095c03cfaec1a61270e3b04868
3,601,632
def _random_customer(cust_dtls) -> tuple: """Return a random account number made of 12 characters.""" return choices(cust_dtls)[0]
0e2732b9357ae5bae248a41d877ce2b12c3228f9
3,601,633
from typing import List from sys import path def generate_declared_arguments() -> List[DeclareLaunchArgument]: """ Generate list of all launch arguments that are declared for this launch script. """ return [ # World for Ignition Gazebo DeclareLaunchArgument( "world", ...
225d21e1951bd42ac6ef8f5b3aeb15a5442a7c93
3,601,634
def getpassword(path): """Get password from an encoded file. Input: path -- source path. Output: passwd -- password. """ # Prepare cipher abs path cipher_abs_path = get_abs_path(path) # Read cipher if exists(cipher_abs_path) and isfile(cipher_abs_path): with ope...
075fc6f01a7de23c51dbbfa109e10a2935e0fd35
3,601,635
def is_type_int16(*args): """ is_type_int16(t) -> bool Does the type specify a 16-bit value? (signed or unsigned, see 'Basic type: integer' ) @param t (C++: type_t) """ return _ida_typeinf.is_type_int16(*args)
37b1ae865d31f3c362128975cef19d973bf325fb
3,601,636
from typing import List def convert_verse_ids_to_references(verse_ids: List[int]) -> List[NormalizedReference]: """ :param verse_ids: :return: a list of normalized references """ references: List[NormalizedReference] = [] if verse_ids is None or not verse_ids: return references ...
6c1f33433d14af58be8adeeb39b1a19e81464ba6
3,601,637
import logging import json import time def collect(type, **kwargs): """Collect result of a task of the given type.""" task_id = str(generate_uuid()) # Check if the task is in the local cache. cache = load_cache() if task_id in cache: logging.info("Cached result found for {}".format(task_i...
366b7fbb5d6623736b3eb2d968aae689ac25375b
3,601,638
def reset_entry_registry(fn): """Decorator for tests using entry node registry """ def wrapper(*a, **kw): root = get_root() factories = set(root.factories.keys()) try: fn(*a, **kw) finally: for key in set(root.factories.keys()).difference(factories): ...
292bab2cd92f4b5eb67e1d3ed151f876f63a2bca
3,601,639
def logsumexp(arr, axis=None): """Computes the sum of arr assuming arr is in the log domain. Returns log(sum(exp(arr))) while minimizing the possibility of over/underflow. Examples -------- >>> import numpy as np >>> a = np.arange(10) >>> np.log(np.sum(np.exp(a))) 9.45862974442671...
f32c7c7a295b548913057f8e78e77a934d290e03
3,601,640
def bezier2_h(t, hs): """ evaluate quadratic bezier curve at t and project result """ x = bezier2(t, hs) return la.proj(x)
a633e153e33850e45c2522824ca4ac00e961d816
3,601,641
import hashlib def first_half(): """ first half solver: find MD5 hashes which, in hexadecimal, start with at least five zeroes. iwrupvqb followed by a number in decimal. To mine AdventCoins, you must find Santa the lowest positive number that produces such a hash. """ n = 1 while n: ...
6c84da1dabd442cc1b28db4e09e1c67fb998a302
3,601,642
import math def init_cv(dataset, fold=0, folds=8, validation=5, shuffle=False, seed=None): """ Initialize Cross-Validation returns three indexes """ n_samples = len(dataset) whole_range = np.arange(n_samples) if shuffle: _state = None if seed is not None: _s...
d9e5ddb8dfe6c52e71a328a4b983034121e30057
3,601,643
def seq2set(xs) : """ bijection from sequences to sets """ rs=[] s = -1 for x in xs: sx=x+1 s+=sx rs.append(s) return rs
b90ec731ce35539240c43d4c616889f71ca7c982
3,601,644
def strike_slip_from_rake_mag(rake, slip_mag = 1., input='degrees'): """ Calculates the strike slip magnitude from slip rake and magnitude. Positive values indicate right-lateral slip. Rake is in Aki and Richards convention (0 = right-lateral, 90 = reverse, 180/-180 = left-lateral, -90 = normal). ...
3ca70027dbfd7ce4df79587e2613b8dc0e087798
3,601,645
def calc_residual(coeff, pcs_arr, light_curve_flux, light_curve_err, map_dates_to_arr_index): """ function to calculate residual of the fit Parameters ---------- coeff: np.array of shape [num_of_pcs] current value of coefficients pcs_arr: np.array of shape [num_pcs, num_prediction_point...
2f7352a1eeffafe55f1cc85ec9e810e52fa7118c
3,601,646
def preprocess_example(image, labels): """Map functions applied to image classification exampels / batches.""" image = tf.cast(image, tf.float32) / 255 return image, labels
b00545df670e7ba3869245fb8ed228e91b9f8e60
3,601,647
def simple_tag_without_context_parameter(arg): """Expected simple_tag_without_context_parameter __doc__""" return "Expected result"
aad64452d051a587447696c6bd616b04f3f5b23e
3,601,648
import random import string def create_ref_code(): """Generate a random reference code.""" return "".join(random.choices(string.ascii_lowercase + string.digits, k=10))
9b09449a8a10e98fc91aa9a6e6773e30d4aa8caf
3,601,649
def removeDuplicates(arr, indices): """ Takes an arr and a sorted list of indices. Removes arr[i] for i in indices and returns a new array. if arr is 2D, removes the i^{th} row for i in indices. :params arr: np.array. e.g., a timeline :params indices: sorted list of indices to remove. :returns ...
16984e28a858a0a9f896628a9740906e57a8b482
3,601,650
def view_election_compound_party_strengths_chart(self, request): """" View the party strengths as grouped bar chart. """ @request.after def add_last_modified(response): add_last_modified_header(response, self.last_modified) return { 'model': self, 'layout': DefaultLayout(self,...
33df0ec1f8ef07f23ccadf943940c2a536984dfc
3,601,651
def _validate_task_type_and_task_id(cluster_spec, task_env, chief_task_type): """Validates the task type and index in `task_env` according to cluster.""" if chief_task_type not in cluster_spec.jobs: raise ValueError( 'If "cluster" is set in TF_CONFIG, it must have one "%s" node.' % chief_task_ty...
7d46e24dd06f17e2f42de54e107c4246635da7d6
3,601,652
from typing import Type def make_hardware_module( decoy: Decoy, type: Type[HardwareModuleT], serial_number: str ) -> HardwareModuleT: """Return a mock hardware module with the specified type and serial number. Ideally, we wouldn't use mocks for this, since our subject uses these objects as pure input...
262bd44af3898f7e53166067a0100fe9b21a4bad
3,601,653
def readGeneralData(filename): """Reads simulation data (includes printing data) from a given file.""" pfile = open(filename,'r') # Read numerical scheme scheme = lire_ligne(pfile).split() scheme = int(scheme[0]) # Read space discretisation information dx,xmax = lire_ligne(pfi...
8f9eeba56dfba6438cdb68623636d432cbb5964c
3,601,654
def VerificaRestricaoOrcamento(s, valor, dados, debug=False): """ Documentação: """ custo = 0 for sonda in s.keys(): for node in s[sonda]: if node.data[0] != -1: custo += dados[20][node.data[0]] if (debug): if round(custo, 5...
0ab52e303a1b5b6399585ecddf63e0b70e8259cb
3,601,655
from typing import Tuple def default_artifact_processor(artifact: riberry.model.job.JobExecutionArtifact) -> Tuple[str, dict]: """ Returns basic information for generated artifacts """ return artifact.filename, { 'name': artifact.name, 'type': artifact.type.value, 'category': artifact...
2ace58d7b9e52d192d9a47e395f527e5edac6b87
3,601,656
def list_datasets_view(user_data, cache): """List all datasets in project.""" return DatasetsListCtrl(cache, user_data, dict(request.args)).to_response()
884c710d606edc311aa68298b2874f9b8a9b33b1
3,601,657
import re def uuid(value: str): """ Validator for Universally unique identifier Example Result: [123e4567-e89b-12d3-a456-426655440000, 6a2f41a3-c54c-fce8-32d2-0324e1c32e22] Detail: https://en.wikipedia.org/wiki/Universally_unique_identifier#Format """ _uuid_pat = r'[0-9a-fA-F]{...
66f498669b52df2e3ff9ea281fb781cb6774c77c
3,601,658
def decode_integer(data, prefix_bits): """ This decodes an integer according to the wacky integer encoding rules defined in the HPACK spec. Returns a tuple of the decoded integer and the number of bytes that were consumed from ``data`` in order to get that integer. """ if prefix_bits < 1 or ...
ce6b782a566bc362556a1837f5f3a8502758be1b
3,601,659
def openMultiple(parent=None, title='Open', directory='', filename='', wildcard='All Files (*.*)|*.*', style=wx.OPEN | wx.MULTIPLE): """File dialog wrapper function.""" return fileDialog(parent, title, directory, filename, wildcard, style)
ffbbe6a185b61127fab8222cb426bb84ee85ad8b
3,601,660
def search_customer(request): """ :param request: :return: """ t = loader.get_template('NearBeach/search/search_customers.html') # Get the first 50 customers customer_results = customer.objects.filter( is_deleted=False, ).order_by('customer_last_name','customer_first_name')[:50]...
7fe06a13d20b734286c92e2b3813755da30c8528
3,601,661
def merge_rows(df_arr: list,start: int,end: int): """ 同一日時のデータをマージする関数 設定では温度取りローデータのディレクトリ内には複数のデータに分割されてファイルが配置されている 同じ日時のデータに合わせるために指定した範囲でデータをまとめる作業を行う デフォルトでは4ファイルごと Args: df_arr [list] : 1ファイルごとのDataFrameが入ったリスト start [int] : 開始時の添字 end [int] : 終了時の添字...
0e80390db888809478a480eeb862960df0d987fc
3,601,662
import requests import json def _update_latest_version(server, key, bundle, data): """Update latest version for the specified bot""" j = json.dumps(data) http_headers = {'API_KEY': key, 'Content-Type': 'application/json'} r = requests.put(server + '/cloud/developer/versions?bundle=' + bundle, headers=...
c7be988910c07114b58bbf589af57b7cd2879989
3,601,663
def reset_command_registry(): """Create empty global command registry""" global _command_registry _command_registry = CommandRegistry() return _command_registry
f581b2c67a7396bb36f3c9f955190a9f89d3085d
3,601,664
async def mongoengine_notregistered_exception_handler(request, exc): """ logs the NotRegistered error detected and returns the appropriate message and details of the error """ logger.debug(exc) return JSONResponse( Response(success=False, error_code=422, message=str(exc)).dict() )
fb868ee2a8a4a14392a8b9f36afdc67080e8429a
3,601,665
def compute_AT(ic) -> float: """ Args: ic (IC): indepentent component. Returns: float: Alpha Topography - Difference between weights in frontal-central sites and other sites """ return np.abs(ic.select_weights(FC).mean()) - np.abs(ic.select_weights(FC_not).mean())
2dbcd23376956330168464acf2ad9ab95db7d70e
3,601,666
def build_inpainter(input_shape=(None, None, 4), downsample=1, instance_norm=False): """ Build the full inpainting network :downsample: reduce number of kernels by this factor """ with tf.name_scope("downsampler"): downsampler = InpainterDownsampler(input_shape, downsample=downsample, ...
d49d38120459546ad6eed2b9b1c5bc39e36b26a3
3,601,667
def get_cooldown(member: discord.Member, cmd: Command): """ Returns the member's time left as a str or None. """ if member not in cooldown_data: return None for cooldown in cooldown_data[member]: if cooldown.command == cmd or cooldown.command is None: diff = cooldown.date - ...
734b97f71fda03051908bd154fbd6d2bc710d46c
3,601,668
import uuid from datetime import datetime def formatCloudEvent(message: str, subject: str) -> str: """ Returns a correctly formatted CloudEvents compliant event """ attributes = { "specversion" : "1.0", "type" : "org.tmforum.for.type.event.an.invented.burton.brian", "source" : ...
128d7791e6d4225f62764d382b6934b9e03f49a4
3,601,669
from pathlib import Path async def validate_item_id( item_id: int = Path(...), db_session: Session = Depends(get_db_session) ) -> Item: """Validates the if an item is present with the given id. Args: item_id: int. The id of the item. db_session: Session. The database session u...
c27801b445b56ccfc16f0138bf88bdc68d819485
3,601,670
import json def status(if_statuses): """Status Arguments: if_statuses {list} -- List of interface statuses Returns: str -- Pretty printed output """ status = HEADER status_template = "{0:<9} {1:<4}\n" if if_statuses is None: return status if_statuses ...
bae6ec2283fb598880281c03def375a36518fc98
3,601,671
def decode(code): """Decode morse code to char """ return CODE2CHAR[code]
8f16ef0269183656ae00090dc6d36d2533f874f2
3,601,672
def standard_plot(dic_of_hists,normalise,xaxis_label): """ standard_plot() displays the (normalised or unnormalised) histograms """ hep.style.use(HEP_histogram_design_parameters["experiment"]) fig,ax = plt.subplots() fig.set_size_inches(6,6) HEP_histogram_design_parameters["HEP experimen...
c0a69d519632d9fca1c6037c458cde7889fc7914
3,601,673
from typing import Optional from typing import Dict import tempfile import os def compile_solidity_code(code: str, working_directory: Optional[str] = None, optimizer_runs=cfg.opt_solc_optimizer_runs) -> Dict: """ Compile the given solidity code with default settings. :param code: code to compile :par...
08c7d6b951770c802c92c6720c627091930aff8a
3,601,674
def information(stock): """gets current information about a certain stock :param stock: stock that will be analyzed :return stock information""" stock = yf.Ticker(str(stock)) return stock.info
756c0a7cbaad19610b41c79f8e921ba27400aeb2
3,601,675
def _DoWeHaveLocalCommits(stable_branch, tracking_branch, cwd): """Returns true if there are local commits.""" output = git.RunGit( cwd, ['rev-parse', stable_branch, tracking_branch]).output.split() return output[0] != output[1]
8c5626ea4c73227966ff713cc1747c64ea2daa30
3,601,676
def LikelihoodRedshiftMeasures( measures=[], datas=[], scenario=False, prior=True, renormalize=False, measurable=False ): """ returns likelihood functions of redshift for observed datas of measures, can be used to obtain estimate and deviation Parameters ---------- measure : string in...
836bd2d07f366d5aa6606bb63ec519a552ad72d5
3,601,677
def generate_mnemonic(strength=256, wordlist=wordlist): """Generate random mnemonic Args: strength (int, optional): The number of bits of the generated key. Defaults to 256. wordlist (list[str], optional): The Word list used to generate the mnemonic. Defaults to wordlist. Returns: ...
75afeed28588ee1c545f59fc7b1393305d99653f
3,601,678
def configuration(request): """Set up a Configurator instance. This Configurator instance sets up a pointer to the location of the database. It also includes the models from your app's model package. Finally it tears everything down, including the in-memory SQLite database. This configurat...
d88a25ae0afeaa78e8ac4bb18734164877c6a21b
3,601,679
def read_dictionary(): """ This function reads file "dictionary.txt" stored in FILE and appends words in each line into a Python list """ global dict_lst with open(FILE, 'r') as f: for line in f: line = line.strip() dict_lst.append(line) return dict_lst
dcc71077146f713cf5a364319dbcad9de6d73353
3,601,680
def O2_molar2umkg(oxygen_conc=None, salinity=None, temperature=None, pressure=None): """unit conversalinity=Noneion for micromole/liter -> micromole/kg""" sigmatheta_pri = sw.eos80.pden(salinity, temperature, pressure) density = sigmatheta_pri / 1000 oxygen_conc = oxygen_conc / density return oxyg...
3bf2eaa4bdd1261d83ed41a88a2ef4933ce28f28
3,601,681
def find_coords(image, fourier_center, fourier_y, fourier_x, y_axis, x_axis): """ Convert the fourier positions to image axes. Do not use numba to accelerate as LLVM IR throws an error from the the if statements Parameters ---------- image: ndarray Original image four_c: nd...
73ee22179acf87da6f0986dddf3375c3bbb52176
3,601,682
def _extract_feats(data_test, model, what, skip=1, batch_size=16): """ :param data_test: test Dataset :param model: network model :param what: SK or IM :param skip: skip a certain number of image/sketches to reduce computation :return: a two-element list [extracted_features, extracted_labels] ...
27f19d26396c778626f3792080cd34df5e7ca343
3,601,683
from typing import Tuple from typing import Dict def field_annotations(typed_dict) -> Tuple[Dict[str, type], Dict[str, type]]: """Return the required and optional fields in the TypedDict.""" return (typed_dict.__annotations__["required_fields"].__annotations__, typed_dict.__annotations__["optional...
2e88481a1668cd40caacb8bfc91a50c8746a704e
3,601,684
def _SetDiskSize(build_config, messages, arg_disk_size): """Set the disk size used to run the build.""" if arg_disk_size is not None: disk_size = compute_utils.BytesToGb(arg_disk_size) if not build_config.options: build_config.options = messages.BuildOptions() build_config.options.diskSizeGb = int...
802d361800e9690f5edbd4214e46a264958f78a5
3,601,685
def frobenious_norm_squared(X): """Calculate :math:`||X||_{F}^{2}`""" return np.power(X, 2).sum()
8a28d4ba9281a6fc2fbd2c0a14fb9b4939e93aba
3,601,686
def read_record(fd): """Read a Record from a file handle. :returns: A Record from the file :rtype: BlipRecord """ header = fd.read(BlipRecord.converter.size) try: magic, exchange, length, payload_type = BlipRecord.converter.unpack(header) except struct_error: raise IncorrectLengthEx...
1c7308c7acda6a52513728524d7935c51cba4487
3,601,687
def _clip_grad_norms(gradients_to_variables, max_norm=10): """Clips the gradients by the given value. Args: gradients_to_variables: A list of gradient to variable pairs (tuples). max_norm: the maximum norm value. Returns: A list of clipped gradient to variable pairs. """ grads_and_vars = [...
6ed880bffc279c409cdf5c9fb615431eb24b7618
3,601,688
import os import subprocess def run_cmd(command, work_dir=None): """ Run shell command. Input: command - string of command to run work_dir - working directory Returns: output_str Raises: CommandException ReturnCodeError """ if work_dir is not ...
4eb2983b391b1e2173cb2630a00599cb46931f4f
3,601,689
def cmd_create(nexus_client, args): """Performs ``nexus3 repository create`` commands""" recipe_name = _args_to_recipe_name(args) repo_type = _args_to_repo_type(args) kwargs = { 'nexus_client': nexus_client, 'recipe': recipe_name, 'blob_store_name': args.get('--blob'), '...
785f925bdb15760c07e45934767e0b06ede962aa
3,601,690
from typing import Optional def connection(conn: Optional["AbstractConnection"]) -> str: """ Formats connection to a string logged in stats :param conn: Connection :return: formatted string """ if conn is None: return "<None>" return conn.format_connection_desc
41b5a75e12ab692c72ef14de424c9043dce99f1f
3,601,691
def line_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD, debug = False): """Similarity between two lines Args: p1a ([float, float]): x and y coordinates. Line A start p1b ([float, float]): x and y coordinates. Line A end p2a ([float, float]): x and y coordinates. Line B start...
8826a2fa08cd37b82f707d764c13dd97f462cd18
3,601,692
def orthogonal_initializer(shape, gain=1., seed=None): """Initializer that generates a random orthogonal matrix. # Arguments gain: Multiplicative factor to apply to the orthogonal matrix. seed: A Python integer. Used to seed the random generator. # References Saxe et al., http://...
2599e898e085d1c387bc43066700543919312b33
3,601,693
from tpDcc.dccs.maya.core import gui def get_camera_sequencer_panel(): """ Returns Maya Camera Sequencer Panel as a QtWidget :return: QtWidget or None """ open_camera_sequencer_window() sequencer = maya.cmds.getPanel(scriptType='sequenceEditorPanel')[0] qt_obj = gui.to_qt_object(sequencer)...
d58dd69535b8bd5bb95de398abb3754c832f708f
3,601,694
import os def get_config_log_dir(): """ Retrieve logging directory, create it if it doesn't exist. """ log_dir = os.path.expanduser(os.path.join(u'~', u'.mssqlscripter')) if (not os.path.exists(log_dir)): os.makedirs(log_dir) return log_dir
dd30794544f19083b74635d2a4c82621f2fd16ba
3,601,695
def load_data(): """ Return the MNIST data as a tuple containing the training data, the validation data, and the test data.""" f = open('../data/mnist.pkl', 'rb') training_set, validation_set, test_set = cPickle.load(f) f.close() return (training_set, validation_set, test_set)
31f7f336ab32937f6f5b52d6e59cefda60a4e8a3
3,601,696
def importmod(modname): """Import module according to policy and check API version""" try: verpkg, purepkg = _packageprefs[policy] except KeyError: raise ImportError('invalid HGMODULEPOLICY %r' % policy) assert verpkg or purepkg if verpkg: pn, mn = _modredirects.get((verpkg, ...
2eeb095b5bc25467eaf4195bf8404c146ad59994
3,601,697
import json async def gadmin(): """ :return : 分群管理json对象 """ async with aiofiles.open(config_group, mode='r') as f: admins_ = await f.read() admins = json.loads(admins_) return admins
0203a208e8e83f5eb866d2288ab4a7a21e70881f
3,601,698
import sqlite3 def get_member_data(member_id: str, conn: sqlite3.Connection) -> dict: """ Gets email and phone data from database based on passed member. This function uses placeholders in query so it is injection safe. Look up get_member_data_injection for example where it's NOT injection safe. "...
a4ca505961352e292109e22318ff7a0188ffc454
3,601,699