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 discord from discord.ext import commands import aiohttp import random import textwrap class Reddit(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name="reddit") async def _reddit(self, ctx, subreddit): bl_users = await self.bot.db.fetch("SELECT * FROM bl WH...
Nora/cogs/reddit.py
import discord from discord.ext import commands import aiohttp import random import textwrap class Reddit(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name="reddit") async def _reddit(self, ctx, subreddit): bl_users = await self.bot.db.fetch("SELECT * FROM bl WH...
0.431345
0.288344
from lab11 import * # Q5 def hailstone(n): """ >>> for num in hailstone(10): ... print(num) ... 10 5 16 8 4 2 1 """ while n is not 1: yield n if n % 2 == 0: n //= 2 else: n = n * 3 + 1 yield n # Q6 def repe...
labs/lab11/lab11_extra.py
from lab11 import * # Q5 def hailstone(n): """ >>> for num in hailstone(10): ... print(num) ... 10 5 16 8 4 2 1 """ while n is not 1: yield n if n % 2 == 0: n //= 2 else: n = n * 3 + 1 yield n # Q6 def repe...
0.627495
0.598606
import slicer import unittest import vtk from slicer.util import VTKObservationMixin class Foo(VTKObservationMixin): def __init__(self): VTKObservationMixin.__init__(self) self.ModifiedEventCount = {} def onObjectModified(self, caller, event): self.ModifiedEventCount[caller] = self.modifiedEventCount...
Base/Python/slicer/tests/test_slicer_util_VTKObservationMixin.py
import slicer import unittest import vtk from slicer.util import VTKObservationMixin class Foo(VTKObservationMixin): def __init__(self): VTKObservationMixin.__init__(self) self.ModifiedEventCount = {} def onObjectModified(self, caller, event): self.ModifiedEventCount[caller] = self.modifiedEventCount...
0.750278
0.365655
import collections.abc import dataclasses import inspect import typing_inspect from erdantic.base import Field, Model, register_model_adapter from erdantic.etyping import GenericAlias, get_args, get_origin from typing import Any, Callable, List, Union class DataClassField(Field[dataclasses.Field]): """Concrete f...
erdantic/edataclasses.py
import collections.abc import dataclasses import inspect import typing_inspect from erdantic.base import Field, Model, register_model_adapter from erdantic.etyping import GenericAlias, get_args, get_origin from typing import Any, Callable, List, Union class DataClassField(Field[dataclasses.Field]): """Concrete f...
0.885879
0.235592
import argparse import logging import sys from os import path from time import sleep from typing import Any, Dict, Optional import yaml from boto import ec2 from boto.utils import get_instance_identity, get_instance_metadata from .modules import Etcd, HostedZone, Hostname, TinyCert log = logging.getLogger(__name__) ...
nodereg/run.py
import argparse import logging import sys from os import path from time import sleep from typing import Any, Dict, Optional import yaml from boto import ec2 from boto.utils import get_instance_identity, get_instance_metadata from .modules import Etcd, HostedZone, Hostname, TinyCert log = logging.getLogger(__name__) ...
0.468547
0.047514
from renderer import SimRenderer import numpy as np import scipy.optimize import redmax_py as redmax if __name__ == '__main__': sim = redmax.make_sim("TorqueFingerFlick-Demo", "BDF2") ndof_r, ndof_m, ndof_u = sim.ndof_r, sim.ndof_m, sim.ndof_u print('ndof_r = ', ndof_r) print('ndof_m = ', ndof_m)...
examples/test_finger_flick_optimize.py
from renderer import SimRenderer import numpy as np import scipy.optimize import redmax_py as redmax if __name__ == '__main__': sim = redmax.make_sim("TorqueFingerFlick-Demo", "BDF2") ndof_r, ndof_m, ndof_u = sim.ndof_r, sim.ndof_m, sim.ndof_u print('ndof_r = ', ndof_r) print('ndof_m = ', ndof_m)...
0.675658
0.428771
from typing import List import numpy as np from ..AShape import AShape from ..AAxes import AAxes from ..backend import Kernel from ..HKernel import HKernel from ..HType import HType from ..info import SliceInfo from ..SCacheton import SCacheton from ..Tensor import Tensor def split(input_t : Tensor, axis, keepdims=...
xlib/avecl/_internal/op/slice_.py
from typing import List import numpy as np from ..AShape import AShape from ..AAxes import AAxes from ..backend import Kernel from ..HKernel import HKernel from ..HType import HType from ..info import SliceInfo from ..SCacheton import SCacheton from ..Tensor import Tensor def split(input_t : Tensor, axis, keepdims=...
0.81231
0.610134
import argparse import json import multiprocessing as mp import os import re import shutil import sys import tarfile import unicodedata from dataclasses import dataclass from datetime import date, timedelta, datetime from os import path, makedirs, listdir from typing import List, Dict, Any import requests def parse_...
backup.py
import argparse import json import multiprocessing as mp import os import re import shutil import sys import tarfile import unicodedata from dataclasses import dataclass from datetime import date, timedelta, datetime from os import path, makedirs, listdir from typing import List, Dict, Any import requests def parse_...
0.634204
0.17037
import subprocess from tensorflow.keras.callbacks import ( TensorBoard, ReduceLROnPlateau, EarlyStopping ) import constants import helpers import models.custom_callbacks as custom_callbacks from visualization.visualize import plot_history def train(model, epochs: int, train_data, val_data, save_freq: in...
src/models/train.py
import subprocess from tensorflow.keras.callbacks import ( TensorBoard, ReduceLROnPlateau, EarlyStopping ) import constants import helpers import models.custom_callbacks as custom_callbacks from visualization.visualize import plot_history def train(model, epochs: int, train_data, val_data, save_freq: in...
0.825167
0.353651
from alembic import op from sqlalchemy.dialects.postgresql import BYTEA from sqlalchemy.schema import Sequence, CreateSequence, DropSequence import os import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '0008' down_revision = '0007' branch_labels = None depends_on = None sequence_key_table = ...
backend/database/migrations/versions/0008_add_card_request_table.py
from alembic import op from sqlalchemy.dialects.postgresql import BYTEA from sqlalchemy.schema import Sequence, CreateSequence, DropSequence import os import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '0008' down_revision = '0007' branch_labels = None depends_on = None sequence_key_table = ...
0.396419
0.129375
from Products.CMFPlone.utils import safe_unicode from bika.lims.controlpanel.bika_analysisservices import AnalysisServicesView from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t from plone.app.content.browser.interfaces import IFolderContentsView from zope.interface import implements class A...
bika/lims/browser/accreditation.py
from Products.CMFPlone.utils import safe_unicode from bika.lims.controlpanel.bika_analysisservices import AnalysisServicesView from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t from plone.app.content.browser.interfaces import IFolderContentsView from zope.interface import implements class A...
0.5083
0.195575
from tensorflow import keras import numpy as np def get_test_data(keras_dataset='mnist', num_samples=None, preprocess=True, preprocessing_function=None, **kwargs): """ Returns (x_test, y_test) of a chosen built-in Keras dataset. Also preprocesses the image datasets (mnist, fashion_mnist, cifar10, cifar100...
flox/utils.py
from tensorflow import keras import numpy as np def get_test_data(keras_dataset='mnist', num_samples=None, preprocess=True, preprocessing_function=None, **kwargs): """ Returns (x_test, y_test) of a chosen built-in Keras dataset. Also preprocesses the image datasets (mnist, fashion_mnist, cifar10, cifar100...
0.853852
0.716999
import os import re import pandas as pd import json import nltk nltk.download('punkt') from nltk.tokenize import sent_tokenize from collections import Counter from tqdm.auto import tqdm from transformers import AutoTokenizer, AutoModelForSequenceClassification from transformers import pipeline def get_file_paths():...
model/sentiment_analysics_model/sentiment_analysis.py
import os import re import pandas as pd import json import nltk nltk.download('punkt') from nltk.tokenize import sent_tokenize from collections import Counter from tqdm.auto import tqdm from transformers import AutoTokenizer, AutoModelForSequenceClassification from transformers import pipeline def get_file_paths():...
0.508788
0.208119
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext from telegram import Update import logging, view, dao, config from coin import CoinHandler token = config.env['TOKEN_TELEGRAM'] # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',...
main.py
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext from telegram import Update import logging, view, dao, config from coin import CoinHandler token = config.env['TOKEN_TELEGRAM'] # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',...
0.598312
0.063222
from torchvision.datasets.vision import VisionDataset from PIL import Image import os import os.path import torch import numpy as np # TODO: remove `device`? def convert_ann(ann, device): xmin, ymin, w, h = ann['bbox'] # DEBUG if w <= 0 or h <= 0: raise ValueError("Degenerate bbox (x, y, w, h): ",...
object-detection/baseline/coco.py
from torchvision.datasets.vision import VisionDataset from PIL import Image import os import os.path import torch import numpy as np # TODO: remove `device`? def convert_ann(ann, device): xmin, ymin, w, h = ann['bbox'] # DEBUG if w <= 0 or h <= 0: raise ValueError("Degenerate bbox (x, y, w, h): ",...
0.673836
0.474631
# Copyright 2022 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
bet500.py
# Copyright 2022 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
0.503174
0.149904
from PIL import Image from DDRDataTypes import DDRScreenshot, DDRParsedData from IIDXDataTypes import IIDXScreenshot, IIDXParsedData import sys, requests, io, os if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: DDRGenie.py [path to screenshot image file]") exit(0) sshot = Image.op...
Genie.py
from PIL import Image from DDRDataTypes import DDRScreenshot, DDRParsedData from IIDXDataTypes import IIDXScreenshot, IIDXParsedData import sys, requests, io, os if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: DDRGenie.py [path to screenshot image file]") exit(0) sshot = Image.op...
0.180793
0.106226
"""This module models elements from UTAU, hence the name.""" import abc import logging from typing import Tuple from pydub import AudioSegment, effects # noqa from . import utau from .jsonclasses import dataclass _log = logging.getLogger("putao") @dataclass class Note: """Notes are the combination of a durat...
putao/model.py
"""This module models elements from UTAU, hence the name.""" import abc import logging from typing import Tuple from pydub import AudioSegment, effects # noqa from . import utau from .jsonclasses import dataclass _log = logging.getLogger("putao") @dataclass class Note: """Notes are the combination of a durat...
0.914839
0.499023
from .Emulator import Emulator, Device from external.containers.emu import docker_device, emu_docker, emu_downloads_menu import subprocess import logging import time import sys class DockerEmulator(Emulator): def __init__(self, path_config, configuration, ): Device.__init__(self, path_config, configurat...
lib/adb/DockerEmulator.py
from .Emulator import Emulator, Device from external.containers.emu import docker_device, emu_docker, emu_downloads_menu import subprocess import logging import time import sys class DockerEmulator(Emulator): def __init__(self, path_config, configuration, ): Device.__init__(self, path_config, configurat...
0.099328
0.062703
from __future__ import print_function import sys import os import argparse from dark.reads import ( addFASTACommandLineOptions, parseFASTACommandLineOptions, unambiguousBases) parser = argparse.ArgumentParser( description=( 'Given FASTA on standard input, and bases to look for, write the ' '...
bin/fasta-base-indices.py
from __future__ import print_function import sys import os import argparse from dark.reads import ( addFASTACommandLineOptions, parseFASTACommandLineOptions, unambiguousBases) parser = argparse.ArgumentParser( description=( 'Given FASTA on standard input, and bases to look for, write the ' '...
0.486332
0.342957
import os import time import sys import threading from pkg_resources import resource_filename import thriftpy from thriftpy.rpc import make_client from thriftpy.protocol.binary import TBinaryProtocolFactory from thriftpy.transport.buffered import TBufferedTransportFactory from .wpwithin_types import Error from .conve...
wrappers/python/wpwithin_python/wpwithin_python/wpwithin.py
import os import time import sys import threading from pkg_resources import resource_filename import thriftpy from thriftpy.rpc import make_client from thriftpy.protocol.binary import TBinaryProtocolFactory from thriftpy.transport.buffered import TBufferedTransportFactory from .wpwithin_types import Error from .conve...
0.493409
0.061961
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import string messages = pd.read_csv('SMSSpamCollection', sep='\t', names=["label", "message"]) from nltk.corpus import stopwords # tokenization and pre-processing def text_process(mess): nopunc = [char for char ...
code/spam.py
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import string messages = pd.read_csv('SMSSpamCollection', sep='\t', names=["label", "message"]) from nltk.corpus import stopwords # tokenization and pre-processing def text_process(mess): nopunc = [char for char ...
0.327883
0.227491
import os import sys import pandas as pd import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter import transformers as tfm from models.text2brain_model import Text2BrainModel from utils.parser import init_args from utils.dataset ...
train.py
import os import sys import pandas as pd import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter import transformers as tfm from models.text2brain_model import Text2BrainModel from utils.parser import init_args from utils.dataset ...
0.707809
0.219892
import os import time import logging from typing import List import wx # pip install wxPython import wx.xrc from .node import Node from .encryption import Encryption from .validation import is_valid_node from .message import Message, OwnMessage from .utils import get_date_from_timestamp from .wxdisp...
sami/controller.py
import os import time import logging from typing import List import wx # pip install wxPython import wx.xrc from .node import Node from .encryption import Encryption from .validation import is_valid_node from .message import Message, OwnMessage from .utils import get_date_from_timestamp from .wxdisp...
0.576423
0.095097
import matplotlib.pyplot as plt import matplotlib.patches as patches from quadtree.node import Node from quadtree.point import Point from quadtree.utils import recursive_subdivide, contains, find_children,leaf_nodes, get_neighbor_of_greater_or_equal_size,Direction,has_to_split, DEBUG_MODE class QTree(): def __ini...
quadtree/quadtree.py
import matplotlib.pyplot as plt import matplotlib.patches as patches from quadtree.node import Node from quadtree.point import Point from quadtree.utils import recursive_subdivide, contains, find_children,leaf_nodes, get_neighbor_of_greater_or_equal_size,Direction,has_to_split, DEBUG_MODE class QTree(): def __ini...
0.698535
0.567517
import math import time import arcade # Do the math to figure out our screen dimensions SCREEN_WIDTH = 1280 SCREEN_HEIGHT = 720 SCREEN_TITLE = "Basic Renderer" class MyGame(arcade.Window): def __init__(self, width, height, title): super().__init__(width, height, title) # vsync must...
env/lib/python3.8/site-packages/arcade/experimental/query_demo.py
import math import time import arcade # Do the math to figure out our screen dimensions SCREEN_WIDTH = 1280 SCREEN_HEIGHT = 720 SCREEN_TITLE = "Basic Renderer" class MyGame(arcade.Window): def __init__(self, width, height, title): super().__init__(width, height, title) # vsync must...
0.391755
0.097347
import numpy as np from utils import DotDict def interpolate_min_x(f, x): return 0.5 * (f[x-1] - f[x+1]) / (f[x-1] - 2 * f[x] + f[x+1]) + x def rms(f): return np.sqrt((f ** 2).mean()) def sine_wave(n): return np.sin(np.linspace(0, 2*np.pi, n, endpoint=False)) def triangle_wave(n): x = np.linspa...
analysis.py
import numpy as np from utils import DotDict def interpolate_min_x(f, x): return 0.5 * (f[x-1] - f[x+1]) / (f[x-1] - 2 * f[x] + f[x+1]) + x def rms(f): return np.sqrt((f ** 2).mean()) def sine_wave(n): return np.sin(np.linspace(0, 2*np.pi, n, endpoint=False)) def triangle_wave(n): x = np.linspa...
0.59796
0.656741
from __future__ import annotations from functools import partial from typing import TYPE_CHECKING import click from cherno.actor.exposer import Exposer from cherno.astrometry import process_and_correct from cherno.exceptions import ExposerError from . import cherno_parser if TYPE_CHECKING: from . import Che...
cherno/actor/acquire.py
from __future__ import annotations from functools import partial from typing import TYPE_CHECKING import click from cherno.actor.exposer import Exposer from cherno.astrometry import process_and_correct from cherno.exceptions import ExposerError from . import cherno_parser if TYPE_CHECKING: from . import Che...
0.844184
0.18954
import time from datetime import datetime, timezone import bme680 from influxdb_client import InfluxDBClient, Point, WritePrecision from influxdb_client.client.write_api import SYNCHRONOUS from pydantic import BaseSettings class Settings(BaseSettings): hive_name: str token: str org: str bucket: str ...
hive/services/environment/environment.py
import time from datetime import datetime, timezone import bme680 from influxdb_client import InfluxDBClient, Point, WritePrecision from influxdb_client.client.write_api import SYNCHRONOUS from pydantic import BaseSettings class Settings(BaseSettings): hive_name: str token: str org: str bucket: str ...
0.566978
0.116186
#Usage: #converter.py [-h] #(-h2b | -h2a | -x2a | -a2h | -a2x | -b64d | -b64e | -urld | -urle) #(-s <input> | -f <filename>) [-c] #Usage examples: #converter.py -a2h -s "ABCDabcd" -> 41 42 43 44 61 62 63 64 #converter.py -x2a -c -s "\x41\x42\x43\x44\x61\x62\x63\x64" -> ABCDabcd (to stdout and clipboard) #co...
converter.py
#Usage: #converter.py [-h] #(-h2b | -h2a | -x2a | -a2h | -a2x | -b64d | -b64e | -urld | -urle) #(-s <input> | -f <filename>) [-c] #Usage examples: #converter.py -a2h -s "ABCDabcd" -> 41 42 43 44 61 62 63 64 #converter.py -x2a -c -s "\x41\x42\x43\x44\x61\x62\x63\x64" -> ABCDabcd (to stdout and clipboard) #co...
0.375936
0.278533
import copy import inspect from schema import Schema, Optional, And, Or, Use from testplan.common.utils.interface import check_signature from testplan.common.utils import logger # A sentinel object meaning not defined, it is useful when you need to # handle arbitrary objects (including None). ABSENT = Optional._MARK...
testplan/common/config/base.py
import copy import inspect from schema import Schema, Optional, And, Or, Use from testplan.common.utils.interface import check_signature from testplan.common.utils import logger # A sentinel object meaning not defined, it is useful when you need to # handle arbitrary objects (including None). ABSENT = Optional._MARK...
0.883619
0.379493
import json import redis from ..util import merge, REQUIRED from .driver import Driver class RedisDriver(Driver): client: redis.Redis def __init__(self, args): args = merge(args, { "host": 'localhost', "port": 6379, "db": 0, "password": <PASSWORD>, ...
qas/driver/redis_driver.py
import json import redis from ..util import merge, REQUIRED from .driver import Driver class RedisDriver(Driver): client: redis.Redis def __init__(self, args): args = merge(args, { "host": 'localhost', "port": 6379, "db": 0, "password": <PASSWORD>, ...
0.442637
0.16455
from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import Staff, Permission, Resource, Menu, Role class StaffCreationForm...
jwt_auth/admin.py
from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import Staff, Permission, Resource, Menu, Role class StaffCreationForm...
0.368747
0.066327
from typing import Dict, List from datetime import datetime, timedelta, date from bs4 import BeautifulSoup import requests import json def GetEPGFromNAVER(serviceId: str, period: int) -> List: """ NAVER에서 ServiceId에 해당하는 채널의 EPG를 받아옵니다.\n @return [ { 'Title': '프로그램 이름', 'Su...
GetEPG/FromNAVER.py
from typing import Dict, List from datetime import datetime, timedelta, date from bs4 import BeautifulSoup import requests import json def GetEPGFromNAVER(serviceId: str, period: int) -> List: """ NAVER에서 ServiceId에 해당하는 채널의 EPG를 받아옵니다.\n @return [ { 'Title': '프로그램 이름', 'Su...
0.635109
0.211641
from webob.request import Request from webob.dec import wsgify from webob.exc import no_escape from webob.exc import strip_tags from webob.exc import HTTPException from webob.exc import WSGIHTTPException from webob.exc import _HTTPMove from webob.exc import HTTPMethodNotAllowed from webob.exc import HTTPExceptionMiddle...
lib/WebOb-1.2.2/tests/test_exc.py
from webob.request import Request from webob.dec import wsgify from webob.exc import no_escape from webob.exc import strip_tags from webob.exc import HTTPException from webob.exc import WSGIHTTPException from webob.exc import _HTTPMove from webob.exc import HTTPMethodNotAllowed from webob.exc import HTTPExceptionMiddle...
0.493897
0.213992
from opnreco.models import perms from opnreco.models.db import File from opnreco.models.db import FileLoopConfig from opnreco.models.db import FileSync from opnreco.models.db import Loop from opnreco.models.db import Movement from opnreco.models.db import OwnerLog from opnreco.models.db import Peer from opnreco.models....
backend/opnreco/api/fileapi.py
from opnreco.models import perms from opnreco.models.db import File from opnreco.models.db import FileLoopConfig from opnreco.models.db import FileSync from opnreco.models.db import Loop from opnreco.models.db import Movement from opnreco.models.db import OwnerLog from opnreco.models.db import Peer from opnreco.models....
0.569972
0.180359
import os from tqdm import tqdm import numpy as np from sklearn.preprocessing import StandardScaler import torch from torch import nn from torch.optim import Adam from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.data import DataLoader from model import BinClassifier def train(): device = ['c...
2d_navigation/imitation_learning/train_model.py
import os from tqdm import tqdm import numpy as np from sklearn.preprocessing import StandardScaler import torch from torch import nn from torch.optim import Adam from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.data import DataLoader from model import BinClassifier def train(): device = ['c...
0.542621
0.324235
import sys import unittest import dask.array import dask.distributed as dd import numpy as np import xarray as xr # Import from directory structure if coverage test, or from installed # packages otherwise if "--cov" in str(sys.argv): from src.geocat.comp import dewtemp, heat_index, relhum, relhum_ice, relhum_wate...
test/test_meteorology.py
import sys import unittest import dask.array import dask.distributed as dd import numpy as np import xarray as xr # Import from directory structure if coverage test, or from installed # packages otherwise if "--cov" in str(sys.argv): from src.geocat.comp import dewtemp, heat_index, relhum, relhum_ice, relhum_wate...
0.384912
0.502258
to BigQuery.""" from google.cloud import bigquery import uuid def upload_metrics_to_bq(test_name, total_time, epochs, batch_size, backend_type, backend_version, cpu_num_cores, cpu_memory, cpu_memory_info, gpu_count, gpu_platform, platform_type, platform_machine_type, keras_version, sample_type=Non...
scripts/keras_benchmarks/upload_benchmarks_bq.py
to BigQuery.""" from google.cloud import bigquery import uuid def upload_metrics_to_bq(test_name, total_time, epochs, batch_size, backend_type, backend_version, cpu_num_cores, cpu_memory, cpu_memory_info, gpu_count, gpu_platform, platform_type, platform_machine_type, keras_version, sample_type=Non...
0.604049
0.381335
from functools import partial import simplejson as json import os import tempfile from celery.exceptions import RetryTaskError from celery.task import task import pandas as pd from bamboo.lib.async import call_async from bamboo.lib.datetools import recognize_dates from bamboo.lib.schema_builder import filter_schema ...
bamboo/lib/readers.py
from functools import partial import simplejson as json import os import tempfile from celery.exceptions import RetryTaskError from celery.task import task import pandas as pd from bamboo.lib.async import call_async from bamboo.lib.datetools import recognize_dates from bamboo.lib.schema_builder import filter_schema ...
0.560734
0.445891
from django.contrib import admin from oscar.core.loading import get_model Attachment = get_model('oscar_support', 'Attachment') Line = get_model('order', 'Line') Message = get_model('oscar_support', 'Message') Priority = get_model("oscar_support", "Priority") Product = get_model('catalogue', 'Product') RelatedOrder = ...
oscar_support/admin.py
from django.contrib import admin from oscar.core.loading import get_model Attachment = get_model('oscar_support', 'Attachment') Line = get_model('order', 'Line') Message = get_model('oscar_support', 'Message') Priority = get_model("oscar_support", "Priority") Product = get_model('catalogue', 'Product') RelatedOrder = ...
0.36523
0.116613
import argparse from pathlib import Path import optuna from optuna.pruners import SuccessiveHalvingPruner import pytorch_lightning as pl import torch from torch import nn, optim from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision import datasets, transforms BATCH_SIZE = 128 D...
pytorch_lightning_optuna/main.py
import argparse from pathlib import Path import optuna from optuna.pruners import SuccessiveHalvingPruner import pytorch_lightning as pl import torch from torch import nn, optim from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision import datasets, transforms BATCH_SIZE = 128 D...
0.880316
0.456289
import os, time, sys, shutil, urllib.request, urllib.parse minify = False def sources(): path = "./src/" return [ os.path.join(base, f) for base, folders, files in os.walk(path) for f in files if f.endswith(".js") ] def build(): path = "./www/fsm.js" data = "\n"...
build.py
import os, time, sys, shutil, urllib.request, urllib.parse minify = False def sources(): path = "./src/" return [ os.path.join(base, f) for base, folders, files in os.walk(path) for f in files if f.endswith(".js") ] def build(): path = "./www/fsm.js" data = "\n"...
0.251096
0.107204
import asyncio from BubotObj.OcfDevice.subtype.Device.Device import Device from Bubot.Core.DeviceLink import ResourceLink from aio_modbus_client.ModbusProtocolOcf import ModbusProtocolOcf from aio_modbus_client.ModbusDevice import ModbusDevice as ModbusDevice from Bubot.Helpers.ExtException import ExtException, ExtTime...
src/BubotObj/OcfDevice/subtype/ModbusSlave/ModbusSlave.py
import asyncio from BubotObj.OcfDevice.subtype.Device.Device import Device from Bubot.Core.DeviceLink import ResourceLink from aio_modbus_client.ModbusProtocolOcf import ModbusProtocolOcf from aio_modbus_client.ModbusDevice import ModbusDevice as ModbusDevice from Bubot.Helpers.ExtException import ExtException, ExtTime...
0.266644
0.063279
from InstagramAPI import InstagramAPI from core.imgur import im import asyncio import codecs import core.constants as constants #this class makes communicating with instagram api straightforward class InstaAPI: def __init__(self, username, password): self.username = username self.password = passwor...
core/instagram.py
from InstagramAPI import InstagramAPI from core.imgur import im import asyncio import codecs import core.constants as constants #this class makes communicating with instagram api straightforward class InstaAPI: def __init__(self, username, password): self.username = username self.password = passwor...
0.244093
0.147709
import os import random import tarfile from rest_framework import viewsets import requests from .models import Answer, Activity from .serializers import AnswerSerializer, ActivityImageSerializer from core.permissions import IsProfessorCoordinatorOrAdminPermissionOrReadOnly from rest_framework.response import Response...
activities/views.py
import os import random import tarfile from rest_framework import viewsets import requests from .models import Answer, Activity from .serializers import AnswerSerializer, ActivityImageSerializer from core.permissions import IsProfessorCoordinatorOrAdminPermissionOrReadOnly from rest_framework.response import Response...
0.226955
0.07658
from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class BiosVfSelectPprTypeConsts: VP_SELECT_PPR_TYPE_DISABLED = "Disabled" VP_SELECT_PPR_TYPE_HARD_PPR = "Hard PPR" VP_SELECT_PPR_TYPE_SOFT_PPR = "Soft PPR" _VP_SELECT_PPR_TYPE_DISAB...
imcsdk/mometa/bios/BiosVfSelectPprType.py
from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class BiosVfSelectPprTypeConsts: VP_SELECT_PPR_TYPE_DISABLED = "Disabled" VP_SELECT_PPR_TYPE_HARD_PPR = "Hard PPR" VP_SELECT_PPR_TYPE_SOFT_PPR = "Soft PPR" _VP_SELECT_PPR_TYPE_DISAB...
0.420362
0.226634
import sys import numpy as np import random import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.distributions import Bernoulli import gym from PIL import Image from time import sleep from pathlib import Path import cv2 # code for the only two actions in Pong...
pong/pong_play.py
import sys import numpy as np import random import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.distributions import Bernoulli import gym from PIL import Image from time import sleep from pathlib import Path import cv2 # code for the only two actions in Pong...
0.707
0.499023
from vas.shared.Deletable import Deletable from vas.shared.MutableCollection import MutableCollection from vas.shared.Resource import Resource from vas.util.LinkUtils import LinkUtils class Templates(MutableCollection): """Used to enumerate, create, and delete tc Server templates :ivar `vas.shared.Security....
vas/tc_server/Templates.py
from vas.shared.Deletable import Deletable from vas.shared.MutableCollection import MutableCollection from vas.shared.Resource import Resource from vas.util.LinkUtils import LinkUtils class Templates(MutableCollection): """Used to enumerate, create, and delete tc Server templates :ivar `vas.shared.Security....
0.828176
0.285216
from FileParsers.Parser import Parser class PVTMetric(Parser): def __init__(self, file): super(PVTMetric, self).__init__(file) # This class is not part of the configuration @staticmethod def metric_naming(file): import re stage = "" syn = re.search(r'.*syn.*', file, re...
genCSV/FileParsers/Synopsys/PVTmetric.py
from FileParsers.Parser import Parser class PVTMetric(Parser): def __init__(self, file): super(PVTMetric, self).__init__(file) # This class is not part of the configuration @staticmethod def metric_naming(file): import re stage = "" syn = re.search(r'.*syn.*', file, re...
0.460895
0.087759
from kubernetes import client from cowait.engine.const import LABEL_TASK_ID from cowait.engine.kubernetes.affinity import create_affinity def test_create_str_stack_affinity(): affinity = create_affinity('stack') assert isinstance(affinity, client.V1Affinity) assert affinity.pod_anti_affinity is None i...
test/engine/kubernetes/test_affinity.py
from kubernetes import client from cowait.engine.const import LABEL_TASK_ID from cowait.engine.kubernetes.affinity import create_affinity def test_create_str_stack_affinity(): affinity = create_affinity('stack') assert isinstance(affinity, client.V1Affinity) assert affinity.pod_anti_affinity is None i...
0.678647
0.735202
from dlkp.models import KeyphraseTagger from dlkp.extraction import ( KEDataArguments, KEModelArguments, KETrainingArguments, ) model_name = "bloomberg/KBIR" print("Training: ", model_name) training_args = KETrainingArguments( output_dir=f"/data/models/keyphrase/dlkp/inspec/extraction/{model_name}/fin...
examples/ke/ke_tagger.py
from dlkp.models import KeyphraseTagger from dlkp.extraction import ( KEDataArguments, KEModelArguments, KETrainingArguments, ) model_name = "bloomberg/KBIR" print("Training: ", model_name) training_args = KETrainingArguments( output_dir=f"/data/models/keyphrase/dlkp/inspec/extraction/{model_name}/fin...
0.651687
0.225566
import argparse import os import pandas import numpy import matplotlib.pyplot import matplotlib.dates import datetime fig_dir = 'fig' table_dir = 'table' class Pointing: def __init__(self, data_path): self.file_base, _ = os.path.splitext(os.path.basename(data_path)) self.data_raw = pandas.read_c...
qlp_plot.py
import argparse import os import pandas import numpy import matplotlib.pyplot import matplotlib.dates import datetime fig_dir = 'fig' table_dir = 'table' class Pointing: def __init__(self, data_path): self.file_base, _ = os.path.splitext(os.path.basename(data_path)) self.data_raw = pandas.read_c...
0.342462
0.254251
import time from celery.utils.log import get_task_logger from django.core.mail import send_mail from django.template.loader import render_to_string from images.models import Image from dominion import base from dominion.app import APP from dominion.engine import EXIT_STATUS, PiemanDocker from dominion.exceptions im...
dominion/tasks.py
import time from celery.utils.log import get_task_logger from django.core.mail import send_mail from django.template.loader import render_to_string from images.models import Image from dominion import base from dominion.app import APP from dominion.engine import EXIT_STATUS, PiemanDocker from dominion.exceptions im...
0.304145
0.098729
import sys, os, time import scipy.io as si import numpy as np import ggmm.gpu as ggmm # Matlab inteface imports import matlab.engine ''' Functions: ''' def readEngine(file): try: X = si.loadmat(file)['output'] except: X = np.array([]) return X def EMEngine(X, thresh_, n_...
experiment/Matlab/emgmm.py
import sys, os, time import scipy.io as si import numpy as np import ggmm.gpu as ggmm # Matlab inteface imports import matlab.engine ''' Functions: ''' def readEngine(file): try: X = si.loadmat(file)['output'] except: X = np.array([]) return X def EMEngine(X, thresh_, n_...
0.200088
0.178777
import abc import random import six from optinum.algorithm import base from optinum.common import objects __all__ = ['HCFirstImprovement', 'HCBestImprovement'] @six.add_metaclass(abc.ABCMeta) class HillClimbing(base.Algorithm): def __init__(self, name="HillClimbing", max_evaluations=50): super(HillCli...
optinum/algorithm/hillclimbing.py
import abc import random import six from optinum.algorithm import base from optinum.common import objects __all__ = ['HCFirstImprovement', 'HCBestImprovement'] @six.add_metaclass(abc.ABCMeta) class HillClimbing(base.Algorithm): def __init__(self, name="HillClimbing", max_evaluations=50): super(HillCli...
0.710427
0.153899
import sys sys.path.append('/home/george2/Raise/ProgramRepair/CodeSeer/projects/src/main/python') from CodeJam.Y11R5P1.dennislissov.A import * def func_3ba6780ca418469a885da55554034725(y, x): area += (x - px) * (y + py) / 2 px, py = x, y return py def func_16bfa03b301e43139f8f644e5e7cbce6(y, x): area...
projects/src/main/python/CodeJam/Y11R5P1/dennislissov/generated_py_bb93a4d1acf540c3b7c8dfd80359bd28.py
import sys sys.path.append('/home/george2/Raise/ProgramRepair/CodeSeer/projects/src/main/python') from CodeJam.Y11R5P1.dennislissov.A import * def func_3ba6780ca418469a885da55554034725(y, x): area += (x - px) * (y + py) / 2 px, py = x, y return py def func_16bfa03b301e43139f8f644e5e7cbce6(y, x): area...
0.313
0.415432
import os import torch as t from config import Config from utils import get_data_loader, fgsm, repeat_error_verfication from datetime import datetime import sys opt = Config() def test(**kwargs): """Test models""" opt.parse(**kwargs) opt.print() # device device = t.device('cuda') i...
test.py
import os import torch as t from config import Config from utils import get_data_loader, fgsm, repeat_error_verfication from datetime import datetime import sys opt = Config() def test(**kwargs): """Test models""" opt.parse(**kwargs) opt.print() # device device = t.device('cuda') i...
0.255529
0.13452
import numpy as np import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects # Setup fig = plt.figure(figsize=(6, 6)) ax = plt.subplot(1, 1, 1, projection="polar", frameon=True) ax.set_thetalim(0, 2 * np.pi) ax.set_rlim(0, 1000) ax.set_xticks([]) ax.set_xticklabels([]) ax.set_yticks(np.linspace(100...
code/scales-projections/projection-polar-histogram.py
import numpy as np import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects # Setup fig = plt.figure(figsize=(6, 6)) ax = plt.subplot(1, 1, 1, projection="polar", frameon=True) ax.set_thetalim(0, 2 * np.pi) ax.set_rlim(0, 1000) ax.set_xticks([]) ax.set_xticklabels([]) ax.set_yticks(np.linspace(100...
0.640861
0.711223
from flask import Flask, request,render_template import sys #sys.path.append("C:/Users/Freddie/Documents/Desktop/dbTest/Front-end/antlr") sys.path.append("../antlr") import runSQL app = Flask(__name__) currentDB = " " errors = "" @app.route('/home') @app.route("/") def hello(): return render_template('home.html...
Front-end/web/routesFile.py
from flask import Flask, request,render_template import sys #sys.path.append("C:/Users/Freddie/Documents/Desktop/dbTest/Front-end/antlr") sys.path.append("../antlr") import runSQL app = Flask(__name__) currentDB = " " errors = "" @app.route('/home') @app.route("/") def hello(): return render_template('home.html...
0.070776
0.038829
from __future__ import division, absolute_import, print_function, unicode_literals from collections import defaultdict from django.utils import six from .util import DoesNotExist from .mappings import OldValues from .descriptors import _inject_descriptors __all__ = ('SaveTheChange', 'UpdateTogether', 'TrackChang...
save_the_change/decorators.py
from __future__ import division, absolute_import, print_function, unicode_literals from collections import defaultdict from django.utils import six from .util import DoesNotExist from .mappings import OldValues from .descriptors import _inject_descriptors __all__ = ('SaveTheChange', 'UpdateTogether', 'TrackChang...
0.747155
0.117294
import json import os import sys import pandas.io.sql as psql import requests crypto_tools_dir = os.getcwd().split('/scripts/')[0] + '/scripts/' sys.path.append(crypto_tools_dir) from crypto_tools import * class PopulateKraken(object): """ """ def __init__(self): """ """ self.po...
scripts/populate_database/populate_kraken.py
import json import os import sys import pandas.io.sql as psql import requests crypto_tools_dir = os.getcwd().split('/scripts/')[0] + '/scripts/' sys.path.append(crypto_tools_dir) from crypto_tools import * class PopulateKraken(object): """ """ def __init__(self): """ """ self.po...
0.202601
0.076304
from azure.cli.core.commands.parameters import ( get_three_state_flag, get_enum_type ) from azure.cli.core.commands.validators import validate_file_or_dict from azext_planner.action import ( AddCategoryDescriptions, AddApplication, AddBucketTaskBoardFormat, AddProgressTaskBoardFormat ) def lo...
msgraph/cli/command_modules/planner/azext_planner/generated/_params.py
from azure.cli.core.commands.parameters import ( get_three_state_flag, get_enum_type ) from azure.cli.core.commands.validators import validate_file_or_dict from azext_planner.action import ( AddCategoryDescriptions, AddApplication, AddBucketTaskBoardFormat, AddProgressTaskBoardFormat ) def lo...
0.601828
0.090695
"""Test the UI.""" from __future__ import absolute_import, print_function, unicode_literals import responses from gimme.helpers import CLOUD_RM def test_not_logged_in(app): """Test what happens when we're not logged in. Ensure we trigger the OAuth flow if we don't have a valid session. """ res ...
tests/test_ui.py
"""Test the UI.""" from __future__ import absolute_import, print_function, unicode_literals import responses from gimme.helpers import CLOUD_RM def test_not_logged_in(app): """Test what happens when we're not logged in. Ensure we trigger the OAuth flow if we don't have a valid session. """ res ...
0.789071
0.474875
from random import choice class CardDeck(): ''' Esta classe descreve o baralho ''' _card_list: list def __init__(self): self._card_list = [] # Geração do baralho # Cada carta é gerada e depois é atribuída a algum naipe suit = '' for i in range(4): ...
Poker/cards.py
from random import choice class CardDeck(): ''' Esta classe descreve o baralho ''' _card_list: list def __init__(self): self._card_list = [] # Geração do baralho # Cada carta é gerada e depois é atribuída a algum naipe suit = '' for i in range(4): ...
0.416678
0.253971
import json import base64 import requests from uuid import UUID from os import urandom from time import timezone from typing import BinaryIO, Union from binascii import hexlify from time import time as timestamp from json_minify import json_minify from . import client from .utils import exceptions, headers, ...
proudcatowner/sub_client.py
import json import base64 import requests from uuid import UUID from os import urandom from time import timezone from typing import BinaryIO, Union from binascii import hexlify from time import time as timestamp from json_minify import json_minify from . import client from .utils import exceptions, headers, ...
0.520009
0.069542
import matplotlib.pyplot as plt import matplotlib as mpl import pandas as pd import numpy as np def gastrack(df: pd.DataFrame, gas: list = None, lims: list = None, dtick: bool =False, ax=None, gas_range:list =[0.2,20000], fontsize:int =8...
reservoirpy/welllogspy/tracks/gastrack.py
import matplotlib.pyplot as plt import matplotlib as mpl import pandas as pd import numpy as np def gastrack(df: pd.DataFrame, gas: list = None, lims: list = None, dtick: bool =False, ax=None, gas_range:list =[0.2,20000], fontsize:int =8...
0.477798
0.531939
import dash from dash.exceptions import PreventUpdate import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import dash_bootstrap_components as dbc import utils.dash_reusable_components as drc import dash_table import plotly.express as ex import plotl...
old experiments/UI_cars.py
import dash from dash.exceptions import PreventUpdate import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import dash_bootstrap_components as dbc import utils.dash_reusable_components as drc import dash_table import plotly.express as ex import plotl...
0.478041
0.14919
# Adds sound to the visualisation import os import subprocess from tempfile import mkstemp import numpy as np from scipy.io.wavfile import write as write_wav from .utils import norm_and_centre from SCE import gen_audio def encode_audio(results, video_file, total_duration, sample_rate=44100, threads=1): # Extra...
mandrake/sound.py
# Adds sound to the visualisation import os import subprocess from tempfile import mkstemp import numpy as np from scipy.io.wavfile import write as write_wav from .utils import norm_and_centre from SCE import gen_audio def encode_audio(results, video_file, total_duration, sample_rate=44100, threads=1): # Extra...
0.431345
0.41324
import os import sys import re # pyside2 package from PySide2.QtWidgets import QFileDialog, QMessageBox, QProgressDialog from PySide2.QtCore import Qt, QDir, QCoreApplication from PySide2.QtSql import QSqlQuery, QSqlQueryModel from PySide2.QtGui import QColor # python-docx package from docx import Document, oxml, sha...
QRegisterConst.py
import os import sys import re # pyside2 package from PySide2.QtWidgets import QFileDialog, QMessageBox, QProgressDialog from PySide2.QtCore import Qt, QDir, QCoreApplication from PySide2.QtSql import QSqlQuery, QSqlQueryModel from PySide2.QtGui import QColor # python-docx package from docx import Document, oxml, sha...
0.181916
0.083516
import wx class TextPanel(wx.Panel): """A :class:`wx.PyPanel` which may be used to display a string of text, oriented either horizontally or vertically. """ def __init__(self, parent, text=None, orient=wx.HORIZONTAL, **kwargs): """Create a ``TextPanel``. :arg parent: The :mod:`wx` pa...
fsleyes_widgets/textpanel.py
import wx class TextPanel(wx.Panel): """A :class:`wx.PyPanel` which may be used to display a string of text, oriented either horizontally or vertically. """ def __init__(self, parent, text=None, orient=wx.HORIZONTAL, **kwargs): """Create a ``TextPanel``. :arg parent: The :mod:`wx` pa...
0.784402
0.23014
from typing import TYPE_CHECKING, Coroutine if TYPE_CHECKING: from Platforms.Discord.main_discord import PhaazebotDiscord from Platforms.Web.main_web import PhaazebotWeb import json import asyncio import discord from aiohttp.web import Response from Utils.Classes.discordserversettings import DiscordServerSettings fr...
Platforms/Web/Processing/Api/Discord/Regulars/create.py
from typing import TYPE_CHECKING, Coroutine if TYPE_CHECKING: from Platforms.Discord.main_discord import PhaazebotDiscord from Platforms.Web.main_web import PhaazebotWeb import json import asyncio import discord from aiohttp.web import Response from Utils.Classes.discordserversettings import DiscordServerSettings fr...
0.605916
0.048812
import os import paramiko import socket import sys import threading hostkey_file = input('HOSTKEY file name: ') CWD = os.path.dirname(os.path.realpath(__file__)) # RSA key can be used to sign and verify SSH data during SSH2 negoatiation HOSTKEY = paramiko.RSAKey(filename=os.path.join(CWD, hostkey_file)) class Sas...
SSHTools/ssh_server.py
import os import paramiko import socket import sys import threading hostkey_file = input('HOSTKEY file name: ') CWD = os.path.dirname(os.path.realpath(__file__)) # RSA key can be used to sign and verify SSH data during SSH2 negoatiation HOSTKEY = paramiko.RSAKey(filename=os.path.join(CWD, hostkey_file)) class Sas...
0.3027
0.068975
import os, sys import numpy as np import numpy as np import os,sys from sklearn import preprocessing import pickle, logging from sklearn.metrics import mean_squared_error import dynet as dy import time, random ''' Assumes that input_full and output_full within a directory called data contain input and output features...
world/FFNN/MVP/map_small_dynet.py
import os, sys import numpy as np import numpy as np import os,sys from sklearn import preprocessing import pickle, logging from sklearn.metrics import mean_squared_error import dynet as dy import time, random ''' Assumes that input_full and output_full within a directory called data contain input and output features...
0.376623
0.412589
from dataclasses import dataclass import copy import numpy as np """ file that constains a few classes that do automatric unit management. The idea of these modules is to provide the units that qcodes needs for plotting. The setpoint_mgr is meant to run in segment object and can be conbined easily for all the channels...
pulse_lib/segments/utility/setpoint_mgr.py
from dataclasses import dataclass import copy import numpy as np """ file that constains a few classes that do automatric unit management. The idea of these modules is to provide the units that qcodes needs for plotting. The setpoint_mgr is meant to run in segment object and can be conbined easily for all the channels...
0.761937
0.274698
import random import logging from ask_sdk_core.skill_builder import SkillBuilder from ask_sdk_core.dispatch_components import ( AbstractRequestHandler, AbstractExceptionHandler, AbstractRequestInterceptor, AbstractResponseInterceptor) from ask_sdk_core.utils import is_request_type, is_intent_name from ask_sdk_...
IndiaFacts/lambda/lambda_function.py
import random import logging from ask_sdk_core.skill_builder import SkillBuilder from ask_sdk_core.dispatch_components import ( AbstractRequestHandler, AbstractExceptionHandler, AbstractRequestInterceptor, AbstractResponseInterceptor) from ask_sdk_core.utils import is_request_type, is_intent_name from ask_sdk_...
0.440951
0.069069
from connexion import request from flask import make_response, jsonify from src import db from src.models import Quote, QuoteItem, Transaction def create_quote(body): # noqa: E501 if request.is_json: customer_id = body.get('customer_id') date = body.get('date') description = body.get('de...
services/server/src/quotes/views.py
from connexion import request from flask import make_response, jsonify from src import db from src.models import Quote, QuoteItem, Transaction def create_quote(body): # noqa: E501 if request.is_json: customer_id = body.get('customer_id') date = body.get('date') description = body.get('de...
0.357119
0.05752
from enum import Enum from pathlib import Path from typing import Callable, Dict, List, Optional, Set, Tuple, Union import pytest from typer.testing import CliRunner from chessli.cli.main import app runner = CliRunner() main_commands = [ "--help", "--version", "-v", "-vv", "-vvv", "--user D...
tests/test_cli_commands.py
from enum import Enum from pathlib import Path from typing import Callable, Dict, List, Optional, Set, Tuple, Union import pytest from typer.testing import CliRunner from chessli.cli.main import app runner = CliRunner() main_commands = [ "--help", "--version", "-v", "-vv", "-vvv", "--user D...
0.694199
0.307124
import numpy as np from scipy.optimize import check_grad from deep_rlsp.solvers.value_iter import value_iter, evaluate_policy from deep_rlsp.solvers.ppo import PPOSolver from deep_rlsp.util.parameter_checks import check_in def compute_g(mdp, policy, p_0, T, d_last_step_list, expected_features_list): nS, nA, nF =...
src/deep_rlsp/rlsp.py
import numpy as np from scipy.optimize import check_grad from deep_rlsp.solvers.value_iter import value_iter, evaluate_policy from deep_rlsp.solvers.ppo import PPOSolver from deep_rlsp.util.parameter_checks import check_in def compute_g(mdp, policy, p_0, T, d_last_step_list, expected_features_list): nS, nA, nF =...
0.673299
0.635208
from adapt.tools.text.trie import Trie from six.moves import xrange __author__ = 'seanfitz' class EntityTagger(object): """ Known Entity Tagger Given an index of known entities, can efficiently search for those entities within a provided utterance. """ def __init__(self, trie, tokenizer, regex_e...
adapt/entity_tagger.py
from adapt.tools.text.trie import Trie from six.moves import xrange __author__ = 'seanfitz' class EntityTagger(object): """ Known Entity Tagger Given an index of known entities, can efficiently search for those entities within a provided utterance. """ def __init__(self, trie, tokenizer, regex_e...
0.774669
0.436442
import os import logging import asyncio import pickle from pathlib import Path from typing import Union import numpy as np import pandas as pd from PIL import Image from easydict import EasyDict from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import train_test_split from sklearn.exte...
src/database/read_db.py
import os import logging import asyncio import pickle from pathlib import Path from typing import Union import numpy as np import pandas as pd from PIL import Image from easydict import EasyDict from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import train_test_split from sklearn.exte...
0.640411
0.256622
_LAMP_DIGITS = { 'red': 0, 'yellow': 1, 'green': 2 } _LAMP_STATES = { 'off': 0, 'on': 1, 'blink': 2, 'quickblink': 3 } def build_lamp_flags(states): """Returns flags that be used as arguments of lamp control commands. The structure of <states> is: {'lamps': {<color>: <sta...
keiko/flags.py
_LAMP_DIGITS = { 'red': 0, 'yellow': 1, 'green': 2 } _LAMP_STATES = { 'off': 0, 'on': 1, 'blink': 2, 'quickblink': 3 } def build_lamp_flags(states): """Returns flags that be used as arguments of lamp control commands. The structure of <states> is: {'lamps': {<color>: <sta...
0.842766
0.572633
from dataclasses import dataclass from typing import Optional, Union import numpy as np import pandas as pd import sklearn.metrics as sk_metrics from .scorer import ScoreCalculator, Timeliness @dataclass class _ThreshRequired: p_thresh: bool p_hat_thresh: bool def check_threshs_correct( self, p...
epiquark/api.py
from dataclasses import dataclass from typing import Optional, Union import numpy as np import pandas as pd import sklearn.metrics as sk_metrics from .scorer import ScoreCalculator, Timeliness @dataclass class _ThreshRequired: p_thresh: bool p_hat_thresh: bool def check_threshs_correct( self, p...
0.959978
0.460774
from unittest import TestCase from collections import Counter from dark.intervals import OffsetAdjuster, ReadIntervals from dark.hsp import HSP class TestReadIntervals(TestCase): """ Test the ReadIntervals class """ EMPTY = ReadIntervals.EMPTY FULL = ReadIntervals.FULL def testEmpty(self): ...
test/test_intervals.py
from unittest import TestCase from collections import Counter from dark.intervals import OffsetAdjuster, ReadIntervals from dark.hsp import HSP class TestReadIntervals(TestCase): """ Test the ReadIntervals class """ EMPTY = ReadIntervals.EMPTY FULL = ReadIntervals.FULL def testEmpty(self): ...
0.864196
0.608972
import inspect import os from types import MethodType from django import shortcuts from django.conf import settings from django.http import HttpResponseNotFound, HttpResponseServerError, HttpRequest, HttpResponse from .util import logger from .util import utils from .util.utils import load_module # 包名称 ...
restful_dj/router.py
import inspect import os from types import MethodType from django import shortcuts from django.conf import settings from django.http import HttpResponseNotFound, HttpResponseServerError, HttpRequest, HttpResponse from .util import logger from .util import utils from .util.utils import load_module # 包名称 ...
0.184878
0.061621
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AliyunAccount', ...
misaka/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AliyunAccount', ...
0.4917
0.13707
import torch from torch import nn from gnn.emn import EMN from gnn.modules import FeedForwardNetwork, GraphGather class EMNImplementation(EMN): def __init__(self, node_features, edge_features, message_passes, out_features, edge_embedding_size, edge_emb_depth=3, edge_emb_hidden_...
gnn/emn_implementations.py
import torch from torch import nn from gnn.emn import EMN from gnn.modules import FeedForwardNetwork, GraphGather class EMNImplementation(EMN): def __init__(self, node_features, edge_features, message_passes, out_features, edge_embedding_size, edge_emb_depth=3, edge_emb_hidden_...
0.850763
0.29348
import logging import shutil import subprocess import sys from typing import List, Optional from codiga.exceptions.git_command_exception import GitCommandException COMMAND_DIFF = 'diff' def get_current_branch() -> Optional[str]: """ Returns the name of the current branch we are on Use the following comm...
codiga/utils/git.py
import logging import shutil import subprocess import sys from typing import List, Optional from codiga.exceptions.git_command_exception import GitCommandException COMMAND_DIFF = 'diff' def get_current_branch() -> Optional[str]: """ Returns the name of the current branch we are on Use the following comm...
0.608129
0.366193
from django.core.management.base import AppCommand from drf_app_generators.compliers.app import AppConfig, AppOptions from drf_app_generators.compliers.model import ModelMeta from drf_app_generators.generators import ( AdminGenerator, FactoryGenerator, ApiGenerator, SerializerGenerator, UnitTestGene...
drf_app_generators/management/commands/app_update.py
from django.core.management.base import AppCommand from drf_app_generators.compliers.app import AppConfig, AppOptions from drf_app_generators.compliers.model import ModelMeta from drf_app_generators.generators import ( AdminGenerator, FactoryGenerator, ApiGenerator, SerializerGenerator, UnitTestGene...
0.477311
0.071203
import pytest @pytest.mark.parametrize( 'path', [ '/images/hosted-logos/', '/hosting-logos/', ], ) @pytest.mark.parametrize( 'image', [ 'berknow150x40.jpg', 'berknow150x40.png', 'binnov-157x46.gif', 'binnov-157x46.png', 'lighter152x41.gif', '...
tests/main/hosting_logos_test.py
import pytest @pytest.mark.parametrize( 'path', [ '/images/hosted-logos/', '/hosting-logos/', ], ) @pytest.mark.parametrize( 'image', [ 'berknow150x40.jpg', 'berknow150x40.png', 'binnov-157x46.gif', 'binnov-157x46.png', 'lighter152x41.gif', '...
0.503174
0.585753
import mysql.connector # Insere informações no bando de dados MySql def insertDataBase(id, initial_dat, initial_time, final_dat, final_time, work_time): connection = mysql.connector.connect(host='localhost', database='db_projects', user='root', password='<PASSWORD>', auth_p...
defs/database.py
import mysql.connector # Insere informações no bando de dados MySql def insertDataBase(id, initial_dat, initial_time, final_dat, final_time, work_time): connection = mysql.connector.connect(host='localhost', database='db_projects', user='root', password='<PASSWORD>', auth_p...
0.153454
0.128607
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AcademicTerms', fields=[ ...
dashboard/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AcademicTerms', fields=[ ...
0.63375
0.115661
from collections import deque from typing import Callable TEST1 = """inp z inp x mul z 3 eql z x""" TEST2 = """inp w add z w mod z 2 div w 2 add y w mod y 2 div w 2 add x w mod x 2 div w 2 mod w 2""" def isinteger(s): if s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit() class Alu: ...
Advent2021/24.py
from collections import deque from typing import Callable TEST1 = """inp z inp x mul z 3 eql z x""" TEST2 = """inp w add z w mod z 2 div w 2 add y w mod y 2 div w 2 add x w mod x 2 div w 2 mod w 2""" def isinteger(s): if s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit() class Alu: ...
0.86241
0.756627
import sys import urllib import json import argparse import urllib.request import unicodedata import collections import os import xml.etree.ElementTree as ET import csv import glob # collection = "masukagami" # collection = "imakagami" # collection = "okagami" # collection = "mizukagami" collection = "azumakagami"...
src/nijl18/61_markDate.py
import sys import urllib import json import argparse import urllib.request import unicodedata import collections import os import xml.etree.ElementTree as ET import csv import glob # collection = "masukagami" # collection = "imakagami" # collection = "okagami" # collection = "mizukagami" collection = "azumakagami"...
0.031041
0.071235
import numpy as np import torch from torch.nn import LayerNorm import torch.nn as nn import torch.nn.functional as F from .layers.crf import CRF from transformers import BertModel, BertPreTrainedModel from .layers.linears import PoolerEndLogits, PoolerStartLogits from torch.nn import CrossEntropyLoss from loss...
models/bert_for_ner.py
import numpy as np import torch from torch.nn import LayerNorm import torch.nn as nn import torch.nn.functional as F from .layers.crf import CRF from transformers import BertModel, BertPreTrainedModel from .layers.linears import PoolerEndLogits, PoolerStartLogits from torch.nn import CrossEntropyLoss from loss...
0.927232
0.334019
import sys import os import numpy as np import argparse from sklearn.metrics import f1_score, accuracy_score import paddle as P import paddle.fluid as F import paddle.fluid.layers as L import paddle.fluid.dygraph as D from reader import ChnSentiCorp, pad_batch_data from paddle_edl.distill.distill_reader import Distil...
example/distill/nlp/model.py
import sys import os import numpy as np import argparse from sklearn.metrics import f1_score, accuracy_score import paddle as P import paddle.fluid as F import paddle.fluid.layers as L import paddle.fluid.dygraph as D from reader import ChnSentiCorp, pad_batch_data from paddle_edl.distill.distill_reader import Distil...
0.594434
0.223695
from pyomo.environ import * model = m = ConcreteModel() m.x2 = Var(within=Reals,bounds=(0,1),initialize=0) m.x3 = Var(within=Reals,bounds=(0,1),initialize=0) m.x4 = Var(within=Reals,bounds=(0,1),initialize=0) m.x5 = Var(within=Reals,bounds=(0,1),initialize=0) m.x6 = Var(within=Reals,bounds=(0,1),initialize=0) m.x7...
models_nonconvex_simple2/gabriel01.py
from pyomo.environ import * model = m = ConcreteModel() m.x2 = Var(within=Reals,bounds=(0,1),initialize=0) m.x3 = Var(within=Reals,bounds=(0,1),initialize=0) m.x4 = Var(within=Reals,bounds=(0,1),initialize=0) m.x5 = Var(within=Reals,bounds=(0,1),initialize=0) m.x6 = Var(within=Reals,bounds=(0,1),initialize=0) m.x7...
0.538741
0.192786
import torch import matplotlib.pyplot as plt import matplotlib.cm as CM from mcnn_model import MCNN from my_dataloader import CrowdDataset def cal_mae(img_root,gt_dmap_root,model_param_path): ''' Calculate the MAE of the test data. img_root: the root of test image data. gt_dmap_root: the root of test...
test.py
import torch import matplotlib.pyplot as plt import matplotlib.cm as CM from mcnn_model import MCNN from my_dataloader import CrowdDataset def cal_mae(img_root,gt_dmap_root,model_param_path): ''' Calculate the MAE of the test data. img_root: the root of test image data. gt_dmap_root: the root of test...
0.499756
0.536738
"""Zeff commandline processing utilities.""" __author__ = """<NAME> <<EMAIL>>""" __copyright__ = """Copyright © 2019, Ziff, Inc. — All Rights Reserved""" __license__ = """ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may...
src/zeff/cli/pipeline.py
"""Zeff commandline processing utilities.""" __author__ = """<NAME> <<EMAIL>>""" __copyright__ = """Copyright © 2019, Ziff, Inc. — All Rights Reserved""" __license__ = """ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may...
0.88521
0.231913
import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("core", "0039_generate_initial_topic_materialzed_paths"), ] operations = [ migrations.AlterField( model_name="topic", name="path", ...
src/backend/partaj/core/migrations/0040_create_manytomany_referrals_units.py
import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("core", "0039_generate_initial_topic_materialzed_paths"), ] operations = [ migrations.AlterField( model_name="topic", name="path", ...
0.553385
0.202621