content
stringlengths
22
815k
id
int64
0
4.91M
def pssm_scan(pwm, seqs, background_probs=[0.27, 0.23, 0.23, 0.27], pad_mode='median', n_jobs=10, verbose=True): """ """ def pwm2pssm(arr, background_probs): """Convert pwm array to pssm array pwm means that rows sum to one """ arr = arr / arr.sum(1, keepdims=True) ar...
5,307,800
def build_orientation_img(d, mask): """ Args: d: [.., H, W, 8] mask: [..., H, W] """ y = np.expand_dims(mask, -1) cw = color_wheel did = np.argmax(d, -1) new_shape = [] for ss in xrange(len(y.shape) - 1): new_shape.append(y.shape[ss]) new_shape.append(3) c...
5,307,801
def compute_projection_transforms(origins, transformer) -> np.ndarray: """ Convert vectors from one coordinate system to another. Unlike positions, this cannot be done with a simple pyproj call. We first need to set up a vector start and end point, convert those into the new coordinate system and th...
5,307,802
def copyfile(filename, target_dir): """Copy a file into a target directory. Defined in :numref:`sec_kaggle_cifar10`""" os.makedirs(target_dir, exist_ok=True) shutil.copy(filename, target_dir)
5,307,803
def get_function_by_name(full_name): """ RETURN FUNCTION """ # IMPORT MODULE FOR HANDLER path = full_name.split(".") function_name = path[-1] path = ".".join(path[:-1]) constructor = None try: temp = __import__(path, globals(), locals(), [function_name], -1) output =...
5,307,804
def get_app(endpoints): """ :param list(Endpoint) endpoints: Endpoints describing the mapper :rtype: aiohttp.web.Application :returns: an app configured as describes in endpoints """ app = web.Application(middlewares=[error_middleware]) async def on_startup(app): app['rabbitmq_conne...
5,307,805
def FdtFsParse(path): """Parse device tree filesystem and return a Fdt instance Should be /proc/device-tree on a device, or the fusemount.py mount point. """ root = FdtNode("/") if path.endswith('/'): path = path[:-1] nodes = {path: root} for subpath, subdirs, files in o...
5,307,806
def get_abbr_data(): """ Get a deep copy of the abbreviation map. Returns ------- :class:`dict` (:class:`str`, :class:`str`) A dictionary of the identifiers, the keys are the abbreviation. """ return copy.deepcopy(_glass_type_registry)
5,307,807
def _load_data_input_from_file(path: str, **further_parse_args) -> Union[pd.DataFrame, list]: """Load and process the input data according the input file format.""" if path.endswith(CSV): return from_dataframe_file(path, CSV) elif path.endswith(XLS_FORMATS): return parse_xls_to_df(path, ...
5,307,808
def generate_ceiling_json(conf: ConfigManager, polyline, room_id: str, multiplication_factor: float) -> dict: """ Generate a json describing a ceiling. :param conf: ConfigManager :param polyline: Outline of the room :param room_id: id of the room :param multiplication_factor: Scale factor to rea...
5,307,809
async def test_user_input_unknown_error( hass, mock_get_device_info_exception, mock_get_source_ip ): """Test when user specifies an existing device, which does not provide the musiccast API.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}...
5,307,810
def _compute_edge_transforms(node_states, depth, num_transforms, ignore_zero=True, name="transform"): """Helper function that computes transformation for keys and values. Let B be the number of batch...
5,307,811
def optimize(model, **kwargs): """Removes LogSoftmax and positive scaling (Mul) layers from the network because they do not change the prediction. Args: model (NeuralNet): The NeuralNet model. Returns: NeuralNet: The NeuralNet model with removed layers. """ while( (isinstance(model...
5,307,812
def fetch_run(workspace: Workspace, run_recovery_id: str) -> Run: """ Finds an existing run in an experiment, based on a recovery ID that contains the experiment ID and the actual RunId. The run can be specified either in the experiment_name:run_id format, or just the run_id. :param workspace: the conf...
5,307,813
def mono_anal(y, fs, param=None): """Run pyin on an audio signal y. Parameters ---------- y : np.array audio signal fs : float audio sample rate param : dict default=None threshdistr : int, default=2 Yin threshold distribution identifier. - 0 ...
5,307,814
def add_compilation_details(): """ Append HTML compilation warnings/errors details Returns: a string with formatted HTML details section. """ cwd = os.getcwd() details = '' with open(os.path.join(cwd, DETAILS_HEADER), 'r') as temp: details = temp.read() details += add_c...
5,307,815
def load_model(model_file): """Load a pretained model from pickel file.""" if not os.path.exists(model_file): raise IOError("Model file does not exist: %s" %model_file) model = joblib.load(model_file) print("INFO: Model %s was loaded successfully." \ %os.path.basename(model_file)) ...
5,307,816
def config_mgmt_for_kerberos(): """ Setup Cloudera Manager Kerberos Configuration :return: """ cm_fqdn = cm_hostname KDC_ADMIN_HOST = cm_client.ApiConfig(name='KDC_ADMIN_HOST', value=cm_fqdn) KDC_ADMIN_PASSWORD = cm_client.ApiConfig(name='KDC_ADMIN_PASSWORD', value=kdc_password) KDC_ADM...
5,307,817
def format_dict(_dict, tidy=True): """ This function format a dict. If the main dict or a deep dict has only on element {"col_name":{0.5: 200}} we get 200 :param _dict: dict to be formatted :param tidy: :return: """ if tidy is True: levels = 2 while (levels>=0): ...
5,307,818
def get_crc24(data: str) -> dict: """ Implementation of the CRC-24 algorithm from OpenPGP. Returns the CRC-24 checksum value in decimal and hexadecimal format. """ data = bytearray(data.encode('utf-8')) crc = 0x00b704ce for byte in data: crc = (CRC24_TABLE[((crc >> 16) ^ byte) & 0xff...
5,307,819
def new_ec2_instances(cluster, n=1, maxWait=180, instance_type=None, ami=None, key=None, az=None, placement_group=None, skipStores=None, ...
5,307,820
def create_pivot_value_request_param(request_params: dict, postgrest_host: str) -> dict: """Find the pivot value for a seek pagination. This should only happen if the user is sorting by anything other than `int_id`, and wants to get data after a certain `int_id`. NOTE: This function performs an O(1) SEL...
5,307,821
def pfirst(*args, **kwargs): """ For each occurrence of this function in source code, print only on the first call. e.g. >>> for n in [1, 2]: ... _ = pfirst(n * 10) ... _ = pfirst(n * 100) 10 100 """ stack = _getstack() if not stack in pfirst.seen_stacktraces: pf...
5,307,822
def read_obo(file): """ read ontology from file :param file: file path of file handle """ G = nx.DiGraph() if isinstance(file, str): if file.endswith('.gz'): f = gzip.open(file, 'rt') else: f = open(file) we_opened_file = True else: f = fi...
5,307,823
def _GetColocationNames(op): """Returns names of the ops that `op` should be colocated with.""" colocation_names = [] try: class_values = op.get_attr('_class') except ValueError: # No _class attr return for val in class_values: val = compat.as_str(val) if val.startswith('loc:@'): col...
5,307,824
def read_tokens(database_path, search_string='', output_max=20): """Вывод характерных для автора слов.""" database = sqlite3.connect(database_path) cursor = database.cursor() storycount_all = cursor.execute("SELECT count(id) FROM stories").fetchone()[0] tokens_list = get_tokens(search_string, cursor...
5,307,825
def add_trusted_member(guild_id: int, user_id: int) -> None: """Add a trusted member for a guild.""" _add_trusted(guild_id, user_id, category=Categories.MEMBER)
5,307,826
def _current_trace(): """Returns the innermost Jax tracer.""" tracers = _masters() if tracers: return tracers[-1] return None
5,307,827
def tailor_queries(query_item, query_target): """ This substitutes common parameters for values from the script. Later, this will be a data driven exercise. """ replacements = dict() replacements['{{deployment}}'] = query_target.split('_')[0] replacements['{{org_id}}'] = query_target.split('...
5,307,828
def parse_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser( description='GloVe with GluonNLP', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Data options group = parser.add_argument_group('Data arguments') group.add_argument( 'cooccurr...
5,307,829
def enlarge(image, size, axis=1, efunc=energy_function, cfunc=compute_cost, dfunc=duplicate_seam, bfunc=backtrack_seam, rfunc=remove_seam): """Enlarges the size of the image by duplicating the low energy seams. We start by getting the k seams to duplicate through function find_seams. We iterate through the...
5,307,830
def _extract_traceback(start): """ SNAGGED FROM traceback.py RETURN list OF dicts DESCRIBING THE STACK TRACE """ tb = sys.exc_info()[2] for i in range(start): tb = tb.tb_next return _parse_traceback(tb)
5,307,831
def get_answer(random_country_index): """ Function that randomly decides the type of the answer (either LANGUAGES or CAPITALS). It also accesses the dictionary using the randomly generated index and it fetches the corresponding item from it.""" random_question = random.randint(1,10) answer = ("",...
5,307,832
def walk_data_type_folder(filesystem, folder_path): """ Walks a data type subfolder of OOI and yields tuples (ooi name, path in filesystem) """ for path in filesystem.listdir(folder_path): if '/' not in path and '.' in path: yield path.split('.')[0], fs.path.combine(folder_path...
5,307,833
def Rx(r): """Construct a rotation matrix around X-axis.""" return _Rx(np.cos(r), np.sin(r))
5,307,834
def dtime(dstr): """Convert datetime strings to datetime instances.""" if isinstance(dstr, bytes): dstr = dstr.decode() return datetime.datetime.strptime(dstr, fs_fmt)
5,307,835
def _create_split(last_key, next_key, query): """Create a new {@link Query} given the query and range.. Args: last_key: the previous key. If null then assumed to be the beginning. next_key: the next key. If null then assumed to be the end. query: the desired query. Returns: A split query with fe...
5,307,836
def test_icon_eval(base_fixture, tmp_path, qtbot): """ Tests, that the icon setter works on all cases. Expects package relative file, config-file rel. file, automaticaly extracted file, and error message and default icon on no file. """ # copy icons to tmp_path to fake package path ...
5,307,837
def compute_checksum(message): """Calculates the 16-bit one's complement of the one's complement sum of a given message.""" # If the message length isn't a multiple of 2 bytes, we pad with # zeros if len(message) % 2: message += struct.pack('x') # We build our blocks to sum to_sum ...
5,307,838
def makeFont(showtext, srcfont, tgtfont): """制作字体""" source_font = TTFont(srcfont) source_cmap = source_font.getBestCmap() plain_text = _pre_deal_obfuscator_input_str(showtext) obfuscator_code_list = random.sample(range(0xE000, 0xF8FF), len(plain_text)) _check_cmap_include_all_text(source_cmap,...
5,307,839
def test_block_structure_vectors_on_nodes_validity(n_rods): """ This function is testing validity of vectors on nodes. It is been tested that for vectors node variables, if the block structure memory and values are set correctly and rods that belong to rod structure share the memory with block struc...
5,307,840
def mockup_return(*args, **kwargs): """Mockup to replace regular functions for error injection.""" return False
5,307,841
def push_notification(title, message, url=None, gcm_url=None, users=None): """プッシュ通知を各端末に送信する。 :param users: :param title: :param message: :param gcm_url: :return: """ if not gcm_url: gcm_url = Config.get_gcm_url() if users: queryset = PushNotification.objects.publi...
5,307,842
def publish_shelter(shelter_id=None): """ Publish/Unpublish a shelter. """ shelter = Shelter.query.filter(Shelter.id == shelter_id).first() if shelter: shelter.is_published = request.args.get('publish', not shelter.is_published) db.sess...
5,307,843
def convert_utc_to_pdt(time_of_interest: datetime) -> datetime: """ Get the datetime in Pacific Daylight Timezone (PDT) : UTC-7 given a datetime in UTC timezone """ return time_of_interest.astimezone(timezone(offset=timedelta(hours=PDT_UTC_OFFSET)))
5,307,844
def format_input(param): """Return a string with all the inputs property formatted. """ tmp1 = ' {type} {var}{ctor}; XC_LI_.load({var});\n' tmp2 = ' {type} {var}{ctor}; XC_LI_.load({var}, {sample});\n' inputs = '' for par in param: if 'sample' in par: inputs += tmp2.format(...
5,307,845
def example(method): """Performs a short example run of the retrievals using local machine. Parameters ---------- method : str The method to use to perform the atmopsheric retrieval; can either be ``multinest`` or ``emcee`` """ # Ensure that the method parameter is valid ...
5,307,846
def patient_sur(N, t, survival, show=False): """ generate N patient survival time from survival function """ y_n = np.random.uniform(0, 1.0, N) x_n = np.interp(1 - y_n, 1 - survival, t) if show: plt.plot(x_n, y_n, '.') plt.plot(t, survival) plt.xlabel('Time') plt.ylabel...
5,307,847
def validate_args(args): """ """ if not args.output.endswith(".tf"): logging.exception(f'Output filename should end with .tf (i.e output.tf)') raise ValueError('Output filename should end with .tf (i.e output.tf)') if args.input == "ALL": return None elif args.input.end...
5,307,848
def get_git_project_files(): """Retrieve a list of all non-ignored files, including untracked files, excluding deleted files. :return: sorted list of git project files :rtype: :class:`list` """ cached_and_untracked_files = git_ls_files( '--cached', # All files cached in the index ...
5,307,849
def _remove_digital_filter(dic, data): """ Remove the digital filter from Bruker data. nmrglue modified Digital Filter Processing """ if "acqus" not in dic: raise KeyError("dictionary does not contain acqus parameters") if "DECIM" not in dic["acqus"]: raise KeyError("dictionary ...
5,307,850
def add_codes(err_cls): """Add error codes to string messages via class attribute names.""" class ErrorsWithCodes(object): def __getattribute__(self, code): msg = getattr(err_cls, code) return "[{code}] {msg}".format(code=code, msg=msg) return ErrorsWithCodes()
5,307,851
def update() -> None: """Retrieve a list of DNS name servers and store them into db.""" ips = get_shecan_ips() if ips: reset() add(ips)
5,307,852
def priceband_search_listener(sender, request=None, category=None, keywords=[], results={}, **kwargs): """Filter search results by price bands. If a "priceband" parameter is available, it will be parsed as follows: lowval-highval if there is no "-", then it will be parsed as lowval or higher ...
5,307,853
def get_token_ids_from_text_field_tensors( text_field_tensors: Dict[str, Dict[str, torch.Tensor]], ) -> torch.Tensor: """ Our `TextFieldTensors` are complex output structures, because they try to handle a lot of potential variation. Sometimes, you just want to grab the token ids from this data structure...
5,307,854
def ping(): """Determine if the container is working and healthy. In this sample container, we declare it healthy if we can load the model successfully.""" global clf if clf is None: clf = ScoringService.get_model() status = 200 return flask.Response(response='\n', status=status, mimetyp...
5,307,855
def s_linear(y, a): """Transformation function.""" assert y >= 0.0 assert y <= 1.0 assert a > 0.0 assert a < 1.0 return correct_to_01(abs(y - a) / abs(math.floor(a - y) + a))
5,307,856
def posts_from_rest_files(fnames): """ Read posts from ReST files """ ret = [] for parts, docinfo in _parse_rest_files(fnames): page = posts.Post(title=parts['title'], contents=parts['body'], slug=docinfo['slug'], ...
5,307,857
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Set up configured Weatherbit.""" # We allow setup only through config flow type of config return True
5,307,858
def _validate_licence(data: dict) -> dict: """Validates that a Licence exists and that the Goods exist on that Licence""" serializer = HMRCIntegrationUsageUpdateLicenceSerializer(data=data) if not serializer.is_valid(): data["errors"] = serializer.errors return data try: licen...
5,307,859
def task_package(): """create/upload package to pypi""" pkg = Package() yield pkg.revision_git() yield pkg.manifest_git() yield pkg.sdist() # yield pkg.sdist_upload()
5,307,860
def extend_bed(bed, bp, direction='both'): """Extend each interval in bed file with specified basepairs. If bp is a list, each interval will be extended bp[0] toward upstream, and bp[1] toward downstream. Note: Be careful! This method does not deal with strandedness of the interval. :param ...
5,307,861
def chem_potential_water_t_exact(SA, t, p): """ Calculates the chemical potential of water in seawater. Parameters ---------- SA : array-like Absolute Salinity, g/kg t : array-like In-situ temperature (ITS-90), degrees C p : array-like Sea pressure (absolute pressure...
5,307,862
def generate_neg_edges(G, num_neg_edges): """ Given a graph, sample negative edges from the complement graph. :param G: graph :param num_neg_edges: number of edges to sample :returns neg_edges: the sampled edges """ G_comp = nx.complement(G) neg_edges = random.sample(G_comp.edges(), num_...
5,307,863
def bolster_missing_time_periods(filter_time_periods, queryset, date_range_type, columns): """ Given the following, generate a list of dict results split by fiscal years/quarters/months Args: filter_time_periods: list of time_period objects usually provided by filters - {'start_...
5,307,864
def write_file(file_name, contents): """Write the contents of a provided list or string to a file""" f = open(file_name, 'w') if contents.__class__.__name__ == 'list': f.write("\n".join(contents)) else: f.write(contents) f.close()
5,307,865
def lock_tables(tablenames, engine): """Lock a list of tables so that other processes can't access them while you do your thing.""" if type(tablenames) not in {list, tuple}: tablenames = [tablenames] try: engine.execute("set innodb_lock_wait_timeout=14400") engine.execute("lock table...
5,307,866
def screenStocks_Multiproccesed(ticker_list, strategy, last_days): """ Screens stock list with strategy. Returns list of [tickers, last buy dates, stock performance stats] if last buy date of stock is within last_days This particular function is multiproccesed with pythons concurrent.futures package Ar...
5,307,867
def get_cached_locale(locale): """ Gets the given locale from cache if present. Parameters ---------- locale : `str` The local to get from cache. Returns ------- locale : `str` """ return LOCALES.setdefault(locale, locale)
5,307,868
def register_default_deserializer(self, factory_class: ParseNodeFactory) -> None: """Registers the default deserializer to the registry. Args: factory_class (ParseNodeFactory):the class of the factory to be registered. """ base_class = type(factory_class) deserializer = base_class() Par...
5,307,869
def _IsTpuTraining(p): """Whether we should create embedding tables and run lookup on tpu.""" return not p.is_inference and py_utils.use_tpu()
5,307,870
def get_first_index_where(array, criterion, value): """get the first index where array fulfills a criterion w.r.t. value, where criterion may be "geq" (greater equal), "gt" (greater than), "leq" (less equal) or "lt" (less than). If criterion is met nowhere, function returns len(array) Args: ...
5,307,871
def score_per_player(df: pd.DataFrame, selected_player: str) -> Tuple[pd.DataFrame, pd.DataFrame]: """Plot score per player Parameters: ----------- selected_game_df : pandas.core.frame.DataFrame Data for the selected game selected_player : str The selected pla...
5,307,872
def GetXcodeDeveloperDirectory(): """Returns the active developer directory as reported by 'xcode-select -p'. Returns None if none is set.""" if not MacOS(): return None return GetCommandOutput("xcode-select -p")
5,307,873
def norm(a, b): """ Return a unit normal to a and b. """ k = np.cross(a, b) return k / np.linalg.norm(k)
5,307,874
def logical_factor_rules() -> FrozenDict: """Logical factor rules for Mixture of Experts.""" rules = flax_core.unfreeze(adafactor.standard_logical_factor_rules()) rules.update({ 'expert': FactorDim.BATCH, 'expert_mlp': FactorDim.COLUMN, 'unmodeled': FactorDim.NONE }) return flax_core.freeze(...
5,307,875
def row_rounder(row: Sequence[str], line: Optional[int], has_total_col: bool = False) -> Sequence[Union[str, float]]: """ To convert the data in a CSV row to percentages and then smartly round the percentages to no decimal with a guarantee that the sum of rounded percentages is 100%. The row can ha...
5,307,876
def three_blocks_avgpooling(img_width, img_height, img_channels, output_dim): """ Define model architecture. # Arguments img_width: Target image widht. img_height: Target image height. img_channels: Target image channels. output_dim: Dimension of model output. # ...
5,307,877
def parse_life_105(file): """Parse a Life 1.05 file, returning a tuple: positions: list of (x,y) co-ordinates comments: all comments in file, as a list of strings, one per line. """ lines = file.split("\n") comments = [] positions = [] ox, oy = 0, 0 x, y = ox, oy patter...
5,307,878
def test_cwy_enum(): """ This test will fail if we accidentally change the public interface for the Cwy enum """ from megalinref import Cwy assert_dictdiffer( result = Cwy, expected_result = { "L": 0b0100, "S": 0b0010, ...
5,307,879
def test_set_descriptor(): """ This test checks that the set_descriptor function works as expected. :return: """ test_dir = os.path.dirname(os.path.realpath(__file__)) data_incorrect = np.load(test_dir + "/data/CN_isopent_light_UCM.npz") data_correct = np.load(test_dir + "/data/local_slatm_...
5,307,880
def tsa_constant_skater_factory(y: Y_TYPE, s: dict, k: int, a: A_TYPE = None, t: T_TYPE = None, e: E_TYPE = None, p:int=TSA_P_DEFAULT, d:int=TSA_D_DEFAULT, q:int=TSA_D_DEFAULT) -> ([float], Any, Any): """ Extremely simple univariate, fixed p,d,q ARIMA model ...
5,307,881
def backup_data_to_s3(config, prev_month=False, **kwargs): """Backup data to AmazonAWS S3.""" today = date.today() added = "" failed = "" if not prev_month: print ("Beginning daily data backup: {}".format(datetime.now())) else: print ("Beginning monthly data backup: {}".for...
5,307,882
def save_vertex_attributes(mesh): """ Saves the boundary and cut attributes that are on the mesh on a dictionary. """ v_attributes_dict = {'boundary_1': [], 'boundary_2': [], 'cut': {}} cut_indices = [] for vkey, data in mesh.vertices(data=True): cut_index = data['cut'] if cut_i...
5,307,883
def record_test_summaries(writer, epoch, scalars): """ Record testing summaries. """ average = scalars["average"] # Average loss writer.add_scalar("Val_loss/junc_loss", average["junc_loss"], epoch) writer.add_scalar("Val_loss/heatmap_loss", average["heatmap_loss"], epoch) writer.add_scalar("Val...
5,307,884
def test_load_data(): """<https://github.com/keras-team/keras/issues/12729>""" import tensorflow as tf tf.keras.datasets.imdb.load_data()
5,307,885
def test_remove01(): """Removing an item maintains list.""" from double_linked_list import Node, DoubleLinkedList dll = DoubleLinkedList() dll.push('z') dll.push('x') dll.push('y') dll.remove('x') assert dll.head.next_node.data == 'z'
5,307,886
def server_error_to_message(e, error_statement, error_detail, rows = None): """サーバーエラーレスポンス(メッセージ付き) server error response with message Args: e (Exception): 例外 exception error_statement (str): エラー情報(処理内容)error info. process contents error_detail (str): エラー情報詳細 error detail Returns:...
5,307,887
def upload(): """Upload package.""" with _dist_wrapper(): local("python setup.py sdist upload", capture=False)
5,307,888
def test_aircall_params_default_limit(con, mocker): """It should retrieve 100 entries by default""" get_page_data_spy = mocker.spy(AircallConnector, '_get_page_data') ds = AircallDataSource( name='test_name', domain='test_domain', endpoint='/calls', filter='.calls | map({id})', ) df = con.g...
5,307,889
def partition_list(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i + n]
5,307,890
def eliminate_nonvalid_coords(coords, mapshape): """ Eliminate nonvalid indices Args: coords(set of tuples): input set of positions h(int): height w(int): width Returns: set of valid coordinates """ h, w = mapshape valid = [] for j, i in coords: if j < 0 or j >= h:...
5,307,891
def lastnedFlere(driftskontrakter = False, veglister=False, kostra=False, mappenavn=None, miljo=None ): """ Skjellet for det som skal bli en robust nedlasting av alle relevante rapporttyper for en (lang) liste av k.områder / andre områder. Under arbeid TODO: Forske fram hvordan er det effektivt å bruke s...
5,307,892
def output_line(line, outfile, verbose): """ Output a (potentially) converted line. Args: line: the line to output outfile: Output file to write converted commands verbose: True iff converted commands should also be output to console """ outfile.write(line) if verbose: ...
5,307,893
def test_object_size(x, y): """Check that Vector is 2 times smaller than a naïve version.""" from pympler.asizeof import asizeof as sizeof # type: ignore assert sizeof(Vector(x, y)) < sizeof(DummyVector(x, y)) / 2
5,307,894
def construct_1d_ndarray_preserving_na( values: Sequence, dtype: Optional[DtypeObj] = None, copy: bool = False ) -> np.ndarray: """ Construct a new ndarray, coercing `values` to `dtype`, preserving NA. Parameters ---------- values : Sequence dtype : numpy.dtype, optional copy : bool, de...
5,307,895
def walk_directory(directory): """ Walk through a data directory and list the number of files. :param directory: Full path to the directory :return: """ for dirpath, dirnames, filenames in os.walk(directory): print(f"There are {len(dirnames)} directories and '{len(filenames)}'' files in ...
5,307,896
def create_environ_file(ctx, type_marker='production'): """Creates environment marker file for a given environment type. :param ctx: :param str type_marker: """ sys_fs.append_to_file(ctx, ctx.paths.remote.project.state.environ, type_marker)
5,307,897
def getPosUntilRoot(object): """ Go through the hierarchy of the object until reaching the top level, increment the position to get the transformation due to parents. @type object: hostObject @param object: the object @rtype: list @return: the cumulative translation along the ...
5,307,898
def add_head(w: Union['WorkflowTemplate', 'CronWorkflow', 'Workflow'], t: Task, append: bool = True) -> None: """Adds a task at the head of the workflow so the workflow start with the given task. This sets the given task as a dependency of the starting tasks of the workflow. Parameters ---------- ...
5,307,899