sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
797d730ea99ca2b4be2c0ffa8cca6efd3e8af4f5c0f053dad7408bdb012964f6
Python
520
17
#python calc_perplexity.py < infile > outfile # computes the perplexity of a grammar on a dataset # infile: line-delimited log-probs of observations from a test dataset # outfile: the perplexity computed from the observation probabilities in infile import math import sys norm = 0 xent = 0 for line in sys.stdin.readli...
d17aac0a396e5a0072c2547c8844ede135cf37e443ee85c5619c27834b379619
Python
520
18
from wordfreq import tokenize, word_frequency import pytest def test_tokens(): assert tokenize('감사합니다', 'ko') == ['감사', '합니다'] def test_combination(): gamsa_freq = word_frequency('감사', 'ko') habnida_freq = word_frequency('합니다', 'ko') assert word_frequency('감사감사', 'ko') == pytest.approx(gamsa_freq /...
d2a0ea17947cca4612f0202c2e06f7fc9b2be1743ba60710465b46c72a56f209
Python
520
27
from pandas.core._numba.kernels.mean_ import ( grouped_mean, sliding_mean, ) from pandas.core._numba.kernels.min_max_ import ( grouped_min_max, sliding_min_max, ) from pandas.core._numba.kernels.sum_ import ( grouped_sum, sliding_sum, ) from pandas.core._numba.kernels.var_ import ( grouped_v...
c83aa8c9059c5d5a2a06148fcf0dbd096c8ebbde506e134f05d1e80f879d5717
Python
521
10
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and relat...
b78d3962a50a38a8da056ce625abf0962fe318107d98e3f813f29074c7569fd9
Python
524
19
# Replaces leaves from a linetrees file with the string 'LEAF' import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts')) import tree def replaceLeaves(t): for x in t.ch: if len(x.ch) == 0: x.c = 'LEAF!' else: r...
7ad6dc74886e92cae6c7da865604ea45baa210ed35784292ead791330b720a6a
Python
526
22
class Controller(object): registered_callbacks = [] def __init__(self): self.registered_functions = [] def register(name): def reg_decorator(func): Controller.registered_callbacks.append((func, name)) return lambda *args: func(*args) return reg_decorator ...
54dd2aef1a352e8a138c6549001a844f36adeadf14331a8ea06b8fa82a301bf3
Python
528
21
import sys import pandas as pd if __name__ == "__main__": data = pd.read_csv(sys.stdin, sep=' ', skipinitialspace=True) evids = [] for i in data.index: subject = data["subject"][i] docid = data["docid"][i] time = int(data["time"][i]) fROI = data["fROI"][i] evid =...
b1faa018fdd5ad5f74de02e9321217a5d093cd7fd60e992995fbb3ea86f78f33
Python
528
23
import numpy import pandas import h5py f = h5py.File('data/Smartseq2_Multisample_human_single_2021-12-15T21-07-41.loom', 'r') cellIds = numpy.array(f['col_attrs']['CellID']) ensambleId = numpy.array(f['row_attrs']['ensembl_ids']) geneName = numpy.array(f['row_attrs']['gene_names']) countTable = numpy.array(f['layers'...
2fd84bea364615abac03a5686d6dafaca1947ed14b045e15012f89e419d5a220
Python
530
18
import os import argparse parser = argparse.ArgumentParser() parser.add_argument('--folder', type=str, default="./") args = parser.parse_args() import glob, os os.chdir(args.folder) for stl_fileName in glob.glob("*.stl"): conversion_command = "meshlabserver -i " + stl_fileName + " -o " + stl_fileName[:-3] + "o...
a9dd21e96c245e1f0b72e249b518b525eb4815d711a7aaf780a2cc424fbfa0c2
Python
530
25
import sys import tree def annotDepth(t,b='L',d=1): if len(t.ch)>0: t.c += '-b'+b+'-d'+str(d) if len(t.ch)==1: annotDepth(t.ch[0], b, d) if len(t.ch)==2: if b=='L': annotDepth(t.ch[0],'L',d) annotDepth(t.ch[1],'R',d) else: annotDepth(t.ch[...
a8f5afe1657db5c9bff2574e779d88f6b90408130d23fb980efbe63889aa0925
Python
534
17
"""Functionals, e.g. norms and loss functions.""" from mrpro.operators.functionals.L1Norm import L1Norm from mrpro.operators.functionals.L1NormViewAsReal import L1NormViewAsReal from mrpro.operators.functionals.L2NormSquared import L2NormSquared from mrpro.operators.functionals.MSE import MSE from mrpro.operators.func...
12c7457de2ef2d40006aef0571cde81e7617d1b34942f5d648ae5d94798ad891
Python
535
28
#! /usr/bin/python3 # -*- coding: utf-8 -*- # @FileName: template.py # @Author: Li Chengxin # @Time: 2023/6/30 22:26 REGIONS_TMP = { "shape_attributes": { "name": "polygon", "all_points_x": [], "all_points_y": [] }, "region_attributes": { ...
a7382feeefff85efe2503536591a2218f6f0c5527c7bacb18abfc40e0142ecd0
Python
535
23
import sys import pandas as pd groupnames = sys.argv[1:] df = pd.read_csv(sys.stdin, sep=' ') groups = df.groupby(groupnames) # Take means of numeric columns means = groups.mean() # Take first entries of all columns first = groups.first() nwords = groups.agg('count')['word'] mean_cols = set(means.columns) keep_col...
af5a7f7e1e5d26de0aeb42ee9b172a20091df8e1ea19262450c6108874adec82
Python
535
19
import pytest import pandas as pd import pandas._testing as tm class TestFreq: def test_freq_setter_deprecated(self): # GH#20678 idx = pd.period_range("2018Q1", periods=4, freq="Q") # no warning for getter with tm.assert_produces_warning(None): idx.freq # Per...
6f72433f00002dcfcdf5554105e3c1058e55f696aa3811fe1863a91e5949b16e
Python
536
26
# pyaging/utils/__init__.py from ._feature_ranges import get_feature_ranges, resolve_feature_ranges from ._utils import ( cite_clock, download, find_clock_by_doi, get_clock_metadata, load_clock_metadata, print_model_details, progress, show_all_clocks, ) __all__ = [ "cite_clock", ...
ab130376cc048f35ea8a40b336cc7127099fa6d4fdf7a8b28aa887c3388aa185
Python
538
20
import os from pathlib import Path PROJ_CODE = 'AG' BASE_DIR = Path(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))) PROJ_DIR = BASE_DIR / 'proj' MODEL_DIR = PROJ_DIR / 'model' CACHE_DIR = PROJ_DIR / 'cache' DATA_DIR = PROJ_DIR / 'data' FIG_DIR = PROJ_DIR / 'fig' SAVE_DIR = PROJ_DIR / 'save' OUTP...
0a76b45284b7c5c092bec600b2117e522c073f6c0162cf84a6b4bcaad354a8cd
Python
539
21
import dclab import matplotlib.pylab as plt # dataset ds = dclab.new_dataset("fluorescence/fluorescence.rtdc") fig = plt.figure(figsize=(7, 3)) ax1 = plt.subplot() ax1.plot([ds["time"][0], ds["time"][-1]], [ds["index"][0], ds["index"][-1]], label="constant slope", lw=3) ax1.plot(ds["time"]...
73d3a65e842b5dd6b8567fa7831f174f11efc06a78927723e2dece20dc0e7f56
Python
539
21
__all__ = ["batched"] from itertools import islice from typing import Iterable, Tuple, TypeVar T = TypeVar('T') def batched(iterable: Iterable[T], n: int) -> Iterable[Tuple[T, ...]]: "Batch data into tuples of length n. The last batch may be shorter." # batched('ABCDEFG', 3) --> ABC DEF G # itertools 3.1...
8a990b48c3b143829e068f9acfe4f3b7e663cc030b952e102726c8d92f47ca8c
Python
539
27
from __future__ import annotations from typing import TYPE_CHECKING import numba if TYPE_CHECKING: import numpy as np @numba.jit( numba.boolean(numba.int64[:]), nogil=True, parallel=False, ) def is_monotonic_increasing(bounds: np.ndarray) -> bool: """Check if int64 values are monotonically incr...
fa1d609e4ebe7012cc9425ebff2b02976ab43487ce12f7a0a769d4ffba4e77bb
Python
539
28
import sys from itertools import chain, combinations def powerset(iterable): xs = list(iterable) return chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1)) preds = sys.argv[1:] if len(preds) == 1: preds = preds[0].split('_') pset = powerset(preds) out = [] for s in pset: out_cur = [] ...
5f11e18a9fe49e86d0b9d87c998b42cce7c04fc53e528ffc3e9837f54730a9d7
Python
541
26
''' Contains utility functions ''' import shlex, subprocess #from subprocess import Popen import warnings warnings.filterwarnings("ignore") DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] def shlex_cmd(command, print_cmd=False): ''' A convinience function that submits a command using shlex and ...
9cb96083e9ebdfc8cbf415ee9c32cff69b75895b354066bff768edee4f74270e
Python
541
21
import numpy as np import pandas as pd class TestSeriesCount: def test_count(self, datetime_series): assert datetime_series.count() == len(datetime_series) datetime_series[::2] = np.nan assert datetime_series.count() == np.isfinite(datetime_series).sum() def test_count_categorical(...
e19547605a81b98139ce067cc608d849974a447061a71d94881006279d4b4814
Python
541
16
import sys for linenum,line in enumerate(sys.stdin): if linenum==0: measures = line.split() for i in range( 0, len(measures) ): ctr = 1 for j in range( i+1, len(measures) ): #sys.stderr.write( measures[i] + ' ?? ' + measures[j] + '\n' ) if me...
71ff9287637ab97d40505da2ce5f94375c5fcd895ba2b121008dfcf8308cde9f
Python
543
16
from typing import List, Tuple, Union import seaborn as sns import matplotlib as mpl Palette = Union[str, List[Union[str, Tuple[float, float, float]]], None] def get_colormap(palette: Palette) -> mpl.colors.Colormap: """Generate a matplotlib Colormap from a `Palette`""" if palette is None: return sn...
bc0da5ff8be172ebadb4a1fc31d1e344b54cdf18fe053d5f46b5a4928336e2b3
Python
543
20
"""Test the models package-level functions.""" from lightning_pose.models import check_if_semi_supervised def test_check_if_semisupervised(): flag = check_if_semi_supervised(losses_to_use=None) assert not flag flag = check_if_semi_supervised(losses_to_use=[]) assert not flag flag = check_if_sem...
f264e253a9678486d1369aafa3fa2e0d69f0c21b5ece9db5a1ae6c9b09148a86
Python
543
22
from flask import jsonify, g, current_app from flask_httpauth import HTTPTokenAuth from .models import AuthKeys auth = HTTPTokenAuth('siteGUID') @auth.verify_token def verify_token(auth_guid): g.auth_key = AuthKeys.query.filter_by(guid=auth_guid).first() if g.auth_key is None: return False retu...
1a4a4b0dcdb436b2d074209994d0aa9919c4e02d171c40c317012a0c015882bb
Python
545
17
def get_cgcnn_input(struct): """return the wren input string TODO update wren to use a more standard convention Args: struct (Structure): input structure to get inputs for Returns: cgcnn inputs as a lattice matrix and list of sites of the form [f"{el} @ {x,y,z}", ] """ elems =...
2efdb5a6a224aecdea27ae6522da1ae6cecaa071df4054119fbff8e76c8c66ac
Python
548
11
# Population Based Training (PBT) for rl_games. # Ported from the Isaac Lab rl_games integration (isaaclab_rl); original DexPBT # implementation from NVIDIA-Omniverse/IsaacGymEnvs (https://arxiv.org/abs/2305.12127). # Copyright (c) 2022-2026, The Isaac Lab Project Developers. # SPDX-License-Identifier: BSD-3-Clause fr...
99c6aafd1b61fd2d9f28c493f6f17aaa8cd489debb4b8a3aeaaca9186fa1f319
Python
548
18
import darts.functional as F from darts.api.metrics.average import MultitaskAveragingSupervisedMetric class MultitaskAccuracy(MultitaskAveragingSupervisedMetric): """ Multitask Classification accuracy """ def __init__(self, scope="train"): super().__init__("accuracy", scope=scope) def _value_fun...
a3b63eb344b9adbdf574352f02b093353cdf15c3cb3b0876f356bb69fbcee775
Python
548
12
"""Removed — use the litpose CLI instead.""" raise SystemExit( "scripts/predict_new_vids.py has been removed.\n" "Please use the command line interface instead:\n\n" " To predict on one or more video files:\n" " litpose predict <model_dir> <video_file1> <video_file2> ...\n\n" " To predict on a...
9b037cfba4f7641e8219acefa3f3ca9933c60afbcefa6e469954c9dbb095228f
Python
550
21
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from .losses import SSIMLoss from .utils import save_reconstructions from .coil_combine import rss, rss_complex from .fftc import fft2c_new a...
bb8803177d93819cb32158d284b64fd3f1f5cc283c571242f815dbab66216a02
Python
552
18
import io import pytest from rich.console import Console import pyaging.logger._live as live_module @pytest.fixture(autouse=True) def non_interactive_display_console(monkeypatch): """Keep the live display off by default so test behavior does not depend on whether pytest runs attached to a TTY (e.g. `pytest ...
e4b157f601ba0ee944bdc54949d00f8a057c94215db5d93c0a87f61be80c5453
Python
557
16
"""Time-series forecasting task — PyCaret 4.0. PyCaret 4.0 is OOP-only; the 3.x functional API was removed. The 3.x class name ``TSForecastingExperiment`` was renamed to the cleaner ``TimeSeriesExperiment`` in 4.0 to match the task's module name. from pycaret.time_series import TimeSeriesExperiment exp = Tim...
879a751810fc4f8901f27daa4566e7a29cb3d631501a69da62159efcaeab75c6
Python
559
25
import sys header = True ROI = sys.argv[1:] if 'AllROI' in ROI: ROI.pop(ROI.index('AllROI')) for i in range(len(ROI)): ROI[i] = 'bold' + ROI[i] ROI_cols = [] for line in sys.stdin: row = line.strip().split() if header: for h in row: if h in ROI: ROI_cols.append(row....
c05f2adc7c1703a5d75cb02de2d3470606f35ff5eb8a073f3eea310821ab6cb0
Python
560
27
""" Tests for behavior if an author does *not* implement EA methods. """ import numpy as np import pytest from pandas.core.arrays import ExtensionArray class MyEA(ExtensionArray): def __init__(self, values) -> None: self._values = values @pytest.fixture def data(): arr = np.arange(10) return M...
99b67ce70d566024c225e1dfe910a5dd6de2d93f134963b9f98c7bf52b2e73ae
Python
561
22
import re import sys ''' take stdin, sub any ==>.*<== lines with (U !ARTICLE). if none, add (U !ARTICLE) at top ''' lines = sys.stdin.readlines() for line in lines: if re.match(r'==>.*<==', line) is not None: delims_exist = True break delims_exist = False if delims_exist == True: for li...
a98173670339613c0df73c45399087be9f2eae494633fcffc7e2be992867ac68
Python
562
22
"""Test segmentation module.""" import numpy as np import pytest from gradec.segmentation import KMeansSegmentation, PCTSegmentation @pytest.mark.parametrize( "segmentation", [ (PCTSegmentation(10)), (KMeansSegmentation(10)), ], ) def test_segmentation_smoke(segmentation): """Smoke te...
b54df1b2ec3db26f387987c7ab5b006cf5e6652072103d64fbb530836840999c
Python
563
15
import sys, re, argparse, itertools argparser = argparse.ArgumentParser(''' Compares an input linetrees file to a GCG-reannotated "target" linetrees file, replacing all trees with newlines that failed to reannotated in the target. ''') argparser.add_argument('target', type=str, nargs=1, help='GCG-reannotated "target" f...
1d74692b8a839909b8aa35c6a8b2cad238ebb8ced6dc230df89ae8effd7b6453
Python
565
21
import numpy as np import pytest import pandas as pd @pytest.mark.parametrize( "data, index, expected", [ ({"col1": [1], "col2": [3]}, None, 2), ({}, None, 0), ({"col1": [1, np.nan], "col2": [3, 4]}, None, 4), ({"col1": [1, 2], "col2": [3, 4]}, [["a", "b"], [1, 2]], 4), ...
e2f4ac3b872dc791e2d9b0093265b16ca92485ac78d1822420348330532be389
Python
565
22
import sys print('word sentid sentpos discid discpos corpus') # 'id's start from 0, 'pos'es start from 1 discid = -1 sentid = 0 discpos = 1 corpus = sys.argv[1] if len(sys.argv) > 1 else 0 for line in sys.stdin: line = line.strip() if line == "!ARTICLE": discid += 1 discpos = 1 ...
2a32e42d4382edc5eb6268505dabe0f7e09ed0cde07063d00026bbe021720c65
Python
566
21
import torch import torch.utils.data as Data def Weighted_Sampling(train_label = None): ''' :param train_label: Input train label (in tensor) to calculate sampling weight :return: Pytorch Weighted Sampler ''' class_sample_count = torch.tensor( [(train_label == t).sum() for t in torch.uni...
678a296176acc54fc885180e579522223add091dc48ffd383c1b8bdabae7d756
Python
566
17
"""Test functions for non-linear optimization.""" import torch from mrpro.operators import Operator # TODO: Consider introducing the concept of a "Functional" for scalar-valued operators class Rosenbrock(Operator[torch.Tensor, torch.Tensor, tuple[torch.Tensor,]]): def __init__(self, a: float = 1, b: float = 100)...
6968062e828883ff9641f14dd51c8213a8ddd98889b3569789106c49f6f7a679
Python
566
26
import sys, os, re, collections sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts')) import tree import gcgtree import semcuegraph RELABEL = False for a in sys.argv: if a=='-d': gcgtree.VERBOSE = True semcuegraph.VERBOSE = True if a=='r': RELABEL = True ####...
ac2f5cea062edd21fefc8f6178d604ae1a87da4a2b34591475a34942941c52b9
Python
566
22
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="msmfcode", version="0.1", description="Package containing code for the simulation, evaluation and optimization of multi-scale, multi-field place codes.", url="https://github.com/dietriro/msmf-code", author="Robin Dietric...
6b12a209c3910501557721414eef43350c6d5991e0942ac5f561a93268670631
Python
567
20
"""Calling cards data analysis in Python""" from ._call_motif import call_motif, compare_motif from ._find_fastq import find_fastq from ._find_related_genes import ( pair_peak_gene_bulk, pair_peak_gene_sc, pair_peak_gene_sc_mu, ) from ._footprint import footprint from ._GWAS import GWAS, GWAS_adata_bulk, G...
5d440d3e8b3cb49743018bfb56f6d9361bb56aa664575db0c6c4cc22c0f7baf5
Python
568
16
import pandas as pd import sys, argparse argparser = argparse.ArgumentParser(''' Extracts RT tokenization from table of experiment data. ''') argparser.add_argument('cols', type=str, nargs='+', help='Column(s) that define(s) a unique key for each RT token.') args, unknown = argparser.parse_known_args() def main(): ...
072293579f1a9c86ff06614e686c2486fdeb69e65dbb017b7faad17dcf73c3c1
Python
569
25
import uuid import pytest from pandas.io.pytables import HDFStore tables = pytest.importorskip("tables") # set these parameters so we don't have file sharing tables.parameters.MAX_NUMEXPR_THREADS = 1 tables.parameters.MAX_BLOSC_THREADS = 1 tables.parameters.MAX_THREADS = 1 @pytest.fixture def temp_h5_path(tmp_path...
a4bb2da0d40bbdf75997fa8125360722ecc68363fbea31b9521bb0957708a761
Python
569
24
import vegas import numpy as np from ffcn_cffi import ffi, lib @vegas.batchintegrand def batch_f(x): n, dim = x.shape ans = np.empty(n, float) _x = ffi.cast('double*', x.ctypes.data) _ans = ffi.cast('double*', ans.ctypes.data) lib.batch_fcn(_ans, _x, n, dim) return ans def main(): integ =...
8684eaeeb3a34eb66464d40e82f594a0d7108f64459a6b6577cebdd59e7dc59c
Python
570
23
import numpy as np import pytest import pandas as pd @pytest.mark.parametrize( "data,exp_size", [ # see gh-16362. ([[pd.NaT, "a", "b", 0], [pd.NaT, "b", "c", 1]], 8), ([[pd.NaT, "a", 0], [pd.NaT, "b", 1]], 6), ], ) def test_maybe_infer_to_datetimelike_df_construct(data, exp_size):...
583ed1c350a714f0d5c1e8a7917500ef434b4caed2187b93a3f3f0f165f63106
Python
572
21
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2026, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
112ae6dea0f8d19e1d4d7c45f7097b84f39557e8a3d6f308806514c4807d51bd
Python
574
17
import torch def to_device(tensor, device: torch.device): """ Convert tensor-like object to given PyTorch device """ if tensor is None: return tensor elif isinstance(tensor, torch.Tensor): return tensor.to(device) elif isinstance(tensor, dict): return {k: to_device(v, device) f...
fe4e3101b15017cb018cf9fe580140128044fad159cb3ca6592fc200215b027c
Python
574
16
from distutils.core import setup import os version_file = open(os.path.join(os.path.dirname(__file__), 'VERSION')) version = version_file.read().strip() setup( name = 'gpmhc', packages = ['gpmhc'], version = version, # Ideally should be same as your GitHub release tag varsion description = 'Inference f...
4ac38075e8e65a95e487b243d046e6a3c7da06817945a3df900130923a617bb9
Python
575
25
SIZE = 256 LABELS = 139 FILTERED_LABELS = 6 LABEL_MAP = { "CSF": 0, "WM": 1, "GM": 2, "BS": 3, "CWM": 4, "CGM": 5 } OUTPUT = "." ADNI_DATASET_DIR = "/home/ivanitz/Data/adni" ADNI_TRAIN = "/home/ivanitz/deepbet/data/adni_seg_train.tfrecord" ADNI_VAL = "/home/iv...
0498b54e86ea33282a109eef2608f6275aa03c4eb99f6470b26e061a91668ab9
Python
577
17
print( """ ################################################################################## ~ MM2SF ~ (v 1.0) An Unsupervised Machine Learning Approach for the Automatic Construction of Local Chemical Descriptors T...
2a970d6e16c958a458283d8dd129538fa97cdbf5dac66d8f62cf05ee81938e8b
Python
577
20
import os, sys import numpy as np from sequence_models import pdb_utils ex_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "examples" ) assert os.path.isdir(ex_dir) orig_coords, orig_atoms, orig_valid = pdb_utils.parse_PDB( os.path.join(ex_dir, "gb1_a60fb_unrelaxed_rank_1_mod...
5e1e2cae24174a37075429388e1762685e9377609cd631df4a6dc917ff811640
Python
577
24
# -*- coding: utf-8 -*- # Authors: Gianvittorio Luria <luria@dima.unige.it> # Sara Sommariva <sommariva@dima.unige.it> # Alberto Sorrentino <sorrentino@dima.unige.it> # # License: BSD (3-clause) class Dipole(object): """Single current dipole class for SESAME. Parameters ---------- ...
e3b94ce3654ff350726e7d1a2e6abc7d1a397cc2c8c49458f8e2007e5bf038ac
Python
577
22
#!/usr/bin/env python __author__ = 'etseng@pacb.com' import os, sys import subprocess def run_cmd(cmd): if subprocess.check_call(cmd, shell=True)!=0: raise Exception("Error cmd:").with_traceback(cmd) input = sys.argv[1] # ex: test.sam if not input.endswith('.sam'): print("Only accepts files ending ...
94c6ee2cbcefc46c33e07a0d29dc5025a6373b00068132c565bf08c5677b1398
Python
578
13
"""Module defining decoders.""" from onmt.decoders.decoder import DecoderBase, InputFeedRNNDecoder, \ StdRNNDecoder from onmt.decoders.transformer import TransformerDecoder, TransformerLMDecoder from onmt.decoders.cnn_decoder import CNNDecoder str2dec = {"rnn": StdRNNDecoder, "ifrnn": InputFeedRNNDecoder, ...
6dbcac44ff2c293cdeb81603e5b0aa4a1dcfae41e9f20881e247ab93a4c89452
Python
579
16
import torch import torch.nn as nn import torch.nn.functional as F from torch_geometric.nn import GCNConv class SimpleGNN(nn.Module): def __init__(self, num_features, hidden_size, num_classes): super(SimpleGNN, self).__init__() self.conv1 = GCNConv(num_features, hidden_size) self.c...
85aec6a22c10b6b2b69c597ae472893e793505a535ef9478f3ddbe77079869dc
Python
579
22
from __future__ import annotations import pytest from pandas.compat import ( is_platform_windows, ) from pandas.compat.pyarrow import pa_version_under22p0 pa = pytest.importorskip("pyarrow") def _require_timezone_database(request): if is_platform_windows() and pa_version_under22p0: mark = pytest.ma...
f8dc2ed08aa3a3cf31495f2454126563cd9008238f07583cf4922864e7132a3a
Python
579
18
"""Re-export façade for the backbones package. All backbone type constants and the ``build_backbone`` factory are defined in ``factory.py``; this module re-exports them. Nothing should be defined here — add new symbols to ``factory.py`` and extend the import list below. """ from lightning_pose.models.backbones.factor...
fd62d443848aaf7e86e77102779d30318a6be95234ebe911edde0a2f1377dd9e
Python
580
19
# License: see [LICENSE, LICENSES/legged_gym/LICENSE] import numpy as np import os from datetime import datetime import isaacgym from legged_gym.envs import * from legged_gym.utils import get_args, task_registry import torch def train(args): env, env_cfg = task_registry.make_env(name=args.task, args=args) pp...
dcf92aacb35a6afac219a2d2de9eabe7b4fc0b2e9c15bb427ae10ce489199cc0
Python
581
28
import matplotlib.pyplot as plt def set_axis(ax, x, y, letter=None): ax.text( x, y, letter, fontsize=25, weight='bold', transform=ax.transAxes) return ax plt.rcParams.update({ 'xtick.labelsize': 15, 'xtick.major.size': 10, 'ytick.labelsize': 15, ...
072de404f2264926c61454a09721aa7aae88801cbcffaefdc6715afcc6266839
Python
587
19
import os inputDir = os.getenv("INPUTDIR") count = 0 # Nifti files are expected to be placed within INPUTDIR. # They will be renamed to match the naming pattern. print("Start renaming ...") for filename in os.listdir(inputDir): old_path = os.path.join(inputDir, filename) if (os.path.isfile(old_path)): ...
2ce956c7c51920e3d3be8109febf2421566e706a6b424f851ab65ce6db1efbff
Python
587
22
# __init__.py from .substructurevocab import * from .molgraph import * from .molgraphdisplay import * from .utilsonehot import * from .utilsmol import * from .utilsgraph import * from .dataset import * from .experiment import * from .graphmodel import * from .gineconv import * from .attentivefp import * from .training ...
6d7cb7388fbeb24c56b31e5749e8acbd1948ad78b236636f5193f34d26bef36b
Python
587
23
import numpy as np import pandas as pd def is_object_or_nan_string_dtype(dtype): """ Check if string-like dtype is following NaN semantics, i.e. is object dtype or a NaN-variant of the StringDtype. """ return (isinstance(dtype, np.dtype) and dtype == "object") or ( dtype.na_value is np.na...
1da598b771869d9142c32329afa7b962c17779e9568e1ede77d7235e81877728
Python
588
26
""" .. module:: gfx_manager :platform: Linux, Windows :synopsis: Manager for handling OpenGL resources and other graphics-related things .. moduleauthor:: Fredrik Nysjo """ import glm class GfxManager: def __init__(self): self.window = None self.width = 1000 self.height = 700 ...
224e7c1939808bd603b7396bfd190ddc35bd3edef8169b356d360fa85d540b50
Python
588
27
import sys sentid_prev = 0 first_line = True first_word = True for line in sys.stdin: row = line.strip().split() if first_line: word_ix = row.index('word') sentid_ix = row.index('sentid') first_line = False else: word = row[word_ix] sentid = row[sentid_ix] i...
bc68747f9bd898744c070d3ead3895a3072e166e1e21672febfb0c460857b55d
Python
588
15
import sys import os import numpy as np sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) from app.models import Condition def get_ppmi_condition(diagnosis): all_diagnoses = ["Prodromal PD", "Healthy C...
aab30481fcb31a4a292dfcc46499660c9e0d4f7acac591f1a32ba7a43825d266
Python
589
23
class AverageMeter: """Computes and stores the average and current value""" def __init__(self, name, fmt=':f'): self.name = name self.fmt = fmt self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, ...
e4700a8a7a7cd236259faa1a414103cf4c9476ff38c981237303c14ccd8d0797
Python
589
18
import functions.functions_torch as ft def weights_and_sparsity(model, tol=1.0e-3): """ It extracts the weights and calculate their spasity (using the tol as the threshold to judge zero element) respectively from the model, and return two dict type results. """ state = model.state_dict() weigh...
461f782ef008f4efde719dab86aacd5eb8965e0afd310db43254b635f5ec2262
Python
592
19
from dissect.PropsSimulator.simulator import simulate from dissect.prepare_data import dataset from dissect.dissect_frac import run_dissect_frac from dissect.dissect_expr import run_dissect_expr def run_dissect(config): print("\033[1mStarting simulations\033[0m") simulate(config) print("-----\n") print("\033[1mPr...
14b4d3d1b3ec7b6d14236ebe1595413112d121669385e48d2deb300f55163263
Python
593
30
import sys import pandas # noqa: F401 blocklist = { "bs4", "gcsfs", "html5lib", "http", "ipython", "jinja2", "lxml", "matplotlib", "openpyxl", "py", "pytest", "s3fs", "scipy", "tables", "urllib.request", "xlrd", "xlsxwriter", } # GH#28227 for some ...
808fc66e4e3ebb82298bfefe147558bbd8cf9d805ccb31f6c287ec27356910a1
Python
593
22
import torch import numpy as np import scipy.fftpack def random_orthogonal(dim3, dtype=None, device=None): q, _ = torch.linalg.qr(torch.randn(dim3, dim3), mode='complete') q = q.to(dtype=dtype, device=device).squeeze() return q def dct_matrix(dim, dtype=None, device=None): """ Form orthogonal dc...
a8a96d2fb96128ce8497310179cb22d6ae0c77c0ec245892c0890a9c613a5010
Python
593
25
import numpy as np from abc import ABC, abstractmethod class Transformations(ABC): """ Parent class for transformations, abstract methods are defined here. """ __slots__ = "gadgetron_array" def __init__(self, gadgetron_array: np.ndarray) -> None: """ Constructor...
8a0c605c7800446a698d0bbdd184cec4ed445cf1f9f348265f9f401dacdf9cbd
Python
594
29
import sys import glob import pandas as pd import numpy as np import h5py file_list = sys.argv[2:] print(file_list) total_data = pd.DataFrame() for ff in file_list: data = pd.read_csv(ff, sep=',', index_col=0, header=0) total_data = total_data.append(data) print(total_data.shape) labels = total_data['ass...
95bf7006bac736009da529703aa791809964238bc71e2fbeb7a294d9c84f2d21
Python
594
16
import sys, re, argparse, pandas as pd argparser = argparse.ArgumentParser(''' Reads x-fabp parser output and appends a summed FJProb field. ''') args, unknown = argparser.parse_known_args() def main(): data = pd.read_csv(sys.stdin, sep=' ', skipinitialspace=True) data['fjprob'] = data['F-L+'] data['noFpr...
3205b8162942e05e59dd031c867760bce936a3ebdbe56b4f88058b17d0239f69
Python
597
30
__all__ = ["MassSpectrumReaderBase"] import abc from typing import Optional from .spec import MassSpectrum class MassSpectrumReaderBase(abc.ABC): def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def __next__(self) -> MassSpectrum: spe...
06284ec550bfcf9c5c84d2fd44c67b95b9105454f0e44feda8cbfa8cc6ffc3cd
Python
598
21
from datetime import datetime import pandas as pd class TestSetName: def test_set_name(self): ser = pd.Series([1, 2, 3]) ser2 = ser._set_name("foo") assert ser2.name == "foo" assert ser.name is None assert ser is not ser2 def test_set_name_attribute(self): ser...
da7e8c3b9342b075fc4b1082c3f844e2d63a24b5d9e3840e876f1d8ead651163
Python
599
18
import h5py import numpy as np import pandas as pd import rdkit import torch import torch.nn as nn import torch.nn.functional as F import torch_geometric from rdkit import Chem from torch_geometric.nn.aggr import GraphMultisetTransformer from torch_geometric.nn.conv import MessagePassing from torch_geometric.typing imp...
3a4ae958845a40ce73a3b4a127096b70b7a80cf97b99708356aae54cd32e9be7
Python
600
20
import os from cptools2 import job def test_job_add_plate_autodetect_layout_old(): """Job.add_plate should auto-detect old IX layout regardless of Job.is_new_ix""" current_path = os.path.dirname(__file__) exp_dir = os.path.join(current_path, "example_dir") plate_name = "test-plate-1" # Intention...
5c9597a920bb96327357d3f5e408ec3cfe85f0a5c07ab260d15b7ef8bc08bc84
Python
600
17
import numpy as np from sequence_models.data import SortishSampler, ApproxBatchSampler n_samples = np.random.randint(100, 500) lengths = np.random.randint(100, 200, n_samples) bucket_size = np.random.randint(10, 20, dtype=int) sampler = SortishSampler(lengths, bucket_size) assert len(sampler) == n_samples assert len(...
3d3c0268cce3db0316b174cb8d6bf08be3d55aec4b1d40b0a2e79a71433e2cc9
Python
601
21
import sys import collections MINCOUNT = 100 Items = [ ] XFeatCount = collections.defaultdict(int) YValCount = collections.defaultdict(int) for line in sys.stdin: XFeats = line.partition(' : ')[0].split(',') for xf in XFeats: XFeatCount[xf] += 1 y = line.partition(' : ')[2][:-1] YValCount[y] += 1 Item...
e0e03097c4295326227e45a8e98bd82593b453aa96a0653fcfb30664b69204b7
Python
601
16
# Due to some werid bug, this would always end up errors so didn't actually use it for bert tuning from subprocess import check_output # Hyper-parameters table = "bert_tuning" target = "dspln_PSYCHIATRY_60" weight_decays = [0, 0.0001] lrs = [0.0001, 0.00005, 0.00001] for lr in lrs: for weight_decay in weight_dec...
ea49f82f3da2345d95b065b657f0f3e0497dc7b00ddc0bb29549c7229364bd6b
Python
602
32
import tube2 import cine import random import glob from skimage import transform, util from skimage import io as skio videonames = glob.glob("data2/*.cine") fcount = 0 for name in videonames: vid = cine.Cine(name) count = vid.image_count frame_indexes = random.sample(range(0, count), 20) for idx ...
627c8fa362e29911c5a0f914461d180d6bcdbf72a4551bee23b23c3b585b10bf
Python
603
39
import sys #python removeAt.py inputfile def init(l): outstr = "" pctr = 0 pstr = "" tag = False skip = False for cix in range(0,len(l)): if l[cix] == "(": pctr += 1 tag = True elif l[cix] == ")": if pstr[-1] == "-": pstr = pstr[:-1] else: outstr += ")" pstr = pstr[:-1] elif ta...
a305093944da94ec1fca2cd3238ede1fd38ac37d3a3c95bdf09176736f40d6ea
Python
603
10
from nnunet.training.loss_functions.ND_Crossentropy import CrossentropyND from nnunet.training.network_training.nnUNetTrainer import nnUNetTrainer class nnUNetTrainerCE(nnUNetTrainer): def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, un...
256881050227738809fa4af1c117208aac74baca44dd2e415c2f3ed18ca23e61
Python
604
11
# # # WARNING # # # # This list must also be updated in doc/_templates/autosummary/class.rst if it # is changed here! from .smc_utils import (compute_neighbours_matrix, compute_correlation_distance_matix, compute_neighbours_probability_matrix, initialize_radius, estimate...
7a557dbd9c5e45785dda05f6fad7f5d42bc5f06895a767c1e6d3f5fca193c55a
Python
605
21
# -*- encoding: utf-8 -*- # JN 2015-01-06 # refactoring from __future__ import print_function, division, absolute_import from PyQt5.QtGui import QPixmap class Cluster(object): """ represents a cluster could as well be a dictionary can objects vanish from memory, so that the 'value' problem of dict...
a7b80b516e462cae6b267c6b0b80d5714a7fe0630f6d6015956e194d6a46b29a
Python
606
14
import numpy as np from sklearn.mixture import GaussianMixture def rejection_step(q_X_N_rej, q_Y_gm, mm): q_Y_N_rej = mm(q_X_N_rej) q_Y_rej_gm_pars = {"n_components": 40, "reg_covar": 1e-3, "tol": 1e-3, "max_iter": 100} q_Y_rej_gm = GaussianMixture(**q_Y_rej_gm_pars).fit(q_Y_N_rej) q_Y_log_prob = q_Y_g...
b2e68ba23c3aedd50248f23522ba526c768b36acf2fe98fdeaffbf8e2ac5eb82
Python
606
17
import pandas as pd import json import os import pdb template_json_file = None for subdir, dirs, files in os.walk('../../temp/unzip_files/unzipped'): for file in files: if file.endswith(".json"): with open(subdir+'/'+file) as f: image_metadata_json = json.load(f) ima...
b607afb72e198a2a05ff16873d14d9df9a9b49de1860acf7aec3549ce81b29b5
Python
607
24
from abc import ABCMeta, abstractmethod from EventController import EventController class BasicAppProcess: def __init__(self) -> None: pass @abstractmethod def initial(self, controller, viewcontainer, messenager): self.controller = controller self.messenager = messena...
a6c1e5d3d4cc24ffbf14fae203bf806781e91c0db418b1a9616c0768eaa843af
Python
609
14
""" Tests for python_module """ from scanometrics.utils.stats import fdr import numpy as np def test_fdr(): """Tests scanometrics.utils.stats.fdr() function, compared to octave output""" p = np.array([0.01, np.nan, 0.003, 0.2, 0.3, 0.004, 0.2, 0.1, 0.02, np.nan, 0.04, 0.1, 0.003, 0.0004, 0.07]) pID, pN =...
eba0e5b13fa9601b2ee505e936bac231c154072674229878a5a96b58f4d5be9c
Python
610
20
import pandas import numpy simulataniousLigands = numpy.array([2, 3, 5]) trainingSamples = numpy.array([10, 50, 100, 400, 800]) allConditions = numpy.zeros((len(simulataniousLigands)*len(trainingSamples), 3), dtype=int) k=0 for i in range(len(simulataniousLigands)): for j in range(len(trainingSamples)): ...
789c4d6a3949fa06f043360b20bf39f15e717ea784194343b8cb7adea8831883
Python
611
28
from .gcn import GCN from .mpnn import MPNN from .schnet import SchNet from .cgcnn import CGCNN from .megnet import MEGNet from .gatgnn import GATGNN from .deep_gatgnn import DEEP_GATGNN from .super_cgcnn import SUPER_CGCNN from .super_megnet import SUPER_MEGNet from .super_schnet import SUPER_SchNet from .su...
7e33c3738a05e90f9852424070973ffcff9f4dd6ec5cda484ddb7fb58f8b75c2
Python
611
18
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
d7007b032af635abcc4a721078daf7ad83a229a2eced0a393be9d2ad0f75111a
Python
611
25
#!/usr/bin/env python # coding: utf-8 import numpy as np import pandas as pd import sys import csv id = sys.argv[1] data = open('results_%s.loop'%(id),'r') heads = data.readline().strip().split('\t') sum_sig = 0 sum_es = 0 with open('results_%s_loop.csv'%(id), 'w') as f: writer = csv.writer(f) writer.writero...
d0df643b811422f9055a32cdbc2a813c33a6cda4cfce5bcb541940865871c059
Python
612
31
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.16.0 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% from pathlib import Path import sys...
f37754249f1df58d896b4bc3f45c56d4e7c3e448442aab65d8e5b1530557cbd2
Python
612
19
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
0fb8ccdc3df9ff422300c31fd7696eb074a9311472b3a9d7da860bf7015d0134
Python
613
19
""" Main entry point of the ONMT library """ # import onmt.inputters import onmt.encoders import onmt.decoders import onmt.models import onmt.utils import onmt.modules from onmt.trainer import Trainer import sys import onmt.utils.optimizers onmt.utils.optimizers.Optim = onmt.utils.optimizers.Optimizer sys.modules["onmt...