content
stringlengths
22
815k
id
int64
0
4.91M
def dump_elem_rel(elem_df, rels_df, relt_df): """Save dataframes as txt or csv on local storage""" # Store elem_df as a text file with row in json format with open('elem.txt', 'w') as file: for _, row in elem_df.sort_values(by='term').iterrows(): file.write(json.dumps(row.to_dict(), ensure_ascii=...
5,288,700
def create_scenario_xx_nc00_hp00(base_sc, path, factor=0.0): """remove nuclear # use massive heat_pumps """ sc = copy.deepcopy(base_sc) sub = "XX_Nc00_HP00_f{0}".format(str(factor).replace(".", "")) base = base_sc.table_collection["meta"].loc["name", "value"] sc.name = "{0}_{1}".format(base,...
5,288,701
async def async_call_action_from_config( hass: HomeAssistant, config: dict, variables: dict, context: Context | None ) -> None: """Execute a device action.""" await hass.services.async_call( "remote", "send_command", service_data={ATTR_COMMAND: config[ATTR_COMMAND]}, context=context,...
5,288,702
def handle_RepeatFirstError(exc, source): """Handles situation where ``repeat`` was uses wrongly as it did not appear as the first keyword of a given statement. """ _ = gettext_lang.lang params = exc.args[0] linenumber = params["linenumber"] begin = linenumber - 1 end = linenumber + 1...
5,288,703
def gradient_point(point: float, gradient: Iterable[str] = REDGREENGRADIENT) -> str: """Get color at a point on color gradient.""" if point < -1 or point > 1: raise ValueError("Point must fall on range [-1, 1]") elif len(gradient) != 3: raise ValueError("Gradient must be an iterable of length 3") if point <= 0:...
5,288,704
def generate_pos_and_dep_set(dataset, data_directory, sanitized_directory): """ Generate and save list of unique pos tag and dep type used in a file. """ file_path = data_directory + dataset + '/train_new.json' unique_pos = set() unique_dep_type = set() with open(file_path, 'r') as file_p: ...
5,288,705
def transform(query, schema, origin=None): """ transform Args: query(dict): query schema(dict): schema origin(list): logical form Returns: parse result Rsises: NULL """ preprocess_schema(schema) if origin is None: lf = query['predicted_rule_tokens'] else: ...
5,288,706
def read_line_from_file(file): """Reads one line from a file and returns it as string.""" with open(file, "r") as f: result = f.readline() return result
5,288,707
def website(c): """Build website.""" from config import out_dir c.run("ivy build") c.run(f"pdoc --html --force --output-dir {out_dir} nitinat")
5,288,708
def _bidirectional_pred_succ(G, source, target, ignore_nodes=None, ignore_edges=None, force_edges=None): """Bidirectional shortest path helper. Returns (pred,succ,w) where pred is a dictionary of predecessors from w to the source, and succ is a dictionary of success...
5,288,709
def subset_partition(lst): """ Finds the two subsets that partition the lst in such a way that the sum of elements in both subsets are equal pre: lst should be a list of numbers ( can be float or int) post: returns the two subsets with equal sum """ if sum(lst) % 2 != 0: r...
5,288,710
def plot_task_completion_rates( completion_rates: Union[List[float], Dict[str, List[float]]], bins: Union[list, range] = None, ax: Optional[Axes] = None ) -> Axes: """ Plot rate of task completion for a given task. :param completion_rates: Completion rates for each participant (0 -...
5,288,711
def generate_mosaic(source_images, n_columns, n_rows, border=0, border_colour=(255, 255, 255), randomise=False, output_folder='./'): """Creates a random mosaic from input images """ w...
5,288,712
def get_config(ini_loc): """ Reads config file 'main.ini' and returns config values Sample config file: [sqlite] dblocation: ./dbs/sops.db soplocation: ./text/ sopPDFlocation: ./pdf/ indexname: sops """ config = configparser.ConfigParser() config.read(os.p...
5,288,713
def write_geofile(graph: GeoGraph, path='./', nodes=True, edges=True, driver="GPKG", fiona_cast=True): """Export a networkx graph as a geographic files. Two files are generated: one for the nodes and one for the edges. The files names will be prefixed by the graph name and suffixed by "_edges" or "_nodes". ...
5,288,714
def deflate_long(n, add_sign_padding=True): """turns a long-int into a normalized byte string (adapted from Crypto.Util.number)""" # after much testing, this algorithm was deemed to be the fastest s = bytes() n = long(n) while (n != 0) and (n != -1): s = struct.pack('>I', n & xffffffff) + s ...
5,288,715
def draw_objects(draw, bboxes, labels): """Draws the bounding box and label for each object.""" for index, bbox in enumerate(bboxes): draw.rectangle([(bbox[0], bbox[1]), (bbox[2], bbox[3])], outline="red") label = labels[index] if " " not in label: draw.text((bbox[0] + 10, bb...
5,288,716
def get_todays_image(session: Session = Depends(generate_session), group_name: str = "Home"): """ Returns the image for todays meal-plan. """ group_in_db: GroupInDB = db.groups.get(session, group_name, "name") recipe = get_todays_meal(session, group_in_db) if recipe: recipe_image = ima...
5,288,717
def plot_imgs( img_list, row_title=None, cmap='viridis', show_axis=False, tight_layout=True, figsize=(10, 6) ): """Plot a series of cropped images. Parameters ---------- img_list : str A list of images to be plotted. row_title : str, optional Y-axis la...
5,288,718
def delete(transaction: spanner_transaction.Transaction, table_name: str, keyset: spanner.KeySet) -> None: """Deletes rows from the given table based on the provided KeySet. Args: transaction: The Spanner transaction to execute the request on table_name: The Spanner table being modified keys...
5,288,719
def sdO(data): """ This is the evolutionary definition of the sdB phase, which is defined as a core He burning phase where the star looks spectroscopically as an sdO star. This is defined as Teff higher than 40000 K. If the star does not have a core He burning phase as defined by HeCoreBurning, this fu...
5,288,720
def get_ecf_club(database, key): """Return ECFrefDBrecordECFclub instance for dbrecord[key].""" c = database.get_primary_record(filespec.ECFCLUB_FILE_DEF, key) cr = ECFrefDBrecordECFclub() cr.load_record(c) return cr
5,288,721
def find_known_node(node): """ Iterate through the config_dict to find to which key the given <node> might corresponds too. Returns: (str or None): config_dict key if match found else None """ for known_node, node_data in config_dict.items(): if node_data["check"](n...
5,288,722
def writeLabProfile(labs_counts, labs_frequencyPerYear, labs_fractionOfSubjects,labs_units, labs_names, labs_stats, labs_aboveBelowNorm, labs_correlatedLabsCoefficients, labs_abscorrelation, labs_correlatedMedsCoefficients, labs_correlatedProceduresCoefficients, ...
5,288,723
def test_save_outliers(test_config_ensemble: PlotCrossValidationConfig, test_output_dirs: OutputFolderForTests) -> None: """Test to make sure the outlier file for a split is as expected""" test_config_ensemble.outputs_directory = test_output_dirs.root_dir test_config_ensemble.outlier_...
5,288,724
def makeDicts(): """make a dict out of a live packet capture w/ the data we want""" listOfDicts = [] for pkt in capture.sniff_continuously(packet_count=50): listOfDicts.append({"source": pkt["ip"].src, "destination":pkt["ip"].dst, "protocol":pkt.highest_layer}) return listOfDicts
5,288,725
def unpack_event_page(event_page): """ Transform an EventPage document into individual Event documents. Parameters ---------- event_page : dict Yields ------ event : dict """ descriptor = event_page['descriptor'] data_list = _transpose_dict_of_lists(event_page['data']) ...
5,288,726
def create_sub_graph_by_node_capacity(dump_path=LIGHTNING_GRAPH_DUMP_PATH, k=64, highest_capacity_offset=0): """ Creates a sub graph with at most k nodes, selecting nodes by their total capacities. :param dump_path: The path to the JSON describing the lightning graph dump. :param k: The maximal number ...
5,288,727
def main(): """ >>> solve(4, 1000000000, 1000000000, 1000000000, 1) 4 >>> solve(4, 1, 1000000000, 1000000000, 1) 3 >>> solve(8, 1, 1000000000, 1000000000, 1) 4 """ T = int(input()) for t in range(T): print(solve(*[int(x) for x in input().split()]))
5,288,728
def parsething(thing): """I figure out what 'foobar baz in quux quum is not documented' means, and return: the name of the foobar, and the kind of the foobar. """ if thing.startswith("Compound "): tp, name = "type", thing.split()[1] else: m = THING_RE.match(thing) if not m...
5,288,729
def process(business: Business, # pylint: disable=too-many-branches filing: Dict, filing_rec: Filing, filing_meta: FilingMeta): # pylint: disable=too-many-branches """Process the incoming registration filing.""" # Extract the filing information for registration registra...
5,288,730
def from_rotation_around_x(angle): """Get the rotation matrix for rotation around X. Args: angle: rank N tensor of shape [..., 1]. Returns: rank N+1 tensor of shape [..., 3, 3] containing rotation matrices. Raises: ValueError: if the shape of angle is invalid. """ angle = tf.convert_to_tensor...
5,288,731
def process_watershed( job_id, watershed_vector_path, watershed_fid, dem_path, hab_path, pop_raster_path_list, target_beneficiaries_path_list, target_normalized_beneficiaries_path_list, target_hab_normalized_beneficiaries_path_list, target_stitch_work_queue_list): """Calculat...
5,288,732
def _get_child_pids(pid): """ Return the list of children ``PID``s for the given parent ``pid``. :param pid: An ``int`` representing the parent ``PID``. :return: A ``list`` of children ``PIDS``s (if any). """ sub_proc = subprocess.Popen( ['ps', '-o', 'pid', '--ppid', s...
5,288,733
def direct_field_search(queryset, field_names, search_string, as_of_date=None): """Takes a queryset and a list of field names that the search string can act on.""" # Split the string in case of first name, surname e.t.c search_strings = tokenize_search_string(search_string) q_filter = Q() ...
5,288,734
def get_all_triplets(labels: ndarray) -> ndarray: """Select all possible triplets of (anchor, positive, negative) from batch""" triplets = [] pos_pairs, neg_pairs = get_all_pairs(labels) for pos in pos_pairs: for neg in neg_pairs: if pos[0] == neg[0]: triplets.append(...
5,288,735
def get_start() -> dict: """Получение start при запуске бота.""" start = client.start() if start: return start sleep_delay() return get_start()
5,288,736
def _get_block_timestamp_from_web3( web3: Web3, block_number: int, ) -> int: """ Gets the timestamp of a block from the blockchain. will raise an exception if the block is not found. """ return web3.eth.getBlock(block_number).timestamp
5,288,737
def round_float(value, precision=1): """ Returns the float as a string, rounded to the specified precision and with trailing zeroes (and . if no decimals) removed. """ return str(round(value, precision)).rstrip("0").rstrip(".")
5,288,738
def stripMakeCodeHeader(incoming): """strip off byte header generated by makecode""" pos = incoming.rfind("\\x")+4 header = incoming[:pos] #TODO: unused body = incoming[pos:-1] return body
5,288,739
def get_etcd_client(): """ Gets the Etcd Client instance using host and port defined in TOTEM_ETCD_SETTINGS :return: Instance of etcd.Client :rtype: etcd.Client """ return etcd.Client(host=TOTEM_ETCD_SETTINGS['host'], port=TOTEM_ETCD_SETTINGS['port'])
5,288,740
def _widen_hsv_color_range(color_range, proportion): """Widens range by proportion new lower bound = old - (old * proportion / 2) new upper bound = old + (old * proportion / 2) """ new_range = [[None, None, None], [None, None, None]] max_values = [180, 255, 255] # h, s ,v for i in range(3): ...
5,288,741
def save_file(filename, response_data, last_update, is_stream=False): """ This writes to the file upon downloading. It reads the data in the response. Makes a new directory if needed and then writes the data to the file. It also modifies the last modified time to that of the S3 object. """ ...
5,288,742
def run(command): """Returns (return-code, stdout, stderr)""" p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, err = p.communicate() rc = p.returncode if PY3: enc = locale.getpreferredencoding() output = output...
5,288,743
def test_get_from_args_no_hit(config_file): """Try building experiment view when not in db""" cmdargs = {"name": "supernaekei", "config": config_file} with OrionState(experiments=[], trials=[]): with pytest.raises(NoConfigurationError) as exc_info: experiment_builder.get_from_args(cmdar...
5,288,744
def date(candidate: str) -> datetime.date: """Converts ECMWF-format date strings into a `datetime.date`. Accepted absolute date formats: - YYYY-MM-DD - YYYYMMDD - YYYY-DDD, where DDD refers to the day of the year For example: - 2021-10-31 - 19700101 - 1950-007 See https://conf...
5,288,745
def ylog(ylog=True): """ Enable or disable a logarithmic scale for the y-axis. :param ylog: whether or not the y-axis should be logarithmic **Usage examples:** >>> # Enable a logarithic y-axis >>> mlab.ylog() >>> # Disable it again >>> mlab.ylog(False) """ _plot_data(ylog=ylog...
5,288,746
def test_game(game,team): """Broken out so we can test for all kinds of variations once we build the variation list.""" return (team.lower() in [game["competitions"][0]["competitors"][0]["team"]["location"].lower(), game["competitions"][0]["competitors"][1]["team"]["location"].lower(), game["competitions"][0]["co...
5,288,747
def calculate_parse_metrics(gold_corpus, annotated_corpus): """Calculate POS/UAS/LAS accuracy based on gold and annotated sentences.""" check.Eq(len(gold_corpus), len(annotated_corpus), 'Corpora are not aligned') num_tokens = 0 num_correct_pos = 0 num_correct_uas = 0 num_correct_las = 0 for ...
5,288,748
def ifftn(x1, s=None, axes=None, norm=None): """ Compute the N-dimensional inverse discrete Fourier Transform. Multi-dimensional arrays computed as batch of 1-D arrays Limitations ----------- Parameter ``norm`` is unsupported. Parameter ``x1`` supports ``dpnp.int32``, ``dpnp.int64``, ``dpn...
5,288,749
def test_ipaddr_re(): """Validate IP address matching against various valid and invalid addresses.""" hostname_re = re.compile(f'^{core.matches.IPv4AddrCoreMatch()}$') valid = [ '199.250.10.0', '250.250.10.0', '250.250.10.1', '250.250.10.10', '255.250.10.1', ...
5,288,750
def get_summary(icalendar_text: str): """Get the first SUMMARY: line from an iCalendar text. Do not care about the line being continued. """ match = re.search(SUMMARY_PATTERN, icalendar_text) return match[1]
5,288,751
def sched_var(func): """This decorator marks the given function as a scheduler variable. The function must take no arguments (other than self).""" # The scheduler plugin class will search for these. func.is_sched_var = True func.is_deferable = False # Wrap the function function so it keeps it'...
5,288,752
def posgres_raw(query_sql, query_args=None, *, as_dict=True, alias=None, filterData=None, modifyData=None, **kwargs): """ Returns the answer to a raw sql statement to ther database. table (str) - Which table to get data from Example Input: posgres_select("SELECT * FROM property") Example Input: posgres_select("S...
5,288,753
def SetMatchmakingQueue(request, callback, customData = None, extraHeaders = None): """ SDK support is limited to C# and Java for this API. Create or update a matchmaking queue configuration. https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking-admin/setmatchmakingqueue """ if not Pla...
5,288,754
def test_parse_string_pretty_print() -> None: """Parse XML from a string. - Pretty-print using `xml.dom.minidom` """ root: ET.Element = ET.fromstring( '<data><country name="Liechtenstein"/><country name="Panama"/></data>' ) xml_string = ET.tostring(root, encoding="unicode") assert ...
5,288,755
def file_upload_url(): """ file_upload_url: returns url to upload files Args: None Returns: string url to file_upload endpoint """ return FILE_UPLOAD_URL.format(domain=DOMAIN)
5,288,756
def parse_command_line(version=None, self_description=None, version_date=None, default_config_file_path=None, ): """parse command line arguments Also add current version and version date to description """ # de...
5,288,757
def test_jax_scan_multiple_output(): """Test a scan implementation of a SEIR model. SEIR model definition: S[t+1] = S[t] - B[t] E[t+1] = E[t] +B[t] - C[t] I[t+1] = I[t+1] + C[t] - D[t] B[t] ~ Binom(S[t], beta) C[t] ~ Binom(E[t], gamma) D[t] ~ Binom(I[t], delta) """ def binomln...
5,288,758
def marathon_on_marathon(name='marathon-user'): """ Context manager for altering the marathon client for MoM :param name: service name of MoM to use :type name: str """ client = marathon.create_client(name) yield client
5,288,759
def appium_bytes(value, encoding): """ Return a bytes-like object. Has _appium_ prefix to avoid overriding built-in bytes. :param value: A value to convert :type value: string :param encoding: A encoding which will convert to :type encoding: string :return: A bytes-like object :rtype:...
5,288,760
def make_traces_one_plane(res, plane_dir, tif_dir_name='reg_tif', n_cols=3, n_comps_per_slice=12, save_dir_name='traces', overwrite=OVERWRITE_VIDS): """Plot and save traces for each component in plane.""" # Make directories to save videos if necessary save...
5,288,761
def main(argv): """Process a given filename""" filename = argv[1] df = pd.read_csv(filename) df["date"] = pd.to_datetime(df["date"]) df["value"] = pd.to_numeric(df["value"]) pdf = df.pivot_table( index=[ "uniqueid", "plotid", "method", "pos...
5,288,762
def read_sts_inputs(path: str) -> List[str]: """Read input texts from a tsv file, formatted like the official STS benchmark""" inputs = [] with open(path, 'r', encoding='utf8') as fh: reader = csv.reader(fh, delimiter='\t', quoting=csv.QUOTE_NONE) for row in reader: try: ...
5,288,763
def get_size(path: Path, decimal_places: int = 1) -> float: """ Get file size in MB, rounded to decimal_places. :param path: Path to the file. :param decimal_places: int, count of sighs after dor in result value. :return: float, rounded size of the file in MB. """ if not path....
5,288,764
def extract_keys(dict, keys, no_key_val=_sentinel): """Removes the specified keys from the given dictionary, and returns a dictionary containing those key:value pairs. Default behaviour is to ignore those keys which can't be found in the original dictionary. The optional argument :no_key_val: can be set to ...
5,288,765
def resnet101(num_classes, pretrained=False, dropout1=0.25, dropout2=0.25, alpha=0.25, gamma=2.0, loss_with_no_bboxes=False, no_bboxes_alpha=0.5, no_bboxes_gamma=2, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet ...
5,288,766
def vuvu_to_vuhw(vuvu): """ Function to transform between top left and bottom right corner box representation (vuvu) to center_dimensions box representation (vuhw) . :param vuvu: N x 4 tensor represeting v_min, u_min, v_max, u_max, the corners of the bounding boxes. :return: vuhw: N x 4 tensor rep...
5,288,767
async def async_unload_entry(hass, config_entry): """Unload an AirVisual config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(config_entry, component) for component in PLATFORMS ] ) )...
5,288,768
def application_doesnt_match(service, custom_application, custom_app_plan, lifecycle_hooks, request): """Second application that doesn't match jwt claim check policy""" plan = custom_app_plan(rawobj.ApplicationPlan(blame(request, "aplan")), service) application = custom_application(rawobj.Application(blame(...
5,288,769
def delete_appliance_for_rediscovery( self, ne_pk: str, ) -> bool: """Delete an appliance from Orchestrator for rediscovery .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - appliance - DELETE - /appliance/delete...
5,288,770
def get_motif_pwm(motif_file: str, args_obj: Findmotif, cores: int, debug: bool ) -> List[Motif]: """Construction of Motif object from PWM file. The motif PWM is processed in order to obtain the corresponding scoring matrix (values scaled in [0,1000]) a...
5,288,771
def start_server(**kwargs): """ Starts the server and obtains all necessary config data. """ if kwargs["log_level"]: # Set logger level level = logging.getLevelName(kwargs["log_level"].upper()) root_logger.setLevel(level) else: root_logger.setLevel("INFO") # Conf...
5,288,772
def increase_index(idx: str) -> str: """Increases an index by one unit. If the index is numeric, in the range '00' to '98', it adds one to the index and returns an index in the range '01' to '99'. If the index is already '99', there is an Exception error. If the index is alphanumeric, with the fir...
5,288,773
def _validate_input_features( input_features = constants.INPUT_FEATURES): """Validates values for `input_features`.""" if not all(x in constants.INPUT_FEATURES for x in input_features): raise ValueError(f'input_features=[{input_features}] should be present in ' f'[{constants.INPUT_FEATU...
5,288,774
def barcode_generator(barcodes): """generator to push out barcodes """ barcode_idx = 0 used_barcodes = set() while barcode_idx < len(barcodes): barcode = barcodes[barcode_idx] if is_barcode_compatible(barcode): #assert _check_min_diff(barcode, used_barcodes) a...
5,288,775
def compare_flow_fields(F1, F2, n_min=1): """Compare two flow fields. """ # Compute the element-by-element difference dX_diff = F1.dX_fit - F2.dX_fit dX_diff_mag = np.linalg.norm(dX_diff, axis=2) # n_grid x n_grid # Filter by the number of observations. Find the number of observations for ...
5,288,776
def rollup_dataseries(dataseries): """ Rollup dataseries. Roll up a sites data series by parameter group if a series has them. Data types for the parameter group is the join of the data types for each measured parameter code. Similarly, the start and end dates are the earliest and latest date o...
5,288,777
def determine_smallest_atom_index_in_scan(atom1: 'rdkit.Chem.rdchem.Atom', atom2: 'rdkit.Chem.rdchem.Atom', ) -> int: """ Determine the smallest atom index in mol connected to ``atom1`` which is not ``atom2``. Returns a heav...
5,288,778
def load_project(project_directory, prefix='', new_targets_location=None, repository_name='default'): """ <Purpose> Return a Project object initialized with the contents of the metadata files loaded from 'project_directory'. <Arguments> project_directory: The path to the project's metadata ...
5,288,779
def get_patches(run_local): """Returns the list of patch files located in the adabot/patches directory. """ return_list = [] if not run_local: contents = requests.get( "https://api.github.com/repos/adafruit/adabot/contents/patches" ) if contents.ok: fo...
5,288,780
def test_get_t50(): """ Find half life of give species from RMG's minimal example. """ t3 = run_minimal(project_directory=TEST_DIR) t3.set_paths() cantera_simulator_adapter = CanteraConstantUV(t3=t3.t3, rmg=t3.rmg, ...
5,288,781
def quartiles(xs): """Divisions between quartiles.""" return quantiles(xs, 0.25, 0.5, 0.75)
5,288,782
async def test_launch_worker(monkeypatch, manager_cfg): """Test the creation of the worker process """ fake_environ = {} monkeypatch.setattr(os, 'environ', fake_environ) manager = init_static_manager(manager_cfg) fake_process = MagicMock() create_subprocess_fn = get_async_task_mock(fake_pro...
5,288,783
def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return date...
5,288,784
def write_domain(domain_home): """ Persist the newly created domain configuration to the provided location. This will automatically overwrite an existing domain at this location. :param domain_home: path location to write the domain and its configuration :raises: PyWLSTException: if a WLST error occ...
5,288,785
def get_utc_timestamp() -> Text: """Get utc timestamp. Returns: Text: utc timestamp """ return str(datetime.datetime.utcnow().timestamp() * 1000)
5,288,786
def test_pickling(simulation_factory, two_particle_snapshot_factory): """Test that QuickCompress objects are picklable.""" qc = hoomd.hpmc.update.QuickCompress(trigger=hoomd.trigger.Periodic(10), target_box=hoomd.Box.square(10.)) sim = simulation_factory(two_particl...
5,288,787
def calc_pure_python(draw_output, desired_width, max_iterations): """Create a list of complex co-ordinates (zs) and complex parameters (cs), build Julia set and display""" x_step = (x2 - x1) / desired_width y_step = (y1 - y2) / desired_width x = [] y = [] ycoord = y2 while ycoord > y1: ...
5,288,788
def ConvolutionalVAE(*args, **kwargs): """ Constructs a Convolutional VAE. References [1]. Oktay, Ozan, et al. “Attention U-Net: Learning Where to Look for the Pancreas.” ArXiv:1804.03999 [Cs], May 2018. arXiv.org, http://arxiv.org/abs/1804.03999. >>> import deeply >>> model = deeply.hub("...
5,288,789
def to_2d_np(a: ndarray, type: str="col") -> ndarray: """ Turns a 1D Tensor into 2D """ assert a.ndim == 1, \ "Input tensors must be 1 dimensional" if type == "col": return a.reshape(-1, 1) elif type == "row": return a.reshape(1, -1)
5,288,790
def import_df(df_path, match_column, seq_dirs, name_column, samples_fp, units_fp, fofn_fp): """ associates sample names from a dataframe column with f and r files """ df = pd.read_csv(df_path) seq_fps = {} for seq_dir in seq_dirs: seq_fps[seq_dir] = parse_seq_dir(seq_dir) ...
5,288,791
def read_dictionary(vocab_path): """ :param vocab_path: :return: """ vocab_path = os.path.join(vocab_path) with open(vocab_path, 'rb') as fr: word2id = pickle.load(fr) print('vocab_size:', len(word2id)) return word2id
5,288,792
def deepsleep(duration=0): """ Deep sleep """
5,288,793
def get_category(main_category, detail_category, region, **filters): """ Scrape OtoDom search results based on supplied parameters. :param main_category: "wynajem" or "sprzedaz", should not be empty :param detail_category: "mieszkanie", "dom", "pokoj", "dzialka", "lokal", "haleimagazyny", "garaz", or ...
5,288,794
def standardize_parameter_type(original_type): """Standardize parameter type descriptions Args: original_type (str): The original type Returns: str: The standarized type name """ original_type = original_type.lower() if 'unc' in original_type: return 'uncertainty' i...
5,288,795
def _yaml_completer(prefix, parsed_args, **__): """ Autocomplete YAML and directories paths. Args: prefix (str): Application prefix to filter. parsed_args (argparse.Namespace): CLI arguments. Yields: str: path """ from os import listdir from os.path import join, isd...
5,288,796
def _get_pd_fields(d, files, r_prefix): """Retrieve form fields representing a product.""" fields = ['id', 'name', 'price', 'quantity_per_package', 'unit', 'quantity_limit', 'quantum', 'unit_weight', 'place', 'described', 'description', 'image-modified'] raw = {f: d.get("%s-%s" % (r_prefix, f)...
5,288,797
def videos_handling(verbose=True): """Handling of all videos files.""" videos_files = list_files_by_patterns(base_directory, list_of_patterns[ 'video_files']) move_files_to_directory(videos_files, ...
5,288,798
def parse_args(args=sys.argv[1:]): """ Get the parsed arguments specified on this script. """ parser = argparse.ArgumentParser(description="") parser.add_argument( 'output_path', action='store', type=str, help='Path to output file.') return parser.parse_args(args)
5,288,799