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 json import unittest import player TWO_PAIR_HAND = [ { "rank": "A", "suit": "hearts" }, { "rank": "A", "suit": "spades" }, { "rank": "8", "suit": "hearts" }, { "rank": "8", "suit": "spades" }, { "rank": ...
tests.py
import json import unittest import player TWO_PAIR_HAND = [ { "rank": "A", "suit": "hearts" }, { "rank": "A", "suit": "spades" }, { "rank": "8", "suit": "hearts" }, { "rank": "8", "suit": "spades" }, { "rank": ...
0.386185
0.353149
def _js_devserver(ctx): files = depset() for d in ctx.attr.deps: if hasattr(d, "node_sources"): files = depset(transitive=[d.node_sources, files]) elif hasattr(d, "files"): files = depset(transitive=[d.files, files]) if ctx.label.workspace_root: # We need the...
experimental/js_devserver/defs.bzl
def _js_devserver(ctx): files = depset() for d in ctx.attr.deps: if hasattr(d, "node_sources"): files = depset(transitive=[d.node_sources, files]) elif hasattr(d, "files"): files = depset(transitive=[d.files, files]) if ctx.label.workspace_root: # We need the...
0.331012
0.23156
import argparse import cv2 import numpy as np import timm import torch from PIL import Image from torchvision import transforms from vit_grad_rollout import VITAttentionGradRollout from vit_rollout import VITAttentionRollout def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--use_cuda'...
vit_explain.py
import argparse import cv2 import numpy as np import timm import torch from PIL import Image from torchvision import transforms from vit_grad_rollout import VITAttentionGradRollout from vit_rollout import VITAttentionRollout def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--use_cuda'...
0.779993
0.209308
import sys import inspect from django import forms from django.apps import apps from backend.models import Artist from backend.models import Album def get_model_form_class(app_label, model_name): model_form_class = None # List all ModelForms in this module model_forms = [ klass for name,...
sample_project/frontend/forms.py
import sys import inspect from django import forms from django.apps import apps from backend.models import Artist from backend.models import Album def get_model_form_class(app_label, model_name): model_form_class = None # List all ModelForms in this module model_forms = [ klass for name,...
0.342462
0.175573
import torch from transformers import BertTokenizer import transformers transformers.logging.set_verbosity_error() import pickle import argparse import os from data.data_loader import load_dataset from models.bert_multi_tokens import MultiTokensBERT from prompts.prompt_scorer import ContentPromptScorer, LogicalPrompt...
main.py
import torch from transformers import BertTokenizer import transformers transformers.logging.set_verbosity_error() import pickle import argparse import os from data.data_loader import load_dataset from models.bert_multi_tokens import MultiTokensBERT from prompts.prompt_scorer import ContentPromptScorer, LogicalPrompt...
0.581303
0.173201
import os import yaml import logging.config import logging from pathlib import Path from email.mime.text import MIMEText from email.header import Header from email.utils import formataddr __all__ = ["setup_logging", "green", "blue", "yellow", "red", "blue_bar"] class TColors: """ Terminal Colors """ ...
fx_lib/log.py
import os import yaml import logging.config import logging from pathlib import Path from email.mime.text import MIMEText from email.header import Header from email.utils import formataddr __all__ = ["setup_logging", "green", "blue", "yellow", "red", "blue_bar"] class TColors: """ Terminal Colors """ ...
0.361616
0.08819
import os import numpy as np import pandas as pd def sid_subdir_path(sid): """ Format subdir path to limit the number directories in any given subdirectory to 100. The number in each directory is designed to support at least 100000 equities. Parameters ---------- sid : int A...
rqalpha/mod/rqalpha_mod_fxdayu_source/share/utils.py
import os import numpy as np import pandas as pd def sid_subdir_path(sid): """ Format subdir path to limit the number directories in any given subdirectory to 100. The number in each directory is designed to support at least 100000 equities. Parameters ---------- sid : int A...
0.716913
0.441673
import unittest, sys, os, os.path curfilePath = os.path.abspath(__file__) curDir = os.path.abspath(os.path.join(curfilePath,os.pardir)) # this will return current directory in which python file resides. parentDir = os.path.abspath(os.path.join(curDir,os.pardir)) # this will return parent directory. sys.path.append(pare...
test_files/combine_test.py
import unittest, sys, os, os.path curfilePath = os.path.abspath(__file__) curDir = os.path.abspath(os.path.join(curfilePath,os.pardir)) # this will return current directory in which python file resides. parentDir = os.path.abspath(os.path.join(curDir,os.pardir)) # this will return parent directory. sys.path.append(pare...
0.251372
0.32338
from datetime import datetime from dateutil.relativedelta import relativedelta from openerp.osv import fields, osv import openerp.addons.decimal_precision as dp import time from openerp.tools.translate import _ import datetime import simplejson try: from openerp import SUPERUSER_ID except ImportError: SUPERUS...
Code/odooerp/odoo-8.0/adding/purchase_order/purchase_order.py
from datetime import datetime from dateutil.relativedelta import relativedelta from openerp.osv import fields, osv import openerp.addons.decimal_precision as dp import time from openerp.tools.translate import _ import datetime import simplejson try: from openerp import SUPERUSER_ID except ImportError: SUPERUS...
0.403802
0.11737
import numpy as np import numba import pyfftw from scipy import ndimage as scnd from ..proc import sobel_canny as sc from ..util import gauss_utils as gt from ..util import image_utils as iu @numba.jit def resize_rotate(original_4D, final_size, rotangle, sampler=2,...
pty/pie.py
import numpy as np import numba import pyfftw from scipy import ndimage as scnd from ..proc import sobel_canny as sc from ..util import gauss_utils as gt from ..util import image_utils as iu @numba.jit def resize_rotate(original_4D, final_size, rotangle, sampler=2,...
0.749912
0.640495
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler from sklearn.compose import ColumnTransformer, make_column_tran...
src/preprocessor.py
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler from sklearn.compose import ColumnTransformer, make_column_tran...
0.739234
0.305503
from json import load def gen_mods(): with open(r'C:\git\RePoE\RePoE\data\mods.json', 'r') as f: mods = load(f) with open(r'C:\git\RePoE\RePoE\data\stat_translations.json', 'r') as f: stats = load(f) map_mods = set() for mod in mods: if mods[mod]['generation_type'] in ['prefix', 'suffix'] and (any(x['weigh...
helper_files/gen_map_mods.py
from json import load def gen_mods(): with open(r'C:\git\RePoE\RePoE\data\mods.json', 'r') as f: mods = load(f) with open(r'C:\git\RePoE\RePoE\data\stat_translations.json', 'r') as f: stats = load(f) map_mods = set() for mod in mods: if mods[mod]['generation_type'] in ['prefix', 'suffix'] and (any(x['weigh...
0.217504
0.257345
from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class Germplasm(Model): """NOTE: This class is auto generated by the swagger code generator pr...
swagger_codegen_server/swagger_server/models/germplasm.py
from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class Germplasm(Model): """NOTE: This class is auto generated by the swagger code generator pr...
0.803945
0.078254
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0002_auto_20150616_2121'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('ar...
mysite/article/migrations/0002_auto_20190306_1640.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0002_auto_20150616_2121'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('ar...
0.524151
0.092852
from concurrent.futures import ThreadPoolExecutor import typing from unittest import mock from common.bounded_executor import BoundedExecutor def create_bounded_pool_executor( bound, max_workers, block_timeout ) -> typing.Tuple[mock.MagicMock, BoundedExecutor]: """Creates a mocked thread pool and a bounded ...
common/tests/test_bounded_executor.py
from concurrent.futures import ThreadPoolExecutor import typing from unittest import mock from common.bounded_executor import BoundedExecutor def create_bounded_pool_executor( bound, max_workers, block_timeout ) -> typing.Tuple[mock.MagicMock, BoundedExecutor]: """Creates a mocked thread pool and a bounded ...
0.860164
0.49939
import pickle from functools import lru_cache from urllib.parse import urlparse import numpy as np from gensim.models.keyedvectors import KeyedVectors from redis import Redis from redis.exceptions import RedisError from tqdm import tqdm class RedisKeyedVectorException(Exception): """ Raised when RedisKeyedVector...
textpipe/wrappers.py
import pickle from functools import lru_cache from urllib.parse import urlparse import numpy as np from gensim.models.keyedvectors import KeyedVectors from redis import Redis from redis.exceptions import RedisError from tqdm import tqdm class RedisKeyedVectorException(Exception): """ Raised when RedisKeyedVector...
0.643777
0.427815
from SPARQLWrapper import SPARQLWrapper, JSON, POST, URLENCODED import memcache import logging import hashlib import pickle import pandas as pd import datetime import typing import os import json from datamart_isi import config from datamart_isi.utilities import connection from datamart_isi.utilities.singleton import s...
datamart_isi/cache/general_search_cache.py
from SPARQLWrapper import SPARQLWrapper, JSON, POST, URLENCODED import memcache import logging import hashlib import pickle import pandas as pd import datetime import typing import os import json from datamart_isi import config from datamart_isi.utilities import connection from datamart_isi.utilities.singleton import s...
0.568416
0.062991
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.calliope.concepts import concepts from googlecloudsdk.calliope.concepts import deps from googlecloudsdk.command_lib.util.concepts import concept_parsers from googlecloudsdk.core import pro...
lib/googlecloudsdk/command_lib/transcoder/resource_args.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.calliope.concepts import concepts from googlecloudsdk.calliope.concepts import deps from googlecloudsdk.command_lib.util.concepts import concept_parsers from googlecloudsdk.core import pro...
0.690976
0.061763
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import tensorflow_hub as hub import pandas as pd # Keras from tensorflow import keras import keras.layers as layers from keras.models import Model from keras.utils import plot_model from keras import backend as K # General imports import gzip ...
Tensorflow/Amazon Question Answer model/Model.py
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import tensorflow_hub as hub import pandas as pd # Keras from tensorflow import keras import keras.layers as layers from keras.models import Model from keras.utils import plot_model from keras import backend as K # General imports import gzip ...
0.393968
0.330958
from operator import itemgetter from typing import List, Union from pylatex import Alignat, NoEscape, LongTable, MultiColumn try: from pytexit import py2tex except ModuleNotFoundError: pass def py2tex_modified(exps: Union[List, tuple, str]): if isinstance(exps, tuple): exps = list(exps) if ...
fsetools/etc/latex.py
from operator import itemgetter from typing import List, Union from pylatex import Alignat, NoEscape, LongTable, MultiColumn try: from pytexit import py2tex except ModuleNotFoundError: pass def py2tex_modified(exps: Union[List, tuple, str]): if isinstance(exps, tuple): exps = list(exps) if ...
0.550245
0.287658
import subprocess import re import os from identity_matching.src.matching import IdentityMatcher from identity_matching.src.model import DistanceModel from identity_matching.src.preprocessor import DistancePreprocessor from identity_matching.src.transform_shortlog import process_shortlog_line def match_emails(direct...
src/identity_matching/matcher.py
import subprocess import re import os from identity_matching.src.matching import IdentityMatcher from identity_matching.src.model import DistanceModel from identity_matching.src.preprocessor import DistancePreprocessor from identity_matching.src.transform_shortlog import process_shortlog_line def match_emails(direct...
0.152568
0.081849
import importlib import json import logging import os import sys import cherrypy from cryptojwt.key_jar import build_keyjar from cryptojwt.key_jar import KeyJar from oidcrp import RPHandler logger = logging.getLogger("") LOGFILE_NAME = 'farp.log' hdlr = logging.FileHandler(LOGFILE_NAME) base_formatter = logging.For...
example/cherrypy_rp/chrp/rp.py
import importlib import json import logging import os import sys import cherrypy from cryptojwt.key_jar import build_keyjar from cryptojwt.key_jar import KeyJar from oidcrp import RPHandler logger = logging.getLogger("") LOGFILE_NAME = 'farp.log' hdlr = logging.FileHandler(LOGFILE_NAME) base_formatter = logging.For...
0.18743
0.043447
import matplotlib import matplotlib.pyplot as plt import os, sys import numpy as np import string import math import operator import multiprocessing from multiprocessing import Pool matplotlib.rcParams['text.usetex'] = True matplotlib.rcParams['font.family'] = 'serif' matplotlib.rcParams['font.size'] ...
examples/4-4-1-reconstruct_eclipse/plot.py
import matplotlib import matplotlib.pyplot as plt import os, sys import numpy as np import string import math import operator import multiprocessing from multiprocessing import Pool matplotlib.rcParams['text.usetex'] = True matplotlib.rcParams['font.family'] = 'serif' matplotlib.rcParams['font.size'] ...
0.273186
0.284124
from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.utils.data import now from mvd.mvd.doctype.mitgliedschaft.mitgliedschaft import create_mitgliedschaftsrechnung from frappe.utils.background_jobs import enqueue import time from frappe.utils.csvutils import to_c...
mvd/mvd/doctype/mv_jahresversand/mv_jahresversand.py
from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.utils.data import now from mvd.mvd.doctype.mitgliedschaft.mitgliedschaft import create_mitgliedschaftsrechnung from frappe.utils.background_jobs import enqueue import time from frappe.utils.csvutils import to_c...
0.208018
0.156459
import sys, json, os, re, requests import nvd, scancode from glob import glob from os import path, remove from subprocess import call from collections import OrderedDict from shutil import rmtree def main(argv): if len(argv) <= 1: print("Usage: ./riskmetrics.py <github-repo-url>") exit(2) ...
riskmetrics/riskmetrics.py
import sys, json, os, re, requests import nvd, scancode from glob import glob from os import path, remove from subprocess import call from collections import OrderedDict from shutil import rmtree def main(argv): if len(argv) <= 1: print("Usage: ./riskmetrics.py <github-repo-url>") exit(2) ...
0.381104
0.123762
# Configuration files consist of functions which define build "targets." # This function creates a Python executable and installs it in a destination # directory. def resource_callback(policy, resource): if type(resource) in ("PythonExtensionModule") or "pytest" in resource.name or "pluggy" in resource.name or "...
pyoxidizer.bzl
# Configuration files consist of functions which define build "targets." # This function creates a Python executable and installs it in a destination # directory. def resource_callback(policy, resource): if type(resource) in ("PythonExtensionModule") or "pytest" in resource.name or "pluggy" in resource.name or "...
0.61682
0.221025
import logging import numpy as np from deprecated import deprecated logger = logging.getLogger(__name__) @deprecated(version="1.1") def index(arr, item): # pragma: no cover for idx, val in np.ndenumerate(arr): if val == item: return idx # If no item was found return None, other return t...
omicron/core/accelerate.py
import logging import numpy as np from deprecated import deprecated logger = logging.getLogger(__name__) @deprecated(version="1.1") def index(arr, item): # pragma: no cover for idx, val in np.ndenumerate(arr): if val == item: return idx # If no item was found return None, other return t...
0.634543
0.353191
from django.db.models import Avg, Sum, Count from django import forms from django.forms.widgets import Input from django.http import HttpResponse from django.template import RequestContext, loader from django.views.decorators.cache import cache_page from colourlens.models import Artwork, Colour PROM_ATTRS = {'min': '0...
colourlens/views.py
from django.db.models import Avg, Sum, Count from django import forms from django.forms.widgets import Input from django.http import HttpResponse from django.template import RequestContext, loader from django.views.decorators.cache import cache_page from colourlens.models import Artwork, Colour PROM_ATTRS = {'min': '0...
0.705684
0.093761
import collections import copy import progressbar from . import mutator_options from . import semantics Mutation = collections.namedtuple('Mutation', ['nodeid', 'name', 'localm', 'globalm']) enabled_mutators = [] def collect_mutators(args): """Initializes the list of all active mutators.""" global enabled_m...
pydelta/mutator.py
import collections import copy import progressbar from . import mutator_options from . import semantics Mutation = collections.namedtuple('Mutation', ['nodeid', 'name', 'localm', 'globalm']) enabled_mutators = [] def collect_mutators(args): """Initializes the list of all active mutators.""" global enabled_m...
0.681727
0.220762
import requests from datetime import datetime, timedelta from requests.auth import HTTPBasicAuth from requests import Request from .config import logger, \ GPM_APP_PASSWORD, \ GPM_EMAIL_ADDRESS, \ SPOTIFY_CLIENT_ID, \ SPOTIFY_CLIENT_SECRET from .exceptions import AuthError from .utils import _raise_fo...
musicsync/auth.py
import requests from datetime import datetime, timedelta from requests.auth import HTTPBasicAuth from requests import Request from .config import logger, \ GPM_APP_PASSWORD, \ GPM_EMAIL_ADDRESS, \ SPOTIFY_CLIENT_ID, \ SPOTIFY_CLIENT_SECRET from .exceptions import AuthError from .utils import _raise_fo...
0.474875
0.054099
from fastapi.testclient import TestClient from api.main import app, get_db from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from api.database import Base import os SQLALCHEMY_DATABASE_PATH = "./test.db" SQLALCHEMY_DATABASE_URL = "sqlite:///" + SQLALCHEMY_DATABASE_PATH try: os.remove(SQL...
tests/test_1.py
from fastapi.testclient import TestClient from api.main import app, get_db from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from api.database import Base import os SQLALCHEMY_DATABASE_PATH = "./test.db" SQLALCHEMY_DATABASE_URL = "sqlite:///" + SQLALCHEMY_DATABASE_PATH try: os.remove(SQL...
0.632162
0.349894
from deeppavlov.models.tokenizers.spacy_tokenizer import StreamSpacyTokenizer from deeppavlov.models.sklearn import SklearnComponent from deeppavlov.dataset_readers.faq_reader import FaqDatasetReader from deeppavlov.core.data.data_learning_iterator import DataLearningIterator FAQ_DATASET_URL = "../data/faq.csv" """ ...
heroku_client/echobot.py
from deeppavlov.models.tokenizers.spacy_tokenizer import StreamSpacyTokenizer from deeppavlov.models.sklearn import SklearnComponent from deeppavlov.dataset_readers.faq_reader import FaqDatasetReader from deeppavlov.core.data.data_learning_iterator import DataLearningIterator FAQ_DATASET_URL = "../data/faq.csv" """ ...
0.655557
0.379896
from solutionparser import SolutionParser, SladerBook, SladerAnswer, SolutionParameters import xml.etree.ElementTree as ET # Alias for SolutionParameters Params = SolutionParameters class XmlSolutionParser(SolutionParser): """ Parse solutions from a given XML file. See example file for the format """...
src/xmlparser.py
from solutionparser import SolutionParser, SladerBook, SladerAnswer, SolutionParameters import xml.etree.ElementTree as ET # Alias for SolutionParameters Params = SolutionParameters class XmlSolutionParser(SolutionParser): """ Parse solutions from a given XML file. See example file for the format """...
0.68637
0.273405
from math import * # -------------------------------------- # -- # -- PROBLEME I # -- # -------------------------------------- def lucas1(n): if n == 0: return 2 phi = (1 + sqrt(5)) / 2 phi2 = (1 - sqrt(5)) / 2 return phi ** n + phi2 ** n def lucas2(n): if n == 0: return 2 ...
exo_6_1.py
from math import * # -------------------------------------- # -- # -- PROBLEME I # -- # -------------------------------------- def lucas1(n): if n == 0: return 2 phi = (1 + sqrt(5)) / 2 phi2 = (1 - sqrt(5)) / 2 return phi ** n + phi2 ** n def lucas2(n): if n == 0: return 2 ...
0.085327
0.499634
# %% from utils import ( get_cifar10_data_loaders, compute_validation_accuracy_multi, NN_FC_CrossEntropy, train_one_epoch, ) from fastprogress.fastprogress import master_bar import torch from torch import nn from torchvision.utils import make_grid from torchvision.models import resnet18 import matpl...
lectures/l21-convolutional-neural-networks.py
# %% from utils import ( get_cifar10_data_loaders, compute_validation_accuracy_multi, NN_FC_CrossEntropy, train_one_epoch, ) from fastprogress.fastprogress import master_bar import torch from torch import nn from torchvision.utils import make_grid from torchvision.models import resnet18 import matpl...
0.86332
0.551393
import pydicom import os import numpy as np from skimage.morphology import disk, binary_dilation from cyvlfeat.fisher import fisher from sklearn.linear_model import LogisticRegression from numba import cuda import pickle class Classifier: def __init__(self, fileData, rawDataPath, maskDataPath): self.PATH...
server/classifier.py
import pydicom import os import numpy as np from skimage.morphology import disk, binary_dilation from cyvlfeat.fisher import fisher from sklearn.linear_model import LogisticRegression from numba import cuda import pickle class Classifier: def __init__(self, fileData, rawDataPath, maskDataPath): self.PATH...
0.238994
0.209551
import json import os import pickle import pandas as pd def append_csv(data, path): """ append to a csv """ assert path.endswith(".csv") to_log = data if isinstance(data, pd.DataFrame) else pd.DataFrame(data) if "~" in path: print("Dont include the user path as ~!, use os.path.expanduser") ...
doors/inout.py
import json import os import pickle import pandas as pd def append_csv(data, path): """ append to a csv """ assert path.endswith(".csv") to_log = data if isinstance(data, pd.DataFrame) else pd.DataFrame(data) if "~" in path: print("Dont include the user path as ~!, use os.path.expanduser") ...
0.322099
0.150403
from __future__ import unicode_literals from .. import Provider as LoremProvider class Provider(LoremProvider): word_list = ( 'alias', 'consequatur', 'aut', 'perferendis', 'sit', 'voluptatem', 'accusantium', 'doloremque', 'aperiam', 'eaque', 'ipsa', 'quae', 'ab', 'illo', 'inventore', 'ver...
components/faker/faker/providers/lorem/la/__init__.py
from __future__ import unicode_literals from .. import Provider as LoremProvider class Provider(LoremProvider): word_list = ( 'alias', 'consequatur', 'aut', 'perferendis', 'sit', 'voluptatem', 'accusantium', 'doloremque', 'aperiam', 'eaque', 'ipsa', 'quae', 'ab', 'illo', 'inventore', 'ver...
0.485356
0.235779
"""Launch experiments through an orchestrator.""" import threading import time import datetime import logging from .experiment import Experiment from .dal import DAL class System(threading.Thread): def __init__(self, orchestrator, db, kafka_server): threading.Thread.__init__(self) self.logger = ...
scheduler/system/system.py
"""Launch experiments through an orchestrator.""" import threading import time import datetime import logging from .experiment import Experiment from .dal import DAL class System(threading.Thread): def __init__(self, orchestrator, db, kafka_server): threading.Thread.__init__(self) self.logger = ...
0.727975
0.146209
from typing import List from .comment_tokenizer import scan_for_comment from .iterator import LineWrapIterator, Span from .number_tokenizer import scan_for_number from .quote_tokenizer import scan_for_quote from .remaining_tokenizer import scan_for_remaining, RemainingToken from .token import Token, StartToken, EndTok...
src/quom/tokenizer/preprocessor_tokenizer.py
from typing import List from .comment_tokenizer import scan_for_comment from .iterator import LineWrapIterator, Span from .number_tokenizer import scan_for_number from .quote_tokenizer import scan_for_quote from .remaining_tokenizer import scan_for_remaining, RemainingToken from .token import Token, StartToken, EndTok...
0.7181
0.154759
import pytest import sys import StringIO from pypy.module.cpyext.state import State from pypy.module.cpyext.pyobject import make_ref from pypy.module.cpyext.test.test_api import BaseApiTest from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase from rpython.rtyper.lltypesystem import rffi class A...
pypy/module/cpyext/test/test_contextvars.py
import pytest import sys import StringIO from pypy.module.cpyext.state import State from pypy.module.cpyext.pyobject import make_ref from pypy.module.cpyext.test.test_api import BaseApiTest from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase from rpython.rtyper.lltypesystem import rffi class A...
0.270769
0.162314
import os import pickle import random import logging from collections import Counter import xmltodict import numpy as np import torch import sentencepiece as spm from matplotlib import pyplot as plt from torch.utils.data import Dataset, DataLoader from transformers import T5Tokenizer def prepare_data(file_name): ...
assin/assin_dataset.py
import os import pickle import random import logging from collections import Counter import xmltodict import numpy as np import torch import sentencepiece as spm from matplotlib import pyplot as plt from torch.utils.data import Dataset, DataLoader from transformers import T5Tokenizer def prepare_data(file_name): ...
0.602997
0.255364
import os import numpy as np from statistics import mean, stdev from nnga.datasets.base_dataset import BaseDataset from nnga.utils.data_io import ( load_csv_file, load_csv_line, save_scale_parameters, save_encoder_parameters, save_decoder_parameters, ) from nnga.utils.data_manipulation import scale_...
nnga/datasets/classification/csv_dataset.py
import os import numpy as np from statistics import mean, stdev from nnga.datasets.base_dataset import BaseDataset from nnga.utils.data_io import ( load_csv_file, load_csv_line, save_scale_parameters, save_encoder_parameters, save_decoder_parameters, ) from nnga.utils.data_manipulation import scale_...
0.663124
0.340896
from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible_collections.cisco.nxos.plugins.modules import nxos_static_routes from ansible_collections.cisco.nxos.tests.unit.compat.mock import ( patch, MagicMock, ) from ansible_collections.cisco.nxos.tests.unit.modules.ut...
venv/lib/python3.6/site-packages/ansible_collections/cisco/nxos/tests/unit/modules/network/nxos/test_nxos_static_routes.py
from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible_collections.cisco.nxos.plugins.modules import nxos_static_routes from ansible_collections.cisco.nxos.tests.unit.compat.mock import ( patch, MagicMock, ) from ansible_collections.cisco.nxos.tests.unit.modules.ut...
0.66454
0.085633
import copy import logging import functools from pathlib import Path from joblib import Memory from typing import Optional, Dict, Tuple, List, Iterable, Union, Callable, Any, Sequence import torch import torchvision from torch.utils.data import Dataset, DataLoader import PIL import numpy as np import albumentations ...
src/deepcv/meta/data/preprocess.py
import copy import logging import functools from pathlib import Path from joblib import Memory from typing import Optional, Dict, Tuple, List, Iterable, Union, Callable, Any, Sequence import torch import torchvision from torch.utils.data import Dataset, DataLoader import PIL import numpy as np import albumentations ...
0.904864
0.353149
from collections import OrderedDict from django.contrib.auth.models import User from django.http import Http404 from django.template import loader from mod import dispatch_module_hook from .models import Project, ProjectResult, Message, MessageResult, Result from .search import SearchEngine from rest_framework import...
api/rest.py
from collections import OrderedDict from django.contrib.auth.models import User from django.http import Http404 from django.template import loader from mod import dispatch_module_hook from .models import Project, ProjectResult, Message, MessageResult, Result from .search import SearchEngine from rest_framework import...
0.521715
0.106924
import csv import pandas as pd import warnings import string import re import os import fasttext warnings.filterwarnings('ignore') PRETRAINED_MODEL_PATH = './files/lid.176.ftz' def language_detection(dataset, clean_data_dir, language_list): df = pd.read_csv(dataset, sep='\t', header=0) df = df[['Tweet']] ...
src/language_detection.py
import csv import pandas as pd import warnings import string import re import os import fasttext warnings.filterwarnings('ignore') PRETRAINED_MODEL_PATH = './files/lid.176.ftz' def language_detection(dataset, clean_data_dir, language_list): df = pd.read_csv(dataset, sep='\t', header=0) df = df[['Tweet']] ...
0.192122
0.196363
import scipy.io as scio import numpy as np from sklearn.cluster import KMeans from sklearn.metrics import normalized_mutual_info_score, adjusted_rand_score from sklearn.metrics import f1_score, accuracy_score, roc_auc_score from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRe...
test.py
import scipy.io as scio import numpy as np from sklearn.cluster import KMeans from sklearn.metrics import normalized_mutual_info_score, adjusted_rand_score from sklearn.metrics import f1_score, accuracy_score, roc_auc_score from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRe...
0.569733
0.330363
from typing import Iterable import torch import torch.nn as nn from lgp.models.alfred.voxel_grid import VoxelGrid from lgp.models.alfred.projection.projection_ops import project_3d_camera_points_to_2d_pixels, project_3d_points, scatter_add_and_pool from lgp.models.alfred.projection.image_to_pointcloud import ImageToP...
lgp/models/alfred/projection/voxel_mask_to_image_mask.py
from typing import Iterable import torch import torch.nn as nn from lgp.models.alfred.voxel_grid import VoxelGrid from lgp.models.alfred.projection.projection_ops import project_3d_camera_points_to_2d_pixels, project_3d_points, scatter_add_and_pool from lgp.models.alfred.projection.image_to_pointcloud import ImageToP...
0.94528
0.446796
import nltk import numpy as np from collections import Counter from scipy.sparse import csc_matrix from sklearn.base import BaseEstimator from sklearn.feature_extraction.text import VectorizerMixin from nltk.corpus import sentiwordnet as swn class NLTKVectorizer(BaseEstimator, VectorizerMixin): """Convert a colle...
tests/vectorizers/NLTKVectorizer.py
import nltk import numpy as np from collections import Counter from scipy.sparse import csc_matrix from sklearn.base import BaseEstimator from sklearn.feature_extraction.text import VectorizerMixin from nltk.corpus import sentiwordnet as swn class NLTKVectorizer(BaseEstimator, VectorizerMixin): """Convert a colle...
0.72526
0.363449
import gzip import io import numpy import logging from lxml import etree from .openquake_gmpe import OpenQuakeGMPE class ShakeMap(object): """ShakeMap reader. """ def __init__(self, gmice=None): """Constructor. """ self.data = None self.grid = None self.gmice = gm...
eewperformance/shakemap.py
import gzip import io import numpy import logging from lxml import etree from .openquake_gmpe import OpenQuakeGMPE class ShakeMap(object): """ShakeMap reader. """ def __init__(self, gmice=None): """Constructor. """ self.data = None self.grid = None self.gmice = gm...
0.785514
0.294334
from enum import Enum class CharacterType(Enum): Role = 'Role' Species = 'Species' PhysicalAttribute = 'PhysicalAttribute' MentalAttribute = 'MentalAttribute' BehaviouralAttribute = 'BehaviouralAttribute' SkillCapability = 'SkillCapability' Aesthetic = 'Aesthetic' class Role(Enum): C...
story/characters.py
from enum import Enum class CharacterType(Enum): Role = 'Role' Species = 'Species' PhysicalAttribute = 'PhysicalAttribute' MentalAttribute = 'MentalAttribute' BehaviouralAttribute = 'BehaviouralAttribute' SkillCapability = 'SkillCapability' Aesthetic = 'Aesthetic' class Role(Enum): C...
0.547464
0.15511
import json from operator import add def get_wire_coordinates(wire): '''Returns a list of coordinates covered by the wire. A wire is a list of directions and distances originating from (0, 0). For example, ['R8','U5','L5','D3'] should return [ (0,0), (1, 0), (2, 0) ...]''' DIRECTIONS = { 'D': (...
2019/day_3.py
import json from operator import add def get_wire_coordinates(wire): '''Returns a list of coordinates covered by the wire. A wire is a list of directions and distances originating from (0, 0). For example, ['R8','U5','L5','D3'] should return [ (0,0), (1, 0), (2, 0) ...]''' DIRECTIONS = { 'D': (...
0.643777
0.511229
import os, math import pickle as pk import numpy as np from collections.abc import Iterable def readPLA(fn): if not os.path.isfile(fn): print('Warning: PLA "{}" not found.'.format(fn)) return (None,) * 3 getNum = lambda s, head: int(s.strip('\n').replace(head, '').replace(' ', '')) ...
utils.py
import os, math import pickle as pk import numpy as np from collections.abc import Iterable def readPLA(fn): if not os.path.isfile(fn): print('Warning: PLA "{}" not found.'.format(fn)) return (None,) * 3 getNum = lambda s, head: int(s.strip('\n').replace(head, '').replace(' ', '')) ...
0.196672
0.29798
from flask import Flask, request from datetime import datetime from database import get_pgconn, insert import os """ Simple greeting app that runs on Python and flask. It remembers the names and left messages, and stores them into a postgres database. """ # Determine the port that this app is running ob via environme...
dockerfiles/greeting/0.2/greeting.py
from flask import Flask, request from datetime import datetime from database import get_pgconn, insert import os """ Simple greeting app that runs on Python and flask. It remembers the names and left messages, and stores them into a postgres database. """ # Determine the port that this app is running ob via environme...
0.603581
0.203787
""" A test framework for testing DPDK. """ import os import sys import argparse # change operation directory os.chdir("../") cwd = os.getcwd() sys.path.append(cwd + '/nics') sys.path.append(cwd + '/framework') #sys.path.append(cwd + '/tests') # suites module path should be loaded in dts/run_all, not here sys.path.app...
ena-dts/framework/main.py
""" A test framework for testing DPDK. """ import os import sys import argparse # change operation directory os.chdir("../") cwd = os.getcwd() sys.path.append(cwd + '/nics') sys.path.append(cwd + '/framework') #sys.path.append(cwd + '/tests') # suites module path should be loaded in dts/run_all, not here sys.path.app...
0.348313
0.134236
import config import collections.abc as container_abcs import errno import numpy as np import os import time import torch import torch.nn as nn import torchvision from itertools import repeat from matplotlib import pyplot as plt from PIL import Image from torchvision.utils import make_grid from torchvision.utils import...
src/utils.py
import config import collections.abc as container_abcs import errno import numpy as np import os import time import torch import torch.nn as nn import torchvision from itertools import repeat from matplotlib import pyplot as plt from PIL import Image from torchvision.utils import make_grid from torchvision.utils import...
0.299822
0.196402
import unittest import time import serial from spawn_virtual_devices import spawn_device, get_virtual_ports from hibike_process import identify_smart_sensors import hibike_message as hm class IdentifySmartSensorsTests(unittest.TestCase): """ Tests for `identify_smart_sensors`. """ VIRTUAL_DEVICE_TYPES ...
hibike/hibike_tests/hibike_process_tests.py
import unittest import time import serial from spawn_virtual_devices import spawn_device, get_virtual_ports from hibike_process import identify_smart_sensors import hibike_message as hm class IdentifySmartSensorsTests(unittest.TestCase): """ Tests for `identify_smart_sensors`. """ VIRTUAL_DEVICE_TYPES ...
0.486332
0.32826
from itertools import chain from django import forms from django.contrib.auth import get_user_model from django.forms import models from django.forms.fields import MultipleChoiceField from ..categories.models import Category from .models import Moderator, ModeratorEvent, ModeratorQuerySet User = get_user_model() #...
forum/moderation/forms.py
from itertools import chain from django import forms from django.contrib.auth import get_user_model from django.forms import models from django.forms.fields import MultipleChoiceField from ..categories.models import Category from .models import Moderator, ModeratorEvent, ModeratorQuerySet User = get_user_model() #...
0.461259
0.091423
import torch from torch import nn import tqdm import numpy as np from kme.extern.sam import SAM def compute_accuracy(pred_y, y, mean_reduce=False): pred = torch.argmax(pred_y, dim=1) correct = pred.eq(y).sum().float() if mean_reduce: return correct.item() / float(len(y)) return correct.item() ...
kme/tools/training.py
import torch from torch import nn import tqdm import numpy as np from kme.extern.sam import SAM def compute_accuracy(pred_y, y, mean_reduce=False): pred = torch.argmax(pred_y, dim=1) correct = pred.eq(y).sum().float() if mean_reduce: return correct.item() / float(len(y)) return correct.item() ...
0.753104
0.455804
import os import numpy as np import pandas as pd from tensorflow.keras.utils import to_categorical from sklearn import model_selection class ACIC(object): def __init__( self, path, trial, center=False, exclude_population=False, ): self.trial ...
ucate/library/data/acic.py
import os import numpy as np import pandas as pd from tensorflow.keras.utils import to_categorical from sklearn import model_selection class ACIC(object): def __init__( self, path, trial, center=False, exclude_population=False, ): self.trial ...
0.556159
0.322299
import sys import json import time import anchore.anchore_utils gate_name = "ANCHORESEC" triggers = { 'VULNLOW': { 'description':'triggers if a vulnerability of LOW severity is found', 'params':'none' }, 'VULNMEDIUM': { 'description':'triggers if a vulnerability of MED sev...
anchore/anchore-modules/gates/98_anchoresec.py
import sys import json import time import anchore.anchore_utils gate_name = "ANCHORESEC" triggers = { 'VULNLOW': { 'description':'triggers if a vulnerability of LOW severity is found', 'params':'none' }, 'VULNMEDIUM': { 'description':'triggers if a vulnerability of MED sev...
0.16398
0.145419
import math import torch.nn as nn import torch.nn.functional as F from .multi_head_attention import * class TransformerFeedForward(nn.Module): def __init__(self, size, hidden_size, dropout_ratio=0.1, act="relu"): super().__init__() self.w_1 = nn.Linear(size, hidden_size) self.w_2 = nn.Line...
misc/pytorch_toolkit/machine_translation/core/models/modules/transformer_encoder.py
import math import torch.nn as nn import torch.nn.functional as F from .multi_head_attention import * class TransformerFeedForward(nn.Module): def __init__(self, size, hidden_size, dropout_ratio=0.1, act="relu"): super().__init__() self.w_1 = nn.Linear(size, hidden_size) self.w_2 = nn.Line...
0.948799
0.217732
from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import ugettext_lazy as _ from .models import User class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" ...
tovp/users/forms.py
from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import ugettext_lazy as _ from .models import User class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" ...
0.640973
0.198608
import asyncio import sys from kopf import config from kopf.k8s import events # TODO: rename it it kopf.log()? kopf.events.log()? kopf.events.warn()? async def event_async(obj, *, type, reason, message=''): """ Issue an event for the object. """ if isinstance(obj, (list, tuple)): for item in ...
kopf/events.py
import asyncio import sys from kopf import config from kopf.k8s import events # TODO: rename it it kopf.log()? kopf.events.log()? kopf.events.warn()? async def event_async(obj, *, type, reason, message=''): """ Issue an event for the object. """ if isinstance(obj, (list, tuple)): for item in ...
0.204183
0.050377
import argparse import os, sys import utils.data_util as data_util import auto_patch import time import numpy as np import gc TOP_N = 1 parser = argparse.ArgumentParser() parser.add_argument("-datadir", action = "store", default = "data", type = str) parser.add_argument('-which_data', action = "store", default = 'c...
arachne/main_rq6.py
import argparse import os, sys import utils.data_util as data_util import auto_patch import time import numpy as np import gc TOP_N = 1 parser = argparse.ArgumentParser() parser.add_argument("-datadir", action = "store", default = "data", type = str) parser.add_argument('-which_data', action = "store", default = 'c...
0.111822
0.143998
import pandas as pd import numpy as np import pickle import os # Create directory if output directory does not already exist cur_path = os.path.split(os.path.abspath(__file__))[0] output_fldr = "csv_output_files" output_dir = os.path.join(cur_path, output_fldr) if not os.access(output_dir, os.F_OK): os.makedirs(o...
ogusa/psid_summ_stats.py
import pandas as pd import numpy as np import pickle import os # Create directory if output directory does not already exist cur_path = os.path.split(os.path.abspath(__file__))[0] output_fldr = "csv_output_files" output_dir = os.path.join(cur_path, output_fldr) if not os.access(output_dir, os.F_OK): os.makedirs(o...
0.456652
0.195268
from bs4 import BeautifulSoup import os,sys import urllib.request, urllib.parse, http.cookiejar import requests import re from datetime import datetime def getcontent(url): text_string = requests.get(url).text #正则匹配出轮胎列表 html_string = re.findall(r'<a class=\\"item-name\\"(.*?)href=\\"//(.*?)target=\\"_bla...
spider/tuhu_tianmao.py
from bs4 import BeautifulSoup import os,sys import urllib.request, urllib.parse, http.cookiejar import requests import re from datetime import datetime def getcontent(url): text_string = requests.get(url).text #正则匹配出轮胎列表 html_string = re.findall(r'<a class=\\"item-name\\"(.*?)href=\\"//(.*?)target=\\"_bla...
0.108756
0.102125
from typing import Dict, Optional, List, Mapping import numpy as np import datasets from raft_baselines.classifiers.in_context_classifier import InContextClassifier from raft_baselines.utils.gpt3_utils import ( complete, search, ) from raft_baselines.utils.tokenizers import TransformersTokenizer GPT3_MAX_TOK...
src/raft_baselines/classifiers/gpt3_classifier.py
from typing import Dict, Optional, List, Mapping import numpy as np import datasets from raft_baselines.classifiers.in_context_classifier import InContextClassifier from raft_baselines.utils.gpt3_utils import ( complete, search, ) from raft_baselines.utils.tokenizers import TransformersTokenizer GPT3_MAX_TOK...
0.876813
0.335814
import datetime, json, os from cantools import config from cantools.util import log, write from cantools.web import fetch, send_mail from .actor import Actor try: import psutil except ImportError as e: pass # google crap engine (get it if you need it!) from six import with_metaclass class BotMeta(type): def __new__...
cantools/scripts/pubsub/bots.py
import datetime, json, os from cantools import config from cantools.util import log, write from cantools.web import fetch, send_mail from .actor import Actor try: import psutil except ImportError as e: pass # google crap engine (get it if you need it!) from six import with_metaclass class BotMeta(type): def __new__...
0.107707
0.080033
import argparse import json import nnetwork from nnetwork import load_checkpoint import utility_functions from utility_functions import imshow, process_image import utility_functions import torch def predict(image_path, model, topk=5): ''' Predict the class (or classes) of an image using a trained deep learnin...
predict.py
import argparse import json import nnetwork from nnetwork import load_checkpoint import utility_functions from utility_functions import imshow, process_image import utility_functions import torch def predict(image_path, model, topk=5): ''' Predict the class (or classes) of an image using a trained deep learnin...
0.620047
0.319692
from copy import deepcopy from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declared_attr, declarative_base from models.common import BaseSchema import models.common.overview as mco import models.common.personnel as mcp import mo...
marcotti/models/national.py
from copy import deepcopy from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declared_attr, declarative_base from models.common import BaseSchema import models.common.overview as mco import models.common.personnel as mcp import mo...
0.609757
0.142202
import sys sys.stdin = open("../input.txt", "r") si = sys.stdin.readline def check_row(): visited = [[0 for _ in range(n)] for _ in range(n)] cnt = 0 for i in range(n): check = True last = board[i][0] for j in range(n): if board[i][j] == last: continue ...
BOJ/simulation_boj/boj_14890.py
import sys sys.stdin = open("../input.txt", "r") si = sys.stdin.readline def check_row(): visited = [[0 for _ in range(n)] for _ in range(n)] cnt = 0 for i in range(n): check = True last = board[i][0] for j in range(n): if board[i][j] == last: continue ...
0.073682
0.112308
import pytest from ais.ais_track import AISTrackList, ShipEta from nmea.nmea_msg import AISMsgPayloadType1, AISMsgPayloadType5 def test_ais_track_list_single(dummy_ais_tracks_list_single): track_list = AISTrackList(tracks=dummy_ais_tracks_list_single) assert len(track_list.tracks) == 1 def test_ais_track_l...
tests/test_ais_track.py
import pytest from ais.ais_track import AISTrackList, ShipEta from nmea.nmea_msg import AISMsgPayloadType1, AISMsgPayloadType5 def test_ais_track_list_single(dummy_ais_tracks_list_single): track_list = AISTrackList(tracks=dummy_ais_tracks_list_single) assert len(track_list.tracks) == 1 def test_ais_track_l...
0.520496
0.526708
from wxcloudrun.mapper.utils import get_table_column_name from wxcloudrun.utils.SQL.DBUtils import db_utils need_escapr_string_list = ["store_name"] can_not_update_string_list = ["openid", "store_id"] def insert_store_info(store_id, store_name, dsr, openid, ignore=False): sql_str = ''' insert {ignore} into s...
wxcloudrun/mapper/store_info.py
from wxcloudrun.mapper.utils import get_table_column_name from wxcloudrun.utils.SQL.DBUtils import db_utils need_escapr_string_list = ["store_name"] can_not_update_string_list = ["openid", "store_id"] def insert_store_info(store_id, store_name, dsr, openid, ignore=False): sql_str = ''' insert {ignore} into s...
0.215186
0.104981
import sys,time, csv,numpy as np,argparse,string,os,math,logging import numpy as np import iolib import lmem_func import multiprocessing as mp parser = argparse.ArgumentParser(description='Linear mixed effect models for quantitative traits') parser.add_argument('-genfile', metavar='genfile',default="", type=str, help=...
lmem.py
import sys,time, csv,numpy as np,argparse,string,os,math,logging import numpy as np import iolib import lmem_func import multiprocessing as mp parser = argparse.ArgumentParser(description='Linear mixed effect models for quantitative traits') parser.add_argument('-genfile', metavar='genfile',default="", type=str, help=...
0.169991
0.096153
import numpy as np from math import floor import vapoursynth as vs from .utils import frame_to_array from .masking import eoe_convolution from .errors import VariableFormatError, YUVError from typing import Callable, Dict, Any core = vs.core def chromashifter( clip: vs.VideoNode, wthresh: int = 31, vertical: bo...
rvsfunc/dvd.py
import numpy as np from math import floor import vapoursynth as vs from .utils import frame_to_array from .masking import eoe_convolution from .errors import VariableFormatError, YUVError from typing import Callable, Dict, Any core = vs.core def chromashifter( clip: vs.VideoNode, wthresh: int = 31, vertical: bo...
0.870694
0.601535
import sys import time from unittest import mock from unittest.mock import patch import matplotlib.pyplot as plt import pytest from pyinfer import InferenceReport, MultiInferenceReport from pyinfer.errors import ( MatplotlibNotInstalledError, MeasurementIntervalNotSetError, ModelIsNotCallableError, Nam...
test/test_multi_inference_report.py
import sys import time from unittest import mock from unittest.mock import patch import matplotlib.pyplot as plt import pytest from pyinfer import InferenceReport, MultiInferenceReport from pyinfer.errors import ( MatplotlibNotInstalledError, MeasurementIntervalNotSetError, ModelIsNotCallableError, Nam...
0.54577
0.457258
# Time complexities: # Best case -> O(n) -> When v is equal to to_find # Average case -> O(nlog(n)) # Worst case -> O(nlog(n)) from random import randint numbs = [int(i) for i in input().split(' ')] to_find = int(input()) def selection(numbs: list, to_find: int) -> int: """ Generate a random number between ...
misc/selection.py
# Time complexities: # Best case -> O(n) -> When v is equal to to_find # Average case -> O(nlog(n)) # Worst case -> O(nlog(n)) from random import randint numbs = [int(i) for i in input().split(' ')] to_find = int(input()) def selection(numbs: list, to_find: int) -> int: """ Generate a random number between ...
0.708717
0.705145
from django.test import TestCase from django.urls import reverse from .. import models class AdminAddBusinessTestCase(TestCase): """ Tests of who can add businesses """ fixtures = [ "sectors", "business_types", "business_statuses", "regions", "test_admin_add_business"...
biz_portal/apps/portal/tests/test_admin.py
from django.test import TestCase from django.urls import reverse from .. import models class AdminAddBusinessTestCase(TestCase): """ Tests of who can add businesses """ fixtures = [ "sectors", "business_types", "business_statuses", "regions", "test_admin_add_business"...
0.492188
0.410047
import sys from PyQt5.QtWidgets import QPushButton,QMessageBox,QVBoxLayout,QWidget,QApplication,QMainWindow class QMessageBoxDemo(QMainWindow): def __init__(self): super(QMessageBoxDemo, self).__init__() #设置窗口大小 self.resize(400, 150) #设置窗口标题 self.setWindowTitle("QMessageBox...
06-QMessageBox/QMessageBox1.py
import sys from PyQt5.QtWidgets import QPushButton,QMessageBox,QVBoxLayout,QWidget,QApplication,QMainWindow class QMessageBoxDemo(QMainWindow): def __init__(self): super(QMessageBoxDemo, self).__init__() #设置窗口大小 self.resize(400, 150) #设置窗口标题 self.setWindowTitle("QMessageBox...
0.127462
0.089654
import wpilib from magicbot import MagicRobot from rev import CANSparkMax, MotorType from wpilib.buttons import JoystickButton from ctre import WPI_VictorSPX class Robot(MagicRobot): def createObjects(self): self.joystick = wpilib.Joystick(2) self.winch_button = JoystickButton(self.joystick, 6) ...
electrical_test/robot.py
import wpilib from magicbot import MagicRobot from rev import CANSparkMax, MotorType from wpilib.buttons import JoystickButton from ctre import WPI_VictorSPX class Robot(MagicRobot): def createObjects(self): self.joystick = wpilib.Joystick(2) self.winch_button = JoystickButton(self.joystick, 6) ...
0.267026
0.167253
import gc import logging logging.getLogger('transformers').setLevel(logging.WARNING) from random import choice import torch import torch.nn.functional as F from transformers import GPT2Tokenizer, GPT2LMHeadModel # Total length of the paragraph to generate. PARAGRAPH_LENGTH = 100 # Max number of words to process at on...
genesis/AIText.py
import gc import logging logging.getLogger('transformers').setLevel(logging.WARNING) from random import choice import torch import torch.nn.functional as F from transformers import GPT2Tokenizer, GPT2LMHeadModel # Total length of the paragraph to generate. PARAGRAPH_LENGTH = 100 # Max number of words to process at on...
0.747892
0.385751
import re import logging import schema import subprocess from hil.model import db, Switch, Port, BigIntegerType, SwitchSession from hil.errors import SwitchError from hil.ext.switches.common import string_to_dict, string_to_list logger = logging.getLogger(__name__) # Class layout # 1. Public methods: # 2. Private me...
hil/ext/switches/ovs.py
import re import logging import schema import subprocess from hil.model import db, Switch, Port, BigIntegerType, SwitchSession from hil.errors import SwitchError from hil.ext.switches.common import string_to_dict, string_to_list logger = logging.getLogger(__name__) # Class layout # 1. Public methods: # 2. Private me...
0.673514
0.170681
import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch.nn.functional as F from textclf.config.components import RNNConfig class RNN(torch.nn.Module): """ rnn layer """ supported_types = ["RNN", "GRU", "LSTM"] def __init__(self, co...
textclf/models/classifier/components.py
import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch.nn.functional as F from textclf.config.components import RNNConfig class RNN(torch.nn.Module): """ rnn layer """ supported_types = ["RNN", "GRU", "LSTM"] def __init__(self, co...
0.926562
0.281955
"""Make a histogram and calculate entropy of files.""" import math import os.path import subprocess as sp import sys def main(argv): """ Entry point for histdata. Arguments: argv: List of file names. """ if len(argv) < 1: sys.exit(1) for fn in argv: hdata, size = read...
histdata.py
"""Make a histogram and calculate entropy of files.""" import math import os.path import subprocess as sp import sys def main(argv): """ Entry point for histdata. Arguments: argv: List of file names. """ if len(argv) < 1: sys.exit(1) for fn in argv: hdata, size = read...
0.652906
0.580738
import os import fabric from inspect import getsource from textwrap import dedent from fabric.api import run, sudo, cd fabric.state.env.colorize_errors = True fabric.state.output['stdout'] = False # task const variables VARS = dict( current_user=fabric.state.env.user, # project settings project_name='ai...
provision/fabric_provisioner.py
import os import fabric from inspect import getsource from textwrap import dedent from fabric.api import run, sudo, cd fabric.state.env.colorize_errors = True fabric.state.output['stdout'] = False # task const variables VARS = dict( current_user=fabric.state.env.user, # project settings project_name='ai...
0.190498
0.065098
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('movies', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ ...
backend/reviews/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 = [ ('movies', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ ...
0.521715
0.176814
import numpy import re SAVE_PATH = '/home/bioprober/gh/3d-converter/tests/data/' class TransWriter: def __init__(self, filename): self.filename = filename self.info = '' def config(self, axis, degree, steps=65, move=(0, 0, 0)): """ Configs self.info string by given paramete...
misc/trans_writer.py
import numpy import re SAVE_PATH = '/home/bioprober/gh/3d-converter/tests/data/' class TransWriter: def __init__(self, filename): self.filename = filename self.info = '' def config(self, axis, degree, steps=65, move=(0, 0, 0)): """ Configs self.info string by given paramete...
0.710327
0.6137
import os from keystoneauth1.identity import v3 from keystoneauth1 import session from swiftclient import client as swift_client class SwiftHandler: """ Initiates a connection to a project domain. """ @staticmethod def get_scoped_session(os_auth_url, username, password, os_project_domain, os_pro...
src/swift/__init__.py
import os from keystoneauth1.identity import v3 from keystoneauth1 import session from swiftclient import client as swift_client class SwiftHandler: """ Initiates a connection to a project domain. """ @staticmethod def get_scoped_session(os_auth_url, username, password, os_project_domain, os_pro...
0.585931
0.097519
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import grad __all__ = ['BCEGANLoss', 'LSGANLoss', 'WGANGPLoss'] class BCEGANLoss(nn.Module): def __init__(self): super(BCEGANLoss, self).__init__() self.bce_loss = nn.BCELoss() self.register_buffer('tar...
losses/gan_loss.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import grad __all__ = ['BCEGANLoss', 'LSGANLoss', 'WGANGPLoss'] class BCEGANLoss(nn.Module): def __init__(self): super(BCEGANLoss, self).__init__() self.bce_loss = nn.BCELoss() self.register_buffer('tar...
0.936234
0.338282
import re import subprocess import time from .exceptions import InterfaceNotFoundError from control.utils.iface_statistics.stats_reader import StatsReader class InterfaceStatisticsIp(StatsReader): @staticmethod def _call_ip() -> str: cmd = ['ip', '-s', 'link'] completed_process = subprocess.r...
clients/control/utils/iface_statistics/ip.py
import re import subprocess import time from .exceptions import InterfaceNotFoundError from control.utils.iface_statistics.stats_reader import StatsReader class InterfaceStatisticsIp(StatsReader): @staticmethod def _call_ip() -> str: cmd = ['ip', '-s', 'link'] completed_process = subprocess.r...
0.52975
0.118538
import unittest from password_locker import User, Credential class TestUser(unittest.TestCase): ''' Test class that defines test cases for the user class behaviors. Args: unittest.TestCase: helps in creating test cases ''' def setUp(self): ''' Function to create a user ac...
test_password.py
import unittest from password_locker import User, Credential class TestUser(unittest.TestCase): ''' Test class that defines test cases for the user class behaviors. Args: unittest.TestCase: helps in creating test cases ''' def setUp(self): ''' Function to create a user ac...
0.608594
0.488832
import datetime as dt import json import os from urllib import error, request import pandas as pd import pyodbc as sql # TODO: Add argument parsing to allow for command-line options, thinking primarily of refreshing a specific user vs. entire dataset # Could do more like only those active within last month, only one ...
scheduled/UpdateUsernameXRef.py
import datetime as dt import json import os from urllib import error, request import pandas as pd import pyodbc as sql # TODO: Add argument parsing to allow for command-line options, thinking primarily of refreshing a specific user vs. entire dataset # Could do more like only those active within last month, only one ...
0.084768
0.076442
import argparse import numpy as np import chainer.functions as F from consts import activation_func,dtypes,uplayer,downlayer,norm_layer,unettype,optim import os,sys from datetime import datetime as dt def arguments(): parser = argparse.ArgumentParser() parser.add_argument('--gpu', '-g', type=int, default=0, ...
arguments.py
import argparse import numpy as np import chainer.functions as F from consts import activation_func,dtypes,uplayer,downlayer,norm_layer,unettype,optim import os,sys from datetime import datetime as dt def arguments(): parser = argparse.ArgumentParser() parser.add_argument('--gpu', '-g', type=int, default=0, ...
0.545528
0.089813
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.permissions import BasePermission, AllowAny, IsAdminUser, IsAuthenticated from . import models, serializers from gemtown.users import models as user_models from gemtown.modelers im...
gemtown/modelphotos/views.py
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.permissions import BasePermission, AllowAny, IsAdminUser, IsAuthenticated from . import models, serializers from gemtown.users import models as user_models from gemtown.modelers im...
0.377655
0.083853
import os import json import math import matplotlib as maplot import matplotlib.pyplot as pyplot from datetime import datetime # User library from sub.inputprocess import CONSTANTS as CONS # **json.loads(json_data) def get_data(): """Read output file to get data.""" try: with open(CONS["OUTPUT_FILE"]...
src/sub/plot.py
import os import json import math import matplotlib as maplot import matplotlib.pyplot as pyplot from datetime import datetime # User library from sub.inputprocess import CONSTANTS as CONS # **json.loads(json_data) def get_data(): """Read output file to get data.""" try: with open(CONS["OUTPUT_FILE"]...
0.64232
0.49939
import os import numpy as np import ray import torch from gym_ds3.schedulers.scarl.data_worker_scarl import SCARLWorker from gym_ds3.schedulers.scarl.parameter_server import ParameterServer from config import args args.scheduler_name = 'scarl' if args.use_tensorboard: from tensorboardX import SummaryWriter ...
run_scarl_scheduler.py
import os import numpy as np import ray import torch from gym_ds3.schedulers.scarl.data_worker_scarl import SCARLWorker from gym_ds3.schedulers.scarl.parameter_server import ParameterServer from config import args args.scheduler_name = 'scarl' if args.use_tensorboard: from tensorboardX import SummaryWriter ...
0.441432
0.191063
import graphene import json import os import sys import hashlib pf = os.path.join(sys.path[0],'..', 'planets.json') with open(pf) as f: planets = json.load(f) pf = os.path.join(sys.path[0],'..', 'satellites.json') with open(pf) as f: satellites = json.load(f) class Planet(graphene.ObjectType): ...
2020/GraphQL/generate-flag/index.py
import graphene import json import os import sys import hashlib pf = os.path.join(sys.path[0],'..', 'planets.json') with open(pf) as f: planets = json.load(f) pf = os.path.join(sys.path[0],'..', 'satellites.json') with open(pf) as f: satellites = json.load(f) class Planet(graphene.ObjectType): ...
0.356111
0.244386
from src.view_app.View import * class MainView(View): """Vista Principal del programa.""" def _init_view(self): """Método de creación de vista. En este método es donde realmente se genera la vista de la, ventana pues es donde se crean todos los widgets y se colocán, en su lug...
04Cuarto/Sistemas_y_proteccion_de_sistemas_informaticos_SPSI/Practica5/src/view_app/Views.py
from src.view_app.View import * class MainView(View): """Vista Principal del programa.""" def _init_view(self): """Método de creación de vista. En este método es donde realmente se genera la vista de la, ventana pues es donde se crean todos los widgets y se colocán, en su lug...
0.449272
0.330471