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 |
|---|---|---|---|---|
from json.decoder import JSONDecodeError
# ┌────────────────────────────────────────────────────────────────────────────────────┐
# │ BEAUTIFUL SOUP IMPORTS │
# └────────────────────────────────────────────────────────────────────────────────────┘
from bs4 ... | yank/response.py |
from json.decoder import JSONDecodeError
# ┌────────────────────────────────────────────────────────────────────────────────────┐
# │ BEAUTIFUL SOUP IMPORTS │
# └────────────────────────────────────────────────────────────────────────────────────┘
from bs4 ... | 0.746509 | 0.282843 |
import os
import gym
import random
import numpy as np
import tensorflow as tf
from collections import deque
from skimage.color import rgb2gray
from skimage.transform import resize
from keras.models import Sequential
from keras.layers import Convolution2D, Flatten, Dense
ENV_NAME = 'Breakout-v0' # Environment name
FR... | classic_ddqn.py |
import os
import gym
import random
import numpy as np
import tensorflow as tf
from collections import deque
from skimage.color import rgb2gray
from skimage.transform import resize
from keras.models import Sequential
from keras.layers import Convolution2D, Flatten, Dense
ENV_NAME = 'Breakout-v0' # Environment name
FR... | 0.883958 | 0.411288 |
import collections
import datetime
import doctest
import os
import time
import unittest
import sys
from six import u
import jsonstruct
from jsonstruct import handlers
from jsonstruct import tags
from jsonstruct.compat import unicode
from jsonstruct._samples import (
BrokenReprThing,
DictSubclass,
... | tests/jsonstruct_test.py |
import collections
import datetime
import doctest
import os
import time
import unittest
import sys
from six import u
import jsonstruct
from jsonstruct import handlers
from jsonstruct import tags
from jsonstruct.compat import unicode
from jsonstruct._samples import (
BrokenReprThing,
DictSubclass,
... | 0.375936 | 0.317281 |
from rest_framework import status
from .base_test import BaseTest
from django.core.files.uploadedfile import SimpleUploadedFile
class ProfileTest(BaseTest):
"""
This class defines the test case suite
for fetching and manipulating user
profiles.
"""
def setUp(self):
"""
Define ... | authors/tests/data/test_profile.py | from rest_framework import status
from .base_test import BaseTest
from django.core.files.uploadedfile import SimpleUploadedFile
class ProfileTest(BaseTest):
"""
This class defines the test case suite
for fetching and manipulating user
profiles.
"""
def setUp(self):
"""
Define ... | 0.632503 | 0.354936 |
__author__ = '<NAME>'
import argparse
from RouToolPa.Tools.HMMER import HMMER3
from RouToolPa.GeneralRoutines.File import check_path
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input_hmm", action="store", dest="input",
help="Input hmm3 file")
parser.add_argument("-s", "--input... | scripts/hmmer3/parallel_hmmscan.py | __author__ = '<NAME>'
import argparse
from RouToolPa.Tools.HMMER import HMMER3
from RouToolPa.GeneralRoutines.File import check_path
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input_hmm", action="store", dest="input",
help="Input hmm3 file")
parser.add_argument("-s", "--input... | 0.436622 | 0.104523 |
from redbot.core import Config, bank
from redbot.core.data_manager import bundled_data_path
import time
import bisect
import random
import asyncio
from operator import itemgetter
from ast import literal_eval
# Thanks stack overflow http://stackoverflow.com/questions/21872366/plural-string-formatting
class ... | heist/thief.py | from redbot.core import Config, bank
from redbot.core.data_manager import bundled_data_path
import time
import bisect
import random
import asyncio
from operator import itemgetter
from ast import literal_eval
# Thanks stack overflow http://stackoverflow.com/questions/21872366/plural-string-formatting
class ... | 0.464173 | 0.157493 |
import dataclasses
import json
import logging
from dataclasses import dataclass, field
from typing import Any, Dict, Optional, Tuple
import torch
from transformers import MODEL_WITH_LM_HEAD_MAPPING
from transformers.training_args import is_torch_tpu_available
from transformers.file_utils import cached_prope... | src/deepex/args.py | import dataclasses
import json
import logging
from dataclasses import dataclass, field
from typing import Any, Dict, Optional, Tuple
import torch
from transformers import MODEL_WITH_LM_HEAD_MAPPING
from transformers.training_args import is_torch_tpu_available
from transformers.file_utils import cached_prope... | 0.809088 | 0.202838 |
import game_logic
import unittest
import checkers_exception
import log_parser
import glob
import os
class ParserTest(unittest.TestCase):
file_for_deleted = []
def tearDown(self):
for file in self.file_for_deleted:
os.remove(file)
def init_parser(self):
self.pa... | test.py | import game_logic
import unittest
import checkers_exception
import log_parser
import glob
import os
class ParserTest(unittest.TestCase):
file_for_deleted = []
def tearDown(self):
for file in self.file_for_deleted:
os.remove(file)
def init_parser(self):
self.pa... | 0.238107 | 0.197039 |
import h2o
import tempfile
import os
from h2o.estimators import H2ORandomForestEstimator, H2OGenericEstimator
from tests import pyunit_utils
from tests.testdir_generic_model import compare_output, Capturing
def test(x, y, output_test, strip_part, algo_name, generic_algo_name):
airlines = h2o.import_file(path=pyu... | h2o-py/tests/testdir_generic_model/pyunit_generic_model_mojo_drf.py | import h2o
import tempfile
import os
from h2o.estimators import H2ORandomForestEstimator, H2OGenericEstimator
from tests import pyunit_utils
from tests.testdir_generic_model import compare_output, Capturing
def test(x, y, output_test, strip_part, algo_name, generic_algo_name):
airlines = h2o.import_file(path=pyu... | 0.445771 | 0.456046 |
import abc
from typing import Callable, Iterator, List, Optional
__all__ = [
"Event",
"ForEveryCallbackDistribution",
"ForFirstToTakeDistribution",
]
class EventDistribution(abc.ABC):
context: "Event"
def set_context(self, context):
self.context = context
@abc.abstractmethod
de... | code_sandbox/utils/events/events.py | import abc
from typing import Callable, Iterator, List, Optional
__all__ = [
"Event",
"ForEveryCallbackDistribution",
"ForFirstToTakeDistribution",
]
class EventDistribution(abc.ABC):
context: "Event"
def set_context(self, context):
self.context = context
@abc.abstractmethod
de... | 0.793106 | 0.208884 |
PCODE_LEN = 2
ADD = 1
MULTIPLY = 2
SAVE = 3
OUTPUT = 4
HALT = 99
OP_PARAMS = {
ADD: 3,
MULTIPLY: 3,
SAVE: 1,
OUTPUT: 1,
HALT: 0,
}
POSITION = 0
IMMEDIATE = 1
class IntcodeCompiler:
def __init__(self, filepath):
with open(filepath) as f:
self.program = list(map(int, f.re... | 2019/05/day5B.py | PCODE_LEN = 2
ADD = 1
MULTIPLY = 2
SAVE = 3
OUTPUT = 4
HALT = 99
OP_PARAMS = {
ADD: 3,
MULTIPLY: 3,
SAVE: 1,
OUTPUT: 1,
HALT: 0,
}
POSITION = 0
IMMEDIATE = 1
class IntcodeCompiler:
def __init__(self, filepath):
with open(filepath) as f:
self.program = list(map(int, f.re... | 0.365117 | 0.279056 |
# In[1]:
import numpy as np
import pandas as pd
import skimage, os
import SimpleITK as sitk
from scipy import ndimage
import matplotlib.pyplot as plt
get_ipython().magic(u'matplotlib inline')
import os
import zarr
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0... | dsb2017/25.03_3D_UNet_normalized.py |
# In[1]:
import numpy as np
import pandas as pd
import skimage, os
import SimpleITK as sitk
from scipy import ndimage
import matplotlib.pyplot as plt
get_ipython().magic(u'matplotlib inline')
import os
import zarr
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0... | 0.547948 | 0.296655 |
from unittest.mock import patch
import saltext.vmware.modules.nsxt_policy_segment as nsxt_policy_segment
from saltext.vmware.utils import nsxt_request
_mock_segment = {
"type": "DISCONNECTED",
"overlay_id": 75005,
"transport_zone_path": "/infra/sites/default/enforcement-points/default/transport-zones/b68c... | tests/unit/modules/test_nsxt_policy_segment.py | from unittest.mock import patch
import saltext.vmware.modules.nsxt_policy_segment as nsxt_policy_segment
from saltext.vmware.utils import nsxt_request
_mock_segment = {
"type": "DISCONNECTED",
"overlay_id": 75005,
"transport_zone_path": "/infra/sites/default/enforcement-points/default/transport-zones/b68c... | 0.477311 | 0.293962 |
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table
# Imports from this application
from app import app
from joblib import load
# 1 column layout
# https://dash-bootstrap-components.o... | pages/insights.py | import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table
# Imports from this application
from app import app
from joblib import load
# 1 column layout
# https://dash-bootstrap-components.o... | 0.395484 | 0.406214 |
import multiprocessing
import os
import dask
import dask.array as da
import dask.dataframe as dd
from ludwig.constants import NAME, PROC_COLUMN
from ludwig.data.dataset.parquet import ParquetDataset
from ludwig.data.dataframe.base import DataFrameEngine
from ludwig.utils.data_utils import DATA_PROCESSED_CACHE_DIR, D... | ludwig/data/dataframe/dask.py |
import multiprocessing
import os
import dask
import dask.array as da
import dask.dataframe as dd
from ludwig.constants import NAME, PROC_COLUMN
from ludwig.data.dataset.parquet import ParquetDataset
from ludwig.data.dataframe.base import DataFrameEngine
from ludwig.utils.data_utils import DATA_PROCESSED_CACHE_DIR, D... | 0.632049 | 0.393152 |
from __future__ import print_function
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import httplib2, sqlite3, os
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportErr... | botkue/uploader.py |
from __future__ import print_function
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import httplib2, sqlite3, os
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportErr... | 0.359926 | 0.113973 |
from tomlkit.toml_file import TOMLFile
from git import Repo
import sys
from datetime import datetime
class PyProject:
def __init__(self):
self._file = TOMLFile('pyproject.toml')
def get_version(self):
pyproject_data = self._file.read()
version = pyproject_data['tool']['poetry']['versi... | release.py | from tomlkit.toml_file import TOMLFile
from git import Repo
import sys
from datetime import datetime
class PyProject:
def __init__(self):
self._file = TOMLFile('pyproject.toml')
def get_version(self):
pyproject_data = self._file.read()
version = pyproject_data['tool']['poetry']['versi... | 0.332202 | 0.093099 |
from fontTools.misc.bezierTools import calcCubicParameters, solveCubic
from math import hypot
from jkFontGeometry.beziertools import (
estimateCubicCurveLength,
getInflectionsForCubic,
getExtremaForCubic,
)
from jkFontGeometry.beziertools import getPointOnCubic as get_cubic_point
from jkFontGeometry impor... | Lib/jkFontGeometry/cubics.py | from fontTools.misc.bezierTools import calcCubicParameters, solveCubic
from math import hypot
from jkFontGeometry.beziertools import (
estimateCubicCurveLength,
getInflectionsForCubic,
getExtremaForCubic,
)
from jkFontGeometry.beziertools import getPointOnCubic as get_cubic_point
from jkFontGeometry impor... | 0.862641 | 0.3628 |
from __future__ import division, print_function
from scipy.stats import multivariate_normal, norm
from scipy.optimize import minimize
import numpy as np
from itertools import combinations, product
import warnings
def _get_polychoric_init(data):
# 用相关系数作为polychoric的初值
return np.corrcoef(data, rowvar=False)
d... | psy/sem/ccfa.py | from __future__ import division, print_function
from scipy.stats import multivariate_normal, norm
from scipy.optimize import minimize
import numpy as np
from itertools import combinations, product
import warnings
def _get_polychoric_init(data):
# 用相关系数作为polychoric的初值
return np.corrcoef(data, rowvar=False)
d... | 0.372734 | 0.425605 |
from core.forms import UserForm
from django.shortcuts import render
# Create your views here.
def form_user(request):
datos = {
'form':UserForm()
}
if request.method == 'POST':
formulario = UserForm(request.POST)
if formulario.is_valid():
formulario.save()
d... | DjangoWeb/core/views.py | from core.forms import UserForm
from django.shortcuts import render
# Create your views here.
def form_user(request):
datos = {
'form':UserForm()
}
if request.method == 'POST':
formulario = UserForm(request.POST)
if formulario.is_valid():
formulario.save()
d... | 0.349866 | 0.153581 |
from deep_dialog.nlu.watson_handler import WatsonAPI
class watson():
def __init__(self, params, top_intents):
self.params = params
self.top_intents = top_intents
username= 'apikey'
password = '<PASSWORD>'
WID ='5ad83f0a-2e75-4a7d-934b-2db3aad2f5db' #'34... | SIRL_bot/deep_dialog/nlu/watson.py | from deep_dialog.nlu.watson_handler import WatsonAPI
class watson():
def __init__(self, params, top_intents):
self.params = params
self.top_intents = top_intents
username= 'apikey'
password = '<PASSWORD>'
WID ='5ad83f0a-2e75-4a7d-934b-2db3aad2f5db' #'34... | 0.255901 | 0.099865 |
from pyspark.tests import ReusedPySparkTestCase
from pyspark.sql import SparkSession
from pyspark.mllib.linalg.distributed import MatrixEntry, CoordinateMatrix
import numpy as np
import labelpropagation
from labelpropagation import lp_matrix_multiply
class TestNaive_multiplication_rdd(ReusedPySparkTestCase):
def ... | test/semisupervised/labelpropagation/lp_matrix_multiply/test_naive_multiplication_rdd.py | from pyspark.tests import ReusedPySparkTestCase
from pyspark.sql import SparkSession
from pyspark.mllib.linalg.distributed import MatrixEntry, CoordinateMatrix
import numpy as np
import labelpropagation
from labelpropagation import lp_matrix_multiply
class TestNaive_multiplication_rdd(ReusedPySparkTestCase):
def ... | 0.797399 | 0.688346 |
from django.core.exceptions import PermissionDenied
from django.shortcuts import reverse, redirect
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.models import Group
from django.shortcuts import... | users/decorators.py | from django.core.exceptions import PermissionDenied
from django.shortcuts import reverse, redirect
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.models import Group
from django.shortcuts import... | 0.478773 | 0.103386 |
import string
import unittest
from simu import random
__time__ = 100
__natural_range__ = [*range(0, random.DEFAULT_MAX + 1, 1)]
__integer_range__ = [*range(random.DEFAULT_MIN, random.DEFAULT_MAX + 1, 1)]
class RandomTest(unittest.TestCase):
def test_boolean(self):
for _ in range(__time__):
... | tests/test_random.py | import string
import unittest
from simu import random
__time__ = 100
__natural_range__ = [*range(0, random.DEFAULT_MAX + 1, 1)]
__integer_range__ = [*range(random.DEFAULT_MIN, random.DEFAULT_MAX + 1, 1)]
class RandomTest(unittest.TestCase):
def test_boolean(self):
for _ in range(__time__):
... | 0.410166 | 0.474266 |
import json
import os
import traceback
from distutils.version import LooseVersion
from bzt import TaurusInternalException, TaurusConfigError
from bzt.engine import Scenario
from bzt.jmx import JMX
from bzt.requests_model import RequestVisitor, has_variable_pattern
from bzt.six import etree, iteritems, numeric_types
fr... | bzt/jmx/tools.py | import json
import os
import traceback
from distutils.version import LooseVersion
from bzt import TaurusInternalException, TaurusConfigError
from bzt.engine import Scenario
from bzt.jmx import JMX
from bzt.requests_model import RequestVisitor, has_variable_pattern
from bzt.six import etree, iteritems, numeric_types
fr... | 0.519521 | 0.100657 |
from flask_app.config.mysqlconnection import connectToMySQL
from flask_app.models import recipe
from flask import flash
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class User:
db = 'recipe_schema'
def __init__(self,data):
self.id = data['id']
self.fi... | flask_app/models/user.py | from flask_app.config.mysqlconnection import connectToMySQL
from flask_app.models import recipe
from flask import flash
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class User:
db = 'recipe_schema'
def __init__(self,data):
self.id = data['id']
self.fi... | 0.271059 | 0.119768 |
# In[ ]:
# In[2]:
import tensorflow as tf
import numpy as np
import experiment_manager as em
import far_ho as far
# In[4]:
far.utils._check()
# In[16]:
try: ss.close()
except: pass
tf.reset_default_graph()
ss = tf.InteractiveSession()
v1 = tf.Variable([1.,3])
v2 = tf.Variable([[-1., -2], [1., 0.]])
# In[1... | tests/check reverse with rfho.py |
# In[ ]:
# In[2]:
import tensorflow as tf
import numpy as np
import experiment_manager as em
import far_ho as far
# In[4]:
far.utils._check()
# In[16]:
try: ss.close()
except: pass
tf.reset_default_graph()
ss = tf.InteractiveSession()
v1 = tf.Variable([1.,3])
v2 = tf.Variable([[-1., -2], [1., 0.]])
# In[1... | 0.255529 | 0.352063 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0012_submissionset_2'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operation... | src/rolca/rating/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0012_submissionset_2'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operation... | 0.554953 | 0.134122 |
import os
import sys
import shutil
def main(cfg, out_dir, tgt_pfx, data_key="base"):
import ast
import logging
import numpy as np
import torch
from argparse import Namespace
import sacrebleu
from dataclasses import dataclass
from fairseq import utils, options, tasks, checkpoint_ut... | build_offline_dataset.py | import os
import sys
import shutil
def main(cfg, out_dir, tgt_pfx, data_key="base"):
import ast
import logging
import numpy as np
import torch
from argparse import Namespace
import sacrebleu
from dataclasses import dataclass
from fairseq import utils, options, tasks, checkpoint_ut... | 0.363534 | 0.169681 |
import os
import sys
from logging import Filter
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/ch... | homevisit_project/settings.py | import os
import sys
from logging import Filter
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/ch... | 0.335677 | 0.114963 |
from rest_framework import serializers
from goods.models import SKUImage, SKU, SKUSpecification, SPU, SPUSpecification, SpecificationOption, GoodsCategory
class SPECSSimpleSerializer(serializers.ModelSerializer):
"""规格选项序列化器"""
spec_id = serializers.IntegerField(label='商品规格id')
option_id = serializers.In... | meiduo_mall/meiduo_mall/apps/meiduo_admin/serializers/skus.py | from rest_framework import serializers
from goods.models import SKUImage, SKU, SKUSpecification, SPU, SPUSpecification, SpecificationOption, GoodsCategory
class SPECSSimpleSerializer(serializers.ModelSerializer):
"""规格选项序列化器"""
spec_id = serializers.IntegerField(label='商品规格id')
option_id = serializers.In... | 0.48121 | 0.123895 |
from scrapy.crawler import CrawlerProcess
from app.spiders import products, reviews, specs
def start_parse():
start_products()
start_reviews()
start_specs()
def start_specs():
process = CrawlerProcess()
process.crawl(products.NotebooksSpider)
process.crawl(products.DesktopsSpider)
proce... | app/main.py | from scrapy.crawler import CrawlerProcess
from app.spiders import products, reviews, specs
def start_parse():
start_products()
start_reviews()
start_specs()
def start_specs():
process = CrawlerProcess()
process.crawl(products.NotebooksSpider)
process.crawl(products.DesktopsSpider)
proce... | 0.44071 | 0.179441 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
from dgl.geometry import farthest_point_sampler
'''
Part of the code are adapted from
https://github.com/yanx27/Pointnet_Pointnet2_pytorch
'''
def square_distance(src, dst):
'''
Adapted from https://github.com/yanx27/Pointnet_Point... | examples/pytorch/pointcloud/pct/helper.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
from dgl.geometry import farthest_point_sampler
'''
Part of the code are adapted from
https://github.com/yanx27/Pointnet_Pointnet2_pytorch
'''
def square_distance(src, dst):
'''
Adapted from https://github.com/yanx27/Pointnet_Point... | 0.900931 | 0.730254 |
import base64
import imghdr
import uuid
import sys
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from django.utils.translation import ugettext_lazy as _
from rest_framework.fields import ImageField
DEFAULT_CONTENT_TYPE = "application/octet-stream"
ALLOWED_IMAGE_TYP... | drf_extra_fields/fields.py | import base64
import imghdr
import uuid
import sys
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from django.utils.translation import ugettext_lazy as _
from rest_framework.fields import ImageField
DEFAULT_CONTENT_TYPE = "application/octet-stream"
ALLOWED_IMAGE_TYP... | 0.349977 | 0.081996 |
import cv2
import time
import hand_tracking as ht
from predict_gestures import PredictGestures
from game_handle import GameHandle
from show_menu import ShowMenu
""" cv2 config """
w_cam, h_cam = 640, 480
cap = cv2.VideoCapture(0)
cap.set(3, w_cam)
cap.set(4, h_cam)
"""fps config"""
c_time = p_time = 0
"""game start... | hand_cricket/hand_cricket.py | import cv2
import time
import hand_tracking as ht
from predict_gestures import PredictGestures
from game_handle import GameHandle
from show_menu import ShowMenu
""" cv2 config """
w_cam, h_cam = 640, 480
cap = cv2.VideoCapture(0)
cap.set(3, w_cam)
cap.set(4, h_cam)
"""fps config"""
c_time = p_time = 0
"""game start... | 0.282691 | 0.147279 |
from rest_framework import serializers
from core import models
from meals.serializers import MealsSerializer
class TableSerializer(serializers.ModelSerializer):
"""Serializer for table objects"""
class Meta:
model = models.Table
fields = ('id', 'name')
read_only_fields = ('id',)
cla... | app/orders/serializers.py | from rest_framework import serializers
from core import models
from meals.serializers import MealsSerializer
class TableSerializer(serializers.ModelSerializer):
"""Serializer for table objects"""
class Meta:
model = models.Table
fields = ('id', 'name')
read_only_fields = ('id',)
cla... | 0.638948 | 0.193452 |
import csv
import io
import codecs
from urllib import request
from owlready2 import *
import pandas
from standard.models import Term, Project, TermCategory, ProjectTerm, TermStatus
from pygbif import occurrences as occ
class Schema:
"""
Base class to store a data schema including terms, definitions, versions ... | standard/utils.py | import csv
import io
import codecs
from urllib import request
from owlready2 import *
import pandas
from standard.models import Term, Project, TermCategory, ProjectTerm, TermStatus
from pygbif import occurrences as occ
class Schema:
"""
Base class to store a data schema including terms, definitions, versions ... | 0.57344 | 0.262605 |
import unittest
import os.path
import warnings
from stagger.tags import Tag22, Tag23, Tag24
from stagger.id3 import TT2, TIT1, TIT2, TPE1, TPE2, TALB, TCOM, TCON, TSOT
from stagger.id3 import TSOP, TSO2, TSOA, TSOC, TRCK, TPOS, TYE, TDA, TIM, TYER
from stagger.id3 import TDAT, TIME, TDRC, PIC, APIC, COM, COMM
from st... | test/friendly.py |
import unittest
import os.path
import warnings
from stagger.tags import Tag22, Tag23, Tag24
from stagger.id3 import TT2, TIT1, TIT2, TPE1, TPE2, TALB, TCOM, TCON, TSOT
from stagger.id3 import TSOP, TSO2, TSOA, TSOC, TRCK, TPOS, TYE, TDA, TIM, TYER
from stagger.id3 import TDAT, TIME, TDRC, PIC, APIC, COM, COMM
from st... | 0.539226 | 0.304416 |
from aide_design.play import *
import aguaclara_research.ProCoDA_Parser as pro
import aguaclara_research.Environmental_Processes_Analysis as epa
import aguaclara_research.floc_model as floc_mod
import aguaclara_research.tube_sizing as tube
def setup_aguaclara():
"""
This is the public function that should be c... | aguaclara_research/play.py | from aide_design.play import *
import aguaclara_research.ProCoDA_Parser as pro
import aguaclara_research.Environmental_Processes_Analysis as epa
import aguaclara_research.floc_model as floc_mod
import aguaclara_research.tube_sizing as tube
def setup_aguaclara():
"""
This is the public function that should be c... | 0.476336 | 0.399343 |
from typing import List
from slack_sdk.models.blocks import ConfirmObject, Block, SectionBlock, \
MarkdownTextObject, ButtonElement
from sched_slack_bot.model.reminder import Reminder
SKIP_CURRENT_MEMBER_ACTION_ID = "SCHED_SLACK_BOT_SKIP_ACTION_ID"
def _get_confirm_object_for_skip(reminder: Reminder) -> Confir... | sched_slack_bot/views/reminder_blocks.py | from typing import List
from slack_sdk.models.blocks import ConfirmObject, Block, SectionBlock, \
MarkdownTextObject, ButtonElement
from sched_slack_bot.model.reminder import Reminder
SKIP_CURRENT_MEMBER_ACTION_ID = "SCHED_SLACK_BOT_SKIP_ACTION_ID"
def _get_confirm_object_for_skip(reminder: Reminder) -> Confir... | 0.744471 | 0.147003 |
import torch
import torch.nn as nn
from utils.save_net import *
class ComplexConv(nn.Module):
def __init__(self, rank,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
output_padding=0,
... | complexnet/cmplxconv.py | import torch
import torch.nn as nn
from utils.save_net import *
class ComplexConv(nn.Module):
def __init__(self, rank,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
output_padding=0,
... | 0.963789 | 0.504272 |
import logging
import os
import shutil
import pwd
import grp
import base64
from bson import objectid
import _judger
import yamajudge
from yamajudge import db
from yamajudge import request
from yamajudge import error
from yamajudge import workspace
from yamajudge import judge
from yamajudge.constant import record
from... | yamajudge/job/task.py | import logging
import os
import shutil
import pwd
import grp
import base64
from bson import objectid
import _judger
import yamajudge
from yamajudge import db
from yamajudge import request
from yamajudge import error
from yamajudge import workspace
from yamajudge import judge
from yamajudge.constant import record
from... | 0.169991 | 0.084342 |
import os
import sys
import logging
import click
from prettytable import PrettyTable
from .core import TPCore
from .passwd import Passwd
from .target import Target
from .settings import opts
from .__version__ import __version__
def banner():
return (
"\nTotalPass %s created by HJK.\nhttps://github.com/0x... | totalpass/__main__.py |
import os
import sys
import logging
import click
from prettytable import PrettyTable
from .core import TPCore
from .passwd import Passwd
from .target import Target
from .settings import opts
from .__version__ import __version__
def banner():
return (
"\nTotalPass %s created by HJK.\nhttps://github.com/0x... | 0.166743 | 0.076098 |
import struct
from constants import *
import json
class Importer:
def __init__(self, terms_size, docnames_size):
self.terms_size = terms_size
self.docnames_size = docnames_size
def read_vocabulary(self):
with open(BIN_VOCABULARY_FILEPATH, "rb") as f:
string_format = "{}s{}... | TP_04/ejercicio_4/script_2/importer.py | import struct
from constants import *
import json
class Importer:
def __init__(self, terms_size, docnames_size):
self.terms_size = terms_size
self.docnames_size = docnames_size
def read_vocabulary(self):
with open(BIN_VOCABULARY_FILEPATH, "rb") as f:
string_format = "{}s{}... | 0.390592 | 0.126299 |
import pandas as pa
import numpy as np
import matplotlib.pyplot as plt
from statistics import *
from sklearn.preprocessing import Imputer,LabelEncoder,OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_sc... | scripts/prediction_scripts/three_reg.py | import pandas as pa
import numpy as np
import matplotlib.pyplot as plt
from statistics import *
from sklearn.preprocessing import Imputer,LabelEncoder,OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_sc... | 0.264833 | 0.446917 |
from enum import Enum
class FormFactorConstant(Enum):
# Virtual interfaces
VIRTUAL = 0
LAG = 200
# Ethernet (fixed)
BASE_TX_10_100ME = 800
BASE_T_1GE = 1000
GBASE_T_10GE = 1150
# Ethernet (modular)
GBIC_1GE = 1050
SFP_1GE = 1100
SFP_PLUS_10GE = 1200
XFP_10GE = 1300
... | netbox_api/model/interface.py | from enum import Enum
class FormFactorConstant(Enum):
# Virtual interfaces
VIRTUAL = 0
LAG = 200
# Ethernet (fixed)
BASE_TX_10_100ME = 800
BASE_T_1GE = 1000
GBASE_T_10GE = 1150
# Ethernet (modular)
GBIC_1GE = 1050
SFP_1GE = 1100
SFP_PLUS_10GE = 1200
XFP_10GE = 1300
... | 0.747892 | 0.172241 |
from twisted.internet.defer import inlineCallbacks, succeed
from twisted.internet import reactor
from twisted.python.modules import getModule
from twisted.trial import unittest
from twistedcaldav.config import ConfigDict
from twistedcaldav.ical import Component
from txdav.caldav.datastore.scheduling.imip.inbound im... | txdav/caldav/datastore/scheduling/imip/test/test_inbound.py |
from twisted.internet.defer import inlineCallbacks, succeed
from twisted.internet import reactor
from twisted.python.modules import getModule
from twisted.trial import unittest
from twistedcaldav.config import ConfigDict
from twistedcaldav.ical import Component
from txdav.caldav.datastore.scheduling.imip.inbound im... | 0.491944 | 0.092196 |
from oslo_config import cfg
from ironic_lib import exception
from ironic_lib import metrics as metricslib
from ironic_lib import metrics_statsd
from ironic_lib import metrics_utils
from ironic_lib.tests import base
CONF = cfg.CONF
class TestGetLogger(base.IronicLibTestCase):
def setUp(self):
super(Test... | ironic_lib/tests/test_metrics_utils.py |
from oslo_config import cfg
from ironic_lib import exception
from ironic_lib import metrics as metricslib
from ironic_lib import metrics_statsd
from ironic_lib import metrics_utils
from ironic_lib.tests import base
CONF = cfg.CONF
class TestGetLogger(base.IronicLibTestCase):
def setUp(self):
super(Test... | 0.695545 | 0.206374 |
import unittest
from tests import PluginTest
from plugins.basketball import basketball
from mock import patch, call
import requests
import datetime
from packages.memory.memory import Memory
class BasketballTest(PluginTest):
"""
Tests For Basketball Plugin
!!! test will be executed only if user has added h... | jarviscli/tests/test_basketball.py | import unittest
from tests import PluginTest
from plugins.basketball import basketball
from mock import patch, call
import requests
import datetime
from packages.memory.memory import Memory
class BasketballTest(PluginTest):
"""
Tests For Basketball Plugin
!!! test will be executed only if user has added h... | 0.5083 | 0.337313 |
import os
import pickle
import sys
from typing import Dict, List
from pathpicker import parse, state_files
from pathpicker.formatted_text import FormattedText
from pathpicker.line_format import LineBase, LineMatch, SimpleLine
from pathpicker.screen_flags import ScreenFlags
from pathpicker.usage_strings import USAGE_ST... | src/process_input.py | import os
import pickle
import sys
from typing import Dict, List
from pathpicker import parse, state_files
from pathpicker.formatted_text import FormattedText
from pathpicker.line_format import LineBase, LineMatch, SimpleLine
from pathpicker.screen_flags import ScreenFlags
from pathpicker.usage_strings import USAGE_ST... | 0.275617 | 0.104706 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import tensorflow as tf
import nrrd
import numpy as np
from tensorflow.contrib.learn.python.learn.datasets import mnist
FLAGS = None
def _int64_feature(value):
return... | src/tf/util/nrrdToTfrecords.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import tensorflow as tf
import nrrd
import numpy as np
from tensorflow.contrib.learn.python.learn.datasets import mnist
FLAGS = None
def _int64_feature(value):
return... | 0.391173 | 0.120284 |
import argparse
import json
import os
import sys
import imageio
import numpy
METADATA_FILE = 'meta.json'
THUMBNAIL_FILE = 'tn.jpg'
def assertRecursive(expectedPath, actualPath):
expected = os.listdir(expectedPath)
actual = os.listdir(actualPath)
assert actual == expected, 'Dissimilar folders: ' + \
... | src/test/python/assert_same_meta.py | import argparse
import json
import os
import sys
import imageio
import numpy
METADATA_FILE = 'meta.json'
THUMBNAIL_FILE = 'tn.jpg'
def assertRecursive(expectedPath, actualPath):
expected = os.listdir(expectedPath)
actual = os.listdir(actualPath)
assert actual == expected, 'Dissimilar folders: ' + \
... | 0.376509 | 0.426202 |
import argparse
from rdkit import Chem
from rdkit.Chem import rdFMCS
def _process_input():
"""Define and parse the command line arguments"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-target',
'--target_file',
required=True,
help='Path to the file containin... | education/HADDOCK24/shape-small-molecule/scripts/calc_mcs.py |
import argparse
from rdkit import Chem
from rdkit.Chem import rdFMCS
def _process_input():
"""Define and parse the command line arguments"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-target',
'--target_file',
required=True,
help='Path to the file containin... | 0.512205 | 0.442637 |
import json
import uuid
from unittest.mock import patch, PropertyMock
from django.contrib.gis.geos import Point
from django.test import TestCase
from rest_framework.reverse import reverse
from rhodonea_mapper.api.serializers import (
LayerSerializer,
LayerDetailSerializer,
)
from rhodonea_mapper.models impor... | tests/rhodonea_mapper/api/tests_layers.py | import json
import uuid
from unittest.mock import patch, PropertyMock
from django.contrib.gis.geos import Point
from django.test import TestCase
from rest_framework.reverse import reverse
from rhodonea_mapper.api.serializers import (
LayerSerializer,
LayerDetailSerializer,
)
from rhodonea_mapper.models impor... | 0.605682 | 0.220762 |
from time import sleep
import numpy as np
from stop_watch import Stopwatch
from text_colors import TextColors
class Traffic:
def display(self, traffic, active_lane):
'''
Prints the number of traffic on each intersection and the map of the road
Precondition: Traffic must be Traffic_Light... | traffic.py | from time import sleep
import numpy as np
from stop_watch import Stopwatch
from text_colors import TextColors
class Traffic:
def display(self, traffic, active_lane):
'''
Prints the number of traffic on each intersection and the map of the road
Precondition: Traffic must be Traffic_Light... | 0.479016 | 0.349061 |
import numpy as np
from scipy.stats import ranksums, wilcoxon, ttest_ind, ttest_rel
from ._statsmodels import multipletests
from sklearn.metrics import roc_auc_score
import pandas as pd
from brainbox.population.decode import get_spike_counts_in_bins
def responsive_units(spike_times, spike_clusters, event_times,
... | brainbox/task/closed_loop.py | import numpy as np
from scipy.stats import ranksums, wilcoxon, ttest_ind, ttest_rel
from ._statsmodels import multipletests
from sklearn.metrics import roc_auc_score
import pandas as pd
from brainbox.population.decode import get_spike_counts_in_bins
def responsive_units(spike_times, spike_clusters, event_times,
... | 0.884321 | 0.791982 |
from urllib.parse import urlparse
from urllib.parse import parse_qsl
import scrapy
import requests
class ProductsSpider(scrapy.Spider):
name = "products"
product_num = 0
DETAIL_HTML = open('detail_format.html', 'r', encoding='utf8').read()
MAX_INIT_PRICE = 6000
def __init__(self, author_url=None... | yahoo_auc_crawler/spiders/products_spider.py | from urllib.parse import urlparse
from urllib.parse import parse_qsl
import scrapy
import requests
class ProductsSpider(scrapy.Spider):
name = "products"
product_num = 0
DETAIL_HTML = open('detail_format.html', 'r', encoding='utf8').read()
MAX_INIT_PRICE = 6000
def __init__(self, author_url=None... | 0.348091 | 0.114294 |
from datahandler.AbstractDataSet import AbstractDataSet
import numpy as np
class NumericalDataSet(AbstractDataSet):
'''
Dataset for numerical data used either for regression or classification.
Contains fields inputs and labels as numpy.ndarray
'''
def __init__(self, inputs, targets=None):
... | Engine/src/datahandler/numerical/NumericalDataSet.py | from datahandler.AbstractDataSet import AbstractDataSet
import numpy as np
class NumericalDataSet(AbstractDataSet):
'''
Dataset for numerical data used either for regression or classification.
Contains fields inputs and labels as numpy.ndarray
'''
def __init__(self, inputs, targets=None):
... | 0.637031 | 0.675591 |
import DocsSigMember
# Import the latest membership file from community repo
member_list_file = 'membership.json'
# Import the latest pr and review raw data from pingcap metabase
pr_1_year_file = 'pr_1_year.json'
review_1_year_file = 'review_1_year.json'
pr_all_file = 'pr_all_file.json'
# Generate a dictionary of ol... | main.py | import DocsSigMember
# Import the latest membership file from community repo
member_list_file = 'membership.json'
# Import the latest pr and review raw data from pingcap metabase
pr_1_year_file = 'pr_1_year.json'
review_1_year_file = 'review_1_year.json'
pr_all_file = 'pr_all_file.json'
# Generate a dictionary of ol... | 0.148571 | 0.098123 |
import sys
import argparse
from tools import s3
from tools import clamav as av
from blessings import Terminal
t = Terminal()
#Check if we are running this on windows platform
is_windows = sys.platform.startswith('win')
#Console Colors
if is_windows:
G = Y = B = R = W = G = Y = B = R = W = '' #use no termina... | sleuth.py | import sys
import argparse
from tools import s3
from tools import clamav as av
from blessings import Terminal
t = Terminal()
#Check if we are running this on windows platform
is_windows = sys.platform.startswith('win')
#Console Colors
if is_windows:
G = Y = B = R = W = G = Y = B = R = W = '' #use no termina... | 0.049451 | 0.074332 |
from models.user.user import User
from exceptions.invalid_usage_exception import ClusterNotFoundException
from models.magic_castle.magic_castle import MagicCastle
from models.configuration import config
class AuthenticatedUser(User):
"""
User class for users created when the authentication type is set to SAML... | app/models/user/authenticated_user.py | from models.user.user import User
from exceptions.invalid_usage_exception import ClusterNotFoundException
from models.magic_castle.magic_castle import MagicCastle
from models.configuration import config
class AuthenticatedUser(User):
"""
User class for users created when the authentication type is set to SAML... | 0.673514 | 0.128006 |
from django.db import models
from django.db.models import Q
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class University(models.Model):
university = models.CharField(max_length=3... | accounts/models.py | from django.db import models
from django.db.models import Q
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class University(models.Model):
university = models.CharField(max_length=3... | 0.499512 | 0.187411 |
import sys
import dns.resolver
import requests
import pickle
def resolve(target_domain):
# Spawn a resolver instance
resolver = dns.resolver.Resolver()
# Attempt to resolve the domain
try:
answer = resolver.query(target_domain, "A")
if len(answer) == 1:
return answer... | client/main.py | import sys
import dns.resolver
import requests
import pickle
def resolve(target_domain):
# Spawn a resolver instance
resolver = dns.resolver.Resolver()
# Attempt to resolve the domain
try:
answer = resolver.query(target_domain, "A")
if len(answer) == 1:
return answer... | 0.223631 | 0.194884 |
__description__ = "an Executable class implementation"
__version__ = "0.1.0"
__author__ = "<NAME>."
import os
from subprocess import Popen, PIPE, STDOUT
class Executable(object):
"""
Executable - abstract class implementing the executable script
"""
def __init__(self, command):
... | core/executable.py | __description__ = "an Executable class implementation"
__version__ = "0.1.0"
__author__ = "<NAME>."
import os
from subprocess import Popen, PIPE, STDOUT
class Executable(object):
"""
Executable - abstract class implementing the executable script
"""
def __init__(self, command):
... | 0.602179 | 0.087759 |
import datetime
import typing as T
import logging as lg
from .. import _util
_logger = lg.getLogger(__name__)
class ChoiceRule:
"""A choice case for the 'Choice' state.
Args:
next_state (sfini.state.State): state to execute on success
"""
_final = False
def __init__(self, next_state=N... | src/sfini/state/choice.py | import datetime
import typing as T
import logging as lg
from .. import _util
_logger = lg.getLogger(__name__)
class ChoiceRule:
"""A choice case for the 'Choice' state.
Args:
next_state (sfini.state.State): state to execute on success
"""
_final = False
def __init__(self, next_state=N... | 0.828731 | 0.290987 |
import os, sys
from unittest.mock import Mock, patch
import json
import asyncio
from nose.tools import assert_true, assert_list_equal, assert_dict_equal, assert_equals
import discord
sys.path.append('../src')
from btcapi import *
from commands import Commands
import bot
class TestBTCAPIClient(object):
@classmetho... | tests/tests.py | import os, sys
from unittest.mock import Mock, patch
import json
import asyncio
from nose.tools import assert_true, assert_list_equal, assert_dict_equal, assert_equals
import discord
sys.path.append('../src')
from btcapi import *
from commands import Commands
import bot
class TestBTCAPIClient(object):
@classmetho... | 0.214198 | 0.282513 |
import os
import numpy
import datetime
from pyami import mrc,imagefun
from leginon import leginondata,ddinfo
from appionlib import apDDprocess,apDisplay
# testing options
save_jpg = False
debug = False
ddtype = 'thin'
class SimFrameProcessing(apDDprocess.DDFrameProcessing):
'''
sim frame movie processing
'''
def... | lib/python2.7/site-packages/appionlib/apSimFrameProcess.py |
import os
import numpy
import datetime
from pyami import mrc,imagefun
from leginon import leginondata,ddinfo
from appionlib import apDDprocess,apDisplay
# testing options
save_jpg = False
debug = False
ddtype = 'thin'
class SimFrameProcessing(apDDprocess.DDFrameProcessing):
'''
sim frame movie processing
'''
def... | 0.299208 | 0.142351 |
import serial
from collections import deque
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class AnalogPlot:
def __init__(self, strPort, maxLen):
self.ser = serial.Serial(strPort, 9600)
# device initialization
self.ser.write(b'2') # start the stream
lin... | scalpel/utils/serial-plotter.py | import serial
from collections import deque
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class AnalogPlot:
def __init__(self, strPort, maxLen):
self.ser = serial.Serial(strPort, 9600)
# device initialization
self.ser.write(b'2') # start the stream
lin... | 0.428831 | 0.359027 |
from sqlalchemy import orm, func, and_
from origin.sql import SqlQuery
from .models import DbUser, DbExternalUser, DbToken, DbLoginRecord
class UserQuery(SqlQuery):
"""Query DbUser."""
def _get_base_query(self) -> orm.Query:
"""Override function used in base class."""
return self.session.q... | src/auth_api/queries.py | from sqlalchemy import orm, func, and_
from origin.sql import SqlQuery
from .models import DbUser, DbExternalUser, DbToken, DbLoginRecord
class UserQuery(SqlQuery):
"""Query DbUser."""
def _get_base_query(self) -> orm.Query:
"""Override function used in base class."""
return self.session.q... | 0.811041 | 0.194502 |
import json
import re
import textwrap
from collections import UserList, namedtuple
from datetime import datetime
from functools import reduce
from os.path import dirname, join, pardir
from urllib.parse import urlparse
from dateutil.relativedelta import relativedelta
from dateutil.rrule import MONTHLY, rrule
def load... | radarly/utils/misc.py | import json
import re
import textwrap
from collections import UserList, namedtuple
from datetime import datetime
from functools import reduce
from os.path import dirname, join, pardir
from urllib.parse import urlparse
from dateutil.relativedelta import relativedelta
from dateutil.rrule import MONTHLY, rrule
def load... | 0.704872 | 0.300681 |
import torch
import sys
import gym
from argparse import Namespace
import numpy as np
import glob
import re
import os
import copy
try:
import gym_minigrid
except ImportError:
pass
from models import get_model
from agents import get_agent
from utils import utils, get_wrappers, save_training, get_obss_pre_proce... | train_mtop_ppo.py | import torch
import sys
import gym
from argparse import Namespace
import numpy as np
import glob
import re
import os
import copy
try:
import gym_minigrid
except ImportError:
pass
from models import get_model
from agents import get_agent
from utils import utils, get_wrappers, save_training, get_obss_pre_proce... | 0.39036 | 0.231006 |
import discord
import json
import time
import os
from discord.ext import commands
WEEK = 604800
class Tracker(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.subjects = {}
self._checkrole_id = 458374484244693005
self._tracker_chan_id = 755624749824082050
with... | cogs/tracker.py | import discord
import json
import time
import os
from discord.ext import commands
WEEK = 604800
class Tracker(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.subjects = {}
self._checkrole_id = 458374484244693005
self._tracker_chan_id = 755624749824082050
with... | 0.365457 | 0.113703 |
from alembic import op
import sqlalchemy as sa
import commandment.dbtypes
from alembic import context
# revision identifiers, used by Alembic.
revision = '1005dc7dea01'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
schema_upgrades()
if context.get_x_argument(as_dictionary=T... | commandment/alembic/versions/1005dc7dea01_os_update_settings.py |
from alembic import op
import sqlalchemy as sa
import commandment.dbtypes
from alembic import context
# revision identifiers, used by Alembic.
revision = '1005dc7dea01'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
schema_upgrades()
if context.get_x_argument(as_dictionary=T... | 0.447702 | 0.096962 |
# While Loop
# 1. >>> n=1
# 2. >>> while(n<=5):
# 3. print("Hello")
# 4. n+=1
# FOR Loop
# 1. # List of numbers
# 2. numbers = [6,5,3,8,4,2,5,4,11]
# 3. # variable to store the sum
# 4. sum total = 0
# 5. # iterate over the list
# 6. for val in numbers:
# 7. sum total = sumtotal+totalval
# 8. # print the su... | Chapter 06/438_Chapter_6.py | # While Loop
# 1. >>> n=1
# 2. >>> while(n<=5):
# 3. print("Hello")
# 4. n+=1
# FOR Loop
# 1. # List of numbers
# 2. numbers = [6,5,3,8,4,2,5,4,11]
# 3. # variable to store the sum
# 4. sum total = 0
# 5. # iterate over the list
# 6. for val in numbers:
# 7. sum total = sumtotal+totalval
# 8. # print the su... | 0.125721 | 0.233991 |
x = 42
print(type(x)) # prints: <class 'int'>
class Robot:
__number_of_instances = 0
# name Public These attributes can be freely used inside or outside of a class definition.
# _name Protected Protected attributes should not be used outside of the class definition, unless inside of a subclass d... | oop/classes.py |
x = 42
print(type(x)) # prints: <class 'int'>
class Robot:
__number_of_instances = 0
# name Public These attributes can be freely used inside or outside of a class definition.
# _name Protected Protected attributes should not be used outside of the class definition, unless inside of a subclass d... | 0.500488 | 0.266653 |
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.db.models import Avg
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reve... | website/views.py | from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.db.models import Avg
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reve... | 0.408513 | 0.054199 |
import argparse
from argparse import RawTextHelpFormatter
import logging
from asreview.ascii import welcome_message
from asreview.config import DEFAULT_MODEL, DEFAULT_FEATURE_EXTRACTION
from asreview.config import DEFAULT_QUERY_STRATEGY
from asreview.config import DEFAULT_BALANCE_STRATEGY
from asreview.config import ... | asreview/entry_points/oracle.py | import argparse
from argparse import RawTextHelpFormatter
import logging
from asreview.ascii import welcome_message
from asreview.config import DEFAULT_MODEL, DEFAULT_FEATURE_EXTRACTION
from asreview.config import DEFAULT_QUERY_STRATEGY
from asreview.config import DEFAULT_BALANCE_STRATEGY
from asreview.config import ... | 0.703142 | 0.211641 |
import ctypes
import IceRayPy
import IceRayPy.type.math.interval
Pointer = ctypes.POINTER
AddresOf = ctypes.addressof
Scalar = IceRayPy.type.basic.Scalar
Coord3D = IceRayPy.type.math.coord.Scalar3D
Interval3D = IceRayPy.type.math.interval.Scalar3D
class Vacuum:
def __init__( self, P_dll ... | src/IceRayPy/core/geometry/volumetric.py | import ctypes
import IceRayPy
import IceRayPy.type.math.interval
Pointer = ctypes.POINTER
AddresOf = ctypes.addressof
Scalar = IceRayPy.type.basic.Scalar
Coord3D = IceRayPy.type.math.coord.Scalar3D
Interval3D = IceRayPy.type.math.interval.Scalar3D
class Vacuum:
def __init__( self, P_dll ... | 0.355999 | 0.321274 |
import numpy as np
import time
import my_sgf
B = -1 # black
N = 0 # none
W = 1 # white
# B and W do not matter when call the function. Because this is onyl a test file.
# But make sure set the blank(empty) as 0.
if __name__ == "__main__":
"""
------------------------------------------
move(board, pos... | Model Train/test_sgf.py | import numpy as np
import time
import my_sgf
B = -1 # black
N = 0 # none
W = 1 # white
# B and W do not matter when call the function. Because this is onyl a test file.
# But make sure set the blank(empty) as 0.
if __name__ == "__main__":
"""
------------------------------------------
move(board, pos... | 0.32146 | 0.479626 |
import numpy as np
# Referenced colorconv.py from scikit-image for more efficient implementation
# of colorspace transformations. Will continue to maintain an independent
# implementation for educational purposes but scikit-image is the standard.
# https://wikipedia.org/wiki/Standard_illuminant
# These values assume ... | dmtools/colorspace.py | import numpy as np
# Referenced colorconv.py from scikit-image for more efficient implementation
# of colorspace transformations. Will continue to maintain an independent
# implementation for educational purposes but scikit-image is the standard.
# https://wikipedia.org/wiki/Standard_illuminant
# These values assume ... | 0.89616 | 0.750324 |
from django.core.paginator import EmptyPage
from django.db.models import Prefetch
from django.http import Http404
from django.shortcuts import redirect, render
from django.urls import reverse
from elections.forms import MayorCandidatesFiltersForm
from elections.models import Debates, Election, EuroParliamentCandidate,... | elections/views.py | from django.core.paginator import EmptyPage
from django.db.models import Prefetch
from django.http import Http404
from django.shortcuts import redirect, render
from django.urls import reverse
from elections.forms import MayorCandidatesFiltersForm
from elections.models import Debates, Election, EuroParliamentCandidate,... | 0.447702 | 0.139133 |
from django.shortcuts import get_object_or_404, get_list_or_404
from django.http import Http404, QueryDict
from django.db.models import Q
from django.contrib.postgres.search import SearchQuery
from django.utils import timezone
from rest_framework.views import APIView
from rest_framework.response import Response
from r... | home_seller_app/sell/api/views.py | from django.shortcuts import get_object_or_404, get_list_or_404
from django.http import Http404, QueryDict
from django.db.models import Q
from django.contrib.postgres.search import SearchQuery
from django.utils import timezone
from rest_framework.views import APIView
from rest_framework.response import Response
from r... | 0.390708 | 0.120931 |
DESCRIPTION = """
"""
import os
import argparse
import logging
import h5py
import numpy as np
from scipy.io import loadmat, savemat
def runcmd(cmd):
""" Run command.
"""
logging.info("%s" % cmd)
os.system(cmd)
def getargs():
""" Parse program arguments.
"""
parser = argparse.Argument... | scripts/merge.py | DESCRIPTION = """
"""
import os
import argparse
import logging
import h5py
import numpy as np
from scipy.io import loadmat, savemat
def runcmd(cmd):
""" Run command.
"""
logging.info("%s" % cmd)
os.system(cmd)
def getargs():
""" Parse program arguments.
"""
parser = argparse.Argument... | 0.464659 | 0.193319 |
# Standard library imports
import socket
import os
import pwd
import math
# Third party imports
from google.protobuf.service import RpcChannel
# Protobuf imports
import snakebite.protobuf.RpcPayloadHeader_pb2 as rpcheaderproto
import snakebite.protobuf.IpcConnectionContext_pb2 as connectionContext
import snakebite.pr... | snakebite/channel.py | # Standard library imports
import socket
import os
import pwd
import math
# Third party imports
from google.protobuf.service import RpcChannel
# Protobuf imports
import snakebite.protobuf.RpcPayloadHeader_pb2 as rpcheaderproto
import snakebite.protobuf.IpcConnectionContext_pb2 as connectionContext
import snakebite.pr... | 0.488527 | 0.162712 |
import unittest
from mycleanup import (
get_all_matching_keys,
is_matching_versioned_pattern,
)
import mycleanup
from mydeploy import S3Util
import boto
from contextlib import redirect_stdout
import io
import moto
exists = S3Util.file_exists_in_s3_bucket
upload = S3Util.upload_gzipped_file_to_bucket
... | test_mycleanup.py | import unittest
from mycleanup import (
get_all_matching_keys,
is_matching_versioned_pattern,
)
import mycleanup
from mydeploy import S3Util
import boto
from contextlib import redirect_stdout
import io
import moto
exists = S3Util.file_exists_in_s3_bucket
upload = S3Util.upload_gzipped_file_to_bucket
... | 0.382141 | 0.27349 |
import os
import sys
import argparse
import time
import random
import copy
import shutil
import scipy.io as sio
import math
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn
from torch.utils.data import DataLoader
from tqdm impo... | main-test.py | import os
import sys
import argparse
import time
import random
import copy
import shutil
import scipy.io as sio
import math
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn
from torch.utils.data import DataLoader
from tqdm impo... | 0.38341 | 0.083255 |
from django.views.generic import ListView, DetailView, CreateView, \
DeleteView, UpdateView, \
ArchiveIndexView, DateDetailView, \
DayArchiveView, MonthArchiveView, \
TodayArchiveView, Wee... | students/views/child_family_detail_views.py | from django.views.generic import ListView, DetailView, CreateView, \
DeleteView, UpdateView, \
ArchiveIndexView, DateDetailView, \
DayArchiveView, MonthArchiveView, \
TodayArchiveView, Wee... | 0.375821 | 0.121895 |
from django.urls import reverse_lazy
from django.contrib import messages
from django.shortcuts import redirect, render
from django.contrib.auth import (authenticate,
login,
logout,
update_session_auth_hash)
from django.co... | mainapp/accounts/views.py | from django.urls import reverse_lazy
from django.contrib import messages
from django.shortcuts import redirect, render
from django.contrib.auth import (authenticate,
login,
logout,
update_session_auth_hash)
from django.co... | 0.496582 | 0.069007 |
import os
import click
import subprocess
from typing import List
from persia.logger import get_logger
_logger = get_logger(__file__)
_DEBUG = int(os.environ.get("DEBUG", False))
_ENV = os.environ.copy()
if _DEBUG:
# add persia_dev_path into PATH
persia_dev_path = os.environ.get("PERSIA_DEV_PATH", None)
... | persia/launcher.py | import os
import click
import subprocess
from typing import List
from persia.logger import get_logger
_logger = get_logger(__file__)
_DEBUG = int(os.environ.get("DEBUG", False))
_ENV = os.environ.copy()
if _DEBUG:
# add persia_dev_path into PATH
persia_dev_path = os.environ.get("PERSIA_DEV_PATH", None)
... | 0.427636 | 0.074838 |
import argparse
import utils
import networks
import torch
from torch import autograd
import torch.optim as optim
import torch.nn.functional as F
def get_flags():
arg_parser = argparse.ArgumentParser(
description="Parser for distillation experiment.")
arg_parser.add_argument("--dataset", type=str, defau... | train.py | import argparse
import utils
import networks
import torch
from torch import autograd
import torch.optim as optim
import torch.nn.functional as F
def get_flags():
arg_parser = argparse.ArgumentParser(
description="Parser for distillation experiment.")
arg_parser.add_argument("--dataset", type=str, defau... | 0.692226 | 0.228544 |
from tensorflow.keras import backend as K
from yolo2.postprocess import yolo2_head
def _smooth_labels(y_true, label_smoothing):
label_smoothing = K.constant(label_smoothing, dtype=K.floatx())
return y_true * (1.0 - label_smoothing) + 0.5 * label_smoothing
def yolo2_loss(args, anchors, num_classes, label_sm... | yolo2/loss.py |
from tensorflow.keras import backend as K
from yolo2.postprocess import yolo2_head
def _smooth_labels(y_true, label_smoothing):
label_smoothing = K.constant(label_smoothing, dtype=K.floatx())
return y_true * (1.0 - label_smoothing) + 0.5 * label_smoothing
def yolo2_loss(args, anchors, num_classes, label_sm... | 0.813238 | 0.554893 |
import os
import signal
import sys
import unittest
from devil import devil_env
from devil.android.sdk import adb_wrapper
from devil.utils import cmd_helper
from devil.utils import timeout_retry
_PYMOCK_PATH = os.path.abspath(os.path.join(
os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, os.pardir,
... | third_party/catapult/devil/devil/android/sdk/adb_compatibility_devicetest.py |
import os
import signal
import sys
import unittest
from devil import devil_env
from devil.android.sdk import adb_wrapper
from devil.utils import cmd_helper
from devil.utils import timeout_retry
_PYMOCK_PATH = os.path.abspath(os.path.join(
os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, os.pardir,
... | 0.202286 | 0.179963 |
from datetime import datetime
# Use to generate token
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app
from app import db, login_manager
from flask_login import UserMixin
# This is where the session or current_user gets the data when login_user is triggered
@login_ma... | app/models.py | from datetime import datetime
# Use to generate token
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app
from app import db, login_manager
from flask_login import UserMixin
# This is where the session or current_user gets the data when login_user is triggered
@login_ma... | 0.643553 | 0.071526 |
from pyquil import Program
from pyquil.api import QuantumComputer
from pyquil.gates import I
from pyquil.api._quantum_computer import Executable
from pyquil.noise import add_decoherence_noise
import numpy as np
import types
from typing import Iterator
from pyquil.quilbase import Gate
__all__ = ['apply_em', 'apply_no... | em_pyquil/__init__.py | from pyquil import Program
from pyquil.api import QuantumComputer
from pyquil.gates import I
from pyquil.api._quantum_computer import Executable
from pyquil.noise import add_decoherence_noise
import numpy as np
import types
from typing import Iterator
from pyquil.quilbase import Gate
__all__ = ['apply_em', 'apply_no... | 0.815783 | 0.626496 |
import sqlalchemy as sa
from aim.db import model_base
# Some aim_lib utilities may require additional DB model for keeping state.
# Use this module for such purpose
class CloneL3Out(model_base.Base):
"""DB model for CloneL3Out.
Keeps relationship between L3Outs and their clones.
Each L3Out can be clo... | aim/aim_lib/db/model.py |
import sqlalchemy as sa
from aim.db import model_base
# Some aim_lib utilities may require additional DB model for keeping state.
# Use this module for such purpose
class CloneL3Out(model_base.Base):
"""DB model for CloneL3Out.
Keeps relationship between L3Outs and their clones.
Each L3Out can be clo... | 0.693265 | 0.212886 |
from rdkit import Chem
from rdkit.Chem import rdMolAlign
from utils.mcs import substucture_search
from utils.io import read_sdf, write_sdf
from utils.rmsd import find_closest_mcs
def align(target_pose, ref_pose, substructure=None):
"""Aligmnent of target_pose against reference
Args:
ref_pose (TYPE): ... | Alignment.py | from rdkit import Chem
from rdkit.Chem import rdMolAlign
from utils.mcs import substucture_search
from utils.io import read_sdf, write_sdf
from utils.rmsd import find_closest_mcs
def align(target_pose, ref_pose, substructure=None):
"""Aligmnent of target_pose against reference
Args:
ref_pose (TYPE): ... | 0.630002 | 0.398465 |
import magma as m
import mantle
import fault
import hwtypes as ht
import os
import tempfile
def test_top():
# First, we define an interface generator for an N-bit adder
def DeclareAdder(N):
"""
Generates the interface for an N-bit adder
"""
T = m.UInt[N]
class Adder(m.... | tests/test_select_model.py | import magma as m
import mantle
import fault
import hwtypes as ht
import os
import tempfile
def test_top():
# First, we define an interface generator for an N-bit adder
def DeclareAdder(N):
"""
Generates the interface for an N-bit adder
"""
T = m.UInt[N]
class Adder(m.... | 0.584864 | 0.490785 |
import os
import pandas
import numpy
from calendar import formatstring
from CommonDef.DefStr import *
from unittest.mock import inplace
def SymbolToPath(symbol, save_dir = "data"):
"""Return CSV file path given ticker symbol."""
return os.path.join(save_dir, "{}.csv".format(str(symbol)))
def CalChange(now, ... | src/Program/Common.py | import os
import pandas
import numpy
from calendar import formatstring
from CommonDef.DefStr import *
from unittest.mock import inplace
def SymbolToPath(symbol, save_dir = "data"):
"""Return CSV file path given ticker symbol."""
return os.path.join(save_dir, "{}.csv".format(str(symbol)))
def CalChange(now, ... | 0.605333 | 0.29443 |
from audiomate import annotations
from evalmate import alignment
from evalmate import confusion
import pytest
def test_create_from_segments():
segments = [
alignment.Segment(0, 4, annotations.Label('music', start=0, end=5), annotations.Label('music', start=0, end=4)),
alignment.Segment(4, 5, ann... | tests/confusion/__init__.py | from audiomate import annotations
from evalmate import alignment
from evalmate import confusion
import pytest
def test_create_from_segments():
segments = [
alignment.Segment(0, 4, annotations.Label('music', start=0, end=5), annotations.Label('music', start=0, end=4)),
alignment.Segment(4, 5, ann... | 0.810066 | 0.768907 |
from sys import argv
import os
from os import path
import itertools
import numpy as np
import json
from collections import Counter
import torch
from allennlp.data import Vocabulary
from dygie.models.shared import fields_to_batches
from dygie.commands import predict_dygie as pdy
def unwrap(trig_pred_dict):
res... | dygiepp/dygie/commands/predict_from_ensemble.py |
from sys import argv
import os
from os import path
import itertools
import numpy as np
import json
from collections import Counter
import torch
from allennlp.data import Vocabulary
from dygie.models.shared import fields_to_batches
from dygie.commands import predict_dygie as pdy
def unwrap(trig_pred_dict):
res... | 0.419648 | 0.2927 |