content
stringlengths
22
815k
id
int64
0
4.91M
def generation(this, genct, thisgen, lastgen): """ Prints a notice that a generation is done. """ print >> this.out, 'Generation {0} complete.'.format(genct)
5,340,400
def extract_zip(filepath): """ Function purpose: unzip file (always inside a new folder) filepath: filepath to zipfile """ abs_path = os.path.abspath(filepath) root_folder = os.path.split(abs_path)[0] zip_name = os.path.split(abs_path)[1][:-4] zip_folder_path = os.path.join(root_folder,...
5,340,401
def get_label_parts(label): """returns the parts of an absolute label as a list""" return label[2:].replace(":", "/").split("/")
5,340,402
def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Argparse Python script', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-c', '--cdhit', help='Output file from CD-HIT (clustered proteins)',...
5,340,403
def test_invalid_arguments(): """Test error messages raised by invalid arguments.""" n_ch, n_times = 2, 100 data = np.random.RandomState(0).randn(n_ch, n_times) info = create_info(n_ch, 100., 'eeg') raw = RawArray(data, info, first_samp=0) # negative floats PTP with pytest.raises(ValueError...
5,340,404
def assert_array_equal(x: xarray.coding.strings.StackedBytesArray, y: numpy.ndarray): """ usage.xarray: 2 """ ...
5,340,405
def alignImages(): """ how good the the align have to be """ MAX_FEATURES = 1000 GOOD_MATCH_PERCENT = 1 tempSearch = 'temp\\' typeSearch = '.png' nameSearch = 'align' imFilename = tempSearch + nameSearch + typeSearch im1 = cv2.imread(imFilename, cv2.IMREAD_COLOR) refFilename = "resources...
5,340,406
def combined_spID(*species_identifiers): """Return a single column unique species identifier Creates a unique species identifier based on one or more columns of a data frame that represent the unique species ID. Args: species_identifiers: A tuple containing one or pieces of a unique ...
5,340,407
def use_meter_tide_correction(MainProg): """ Function for using internal CG5 tide correction option. update the Campaign().corr_g list """ tide_correction_meter(MainProg.campaigndata)
5,340,408
def live( lang: str = typer.Argument( None, callback=lang_callback, autocompletion=complete_existing_lang ) ): """ Serve with livereload a docs site for a specific language. This only shows the actual translated files, not the placeholders created with build-all. Takes an optional LA...
5,340,409
def qr(A, prec=1e-10): """ computes a faster and economic qr decomposition similar to: http://www.iaa.ncku.edu.tw/~dychiang/lab/program/mohr3d/source/Jama%5CQRDecomposition.html """ m = len(A) if m <= 0: return [], A n = len(A[0]) Rdiag = [0] * n; QR = copy.deepcopy(A) fo...
5,340,410
def test_extract_zip(tmpdir): """Test Case""" with pytest.raises(TypeError, match=r'[E001]'): extract_zip(zip_file=123, unzip_dir=1254) temp_model_dir = tmpdir.mkdir("sub") zipped_file = str(temp_model_dir) + "/" + WORD_TOKENIZER_FILE_NAME download_from_url(WORD_TOKENIZER_WEIGHTS_URL, str(...
5,340,411
def on_task_requested(summary, deduped): """When a task is created.""" fields = _extract_job_fields(summary.tags) fields['deduped'] = deduped _jobs_requested.increment(fields=fields)
5,340,412
def split_range(r, n): """ Computes the indices of segments after splitting a range of r values into n segments. Parameters ---------- r : int Size of the range vector. n : int The number of splits. Returns ------- segments : list The list of lists of fi...
5,340,413
def is_connected_to_mongo(): """ Make sure user is connected to mongo; returns True if connected, False otherwise. Check below url to make sure you are looking for the right port. """ maxSevSelDelay = 1 # how long to spend looking for mongo try: # make sure this address is running ...
5,340,414
def make_xyY_boundary_data( color_space_name=cs.BT2020, white=cs.D65, y_num=1024, h_num=1024): """ Returns ------- ndarray small x and small y for each large Y and hue. the shape is (N, M, 2). N is a number of large Y. M is a number of Hue. "2" are small x...
5,340,415
def _fill_three_digit_hex_color_code(*, hex_color_code: str) -> str: """ Fill 3 digits hexadecimal color code until it becomes 6 digits. Parameters ---------- hex_color_code : str One digit hexadecimal color code (not including '#'). e.g., 'aaa', 'fff' Returns --...
5,340,416
def normalize(text: str, convert_digits=True) -> str: """ Summary: Arguments: text [type:string] Returns: normalized text [type:string] """ # replacing all spaces,hyphens,... with white space space_pattern = ( r"[\xad\ufeff\u200e\u200d\u200b\x7f\u202a\u2003\xa0\u2...
5,340,417
def register_name_for(entity): """ gets the admin page register name for given entity class. it raises an error if the given entity does not have an admin page. :param type[pyrin.database.model.base.BaseEntity] entity: the entity class of a...
5,340,418
def test_open_tigl(): """Test the function 'open_tigl'""" # Create TIGL handle for a valid TIXI handles tixi_handle = cpsf.open_tixi(CPACS_IN_PATH) tigl_handle = cpsf.open_tigl(tixi_handle) assert tigl_handle # Raise error for an invalid TIXI handles with pytest.raises(AttributeError): ...
5,340,419
def strip_function_tags(tree): """Removes all function tags from the tree.""" for subtree in tree.all_subtrees(): subtree.label_suffix = ''
5,340,420
def index(): """Show all the posts, most recent first.""" db = get_db() posts = db.execute( # "SELECT p.id, title, body, created, author_id, username" # " FROM post p" # " JOIN user u ON p.author_id = u.id" # " ORDER BY created DESC" "SELECT *, l.author_id as love_a...
5,340,421
def get_user_information(fbid, extra_fields=[]): """ Gets user basic information: first_name, last_name, gender, profile_pic, locale, timezone :usage: >>> # Set the user fbid you want the information >>> fbid = "<user fbid>" >>> # Call the function passing the fbid of user. ...
5,340,422
def parseTeam(teamString): """Parse strings for data from official Pokemon Showdown format. Keyword arguemnts:\n teamString -- a team string, copied from pokepaste or pokemon showdown """ pokemonList = teamString.split('\n\n') teamList = [] #print(pokemonList) for pokemon in pokemonLis...
5,340,423
def url_scheme(url, path): """Treat local URLs as 'file://'.""" if not urlparse(url).scheme: url = "file://" + os.path.join(path, url) return url
5,340,424
def mix_style(style_codes, content_codes, num_layers=1, mix_layers=None, is_style_layerwise=True, is_content_layerwise=True): """Mixes styles from style codes to those of content codes. Each style code or content code consists of `num_layers` co...
5,340,425
def genKinship(args): """ %prog genKinship genotype.mean Calculate kinship matrix file """ p = OptionParser(genKinship.__doc__) p.add_option('--type', default='1', choices=('1', '2'), help='specify the way to calculate the relateness, 1: centered; 2: standardized') p.set_sl...
5,340,426
def train_many_models(extractor, param_grid, data_dir, output_dir=None, **kwargs): """ Train many extractor models, then for the best-scoring model, write train/test block-level classification performance as well as the model itself to disk in ``output_dir``. Args: ext...
5,340,427
def broadcast(connect_queue, disconnect_queue, event_queue): """ Broadcast enqueued events to the connected websockets. :param connect_queue: A ``Queue`` instance for new connections. :param disconnect_queue: A ``Queue`` instance for disconnected websockets. :param event_queue: ...
5,340,428
def cleanup_tmps(**kwargs): """Remove the temporal directory.""" tmpdir = os.getcwd() os.chdir('/') rmtree(tmpdir)
5,340,429
def test_new_justified_is_later_than_store_justified(spec, state): """ J: Justified F: Finalized fork_1_state (forked from genesis): epoch [0] <- [1] <- [2] <- [3] <- [4] F J fork_2_state (forked from fork_1_state's epoch 2): epoch ...
5,340,430
def analyze_iw(aoi, doi, dictionary, size, aoiId): """ Function that pre-processes sentinel-2 imagery and runs the LCC change detection algorithm Parameters: aoi(ee.Feature): area of interest with property 'landcover' doi(ee.Date): date of interest dictionary (ee.Dictionary): ap...
5,340,431
def _build_client_update(model: model_lib.Model, use_experimental_simulation_loop: bool = False): """Creates client update logic for FedSGD. Args: model: A `tff.learning.Model` used to compute gradients. use_experimental_simulation_loop: Controls the reduce loop function for ...
5,340,432
def test_capped_setup(hass, aioclient_mock): """Test the default setup.""" config = {'platform': 'startca', 'api_key': 'NOTAKEY', 'total_bandwidth': 400, 'monitored_variables': [ 'usage', 'usage_gb', 'limit', ...
5,340,433
def ipv4_addr_check(): """Prompt user for IPv4 address, then validate. Re-prompt if invalid.""" while True: try: return ipaddress.IPv4Address(input('Enter valid IPv4 address: ')) except ValueError: print('Bad value, try again.') raise
5,340,434
def test_account_reg_base_query(session, reg_num, reg_type, client_ref, registering, status, start_ts, end_ts): """Assert that account registration query base is as expected.""" params: AccountRegistrationParams = AccountRegistrationParams(account_id='PS12345', ...
5,340,435
def text(message): """Sent by a client when the user entered a new message. The message is sent to all people in the room.""" room = session.get('room') emit('message', {'msg': session.get('name') + ': ' + message['msg']}, room=room) if room in active_bots.keys(): b = active_bots[room] ...
5,340,436
def getPlugins(): """ List the plugins located in the plugins folder. """ plugins = [] pluginList = os.listdir(PluginFolder) for pluginName in pluginList: location = os.path.join(PluginFolder, pluginName) if not os.path.isdir(location) or not MainModule + ".py" in os.listdir(loc...
5,340,437
def energybalance_erg(ratio,crew,erg,w0=4.3801,dt=0.03,doplot=1,doprint=0,theconst=1.0): """ calculates one stroke with ratio as input, using force profile in time domain """ # w0 = initial flywheel angular velo # initialising output values dv = 100. vavg = 0.0 vend = 0.0 power = 0.0 #...
5,340,438
def _read_blockstream(file): """Read a block from a file.""" while True: size = file.read(1)[0] if size == 0: break for _ in range(size): yield file.read(1)[0]
5,340,439
def get_gpu_count(): """get avaliable gpu count Returns: gpu_count: int """ gpu_count = 0 env_cuda_devices = os.environ.get('CUDA_VISIBLE_DEVICES', None) if env_cuda_devices is not None: assert isinstance(env_cuda_devices, str) try: if not env_cuda_devices:...
5,340,440
def get_EXP3_policy(Q, eta, G_previous): """ Obtain EXP-3 policy based on a given Q-function. Also, return updated values of G, to be used in future calls to this function. Inputs: 1) Q: a num_states x num_actions matrix, in which Q[s][a] specifies the Q-function in state s...
5,340,441
def table_content(db, table): """ return a 2 dimentioanl array cont-aining all table values ======================================================== >>> table_content("sys", "host_ip") [[1, 2, 3], [2, 3, 4], [3, 4, 5]] ======================================================== """ ...
5,340,442
def process_sort_params(sort_keys, sort_dirs, default_keys=None, default_dir='asc'): """Process the sort parameters to include default keys. Creates a list of sort keys and a list of sort directions. Adds the default keys to the end of the list if they are not already included. ...
5,340,443
def namify(idx): """ Helper function that pads a given file number and return it as per the dataset image name format. """ len_data = 6 #Ilsvr images are in the form of 000000.JPEG len_ = len(str(idx)) need = len_data - len_ assert len_data >= len_, "Error! Image idx being fetched is incorr...
5,340,444
def subreddit_count(): """ Get number of redditors, percentage of active redditors and growth in new redditors """ print("Getting Subreddit Stats now ...") for key, subreddit_names in {**interested_stocks_subreddits, **interested_crypto_subreddits}.items(): for subreddit_name in subreddit_na...
5,340,445
def delete_meeting(request, club_name, meeting_id): """Meeting is deleted by the host""" meeting = Meeting.objects.get(id=meeting_id) MeetingAttendance.objects.filter(user=request.user, meeting=meeting).delete() meeting.delete() return redirect('meeting_list', club_name)
5,340,446
def log_dir(request): """Retrieve user-provided logging directory on the command line.""" yield request.config.getoption("--log-dir")
5,340,447
def get_best_gain(mapping, candidate_mappings, weight_dict, instance_len, cur_match_num, lol1=None): """ Hill-climbing method to return the best gain swap/move can get Arguments: mapping: current node mapping candidate_mappings: the candidates mapping list weight_dict: the weight dictionary ...
5,340,448
def best_predictor(user, restaurants, feature_fns): """Find the feature within FEATURE_FNS that gives the highest R^2 value for predicting ratings by the user; return a predictor using that feature. Arguments: user -- A user restaurants -- A dictionary from restaurant names to restaurants featu...
5,340,449
def mock_environ(): """Mock for `os.environ.copy`""" return {"SOME_ENV_VAR": "42"}
5,340,450
def get_bedtools_coverage_cmd(bam_filename, gff_filename, output_filename, require_paired=False): """ Get bedtools command for getting the number of reads from the BAM filename that are strictly contained within each interval of the GFF. ""...
5,340,451
def test_encode_datetime(): """ encode_datetime() should return a ECMA-262 compliant datetime string. """ val = datetime.datetime(2006, 11, 21, 16, 30) assert encode_datetime(val) == '2006-11-21T16:30:00'
5,340,452
def get_notes_mapping_dict(notes_list: List) -> Tuple[Dict, np.array]: """ Function get list of midi notes and returns mapping for each note :param notes_list: :return: """ assert len(notes_list) > 0, 'Empty notes list !!' full_list = sorted(set(notes_list)) notes2idx = {note_e: i for ...
5,340,453
def p_y_given_x(X, mean_x, variance_x): """ Calculates the probablity of class value being y, given label is x. PARAMETERS ========== X: list Input of unknown class values given by user. mean_x: ndarray(dtype=int,ndim=1,axis=1) Mean for given label. variance_x...
5,340,454
def run_train(cfg, wandb): """Train function starts here Args: cfg (obj `DictConfig`): This is the config from hydra. """ data_directory = cfg.data.data_directory train_batch_size = cfg.data.train_batch_size max_seq_len = cfg.task.max_seq_len # Maximum length per sequence max_pred...
5,340,455
def test_cross_validation_manual_vs_scikit(estimator, build_dataset, with_preprocessor): """Tests that if we make a manual cross-validation, the result will be the same as scikit-learn's cross-validation (some code for generating the folds is taken from scikit-learn). ...
5,340,456
def wrf_ll_to_ij(lon, lat, map_proj, truelat1=-999.,truelat2=-999.,stand_lon=999., \ ref_lat=-999,ref_lon=-999,pole_lat=90,pole_lon=0,knowni=-999,\ knownj=-999,dx=-999, dy=-999, latinc=-999., loninc=-999): """ Converts lon/lat values to i/j index values. lon,lat - lat,lon values to ...
5,340,457
def create_specimen_resource(specimen_identifier: List[dict], patient_reference: dict, specimen_type: str, received_datetime: str = None, collection_datetime: str = None, note...
5,340,458
def get_attribute_slots( tracker: "Tracker", object_attributes: List[Text] ) -> List[Dict[Text, Text]]: """ Copied from rasa_sdk.knowledge_base.utils and overridden as we also need to return the entity role for range queries. If the user mentioned one or multiple attributes of the provided obj...
5,340,459
def pearson_correlation(self, preferences): """ Returns the Pearson Correlation of two user_s, A and B by performing the PPMC calculation on the scatter plot of (a, b) ratings on the shared set of critiqued titles. """ # Store the length to save traversals of the len computation. # If they ...
5,340,460
def update_stakeholder(id: int, name: str = None, company: str = None, role: str = None, attitude: str = None, archived: bool = None) -> Stakeholder or None: """ Provide a POST API endpoint for updating a specific stakeholder. :param id: ID of the stakeholder. :param name: Name o...
5,340,461
def register(): """Sign up user.""" if current_user.is_authenticated: return redirect(url_for("homepage")) form = RegistrationForm() if form.validate_on_submit(): user = User( username=form.username.data, name=form.name.data, email=form.email.data, ...
5,340,462
def _collect_all_tags(nb=None): """ a fancy generated note showing #tag per [[]] (and [[]] per #tag) -> nb/all tags.md """ ns = [] ns.append(', '.join([t.tag for t in nb.tags])) ns.append('\n--- ') for t in nb.tags: t_w = f'{t} - ' for n in nb.get_tagged(t): if not n.name == 'all tags': t_w += f...
5,340,463
def txt_as_matrix(buff, border): """\ Returns the text QR code as list of [0,1] lists. :param io.StringIO buff: Buffer to read the matrix from. """ res = [] code = buff.getvalue().splitlines() len_without_border = len(code) - border for l in islice(code, border, len_without_border): ...
5,340,464
def create_logismosb_node(name="LOGISMOSB"): """ This function... :param name: :return: """ node = Node(LOGISMOSB(), name=name) config = read_machine_learning_config() return set_inputs(node, config)
5,340,465
def segfault(): """ (gdb) r <<< $(python2 -c "import pwn;print(pwn.cyclic(128, n=8))") ... Can you ROP your way out of this? Program received signal SIGSEGV, Segmentation fault. 0x0000000000400b6e in vuln () (gdb) info stack #0 0x0000000000400b6e in vuln () #1 0x6161616161616164 i...
5,340,466
def test_get_source(): """Tests if source of objects is gotten properly.""" assert source_utils.get_source(pytest.Cache)
5,340,467
def calc_tract_accessibility(tracts, pois, G, weight='length', func=acc_cumulative_gaussian,k=5, random_seed=None, func_kws={}, pois_weight_column=None,iter_cap=1_000): """ Calculate accessibility by census tract using given...
5,340,468
def _exp_func(x, a, b, c): """Exponential function of a single variable, x. Parameters ---------- x : float or numpy.ndarray Input data. a : float First parameter. b : float Second parameter. c : float Third parameter. Returns ------- flo...
5,340,469
def ilevenshtein(seq1, seqs, max_dist=-1): """Compute the Levenshtein distance between the sequence `seq1` and the series of sequences `seqs`. `seq1`: the reference sequence `seqs`: a series of sequences (can be a generator) `max_dist`: if provided and > 0, only the sequences which distance from the referen...
5,340,470
def save_ages(history,outdir,index=0): """saves all cell ages for each tissue in history""" if not os.path.exists(outdir): # if the folder doesn't exist create it os.makedirs(outdir) filename = "%s/ages_%03d"%(outdir,index) wfile = open(filename,"w") for tissue in history: for age i...
5,340,471
def seek_inactive(x, start, length, direction=-1, abstol=0): """ Seek inactive region to the left of start Example ------- >>> # _______ | >>> seek_inactive([3, 2, 1, 1, 1, 2, 3, 4, 2], start=7, length=3) (1, slice(2, 4)) When no sufficiently long sequence is fou...
5,340,472
def test_Coding_inverted(): """Reverse oriented coding transcript.""" crossmap = Coding(_exons, _cds, True) # Boundary between 5' and CDS. invariant( crossmap.coordinate_to_coding, 43, crossmap.coding_to_coordinate, (-1, 0, -1, 0)) invariant( crossmap.coordinate_to_coding, 4...
5,340,473
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up the Firmata sensors.""" new_entities = [] board = hass.data[DOMAIN][config_entry.entry_id] for sensor in board.sensors: pin = sensor[CONF_PIN] pin_mode = sensor[CONF_...
5,340,474
def export(est, export_dir, input_image_size=None): """Export graph to SavedModel and TensorFlow Lite. Args: est: estimator instance. export_dir: string, exporting directory. input_image_size: int, input image size. Raises: ValueError: the export directory path is not specified. """ if not e...
5,340,475
def word_cross_product_phi(t1, t2): """Basis for cross-product features. This tends to produce pretty dense representations. Parameters ---------- t1, t2 : `nltk.tree.Tree` As given by `str2tree`. Returns ------- defaultdict Maps each (w1, w2) in the cross-...
5,340,476
def cube_filter_highpass(array, mode='laplacian', verbose=True, **kwargs): """ Apply ``frame_filter_highpass`` to the frames of a 3d or 4d cube. Parameters ---------- array : numpy ndarray Input cube, 3d or 4d. mode : str, optional ``mode`` parameter to the ``frame_filter_highpa...
5,340,477
def train( mat_dir, output_dir, ckpt_dir, blm_idx, lr, weight_decay, device, epoch, ): """ Train refinement stage Args: mat_dir (str): mat file directories output_dir (str): Output dir ckpt_dir (str): Checkpoint directory for trained models blm_idx (int): Index for targeted bi...
5,340,478
def translate_text(text: str, url: str, model_id) -> TranslatedObject: """Translates a text with the url of a translation server. The url is the url that comes up when you start the translation model""" assert type(text) == str, "Text has to be of type string" assert type(url) == str, "Url has to be of ...
5,340,479
def quantized_avg_pool_run(shape, dtype1, shape_list, dtype2, ksize, strides, padding, data_format, quant_algo, scale_mode, scale_sqrt, attrs): """run function""" if not isinstance(shape_list, (list, tuple, type(None))): raise RuntimeError("shap...
5,340,480
def map_repositories(packages): """Map repositories from PES data to RHSM repository id""" repositories_mapping = _get_repositories_mapping() repo_without_mapping = set() for pkg, repo in packages.items(): if repo not in repositories_mapping: repo_without_mapping.add(pkg) ...
5,340,481
def dry(message, func, *args, **kw): """Wraps a function that performs a destructive operation, so that nothing will happen when a dry run is requested. Runs func with the given arguments and keyword arguments. If this is a dry run, print the message rather than running the function.""" if message ...
5,340,482
def move_cups(current: int, cups: CircularLinkedList) -> int: # return the new current cup """ 1. The crab picks up the three cups that are immediately clockwise of the current cup. They are removed from the circle; cup spacing is adjusted as necessary to maintain the circle. 2. The crab selec...
5,340,483
def hire(name, address, salary, manager, is_active, Session=Session): """Add an employee to the bank.""" # get manager_id if manager: firstname, lastname = split_name(manager) with Session() as session: stmt = select(Employee).where(and_( Employee.firstname == fi...
5,340,484
def get_colormap(n=18, randomize=True): """ "Get expanded colormap""" n_colors = np.ceil(n / 6) + 1 cols = [] for col in COLORS: pal = sns.light_palette(col, n_colors=n_colors) for rgb in pal[1:]: cols.append(rgb) if randomize: shuffle(cols) # shuffle to break g...
5,340,485
def partition2(n): """ Coin partitions. Let partition(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so partition(5)=7. """ # dynamic programming table, table cell (i,j), parition size =...
5,340,486
def all_gather_batch(tensors): """ Performs all_gather operation on the provided tensors. """ # Queue the gathered tensors world_size = get_world_size() # There is no need for reduction in the single-proc case if world_size == 1: return tensors tensor_list = [] output_tensor ...
5,340,487
def get_duration_and_elevation(table): """"Return an array of duration and elevation gain from an html table""" try: hiking_duration = str(table.contents[0].text.strip()) #av.note: want this to be numeric except: hiking_duration = "" try: elevation_gain_ft = str( ta...
5,340,488
def display_nft_of_the_day(export: str) -> None: """Shows NFT of the day "https://www.coingecko.com/en/nft" [Source: CoinGecko] NFT (Non-fungible Token) refers to digital assets with unique characteristics. Examples of NFT include crypto artwork, collectibles, game items, financial products, and more. ...
5,340,489
def show_comparison(model, X_test, y_test, A_test, protected_features, prostprocess_preds): """ Returns Dashboard to show comparison of models based on the trade off of the disparity and accuracy """ FairlearnDashboard(sensitive_features=A_test, sensitive_feature_names=protected_features, ...
5,340,490
def my_edge(bw, threshold): """ 2018.11.26 检测图像边缘 返回检测到的边缘二值图像 阈值用于消去检测到的噪声 时间复杂度: Args: bw: a grey-scale image with 8-bit depth threshold: a decimal between 0 and 1 Returns: bw_edge_binary: 二值化的边缘图像 Raises: """ m, n = bw.shape bw0 = bw.astype(...
5,340,491
def csc_matvec(csc, x): """ Matrix vector multiplication using csc format """ if not sparse.isspmatrix_csc(csc): raise Exception("Matrix must be in csc format") nrow, ncol = csc.shape nnz = csc.data.shape[0] if x.size != ncol: print(x.size, ncol) raise Value...
5,340,492
def cmd_IMC2chan(command): """ @imc2chan Usage: @imc2chan <IMCServer> : <IMCchannel> <channel> Links an IMC channel to an existing evennia channel. You can link as many existing evennia channels as you like to the IMC channel this way. Running the command with an existing mapping...
5,340,493
async def delete_all_groups_for_user( user_id: int, query: CreateActionLogQuery, db: Session = Depends(get_db) ) -> Response: """ When a user removes his/her profile, make the user leave all groups. This API is run asynchronously, and returns a `201 Created` instead of `200 OK`. **Potential er...
5,340,494
def encode_base58(s) -> bytes: """ Encodes/converts any bytes to Base58 to transmit public key """ count = 0 for c in s: if c == 0: count += 1 else: break num = int.from_bytes(s, 'big') prefix = '1' * count result = '' while num > 0: ...
5,340,495
def get_config(): """Get config from env vars. Return: dict: Keys are: policy_url, dane_id, policy_file_dir, crypto_path, policy_name, ssids. """ config = {} for x in ["policy_url", "policy_file_dir", "dane_id", "crypto_path", "policy_name", "app_uid", "roles", ...
5,340,496
def unix_only(f): """Only execute on unix systems""" f.__test__ = os.name == "posix" return f
5,340,497
def save_chapter( body, source_lang, target_lang, title, public=False, user=None): """Save chapter to database Parameters: body (string): input text source_lang (string): source language target_lang (string): target language title (string): title of the chapter publi...
5,340,498
def frequency(g, k, h): """ Computes the frequency for a given wave number and water depth (linear dispersion relationship) :param k: the wave number :param g: -- gravitational acceleration :param h: -- the water depth :returns omega: -- wave frequency """ return np.sqrt(g * k * n...
5,340,499