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 librosa import math import numpy as np import jukebox.utils.dist_adapter as dist from torch.utils.data import Dataset from jukebox.utils.dist_utils import print_all from jukebox.utils.io import get_duration_sec, load_audio from jukebox.data.labels import Labeller class FilesAudioDataset(Dataset): def __init...
jukebox/data/files_dataset.py
import librosa import math import numpy as np import jukebox.utils.dist_adapter as dist from torch.utils.data import Dataset from jukebox.utils.dist_utils import print_all from jukebox.utils.io import get_duration_sec, load_audio from jukebox.data.labels import Labeller class FilesAudioDataset(Dataset): def __init...
0.651577
0.3398
from logging import getLogger from os import urandom from urllib.parse import urlparse, urljoin, urlencode import flask from flask_login import current_user, login_user, \ logout_user, login_required, LoginManager from babel.dates import format_datetime from .user import User from ._version import __versi...
crackomatic/flask.py
from logging import getLogger from os import urandom from urllib.parse import urlparse, urljoin, urlencode import flask from flask_login import current_user, login_user, \ logout_user, login_required, LoginManager from babel.dates import format_datetime from .user import User from ._version import __versi...
0.305076
0.081996
from .atom import atom def preparse(tokens): """ Break up a tokenized source into lists; this allows input like pl> (a, b) (c, d) to work as expected. """ count_open = 0 lists = [] current_list = [] if len(tokens) == 0: raise SyntaxError("Unexpected EOF while preparsing."...
parens/parse.py
from .atom import atom def preparse(tokens): """ Break up a tokenized source into lists; this allows input like pl> (a, b) (c, d) to work as expected. """ count_open = 0 lists = [] current_list = [] if len(tokens) == 0: raise SyntaxError("Unexpected EOF while preparsing."...
0.355775
0.364297
import pandas as pd import param import pytest from bokeh.models.sources import ColumnDataSource from awesome_panel_extensions.widgets.dataframe_base import ( DataFrameWithStreamAndPatchBaseWidget as DFWidget, ) VALUE_CHANGED_COUNT = 0 # region value @pytest.fixture def data(): return {"x": [1, 2, 3, 4], "...
tests/widgets/test_dataframe_base.py
import pandas as pd import param import pytest from bokeh.models.sources import ColumnDataSource from awesome_panel_extensions.widgets.dataframe_base import ( DataFrameWithStreamAndPatchBaseWidget as DFWidget, ) VALUE_CHANGED_COUNT = 0 # region value @pytest.fixture def data(): return {"x": [1, 2, 3, 4], "...
0.628635
0.589037
import argparse def main(inputfile, outputdir): read_file = open(inputfile,"r") lines_read = read_file.readlines() read_file.close() filename = inputfile.split('/')[-1] page_id = filename.split('.')[0] lines_to_write = [] try: header = lines_read[0] header_items = header.spl...
storage_machine/convertPostFile.py
import argparse def main(inputfile, outputdir): read_file = open(inputfile,"r") lines_read = read_file.readlines() read_file.close() filename = inputfile.split('/')[-1] page_id = filename.split('.')[0] lines_to_write = [] try: header = lines_read[0] header_items = header.spl...
0.134747
0.144541
import discord from discord.ext import commands import json import urllib.request import random answers = [] tokenID = "" amounts = {} userAnswers = {} class TriviaCog(commands.Cog): """ Commands for the Trivia Questions """ def __init__(self, bot): self.bot = bot # This batch of comma...
bot/cogs/trivia.py
import discord from discord.ext import commands import json import urllib.request import random answers = [] tokenID = "" amounts = {} userAnswers = {} class TriviaCog(commands.Cog): """ Commands for the Trivia Questions """ def __init__(self, bot): self.bot = bot # This batch of comma...
0.436142
0.231766
import pytest import requests from collections import OrderedDict from rainman2.utils import exceptions from rainman2.lib.environment.cellular.dev import client __author__ = '<NAME> (<EMAIL>)' __date__ = 'Thursday, April 5th 2018, 10:58:40 am' CELLULAR_DEV_CONFIG = OrderedDict( NAME='Cellular', TYPE='Dev', ...
tests/unit_tests/cellular/test_cellular_dev_client.py
import pytest import requests from collections import OrderedDict from rainman2.utils import exceptions from rainman2.lib.environment.cellular.dev import client __author__ = '<NAME> (<EMAIL>)' __date__ = 'Thursday, April 5th 2018, 10:58:40 am' CELLULAR_DEV_CONFIG = OrderedDict( NAME='Cellular', TYPE='Dev', ...
0.321993
0.237886
from marshmallow import fields from ...models.base_record import BaseRecord, BaseRecordSchema class PresentationExchange(BaseRecord): """Represents a presentation exchange.""" class Meta: """PresentationExchange metadata.""" schema_class = "PresentationExchangeSchema" RECORD_TYPE = "p...
aries_cloudagent/messaging/presentations/models/presentation_exchange.py
from marshmallow import fields from ...models.base_record import BaseRecord, BaseRecordSchema class PresentationExchange(BaseRecord): """Represents a presentation exchange.""" class Meta: """PresentationExchange metadata.""" schema_class = "PresentationExchangeSchema" RECORD_TYPE = "p...
0.8874
0.125146
import pprint import re # noqa: F401 import six class UserSettingsObject(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name a...
syntropy_sdk/models/user_settings_object.py
import pprint import re # noqa: F401 import six class UserSettingsObject(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name a...
0.622918
0.202838
""" This is a developers tool used for developing libraries and subsystems for BBc-1 (Beyond Blockchain One), before making these pip-installable. This tool copies source files being developed onto the core source code tree. """ import argparse import os import subprocess DIRS = ['bbc1', 'examples', 'lib', 'tests', 'u...
devmerge.py
""" This is a developers tool used for developing libraries and subsystems for BBc-1 (Beyond Blockchain One), before making these pip-installable. This tool copies source files being developed onto the core source code tree. """ import argparse import os import subprocess DIRS = ['bbc1', 'examples', 'lib', 'tests', 'u...
0.399694
0.338077
import argparse import json import logging import os import re from datetime import datetime from datetime import timedelta from babel import Locale from babel.core import UnknownLocaleError from googleapiclient import discovery from googleapiclient.http import build_http from googleapiclient.errors import HttpError ...
api.py
import argparse import json import logging import os import re from datetime import datetime from datetime import timedelta from babel import Locale from babel.core import UnknownLocaleError from googleapiclient import discovery from googleapiclient.http import build_http from googleapiclient.errors import HttpError ...
0.300951
0.075483
import os from rich.text import Text def read_adventure(adventure_file, console, game_window): import TRPG f = open(("Adventures/" + adventure_file + ".txt"), mode="r") lines = f.readlines() lines = "".join(lines) lines = lines.split("*encounter*:")[1:] encounters = {} for encounter_in...
Adventures/adventures.py
import os from rich.text import Text def read_adventure(adventure_file, console, game_window): import TRPG f = open(("Adventures/" + adventure_file + ".txt"), mode="r") lines = f.readlines() lines = "".join(lines) lines = lines.split("*encounter*:")[1:] encounters = {} for encounter_in...
0.181191
0.080321
import grpc from feast.core import CoreService_pb2 as feast_dot_core_dot_CoreService__pb2 from feast.specs import EntitySpec_pb2 as feast_dot_specs_dot_EntitySpec__pb2 from feast.specs import FeatureGroupSpec_pb2 as feast_dot_specs_dot_FeatureGroupSpec__pb2 from feast.specs import FeatureSpec_pb2 as feast_dot_specs_do...
sdk/python/feast/core/CoreService_pb2_grpc.py
import grpc from feast.core import CoreService_pb2 as feast_dot_core_dot_CoreService__pb2 from feast.specs import EntitySpec_pb2 as feast_dot_specs_dot_EntitySpec__pb2 from feast.specs import FeatureGroupSpec_pb2 as feast_dot_specs_dot_FeatureGroupSpec__pb2 from feast.specs import FeatureSpec_pb2 as feast_dot_specs_do...
0.623492
0.073364
import os import datetime import logging import json import uuid from installed_clients.WorkspaceClient import Workspace as Workspace from installed_clients.KBaseReportClient import KBaseReport from installed_clients.annotation_ontology_apiServiceClient import annotation_ontology_api import MergeMetabolicAnnotations....
lib/MergeMetabolicAnnotations/utils/ImportAnnotationsUtil.py
import os import datetime import logging import json import uuid from installed_clients.WorkspaceClient import Workspace as Workspace from installed_clients.KBaseReportClient import KBaseReport from installed_clients.annotation_ontology_apiServiceClient import annotation_ontology_api import MergeMetabolicAnnotations....
0.447219
0.078078
import pytest from pyomo.environ import ConcreteModel, Var, Constraint from idaes.core.solvers import get_solver from watertap.core.util.infeasible import ( print_infeasible_constraints, print_infeasible_bounds, print_variables_close_to_bounds, print_constraints_close_to_bounds, print_close_to_boun...
watertap/core/util/tests/test_infeasible.py
import pytest from pyomo.environ import ConcreteModel, Var, Constraint from idaes.core.solvers import get_solver from watertap.core.util.infeasible import ( print_infeasible_constraints, print_infeasible_bounds, print_variables_close_to_bounds, print_constraints_close_to_bounds, print_close_to_boun...
0.451327
0.518851
import numpy as np from .. import Fourier from .. import LombScargle from .. import CrossPhase def Spectrogram(t,v,wind,slip,Method='FFT',**kwargs): ''' Creates a spectogram using a sliding window. Inputs ====== t : time array in seconds v : array of values the same length as t. If using crossphase, this ...
wavespec/Spectrogram/Spectrogram.py
import numpy as np from .. import Fourier from .. import LombScargle from .. import CrossPhase def Spectrogram(t,v,wind,slip,Method='FFT',**kwargs): ''' Creates a spectogram using a sliding window. Inputs ====== t : time array in seconds v : array of values the same length as t. If using crossphase, this ...
0.560012
0.716355
from collections import namedtuple from DaPy.core import is_math, is_seq, is_str from DaPy.core import SeriesSet from DaPy.operation import get_ranks from .distribution import Fcdf, Ncdf from math import sqrt __all__ = ['ANOVA'] ANOVA_result = namedtuple('one_way_ANOVA_Result', ['F', 'pvalue']) MoodTestResult = named...
DaPy/methods/statistic/compare_scaler.py
from collections import namedtuple from DaPy.core import is_math, is_seq, is_str from DaPy.core import SeriesSet from DaPy.operation import get_ranks from .distribution import Fcdf, Ncdf from math import sqrt __all__ = ['ANOVA'] ANOVA_result = namedtuple('one_way_ANOVA_Result', ['F', 'pvalue']) MoodTestResult = named...
0.789518
0.672775
import copy import datetime import graphviz import logging import numpy as np import os import sys import pandas as pd from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import GradientBoostingClassifi...
code/confussionGivenFile.py
import copy import datetime import graphviz import logging import numpy as np import os import sys import pandas as pd from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import GradientBoostingClassifi...
0.303422
0.192084
from OpenGL.GL import * from math import * import os import pygame from Ship import Ship from GLText import GLText SQRT_3 = sqrt(3.0) SQRT_3_2 = SQRT_3 * 2 HEX_M = 1 / SQRT_3 class World(object): """ The world class represents and draws a Hexagon-Based Tile Map. Origo is bottom left. Hex Dimens...
World.py
from OpenGL.GL import * from math import * import os import pygame from Ship import Ship from GLText import GLText SQRT_3 = sqrt(3.0) SQRT_3_2 = SQRT_3 * 2 HEX_M = 1 / SQRT_3 class World(object): """ The world class represents and draws a Hexagon-Based Tile Map. Origo is bottom left. Hex Dimens...
0.691185
0.284116
from vedo.shapes import Cylinder import yaml import brainrender from loguru import logger from probeplanner.probe import Probe from probeplanner._probe import BREGMA from probeplanner.ui import UI from probeplanner.terminal_ui import ( StructuresTree, ProbeTarget, ProbeParameters, ) from probeplanner.hiera...
probeplanner/core.py
from vedo.shapes import Cylinder import yaml import brainrender from loguru import logger from probeplanner.probe import Probe from probeplanner._probe import BREGMA from probeplanner.ui import UI from probeplanner.terminal_ui import ( StructuresTree, ProbeTarget, ProbeParameters, ) from probeplanner.hiera...
0.561696
0.274816
import pytest import shutil from argparse import Namespace from pathlib import Path import grimagents.training_wrapper from grimagents.training_wrapper import TrainingRunInfo @pytest.fixture def arguments(): return [ 'config/3DBall_config.yaml', '--env', 'builds/3DBall/3DBall.exe', ...
grimagents/tests/unit/test_training_wrapper.py
import pytest import shutil from argparse import Namespace from pathlib import Path import grimagents.training_wrapper from grimagents.training_wrapper import TrainingRunInfo @pytest.fixture def arguments(): return [ 'config/3DBall_config.yaml', '--env', 'builds/3DBall/3DBall.exe', ...
0.647687
0.527073
# 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, software # distributed under the...
pymedphys/labs/managelogfiles/orchestration.py
# 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, software # distributed under the...
0.832475
0.364891
import pytest import eagerpy as ep import numpy as np import torch import jax import tensorflow as tf from clipping_aware_rescaling import l2_clipping_aware_rescaling from naive_rescaling import l2_naive_rescaling def get_effective_norms(x, eta, delta, a, b): x, eta, delta = ep.astensors(x, eta, delta) xp = ...
test_rescaling.py
import pytest import eagerpy as ep import numpy as np import torch import jax import tensorflow as tf from clipping_aware_rescaling import l2_clipping_aware_rescaling from naive_rescaling import l2_naive_rescaling def get_effective_norms(x, eta, delta, a, b): x, eta, delta = ep.astensors(x, eta, delta) xp = ...
0.826537
0.594669
import os import sqlite3 from datetime import datetime #Создание переменных даты и времени формата DDMMYYYYHHmm current_year = str(datetime.now().year) current_month = str(datetime.now().month) current_day = str(datetime.now().day) current_hour = str(datetime.now().hour) current_minute = str(dateti...
main.py
import os import sqlite3 from datetime import datetime #Создание переменных даты и времени формата DDMMYYYYHHmm current_year = str(datetime.now().year) current_month = str(datetime.now().month) current_day = str(datetime.now().day) current_hour = str(datetime.now().hour) current_minute = str(dateti...
0.036735
0.310498
import arcpy import sys, os #--------------------------------------------------------------------------------------------- # 1. Get parameters from the toolbox using 'GetParametersAsText' method # --> check ArcGIS help for info how to use methods # Method info: http://resources.arcgis.com/en/help/main/10.2/index.h...
source/codes/Arcpy_3_SpeciesPoly2Raster_Iterate.py
import arcpy import sys, os #--------------------------------------------------------------------------------------------- # 1. Get parameters from the toolbox using 'GetParametersAsText' method # --> check ArcGIS help for info how to use methods # Method info: http://resources.arcgis.com/en/help/main/10.2/index.h...
0.452052
0.219567
import datetime from django.contrib import admin from django.http import HttpResponseRedirect from django.shortcuts import render from djmoney.money import Money from behind import settings from payments.models import Payment, STATUS, AUTHORITY from purchases.models import Purchase, STATE from users.forms import Conf...
behind/users/admin.py
import datetime from django.contrib import admin from django.http import HttpResponseRedirect from django.shortcuts import render from djmoney.money import Money from behind import settings from payments.models import Payment, STATUS, AUTHORITY from purchases.models import Purchase, STATE from users.forms import Conf...
0.351089
0.091951
from osmexit import common from osmexit.result import ( Result, JointResult, UNKNOWN, SUCCESS, AMBIGUOUS, CONFLICT, ) def assign_exits(node, way_in, ways_out): algos = { 'noref': noref, 'basic': basic_junction, 'left_right': left_right_junction, 'junction_ref': junction_ref, ...
osmexit/exits.py
from osmexit import common from osmexit.result import ( Result, JointResult, UNKNOWN, SUCCESS, AMBIGUOUS, CONFLICT, ) def assign_exits(node, way_in, ways_out): algos = { 'noref': noref, 'basic': basic_junction, 'left_right': left_right_junction, 'junction_ref': junction_ref, ...
0.489748
0.332757
import pickle from konlpy.tag import Okt from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing.sequence import pad_sequences okt = Okt() stopwords = ['의', '가', '이', '은', '들', '는', '좀', '잘', '걍', '과', '도', '를', '으로', '자', '에', '와', '한', '하다'] max_len = 40 with open('tokenizer.pickle', 'rb')...
main.py
import pickle from konlpy.tag import Okt from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing.sequence import pad_sequences okt = Okt() stopwords = ['의', '가', '이', '은', '들', '는', '좀', '잘', '걍', '과', '도', '를', '으로', '자', '에', '와', '한', '하다'] max_len = 40 with open('tokenizer.pickle', 'rb')...
0.344774
0.275233
import numpy as np import tensorflow as tf from keras import backend as K from keras.layers import Input, Lambda, Conv2D from keras.models import load_model, Model from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping, CSVLogger from .keras_yolo import preprocess_true_boxes, yolo_body, yolo_eval, yolo...
repos/yolo/trainer.py
import numpy as np import tensorflow as tf from keras import backend as K from keras.layers import Input, Lambda, Conv2D from keras.models import load_model, Model from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping, CSVLogger from .keras_yolo import preprocess_true_boxes, yolo_body, yolo_eval, yolo...
0.617628
0.307339
import sys import numpy as np import math fname = sys.argv[1] quantums = [] with open(fname) as f: content = f.readlines() content = [x.strip() for x in content] count = 0 is_quantum = False quantum = [] for line in content: if line.startswith("-----------"): quantum.append(line) is_quantum ...
benchmarks/SimResults/combinations_spec_ml/avarageBigSmallIpcParser.py
import sys import numpy as np import math fname = sys.argv[1] quantums = [] with open(fname) as f: content = f.readlines() content = [x.strip() for x in content] count = 0 is_quantum = False quantum = [] for line in content: if line.startswith("-----------"): quantum.append(line) is_quantum ...
0.117673
0.286058
from pyomo.environ import * model = m = ConcreteModel() m.b1 = Var(within=Binary, bounds=(0,1), initialize=0) m.b2 = Var(within=Binary, bounds=(0,1), initialize=0) m.b3 = Var(within=Binary, bounds=(0,1), initialize=0) m.b4 = Var(within=Binary, bounds=(0,1), initialize=0) m.b5 = Var(within=Binary, bounds=(0,1), initi...
models_all_solvable2/p_ball_30b_10p_2d_h.py
from pyomo.environ import * model = m = ConcreteModel() m.b1 = Var(within=Binary, bounds=(0,1), initialize=0) m.b2 = Var(within=Binary, bounds=(0,1), initialize=0) m.b3 = Var(within=Binary, bounds=(0,1), initialize=0) m.b4 = Var(within=Binary, bounds=(0,1), initialize=0) m.b5 = Var(within=Binary, bounds=(0,1), initi...
0.7237
0.231386
import logging from os.path import expanduser, join from hdx.facades.simple import facade from hdx.api.configuration import Configuration from hdx.utilities.downloader import Download from hdx.utilities.path import progress_storing_folder, wheretostart_tempdir_batch from faostat import download_indicatorsets, generat...
run.py
import logging from os.path import expanduser, join from hdx.facades.simple import facade from hdx.api.configuration import Configuration from hdx.utilities.downloader import Download from hdx.utilities.path import progress_storing_folder, wheretostart_tempdir_batch from faostat import download_indicatorsets, generat...
0.346099
0.180035
from typing import List import numpy as np class DasDennis: """Class implementing the Das-Dennis method to generate a set of uniformly-spaced weight vectors. The method is described in: <NAME> and <NAME>. Normal-boundary intersection: a new method for generating the pareto surface in nonlinear multicrit...
das_dennis.py
from typing import List import numpy as np class DasDennis: """Class implementing the Das-Dennis method to generate a set of uniformly-spaced weight vectors. The method is described in: <NAME> and <NAME>. Normal-boundary intersection: a new method for generating the pareto surface in nonlinear multicrit...
0.915757
0.591104
from django.conf import settings from django.db import models from django.urls import reverse from django.utils.functional import cached_property from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from django_countries.fields import CountryField from martor.models import Marto...
writing/models.py
from django.conf import settings from django.db import models from django.urls import reverse from django.utils.functional import cached_property from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from django_countries.fields import CountryField from martor.models import Marto...
0.50293
0.091463
from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import datetime, time, requests import Configuration as cfg import home.SQLTabHome as SQLTabHome import home.FBTabHome as FBTabHome import home.CustomMessageMgmt as CustomMessageMgmt class TabHome(QWidget): def __init__(self, tray...
gymms_desktop/home/TabHome.py
from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import datetime, time, requests import Configuration as cfg import home.SQLTabHome as SQLTabHome import home.FBTabHome as FBTabHome import home.CustomMessageMgmt as CustomMessageMgmt class TabHome(QWidget): def __init__(self, tray...
0.341692
0.123418
import json import logging import requests import salt.config __opts__ = salt.config.minion_config("/etc/salt/minion") __salt__ = salt.loader.minion_mods(__opts__) log = logging.getLogger(__name__) base_api_path = 'service/rest' # TODO: revisit the error handling def _get_config(): ''' Gets configuration ...
_utils/nexus3.py
import json import logging import requests import salt.config __opts__ = salt.config.minion_config("/etc/salt/minion") __salt__ = salt.loader.minion_mods(__opts__) log = logging.getLogger(__name__) base_api_path = 'service/rest' # TODO: revisit the error handling def _get_config(): ''' Gets configuration ...
0.160167
0.052473
from forge.match import ( compile, match, many, opt, when, choice, one, delay, lazy, trait, MatchError ) class Action(object): def __init__(self, label): self.label = label self.args = None def __call__(self, *args): self.args = args return self def __repr__(self): ...
forge/tests/test_match.py
from forge.match import ( compile, match, many, opt, when, choice, one, delay, lazy, trait, MatchError ) class Action(object): def __init__(self, label): self.label = label self.args = None def __call__(self, *args): self.args = args return self def __repr__(self): ...
0.617513
0.535281
from __future__ import annotations import textwrap from contextlib import contextmanager from typing import ( TYPE_CHECKING, Any, Iterable, List, Optional, ) import numpy as np from bokeh.document import Document from bokeh.document.events import ( ColumnDataChangedEvent, DocumentPatchedEvent, ModelChangedE...
panel/io/model.py
from __future__ import annotations import textwrap from contextlib import contextmanager from typing import ( TYPE_CHECKING, Any, Iterable, List, Optional, ) import numpy as np from bokeh.document import Document from bokeh.document.events import ( ColumnDataChangedEvent, DocumentPatchedEvent, ModelChangedE...
0.807043
0.338596
from django.db import models from core.models import TimeStampedModel, Active from restaurants.models import Restaurant class Category(TimeStampedModel, Active): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) name = models.CharField("Categoria", max_length=50) description = models.T...
products/models.py
from django.db import models from core.models import TimeStampedModel, Active from restaurants.models import Restaurant class Category(TimeStampedModel, Active): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) name = models.CharField("Categoria", max_length=50) description = models.T...
0.671794
0.169166
import scrapy import re from ..items import LaptopItem from scrapy_selenium import SeleniumRequest from selenium import webdriver from scrapy.utils.project import get_project_settings class TikiSpider(scrapy.Spider): name = 'tiki' allowed_domains = ['tiki.vn'] start_urls = ['https://tiki.vn/may-tinh-xach-...
laptop/spiders/tiki.py
import scrapy import re from ..items import LaptopItem from scrapy_selenium import SeleniumRequest from selenium import webdriver from scrapy.utils.project import get_project_settings class TikiSpider(scrapy.Spider): name = 'tiki' allowed_domains = ['tiki.vn'] start_urls = ['https://tiki.vn/may-tinh-xach-...
0.105475
0.068725
import tvm import numpy as np from tvm.relay.ir_pass import infer_type from tvm import relay def test_monomorphic_let(): "Program: let x = 1; return x" sb = relay.ScopeBuilder() x = sb.let('x', relay.const(1.0, "float64")) sb.ret(x) xchecked = relay.ir_pass.infer_type(sb.get()) assert xchecked...
tests/python/relay/test_type_infer.py
import tvm import numpy as np from tvm.relay.ir_pass import infer_type from tvm import relay def test_monomorphic_let(): "Program: let x = 1; return x" sb = relay.ScopeBuilder() x = sb.let('x', relay.const(1.0, "float64")) sb.ret(x) xchecked = relay.ir_pass.infer_type(sb.get()) assert xchecked...
0.607081
0.537648
from . import core # noqa: F401 from . import io from . import utils import cement import copy import obj_tables import os import os.path import sys import types # noqa: F401 DEFAULT_WRITER_ARGS = { 'write_empty_models': False, 'write_empty_cols': False, } DEFAULT_READER_ARGS = { 'allow_multiple_sheets_...
obj_tables/__main__.py
from . import core # noqa: F401 from . import io from . import utils import cement import copy import obj_tables import os import os.path import sys import types # noqa: F401 DEFAULT_WRITER_ARGS = { 'write_empty_models': False, 'write_empty_cols': False, } DEFAULT_READER_ARGS = { 'allow_multiple_sheets_...
0.384797
0.160759
from decimal import Decimal from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_raises_rpc_error, ) from test_framework.blocktools import ( TIME_GENESIS_BLOCK, ) class CreateTxWalletTest(BitcoinTestFramework): def set_test_params(self...
test/functional/wallet_create_tx.py
from decimal import Decimal from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_raises_rpc_error, ) from test_framework.blocktools import ( TIME_GENESIS_BLOCK, ) class CreateTxWalletTest(BitcoinTestFramework): def set_test_params(self...
0.803135
0.465023
from decimal import Decimal from .apitask import APITask from thing.models import Character, CorporationStanding, Faction, FactionStanding class Standings(APITask): name = 'thing.standings' def run(self, url, taskstate_id, apikey_id, character_id): if self.init(taskstate_id, apikey_id) is False: ...
thing/tasks/standings.py
from decimal import Decimal from .apitask import APITask from thing.models import Character, CorporationStanding, Faction, FactionStanding class Standings(APITask): name = 'thing.standings' def run(self, url, taskstate_id, apikey_id, character_id): if self.init(taskstate_id, apikey_id) is False: ...
0.474875
0.112795
import tensorflow as tf import argparse import os import json import wandb import logging import math import yaml from datetime import datetime from wandb.keras import WandbCallback from regnety.models.model import RegNetY from regnety.dataset.imagenet import ImageNet from regnety.utils import train_utils as tutil fr...
regnety/train.py
import tensorflow as tf import argparse import os import json import wandb import logging import math import yaml from datetime import datetime from wandb.keras import WandbCallback from regnety.models.model import RegNetY from regnety.dataset.imagenet import ImageNet from regnety.utils import train_utils as tutil fr...
0.415254
0.098123
import contextlib def read_value(): """Reads a line as a single integer.""" return int(input()) def read_record(): """Reads a line as a record of integers.""" return map(int, input().split()) def read_row(width): """Reads a grid row of the specific width.""" row = list(input().strip()) ...
main/count-luck/count-luck.py
import contextlib def read_value(): """Reads a line as a single integer.""" return int(input()) def read_record(): """Reads a line as a record of integers.""" return map(int, input().split()) def read_row(width): """Reads a grid row of the specific width.""" row = list(input().strip()) ...
0.831451
0.702519
from mcc.graph import Edge class EventModel: pass class PJEventModel(EventModel): def __init__(self, P, J=0): super().__init__() self.P = P self.J = J def __repr__(self): return 'P=%d, J=%d' % (self.P, self.J) class InEventModel(EventModel): def __init__(self, name)...
mcc/taskmodel.py
from mcc.graph import Edge class EventModel: pass class PJEventModel(EventModel): def __init__(self, P, J=0): super().__init__() self.P = P self.J = J def __repr__(self): return 'P=%d, J=%d' % (self.P, self.J) class InEventModel(EventModel): def __init__(self, name)...
0.778018
0.316
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Account', ...
apps/accounts/migrations/0001_initial.py
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Account', ...
0.586404
0.115112
import socket import itertools from types import FunctionType from typing import Tuple import inspect import ray import numpy as np from nums.core.systems.interfaces import ComputeInterface, ComputeImp from nums.core.systems.utils import check_implementation, extract_functions class RayScheduler(ComputeInterface)...
nums/core/systems/schedulers.py
import socket import itertools from types import FunctionType from typing import Tuple import inspect import ray import numpy as np from nums.core.systems.interfaces import ComputeInterface, ComputeImp from nums.core.systems.utils import check_implementation, extract_functions class RayScheduler(ComputeInterface)...
0.748352
0.25548
import os import sys import argparse import numpy as np ## Pytorch modules. import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim fruit_names = [ 'Apple Braeburn', 'Apple Golden 1', 'Apple Golden 2', 'Apple Golden 3', 'Apple Granny Smith', 'Apple Red 1'...
fruit-classification/fruit_classification.py
import os import sys import argparse import numpy as np ## Pytorch modules. import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim fruit_names = [ 'Apple Braeburn', 'Apple Golden 1', 'Apple Golden 2', 'Apple Golden 3', 'Apple Granny Smith', 'Apple Red 1'...
0.64713
0.381508
from __future__ import print_function import pytest import uuid from mlt.commands.events import EventsCommand from test_utils.io import catch_stdout @pytest.fixture def json_mock(patch): return patch('json') @pytest.fixture def open_mock(patch): return patch('open') @pytest.fixture def os_path_mock(patch)...
tests/unit/commands/test_events.py
from __future__ import print_function import pytest import uuid from mlt.commands.events import EventsCommand from test_utils.io import catch_stdout @pytest.fixture def json_mock(patch): return patch('json') @pytest.fixture def open_mock(patch): return patch('open') @pytest.fixture def os_path_mock(patch)...
0.559771
0.177561
import numpy as np def kashin_representation(x, u, eta=0.4, delta=0.8): """Computes the kashin representation of x.""" (kashin_n, _) = u.shape a = np.zeros((kashin_n, 1)) k = 1 / ((1 - eta) * np.sqrt(delta)) # Set kashin level to be k m = eta / np.sqrt(delta * kashin_n) y = x itr = int(np.log(kashin_...
rcc_dp/sqkr.py
import numpy as np def kashin_representation(x, u, eta=0.4, delta=0.8): """Computes the kashin representation of x.""" (kashin_n, _) = u.shape a = np.zeros((kashin_n, 1)) k = 1 / ((1 - eta) * np.sqrt(delta)) # Set kashin level to be k m = eta / np.sqrt(delta * kashin_n) y = x itr = int(np.log(kashin_...
0.916115
0.579936
from django import template from django.utils.safestring import SafeString from django.utils.html import escape register = template.Library() def enum_key(enum, value): for key in enum.__dict__: if value == getattr(enum, key): return key return '?' @register.filter def instance_status(v...
master_django/intensity/templatetags/intensity_tags.py
from django import template from django.utils.safestring import SafeString from django.utils.html import escape register = template.Library() def enum_key(enum, value): for key in enum.__dict__: if value == getattr(enum, key): return key return '?' @register.filter def instance_status(v...
0.503662
0.164349
import os import glob import pandas as pd from selenium import webdriver import time import copy import warnings warnings.filterwarnings('ignore') import pickle def save_obj(obj, path ): with open(path, 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) def load_obj(path ): with open(p...
broadcom_scraper.py
import os import glob import pandas as pd from selenium import webdriver import time import copy import warnings warnings.filterwarnings('ignore') import pickle def save_obj(obj, path ): with open(path, 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) def load_obj(path ): with open(p...
0.18396
0.097433
from django.test import TestCase from apps.log_databus.exceptions import CleanTemplateRepeatException, CleanTemplateNotExistException from apps.log_databus.handlers.clean import CleanTemplateHandler from apps.tests.log_databus.test_clean import TestClean CREATE_PARAMS = { "name": "test", "clean_type": "bk_log...
apps/tests/log_databus/test_clean_template.py
from django.test import TestCase from apps.log_databus.exceptions import CleanTemplateRepeatException, CleanTemplateNotExistException from apps.log_databus.handlers.clean import CleanTemplateHandler from apps.tests.log_databus.test_clean import TestClean CREATE_PARAMS = { "name": "test", "clean_type": "bk_log...
0.385953
0.316911
import logging from asyncio import run from concurrent.futures import ThreadPoolExecutor from time import time from typing import Dict, List, Iterable from uuid import uuid4 import grpc from sage.database.core.dataset import Dataset from sage.database.core.graph import Graph from sage.database.core.yaml_config import...
sage/grpc/grpc_server.py
import logging from asyncio import run from concurrent.futures import ThreadPoolExecutor from time import time from typing import Dict, List, Iterable from uuid import uuid4 import grpc from sage.database.core.dataset import Dataset from sage.database.core.graph import Graph from sage.database.core.yaml_config import...
0.822581
0.149593
import numpy as np import cv2 settings = { 'Read': { 'interpolation_method' : cv2.INTER_CUBIC, 'interpolation_k' : 2.5, 'colors' : { # Colors are [RGB_min,RGB_max,HSV_min,HSV_max] ...
Settings.py
import numpy as np import cv2 settings = { 'Read': { 'interpolation_method' : cv2.INTER_CUBIC, 'interpolation_k' : 2.5, 'colors' : { # Colors are [RGB_min,RGB_max,HSV_min,HSV_max] ...
0.30767
0.135775
import functools import os from celery.utils.log import get_task_logger from celery import shared_task from django.conf import settings from django.core.mail import mail_admins, send_mail from django.db.models import signals from django.db import transaction from django.dispatch import receiver from django.urls import...
locuszoom_plotting_service/taskapp/tasks.py
import functools import os from celery.utils.log import get_task_logger from celery import shared_task from django.conf import settings from django.core.mail import mail_admins, send_mail from django.db.models import signals from django.db import transaction from django.dispatch import receiver from django.urls import...
0.362743
0.144692
"""Test discover_commands.py.""" from pathlib import Path import typing as t import uuid import pytest from slipbox.discover_commands import discover_commands as discover def custom_cli_file() -> str: """Generate custom CLI file.""" return f"slipbox_cli_{uuid.uuid4().hex}.py" def test_discover_with_no_cus...
tests/test_discover_commands.py
"""Test discover_commands.py.""" from pathlib import Path import typing as t import uuid import pytest from slipbox.discover_commands import discover_commands as discover def custom_cli_file() -> str: """Generate custom CLI file.""" return f"slipbox_cli_{uuid.uuid4().hex}.py" def test_discover_with_no_cus...
0.786869
0.495911
import pytest from url2tree import url2tree @pytest.fixture def randomUrlData(): # TODO : Add faker for random url test from faker import Faker fake = Faker() domain = fake.url() url_logs = [(domain + fake.uri_path(), 1) for _ in range(100)] while True: domain2 = fake.url() i...
tests/test_url2tree.py
import pytest from url2tree import url2tree @pytest.fixture def randomUrlData(): # TODO : Add faker for random url test from faker import Faker fake = Faker() domain = fake.url() url_logs = [(domain + fake.uri_path(), 1) for _ in range(100)] while True: domain2 = fake.url() i...
0.22093
0.470676
from flask import Blueprint from flasgger import swag_from from .api_utils import validate_asns, validate_policies, format_json, dictify __author__ = "<NAME>" __credits__ = ["<NAME>"] __Lisence__ = "BSD" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" policies_app = Blueprint("policies_app...
lib_bgp_data/forecast/api/policies.py
from flask import Blueprint from flasgger import swag_from from .api_utils import validate_asns, validate_policies, format_json, dictify __author__ = "<NAME>" __credits__ = ["<NAME>"] __Lisence__ = "BSD" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" policies_app = Blueprint("policies_app...
0.796649
0.252753
"""Unit tests for the processes module.""" import unittest import mock from apache_beam.utils import processes class Exec(unittest.TestCase): def setUp(self): pass @mock.patch('apache_beam.utils.processes.subprocess') def test_method_forwarding_not_windows(self, *unused_mocks): # Test that the corr...
sdks/python/apache_beam/utils/processes_test.py
"""Unit tests for the processes module.""" import unittest import mock from apache_beam.utils import processes class Exec(unittest.TestCase): def setUp(self): pass @mock.patch('apache_beam.utils.processes.subprocess') def test_method_forwarding_not_windows(self, *unused_mocks): # Test that the corr...
0.807764
0.501038
import sys import urllib2 from bs4 import BeautifulSoup, Comment dokuwikipageid = "start" attributes = ["id", "class"] def getExportFromWiki(): dokuwikipageid = sys.argv[-1] url = "http://wiki.local/doku.php?id=" + dokuwikipageid + "&do=export_xhtmlbody" response = urllib2.urlopen(url) html = response...
DokuwikiToConfluence.py
import sys import urllib2 from bs4 import BeautifulSoup, Comment dokuwikipageid = "start" attributes = ["id", "class"] def getExportFromWiki(): dokuwikipageid = sys.argv[-1] url = "http://wiki.local/doku.php?id=" + dokuwikipageid + "&do=export_xhtmlbody" response = urllib2.urlopen(url) html = response...
0.203075
0.062674
__author__ = '<NAME>' from datetime import datetime import requests import turtle import time def main(): r = requests.get("http://api.open-notify.org/astros.json").json() print(f'There are {r.get("number")} astronauts on the ISS.') print(f'Their names are: \n') for names in r.get("people"): ...
iss.py
__author__ = '<NAME>' from datetime import datetime import requests import turtle import time def main(): r = requests.get("http://api.open-notify.org/astros.json").json() print(f'There are {r.get("number")} astronauts on the ISS.') print(f'Their names are: \n') for names in r.get("people"): ...
0.178777
0.13288
import numpy as np def line_area_intersection(l_src, l_tar): """ calculate the overlapping area :param l_src: gt(N) :param l_tar: est(1) :return: est-> overlapping area to each gt """ N =len(l_src) idx_valid = [False for i in range(N)] pd_covered = np.zeros(N) vec_base = l_src[:...
Metrics/LAP/lib/line_intersection.py
import numpy as np def line_area_intersection(l_src, l_tar): """ calculate the overlapping area :param l_src: gt(N) :param l_tar: est(1) :return: est-> overlapping area to each gt """ N =len(l_src) idx_valid = [False for i in range(N)] pd_covered = np.zeros(N) vec_base = l_src[:...
0.355775
0.510192
import warnings import sunpy.net.attrs as a from sunpy.net.attr import AttrAnd, AttrOr, AttrWalker, DataAttr, SimpleAttr from sunpy.util.exceptions import SunpyDeprecationWarning __all__ = ['Product'] class Product(SimpleAttr): """ The data product identifier to search for. """ class Identifier(Produc...
sunpy_soar/attrs.py
import warnings import sunpy.net.attrs as a from sunpy.net.attr import AttrAnd, AttrOr, AttrWalker, DataAttr, SimpleAttr from sunpy.util.exceptions import SunpyDeprecationWarning __all__ = ['Product'] class Product(SimpleAttr): """ The data product identifier to search for. """ class Identifier(Produc...
0.72331
0.473718
import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))) from daliMasterRPI import daliMaster, defines master = daliMaster.daliMaster() masterAddress = defines.LW14_I2C_ADDRESS if len(sys.argv) > 1 : masterAddress = sys.argv[1] if master.begin(masterAd...
examples/shellControl/shellControl.py
import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))) from daliMasterRPI import daliMaster, defines master = daliMaster.daliMaster() masterAddress = defines.LW14_I2C_ADDRESS if len(sys.argv) > 1 : masterAddress = sys.argv[1] if master.begin(masterAd...
0.124399
0.203965
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.patches import Ellipse import string def corrplot(data, pvalues, labels): """Creates a correlation plot of the passed data. The function returns the plot which can then be shown with plot.show(), saved to a file ...
utils/corrplot.py
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.patches import Ellipse import string def corrplot(data, pvalues, labels): """Creates a correlation plot of the passed data. The function returns the plot which can then be shown with plot.show(), saved to a file ...
0.793946
0.8156
from django.db import models from django import forms from .backend import Factory import datetime class Category(models.Model): '''Category whre all items are included''' name = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=400) def __str__(self): return self.name clas...
stock/models.py
from django.db import models from django import forms from .backend import Factory import datetime class Category(models.Model): '''Category whre all items are included''' name = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=400) def __str__(self): return self.name clas...
0.516595
0.076064
import gym import numpy as np import pandas as pd import random import matplotlib import torch as T import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from gym_pybullet_drones.envs.single_agent_rl.TakeoffAviary import TakeoffAviary from gym_pybullet_drones.envs.single_agent_rl.HoverAviar...
experiments/learning/test_ddpg.py
import gym import numpy as np import pandas as pd import random import matplotlib import torch as T import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from gym_pybullet_drones.envs.single_agent_rl.TakeoffAviary import TakeoffAviary from gym_pybullet_drones.envs.single_agent_rl.HoverAviar...
0.914495
0.430028
import abc import logging import os import warnings from typing import Dict, Any import six.moves.urllib_parse as urlparse import requests from .exceptions import InvalidTokenError from .exceptions import UnknownAuthenticationScheme from .exceptions import ImmutaCredentialsError class AuthScheme(object): __meta...
fh_immuta_utils/authenticate.py
import abc import logging import os import warnings from typing import Dict, Any import six.moves.urllib_parse as urlparse import requests from .exceptions import InvalidTokenError from .exceptions import UnknownAuthenticationScheme from .exceptions import ImmutaCredentialsError class AuthScheme(object): __meta...
0.745584
0.06666
from typing import Optional import logging from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT, FigureCanvasQTAgg from matplotlib.figure import Figure from matplotlib.axes import Axes from matplotlib.widgets import SpanSelector from .processingwindow import ProcessingWindow from .merging_ui import Ui_...
cct/qtgui2/processingmain/merging.py
from typing import Optional import logging from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT, FigureCanvasQTAgg from matplotlib.figure import Figure from matplotlib.axes import Axes from matplotlib.widgets import SpanSelector from .processingwindow import ProcessingWindow from .merging_ui import Ui_...
0.666388
0.157105
import urllib from typing import Optional import re import markdown from markdown.inlinepatterns import LinkInlineProcessor, LINK_RE, ImageReferenceInlineProcessor, IMAGE_REFERENCE_RE, IMAGE_LINK_RE, ImageInlineProcessor from urllib.parse import urlparse from django.core.exceptions import ValidationError from django.c...
library/my_md.py
import urllib from typing import Optional import re import markdown from markdown.inlinepatterns import LinkInlineProcessor, LINK_RE, ImageReferenceInlineProcessor, IMAGE_REFERENCE_RE, IMAGE_LINK_RE, ImageInlineProcessor from urllib.parse import urlparse from django.core.exceptions import ValidationError from django.c...
0.586049
0.108283
import unittest from datetime import datetime from datetime import timedelta from programy.services.library.base import PythonAPIService from programy.services.library.base import PythonAPIServiceException from programy.services.config import ServiceConfiguration class PythonAPIServiceExceptionTests(unittest.TestCase...
test/programytest/services/library/test_base.py
import unittest from datetime import datetime from datetime import timedelta from programy.services.library.base import PythonAPIService from programy.services.library.base import PythonAPIServiceException from programy.services.config import ServiceConfiguration class PythonAPIServiceExceptionTests(unittest.TestCase...
0.696371
0.441793
# pylint: disable=invalid-name # pylint: disable=no-else-return import re from logging import getLogger from ggrc.maintenance import maintenance_app from ggrc import db from ggrc import migrate from ggrc import settings from ggrc.models.maintenance import Maintenance from ggrc.models.maintenance import MigrationLog ...
src/ggrc/maintenance_views/maintenance.py
# pylint: disable=invalid-name # pylint: disable=no-else-return import re from logging import getLogger from ggrc.maintenance import maintenance_app from ggrc import db from ggrc import migrate from ggrc import settings from ggrc.models.maintenance import Maintenance from ggrc.models.maintenance import MigrationLog ...
0.414069
0.069637
import asyncio import json import os import random import aiowirecard async def main(): wirecard = aiowirecard.Wirecard(environment='sandbox', key=os.environ['WIRECARD_KEY'], token=os.environ['WIRECARD_TOKEN']) print('Creating customer...') customer = { "ownId"...
tests/test.py
import asyncio import json import os import random import aiowirecard async def main(): wirecard = aiowirecard.Wirecard(environment='sandbox', key=os.environ['WIRECARD_KEY'], token=os.environ['WIRECARD_TOKEN']) print('Creating customer...') customer = { "ownId"...
0.18396
0.238495
"""BitBoxBase""" from typing import Optional import serial from bitbox02 import communication from bitbox02.communication.devices import DeviceInfo from bitbox02.communication.generated import bitboxbase_pb2 as bitboxbase from bitbox02.communication.generated import hww_pb2 as hww def get_bitboxbase_default_devic...
py/bitbox02/bitbox02/bitboxbase/bitboxbase.py
"""BitBoxBase""" from typing import Optional import serial from bitbox02 import communication from bitbox02.communication.devices import DeviceInfo from bitbox02.communication.generated import bitboxbase_pb2 as bitboxbase from bitbox02.communication.generated import hww_pb2 as hww def get_bitboxbase_default_devic...
0.883494
0.117243
import ctypes import datetime import os from six.moves import winreg VALUE_CURRENT = 0 VALUE_MIN = 1 VALUE_MAX = 2 class RailDriver(object): dll = None _restypes = { 'GetControllerList': ctypes.c_char_p, 'GetLocoName': ctypes.c_char_p, 'GetControllerValue': ctypes.c_float, } ...
raildriver/library.py
import ctypes import datetime import os from six.moves import winreg VALUE_CURRENT = 0 VALUE_MIN = 1 VALUE_MAX = 2 class RailDriver(object): dll = None _restypes = { 'GetControllerList': ctypes.c_char_p, 'GetLocoName': ctypes.c_char_p, 'GetControllerValue': ctypes.c_float, } ...
0.766294
0.204998
import sys import torch from torch import nn, optim from torch.nn import functional as F from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader, Dataset from tqdm.auto import tqdm from nlptoolkit.data.utils.utils import load_sentence_polarity sys.path.append('../../') class CnnDataset(...
examples/sentence_polarity/cnn_sent_polarity.py
import sys import torch from torch import nn, optim from torch.nn import functional as F from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader, Dataset from tqdm.auto import tqdm from nlptoolkit.data.utils.utils import load_sentence_polarity sys.path.append('../../') class CnnDataset(...
0.806967
0.50177
import os import pygame class Sound(): """Load game sounds and make them available to play. This class follows the singleton design pattern. """ _instance = None _sounds = {} def __new__(cls): if cls._instance is None: cls._instance = super(Sound, cls).__new__(cls) ...
sound.py
import os import pygame class Sound(): """Load game sounds and make them available to play. This class follows the singleton design pattern. """ _instance = None _sounds = {} def __new__(cls): if cls._instance is None: cls._instance = super(Sound, cls).__new__(cls) ...
0.468791
0.174551
from rich.table import Table from rich.console import Console from io import StringIO from rich import print import pandas as pd from loguru import logger from myterial import orange, amber, pink, light_green, blue_grey_lighter from refy.authors import get_authors class Suggestions: def __init__(self, suggestio...
refy/suggestions.py
from rich.table import Table from rich.console import Console from io import StringIO from rich import print import pandas as pd from loguru import logger from myterial import orange, amber, pink, light_green, blue_grey_lighter from refy.authors import get_authors class Suggestions: def __init__(self, suggestio...
0.743541
0.386213
import numpy as np import matplotlib.pyplot as plt from matplotlib import style from scipy import linalg from scipy.stats import multivariate_normal import pyprobml_utils as pml mu_1 = np.array([[0.22], [0.45]]) mu_2 = np.array([[0.5], [0.5]]) mu_3 = np.array([[0.77], [0.55]]) Mu = np.array([mu_1, mu_2, mu_3]) Sigma1...
scripts/gmm_plot_demo.py
import numpy as np import matplotlib.pyplot as plt from matplotlib import style from scipy import linalg from scipy.stats import multivariate_normal import pyprobml_utils as pml mu_1 = np.array([[0.22], [0.45]]) mu_2 = np.array([[0.5], [0.5]]) mu_3 = np.array([[0.77], [0.55]]) Mu = np.array([mu_1, mu_2, mu_3]) Sigma1...
0.627267
0.807157
import matplotlib.pyplot as plt import numpy as np import pandas as pd from mpl_toolkits.axes_grid1 import make_axes_locatable from ...formatting import dataframe_to_string from ..binning_statistics import _check_build_parameters from ..binning_statistics import _check_is_built from ..binning_statistics import Binni...
optbinning/binning/multidimensional/binning_statistics_2d.py
import matplotlib.pyplot as plt import numpy as np import pandas as pd from mpl_toolkits.axes_grid1 import make_axes_locatable from ...formatting import dataframe_to_string from ..binning_statistics import _check_build_parameters from ..binning_statistics import _check_is_built from ..binning_statistics import Binni...
0.756358
0.819352
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from radiomanager_sdk.api_client import ApiClient class BroadcastApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually....
radiomanager_sdk/api/broadcast_api.py
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from radiomanager_sdk.api_client import ApiClient class BroadcastApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually....
0.718594
0.052912
# UPDATE: # @Time : 2020/11/24, 2020/12/29, 2020/12/17 # @Author : <NAME>, <NAME>, <NAME> # @Email : <EMAIL>, <EMAIL>, <EMAIL> """Data module which reads, processes and batches data for the whole system Attributes: dataset_register_table (dict): record all supported dataset dataset_language_map (dict): re...
crslab/data/__init__.py
# UPDATE: # @Time : 2020/11/24, 2020/12/29, 2020/12/17 # @Author : <NAME>, <NAME>, <NAME> # @Email : <EMAIL>, <EMAIL>, <EMAIL> """Data module which reads, processes and batches data for the whole system Attributes: dataset_register_table (dict): record all supported dataset dataset_language_map (dict): re...
0.784855
0.440048
from IPython.display import display, Markdown,Latex,HTML import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from pathlib import Path import _pickle as cPickle def load(stage='raw',reapply=False,input_path='../Data',input_name='oasis3'): input_file = f'{input_path}/proc...
files/preprocessing.py
from IPython.display import display, Markdown,Latex,HTML import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from pathlib import Path import _pickle as cPickle def load(stage='raw',reapply=False,input_path='../Data',input_name='oasis3'): input_file = f'{input_path}/proc...
0.385837
0.254567
from manimlib.imports import * from manimlib.mobject.svg.svg_mobject import * from manimlib.animation.indication import * from manimlib.animation.transform import * import math import manimlib.constants as consts L,U,R,D = LEFT, UP, RIGHT, DOWN class Scene1(Scene): def construct(self): integersgroup = Te...
groups.py
from manimlib.imports import * from manimlib.mobject.svg.svg_mobject import * from manimlib.animation.indication import * from manimlib.animation.transform import * import math import manimlib.constants as consts L,U,R,D = LEFT, UP, RIGHT, DOWN class Scene1(Scene): def construct(self): integersgroup = Te...
0.255529
0.320197
from django.db import models from django.utils.translation import ugettext_lazy as _ from imagekit.models import ProcessedImageField from imagekit.processors import ResizeToFill from statistics import median from datetime import datetime, timedelta, timezone class Country(models.Model): """! Countries of...
limebet/data/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from imagekit.models import ProcessedImageField from imagekit.processors import ResizeToFill from statistics import median from datetime import datetime, timedelta, timezone class Country(models.Model): """! Countries of...
0.766992
0.226891
import sys from zope.interface import provider from twisted.plugin import IPlugin from twisted.python.usage import Options from twisted.python import reflect from twisted.application.service import IServiceMaker @provider(IPlugin, IServiceMaker) class AMPoulePlugin(object): """ This plugin provides ways to cre...
twisted/plugins/ampoule_plugin.py
import sys from zope.interface import provider from twisted.plugin import IPlugin from twisted.python.usage import Options from twisted.python import reflect from twisted.application.service import IServiceMaker @provider(IPlugin, IServiceMaker) class AMPoulePlugin(object): """ This plugin provides ways to cre...
0.428951
0.210543
from unittest import TestCase import glob import os import numpy as np from ibeatles.utilities.load_data import LoadData class TestLoadData(TestCase): def setUp(self): _file_path = os.path.dirname(__file__) self.data_path = os.path.abspath(os.path.join(_file_path, '../../data/')) def test_l...
tests/ibeatles/utilities/test_load_data.py
from unittest import TestCase import glob import os import numpy as np from ibeatles.utilities.load_data import LoadData class TestLoadData(TestCase): def setUp(self): _file_path = os.path.dirname(__file__) self.data_path = os.path.abspath(os.path.join(_file_path, '../../data/')) def test_l...
0.506591
0.463262
import numpy as np import PIL.Image as pil from flask import Flask, request, redirect, url_for, render_template, json, jsonify from model import model import re import base64 import tensorflow as tf app = Flask(__name__) # Create tensorflow placeholders and load stored values from trained session x = tf.placeholder(...
digit_reader.py
import numpy as np import PIL.Image as pil from flask import Flask, request, redirect, url_for, render_template, json, jsonify from model import model import re import base64 import tensorflow as tf app = Flask(__name__) # Create tensorflow placeholders and load stored values from trained session x = tf.placeholder(...
0.63023
0.351061
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np class DataFactory(object): """singletance pattern """ __instance = None def __new__(clz, real_data=None): if not DataFactory.__instance: ...
src/system/utils.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np class DataFactory(object): """singletance pattern """ __instance = None def __new__(clz, real_data=None): if not DataFactory.__instance: ...
0.64579
0.402656
from Chunk import * from PythonEuterpea import * from GMInstruments import * from copy import deepcopy from MidiReader import * def extractChord(startChunk, chunks): ''' Locate well-formed chords of Chunks with the same onsets and durations :param startChunk: Chunk to compare against :param chunks: Al...
PythonEuterpeaN/FromMidi2.py
from Chunk import * from PythonEuterpea import * from GMInstruments import * from copy import deepcopy from MidiReader import * def extractChord(startChunk, chunks): ''' Locate well-formed chords of Chunks with the same onsets and durations :param startChunk: Chunk to compare against :param chunks: Al...
0.625324
0.49823
import pygal import pandas as pd from pygal.style import Style from pygal.style import DefaultStyle def line_chart_24h(df): temperature_list = df["Temperature"].tolist() humidity_list = df["Humidity"].tolist() x_labels = [] for time in df.Timestamp: m = time[11:16] x_labels.append(m) ...
app/helper/line_chart_24h.py
import pygal import pandas as pd from pygal.style import Style from pygal.style import DefaultStyle def line_chart_24h(df): temperature_list = df["Temperature"].tolist() humidity_list = df["Humidity"].tolist() x_labels = [] for time in df.Timestamp: m = time[11:16] x_labels.append(m) ...
0.51879
0.293518
from radcad.engine import Engine from collections import namedtuple RunArgs = namedtuple("RunArgs", "simulation timesteps run subset initial_state state_update_blocks parameters deepcopy drop_substeps") Context = namedtuple("Context", "simulation run subset timesteps initial_state parameters") class Model: def _...
pool_v0.1_1agent_timestep/radcad/wrappers.py
from radcad.engine import Engine from collections import namedtuple RunArgs = namedtuple("RunArgs", "simulation timesteps run subset initial_state state_update_blocks parameters deepcopy drop_substeps") Context = namedtuple("Context", "simulation run subset timesteps initial_state parameters") class Model: def _...
0.866033
0.459379
import unittest import requests from versa_plugin.versaclient import VersaClient import versa_plugin.cgnat from versa_plugin.cgnat import AddressRange import configuration requests.packages.urllib3.disable_warnings() class CgnatTestCase(unittest.TestCase): def setUp(self): self.config = configuration.dat...
tests/integration/test_cgnat.py
import unittest import requests from versa_plugin.versaclient import VersaClient import versa_plugin.cgnat from versa_plugin.cgnat import AddressRange import configuration requests.packages.urllib3.disable_warnings() class CgnatTestCase(unittest.TestCase): def setUp(self): self.config = configuration.dat...
0.316158
0.205934
import gen_layer import math label_source = "/ssd/ijcai18/data/agnews" #training and testing label generated by 'gen_data.py' data_source = "/ssd/ijcai18/data/agnews" #training and testing data generated by 'gen_data.py' local_dict_source = "/ssd/ijcai18/data/agnews/local_dict.txt" #local dict generated by 'gen_data.p...
script/gen_model.py
import gen_layer import math label_source = "/ssd/ijcai18/data/agnews" #training and testing label generated by 'gen_data.py' data_source = "/ssd/ijcai18/data/agnews" #training and testing data generated by 'gen_data.py' local_dict_source = "/ssd/ijcai18/data/agnews/local_dict.txt" #local dict generated by 'gen_data.p...
0.384565
0.175467
from django.utils.translation import ugettext as _ from rest_framework import serializers class CreateBulkProcessSerializer(serializers.Serializer): """ 多个modeling processing创建校验器 参数如下: { "sql_list" : [sql1, sql2], "bk_biz_id": 591, "project_id": 13105, "type": "datala...
src/api/dataflow/modeling/processing/processing_serializer.py
from django.utils.translation import ugettext as _ from rest_framework import serializers class CreateBulkProcessSerializer(serializers.Serializer): """ 多个modeling processing创建校验器 参数如下: { "sql_list" : [sql1, sql2], "bk_biz_id": 591, "project_id": 13105, "type": "datala...
0.580352
0.275344
import flask import pytest # Rewrites the path so the app can be imported like it normally is import os import sys topdir = os.path.join(os.path.dirname(__file__), "..") sys.path.append(topdir) from app import app INVALID_USER = dict( username="invalid", password="<PASSWORD>" ) TEST_ENDPOINTS = [ '/', ...
src/tests/test_api.py
import flask import pytest # Rewrites the path so the app can be imported like it normally is import os import sys topdir = os.path.join(os.path.dirname(__file__), "..") sys.path.append(topdir) from app import app INVALID_USER = dict( username="invalid", password="<PASSWORD>" ) TEST_ENDPOINTS = [ '/', ...
0.357231
0.133556
from gevent.monkey import patch_all patch_all() import os import time import logging from datetime import datetime from flask import Flask, render_template, jsonify, abort, redirect, url_for, flash, request from flask_wtf import FlaskForm from gevent import Greenlet, sleep from sqlalchemy import create_engine, Column...
sprink/app_server.py
from gevent.monkey import patch_all patch_all() import os import time import logging from datetime import datetime from flask import Flask, render_template, jsonify, abort, redirect, url_for, flash, request from flask_wtf import FlaskForm from gevent import Greenlet, sleep from sqlalchemy import create_engine, Column...
0.537284
0.112869