content
stringlengths
22
815k
id
int64
0
4.91M
def format_batch_request_last_fm(listens: List[Listen]) -> Request: """ Format a POST request to scrobble the given listens to Last.fm. """ assert len(listens) <= 50, 'Last.fm allows at most 50 scrobbles per batch.' params = { 'method': 'track.scrobble', 'sk': LAST_FM_SESSION_KEY, ...
5,350,500
def train_eval( root_dir, gpu=0, env_load_fn=None, model_ids=None, reload_interval=None, eval_env_mode='headless', num_iterations=1000000, conv_1d_layer_params=None, conv_2d_layer_params=None, encoder_fc_layers=[256], actor_fc_layer...
5,350,501
def file_mtime_ns(file): """Get the ``os.stat(file).st_mtime_ns`` value.""" return os.stat(file).st_mtime_ns
5,350,502
def get_entry_for_file_attachment(item_id, attachment): """ Creates a file entry for an attachment :param item_id: item_id of the attachment :param attachment: attachment dict :return: file entry dict for attachment """ entry = fileResult(get_attachment_name(attachment.name), attachment.cont...
5,350,503
def fix(args): """ %prog fix bedfile > newbedfile Fix non-standard bed files. One typical problem is start > end. """ p = OptionParser(fix.__doc__) p.add_option("--minspan", default=0, type="int", help="Enforce minimum span [default: %default]") p.set_outfile() opts, ar...
5,350,504
def test_root__FrontPage__3(address_book, browser): """`FrontPage` lists only address books. When another object is in the root folder it is not listed. """ from zope.container.btree import BTreeContainer address_book.__parent__['btree'] = BTreeContainer() browser.login('mgr') browser.open(...
5,350,505
def check_all_particles_present(partlist, gambit_pdg_codes): """ Checks all particles exist in the particle_database.yaml. """ absent = [] for i in range(len(partlist)): if not partlist[i].pdg() in list(gambit_pdg_codes.values()): absent.append(partlist[i]) absent_...
5,350,506
def binarize_tree(t): """Convert all n-nary nodes into left-branching subtrees Returns a new tree. The original tree is intact. """ def recurs_binarize_tree(t): if t.height() <= 2: return t[0] if len(t) == 1: return recurs_binarize_tree(t[0]) elif len(t)...
5,350,507
def calculate_prfs_using_rdd(y_actual, y_predicted, average='macro'): """ Determines the precision, recall, fscore, and support of the predictions. With average of macro, the algorithm Calculate metrics for each label, and find their unweighted mean. See http://scikit-learn.org/stable/modules/generated/...
5,350,508
def translation_from_matrix(M): """Returns the 3 values of translation from the matrix M. Parameters ---------- M : list[list[float]] A 4-by-4 transformation matrix. Returns ------- [float, float, float] The translation vector. """ return [M[0][3], M[1][3], M[2][3]...
5,350,509
def test_camera(make_test_viewer): """Test vispy camera creation in 2D.""" viewer = make_test_viewer() vispy_camera = viewer.window.qt_viewer.camera np.random.seed(0) data = np.random.random((11, 11, 11)) viewer.add_image(data) # Test default values camera values are used and vispy camera ...
5,350,510
def saving_filename_boundary(save_location, close_up, beafort, wave_roughness): """ Setting the filename of the figure """ if close_up is None: return save_location + 'Boundary_comparison_Bft={}_roughness={}.png'.format(beafort, wave_roughness) else: ymax, ymin = close_up return save...
5,350,511
def get_library() -> CDLL: """Return the CDLL instance, loading it if necessary.""" global LIB if LIB is None: LIB = _load_library("aries_askar") _init_logger() return LIB
5,350,512
def childs_page_return_right_login(response_page, smarsy_login): """ Receive HTML page from login function and check we've got expected source """ if smarsy_login in response_page: return True else: raise ValueError('Invalid Smarsy Login')
5,350,513
def merge_files(intakes, outcomes): """ Merges intakes and outcomes datasets to create unique line for each animal in the shelter to capture full stories for each animal takes intakes file then outcomes file as arguments returns merged dataset """ # Merge intakes and outcomes on animal id and yea...
5,350,514
def _ssepdpsolve_single_trajectory(data, Heff, dt, times, N_store, N_substeps, psi_t, dims, c_ops, e_ops): """ Internal function. See ssepdpsolve. """ states_list = [] phi_t = np.copy(psi_t) prng = RandomState() # todo: seed it r_jump, r_op = prng.rand(2) jump_times = [] jump_op_...
5,350,515
def construct_features_MH_1(data): """ Processes the provided pandas dataframe object by: Deleting the original METER_ID, LOCATION_NO, BILLING_CYCLE, COMMENTS, and DAYS_FROM_BILLDT columns Constructing a time series index out of the year, month, day, hour, minute, second columns Sorting by the tim...
5,350,516
def sort_observations(observations): """ Method to sort observations to make sure that the "winner" is at index 0 """ return sorted(observations, key=cmp_to_key(cmp_observation), reverse=True)
5,350,517
def coor_trans(point, theta): """ coordinate transformation (坐标转换) theta方向:以顺时针旋转为正 """ point = np.transpose(point) k = np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]]) print(point) # return np.dot(k, point) return np.round(np.dot(k, point),6)
5,350,518
async def test_default_state(hass): """Test light switch default state.""" await async_setup_component( hass, "light", { "light": { "platform": "switch", "entity_id": "switch.test", "name": "Christmas Tree Lights", }...
5,350,519
def ppo( env_fn, actor_critic=core.MLPActorCritic2Heads, ac_kwargs=dict(), seed=0, steps_per_epoch=4000, epochs=100, epochs_rnd_warmup=1, gamma=0.99, clip_ratio=0.2, pi_lr=3e-4, vf_lr=1e-3, rnd_lr=1e-3, train_pi_iters=80, train_v_iters=80, train_rnd_iters=80, ...
5,350,520
def get_zz500_stocks(): """ 获取中证500成分股 """ # 登陆系统 lg = bs.login() # 显示登陆返回信息 print('login respond error_code:'+lg.error_code) print('login respond error_msg:'+lg.error_msg) # 获取中证500成分股 rs = bs.query_zz500_stocks() print('query_zz500 error_code:'+rs.error_code) print('...
5,350,521
def ltopk(k, seq, key=None): """ >>> ltopk(2, [1, 100, 10, 1000]) [1000, 100] >>> ltopk(2, ['Alice', 'Bob', 'Charlie', 'Dan'], key=len) ['Charlie', 'Alice'] """ if key is not None and not callable(key): key = getter(key) return list(heapq.nlargest(k, seq, key=key))
5,350,522
def index(): """ Root URL response """ return ( jsonify( name="Promotion REST API Service", version="1.0", ), status.HTTP_200_OK, )
5,350,523
def test_insight_get_comments(requests_mock): """Tests sumologic-sec-insight-get-comments command function. """ from SumoLogicCloudSIEM import Client, insight_get_comments, DEFAULT_HEADERS mock_response = util_load_json('test_data/insight_comments.json') insight_id = 'INSIGHT-116' comments = mo...
5,350,524
def dump_report_to_file(file: Union[TextIO, str], etype: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType], *, show_locals: bool = True, show_globals: bool = True, show_main_globals: bool = True, show_sys: bool = True, show_simple_tb: bool = True,...
5,350,525
def add_cameras_default(scene): """ Make two camera (main/top) default setup for demo images.""" cam_main = create_camera_perspective( location=(-33.3056, 24.1123, 26.0909), rotation_quat=(0.42119, 0.21272, -0.39741, -0.78703), ) scene.collection.objects.link(cam_main) cam_top = cre...
5,350,526
def distr_mean_stde(distribution: np.ndarray) -> tuple: """ Purpose: Compute the mean and standard deviation for a distribution. Args: distribution (np.ndarray): distribution Returns: tuple (ie. distribution mean and standard deviation) """ # Compute and prin...
5,350,527
def release_waiting_requests_grouped_fifo(rse_id, count=None, direction='destination', deadline=1, volume=0, session=None): """ Release waiting requests. Transfer requests that were requested first, get released first (FIFO). Also all requests to DIDs that are attached to the same dataset get released, if o...
5,350,528
def _get_gap_memory_pool_size_MB(): """ Return the gap memory pool size suitable for usage on the GAP command line. The GAP 4.5.6 command line parser had issues with large numbers, so we return it in megabytes. OUTPUT: String. EXAMPLES: sage: from sage.interfaces.gap import ...
5,350,529
async def order_book_l2(symbol: str) -> dict: """オーダーブックを取得""" async with pybotters.Client(base_url=base_url, apis=apis) as client: r = await client.get("/orderBook/L2", params={"symbol": symbol,},) data = await r.json() return data
5,350,530
def fold_generator( number_of_folds, data, labels, max_per_class, transformer_class=Standardizer ): """generate class balanced splits of data and labels""" for fold in range(number_of_folds): if isinstance(data, dict): data_type_labels = list(data.keys()) if l...
5,350,531
def notify_by_email(): """Sends out notifications via email""" samples = db.session.query(Sample)\ .filter(Sample.result_code != None)\ .filter(Sample.email_notified == False).all() notifier = NotificationService(app) for sample in samples: try: notifier.send_result_...
5,350,532
def _load_json(json_path): """Load JSON from a file with a given path.""" # Note: Binary so load can detect encoding (as in Section 3 of RFC 4627) with open(json_path, 'rb') as json_file: try: return json.load(json_file) except Exception as ex: if sys.version_info[0] ...
5,350,533
def add_ticket_to_package(ticket, package): """Add a ticket to the definition file for a package and commit that change.""" project_repo = Repo.discover() package_file = Path( project_repo.path, 'deploy', 'packages', package, 'tickets.yml') with package_file.open('a') as f: f.write(...
5,350,534
def op_skip_to_output_sig(c: AF_Continuation) -> None: """ WordDefinition(Op_name) -> WordDefinition(Op_name), OutputTypeSignature(TypeSignature). Used when a WordDefition is encountered that has no InputTypeSignature. """ sig = TypeSignature([],[]) c.stack.push(StackObject(sig,TOutputTypeSigna...
5,350,535
async def create_comment_in_post(*, post: models.Post = Depends(resolve_post), created_comment: CreateComment, current_user: models.User = Depends(resolve_current_user), db: Session = Depends(get_db)): """Create a comment in a post.""" return cru...
5,350,536
def sigma_bot(sigma_lc_bot, sigma_hc_bot, x_aver_bot_mass): """ Calculates the surface tension at the bottom of column. Parameters ---------- sigma_lc_bot : float The surface tension of low-boilling component at the bottom of column, [N / m] sigma_hc_bot : float The surface tensi...
5,350,537
def usage(): """usage information""" print(r""" %(EXEC)s-- Calculate volumes of a given image Usage: %(EXEC)s [OPTIONS] OPTIONS: Basic: [-i --input ] < file > Input image [-M --mask ] < file > Mask image in the --input image space (optional) [-s --subid ] < ID > Subject ...
5,350,538
def _normalize_zonal_lat_lon(ds: xr.Dataset) -> xr.Dataset: """ In case that the dataset only contains lat_centers and is a zonal mean dataset, the longitude dimension created and filled with the variable value of certain latitude. :param ds: some xarray dataset :return: a normalized xarray dataset ...
5,350,539
def setup_audio(song_filename): """Setup audio file and setup setup the output device.output is a lambda that will send data to fm process or to the specified ALSA sound card :param song_filename: path / filename to music file :type song_filename: str :return: output, fm_process, fft_calc, mus...
5,350,540
def _collect_package_prefixes(package_dir, packages): """ Collect the list of prefixes for all packages The list is used to match paths in the install manifest to packages specified in the setup.py script. The list is sorted in decreasing order of prefix length so that paths are matched with t...
5,350,541
def _grae_ymin_ ( graph ) : """Get minimal y for the points >>> graph = ... >>> ymin = graph.ymin () """ ymn = None np = len(graph) for ip in range( np ) : x , exl , exh , y , eyl , eyh = graph[ip] y = y - abs( eyl ) if None == ymn or y <= ymn : ymn = y ...
5,350,542
def get_working_id(id_: str, entry_id: str) -> str: """Sometimes new scanned files ID will be only a number. Should connect them with base64(MD5:_id). Fixes bug in VirusTotal API. Args: entry_id: the entry id connected to the file id_: id given from the API Returns: A working I...
5,350,543
def cls(): """nt (windows) = cls | unix = clear""" os.system('cls' if os.name == 'nt' else 'clear')
5,350,544
def remove_empty_blocks(blocks: List[CodeBlock]) -> None: """ Removes empty blocks from given list, keeping the program correct Ex: [a=1]> > > [write(a)]> turns into [a=1]> [write(a)]> """ while isinstance(blocks[0], CodeBlockEmpty): # First block is empty. Remov...
5,350,545
def merck_net(input_shape=(128)): """ # The recommended network presented in the paper: Junshui Ma et. al., Deep Neural Nets as a Method for Quantitative # Structure Activity Relationships # URL: http://www.cs.toronto.edu/~gdahl/papers/deepQSARJChemInfModel2015.pdf # :param input_shape: dim of inpu...
5,350,546
def vec_sum(a, b): """Compute the sum of two vector given in lists.""" return [va + vb for va, vb in zip(a, b)]
5,350,547
def one_v_one_classifiers(x,y,lambd,max_iters,eps=.0001): """ Function for running a 1v1 classifier on many classes using the linearsvm function. Inputs: x: numpy matrix a matrix of size nxd y: numpy matrix a matrix of size nx1 lambd: float la...
5,350,548
def rlsp(mdp, s_current, p_0, horizon, temp=1, epochs=1, learning_rate=0.2, r_prior=None, r_vec=None, threshold=1e-3, check_grad_flag=False): """The RLSP algorithm""" def compute_grad(r_vec): # Compute the Boltzmann rational policy \pi_{s,a} = \exp(Q_{s,a} - V_s) policy = value_iter(mdp...
5,350,549
def rotate(img, angle=0, order=1): """Rotate image by a certain angle around its center. Parameters ---------- img : ndarray(uint16 or uint8) Input image. angle : integer Rotation angle in degrees in counter-clockwise direction. Returns -----...
5,350,550
def activate(request, uidb64, token): """Function that activates the user account.""" try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_...
5,350,551
def dfn(*args, **kwargs): """ The HTML Definition Element (<dfn>) represents the defining instance of a term. """ return el('dfn', *args, **kwargs)
5,350,552
def _compile_rds_files_TRHP(array_codes, years_processed, filetypes_to_check, extensions_to_check, subfolder_filestypes): """ Get indexed information from server for Hydrothermal Vent Fluid Temperature and Resistivity (RS03INT1-MJ03C-10-TRHPHA301) Example where dat exi...
5,350,553
def handle_post_runs(project_id, deployment_id): """Handles POST requests to /.""" is_experiment_deployment = False experiment_deployment = request.args.get('experimentDeploy') if experiment_deployment and experiment_deployment == 'true': is_experiment_deployment = True run_id = create_deplo...
5,350,554
def get_in_reply_to_user_id(tweet): """ Get the user id of the uesr whose Tweet is being replied to, and None if this Tweet is not a reply. \n Note that this is unavailable in activity-streams format Args: tweet (Tweet): A Tweet object (or a dictionary) Returns: str: the user i...
5,350,555
def cl35(): """Cl35 ENDF data (contains RML resonance range)""" endf_data = os.environ['OPENMC_ENDF_DATA'] filename = os.path.join(endf_data, 'neutrons', 'n-017_Cl_035.endf') return openmc.data.IncidentNeutron.from_endf(filename)
5,350,556
def release_definition_show(definition_id=None, name=None, open_browser=False, team_instance=None, project=None, detect=None): """Get the details of a release definition. :param definition_id: ID of the definition. :type definition_id: int :param name: Name of the definition. I...
5,350,557
def GKtoUTM(ea, no=None, zone=32, gk=None, gkzone=None): """Transform any Gauss-Krueger to UTM autodetect GK zone from offset.""" if gk is None and gkzone is None: if no is None: rr = ea[0][0] else: if isinstance(ea, list) or isinstance(ea, tuple): rr = ea...
5,350,558
def run_metric_image(metric_frontend_name, docker_client, common_labels, prometheus_port, prom_config_path, log_config, extra_container_kwargs): """ Run the prometheus image. :param metric_frontend_name: container name :param docker_client: The docker client obj...
5,350,559
def robots(req): """ .. seealso:: http://www.sitemaps.org/protocol.html#submit_robots """ return Response( "Sitemap: %s\n" % req.route_url('sitemapindex'), content_type="text/plain")
5,350,560
def bolling(asset:list, samples:int=20, alpha:float=0, width:float=2): """ According to MATLAB: BOLLING(ASSET,SAMPLES,ALPHA,WIDTH) plots Bollinger bands for given ASSET data vector. SAMPLES specifies the number of samples to use in computing the moving average. ALPHA is an optional input that spe...
5,350,561
def metrics(): """ Expose metrics for the Prometheus collector """ collector = SensorsDataCollector(sensors_data=list(sensors.values()), prefix='airrohr_') return Response(generate_latest(registry=collector), mimetype='text/plain')
5,350,562
def solar_energy_striking_earth_today() -> dict: """Get number of solar energy striking earth today.""" return get_metric_of(label='solar_energy_striking_earth_today')
5,350,563
def write_data_str(geoms, grads, hessians): """ Writes a string containing the geometry, gradient, and Hessian for either a single species or points along a reaction path that is formatted appropriately for the ProjRot input file. :param geoms: geometries :type geoms: list :...
5,350,564
def gen_chart_name(data: types.ChartAxis, formatter: Dict[str, Any], device: device_info.DrawerBackendInfo ) -> List[drawings.TextData]: """Generate the name of chart. Stylesheets: - The `axis_label` style is applied. Args: data: Cha...
5,350,565
def _parse_whois_response(response): """ Dealing with the many many different interpretations of the whois response format. If an empty line is encountered, start a new record If a line with a semicolon is encountered, treat everything before first : as key and start a value If a line without semico...
5,350,566
def vector_cosine_similarity(docs: Sequence[spacy.tokens.Doc]) -> np.ndarray: """ Get the pairwise cosine similarity between each document in docs. """ vectors = np.vstack([doc.vector for doc in docs]) return pairwise.cosine_similarity(vectors)
5,350,567
def test_ycbcr_interp(tmpdir): """A YCbCr TIFF has red, green, blue bands.""" with rasterio.open('tests/data/RGB.byte.tif') as src: meta = src.meta meta['photometric'] = 'ycbcr' meta['compress'] = 'jpeg' meta['count'] = 3 tiffname = str(tmpdir.join('foo.tif')) with rasterio.open(tiff...
5,350,568
def create_test_validation(): """ Returns a constructor function for creating a Validation object. """ def _create_test_validation(db_session, resource, success=None, started_at=None, secret=None): create_kwargs = {"resource": resource} for kwarg in ['success', 'started_at', 'secret']: ...
5,350,569
def nrmse(img, ref, axes = (0,1)): """ Compute the normalized root mean squared error (nrmse) :param img: input image (np.array) :param ref: reference image (np.array) :param axes: tuple of axes over which the nrmse is computed :return: (mean) nrmse """ nominator = np.real(np.sum( (img - ref...
5,350,570
def pairwise_comparison(column1,var1,column2,var2): """ Arg: column1 --> column name 1 in df column2 --> column name 2 in df var1---> 3 cases: abbreviation in column 1 (seeking better model) abbreviation in column 1 (seeking lesser value in column1 in co...
5,350,571
def test_is_valid_manifest_format_with_invalid_urls(caplog): """ Test that invalid urls are detected and error logged Test that empty arrays and empty quote pairs are detected and error logged """ result = is_valid_manifest_format( "tests/validate_manifest_format/manifests/manifest_with_inva...
5,350,572
def copy_static_folder(): """ Copies a static folder to output directory """ copy(TEMPLATES_DIR + "/static", OUTPUT_DIR+"/static")
5,350,573
def prep_data_CNN(documents): """ Prepare the padded docs and vocab_size for CNN training """ t = Tokenizer() docs = list(filter(None, documents)) print("Size of the documents in prep_data {}".format(len(documents))) t.fit_on_texts(docs) vocab_size = len(t.word_counts) print("Vocab ...
5,350,574
def report_error(exc, source, swallow, output=None): """ report_error(exc, source, swallow, output=None) -> None Write a report about the given error to the given output stream. exc is the exception being handled; source indicates the origin of the error (in particular an ERRS_* constant); swallow ...
5,350,575
def main() -> None: """Main function""" args = worker.handle_args(parseargs()) actapi = worker.init_act(args) ta_cards = worker.fetch_json( args.thaicert_url, args.proxy_string, args.http_timeout ) process(actapi, ta_cards["values"]) vocab = worker.fetch_json(STIX_VOCAB, args.proxy_...
5,350,576
def gc2gd_lat(gc_lat): """Convert geocentric latitude to geodetic latitude using WGS84. Parameters ----------- gc_lat : (array_like or float) Geocentric latitude in degrees N Returns --------- gd_lat : (same as input) Geodetic latitude in degrees N """ wgs84_e2 = ...
5,350,577
def _coroutine_format_stack(coro, complete=False): """Formats a traceback from a stack of coroutines/generators. """ dirname = os.path.dirname(__file__) extracted_list = [] checked = set() for f in _get_coroutine_stack(coro): lineno = f.f_lineno co = f.f_code filename = c...
5,350,578
def set_logging(level): """Convenience function to enable logging for the SDK This function will enable logging for the SDK at the level provided. It sends all logging information to stderr. :param level: logging level to emit :type level: int """ log = logging.getLogger(__name__) log...
5,350,579
def polynomial_kernel(X, Y, c, p): """ Compute the polynomial kernel between two matrices X and Y:: K(x, y) = (<x, y> + c)^p for each pair of rows x in X and y in Y. Args: X - (n, d) NumPy array (n datapoints each with d features) Y - (m, d) NumPy array (...
5,350,580
def slug_from_iter(it, max_len=128, delim='-'): """Produce a slug (short URI-friendly string) from an iterable (list, tuple, dict) >>> slug_from_iter(['.a.', '=b=', '--alpha--']) 'a-b-alpha' """ nonnull_values = [str(v) for v in it if v or ((isinstance(v, (int, float, Decimal)) and str(v)))] r...
5,350,581
def modulusOfRigidity(find="G", printEqs=True, **kwargs): """ Defines the slope of the stress-strain curve up to the elastic limit of the material. For most ductile materials it is the same in compression as in tensions. Not true for cast irons, other brittle materials, or magnesium. Where: E =...
5,350,582
def _splitcmdline(cmdline): """ Parses the command-line and returns the tuple in the form (command, [param1, param2, ...]) >>> splitcmdline('c:\\someexecutable.exe') ('c:\\\\someexecutable.exe', []) >>> splitcmdline('C:\\Program Files\\Internet Explorer\\iexplore.exe') ('C:\\\\Program File...
5,350,583
def read_xml_files(region, paths, writer): """Read all XML files for the specified region """ logger.info('Started reading XML files') if region in ['belgium', 'brussels']: read_region( ET.parse(paths['BrusselsMunicipality']).getroot(), ET.parse(paths['BrusselsPostalinfo...
5,350,584
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigType) -> bool: """Unload FRITZ!Box Tools config entry.""" hass.services.async_remove(DOMAIN, SERVICE_RECONNECT) for domain in SUPPORTED_DOMAINS: await hass.config_entries.async_forward_entry_unload(entry, domain) del hass.data[...
5,350,585
def cli(ctx, configfile, configclass): """CattleDB Command Line Tool""" ctx.ensure_object(dict) if configfile: _imported = import_config_file(configfile) if configclass: config = getattr(_imported, configclass) else: config = _imported click.echo("Usin...
5,350,586
def test_valid_targetapps(): """ Tests that the install.rdf contains only valid entries for target applications. """ results = _do_test("tests/resources/targetapplication/pass.xpi", targetapp.test_targetedapplications, False, True...
5,350,587
def queryMaxTransferOutAmount(asset, isolatedSymbol="", recvWindow=""): """# Query Max Transfer-Out Amount (USER_DATA) #### `GET /sapi/v1/margin/maxTransferable (HMAC SHA256)` ### Weight: 5 ### Parameters: Name |Type |Mandatory |Description --------|--------|--------|-------- asset |STRING |YES | isolatedSymbol |...
5,350,588
def IteratePriorityQueueEntry(root, element_type, field_name): """ iterate over a priority queue as defined with struct priority_queue from osfmk/kern/priority_queue.h root - value : Value object for the priority queue element_type - str : Type of the link element field...
5,350,589
def remove_layer(nn, del_idx, additional_edges, new_strides=None): """ Deletes the layer indicated in del_idx and adds additional_edges specified in additional_edges. """ layer_labels, num_units_in_each_layer, conn_mat, mandatory_child_attributes = \ get_copies_from_old_nn(nn) # First add new edges to c...
5,350,590
def brutekeys(pinlength, keys="0123456789", randomorder=False): """ Returns a list of all possibilities to try, based on the length of s and buttons given. Yeah, lots of slow list copying here, but who cares, it's dwarfed by the actual guessing. """ allpossible = list(itertools.imap(lambda x: "".join(x),itertool...
5,350,591
def return_figures(): """Creates four plotly visualizations Args: None Returns: list (dict): list containing the four plotly visualizations """ df = query_generation('DE', 14) graph_one = [] x_val = df.index for energy_source in df.columns: y_val = df[energ...
5,350,592
def create_central_storage_strategy(): """Create a CentralStorageStrategy, using a GPU if it is available.""" compute_devices = ['cpu:0', 'gpu:0'] if ( tf.config.list_logical_devices('GPU')) else ['cpu:0'] return tf.distribute.experimental.CentralStorageStrategy( compute_devices, parameter_device='cpu...
5,350,593
def ToolStep(step_class, os, **kwargs): """Modify build step arguments to run the command with our custom tools.""" if os.startswith('win'): command = kwargs.get('command') env = kwargs.get('env') if isinstance(command, list): command = [WIN_BUILD_ENV_PATH] + command else: command = WIN_...
5,350,594
def get_security_groups(): """ Gets all available AWS security group names and ids associated with an AWS role. Return: sg_names (list): list of security group id, name, and description """ sg_groups = boto3.client('ec2', region_name='us-west-1').describe_security_groups()['SecurityGroups']...
5,350,595
def traverseTokens(tokens, lines, callback): """Traverses a list of tokens to identify functions. Then uses a callback to perform some work on the functions. Each function seen gets a new State object created from the given callback method; there is a single State for global code which is given None in the co...
5,350,596
def test_string_representation(): """ Check unit string representation. """ pc = Unit("pc") Myr = Unit("Myr") speed = pc / Myr dimensionless = Unit() assert_true(str(pc) == "pc") assert_true(str(Myr) == "Myr") assert_true(str(speed) == "pc/Myr") assert_true(repr(speed) == "...
5,350,597
def pollutant(): """ Water treatment example from BHH2, Ch 5, Question 19. Description ----------- The data are from the first 8 rows of the pollutant water treatment example n the book by Box, Hunter and Hunter, 2nd edition, Chapter 5, Question 19. The 3 factors (C, T, and S) are in coded...
5,350,598
def publications_by_country(papers: dict[str, Any]) -> dict[Location, int]: """returns number of published papers per country""" countries_publications = {} for paper in papers: participant_countries = {Location(city=None, state=None, country=location.country) \ for location in paper.loc...
5,350,599