code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import nipype.pipeline.engine as pe from nipype.interfaces import io as nio from nipype.interfaces import ants from nipype.interfaces import fsl from nipype.interfaces import utility as util from nipype.workflows.fmri.fsl.estimate import create_overlay_workflow import numpy as np from nipype.workflows.fmri.fsl.estima...
src/fmri_modelfits/level3_model_parameters.py
import nipype.pipeline.engine as pe from nipype.interfaces import io as nio from nipype.interfaces import ants from nipype.interfaces import fsl from nipype.interfaces import utility as util from nipype.workflows.fmri.fsl.estimate import create_overlay_workflow import numpy as np from nipype.workflows.fmri.fsl.estima...
0.355216
0.241026
from collections import defaultdict import re class TreeNode(object): def __init__(self, text, offset, elements): self.text = text self.offset = offset self.elements = elements def __iter__(self): for el in self.elements: yield el class TreeNode1(TreeNode): ...
src/rollit/grammar.py
from collections import defaultdict import re class TreeNode(object): def __init__(self, text, offset, elements): self.text = text self.offset = offset self.elements = elements def __iter__(self): for el in self.elements: yield el class TreeNode1(TreeNode): ...
0.893408
0.391988
import random import string from logging import getLogger from django.core.cache import cache from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django_redis import get_redis_connection from rest_framework import generics, status from rest_framework.permissio...
backend/ambassador/views.py
import random import string from logging import getLogger from django.core.cache import cache from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django_redis import get_redis_connection from rest_framework import generics, status from rest_framework.permissio...
0.636127
0.088623
import json, re from common.models.applogs.AppAccessLog import AppAccessLog from common.models.applogs.AppErrLog import AppErrLog from common.services.BaseService import BaseService from application import db, app from flask import request class AppLogService(BaseService): @staticmethod def addErrLog(msg=None...
common/services/AppLogService.py
import json, re from common.models.applogs.AppAccessLog import AppAccessLog from common.models.applogs.AppErrLog import AppErrLog from common.services.BaseService import BaseService from application import db, app from flask import request class AppLogService(BaseService): @staticmethod def addErrLog(msg=None...
0.251188
0.031292
import numpy as np from sklearn.externals import joblib import random class Batcher: def __init__(self,storage,data,batch_size,context_length,id2vec,vocab_size): self.context_length = context_length self.storage = storage self.data = data self.num_of_samples = int(data.shape[0]) ...
src/batcher.py
import numpy as np from sklearn.externals import joblib import random class Batcher: def __init__(self,storage,data,batch_size,context_length,id2vec,vocab_size): self.context_length = context_length self.storage = storage self.data = data self.num_of_samples = int(data.shape[0]) ...
0.40251
0.274451
import os import hashlib from time import sleep from pathlib import Path from threading import Thread, RLock import cv2 import dhash from PIL import Image class Extractor: MAX_SAVE_PER_STREAM = 15 MAX_BLANK = 2 def __init__(self, class_names, ip_addresses, detector, output_dir, workers)...
ipscraper/extraction.py
import os import hashlib from time import sleep from pathlib import Path from threading import Thread, RLock import cv2 import dhash from PIL import Image class Extractor: MAX_SAVE_PER_STREAM = 15 MAX_BLANK = 2 def __init__(self, class_names, ip_addresses, detector, output_dir, workers)...
0.659624
0.203668
import requests # для выполнения запросов к сайту from lxml import html #, etry # необходимо для "расшифровки html" from typing import Any, Optional, NoReturn # дабы придерживаться стиля, # указывая типы переменных (а-ля TypeScript) (жаль тут типы проверяются только ide) def parse(title: str, author: str, p...
backend.py
import requests # для выполнения запросов к сайту from lxml import html #, etry # необходимо для "расшифровки html" from typing import Any, Optional, NoReturn # дабы придерживаться стиля, # указывая типы переменных (а-ля TypeScript) (жаль тут типы проверяются только ide) def parse(title: str, author: str, p...
0.343672
0.251941
import os import subprocess import zipfile import logging logger = logging.getLogger(__name__) def save_git_info(output_dir, repo_dir=None): os.makedirs(output_dir, exist_ok=True) if repo_dir is None: repo_dir = os.getcwd() # Get to the top level git dir process = subprocess.run("git rev-par...
baselines/src/utils/reproducibility.py
import os import subprocess import zipfile import logging logger = logging.getLogger(__name__) def save_git_info(output_dir, repo_dir=None): os.makedirs(output_dir, exist_ok=True) if repo_dir is None: repo_dir = os.getcwd() # Get to the top level git dir process = subprocess.run("git rev-par...
0.303525
0.090574
from django.shortcuts import render from rest_framework import generics from django.contrib.auth.models import User from .models import Category, Book, Product, Cart from .serializers import RegistrationSerializer, CategorySerializer, BookSerializer, ProductSerializer, UserSerializer, CartSerializer from rest_framework...
ApiApp/views.py
from django.shortcuts import render from rest_framework import generics from django.contrib.auth.models import User from .models import Category, Book, Product, Cart from .serializers import RegistrationSerializer, CategorySerializer, BookSerializer, ProductSerializer, UserSerializer, CartSerializer from rest_framework...
0.597725
0.074366
import argparse import inverted_index import time """ The function for create a new inverted index, based on the --dataset, --stop-words and --dump-to arguments from the arguments. Apart from creating a new InvertedIndex instance it will also save it as json to the file specified in -...
main.py
import argparse import inverted_index import time """ The function for create a new inverted index, based on the --dataset, --stop-words and --dump-to arguments from the arguments. Apart from creating a new InvertedIndex instance it will also save it as json to the file specified in -...
0.278061
0.207094
from collections import deque import re import sys import os try: from sublime_plugin import EventListener import sublime except ModuleNotFoundError: EventListener = type('EventListener', (object, ), {}) if sys.version_info > (3, 4): from typing import Tuple, List, Deque, Iterable # noqa: F401 def ...
symbol.py
from collections import deque import re import sys import os try: from sublime_plugin import EventListener import sublime except ModuleNotFoundError: EventListener = type('EventListener', (object, ), {}) if sys.version_info > (3, 4): from typing import Tuple, List, Deque, Iterable # noqa: F401 def ...
0.498535
0.130812
import io from adia.token import * from adia.tokenizer import Tokenizer from .helpers import raises def tokenize(string): tokenizer = Tokenizer() with io.StringIO(string) as f: while True: line = f.readline() for t in tokenizer.feedline(line): yield t.type, t...
tests/test_tokenizer.py
import io from adia.token import * from adia.tokenizer import Tokenizer from .helpers import raises def tokenize(string): tokenizer = Tokenizer() with io.StringIO(string) as f: while True: line = f.readline() for t in tokenizer.feedline(line): yield t.type, t...
0.574514
0.554109
import gi, os, sys import datetime from codes import * gi.require_version('Gtk', '3.0') from gi.repository import GLib, Gtk, GObject, GdkPixbuf, Gdk, Pango from pprint import pprint as pp WORKINGDIR = os.getcwd() class View(Gtk.Window): __gsignals__ = { 'send': (GObject.SignalFlags.RUN_FIRST, None, (str,...
GUI/View.py
import gi, os, sys import datetime from codes import * gi.require_version('Gtk', '3.0') from gi.repository import GLib, Gtk, GObject, GdkPixbuf, Gdk, Pango from pprint import pprint as pp WORKINGDIR = os.getcwd() class View(Gtk.Window): __gsignals__ = { 'send': (GObject.SignalFlags.RUN_FIRST, None, (str,...
0.31563
0.083628
data = { "gQq8MjHu1Jf": "LKL{S4Y_H3LLO_T0_G1T_OQUe6Ie2Ye}", "jvhwujZjYXF": "LKL{S4Y_H3LLO_T0_G1T_wh5Mu25Ahw}", "5ogaDpfsjQW": "LKL{S4Y_H3LLO_T0_G1T_OSDZfgsCEW}", "CQsvAk0t0Hp": "LKL{S4Y_H3LLO_T0_G1T_TqLezjAM21}", "hzunrOK4Wut": "LKL{S4Y_H3LLO_T0_G1T_IcV3goEcF3}", "NF6zqFQb9I8": "LKL{S4Y_H3LLO_T...
tasks/strange-archive/teams_and_flags.py
data = { "gQq8MjHu1Jf": "LKL{S4Y_H3LLO_T0_G1T_OQUe6Ie2Ye}", "jvhwujZjYXF": "LKL{S4Y_H3LLO_T0_G1T_wh5Mu25Ahw}", "5ogaDpfsjQW": "LKL{S4Y_H3LLO_T0_G1T_OSDZfgsCEW}", "CQsvAk0t0Hp": "LKL{S4Y_H3LLO_T0_G1T_TqLezjAM21}", "hzunrOK4Wut": "LKL{S4Y_H3LLO_T0_G1T_IcV3goEcF3}", "NF6zqFQb9I8": "LKL{S4Y_H3LLO_T...
0.347537
0.320396
from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.behaviors import ToggleButtonBehavior from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder from kivy.properties import ObjectProperty, StringProperty fr...
kivystudio/components/emulator_area/__init__.py
from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.behaviors import ToggleButtonBehavior from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder from kivy.properties import ObjectProperty, StringProperty fr...
0.395484
0.061003
from os.path import join import torch from kornia import geometry from ..agents.base import BaseModule from ..dataset import JointsConstructor from ..models.hourglass import HourglassModel from ..models.metrics import MPJPE from ..utils import average_loss class HourglassEstimator(BaseModule): """ Agent for...
experimenting/agents/hourglass_estimator.py
from os.path import join import torch from kornia import geometry from ..agents.base import BaseModule from ..dataset import JointsConstructor from ..models.hourglass import HourglassModel from ..models.metrics import MPJPE from ..utils import average_loss class HourglassEstimator(BaseModule): """ Agent for...
0.9252
0.395309
import time from django.utils.translation import ugettext_lazy as _ from docker import Client from horizon import tabs from openstack_dashboard import api from openstack_dashboard.dashboards.images.images_docker import tables as tbl_docker class Images: def __init__(self, imageId, size, repo, tag, created): ...
openstack_dashboard/dashboards/images/images_docker/tabs.py
import time from django.utils.translation import ugettext_lazy as _ from docker import Client from horizon import tabs from openstack_dashboard import api from openstack_dashboard.dashboards.images.images_docker import tables as tbl_docker class Images: def __init__(self, imageId, size, repo, tag, created): ...
0.331552
0.078395
from xml.dom.minidom import Document import os import os.path import xml.etree.ElementTree as ET from tqdm import tqdm opj = os.path.join txt_path = "submit.txt" xml_path = "inference_xml" img_name=[] if not os.path.exists(xml_path): os.mkdir(xml_path) def indent(elem, level=0): i = "\n" +...
submit_xml.py
from xml.dom.minidom import Document import os import os.path import xml.etree.ElementTree as ET from tqdm import tqdm opj = os.path.join txt_path = "submit.txt" xml_path = "inference_xml" img_name=[] if not os.path.exists(xml_path): os.mkdir(xml_path) def indent(elem, level=0): i = "\n" +...
0.083871
0.049245
import math import sys import random random.seed(0) def random_num(n): cnt = 1 a = [0] * n while cnt <= n: num = random.randint(sum(a), sum(a)+1000) a[cnt-1] = num cnt += 1 return a def generate_key(n): print("Input a list of n superincreasing integers, separated by commas...
Merkle-Hellman Knapsack Cryptosystem.py
import math import sys import random random.seed(0) def random_num(n): cnt = 1 a = [0] * n while cnt <= n: num = random.randint(sum(a), sum(a)+1000) a[cnt-1] = num cnt += 1 return a def generate_key(n): print("Input a list of n superincreasing integers, separated by commas...
0.10697
0.314577
import os import glob import random import numpy as np import torch import torch.utils.data as data from PIL import Image, ImageOps, ImageFilter __all__ = ['ycbSegmentation'] class ycbSegmentation(data.Dataset): BASE_DIR = 'YCB-Video' NUM_CLASS = 21+1 # 13 object and background def __init__(self, root=...
data_loader/ycb.py
import os import glob import random import numpy as np import torch import torch.utils.data as data from PIL import Image, ImageOps, ImageFilter __all__ = ['ycbSegmentation'] class ycbSegmentation(data.Dataset): BASE_DIR = 'YCB-Video' NUM_CLASS = 21+1 # 13 object and background def __init__(self, root=...
0.616705
0.270396
import torch from operations.losses.image import LPIPS from torch import Tensor from torchmetrics import Metric from torch.nn import functional as F def psnr(input: Tensor, target: Tensor, maximum: Tensor) -> Tensor: """ Computes the PSNR between two images. :param input: [*, C, H, W] :param target: ...
operations/metrics/image.py
import torch from operations.losses.image import LPIPS from torch import Tensor from torchmetrics import Metric from torch.nn import functional as F def psnr(input: Tensor, target: Tensor, maximum: Tensor) -> Tensor: """ Computes the PSNR between two images. :param input: [*, C, H, W] :param target: ...
0.892786
0.725187
import pandas as pd import hiplot as hip # ----------------------------- # Load data # ----------------------------- # Sample data data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4...
examples/hiplot-examples/plot_main02.py
import pandas as pd import hiplot as hip # ----------------------------- # Load data # ----------------------------- # Sample data data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4...
0.665737
0.275221
""" Web Application Firewall Binding """ import json from ctypes import POINTER, Structure, byref, c_bool, c_char_p, c_int, c_size_t from . import get_lib from ._compat import UNICODE_CLASS from .input import C_PWArgs, PWArgs PW_ERR_INTERNAL = -6 PW_ERR_TIMEOUT = -5 PW_ERR_INVALID_CALL = -4 PW_ERR_INVALID_RULE = -3 P...
exercise/venv/lib/python3.7/site-packages/sq_native/waf.py
""" Web Application Firewall Binding """ import json from ctypes import POINTER, Structure, byref, c_bool, c_char_p, c_int, c_size_t from . import get_lib from ._compat import UNICODE_CLASS from .input import C_PWArgs, PWArgs PW_ERR_INTERNAL = -6 PW_ERR_TIMEOUT = -5 PW_ERR_INVALID_CALL = -4 PW_ERR_INVALID_RULE = -3 P...
0.58676
0.210097
import pytest from sasctl.utils.decorators import deprecated, experimental, ExperimentalWarning def test_deprecated(): """Function can be deprecated with @deprecated(version=XX).""" @deprecated(version=1.2) def old_function(a): """Do old stuff. Parameters ---------- a : ...
tests/unit/test_decorators.py
import pytest from sasctl.utils.decorators import deprecated, experimental, ExperimentalWarning def test_deprecated(): """Function can be deprecated with @deprecated(version=XX).""" @deprecated(version=1.2) def old_function(a): """Do old stuff. Parameters ---------- a : ...
0.733643
0.460228
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from . import ( CloudProvider, CloudEnvironment, CloudEnvironmentConfig, ) from ..util import ( find_executable, display, ConfigParser, ApplicationError, ) from ..docker_util import ( do...
venv/lib/python3.6/site-packages/ansible_test/_internal/cloud/vcenter.py
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from . import ( CloudProvider, CloudEnvironment, CloudEnvironmentConfig, ) from ..util import ( find_executable, display, ConfigParser, ApplicationError, ) from ..docker_util import ( do...
0.568655
0.081923
import datetime import random from typing import List import pandas as pd from dateutil.utils import today from numpy import array_split from toloka.client import TolokaClient from toloka.client.actions import RestrictionV2 from toloka.client.batch_create_results import TaskSuiteBatchCreateResult from toloka.client.co...
results/ytoloka.py
import datetime import random from typing import List import pandas as pd from dateutil.utils import today from numpy import array_split from toloka.client import TolokaClient from toloka.client.actions import RestrictionV2 from toloka.client.batch_create_results import TaskSuiteBatchCreateResult from toloka.client.co...
0.494629
0.153835
import sqlalchemy from sql_alchemy import banco from sqlalchemy import types class PetModel(banco.Model): __tablename__ = 'TB_PET' cadastro_pet = banco.Column(banco.String(10), primary_key=True) nome = banco.Column(banco.String(80)) data_nascimento = banco.Column(types.Date()) raca = banco.Column(ba...
models/pet.py
import sqlalchemy from sql_alchemy import banco from sqlalchemy import types class PetModel(banco.Model): __tablename__ = 'TB_PET' cadastro_pet = banco.Column(banco.String(10), primary_key=True) nome = banco.Column(banco.String(80)) data_nascimento = banco.Column(types.Date()) raca = banco.Column(ba...
0.294418
0.292791
from tests.utils import CustomClient def test_health_check(client: CustomClient): response = client.query( "/graphql", query=""" query q { healthCheck } """, ) assert response.data == {"data": {"healthCheck": "schema load success"}} def ...
tests/e2e/user/test_graphql.py
from tests.utils import CustomClient def test_health_check(client: CustomClient): response = client.query( "/graphql", query=""" query q { healthCheck } """, ) assert response.data == {"data": {"healthCheck": "schema load success"}} def ...
0.701917
0.388009
import xlrd import pandas as pd from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV, StratifiedKFold from sklearn.metrics import confusion_matrix from Utils import * from Model import FeatureReduction """----------------------User Configuration----------------------""" n_train = 1...
Transferability.py
import xlrd import pandas as pd from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV, StratifiedKFold from sklearn.metrics import confusion_matrix from Utils import * from Model import FeatureReduction """----------------------User Configuration----------------------""" n_train = 1...
0.61115
0.34161
import numpy as np from acconeer.exptool import configs, utils from acconeer.exptool.clients import SocketClient, SPIClient, UARTClient from acconeer.exptool.mpl_process import FigureUpdater, PlotProccessDiedException, PlotProcess def main(): args = utils.ExampleArgumentParser().parse_args() utils.config_log...
examples/plotting/plot_with_mpl_process.py
import numpy as np from acconeer.exptool import configs, utils from acconeer.exptool.clients import SocketClient, SPIClient, UARTClient from acconeer.exptool.mpl_process import FigureUpdater, PlotProccessDiedException, PlotProcess def main(): args = utils.ExampleArgumentParser().parse_args() utils.config_log...
0.606498
0.250357
import pytest from schafkopf.game_modes import NO_GAME, PARTNER_MODE, WENZ, SOLO from schafkopf.players.mc_node import MCNode from schafkopf.suits import SUITS, LEAVES @pytest.fixture def next_state(player_hands_partner): leading_player = 0 current_player = 1 mode_proposals = [(NO_GAME, None)] game_m...
tests/test_mc_node.py
import pytest from schafkopf.game_modes import NO_GAME, PARTNER_MODE, WENZ, SOLO from schafkopf.players.mc_node import MCNode from schafkopf.suits import SUITS, LEAVES @pytest.fixture def next_state(player_hands_partner): leading_player = 0 current_player = 1 mode_proposals = [(NO_GAME, None)] game_m...
0.538498
0.39289
from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r""" name: tss author: <NAME> (@amigus) <<EMAIL>> short_description: Get secrets from Thycotic Secret Server version_added: 1.0.0 description: - Uses the Thycotic Secret Server Python SDK to get Secrets from Secr...
venv/lib/python3.6/site-packages/ansible_collections/community/general/plugins/lookup/tss.py
from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r""" name: tss author: <NAME> (@amigus) <<EMAIL>> short_description: Get secrets from Thycotic Secret Server version_added: 1.0.0 description: - Uses the Thycotic Secret Server Python SDK to get Secrets from Secr...
0.725065
0.169269
import os import argparse import numpy as np import glob import imageio import scipy.io as sio from plyfile import PlyElement, PlyData from parse import parse from sklearn.neighbors import NearestNeighbors as nnbrs from scipy.spatial import KDTree from collections import Counter from multiprocessing import Pool import ...
SPConvNets/datasets/preprocess/run_keypoint.py
import os import argparse import numpy as np import glob import imageio import scipy.io as sio from plyfile import PlyElement, PlyData from parse import parse from sklearn.neighbors import NearestNeighbors as nnbrs from scipy.spatial import KDTree from collections import Counter from multiprocessing import Pool import ...
0.461017
0.197019
from utils import (NORTH, EAST, SOUTH, WEST) from numpy.random import RandomState class Car: def __init__(self, orientation, start_pos, end_pos, active=True, p_turn=0.5, turn_ctr=0, switch_ctr=0, asshole_factor=0, asshole_ctr=0): self.orientation = orientation self.cur_pos = star...
car.py
from utils import (NORTH, EAST, SOUTH, WEST) from numpy.random import RandomState class Car: def __init__(self, orientation, start_pos, end_pos, active=True, p_turn=0.5, turn_ctr=0, switch_ctr=0, asshole_factor=0, asshole_ctr=0): self.orientation = orientation self.cur_pos = star...
0.857828
0.596345
from threading import Lock, Thread import logging import re import queue import time class Component(object): ''' Components are responsible for monitoring the underlying physical component, updating dependent properties associated with the component, and responding to updates of those properties by sending...
pyIOT/Component.py
from threading import Lock, Thread import logging import re import queue import time class Component(object): ''' Components are responsible for monitoring the underlying physical component, updating dependent properties associated with the component, and responding to updates of those properties by sending...
0.853593
0.333178
import contextlib import hashlib import json import random import flowws from flowws import Argument as Arg import keras_gtar import numpy as np import tensorflow as tf from tensorflow import keras try: import tensorflow_addons as tfa except ImportError: tfa = None OPTIMIZER_MAP = dict( adadelta='Adadelta...
flowws_keras_experimental/Train.py
import contextlib import hashlib import json import random import flowws from flowws import Argument as Arg import keras_gtar import numpy as np import tensorflow as tf from tensorflow import keras try: import tensorflow_addons as tfa except ImportError: tfa = None OPTIMIZER_MAP = dict( adadelta='Adadelta...
0.61682
0.246635
from .objbase import MeshObject, ChebiObject, EntrezObject, MeshESearchObject __all__ = ['BasicParser', 'MeshSubjectIDParser', 'MeshObjectParser', 'ChebiObjectParser', 'EntrezObjectParser', 'MeshESearchObjectParser'] class BasicParser(object): def parse(self, resp): return resp class MeshSu...
chement/parser.py
from .objbase import MeshObject, ChebiObject, EntrezObject, MeshESearchObject __all__ = ['BasicParser', 'MeshSubjectIDParser', 'MeshObjectParser', 'ChebiObjectParser', 'EntrezObjectParser', 'MeshESearchObjectParser'] class BasicParser(object): def parse(self, resp): return resp class MeshSu...
0.183191
0.120413
import cv2 import numpy as np import tensorflow as tf grid_h = 45 grid_w = 60 # # original paper anchors # wandhG = np.array([[100.0, 100.0], [300.0, 300.0], [500.0, 500.0], # [200.0, 100.0], [370.0, 185.0], [440.0, 220.0], # [100.0, 200.0], [185.0, 370.0], [220.0, 440.0]]) # k...
4-Object_Detection/RPN/utils.py
import cv2 import numpy as np import tensorflow as tf grid_h = 45 grid_w = 60 # # original paper anchors # wandhG = np.array([[100.0, 100.0], [300.0, 300.0], [500.0, 500.0], # [200.0, 100.0], [370.0, 185.0], [440.0, 220.0], # [100.0, 200.0], [185.0, 370.0], [220.0, 440.0]]) # k...
0.617974
0.594316
__all__ = ["icrsFromGal"] import numpy # Constants # _RMat is the rotation matrix to convert galactic to ICRS conversion matrix # (the data is for cpnversion in the other direction, # but transposing a rotation matrix inverts it) _RMat = numpy.transpose(numpy.array (( (-0.054875539726, -0.873437108010, -0.48...
python/opscore/RO/Astro/Cnv/ICRSFromGal.py
__all__ = ["icrsFromGal"] import numpy # Constants # _RMat is the rotation matrix to convert galactic to ICRS conversion matrix # (the data is for cpnversion in the other direction, # but transposing a rotation matrix inverts it) _RMat = numpy.transpose(numpy.array (( (-0.054875539726, -0.873437108010, -0.48...
0.723895
0.573977
import os import torch from functools import partial from collections.abc import Hashable from torch.utils.data import DataLoader from .base import BaseRuntime from ..nn import named_penalties from ..priors import ImplicitSlicePrior from ..priors.implicit import ImplicitPrior from ..source import KernelDataset f...
markovdwp/runtime/dwp.py
import os import torch from functools import partial from collections.abc import Hashable from torch.utils.data import DataLoader from .base import BaseRuntime from ..nn import named_penalties from ..priors import ImplicitSlicePrior from ..priors.implicit import ImplicitPrior from ..source import KernelDataset f...
0.88173
0.543287
import numpy as np import numexpr as ne import argparse, pickle, os.path from collections import OrderedDict from datasets import get_data_generator from class_hierarchy import ClassHierarchy try: from tqdm import tqdm except ImportError: def tqdm(it, **kwargs): return it METRICS ...
evaluate_retrieval.py
import numpy as np import numexpr as ne import argparse, pickle, os.path from collections import OrderedDict from datasets import get_data_generator from class_hierarchy import ClassHierarchy try: from tqdm import tqdm except ImportError: def tqdm(it, **kwargs): return it METRICS ...
0.66072
0.289121
import json import ssl from http.client import HTTPSConnection, HTTPConnection from time import time from urllib.parse import parse_qsl, urlparse, urlencode class Request: def __init__(self, wsgi_environ): self.create_time = time() self.body = None self._wsgi_environ = wsgi_environ ...
evernotebot/util/http.py
import json import ssl from http.client import HTTPSConnection, HTTPConnection from time import time from urllib.parse import parse_qsl, urlparse, urlencode class Request: def __init__(self, wsgi_environ): self.create_time = time() self.body = None self._wsgi_environ = wsgi_environ ...
0.226869
0.10683
import os import pkg_resources import pytest from six import StringIO from req_compile.cmdline import compile_main, _create_input_reqs from req_compile.containers import DistInfo from req_compile.repos.findlinks import FindLinksRepository from req_compile.repos.pypi import PyPIRepository from req_compile.repos.solu...
tests/test_cmdline.py
import os import pkg_resources import pytest from six import StringIO from req_compile.cmdline import compile_main, _create_input_reqs from req_compile.containers import DistInfo from req_compile.repos.findlinks import FindLinksRepository from req_compile.repos.pypi import PyPIRepository from req_compile.repos.solu...
0.472927
0.207295
import os from cryptojwt.jwk import pems_to_x5c from cryptojwt.jwk import x5c_to_pems from cryptojwt.jws.jws import factory from cryptojwt.key_jar import build_keyjar from oidcmsg.exception import MissingPage import pytest import requests import responses from fedservice.entity_statement.collect import Collector from...
tests/test_04_collect.py
import os from cryptojwt.jwk import pems_to_x5c from cryptojwt.jwk import x5c_to_pems from cryptojwt.jws.jws import factory from cryptojwt.key_jar import build_keyjar from oidcmsg.exception import MissingPage import pytest import requests import responses from fedservice.entity_statement.collect import Collector from...
0.529993
0.500488
import os import numpy as np import hyperspy.api as hs from pyiron_base._tests import TestWithCleanProject import pyiron_experimental class TestHSLineProfiles(TestWithCleanProject): @classmethod def setUpClass(cls): super().setUpClass() data = hs.load(os.path.join(cls.project.path, '../../...
tests/test_hs_line_profiles.py
import os import numpy as np import hyperspy.api as hs from pyiron_base._tests import TestWithCleanProject import pyiron_experimental class TestHSLineProfiles(TestWithCleanProject): @classmethod def setUpClass(cls): super().setUpClass() data = hs.load(os.path.join(cls.project.path, '../../...
0.516352
0.683987
import unittest import os import shutil import sys from file_number_rename.file_rename import rename_files, rename_file_name, parse_arguments class NumberRenameTestCase(unittest.TestCase): def setUp(self): self.clean_up_test_dir() file_name = "_test_file.txt" def touch(self, file_path, times=No...
file_number_rename_test/file_rename_test.py
import unittest import os import shutil import sys from file_number_rename.file_rename import rename_files, rename_file_name, parse_arguments class NumberRenameTestCase(unittest.TestCase): def setUp(self): self.clean_up_test_dir() file_name = "_test_file.txt" def touch(self, file_path, times=No...
0.289071
0.332229
from psychopy import visual, core, event from psychopy.visual import ImageStim, TextStim, Circle from random import randint from experiment_objects import ImagePair, Image import os import csv """ I'M NOT GOING TO COMMENT THIS THROUGHOUT, SO THIS IS HOW ANIMATION WORKS: for frameN in range(number_of_seconds * monitor...
training.py
from psychopy import visual, core, event from psychopy.visual import ImageStim, TextStim, Circle from random import randint from experiment_objects import ImagePair, Image import os import csv """ I'M NOT GOING TO COMMENT THIS THROUGHOUT, SO THIS IS HOW ANIMATION WORKS: for frameN in range(number_of_seconds * monitor...
0.506591
0.422147
import json import requests from sentry.plugins.bases.notify import NotificationPlugin import sentry_feishu from .forms import FeiShuOptionsForm class FeiShuPlugin(NotificationPlugin): """ Sentry plugin to send error counts to FeiShu. """ author = 'yjy' author_url = 'https://github.com/DC-ET/sen...
src/sentry_feishu/plugin.py
import json import requests from sentry.plugins.bases.notify import NotificationPlugin import sentry_feishu from .forms import FeiShuOptionsForm class FeiShuPlugin(NotificationPlugin): """ Sentry plugin to send error counts to FeiShu. """ author = 'yjy' author_url = 'https://github.com/DC-ET/sen...
0.522202
0.180287
from PIL import Image, ImageDraw import numpy import face_recognition class ImageProcessor: "Contains sevelral methods to processes into finding faces within" def __init__(self, image=None, nparray=None, filename=None, processing=1024): """class constructor The constructor requires either the f...
imageProcessor.py
from PIL import Image, ImageDraw import numpy import face_recognition class ImageProcessor: "Contains sevelral methods to processes into finding faces within" def __init__(self, image=None, nparray=None, filename=None, processing=1024): """class constructor The constructor requires either the f...
0.893347
0.490236
import solver.solutionInstance as solutionInstance import numpy as np import random def swapTwoClosePeriodsPairs(self: solutionInstance.SolutionInstance): # Turned out not to be a good neighbour generator meetByPeriodByDayByLocalBySubjectByGroup = np.copy(self.meetByPeriodByDayByLocalBySubjectByGroup) firstDa...
Simulated annealing/solver/neighbourGenerators/swapSpecialistTwoCloseMeetingPairs.py
import solver.solutionInstance as solutionInstance import numpy as np import random def swapTwoClosePeriodsPairs(self: solutionInstance.SolutionInstance): # Turned out not to be a good neighbour generator meetByPeriodByDayByLocalBySubjectByGroup = np.copy(self.meetByPeriodByDayByLocalBySubjectByGroup) firstDa...
0.487551
0.35081
from PyQt5.QtWidgets import QGraphicsView from datanodes.core.utils import dumpException from datanodes.core.node_edge import Edge, EDGE_BEZIER, EDGE_DIRECT from datanodes.graphics.graphics_socket import GraphicsSocket from datanodes.core.node_node import SOCKET_INPUT, SOCKET_OUTPUT DEBUG = False class EdgeDragging: ...
datanodes/core/node_edge_dragging.py
from PyQt5.QtWidgets import QGraphicsView from datanodes.core.utils import dumpException from datanodes.core.node_edge import Edge, EDGE_BEZIER, EDGE_DIRECT from datanodes.graphics.graphics_socket import GraphicsSocket from datanodes.core.node_node import SOCKET_INPUT, SOCKET_OUTPUT DEBUG = False class EdgeDragging: ...
0.347869
0.21212
from tkinter import * import numpy as np from scipy.spatial.distance import euclidean # Creating an empty Tkinter window root = Tk() # Setting the Tkinter window properties root.wm_title('My Universe') canvas = Canvas(root, width=700, height=700, bg='black') canvas.grid(row=0, column=0) G = 0.01 # Gravitational co...
N-Body Simulation/main.py
from tkinter import * import numpy as np from scipy.spatial.distance import euclidean # Creating an empty Tkinter window root = Tk() # Setting the Tkinter window properties root.wm_title('My Universe') canvas = Canvas(root, width=700, height=700, bg='black') canvas.grid(row=0, column=0) G = 0.01 # Gravitational co...
0.756088
0.557665
from django.urls import reverse from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APITestCase, APIClient from .models import Service, Bearer class ServiceTest(APITestCase): def setUp(self): self.client = APIClient() self.user = User.obj...
radioepg/tests.py
from django.urls import reverse from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APITestCase, APIClient from .models import Service, Bearer class ServiceTest(APITestCase): def setUp(self): self.client = APIClient() self.user = User.obj...
0.488527
0.270667
import os from ioformat import read_text_file import mess_io.writer PATH = os.path.dirname(os.path.realpath(__file__)) SPC1_LABEL = 'Mol1' SPC2_LABEL = 'Mol1' WELL_LABEL = 'W1' BIMOL_LABEL = 'P1' TS_LABEL = 'B1' # Data Strings MOL_MESS_STR = """RRHO Core RigidRotor SymmetryFactor 1.0 End Geometry[...
autoio/mess_io/tests/test_write_rxnchan.py
import os from ioformat import read_text_file import mess_io.writer PATH = os.path.dirname(os.path.realpath(__file__)) SPC1_LABEL = 'Mol1' SPC2_LABEL = 'Mol1' WELL_LABEL = 'W1' BIMOL_LABEL = 'P1' TS_LABEL = 'B1' # Data Strings MOL_MESS_STR = """RRHO Core RigidRotor SymmetryFactor 1.0 End Geometry[...
0.426322
0.246573
from datetime import datetime from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from request.managers import RequestManager from request.utils import HTTP_STATUS_CODES class Request(models.Model): # Response infomation response = ...
request/models.py
from datetime import datetime from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from request.managers import RequestManager from request.utils import HTTP_STATUS_CODES class Request(models.Model): # Response infomation response = ...
0.417746
0.049474
import textwrap from astroid import nodes from astroid import builder # The name of the transient function that is used to # wrap expressions to be extracted when calling # extract_node. _TRANSIENT_FUNCTION = '__' # The comment used to select a statement to be extracted # when calling extract_node. _STATEMENT_SELECT...
venv/lib/python2.7/site-packages/astroid/test_utils.py
import textwrap from astroid import nodes from astroid import builder # The name of the transient function that is used to # wrap expressions to be extracted when calling # extract_node. _TRANSIENT_FUNCTION = '__' # The comment used to select a statement to be extracted # when calling extract_node. _STATEMENT_SELECT...
0.771413
0.503357
from django.db import models from django.contrib.auth.models import User class GuideBookManager(models.Manager): def get_guide_book(self,id): return super(GuideBookManager, self).get_queryset().filter(book_guide=id).order_by('-average') class Book(models.Model): objec...
backend/Backendapi/bookdata/models.py
from django.db import models from django.contrib.auth.models import User class GuideBookManager(models.Manager): def get_guide_book(self,id): return super(GuideBookManager, self).get_queryset().filter(book_guide=id).order_by('-average') class Book(models.Model): objec...
0.368747
0.134094
from django.test import override_settings from django.urls import reverse_lazy from model_bakery import baker from rest_framework import status from rest_framework.test import APITestCase from hypha.apply.funds.models import ScreeningStatus from hypha.apply.funds.tests.factories.models import ApplicationSubmissionFact...
hypha/apply/api/v1/screening/tests/test_views.py
from django.test import override_settings from django.urls import reverse_lazy from model_bakery import baker from rest_framework import status from rest_framework.test import APITestCase from hypha.apply.funds.models import ScreeningStatus from hypha.apply.funds.tests.factories.models import ApplicationSubmissionFact...
0.48121
0.106412
import pytest import requests_mock import requests.exceptions from dteenergybridge import DteEnergyBridge from dteenergybridge import exceptions def test_invalid_bridge_version(): """Tests to make sure constructor throws on invalid bridge_version""" with pytest.raises(exceptions.InvalidArgumentError): ...
tests/test_dteenergybridge.py
import pytest import requests_mock import requests.exceptions from dteenergybridge import DteEnergyBridge from dteenergybridge import exceptions def test_invalid_bridge_version(): """Tests to make sure constructor throws on invalid bridge_version""" with pytest.raises(exceptions.InvalidArgumentError): ...
0.589007
0.374762
import os,re,webbrowser from itertools import chain from collections import Counter from gensim.summarization import textcleaner #Define court object class court: def __init__(self, cases=[]): assert isinstance(cases,list) if len(cases)>0: assert isinstance(cases[0],str) self.cases=cases self....
InfoExtract/main.py
import os,re,webbrowser from itertools import chain from collections import Counter from gensim.summarization import textcleaner #Define court object class court: def __init__(self, cases=[]): assert isinstance(cases,list) if len(cases)>0: assert isinstance(cases[0],str) self.cases=cases self....
0.186243
0.255907
from keras.layers import Conv2D, Dense, MaxPooling2D, AveragePooling2D, BatchNormalization from keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D from utils.keras_sparisity_regularization import SparsityRegularization from copy import deepcopy import numpy as np def freeze_SR_layer(model, prune_rate=0.):...
utils/channel_pruning.py
from keras.layers import Conv2D, Dense, MaxPooling2D, AveragePooling2D, BatchNormalization from keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D from utils.keras_sparisity_regularization import SparsityRegularization from copy import deepcopy import numpy as np def freeze_SR_layer(model, prune_rate=0.):...
0.491456
0.501587
import serial import enum class PumpDirection(enum.Enum): Infuse = 'INF' Refill = 'REF' Reverse = 'REV' class PumpMode(enum.Enum): AutoStop = 'AUT' Proportional = 'PRO' Continuous = 'CON' class PumpState(enum.Enum): Stopped = enum.auto() Infusing = enum.auto() Refilling = enum.au...
storm_control/sc_hardware/harvardApparatus/pump33.py
import serial import enum class PumpDirection(enum.Enum): Infuse = 'INF' Refill = 'REF' Reverse = 'REV' class PumpMode(enum.Enum): AutoStop = 'AUT' Proportional = 'PRO' Continuous = 'CON' class PumpState(enum.Enum): Stopped = enum.auto() Infusing = enum.auto() Refilling = enum.au...
0.530966
0.183118
import argparse import json import logging import re import sys import srt import datetime def make_subs_fixed(response, bin_size=3000): """ Create subtitles that fit in fixed size bins. This is the method used by the original Medium article. The produced output should be identical, minus a few ro...
gcsubs/gcsconvert.py
import argparse import json import logging import re import sys import srt import datetime def make_subs_fixed(response, bin_size=3000): """ Create subtitles that fit in fixed size bins. This is the method used by the original Medium article. The produced output should be identical, minus a few ro...
0.31944
0.316092
import urllib2 from django.core.paginator import Paginator, EmptyPage, InvalidPage, PageNotAnInteger from django.template.response import TemplateResponse from django.views.defaults import page_not_found from common.login_required_mixin import LoginRequiredMixin from reducer.forms import ReduceURLForm from django.views...
reducer/views.py
import urllib2 from django.core.paginator import Paginator, EmptyPage, InvalidPage, PageNotAnInteger from django.template.response import TemplateResponse from django.views.defaults import page_not_found from common.login_required_mixin import LoginRequiredMixin from reducer.forms import ReduceURLForm from django.views...
0.244273
0.061199
from private.constants_private import endpoint, sapi_token from qubo.qubo import Qubo # Scenario 1 variables = ['x14', 'x15', 'x16', 'x17', 'x23', 'x24', 'x25', 'x26', 'x27', 'x28', 'x31', 'x32', 'x34', 'x35', 'x36', 'x37', 'x38', 'x40', 'x41', 'x42', 'x43', 'x44', 'x45', 'x46', ...
main.py
from private.constants_private import endpoint, sapi_token from qubo.qubo import Qubo # Scenario 1 variables = ['x14', 'x15', 'x16', 'x17', 'x23', 'x24', 'x25', 'x26', 'x27', 'x28', 'x31', 'x32', 'x34', 'x35', 'x36', 'x37', 'x38', 'x40', 'x41', 'x42', 'x43', 'x44', 'x45', 'x46', ...
0.417746
0.31127
from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import inspect import ga4gh.exceptions as exceptions import ga4gh.frontend as frontend import ga4gh.protocol as protocol class TestExceptionHandler(unittest.TestCase): """ Test that ...
tests/unit/test_exceptions.py
from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import inspect import ga4gh.exceptions as exceptions import ga4gh.frontend as frontend import ga4gh.protocol as protocol class TestExceptionHandler(unittest.TestCase): """ Test that ...
0.789842
0.264548
def create_taxa_mask(TaXon_table_xlsx, mask, taxon_mask): import pandas as pd from pandas import DataFrame from pathlib import Path TaXon_table_xlsx = Path(TaXon_table_xlsx) TaXon_table_xlsx = pd.ExcelFile(TaXon_table_xlsx) data = pd.read_excel(TaXon_table_xlsx, 'TaXon table', header=0) a...
taxontabletools/taxon_table_filtering.py
def create_taxa_mask(TaXon_table_xlsx, mask, taxon_mask): import pandas as pd from pandas import DataFrame from pathlib import Path TaXon_table_xlsx = Path(TaXon_table_xlsx) TaXon_table_xlsx = pd.ExcelFile(TaXon_table_xlsx) data = pd.read_excel(TaXon_table_xlsx, 'TaXon table', header=0) a...
0.324878
0.563378
import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("components", "0001_initial"), ("cases", "0024_auto_20200525_0634"), ("algorithms", "0025_algorithmimage_queue_override"), ] operations = [ m...
app/grandchallenge/algorithms/migrations/0026_auto_20200622_1314.py
import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("components", "0001_initial"), ("cases", "0024_auto_20200525_0634"), ("algorithms", "0025_algorithmimage_queue_override"), ] operations = [ m...
0.625781
0.220112
from apitools.base.protorpclite import messages as _messages from apitools.base.py import encoding from apitools.base.py import extra_types package = 'gkehub' class AuditConfig(_messages.Message): r"""Specifies the audit configuration for a service. The configuration determines which permission types are logge...
lib/googlecloudsdk/third_party/apis/gkehub/v1alpha1/gkehub_v1alpha1_messages.py
from apitools.base.protorpclite import messages as _messages from apitools.base.py import encoding from apitools.base.py import extra_types package = 'gkehub' class AuditConfig(_messages.Message): r"""Specifies the audit configuration for a service. The configuration determines which permission types are logge...
0.735167
0.343232
import optparse import os, sys import re def readATGC_buffer(buf, s, e): """ read numbers of A/T/G/C btw start and end in the path :param buf: fasta buffer with \n removed :param s: start position (inclusive), one based index :param e: end position (inclusive), one based index :return: numbers ...
PhD_python_script/exon.py
import optparse import os, sys import re def readATGC_buffer(buf, s, e): """ read numbers of A/T/G/C btw start and end in the path :param buf: fasta buffer with \n removed :param s: start position (inclusive), one based index :param e: end position (inclusive), one based index :return: numbers ...
0.184143
0.392803
import random import string import escape_helpers import helpers import numpy as np import json relation_map = {"uuid": "mu:uuid", "name": "ext:name", "path": "ext:path", "description": "ext:description", "note": "ext:note", "disable_proce...
column.py
import random import string import escape_helpers import helpers import numpy as np import json relation_map = {"uuid": "mu:uuid", "name": "ext:name", "path": "ext:path", "description": "ext:description", "note": "ext:note", "disable_proce...
0.508544
0.158435
from __future__ import unicode_literals from functools import wraps from django.http.response import HttpResponseRedirect from django.template.response import TemplateResponse from django.utils.translation import ugettext_lazy as _ from .utils import object_tool_context, OBJECTTOOL_ALLOWED_PROPERTIES def link(url,...
object_tool/shortcuts.py
from __future__ import unicode_literals from functools import wraps from django.http.response import HttpResponseRedirect from django.template.response import TemplateResponse from django.utils.translation import ugettext_lazy as _ from .utils import object_tool_context, OBJECTTOOL_ALLOWED_PROPERTIES def link(url,...
0.585694
0.052376
import torch from survae.transforms.bijections import Bijection class CouplingBijection(Bijection): """Transforms each input variable with an invertible elementwise bijection. This input variables are split in two parts. The second part is transformed conditioned on the first part. The coupling network t...
survae/transforms/bijections/coupling/coupling.py
import torch from survae.transforms.bijections import Bijection class CouplingBijection(Bijection): """Transforms each input variable with an invertible elementwise bijection. This input variables are split in two parts. The second part is transformed conditioned on the first part. The coupling network t...
0.93396
0.757234
import requests import json from trainmodel import Learning import configparser import datetime def update_config(param, model_name): config = configparser.ConfigParser() config.read('./configs/default.ini') configs = config["default"] new_configs = configparser.ConfigParser() new_configs["default"...
src/Python/ResNet/resnet-test/run_training.py
import requests import json from trainmodel import Learning import configparser import datetime def update_config(param, model_name): config = configparser.ConfigParser() config.read('./configs/default.ini') configs = config["default"] new_configs = configparser.ConfigParser() new_configs["default"...
0.348534
0.146423
from __future__ import absolute_import from __future__ import unicode_literals from pyhive import trino from pyhive.tests.dbapi_test_case import with_cursor, with_complex_processing_cursor from pyhive.tests.test_presto import TestPresto import datetime _HOST = 'localhost' _PORT = '18080' class TestTrino(TestPresto...
pyhive/tests/test_trino.py
from __future__ import absolute_import from __future__ import unicode_literals from pyhive import trino from pyhive.tests.dbapi_test_case import with_cursor, with_complex_processing_cursor from pyhive.tests.test_presto import TestPresto import datetime _HOST = 'localhost' _PORT = '18080' class TestTrino(TestPresto...
0.467818
0.298888
import functools import argparse import logging import random import numpy as np import torch from data_search import load_dir from search import LocalSearch from multiprocessing import Pool logger = logging.getLogger(__name__) def flip_update(fp, flips, max_flips): mf, af, xf, sv = fp med = np.median(flip...
code/evaluate.py
import functools import argparse import logging import random import numpy as np import torch from data_search import load_dir from search import LocalSearch from multiprocessing import Pool logger = logging.getLogger(__name__) def flip_update(fp, flips, max_flips): mf, af, xf, sv = fp med = np.median(flip...
0.404507
0.201283
import m5 from m5.params import * from m5.objects import * from BaseTopology import SimpleTopology from TikzTopology import TikzTopology from TopologyToDSENT import TopologyToDSENT class FlattenedButterfly(SimpleTopology): # Creates a generic FlattenedButterfly topology assuming an equal number of cache # an...
configs/topologies/FlattenedButterfly.py
import m5 from m5.params import * from m5.objects import * from BaseTopology import SimpleTopology from TikzTopology import TikzTopology from TopologyToDSENT import TopologyToDSENT class FlattenedButterfly(SimpleTopology): # Creates a generic FlattenedButterfly topology assuming an equal number of cache # an...
0.576184
0.284748
import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.ext import declarative from sqlalchemy.dialects.mysql import VARCHAR from sqlalchemy.dialects.mysql import TINYINT from sqlalchemy.dialects.mysql import SMALLINT from sqlalchemy.dialects.mysql import INTEGER from sqlalchemy.dialects.mysql import CHAR f...
gogamechen3/models.py
import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.ext import declarative from sqlalchemy.dialects.mysql import VARCHAR from sqlalchemy.dialects.mysql import TINYINT from sqlalchemy.dialects.mysql import SMALLINT from sqlalchemy.dialects.mysql import INTEGER from sqlalchemy.dialects.mysql import CHAR f...
0.191063
0.101947
import sys, socket, time, select, dw1000_regs as regs from dw1000_regs import Reg, msdelay RESET_VAL = 0xff ANS_VAL = 0xaa SOCK_TIMEOUT = 0.05 MAX_DATALEN = 2048 IRQ_VAL = 0xfe SEQLEN = 2 RETRIES = 3 resetime = time.time() # Class for an SPI interfa...
dw1000_spi.py
import sys, socket, time, select, dw1000_regs as regs from dw1000_regs import Reg, msdelay RESET_VAL = 0xff ANS_VAL = 0xaa SOCK_TIMEOUT = 0.05 MAX_DATALEN = 2048 IRQ_VAL = 0xfe SEQLEN = 2 RETRIES = 3 resetime = time.time() # Class for an SPI interfa...
0.224991
0.060891
from xml.etree.cElementTree import parse, Element, ElementTree, dump from os import walk from os.path import join from optparse import OptionParser description = "Update the master package.config from individual project ones." command_group = "Developer tools" # Snippet used from the ElementTree documentation. # Tidy...
lib/ohdevtools/commands/update-nuget.py
from xml.etree.cElementTree import parse, Element, ElementTree, dump from os import walk from os.path import join from optparse import OptionParser description = "Update the master package.config from individual project ones." command_group = "Developer tools" # Snippet used from the ElementTree documentation. # Tidy...
0.399109
0.078113
import os from django.test import TestCase from app.tests.test_modules.loader import test_flow, TestCaseFlow, TestCaseFlowRunner from module.MicrocloudchipException.exceptions import * from module.data.shared_storage_data import SharedFileData from module.data.storage_data import FileData from module.data_builder.sha...
app/server/app/tests/test_shared_file_control.py
import os from django.test import TestCase from app.tests.test_modules.loader import test_flow, TestCaseFlow, TestCaseFlowRunner from module.MicrocloudchipException.exceptions import * from module.data.shared_storage_data import SharedFileData from module.data.storage_data import FileData from module.data_builder.sha...
0.323594
0.38445
from flask import Blueprint, request # own project imports from cagecat.tools.tools_helpers import read_headers, parse_selected_cluster_numbers from cagecat.forms.forms import CblasterSearchForm, CblasterGNEForm, CblasterExtractSequencesForm, \ CblasterExtractClustersForm, CblasterVisualisationForm, ClinkerDownstr...
cagecat/tools/tools_routes.py
from flask import Blueprint, request # own project imports from cagecat.tools.tools_helpers import read_headers, parse_selected_cluster_numbers from cagecat.forms.forms import CblasterSearchForm, CblasterGNEForm, CblasterExtractSequencesForm, \ CblasterExtractClustersForm, CblasterVisualisationForm, ClinkerDownstr...
0.721743
0.183685
import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages from scipy import interpolate import Process_Data.constants as c from Lime import gassuan_weight from Process_Data.xfcc.common import get_filterbanks timit_soft = get_filterbanks(nfilt=23, nfft=320, samplerate=1600...
Lime/Plot/plt_weight.py
import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages from scipy import interpolate import Process_Data.constants as c from Lime import gassuan_weight from Process_Data.xfcc.common import get_filterbanks timit_soft = get_filterbanks(nfilt=23, nfft=320, samplerate=1600...
0.498047
0.35928
import unittest try: from unittest.mock import patch except ImportError: # Python 2 backport of mock from mock import patch import pythonfuzz.corpus as corpus class FakeCorpus(object): pass class BaseTestMutators(unittest.TestCase): """ Test that the mutators objects are doing what we want...
testing_tool/fuzztool/tests/unittest_mutators.py
import unittest try: from unittest.mock import patch except ImportError: # Python 2 backport of mock from mock import patch import pythonfuzz.corpus as corpus class FakeCorpus(object): pass class BaseTestMutators(unittest.TestCase): """ Test that the mutators objects are doing what we want...
0.635675
0.658198
from __future__ import absolute_import, division, print_function, with_statement from __future__ import unicode_literals from deepstreampy.constants import topic as topic_constants from deepstreampy.constants import actions from deepstreampy.constants import event as event_constants from deepstreampy.message import m...
deepstreampy/rpc.py
from __future__ import absolute_import, division, print_function, with_statement from __future__ import unicode_literals from deepstreampy.constants import topic as topic_constants from deepstreampy.constants import actions from deepstreampy.constants import event as event_constants from deepstreampy.message import m...
0.765199
0.163179
__author__ = 'mahajrod' import os import numpy as np from Parsers.VCF import CollectionVCF from Parsers.CCF import CollectionCCF import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib import rcParams from scipy.stats import chi2_contingency from math import sqrt def phi_coefficient_...
examples/desaminases/homogeneity_article_5_UTR.py
__author__ = 'mahajrod' import os import numpy as np from Parsers.VCF import CollectionVCF from Parsers.CCF import CollectionCCF import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib import rcParams from scipy.stats import chi2_contingency from math import sqrt def phi_coefficient_...
0.387922
0.26776
import torch from torch_geometric.datasets import Planetoid, NELL import torch.nn.functional as F from torch_geometric.nn import GCNConv class GCN(torch.nn.Module): def __init__(self, num_node_features, num_classes): super(GCN, self).__init__() self.conv1 = GCNConv(num_node_features, 32) s...
gcn.py
import torch from torch_geometric.datasets import Planetoid, NELL import torch.nn.functional as F from torch_geometric.nn import GCNConv class GCN(torch.nn.Module): def __init__(self, num_node_features, num_classes): super(GCN, self).__init__() self.conv1 = GCNConv(num_node_features, 32) s...
0.894338
0.670797
import configuration import csv import json import math import matplotlib.pyplot as plt parent_dir = 'cdf/raw/' dir_names = ['instance_lifetime/', 'interval_arrivals/', 'popular_unpopular_instance_lifetime/'] meta_filename = 'meta.txt' class MetaCDF(object): def __init__(self, filename): # Origin coo...
control/Control/src/schedule/cdf_transformer.py
import configuration import csv import json import math import matplotlib.pyplot as plt parent_dir = 'cdf/raw/' dir_names = ['instance_lifetime/', 'interval_arrivals/', 'popular_unpopular_instance_lifetime/'] meta_filename = 'meta.txt' class MetaCDF(object): def __init__(self, filename): # Origin coo...
0.689828
0.366363
from JumpScale import j """ make sure to load the ssh-agent before running this script" """ def createDocker(name, consume, parent, pf=''): data = { 'docker.image': 'jumpscale/ubuntu1504', 'docker.portsforwards': pf, 'docker.volumes': '', 'jumpscale.branch': 'ays_unstable', ...
aysold/agent_multiple_docker.py
from JumpScale import j """ make sure to load the ssh-agent before running this script" """ def createDocker(name, consume, parent, pf=''): data = { 'docker.image': 'jumpscale/ubuntu1504', 'docker.portsforwards': pf, 'docker.volumes': '', 'jumpscale.branch': 'ays_unstable', ...
0.329392
0.153803
import unittest from force_bdss.api import ( DataValue, ExecutionLayer, Workflow, InputSlotInfo ) from force_bdss.tests.probe_classes.data_source import \ ProbeDataSourceFactory from force_bdss.tests.probe_classes.factory_registry import ( ProbeFactoryRegistry ) from force_bdss.tests.probe_classes.mco imp...
force_wfmanager/ui/setup/tests/wfmanager_base_test_case.py
import unittest from force_bdss.api import ( DataValue, ExecutionLayer, Workflow, InputSlotInfo ) from force_bdss.tests.probe_classes.data_source import \ ProbeDataSourceFactory from force_bdss.tests.probe_classes.factory_registry import ( ProbeFactoryRegistry ) from force_bdss.tests.probe_classes.mco imp...
0.538012
0.272509
import os import time import boto3 import shutil import logging import datetime import subprocess from botocore.exceptions import ClientError VERSION = 0.5 # Configurable Variables WALLET_NAME = 'default' _FORMAT = 'zip' COMP_MAP = { 'zip': '.zip', 'tar': '.tar', 'gztar': '.tar.gz', 'bztar': '.tar.bz...
blockchain_upload.py
import os import time import boto3 import shutil import logging import datetime import subprocess from botocore.exceptions import ClientError VERSION = 0.5 # Configurable Variables WALLET_NAME = 'default' _FORMAT = 'zip' COMP_MAP = { 'zip': '.zip', 'tar': '.tar', 'gztar': '.tar.gz', 'bztar': '.tar.bz...
0.256459
0.056366
import logging import re import sys from datetime import datetime from pathlib import Path HEADER = "// LemonUI for RageMP\n// Generated on {date}{comment}\n\n{statements}\n\n#define RAGEMP{code}\n" LOGGER = logging.getLogger("merger") RE_SPECIFIC_USINGS = re.compile("#e?l?if RAGEMP\n([a-zA-Z0-9; . =\n]*)\n(?:#elif|#...
ragemp.py
import logging import re import sys from datetime import datetime from pathlib import Path HEADER = "// LemonUI for RageMP\n// Generated on {date}{comment}\n\n{statements}\n\n#define RAGEMP{code}\n" LOGGER = logging.getLogger("merger") RE_SPECIFIC_USINGS = re.compile("#e?l?if RAGEMP\n([a-zA-Z0-9; . =\n]*)\n(?:#elif|#...
0.187951
0.111992
from __future__ import absolute_import, division, print_function, unicode_literals from collections import OrderedDict import torch from torch import nn from torch.distributions import Distribution from .lazy import LazyTensor from .variational import VariationalStrategy class Module(nn.Module): def __init__(s...
gpytorch/module.py
from __future__ import absolute_import, division, print_function, unicode_literals from collections import OrderedDict import torch from torch import nn from torch.distributions import Distribution from .lazy import LazyTensor from .variational import VariationalStrategy class Module(nn.Module): def __init__(s...
0.934313
0.267797
from PyTrinamicMicro.platforms.motionpy2.modules.hc_sr04_multi import hc_sr04_multi from PyTrinamicMicro.platforms.motionpy2.modules.MCP23S08 import MCP23S08 from PyTrinamic.modules.TMCM0960.TMCM0960 import TMCM0960 import logging class linear_distance(object): def __init__(self, sensor, sensor_index, module, len...
PyTrinamicMicro/platforms/motionpy2/modules/linear_distance.py
from PyTrinamicMicro.platforms.motionpy2.modules.hc_sr04_multi import hc_sr04_multi from PyTrinamicMicro.platforms.motionpy2.modules.MCP23S08 import MCP23S08 from PyTrinamic.modules.TMCM0960.TMCM0960 import TMCM0960 import logging class linear_distance(object): def __init__(self, sensor, sensor_index, module, len...
0.491944
0.157331
import os import json def handler(event, context): """ Handles requests to start games from the game client. By design of the deployment scenario, this function is stubbed to always return a 501 (Not implemented) error. However, the lambda echoes the lambda environment variable as well as the playe...
Editor/Resources/CloudFormation/scenario1_auth_only/lambda/game_request.py
import os import json def handler(event, context): """ Handles requests to start games from the game client. By design of the deployment scenario, this function is stubbed to always return a 501 (Not implemented) error. However, the lambda echoes the lambda environment variable as well as the playe...
0.600423
0.382833
from MDSplus import mdsExceptions, Device, Data class PV_WAVE_SETUP(Device): """Epics Waveform Configurator""" parts = [{'path': ':BOARD_ID', 'type': 'numeric', 'value': 0}, {'path': ':COMMENT', 'type': 'text'}, {'path': ':TRIG_SOURCE', 'type': 'numeric', 'value': 0}, {...
pydevices/RfxDevices/PV_WAVE_SETUP.py
from MDSplus import mdsExceptions, Device, Data class PV_WAVE_SETUP(Device): """Epics Waveform Configurator""" parts = [{'path': ':BOARD_ID', 'type': 'numeric', 'value': 0}, {'path': ':COMMENT', 'type': 'text'}, {'path': ':TRIG_SOURCE', 'type': 'numeric', 'value': 0}, {...
0.267121
0.133246
from django.db.models.signals import post_save from django.dispatch import receiver from researchhub_case.constants.case_constants import APPROVED, INITIATED from researchhub_case.models import AuthorClaimCase from researchhub_case.utils.author_claim_case_utils import ( get_new_validation_token, reward_author_clai...
src/researchhub_case/signals/author_claiming_case_signals.py
from django.db.models.signals import post_save from django.dispatch import receiver from researchhub_case.constants.case_constants import APPROVED, INITIATED from researchhub_case.models import AuthorClaimCase from researchhub_case.utils.author_claim_case_utils import ( get_new_validation_token, reward_author_clai...
0.425486
0.16248
import math import numpy as np import tensorflow as tf from tensorflow.keras import layers from tensorflow.keras import backend as K class PositionLayer(tf.keras.layers.Layer): def __init__(self, embedding_size, **kwargs): self.embedding_size = embedding_size super(PositionLayer, self).__init__(*...
transformer/tensorflow/tf1.15_hvd/layers.py
import math import numpy as np import tensorflow as tf from tensorflow.keras import layers from tensorflow.keras import backend as K class PositionLayer(tf.keras.layers.Layer): def __init__(self, embedding_size, **kwargs): self.embedding_size = embedding_size super(PositionLayer, self).__init__(*...
0.825625
0.480966
from pytown_core.serializers import IJSONSerializable from .inventory import Inventory, Item class BackgroundCreator: def create_grass_backgound(self): return Background("grass", ["house", "sawmill"], 1) def create_water_background(self): return Background("water", [], 0.5) def create_r...
src/pytown_model/entity.py
from pytown_core.serializers import IJSONSerializable from .inventory import Inventory, Item class BackgroundCreator: def create_grass_backgound(self): return Background("grass", ["house", "sawmill"], 1) def create_water_background(self): return Background("water", [], 0.5) def create_r...
0.668664
0.208541
import unittest from unittest.mock import Mock import rclpy from rclpy.handle import Handle from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.qos_event import PublisherEventCallbacks from rclpy.qos_event import QoSLivelinessChangedInfo from rclpy.qos_event import QoSLivelinessL...
rclpy/test/test_qos_event.py
import unittest from unittest.mock import Mock import rclpy from rclpy.handle import Handle from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.qos_event import PublisherEventCallbacks from rclpy.qos_event import QoSLivelinessChangedInfo from rclpy.qos_event import QoSLivelinessL...
0.628065
0.233286