content
stringlengths
22
815k
id
int64
0
4.91M
def decode_from_bioes(tags): """ Decode from a sequence of BIOES tags, assuming default tag is 'O'. Args: tags: a list of BIOES tags Returns: A list of dict with start_idx, end_idx, and type values. """ res = [] ent_idxs = [] cur_type = None def flush(): ...
67,400
def test_handle_rsvp_disambiguate( mock_send_reply, mock_user, make_handler_params, make_time, ): """ Ensures that, when there are multiple lunches, the user can construct a query to disambiguate between them. """ params = make_handler_params("rsvp tjs 12:30") plan1 = Plan("tjs", make_time(...
67,401
def getMaxVoltCurr(ser): """Get the maximum voltage and current from the supply. The response is an array: [0] = voltage, [1] = current""" resp = spdQuery(ser, "GMAX\r") print(resp) return [int(resp[0][0:3])/10., int(resp[0][3:5])/10.]
67,402
def do_disk_change_owner(client, args): """ Show details of a virtual disk """ kwargs = {} kwargs['tenant'] = args.tenant kwargs['user'] = args.user disk = client.disks.perform_action(args.id, 'change-owner', **kwargs) utils.print_dict(disk)
67,403
def with_data(request, new_package): """Builds a python package which includes data files.""" new_module, pkg_root = new_package data_dir = os.path.join(pkg_root, "data") os.mkdir(data_dir) write_py(data_dir, "data_1", data=True) with open(os.path.join(new_module, META_NAME), "w") as openmeta...
67,404
def datetime_x_days_ago_at_y_oclock( tz_aware_original_time: datetime, x: int, y: Union[int, float], z: str ) -> datetime: """Returns the datetime x days ago a y o'clock as determined from the perspective of timezone z.""" if isinstance(y, float): micros = int(y * 60 * 60 * 10 ** 6) s, micro...
67,405
def set_rate_limit(new_interval=1.0, new_requests=1): """Sets the rate limiting behavior of the module. Must be invoked before the first Web service call. Specify the number of requests (`new_requests`) that may be made per given interval (`new_interval`). """ global limit_interval global limit_requests limit_...
67,406
def timedelta2str(time_delta: timedelta) -> str: """Convert a timedelta object to its DICOM string counterpart. Parameters ---------- time_delta : timedelta The timedelta object to convert to string. Returns ------- str The timdelta objected represented as a DICOM time stri...
67,407
def getServiceForQS(query_str): """URI ends is followed by HTTP version (space-delimited) """ query_params = parse_qs(query_str) if ('s' in query_params): return query_params['s'][-1] eprint('HTTP request captured, but no service in URI. attributing data to _unspecified.') return '_unspeci...
67,408
def compress_and_resize_image(files: List[str], max_w=PIC_MAX_WIDTH, quality=PIC_QUALITY): """ 压缩图片 """ for input_path in files: im = Image.open(input_path) w,h = im.size out = None if w > max_w: max_h = int(h*max_w/w) out = im.resize((max_w,max_h...
67,409
def lazy_property(func: Callable) -> Callable: """ Decorator that makes a property lazy-evaluated. Inspired by: https://stevenloria.com/lazy-properties. Arguments: func: The function to be decorated as a lazy @property. Returns: Callable: The decorated function. """ attr_nam...
67,410
def test_threebot_phonebook(): """ kosmos 'j.servers.threebot.test(name="threebot_phonebook")' :return: """ # add an actor cl = j.servers.threebot.client j.me.configure(name="test", ask=False, reset=True) nacl_test = j.myidentities.get(name="test").encryptor # nacl_test = j.data.n...
67,411
def cancel_order(order_id): """ :param order_id: :return: """ params = {} url = "/v1/order/orders/{0}/submitcancel".format(order_id) return api_key_post(params, url)
67,412
def create(): """Create a new post for the current user.""" if request.method == "POST": group = request.form["group"] name = request.form["name"] rating = request.form["rating"] trigger = request.form["trigger"] error = None if not name: error = "Nam...
67,413
def get_ssl_cipher_suite(load_balancer_id: Optional[str] = None, name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSslCipherSuiteResult: """ This data source provides details about a specific Ssl Cipher Suite resource in Ora...
67,414
def search(): """ Поиск в базе данных """ global current_db if current_db_name is None: print('Сначала вы должны открыть базу данных.') else: while True: k = input('Введите название столбца, по которому вы хотите\n\ отфильтровать записи(1)фамилия; 2)год; 3)фамилия и г...
67,415
def plot_cospectra(cosp, freqs, ylabels=None, title='Cospectra'): """Plot cospectral matrices Parameters ---------- cosp : ndarray, shape (n_freqs, n_channels, n_channels) ndarray of cospectra. freqs : ndarray, shape (n_freqs,) The frequencies associated to cospectra. Returns ...
67,416
def get_timestamps(etree_xml): """Parse SAML assertion validity timestamps Timestamps are parsed from Conditions element and converted to Unix timestamps. :param etree_xml: etree element object :return: NotBefore, NotOnOrAfter """ logger = logging.getLogger(__pam_module_name__) time_a...
67,417
def update_account(admin_id, root, service_name, data): """Method to update the account for given storage service. Args: admin_id (str): Root privileges flag. root (str): Root privileges activation flag. service_name (str): The...
67,418
def _invoke_on_executor_thread(func, thread_name, block=True): """ Return wrapper to run the function on a given thread. If block==False, the call returns immediately without waiting for the decorated function to complete. If block==True, the call waits for the decorated function to complete before ret...
67,419
def Distance(distance='euclidean', **kwargs): """Construct a factory function that produces Distance nodes. Parameters ---------- distance : str, callable Specifies the distance function to use (See elfi.Distance). **kwargs Any additional arguments to elfi.Distance. Returns ---...
67,420
def generate_body(du_dept_dict): """Return HTML that will be used for the body content of the box report BlogPage""" body = '<ul>' for item in du_dept_dict.items(): body += '<li>{}: {} GB</li>'.format(item[0], int(item[1]) / 1000000) # Convert to GB body += '</ul>' return body
67,421
def file_handler_test_file() -> FileHandler: """Fixture returns FileHandler instance. FileHandler is constructed from test xlsx file in input_for_tests directory. Returns: :obj:`FileHandler`: Instantiated with actual Excel doc. """ file_handler_test_file = FileHandler( "input_f...
67,422
def load_dygraph(model_path, keep_name_table=False): """ To load python2 saved models in python3. """ try: para_dict, opti_dict = fluid.load_dygraph(model_path, keep_name_table) return para_dict, opti_dict except UnicodeDecodeError: warnings.warn( "An UnicodeDecod...
67,423
def timeit_grid( stmt_list, setup='', iterations=10000, input_sizes=None, verbose=True, show=False ): """ Timeit: >>> import utool as ut >>> setup = ut.codeblock( >>> ''' >>> import utool as ut >>> from six.moves import range, zip >>> import ti...
67,424
def get_profiles() -> dict: """Returns the profiles of all players. Returns ------- dict profiles of the players """ with OpenJson(PLAYERS_DATA_PATH + "profiles.json") as profiles_file: profiles = profiles_file.load() return profiles
67,425
def calculate_check_digit(data): """Calculate MRZ check digits for data. :data data: Data to calculate the check digit of :returns: check digit """ values = { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "<": 0, "A": 10, "B": 11, "C": 12, "...
67,426
def flatten(root): """Flatten a hierarchical YAML dictionary into one with composite keys. Args: root: [dict] A hierarchical dictionary. Returns: Equivalent dictionary with '.'-delimited keys. """ result = {} __flatten_into(root, '', result) return result
67,427
def lookup(cubeWithData, cubeWithMap, sharedIndex): """ Returns the value of cubeWithData indexed by the index of cubeWithMap. cubeWithData must be indexed by sharedIndex and cubeWithData values must correspond to elements of sharedIndex. For example: Let's say you have a cube with an estimated inflati...
67,428
def write_list_tsv(out, collection): """ Write a list separated by tabs, with new line at the end """ for i, value in enumerate(collection): if i < len(collection) - 1: out.write(str(value) + '\t') else: out.write(str(value) + '\n')
67,429
def utility(board): """ Returns 1 if X has won the game, -1 if O has won, 0 otherwise. """ # if someone has won the game, utility will be 1 or -1 according to who won # X wins --> utility = 1 # O wins --> utility = -1 if is_over(board): if winner(board) == X: return 1 ...
67,430
def notimplemented(f): """Takes a function f with a docstring and replaces it with a function which raises NotImplementedError(f.__doc__). Useful to avoid having to retype docstrings on methods designed to be overridden elsewhere.""" def wrapper(self,*args,**kws): raise NotImplementedErro...
67,431
def make_become_cmd(cmd, user, shell, method, flags=None, exe=None): """ helper function for connection plugins to create privilege escalation commands """ randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32)) success_key = 'BECOME-SUCCESS-%s' % randbits prompt = None ...
67,432
async def async_setup_platform( hass: HomeAssistantType, config: ConfigType, async_add_entities: Callable, discovery_info: Optional[DiscoveryInfoType] = None, ) -> bool: """Add Mug Sensor Entity to HASS.""" from .services import set_led_colour, set_target_temp, set_mug_name _LOGGER.debug("S...
67,433
def test_transfer_learning(tmpdir): """Transfer learning smoke test. Saves a dummy AIRL test reward, then loads it for transfer learning. """ tmpdir = pathlib.Path(tmpdir) log_dir_train = tmpdir / "train" run = train_adversarial.train_adversarial_ex.run( named_configs=["cartpole", "airl...
67,434
def _get_configuration(project_dir, args): """ Get the final configuration to use. This merges the defaults, file configuration if present, and command line arguments, in that order of priority. """ # Start with the default configuration config = _default_configuration() # Update with...
67,435
def readFileBytes(path) -> bytes: """ 读取文件字节数据 :param path: 文件路径 :return: 字节数组 """ with openReadBytesFile(path) as f: return f.read()
67,436
def check_if_list_and_matches_length( param: "object", expected_length: int, name: str = "parameter" ) -> list: """ Checks, if the passed variable is a list. Otherwise creates a list of the variable of length expected_length. Then checks if the length of the list is the expected length. Arg...
67,437
def evaluatePortfolioRet(Rev_seq,t=12): """ @param Rev_seq: @param t:天数 默认12(月) 252 日 @return: """ ret_mean=e**(Rev_seq.apply(lambda x:np.log(x+1)).mean()*t)-1 ret_sharpe=Rev_seq.mean()*t/Rev_seq.std()/t**0.5 ret_winrate=Rev_seq[Rev_seq>0].count()/Rev_seq.count() ret_maxloss...
67,438
def subs(exp, *s): """ Substitute the given subexpressions in the expression. """ if isinstance(exp, Expression): return exp.subs(*s) return exp
67,439
def fghost(cli, nick, chan, rest): """Voices you, allowing you to haunt the remaining players after your death.""" cli.mode(botconfig.CHANNEL, '+v', nick)
67,440
def guess_encoding(fname): """ Guesses the encoding of a file. fname - the name of the file whose encoding to guess. Returns the guessed encoding of the file (string). """ with open(fname, "rb") as file: result = chardet.detect(file.read()) return result["encoding"]
67,441
def buffer_filtering(buffer): """ Check whether "buffer" should be filtered. """ local = weechat.buffer_get_string(buffer, "localvar_%s" % SCRIPT_LOCALVAR) return {"": None, "0": False, "1": True}[local]
67,442
def parameter_count(funcsig): """Get the number of positional-or-keyword or position-only parameters in a function signature. Parameters ---------- funcsig : inspect.Signature A UDF signature Returns ------- int The number of parameters """ return sum( p...
67,443
def sum_of_squares(v: Vector) -> float: """Uses dot_product function""" return dot_product(v, v)
67,444
def createRuleHeatmap(rules): """ create a Heatmap to represent rules :param rules: rules given by apriori rules algorithm """ # we create a list to recover the rules data # k-th rule say that 'list_rules[k][1] is implied by list_rules[k][0] with a confidence of list_rules[k][2] list_...
67,445
def get_channel_index(image, label): """ Get the channel index of a specific channel :param image: The image :param label: The channel name :return: The channel index (None if not found) """ labels = image.getChannelLabels() if label in labels: idx = labels.index(label) ...
67,446
def plot_freq_effects(): """ Plot the effect of frequency """ phx1 = pd.read_csv("/home/amaity/Dropbox/Datasets-Analyses/ptss-poc/lace_case9/dataset_ph1.csv") phx2 = pd.read_csv("/home/amaity/Dropbox/Datasets-Analyses/ptss-poc/lace_case10/dataset_ph1.csv") t1 = np.array(phx1['time'].values) t2 =...
67,447
def search_ignore_case(s, *keywords): """Convenience function to search a string for keywords. Case insensitive version. """ acora = AcoraBuilder(keywords).build(ignore_case=True) return acora.findall(s)
67,448
def make_rgba(data_in: ArrayLike) -> ArrayLike: """Convert any array to an RGBA array. RGBA arrays have 3 dimensions where the last represents the channels. If an Alpha channel needs to be added it will be made completely opaque. Returns ------- 3D RGBA unsigned 8-bit array """ max_va...
67,449
def test_azure_event_hub_consumer(sdc_builder, sdc_executor, azure, use_websockets): """Test for Azure IoT/Event Hub consumer origin stage. We do so by publishing data to a test event hub Azure client and having a pipeline which reads that data using Azure IoT/Event Hub consumer origin stage. Data is then asser...
67,450
def get_args(): """Command line argument processing.""" usage="apply_ar_tweet_oov_rules.py [options] [infile [outfile]]" help=""" Apply Arabic tweet preprocessing rules to Arabic OOVs in either the original Arabic text or buckwalter transliterated text. The script can also produce a rules output ...
67,451
def main(min_kmers, min_reads, slope, rank, longform_table, table_out): """Filter taxa according to the ratio of reads to kmers.""" long_taxa = pd.read_csv(longform_table) long_taxa.columns = ['uuid', 'taxa', 'taxid', 'rank'] + long_taxa.columns.tolist()[4:] long_taxa = long_taxa.query('rank == @rank') ...
67,452
def error(v1, v2): """Returns the relative error with respect to the first value. Positive error if program output is greater than AREMA table. Negative error if program output is less than AREMA table. """ e = (v2 - v1)/v1 return e
67,453
def read_meta(metafn=None): """ Read a [metadata] text file into a dictionary. Function modified from https://github.com/JessicaS11/python_geotif_fns/blob/master/Landsat_TOARefl.py """ metadata = {} # potential future improvement: strip quotation marks from strings, where applicable. Will then...
67,454
def ODE_step_euler(x, y, h, derivs): """ Advances the solution y(x) from x to x+h using the Euler method. derivs .... a python function f(x, (y1, y2, y3, ...)) returning a tuple (y1', y2', y3', ...) where y1' is the derivative of y1 at x. """ X = derivs(y,x) return vadd(y, smul(h, X))
67,455
def check_go(*args): """Check GO State. If all three panels are NOT a 'GO', ignitor state is set to 'Safe' mode. Arguments --------- args[0] : ucl --> UpperClass Instance Nested Functions ---------------- getGOState() ...
67,456
def max_abs_error_relative_to_mean_radius(standard_shape, test_shape): """ Compare test_shape to standard_shape, relative to mean radius of standard. Returned value is a percentage. standard_shape npy array test_shape npy array Must have the same shape. Either: one-dimensional (s...
67,457
def get_calendar(caldav_url): """ Get the calendar using credentials from `credentials.py`. """ url = caldav_url client = caldav.DAVClient(url) princ = caldav.Principal(client, url) return princ.calendars()[0]
67,458
def batch_get_heuristic_mask_fetchpush_(s, a): """ heuristic mask for disentangled fetch """ grip_poses = s[:, 0, :3] obj_poses = s[:, 1, 10:13] entangled = np.linalg.norm(grip_poses - obj_poses, axis=1, keepdims=True)[:, None] < 0.1 entangled_mask = np.ones((1, 3, 3)) disentangled_mask = np.array([[[1...
67,459
def is_hidden(tree: nx.DiGraph, node: Hashable, attr: str) -> bool: """Iterate on the node ancestors and determine if it is hidden along the chain""" if tree is not None and node in tree: if tree.nodes[node].get(attr, False): return True for ancestor in nx.ancestors(tree, node): ...
67,460
def index(document, filename, chapterReference): """ Extract index entries from the given document and store them for later use and insert named anchors so that the index can link back to those entries. Any node with a C{class} attribute set to C{index} is considered an index entry. @type docu...
67,461
def parse_both_2(image_results): """ parses the tags and repos from a image_results with the format: { 'image': [{ 'pluginImage': { 'ibmContainerRegistry': 'internalRepo/name' 'publicRegistry': 'repo/name' }, 'driverImage': { ...
67,462
def test_vm_resumecycle(vm_dir): """Test methods controlling the VM - up(), suspend(), resume().""" v = vagrant.Vagrant(vm_dir) v.up() assert v.RUNNING == v.status()[0].state v.suspend() assert v.SAVED == v.status()[0].state v.resume() assert v.RUNNING == v.status()[0].state
67,463
def decode_auth_token(token: str) -> Optional[LoginSessionDict]: """Decode an authorization token into a LoginSessionDict.""" decoded = None try: secret = get_secret_key() decoded = jwt.decode(token, secret) except InvalidSignatureError: return None except ExpiredSignatureE...
67,464
def splitexts(path, exts=None): """ Split each extension of a given file (.tar.gz, .tar, .pp, etc). """ exts = [] ext = os.path.splitext(path) while True: if len(ext[1]) < 1: break else: exts.append(ext[1]) ext = os.path.splitext(ext[0]) ex...
67,465
def ComputeEnabledAABB(kinbody): """ Returns the AABB of the enabled links of a KinBody. @param kinbody: an OpenRAVE KinBody @returns: AABB of the enabled links of the KinBody """ from numpy import NINF, PINF from openravepy import AABB min_corner = numpy.array([PINF] * 3) max_corn...
67,466
def find_last_version_pypi(package, delay): """Return the last version of a package """ url = 'https://pypi.org/project/{}/#history'.format(package) page = requests_get_handler(url) if page.status_code == 404: print('{} not found'.format(package)) return "" elements = pypi_parser...
67,467
def set_quantization_configs_to_node(node: BaseNode, quant_config: QuantizationConfig, fw_info: FrameworkInfo): """ Create and set quantization configurations to a node (for both weights and activation). Args: node: Node to s...
67,468
def make_field_value_change_in_struct_recursively(struct, field_name, new_field_value): """ This function makes recursive walk in the structure `struct` and for each dict if the dict has key `field_name`, the function sets its value to `new_field_value` (may be any python structure) """ logging....
67,469
def get_put_single_endpoint_schema(class_name, form_schema_model, response_schema): """ :param class_name: :param form_schema_model: :param response_schema: """ return { "tags": [class_name], "description": f"Create a {class_name}", "requestBody": { "descrip...
67,470
def get_bit(byte, bit_num): """ Return bit number bit_num from right in byte. @param int byte: a given byte @param int bit_num: a specific bit number within the byte @rtype: int >>> get_bit(0b00000101, 2) 1 >>> get_bit(0b00000101, 1) 0 """ return (byte & (1 << bit_n...
67,471
def dashboard(i): """ Input: { (host) - Internal web server host (port) - Internal web server port (wfe_host) - External web server host (wfe_port) - External web server port (extra_url) - extra URL } ...
67,472
def create_translation_field(model, field_name, lang): """ Translation field factory. Returns a ``TranslationField`` based on a fieldname and a language. The list of supported fields can be extended by defining a tuple of field names in the projects settings.py like this:: MODELTRANSLATION...
67,473
def ExtractPrompt(source, default): """Attempts to extract the prompt from the code cell. Args: source: The merged source string of the code cell. default: The default prompt string. Returns: The source with prompt removed. The first extracted prompt if prompt regexp matche...
67,474
def find_dominant_axis(vertices): """ measures which axis has least variance and returns 0, 1, or 2 (x, y, z) so the 3D coordinates can be reduced to 2D """ xArray = [x[0] for x in vertices] yArray = [x[1] for x in vertices] zArray = [x[2] for x in vertices] xVariance = max(xArray) -...
67,475
def test_outdated_local(tmpdir, local, remote): """Test with remote changes not pulled. :param tmpdir: pytest fixture. :param local: conftest fixture. :param remote: conftest fixture. """ # Commit to separate local repo and push to common remote. local_ahead = tmpdir.ensure_dir('local_ahead...
67,476
def read_file(file_path): """ Read the given file path and its metadata. Returns a LoaderResult. """ with open(file_path, 'r') as f: stats = fstat(f.fileno()) return LoaderResult( buffer=f.read(), successful=True, metadata=dict(size=stats.st_size, ...
67,477
def test_s22_list_select(s22_fixture): """tests list_values and get_values with multiple selections on the method and basis field""" client, ds = s22_fixture methods = {"b3lyp", "pbe"} bases = {"def2-svp", "def2-tzvp"} names = {f"{method}/{basis}" for (method, basis) in itertools.product(methods, b...
67,478
def abline(slope, intercept, color, axis=None): """Plot a line from slope and intercept""" if axis is None: axis = plt.gca() x_vals = np.array(axis.get_xlim()) y_vals = intercept + slope * x_vals axis.plot(x_vals, y_vals, '--', color=color)
67,479
def serving_proto_library( name, srcs = [], has_services = False, deps = [], visibility = None, testonly = 0, cc_grpc_version = None, cc_api_version = 2): """ Wrapper for proto library. Args: name: srcs: has_services: ...
67,480
def generate_local_graph(N=N, n_divisions=4, mean_degree=MEAN_DEGREE): """Generates a graph with a much higher clustering coefficient. Smaller n_divisions -> higher clustering. """ edges = genereate_local_edges(N, n_divisions, mean_degree) H = edges2graph(edges, N) # In Graph name, include the parameters....
67,481
def GlyphCollection(mode="sdf", *args, **kwargs): """ mode: string - "sdf" (speed: fast, size: small, output: decent) - "agg" (speed: fasteest, size: big output: perfect) """ if mode == "agg": return AggGlyphCollection(*args, **kwargs) return SDFGlyphCollection(*arg...
67,482
async def test_matching_url(): """Test we can match urls.""" mocker = AiohttpClientMocker() mocker.get("http://example.com") await mocker.match_request("get", "http://example.com/") mocker.clear_requests() with pytest.raises(AssertionError): await mocker.match_request("get", "http://ex...
67,483
def extract_dates_mp(raw_cert): """ Override SleekXMPP's TLS Certificte to handle all Valid TLS Date Formats - Date prior to 1/1/2050:'%y%m%d%H%M%SZ' - Date post after 1/1/2050: '%Y%m%d%H%M%SZ' """ slk_cert = sleekxmpp.xmlstream.cert if not slk_cert.HAVE_PYASN1: log.warning(...
67,484
def opt_pairwise(n_items, data, alpha=1e-6, method="Newton-CG", initial_params=None, max_iter=None, tol=1e-5): """Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameters given pairwise-comparison data (see :ref...
67,485
async def test_flow_one_bridge_discovered(hass, aioclient_mock): """Test config flow discovers one bridge.""" aioclient_mock.get(hue.API_NUPNP, json=[ {'internalipaddress': '1.2.3.4', 'id': 'bla'} ]) flow = hue.HueFlowHandler() flow.hass = hass result = await flow.async_step_init() ...
67,486
def Initialize(): """Initializes the authentication process for Radiant ML Hub. Examples -------- >>> import easystac.radiant as rd >>> rd.Initialize() """ credentials_path = Path(CREDENTIAL_FILE).expanduser() if credentials_path.is_file(): credential = json.load(open(credential...
67,487
def test_create_extendedReceive_message(): """Test create extendedReceive message.""" address1 = 0x01 address2 = 0x02 address3 = 0x03 target1 = 0x04 target2 = 0x05 target3 = 0x06 flags = 0x07 cmd1 = 0x08 cmd2 = 0x09 rawmessage = bytearray([0x02, 0x51, address1, address2, addr...
67,488
def autocrop(img): """ Remove zero-valued rectangles at the border of the image. Parameters ---------- img: ndarray Image to be cropped """ slices = ndimage.find_objects(img > 0)[0] return img[slices]
67,489
def authorize_payment(payment): """Activate client's payment authorization page from a PayPal Payment.""" for link in payment.links: if link.rel == "approval_url": # Convert to str to avoid Google App Engine Unicode issue approval_url = str(link.href) return app...
67,490
def import_sites_vcf(**kwargs) -> hl.Table: """Import site-level data from a VCF into a Hail Table.""" return hl.import_vcf(**kwargs).rows()
67,491
def roll_axes(viewer): """Change order of the visible axes, e.g. [0, 1, 2] -> [2, 0, 1].""" viewer.dims._roll()
67,492
def process_operator_filter(field, value): """ Process a mongo operador attached to a field like name__in, pay__gte Args: field (str): The field name value (str): The value """ params = field.split('__') if len(params) is not 2: return {} field, operator = params o...
67,493
def rref(mat, aug=0): """Performs Gauss-Jordan elimination to turn the matrix mat into RREF form in-place and returns a string showing the working in LaTeX""" row = 0 col = 0 n_rows = len(mat) n_cols = len(mat[0]) ans = "\\begin{align*}\n" while True: if(row >= n_rows): # ran out of ...
67,494
def _data_checks_pivot_longer( df, index, column_names, names_to, values_to, column_level, names_sep, names_pattern, sort_by_appearance, ignore_index, ): """ This function raises errors if the arguments have the wrong python type, or if an unneeded argument is provid...
67,495
def natsort_list(unsorted_list): """Basic function that organizes a list based on human (or natural) sorting methodology. Parameters ----------- unsorted_list : list List of strings. Returns ------- list Sorted list of string. """ sorted_list = natsorted...
67,496
def test_tuple(module, assert_dump_load): """Round trip a tuple. The tuple is converted to list only for dumps(), not during dump(). """ @module.dataclass class A: x: t.Tuple[int, bool] schema = desert.schema_class(A)() dumped = {"x": (1, False)} loaded = A(x=(1, False)) ...
67,497
def getCatalogFiles(fname): """Return the files in an XML file catalog""" print "Catalog content:" print commands.getoutput("cat %s"%fname) flist = [] xmldoc = minidom.parse(fname) fileList = xmldoc.getElementsByTagName("File") for thisfile in fileList: fdict = {} fdict['lfn'...
67,498
def cli(conn, file, sql): """ This little Python script runs SQL statements on databases from the command-line. You must pass in a valid connection string. The raw query overrides the file query. """ if conn is not None and (file is not None or sql is not None): if sql: ...
67,499