content
stringlengths
22
815k
id
int64
0
4.91M
def _plot_fronts(front_line_table, ternary_front_matrix, title_string, annotation_string, output_file_name): """Plots one set of WPC fronts (either before or after dilation). :param front_line_table: See doc for `fronts_io.write_polylines_to_file`. :param ternary_front_matrix: numpy array ...
34,500
def dump(file_path, spectrum, append=False, overwrite=False, group_name="spectrum"): """ Dump the spectrum to the file_path. Args: file_path (string): Location to save to. spectrum (:class:`spectra.Spectra`): The spectrum to save """ if append: file_opt = "a" else: ...
34,501
def update_bc_val(gridx, gridy, ivar, t): """Update Dirichlet boundary values for the velocity components. Parameters ---------- gridx : flowx.GridFaceX object The grid for the x-component of the velocity. gridy : flowx.GridFaceY object The grid for the y-component of the velocity. ...
34,502
def countDigits(string): """return number of digits in a string (Helper for countHaveTenDigits)""" count = 0 for char in string: if char == '0' or char == '1' or char == '2' or char == '3' or char == '4' or \ char == '5' or char == '6' or char == '7' or char == '8' or char == '9': ...
34,503
def get_process_entry(process_id: int) -> Process: """Get process entry :raises AssertionError: When illegal state: Active processes != 1 :param process_id: specify process :return: Process entry """ active_process_entry_query = db.session.query(Process).filter(Process.id == process_id) ass...
34,504
def shrink(filename): """ The function will make the original image shrink to its half without losing too much quality. :param filename: The directory of an image tou want to process. :return img: SimpleImage, a shrink image that is similar to the original image. """ img = SimpleImage(file...
34,505
def get_target_config(): """ Get details of the target database (Postgres) """ print('\n------------------------------------------') print('Enter target database settings:') print('------------------------------------------') config = {} config['username'] = input('- Username on target...
34,506
def do_cli( # pylint: disable=too-many-locals, too-many-statements click_ctx, function_identifier: Optional[str], template: str, base_dir: Optional[str], build_dir: str, cache_dir: str, clean: bool, use_container: bool, cached: bool, parallel: bool, manifest_path: Optional[s...
34,507
def add_utxos_to_set(utxo_set, utxos): """ 将UTXO添加到集合中 :param utxo_set: UTXO集合 :param utxos: UTXO列表 """ if isinstance(utxos, dict): utxos = utxos.values() for utxo in utxos: utxo_set[utxo.pointer] = utxo
34,508
def GetGPU(): """Get the global index of GPU. Returns ------- int The global index of GPU. """ return option['device_id']
34,509
def test_empty_chain(object_store): """Check that empty chain raises only the expected error.""" chain = Chain(object_store) assert chain.head is None assert chain.get_block_by_index(0) is None with pytest.raises(IndexError): chain[0]
34,510
def _docker_call(method, msg, *args, **kwargs): """ Calls `method`, echoing `msg`, and passing `*args` and `**kwargs` to the method """ click.echo(msg, nl=False) try: method(*args, **kwargs) except docker.errors.APIError as exc: if exc.status_code != 409: raise click....
34,511
def get_generic_explanation(exception_type): """Provides a generic explanation about a particular exception.""" if hasattr(exception_type, "__name__"): exception_name = exception_type.__name__ else: exception_name = exception_type if exception_name in GENERIC: return GENERIC[exce...
34,512
def test_runtime_config(): """Basic test for the class RuntimeConfig.""" config = RuntimeConfig() assert config is not None
34,513
def _normalized_bam_coverage(name, bam_input, data): """Run bamCoverage from deeptools but produce normalized bigWig files""" cmd = ("{bam_coverage} --bam {bam_input} --outFileName {bw_output} " "--binSize 20 --effectiveGenomeSize {size} " "--smoothLength 60 --extendReads 150 --centerReads -...
34,514
def requestPump(): """Request a core pump. This will perform any queued activity. It is delayed slightly so that queues can implement rate limiting, filter extraneous events, etc. """ global _isPumpPending global _pump # print("#### rp", _isPumpPending, _pump) if not _pump or _isPum...
34,515
def simple_histogram(queryset, column, bins): """ Return a histogram from data in queryset. :param queryset: A Queryet, Model, or Manager :param column: The column we are aggregating into a histogram :param bins: An ordered iterable of left endpoints of the bins. Must have at least two elements. ...
34,516
def test_md013_good_medium_line_with_long_last_word_with_config_stern(): """ Test to make sure this rule does not trigger with a document that contains a single line the crosses the normal 80 character limit with a 31 character last "word" and stern mode active. """ # Arrange scanner = Mark...
34,517
def ProbeDebuggerDir(): """Probes the debugger installed path and returns the path.""" program_files = os.environ.get('ProgramFiles') if not program_files: return None # Probing debugger installed path. # Starting with 32 bit debugger on 32 bit platform. debugger_dir = '%s\\Debugging Tools For Windows' ...
34,518
def bounding_box(points): """Bounding box Args: points: Array of shape (amount_of_points, dimensions) Returns: numpy.ndarray: Array of [[min, max], [min, max], ...] along the dimensions of points. """ out = np.empty((points.ndim, 2)) for i in range(points.ndim): ...
34,519
def add_signer_layer(api_client, key_file, key_password, consumer_key): """Create and load configuration. Decorate APIClient.request with header signing""" api_signer = SignerInterceptor(key_file, key_password, consumer_key) api_client.request = api_signer.oauth_signing(api_client.request)
34,520
def get_ts_WFI(self): """ Get kinetic energy density """ ts = np.zeros((self.grid.Nelem, len(self.solver[0,:]) )) if self.optInv.ens_spin_sym is not True: for i in range(self.solver.shape[0]): for j in range(self.solver.shape[1]): self.solver[i,j].calc_ked_WFI...
34,521
def _correct_outlier_correlation(rpeaks: pd.DataFrame, bool_mask: np.array, corr_thres: float, **kwargs) -> np.array: """Apply outlier correction method 'correlation'. This function compute the cross-correlation coefficient between every single beat and the average of all detected beats. It marks beats as ...
34,522
def formatLH(figsizex = 2, figsizey = 2, frame = False): """ :param: figsizex, integer specifying how many figures should be next to each other in x-direction :param: figsizey, integer specifying how many figures should be next to each other in y-direction """ import matplotlib as mpl mpl.r...
34,523
def _time_from_timestamp(timestamp: int) -> time: """ Casts a timestamp representing the number of seconds from the midnigh to a time object Parameters ---------- timestamp : int The number of seconds since midnight Returns ------- time The associated time object ""...
34,524
def get_marginal_frequencies_of_spikes_in_bins(symbol_counts, number_of_bins_d): """ Compute for each past bin 1...d the sum of spikes found in that bin across all observed symbols. """ return np.array(sum((emb.symbol_binary_to_array(symbol, number_of_bins_d) * symbol_counts...
34,525
def member_stand(v, m): """ returns member m stand on vote v """ va = VoteAction.objects.filter(member = m, vote = v) if va: for (name,string) in VOTE_ACTION_TYPE_CHOICES: if va[0].type==name: stand = _(string) cls = name return {'stand':stand, 'cl...
34,526
def pagination(cl): """ Generate the series of links to the pages in a paginated list. """ paginator, page_num = cl.paginator, cl.page_num pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page if not pagination_required: page_range = [] else: ON_EA...
34,527
def set_attr(objs, attr, value): """Remove an attribute from a list of objects.""" try: for o in objs: setattr(o, attr, value) except TypeError: setattr(obj, attr, value)
34,528
def ants_apply_inverse_warps_template_to_func( workflow, strat, num_strat, num_ants_cores, input_node, input_outfile, ref_node, ref_outfile, func_name, interp, input_image_type ): """Apply the functional-to-structural and structural-to-template warps inversely to functional time-series in templa...
34,529
def get_metrics_influx(query, query_index): """ Function to Query InfluxDB """ influx_connect = InfluxDBClient( host=defs.INFLUX_DETAILS[query_index][0], database=defs.INFLUX_DETAILS[query_index][1], port=8086, timeout=5, retries=5) response = influx_connect.query(que...
34,530
def spectra(data, freq_sel=None, prod_sel=None, time_sel=None, part_sel=None, **kwargs): """Plots spectra at different times and for different correlation products.""" plt_data = _coerce_data_shape(data, freq_sel, prod_sel, time_sel, axes=()) ntime = plt_data.shape[2] nprod = plt_data.shape[1] for ...
34,531
def recursive_filter(condition: Callable[[OrgBaseNode], bool], root: Iterable[OrgBaseNode]) -> Iterable[OrgBaseNode]: """recursively trasvese all possible nodes from root and return only those for which condition returns True Args: condition: condition which evaluates to true nodes: nod...
34,532
def find_buckets(pc, target_centres, N, bucket_height=.38, bucket_radius=.15): """ Returns: pc, bucket_centres """ ### find buckets and remove ### print ('finding buckets') buckets = pc[pc.z.between(.1, .4)] # voxelise to speed-up dbscan buckets.loc[:, 'xx'] = (buckets.x // .0...
34,533
def fit_model(model, state_train, action_train, num_epochs, learning_rate = 1e-2, batch_size=32, shuffle=True): """ Trains a pytorch module model to predict actions from states for num_epochs passes through the dataset. This is used to do a (relatively naive) version of behavior cloning pretty naive (b...
34,534
def export_item(item_task, library_home): """Create strm file for an item and add it to the library""" destination_folder = os.path.join( library_home, item_task['section'], item_task['destination']) export_filename = os.path.join( destination_folder, item_task['filename'] + '.strm') _ad...
34,535
def _deserialize_dict( class_reference, data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ): """Deserialize a dictionary to a Python object.""" # Check if we are doing a straightforward dictionary parse first, or if it # has to be deserialized remaining_properties = s...
34,536
def red_bg(text): """ Red background. """ return _create_color_func(text, bgcolor=1)
34,537
async def send_dir(pathDir, writer, oDir): """Fonction envoyant les fichiers d'un dossier de manière récursive. On lui passe en paramètre le chemin pour accéder au dossier originel, le writer, et le nom du dossier originel.""" if os.path.isdir(pathDir): tree = os.listdir(pathDir) for fileord...
34,538
def save_model(model, neural_net_type, bands, tile_size): """Save a DeepOSM tflearn model and its metadata. """ model.save(CACHE_PATH + 'model.pickle') # dump the training metadata to disk, for later loading model from disk training_info = {'neural_net_type': neural_net_type, 'bands...
34,539
def does_block_type_support_children(block_type): """ Does the specified block type (e.g. "html", "vertical") support child blocks? """ try: return XBlock.load_class(block_type).has_children except PluginMissingError: # We don't know if this now-uninstalled block type had childre...
34,540
def jsonDateTimeHandler(obj): """Takes an object and tries to serialize it in JSON by using strftime or isoformat.""" if hasattr(obj, "strftime"): # To avoid problems with the js date-time format return obj.strftime("%a %b %d, %Y %I:%M %p") elif hasattr(obj, 'isoformat'): return ...
34,541
def truncate_desired(cluster, desired, min_size, max_size): """Do truncation of desired capacity for non-strict cases. :param cluster: The target cluster. :param desired: The expected capacity of the cluster. :param min_size: The NEW minimum capacity set for the cluster. :param max_size: The NEW ma...
34,542
def _plot_slice(ax, slice, slice_nr, orientation, x_lab, y_lab, color_map): """ Plot a slice on an ax object, along with labels and titles :param ax: matplotlib ax object :param slice: 2D numpy array with grey values :param slice_nr: int, the slice number :param orientation: str, choose fro...
34,543
def test_required_fields(data, fld): """Verify that the required fields without custome error message raise the default messge if they are not provided. Arguments: - `data`: """ data[fld] = None with pytest.raises(ValidationError) as excinfo: FN124(**data) msg = "none is not...
34,544
def get_crypto_price(crypto, fiat): """Helper function to convert any cryptocurrency to fiat""" converted_btc_value = float(binance_convert_crypto( crypto, "BTC").split('=')[1].strip().split()[0]) # grab latest bitcoin price btc_price = float(get_price("btc", fiat).split('=')[1].strip().split()...
34,545
def get_js_files() -> Generator[str, None, None]: """Yield all the js files that are needed for the users selected extensions.""" # For every extension... for ext in (simple_bulma_path / "extensions").iterdir(): # ...check if it is enabled... if is_enabled(ext): dist_folder = ext...
34,546
def boxblur(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#boxblur""" return filter(stream, boxblur.__name__, *args, **kwargs)
34,547
def add_stretch(layout: QLayout): """ Adds a stretcheable zone to a layout. """ layout.addStretch()
34,548
def create_netcdf_dataset( location, name, start_time, end_time, sweep, inpath=None, outpath="", chunks={}, engine="h5netcdf", ): """Create NetCDF file from radar data""" radar_path = get_xpol_path(inpath=inpath, start_time=start_time, loc=location) file_path = os.path.jo...
34,549
def fmxKeys(mKey): """ """ mq = MootQuery(None) constits = vectorOfConstitInfo() ci = mq.getActiveFilters(mKey,constits,0) for ci in constits: print (ci.getKey(),ci.getFswId(),ci.getSchemaId(),ci.getSchemaVersionId(),ci.getInstanceId() )
34,550
def flatten(lis): """Given a list, possibly nested to any level, return it flattened.""" new_lis = [] for item in lis: if type(item) == type([]): new_lis.extend(flatten(item)) else: new_lis.append(item) return new_lis
34,551
def not_dumpable( py_obj, h_group, name, **kwargs): # pragma: no cover """ create_dataset method attached to loader of dummy py_object which is used to mimic PyContainer class for groups in legacy hickle 4.x file. Raises ------ RuntimeError: in any case as this function shall ...
34,552
def name(ndims=2, ndepth=2): """ encrypt n and version into a standardized string """ # Model name, depth and version value = 'care_denoise_%dDdepth%d' % (ndims, ndepth) return value
34,553
def _generate_url_slug(size=10, chars=string.ascii_lowercase + string.digits): """ This is for a Django project and it assumes your instance has a model with a slug field and a title character (char) field. Parameters ---------- size: <Int> Size of the slug. chars: <string.class> ...
34,554
def mc_compute_stationary(P): """ Computes the stationary distribution of Markov matrix P. Parameters ---------- P : array_like(float, ndim=2) A discrete Markov transition matrix Returns ------- solution : array_like(float, ndim=1) The stationary distribution for P ...
34,555
def isight_prepare_data_request(a_url, a_query, a_pub_key, a_prv_key): """ :param a_url: :type a_url: :param a_query: :type a_query: :param a_pub_key: :type a_pub_key: :param a_prv_key: :type a_prv_key: :return: :rtype: """ header = set_header(a_prv_key, a_pub_key, a_...
34,556
def norm_fisher_vector(v, method=['power', 'l2']): """ Normalize a set of fisher vectors. :param v: numpy.array A matrix with Fisher vectors as rows (each row corresponding to an image). :param method: list A list of normalization methods. Choices: 'power', 'l2'. :return: n...
34,557
def download_datasets(num=10, local_database=None, msg_flag=True, download_flag=True): """ Downloads datasets and puts them in a local directory named after the dataset. By default downloads first 10 datasets only. User can choose the number of dataets to be downloaded. msg_flag: Controls verbosity. do...
34,558
def get_top_funnels_df(funurl: str, funlen: int, useResolvedUrls: bool, events: DataFrame, limit_rows: int = 0) -> dict: """Get top funnels of specified length which contain the specified URL :param funurl: URL that should be contained in the funnel :param funlen: funnel length :param useResolvedUrls: ...
34,559
def check_write_access(filepath: Path): """Checks that the program can write safely in a file. Args: filepath (Path): file to check write permissions. Raises: click.ClickException: if the file raises PermissionError. """ try: with filepath.open("a"): pass e...
34,560
def count_alphabet(): """ Return dict which contains rating of alplabet """ # Get all txt file in folder data list_file = [] for file in os.listdir("data"): if file.endswith(".txt"): list_file.append(os.path.join("data", file)) # Int result result = {} for i in st...
34,561
def CompositeToBayesComposite(obj): """ converts a Composite to a BayesComposite if _obj_ is already a BayesComposite or if it is not a _Composite.Composite_ , nothing will be done. """ if obj.__class__ == BayesComposite: return elif obj.__class__ == Composite.Composite: obj.__class__ = BayesCo...
34,562
def resilience(msg="ignoring error {type}", acceptable=Exception, unacceptable=(), log_level=logging.DEBUG, pred=None): """Suppress exceptions raised from the wrapped scope. msg - format of log to print when an exception is suppressed. acceptable - exception or tuple of exceptions which to suppr...
34,563
def graph_to_json(obj: Graph) -> Dict[str, Any]: """ Uses regular serialization but excludes "operator" field to rid of circular references """ serialized_obj = { k: v for k, v in any_to_json(obj).items() if k != 'operator' # to prevent circular reference } return serial...
34,564
def log_ttest_vs_basal(df, basal_key): """Do t-tests in log space to see if sequences has the same activity as basal. Parameters ---------- df : pd.DataFrame Index is sequence ID, columns are average RNA/DNA barcode counts for each replicate. basal_key : str Index value for basal. ...
34,565
def spleen_lymph_cite_seq( save_path: str = "data/", protein_join: str = "inner", remove_outliers: bool = True, run_setup_anndata: bool = True, ) -> anndata.AnnData: """ Immune cells from the murine spleen and lymph nodes [GayosoSteier21]_. This dataset was used throughout the totalVI manus...
34,566
def enable_packet_aging(duthost): """ Enable packet aging feature (only on MLNX switches) Args: duthost (AnsibleHost): Device Under Test (DUT) Returns: N/A """ if isMellanoxDevice(duthost): duthost.copy(src="qos/files/mellanox/packets_aging.py", dest="/tmp") dut...
34,567
def test_remote_constructor_valid_ssh(mock_key, valid_ssh_conn): """Validate Remote command runner SSH connections strings.""" valid = valid_ssh_conn runner = Remote(environment=valid[0]) assert runner.user == valid[1] assert runner.host == valid[2] assert runner.port == valid[3]
34,568
def getInputs(path, sequenceNames): """Requires setting SON_TRACE_DATASETS variable and having access to datasets. """ seqPath = os.path.join(TestStatus.getPathToDataSets(), path) sequences = [ os.path.join(seqPath, sequence) for sequence in sequenceNames ] #Same order as tree newickTreeString = par...
34,569
def save_model(model, model_filepath): """ Export the model as a pickle file Args: model: sklearn.model_selection.GridSearchCV. model_filepath: String. location to save the trained model """ with open(model_filepath, 'wb') as file: pickle.dump(model, file)
34,570
def strftime_local(aware_time, fmt="%Y-%m-%d %H:%M:%S"): """ 格式化aware_time为本地时间 """ if not aware_time: # 当时间字段允许为NULL时,直接返回None return None if timezone.is_aware(aware_time): # translate to time in local timezone aware_time = timezone.localtime(aware_time) return a...
34,571
def process_message(ws, message_json): """ Parse at high level and output JSON of message """ message_type = message_json['Type'] if message_type == "Refresh": if 'Domain' in message_json: message_domain = message_json['Domain'] if message_domain == "Login": ...
34,572
def exclude(community, index_name, facets): """Exclude some facets on a given index for a given community.""" community = OARepoCommunity.get_community(community) _validate_facets(index_name=index_name, facets=facets) with db.session.begin_nested(): community.json.setdefault('excluded_facets', ...
34,573
def filter_issues_fixed_by_prs(issues, prs, show_related_prs, show_related_issues): """ Find related issues to prs and prs to issues that are fixed. This adds extra information to the issues and prs listings. """ words = [ 'close', 'closes', 'fix', 'fixes', 'fixed', 'resolve', 'resolves', ...
34,574
def run_job(answer: str, job: dict, grade: float, feedback: str): """ Match answer to regex inside job dictionary. Add weight to grade if successful, else add comment to feedback. :param answer: Answer. :param job: Dictionary with regex, weight, and comment. :param grade: Current grade for the ...
34,575
def __build_data__(feature, qars): """ Return all the data needed to build the Benin republic departments Layer """ data = { 'qars': qars, } # GEOJSON layer consisting of a single feature department_name = feature["properties"]["NAME_1"] data["department"] = department_name ...
34,576
def hook(callback): """ Installs a global listener on all available mouses, invoking `callback` each time it is moved, a key status changes or the wheel is spun. A mouse event is passed as argument, with type either `mouse.ButtonEvent`, `mouse.WheelEvent` or `mouse.MoveEvent`. Returns the g...
34,577
def notification_list(request): """ returns the notification list """ notifications = Notification.get_notifications(user=request.user) return {"notifications": notifications}
34,578
def filter_samples_by_detected_language_via_langid( samples_iterator: Iterator[Sample], lang_code: str, ) -> Iterator[Sample]: """Return sample documents whose language detected by langid matches the expected language. Documents are converted to a simple text via the method `slub_docsa.data.preproc...
34,579
async def test_state_update(hass): """Test water heater is updated accordingly to data.""" assert await setup_multimatic(hass) _assert_state(hass, OperatingModes.AUTO, HotWater.MIN_TARGET_TEMP, 45, "off") dhw = SystemManagerMock.data["get_dhw"] SystemManagerMock.data["DomesticHotWaterTankTemperature...
34,580
def predictClass(x, mus, sigmas, X_train, number_of_classes, class_probabilities): """ For every model, it calculates the likelihood for each class, and picks the class with max likelihood. :param x: The datapoint we want to derive the class for. :param mus: A list with the mean vector for each method....
34,581
def create_secret_id(vault, name, version=None): """ :param vault: The vault uri. :type vault: str :param name: The secret name. :type name: str :param version: The secret version. :type version: str :rtype: KeyVaultId """ return create_object_id('secrets', vault, name, version)
34,582
def test_keyword__Table__3(address_book, KeywordFactory, browser): """A visitor is allowed to see the keywords in the `Table`.""" KeywordFactory(address_book, u'Arbeit') browser.login('visitor') browser.open(browser.KEYWORDS_LIST_URL) assert ['Arbeit'] == browser.etree.xpath('//tbody/tr/td/a/text()'...
34,583
def config_output_page(): """ Configuration landing page :return: config.html """ config_type = "output" c = ConfigFile() # First load in all the configuration from the provided configuration file, if it exists c.load_from_file(DEFAULT_CONFIG_FILE) cdb = c.get_cdb() cdb.update_...
34,584
def compute_all_aggregator_metrics( per_plan_confidences: np.ndarray, predictions: np.ndarray, ground_truth: np.ndarray, metric_name: Optional[str] = None ): """Batch size B, we assume consistent number of predictions D per scene. per_plan_confidences: np.ndarray, shape (B, D), we assume that a...
34,585
def query_url_base(_url, _proxy=True, _isPC=True, _isPhone=False): """ 基于requset的模块,不能采集动态网页数据 :param _url<str> :param _proxy<bool> :param _isPc<bool> :param _isPhone<bool> :return _result<dict> """ _result = {} _headers = {'Connection':'kepp-alive'} if _isPC: _headers['U...
34,586
def timefstring(dtobj, tz_name=True): """Standardize the format used for timestamp string format. Include 3 letter string for timezone if set to True. """ if tz_name: return f'{dtobj.strftime("%Y-%m-%d_%H:%M:%S%Z")}' else: return f'{dtobj.strftime("%Y-%m-%d_%H:%M:%S")}NTZ'
34,587
def is_block(modules): """Check if is ResNet building block.""" if isinstance(modules, (ShuffleUnit, )): return True return False
34,588
def run(job_input: IJobInput): """ Function named `run` is required in order for a python script to be recognized as a Data Job Python step and executed. VDK provides to every python step an object - job_input - that has methods for: * executing queries to OLAP Database; * ingesting data into a da...
34,589
def add_data( dates=None, product="AOD15", *, inv_type=None, latlonbox=None, siteid=None, daily=False, lunar=False, # # post-proc freq=None, detect_dust=False, interp_to_aod_values=None, # # joblib n_procs=1, verbose=10, ): """Load AERONET data fro...
34,590
def create_tiled_cogs( input_file: str, output_directory: str, raise_on_fail: bool = True, ) -> None: """Split tiff into tiles and create COGs Args: input_path (str): Path to the World Climate data. output_directory (str): The directory to which the COG will be written. rais...
34,591
def _func(*args, **kwargs): """Test function used in some tests.""" return args, kwargs
34,592
def combine_parallel_circuits(IVprev_cols, pvconst): """ Combine crosstied circuits in a substring :param IVprev_cols: lists of IV curves of crosstied and series circuits :return: """ # combine crosstied circuits Irows, Vrows = [], [] Isc_rows, Imax_rows = [], [] for IVcols in zip(*...
34,593
def update_symlinks_generic(dirname, attr, values): """dirname should be without "_data"; wd should be at project root""" for v in values: p = Path(os.path.join(attr, v)) p.mkdir(exist_ok=True) dst = os.path.join(p, dirname) if os.path.exists(dst): os.unlink(dst) ...
34,594
def _create_pipeline(pipeline_name: str, pipeline_root: str, data_root: str, module_file: str, serving_model_dir: str, metadata_path: str) -> tfx.dsl.Pipeline: """Creates a three component penguin pipeline with TFX.""" # Brings data into the pipeline. example_gen = tfx.co...
34,595
def mask_conv2d(module, c_in, c_out): """Mask conv2d.""" if not isinstance(module, torch.nn.Conv2d): return mask_conv2d_in_channels(module, c_in) mask_conv2d_out_channels(module, c_out)
34,596
def create_global_step() -> tf.Variable: """Creates a `tf.Variable` suitable for use as a global step counter. Creating and managing a global step variable may be necessary for `AbstractTrainer` subclasses that perform multiple parameter updates per `Controller` "step", or use different optimizers on different...
34,597
def supported_coins_balance(balance, tickers): """ Return the balance with non-supported coins removed """ supported_coins_balance = {} for coin in balance.keys(): if coin != "BTC": if f"{coin}/BTC" in tickers: supported_coins_balance[coin] = balance[coin] ...
34,598
def _identity_map(size): """Function returning list of lambdas mapping vector to itself.""" return [lambda x, id: x[id] for _ in range(size)]
34,599