sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
19ec156b13d8017314510d206311a992d1fd2278f448791675548358597acb04
Python
1,040
30
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import textwrap from drf_spectacular.authentication import TokenScheme class AccessTokenAuthenticationScheme(TokenScheme): """ Adds the token auth method to schema. The description includes extra info comparing to what is generated by ...
77c1957d75e8874aaabe6d35434b88050d78ae4516ac3040af10757e94b59dc3
Python
1,041
38
# Copyright 2016 Numenta Inc. # # Copyright may exist in Contributors' modifications # and/or contributions to the work. # # Use of this source code is governed by the MIT # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. from nab.detectors.base import AnomalyDetector from na...
7c4734065c001aa8d3491a5c0e82f445cf29efaf96385d4593d9c7f5e2434d83
Python
1,041
30
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import os from datetime import timedelta ACCESS_TOKEN_STALE_PERIOD = timedelta( seconds=int(os.getenv("CVAT_ACCESS_TOKEN_STALE_PERIOD", 6 * 30 * 24 * 60 * 60)) ) """The time period after which unused API access tokens automatically become invali...
d95e8f6466695da0888ae5f58d955a7be849cd5f8ff45045dab6e8332750e13c
Python
1,042
29
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['bst.zip']) tmp_dir = tempfile.Temporar...
1cf45bd05c05ecfb75e89e0cf9f175ebb3bd81759fb2969c27354ddeb82c5ce1
Python
1,043
41
import json import os import random from dataclasses import dataclass from typing import Any, Dict import numpy as np import torch def set_seed(seed: int) -> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def save_json(obj: Dict[str, Any], path: ...
1ef720a6112bda3c1d4c3648fb69c730251f507e8c7e4c4ad7545eeca7618403
Python
1,043
41
#!/usr/bin/env python """ Create a site profile vector showing the average signal accumulated from a bigwig file around the center of each interval from a BED file. Output is the average signal value at that relative position across the intervals. usage: %prog bigwig_file.bw padding < bed_file.bed """ import sys f...
259bacfcaf3d7b950a6861021426674567159a89d097a2e3852475b28280c7f7
Python
1,043
31
from torch import nn from torch.autograd import Variable class TripletLoss(object): """Modified from Tong Xiao's open-reid (https://github.com/Cysu/open-reid). Related Triplet Loss theory can be found in paper 'In Defense of the Triplet Loss for Person Re-Identification'.""" def __init__(self, margin=None):...
6b7bc7732508e2a8b754cdab557d2f223c61d4b0135a648839e1b198e8c1f7aa
Python
1,043
40
import torch import torch.nn as nn import torch.nn.functional as F class DNN_Class(nn.Module): def __init__(self, input_dim=420, output_dim=300): super(DNN_Class, self).__init__() self.fc1 = nn.Linear(input_dim, 4096) self.dropout1 = nn.Dropout(0.5) self.fc2 = nn.Linear(4096, 2048)...
f63e04dd4465b7bcecfd9940de38b18fc7c45f122c0977333bc77906fbf34d15
Python
1,043
40
import torch import torch.nn as nn import torch.nn.functional as F class DNN_Class(nn.Module): def __init__(self, input_dim=420, output_dim=300): super(DNN_Class, self).__init__() self.fc1 = nn.Linear(input_dim, 4096) self.dropout1 = nn.Dropout(0.5) self.fc2 = nn.Linear(4096, 2048)...
3204b7069a708af7ee0fd898eb51b611d98449a1fe5b8c74e7ef4dafade030f4
Python
1,044
31
import argparse import os import os.path as osp import time import numpy as np import torch import torch.nn.functional as F from sklearn.metrics import f1_score import pandas import json import torch_geometric.transforms as T from torch_geometric.nn import ChebConv, GCNConv # noqa from tqdm import tqdm from sklearn.me...
ae38e70f3dfd04e297bb3eba69ac5b6b0681444e2247dccde1f805c140cc3e16
Python
1,044
32
"""Classical Evolutionary Algorithm.""" import random from analogainas.search_spaces.sample import random_sample class EAOptimizer: def __init__(self, max_iter, population_size, mutation_prob): self.max_iter = max_iter self.population_size = population_size self.mutation_prob = mutation_pro...
b9d559e60d8f7d2c8a76a853a0d7b41d9ba1b8dce4cabb2f0f5cdcde355d8a30
Python
1,044
35
# -*- coding: utf-8 -*- """ Created on Fri Apr 11 19:03:57 2025 @author: axthi """ import sys # -------------------------------------------------- # NOTE: Update this path to fit to your installation path_to_utils = '/mrhome/axelt/memoslap_utils/memoslap' sys.path.append(path_to_utils) from simnibs_memoslap_utils.uti...
052eaa0a027b3ff9373f6bfbd636a217879d3dac59f60a482bd0449f61c45222
Python
1,045
33
"""Nottingham MEGUK: Sign flipping. Aligns the sign of each parcel time course across sessions using the covariance-based search in :code:`Data.align_channel_signs`, then writes the sign-flipped data back to a fif file alongside the original. """ from glob import glob import mne from osl_dynamics.data import Data f...
1bdc9c9f9abb0225dd4eb797feac19ced3085e1cae656f1382ccf94321c2adb3
Python
1,045
26
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
41b66125d12a3ff3d43b813bd711cc430688c329e1db1bc7badda2920db2e551
Python
1,046
33
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import os import numpy as np def save_comparison(original, predicted, ground_truth, epoch, batch_idx): fig, axarr = plt.subplots(1, 3, figsize=(15, 5)) original = original[0].squeeze().cpu().numpy() predicted = predicted[0]....
50855c2cc3d842563b78f0c4dc11490d11a94712fc2db592da1f5475f3e5836c
Python
1,046
46
""" Utility functions """ import os def get_data_root(verbose=True): """ Get root to data as an environment variable """ # Get the value of DATAROOT data_root = os.getenv('DATAROOT') assert data_root is not None, \ ('DATAROOT is not set!' 'please run export DATAROOT=/path/to/...
50fd94ca420bec39403c17120866bb4f0a60c82bfdd030fdb73f2ce6dd8cb8fb
Python
1,046
50
#!/usr/bin/env python """ Read a set of ranges and a nib file, print portions of nib overlapping those ranges to stdout TODO: General sequence handling would be nice, as well as merging with 'nib_intervals_to_fasta.py'. usage: %prog nib_dir < range_file """ import sys import bx.seq.nib from bx.cookbook impor...
517694c82e638c217faf26d72de11d8c68fbfd53da4940947ef5ee934b813d23
Python
1,046
47
from setuptools import setup, find_packages import re import os import io def _read(*parts, **kwargs): filepath = os.path.join(os.path.dirname(__file__), *parts) encoding = kwargs.pop("encoding", "utf-8") with io.open(filepath, encoding=encoding) as fh: text = fh.read() return text def get_v...
913c2ca55da05015b070de69a03cde4918e58e23d23a6e75e4b6d5ea6932efeb
Python
1,046
33
"""Wakeman-Henson: Dipole Sign Flip. Aligns the sign of each parcel time course across sessions using the covariance-based search in :code:`Data.align_channel_signs`, then writes the sign-flipped data back to a fif file alongside the original. """ from glob import glob import mne from osl_dynamics.data import Data ...
488e86971496abad091928519de63329e26fb0f52a9db576fccff81beaa8be6d
Python
1,048
51
import tqdm, sys import matplotlib.pyplot as plt from mpl_toolkits import mplot3d import numpy as np from scipy.spatial import ConvexHull import os import ngauge ngauge.__version__ ######################## # Read SWC neuron ######################## path='/mnt/DD/Sc RNA-Seq/LR/morpho/swc_file' #Change directory os.c...
4b5052da94e4d5132e276fb3c67040fe3cf44c8506411001112f24cc934212e7
Python
1,048
33
from typing import Optional from torch import nn, Tensor import torch.nn.functional as F from .functional import label_smoothed_nll_loss __all__ = ["SoftCrossEntropyLoss"] class SoftCrossEntropyLoss(nn.Module): """ Drop-in replacement for nn.CrossEntropyLoss with few additions: - Support of label smoothi...
4c3ad216c5ba71500f23c7f8b0ab452b6451edaadeec6b5a8bb9bc46202a3850
Python
1,048
28
# /------------------------------------------------------------------------------+ # | 06-JUL-2022 | # | Copyright (c) Bone Imaging Laboratory | # | All rights reserved ...
b303aed6eb73ec2515c992ae580b88a7a172215047a25382d584fbd724c6500b
Python
1,048
30
""" Support for chopping a list of alignment blocks to only the portion that intersects a particular interval. """ def chop_list(blocks, src, start, end): """ For each alignment block in the sequence `blocks`, chop out the portion of the block that overlaps the interval [`start`,`end`) in the componen...
cb3c298d3d4efc6c5103d95f5a466b9f737630f4cef22e2c4a2107ffab877d6e
Python
1,048
45
""" Base classes for site maskers. """ from bx.filter import ( Filter, Pipeline, ) class Masker(Filter): def __init__(self, mask="?"): self.mask = mask self.masked = 0 self.total = 0 class MaskPipeline(Pipeline): """ MaskPipeline implements a Pipeline through which align...
da9c17a776a349a6ceba546e5333bfddaa6da6681e133d9ade10bd954e9cb541
Python
1,048
39
# Copyright (c) OpenMMLab. All rights reserved. import argparse from mmcv import Config, DictAction from depth.apis import init_depther def parse_args(): parser = argparse.ArgumentParser(description='Print the whole config') parser.add_argument('config', help='config file path') parser.add_argument( ...
454fd1cdac21f1d8b69e77497a56328d61ca6657b9c19746c29572db3252f09f
Python
1,049
31
from curvature_calculation import new_workflow, extract_curvatures_after_new_workflow import time t_begin = time.time() fold = r"/Users/benjaminbarad/Dropbox (Scripps Research)/Grotjahn Lab/Data/Surfaces/Lam2_TS1/" # output will be also written there base_filename = "all" # seg_file = "TS1_surf.labels.mrc" seg_file = ...
9d5d4b0e2a89b6b225b2aff8c92c3b9407fc29f463047dffb71198f7f56487d8
Python
1,049
35
import networkx as nx import numpy as np import os from graphwave import * from tqdm import tqdm # edge_path=r'/data2/whr/lyh/baseline2/Twibot-22/edges.npy' # edge_index=list(np.load(edge_path)) # edges=[] dataset_name='Twibot-22' edges=np.load('/data2/whr/lyh/baseline2/Twibot-22/edges.npy') G = nx.Graph() G.add_edg...
f99dc5b368f5d02229cd9e142dc54cedefacfbfb951891600fd8d8a04f762153
Python
1,049
27
import torch from utils import loss_and_miner_utils as lmu from distances.base_distance import BaseDistance class LpDistance(BaseDistance): def __init__(self, **kwargs): super().__init__(**kwargs) assert not self.is_inverted def compute_mat(self, query_emb, ref_emb): dtype, device = ...
3a6501176e9270ebabc59096d8c3b1a02466a839f804a2c7bcbc0aa61d5b660d
Python
1,050
37
import csv import numpy as np from tqdm import tqdm import json dataset_name='Twibot-22' edges=[] id_list=np.load('/data2/whr/lyh/twibot22_baseline/'+dataset_name+'/id.npy') id_list=list(id_list) f_write=open('/data2/whr/lyh/baseline2/edge_cleaned.txt','w') count=0 with open('/data2/whr/czl/TwiBot22-baselines/dataset...
5261bb57d4194e9c4eb9fca16935435c76c459850d2e178fd1ea99bc64cfd4d3
Python
1,050
38
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import django_rq from django.conf import settings from rq import Retry from rq.types import JobDependencyType from .models import Webhook def add_to_queue( webhook: Webhook, payload: dict, redelivery: bool = False, depends_on: Job...
6f0b07a75016c86fc19fa52f41f012f4105d78250c6b38d859e692e773bec1f3
Python
1,050
38
import base64 from io import BytesIO import requests from PIL import Image def encode_image_to_base64(file_path: str) -> str: with Image.open(file_path) as image: buffered = BytesIO() image.save(buffered, format="JPEG") return base64.b64encode(buffered.getvalue()).decode("utf-8") def se...
a268a78a7f5aff52df0e96661ac7fc1098ac53cbcde8e6fd656f8997f7e4fe35
Python
1,050
24
class Defaults(object): window_size = 7 hidden_sizes = [300] hidden_activation = 'relu' max_vocab_size = 1000000 optimizer = 'sgd' # 'adam' learning_rate = 0.1 # 1e-4 epochs = 20 iobes = True # Map tags to IOBES on input max_tokens = None # Max dataset size in tokens encodi...
88db5abdd35212b8a42898f2b1aac15077a78a1f662a115b35670e06b11082f4
Python
1,051
44
# Train a Linear Regressor # Imports import numpy.typing as npt from sklearn.kernel_ridge import KernelRidge from modules.tools.types_abbrv import KERNEL_RIDGE_REG_TYPE def train( X: npt.NDArray[float], y: npt.NDArray[float], cfg: dict ) -> tuple[KERNEL_RIDGE_REG_TYPE, dict]: """Train a kernel ridge regres...
5f39601c7f6286128004e1c6c3786929061d283c842c5b03ae00bb754a66764d
Python
1,052
35
import pandas as pd label = pd.read_csv('/data2/whr/czl/TwiBot22-baselines/datasets/botwiki-2019/label.csv') main_user = pd.read_csv('./user_feature.csv') user = main_user.loc[0:len(main_user)-1] user_list = list(user['user_id']) del_list = [] bool_label = [] for i,r in label.iterrows(): if r[1] == 'human': ...
6c585a441da0c6243254937ef0c0004a8c50f2d96b84dbc1d5db91d6a2d94df5
Python
1,052
44
import torch import os # global variable: cache_root cache_root = os.path.expanduser(os.path.join("~", ".flair")) # global variable: device device = None if torch.cuda.is_available(): device = torch.device("cuda:0") else: device = torch.device("cpu") from . import data from . import models from . import visu...
e212760ecd155792c9388567ce26f88513aa13207a87c89e85dfd435c2cb3603
Python
1,052
33
import os import numpy as np from impedancefitter.fra import bode_csv_to_impedance, bode_to_impedance freq = np.logspace(1, 6) attenuation = np.linspace(1, 10) phase = np.linspace(-90, 0) def test_bode_to_impedance(): """Test correct frequency conversion.""" omega, _impedance = bode_to_impedance(freq, atte...
09ad33fbf86818b74e36c54de8d91be3c2f08383a38abf4813d5585bebcf4bf8
Python
1,053
35
import pandas as pd label = pd.read_csv('/data2/whr/czl/TwiBot22-baselines/datasets/pronbots-2019/label.csv') main_user = pd.read_csv('./user_feature.csv') user = main_user.loc[0:len(main_user)-1] user_list = list(user['user_id']) del_list = [] bool_label = [] for i,r in label.iterrows(): if r[1] == 'human': ...
63774ca8e7bf4d70b71061c18644e2681eb67fddb65f2452af637fecca258fb1
Python
1,053
36
import pathlib from setuptools import setup # The directory containing this file HERE = pathlib.Path(__file__).parent # The text of the README file README = (HERE / "README.md").read_text() # This call to setup() does all the work setup( name="density-peak-for-hic", version="0.0.1", description="Read the...
f552ea203f238ddc3f527dbbd05deb40bbcdcfdbd032137d9adb3b924fcc6bf6
Python
1,053
43
""" Layer/Module Helpers Hacked together by / Copyright 2020 Ross Wightman """ from itertools import repeat import collections.abc # From PyTorch internals def _ntuple(n): def parse(x): if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): return tuple(x) return tuple...
fc1deb833e4d00631e7ea23e32aa13675c684c87f7b6cc5ef00ebfe947e1467d
Python
1,053
35
import pandas as pd label = pd.read_csv('/data2/whr/czl/TwiBot22-baselines/datasets/verified-2019/label.csv') main_user = pd.read_csv('./user_feature.csv') user = main_user.loc[0:len(main_user)-1] user_list = list(user['user_id']) del_list = [] bool_label = [] for i,r in label.iterrows(): if r[1] == 'human': ...
236acbefe2efdf02b2ba65c7895b99c205316027c0222c82848c00a17375732c
Python
1,054
29
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['lesions.zip']) tmp_dir = tempfile.Temp...
33bdf44f8f65a5a10189cf33a8b89e605db21e5bf0ccdc05c73b32824bb83ec5
Python
1,054
36
#!/usr/bin/env python """ Read BED file and extend each record to the specified minimum length. If chromosome size information is provided trim extended intervals. usage: %prog amount [ chrom_file ] < bed_file """ import sys from bx.intervals.io import GenomicIntervalReader length = int(sys.argv[1]) chrom_len = No...
941e7a2a539adfe61be64e3a233c7fa516070dfd5f5cc67a49e780726207764d
Python
1,054
34
import subprocess import sys import yaml script_plot = 'SOM/clusterSOM/clusterplot_SOM.py' script_labels_spont = 'SOM/clusterSOM/plot_clusterlabels.py' script_labels_resp = 'SOM/clusterSOM/plot_clusterlabels_response.py' pathpath = 'PATHS/filepaths_carlen.yml' with open(pathpath, 'r') as myfile: pathdict = yaml.safe_...
d6e9949efb27710f0128c7f4239edc50406f2101c47a32e82e8ebf085a20e752
Python
1,054
35
import pandas as pd label = pd.read_csv('/data2/whr/czl/TwiBot22-baselines/datasets/celebrity-2019/label.csv') main_user = pd.read_csv('./user_feature.csv') user = main_user.loc[0:len(main_user)-1] user_list = list(user['user_id']) del_list = [] bool_label = [] for i,r in label.iterrows(): if r[1] == 'human': ...
63faec9fd7fe2cf946cd994bc34cfe4634edc554ce4bdab392e7a1c1a9dcb2e1
Python
1,055
44
import scanpy as sc import pandas as pd from anndata import AnnData import warnings from builtins import int warnings.filterwarnings('ignore') import losses, miners, distances, reducers, testers from utils.transformations import * from utils.accuracy_calculator import AccuracyCalculator import torch import torch.optim...
961df1ef27b7546d527defcab228a3ae65175c235d02fe1fe0fcb9e5a4fac7e9
Python
1,055
40
"""Example script for plotting power maps from static spectra. """ print("Setting up") import os import numpy as np from osl_dynamics.analysis import power # Make directory to hold plots os.makedirs("figures", exist_ok=True) # Load spectra (calculated with static/calc_spectra.py) f = np.load("spectra/f.npy") psd = ...
996f7732c533f25c8da074aa5f827495537b9cf797be0f9fb4b0fcecab9ac105
Python
1,055
59
# -*- coding: utf-8 -*- # external inputs import numpy as np def get_white_2d(nx, ny, mu, sigma): """Get white 2D. Creates a 2D array with Gaussian noise. Parameters ---------- nx : int Array size in x-direction. ny : int Array size in x-direction. mu : float ...
26f10403f8815c6f1067d5af13c679c7647a2c5c5aada1e286891a0abbbc6dab
Python
1,056
29
import json, subprocess, os os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1' with open("hyperopt/best_param.json", "r") as f: params = json.load(f) for fold in [0, 1, 2, 4]: # range(5): fold_3 is not used as it is undertrained predict_command = f"""chemprop predict \ --test-path data...
3b356c4fcedcf8f9bfcd34c3436fb71c96d48788fee2d04867cf66ef08a71b6f
Python
1,056
40
"""Base simulation class.""" from typing import Optional import numpy as np class Simulation: """Simulation base class. Parameters ---------- n_samples : int Number of time points to generate. """ def __init__(self, n_samples: int) -> None: self.n_samples = n_samples ...
5dbc54f74f752d5c74b98b1462ae59c3c299fb9f7b019ec84382ba83cec8c73f
Python
1,056
31
import os from nipype.interfaces.fsl import Reorient2Std from PUMI.engine import BidsPipeline from PUMI.engine import NestedNode as Node from PUMI.pipelines.func.deconfound import motion_correction_mcflirt ROOT_DIR = os.getcwd() input_dir = os.path.join(ROOT_DIR, 'data_in/pumi-unittest') # path where the bids data is...
1dab79f4d72d199d80a7d079c293249c5db4004b0daf1e81072ddddb98e8d8c4
Python
1,057
26
import torch # Pytorch loss functions LOSS_FUNCTIONS = { "l1loss": torch.nn.L1Loss, "mseloss": torch.nn.MSELoss, "crossentropyloss": torch.nn.CrossEntropyLoss, "ctcloss": torch.nn.CTCLoss, "nllloss": torch.nn.NLLLoss, "poissonnllloss": torch.nn.PoissonNLLLoss, "gaussiannllloss": torch.nn.Ga...
82bc38a6a6f1e215656e3df72486a6ab006f369a9c1592394be62b5650e31178
Python
1,057
36
import numpy as np import torch as th from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, f1_score def write_list(li): formattor = "{:.4f}" return ",".join(map(lambda x: formattor.format(x), li)) + "\n" def training_one_data(data, label): data = np.array(data) ...
dd6ff430caf3e30307138f95ce19c1ec73e9b0202665810af348a9a86b7cd367
Python
1,057
33
import fire import pickle import numpy as np from rsatoolbox.data.dataset import Dataset from rsatoolbox.rdm.calc import calc_rdm from nilearn.glm.contrasts import expression_to_contrast_vector, compute_contrast import nilearn import nilearn.plotting import nilearn.image data_path = "../bids_dataset/derivatives" mapp...
ea49133fc88bec89fd851a07a255c8a6e2594f26d02cf8c2659a598772656cca
Python
1,057
38
import base64 import io import json import yaml from model_handler import ModelHandler from PIL import Image def init_context(context): context.logger.info("Init context... 0%") # Read labels with open("/opt/nuclio/function.yaml", "rb") as function_file: functionconfig = yaml.safe_load(function...
44da0e5a39e4126fa9fa45001c618a8a04d2669cc56f783496a36f79e0391d49
Python
1,058
35
def chunk_indices(indices, num_batches): batch_size = (len(indices) + num_batches - 1) // num_batches for i in range(0, len(indices), batch_size): yield indices[i:i + batch_size] def contrast_index(x1, x2, double=True): """ Calculate the contrast index between two arrays. The contrast inde...
50d0cb6c001d847fc087ce14aa0d1d6f4fca28077b4a027a828fa97be1728e57
Python
1,058
29
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['connectivity.zip']) tmp_dir = tempfile...
de99060583d75df11d1e1837a1e97dd48d08c8bf0fda2b0c5330bbb8c4bcc912
Python
1,058
30
from __future__ import annotations import numpy as np from brainways.pipeline.brainways_params import AffineTransform2DParams from brainways.transforms.affine_transform_2d import BrainwaysAffineTransform2D from brainways.utils.atlas.brainways_atlas import AtlasSlice from brainways.utils.image import ImageSizeHW, brai...
f116d4c35da76f966f22c8575e89c2fd6bcd8335ab4a03278ae4dee8223d37a7
Python
1,059
35
import pandas as pd label = pd.read_csv('/data2/whr/czl/TwiBot22-baselines/datasets/political-bots-2019/label.csv') main_user = pd.read_csv('./user_feature.csv') user = main_user.loc[0:len(main_user)-1] user_list = list(user['user_id']) del_list = [] bool_label = [] for i,r in label.iterrows(): if r[1] == 'huma...
2a200490c0fc6386bf95b2b5f9453a7a089af2067fdf60b8c1a197d51e581e4a
Python
1,061
43
#!/usr/bin/env python """ Focus lock find sum tests. """ from storm_control.test.hal.standardHalTest import halTest def test_hal_tcp_fs_1(): halTest(config_xml = "none_tcp_config.xml", class_name = "FindSum1", show_gui = True, test_module = "storm_control.test.hal.tcp_tests") ...
6073dba77826786d9efa81fac4d0d4be1ce7f08ced3eb0c7d2476d5c5bb5045e
Python
1,061
46
#!/usr/bin/env python """ Read an alignment from stdin and for each block print the result of evaluating `template_string` (in cheetah template format). The alignment block will be placed in the template context as `a` and the list of components as `c`. usage: %prog template [options] -f, --format = maf: Input fo...
8255751f01061c0828f5fd8a005dec9ed624cd7c0baf9ddba790fc6718f7f181
Python
1,061
35
import pandas as pd label = pd.read_csv('/data2/whr/czl/TwiBot22-baselines/datasets/vendor-purchased-2019/label.csv') main_user = pd.read_csv('./user_feature.csv') user = main_user.loc[0:len(main_user)-1] user_list = list(user['user_id']) del_list = [] bool_label = [] for i,r in label.iterrows(): if r[1] == 'hu...
8c001d0c6728a3541b0a00b229161ef9713fd9e595d5ac921d84d31d05053059
Python
1,061
37
from graphrole import RecursiveFeatureExtractor, RoleExtractor import networkx as nx from karateclub import Role2Vec import numpy as np import os from tqdm import tqdm edge_path=r'Twibot-22/edges.npy' edge_index=list(np.load(edge_path)) edges=[] dataset_name='Twibot-22' id_include=(np.load(dataset_name+'/id_include.npy...
47e9ebb144389496f1543a893b84feffc0c5cf2cda69c299987f4d3bcb6c3f8d
Python
1,062
27
# Copyright (c) 2015 Tobias Neumann, Philipp Rescheneder. # # This file is part of Slamdunk. # # Slamdunk is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your ...
4de78739d28226865a506c61d4bc8ee1218007a1c54611bf9a3231a88d20ea0c
Python
1,062
29
import os from fairseq.tasks import register_task from fairseq.tasks.translation import TranslationTask from dasa_fairseq.data.dep_bias_dataset import DepBiasDataset @register_task("translation_dasa") class TranslationTaskDASA(TranslationTask): """ Same as TranslationTask, but wraps split datasets with DepBi...
705e774c89a42636e5fd22554b39e6c73751d084316c8cbed10735e0243e8366
Python
1,062
32
''' Python implementation of "native thalamus". Currently does as little as possible, just allows the task controller to run. ''' import asyncio import typing import logging import grpc from .. import thalamus_pb2 from .. import thalamus_pb2_grpc LOGGER = logging.getLogger(__name__) class PipelineServicer(thalamus_...
4a702e6e99ffe34260bd01496624d0a9185d790b366a64121cb2dd6e44767557
Python
1,063
29
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['bundles.zip']) tmp_dir = tempfile.Temp...
d3d2c0b23b054265e8803b73441d0ecfca3d9b40d3f92704b9ac5a79b613d5ab
Python
1,063
44
import numpy as np from scipy.constants import epsilon_0 as e0 from impedancefitter.single_shell import eps_cell_single_shell from impedancefitter.suspensionmodels import bh_eps_model, bhcubic_eps_model em = 10.0 Rc = 0.5e-6 dm = 7e-9 dn = 7e-9 km = 1e-6 kcp = 1.0 ecp = 80 kmed = 1.0 emed = 80.0 c0 = 1e-12 p = 0.3 kn...
e652072aa04166e1106f4fcdd0b21e86fb5982412132d4e1d64da1822c9ac317
Python
1,063
32
from .eqtransformer import EQTransformer class OBSTransformer(EQTransformer): """ Initialize an instance of OBSTransformer model. OBSTransformer is built based on the original (non-conservative) EqTransformer model. .. warning :: Creating an OBSTransformer instance does not automatically loa...
77f69a2583e3ccab4522229a4c55a625bdab43ca8cb6f870fd52ebb1053817fc
Python
1,064
30
import numpy as np import os from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping def get_callbacks(early_stop, output_prefix): early_stop_callback = EarlyStopping(monitor='val_loss', patience=early_stop, verbose=1, ...
e31f89a072cd5f11d1394b977c8d23394b003e3df4c3c632b76d1c1cfc2efc52
Python
1,064
35
from __future__ import annotations from PySide6 import QtCore from PySide6 import QtGui from PySide6 import QtWidgets from .._utils._qt import new_icon class InfoButton(QtWidgets.QToolButton): def __init__( self, *, tooltip: str, parent: QtWidgets.QWidget | None = None ) -> None: super().__i...
a306cc13902cc9b3cc47308a8f73c58916ff894b648a4c2f7e0620b193857c96
Python
1,065
27
from brainscore_vision import model_registry from brainscore_vision.model_helpers.brain_transformation import ModelCommitment from .model import get_model, LAYERS ### AlexNet_SIN with different fields of view than 8 visual degrees (default) ### # exploring 4, 12, 16 visual degrees # code is adapted from the original s...
0515bd9e8c30659d522eaaa1216d8fa021d30969531fe9466fb500379e13e096
Python
1,066
48
# -*- coding: utf-8 -*- # external inputs import numpy as np def get_meshlines(vtx_pial, vtx_white): """Get meshlines. This function returns a vertex and a corresponding face array to visualize point-to-point connections between two congruent surface meshs. Parameters ---------- vtx_pial : ...
6804acd6a0a9fdc7c4fafcd25dd2a757771aad13a832b4d8e287062246b17428
Python
1,066
33
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['processing.zip']) tmp_dir = tempfile.T...
089a370f7f9b09b11e9d5fb54925eff82f37cdcfddf251333c5ff2be7e97b6af
Python
1,067
25
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv3D, ReLU, BatchNormalization, MaxPool3D, Lambda, Flatten, Dense, Activation from tensorflow import pad as tf_pad def Model(image_shape=(160,192,160,1)): def conv_block(n_filters, padding1='same'): return Sequential([ ...
232bb9ec6f069f613205489f36aa1405367e6674172708fecb147104977ccaf0
Python
1,067
28
from causallib.metrics.scorers import PropensityScorerBase class SKLearnScorerWrapper(PropensityScorerBase): def __init__(self, score_func, sign=None, **kwargs): super().__init__( score_func=score_func, sign=1, # This keeps original scorer sign **kwargs ) ...
d265ba332302ba70f0bea4d05ddb4adb89a677da797314c5aefa4165a91046b2
Python
1,067
29
import pytest from pytest import approx from brainscore_vision import benchmark_registry, load_benchmark @pytest.mark.parametrize('benchmark', [ 'BMD2024.texture_1Behavioral-accuracy_distance', 'BMD2024.texture_2Behavioral-accuracy_distance', 'BMD2024.dotted_1Behavioral-accuracy_distance', 'BMD2024.d...
0704eef6d11a9ac9aa17e0c77641e0581bfc3da7f7fc213cbfe2066622d4d477
Python
1,068
32
import torch import torch.nn as nn class SpaceToDepth(nn.Module): bs: torch.jit.Final[int] def __init__(self, block_size=4): super().__init__() assert block_size == 4 self.bs = block_size def forward(self, x): N, C, H, W = x.size() x = x.view(N, C, H // self.bs, s...
2ff6da08f0cd62662de0dcb4f5e1c352f838b12e19915ad8994fd0062b1a498c
Python
1,069
36
import os import numpy as np def short_summary(model): NUM_PARAMETERS = {"Not Trainable": 0, "Trainable": 0, "Overall": 0} for params in model.parameters(): num_params = params.numel() trainable = params.requires_grad key = list(NUM_PARAMETERS.keys())[trainable] NUM_PARAMETERS[...
c2700fdad69b780dfdff3e21b4f3fc7835c00e0fb3a331c5a1253cf3c591d1f7
Python
1,069
32
import torch from torch.utils.data import Dataset class BotDataset(Dataset): def __init__(self, name, path): self.name = name # different features dataset # self.cat_features = torch.load(path + "cat_properties_tensor.pt") # self.prop_features = torch.load(path + "num_prope...
01b66cfa58cb3236b0f036cd0de876b461ef3840d9a18d42dd14f6a4e6a47263
Python
1,071
33
import numpy as np import torch import xdas from unittest.mock import patch import seisbench.models as sbm def test_deepsubdas(): # Simple test to check that the code does not crash data = np.random.rand(4000, 2000) nt, nd = data.shape dt = np.timedelta64(10, "ms") dx = 10 t0 = np.datetime64...
61efa7e078171ab545ced5a9ed6b2251be59e0b9d9b2afef99484cd24a2352c9
Python
1,071
37
import json import base64 from PIL import Image import io from model_handler import ModelHandler import yaml def init_context(context): context.logger.info("Init context... 0%") # Read labels with open("/opt/nuclio/function.yaml", "rb") as function_file: functionconfig = yaml.safe_load(function_...
fb0ee8e2864d9683f755f9b12dde06355f56b9cc68e84948cec724ff74307060
Python
1,071
41
from setuptools import setup, find_packages packages = find_packages() print(packages) with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() version = "0.0.1" setup( name="deep_events", version=version, description="Deep-Events", long_description=long_description, ...
fee8bfb54477c8f6757ce74cbb5a48293ca47776a522e2c78a4bd3ca6e767b99
Python
1,072
32
""" Hyperparameter Optimization Package A comprehensive suite of tools for machine learning hyperparameter optimization using Optuna and MLflow with advanced features like stratified data splitting, feature importance analysis, and experiment tracking. Key Components: - hyperparameter_optimizer.py: Main optimization ...
8ebea6cb45c8a4b5ac6bfe1ffe9b60f3059f01c50205d16e512448ca0fa39cdd
Python
1,073
33
import numpy as np from eir.models.input.omics.omics_models import ( al_omics_model_configs, al_omics_model_types, al_omics_models, get_omics_model_class, get_omics_model_init_kwargs, ) from eir.setup.input_setup_modules.common import DataDimensions def get_omics_model_from_model_config( mode...
fcf70f3ebbfad450881cea33653ccfaba0b9a565e37971a4328400606d26f5b4
Python
1,073
35
import os import pytest import torch from {{cookiecutter.project_slug}}.datamodules.mnist_datamodule import MNISTDataModule @pytest.mark.parametrize("batch_size", [32, 128]) def test_mnist_datamodule(batch_size): datamodule = MNISTDataModule(batch_size=batch_size) datamodule.prepare_data() assert not da...
389abff7abfa7bd532cbc749dc717f76e1c5b88eb860bd92cde8cdb43fcb3dbf
Python
1,074
42
# myelinfccoupling/config.py from dataclasses import dataclass, field from typing import List @dataclass class Config: """ Configuration for Myelin–FC coupling modeling (Python). Mirrors the logic in the MATLAB pipeline. """ # Column names in edges.csv col_i: str = "i" col_j: str = "j" ...
dc909f7a10a4a91e1822b78003534d7dd34febf1d0da349547014a7195aceab7
Python
1,074
22
# A script to visualize the ERF. # Scaling Up Your Kernels to 31x31: Revisiting Large Kernel Design in CNNs (https://arxiv.org/abs/2203.06717) # Github source: https://github.com/DingXiaoH/RepLKNet-pytorch # Licensed under The MIT License [see LICENSE for details] # -----------------------------------------------------...
e7f09a74a3287272d428e67c2310df4f421d4fbe225c8226322df63d3e92c3e8
Python
1,074
50
from impedancefitter.cpe import cpe_model, cpe_ct_model, cpe_ct_w_model import numpy as np omega = 2. * np.pi * np.logspace(1, 8, num=20) k = 1e-7 alpha = 0.9 Rct = 100 Aw = 10 def test_cpe_ct_w_type(): Z = cpe_ct_w_model(omega, k, alpha, Rct, Aw) assert isinstance(Z, np.ndarray) def test_cpe_ct_w_shape():...
103860fbfdde787baf9e01841f261f39b6dcd0fd11399cc1b07104f86ae03318
Python
1,075
42
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from .ascend import onnx2ascend from .axelera import torch2axelera from .coreai import torch2coreai from .coreml import torch2coreml from .deepx import onnx2deepx from .engine import onnx2engine, torch2onnx from .executorch import torch2executorch fro...
25d6e9558c07c6b5c231fd2a73f85bc12149c5b210519e942ce8ca04936d16aa
Python
1,075
46
# -*- coding: utf-8 -*- """ Created on Tue Jan 28 08:54:50 2014 @author: dan """ #!/usr/bin/env python # a bar plot with errorbars import numpy as np import matplotlib.pyplot as plt srint = sorted('ADVRGT') N = 6 menMeans = (20, 35, 30, 35, 27,9) menStd = (2, 3, 4, 1, 2,4) ind = np.arange(N) # the x locations fo...
db5af751e5e77a9c3ad1ab80b078963403d156162cce862fde925ec640093c7c
Python
1,075
42
"""Example script for plotting functional connectivity (correlation) maps. """ print("Setting up") import os import numpy as np from osl_dynamics.analysis import static, connectivity from osl_dynamics.data import Data # Make a directory to save plots to os.makedirs("figures", exist_ok=True) # Load data data = Data(...
f29a5f0b3832258d676e0d8948d5373deebf0b4f6507a13cf7b49782eb757191
Python
1,075
42
#!/usr/bin/env python """ Test correlation focus lock fitting. """ import numpy import random import storm_analysis.simulator.draw_gaussians_c as dg import storm_control.sc_hardware.utility.corr_lock_c2dg as clf def test_cl_1(): sigma = 2.0 cl_fit = clf.CorrLockFitter(roi_size = 8, ...
9bf5ea5261c3ec7767c9fdd2d5743b474e707656eee6fd500a5251fd927ffb6d
Python
1,076
31
import os from MyClient import MyClient from utilities import bearer_token from utilities import get_user_timeline_by_id from utilities import get_tweet_dict import random import tqdm import json from tweepy.errors import ( BadRequest, Forbidden, HTTPException, TooManyRequests, TwitterServerError, Unauthorized...
a8ce0fa0727b4ebe2472d4105c89ba95ec80c74b0de9c618039bbd871f0cbe98
Python
1,076
29
import os import sys import click as ck import pandas as pd sys.path.append(os.path.join(os.path.dirname(__file__), '..')) @ck.command() @ck.option('--data-root', '-dr', default='data', required=True, help='data root') @ck.option('--file-name', '-fn', default='proteins', required=True, help='pickle file name') def mai...
11b296f3447106e75dbe3a29fa2e3afe12e53b0f27fc868d1e3e69541e961b62
Python
1,077
46
import pandas as pd import re import os save_dir = r"" root_path = r"" def count_occurrence(anchor_result_path, save_dir): for method in []: if method in anchor_result_path: label = method anchor_result = pd.read_excel(anchor_result_path) anchors = anchor_result['An...
24258eb76a87e8e5ce962dc07a19456d0670ff0c8b522e20c8fe1bb13dac6c11
Python
1,077
30
import os import numpy as np import pandas as pd from brainscore_core.supported_data_standards.brainio.stimuli import StimulusSet from brainscore_core.supported_data_standards.brainio.packaging import package_stimulus_set def collect_stimuli(data_path): assert os.path.isdir(data_path) stimulus_df = pd.read_pi...
34319df3882dd3ea48e9bc66d04ca82d856b10ab0d9363a38b5229a1c20e9235
Python
1,078
35
# Required libraries import matplotlib matplotlib.use('Agg') # Set globally for all matplotlib usage import matplotlib.pyplot as plt import os import numpy as np def save_comparison(original, predicted, ground_truth, epoch, batch_idx): fig, axarr = plt.subplots(1, 3, figsize=(15, 5)) original = original[0]....
45063925ccfe178e061ab370d9fb1c5dcdf9f4942f7d1eb25d69cbf110863319
Python
1,078
33
"""Script to clean FASTA sequences (e.g., remove sequences with stop codons) to use with ESM (https://github.com/facebookresearch/esm).""" from pathlib import Path from Bio import SeqIO from Bio.SeqRecord import SeqRecord from tap import Tap from tqdm import tqdm class Args(Tap): data_path: Path # Path to FASTA...
d25a6cb6a2635f527bdfa07bc05ecae1ceda4b216ed1961db30f1cb222106c7d
Python
1,078
27
import numpy as np import pandas as pd import scanpy as sc from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', '--lambda-file', type=str, required=True, help='Path to HDF5-formatted AnnData object with lambdas.') parser.add_argument('-x', '--layer', type=str, help='Layer in AnnDa...
d4ba626ac9e8f7b79160310a8e0522b6c5283ce49e5416db57f423dcb9f69c63
Python
1,078
29
from Cython.Build import cythonize import numpy from setuptools import setup, Extension define_macros = [('NPY_NO_DEPRECATED_API', 'NPY_1_7_API_VERSION')] # Modules to be compiled and include_dirs when necessary extensions = [ Extension('scilpy.tractograms.uncompress', ['src/scilpy/tractograms/uncom...