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 httpretty as hp import pytest from datahub.databus.event import ( call_dataflow_batch_job, check_hdfs_event_and_notify, send_warn_info, validate_date_time, ) from datahub.databus.models import DatabusStorageEvent # noqa from datahub.databus.rt import get_partitions # noqa from datahub.databus.t...
src/api/datahub/databus/tests/modules/event_test.py
import httpretty as hp import pytest from datahub.databus.event import ( call_dataflow_batch_job, check_hdfs_event_and_notify, send_warn_info, validate_date_time, ) from datahub.databus.models import DatabusStorageEvent # noqa from datahub.databus.rt import get_partitions # noqa from datahub.databus.t...
0.456168
0.372448
import importlib from Common.Straw import Straw from Protocol.TaskProtocol import TaskProtocol from Common.Util import Util class Task(TaskProtocol, Straw): ''' 执行任务类 ''' _taskObj = {} _taskName = None _isTest = False def __init__(self, taskName, isTest = False): super().__init__()...
Factory/Task.py
import importlib from Common.Straw import Straw from Protocol.TaskProtocol import TaskProtocol from Common.Util import Util class Task(TaskProtocol, Straw): ''' 执行任务类 ''' _taskObj = {} _taskName = None _isTest = False def __init__(self, taskName, isTest = False): super().__init__()...
0.123471
0.074568
import numpy as np from tensorflow.contrib.learn.python.learn.estimators import estimator from tensorflow.contrib.learn.python.learn import metric_spec from tensorflow.contrib.tensor_forest.client import eval_metrics from tensorflow.contrib.tensor_forest.client import random_forest from tensorflow.contrib.tensor_forest...
mialab/classifier/decision_forest.py
import numpy as np from tensorflow.contrib.learn.python.learn.estimators import estimator from tensorflow.contrib.learn.python.learn import metric_spec from tensorflow.contrib.tensor_forest.client import eval_metrics from tensorflow.contrib.tensor_forest.client import random_forest from tensorflow.contrib.tensor_forest...
0.94098
0.583352
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split import altair as alt import seaborn as sns import matplotlib.pyplot as plt from docopt import docopt opt = docopt(__doc__) def main(filepath, outdir): #read data df = pd.read_csv(f"./{filepath}", index_col=0) #cr...
src/eda_plots.py
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split import altair as alt import seaborn as sns import matplotlib.pyplot as plt from docopt import docopt opt = docopt(__doc__) def main(filepath, outdir): #read data df = pd.read_csv(f"./{filepath}", index_col=0) #cr...
0.632049
0.490541
import torch import torch.nn as nn class ConvBlock(nn.Sequential): """ Class representing a convolutional block. Attributes ---------- in_channels : int The number of input channels. out_channels : int The number of output channels. kernel_size : int (default=3) Th...
src/model.py
import torch import torch.nn as nn class ConvBlock(nn.Sequential): """ Class representing a convolutional block. Attributes ---------- in_channels : int The number of input channels. out_channels : int The number of output channels. kernel_size : int (default=3) Th...
0.96516
0.814238
from conans import ConanFile, CMake, tools import functools import os required_conan_version = ">=1.43.0" class CppKafkaConan(ConanFile): name = "cppkafka" description = "Modern C++ Apache Kafka client library (wrapper for librdkafka)" topics = ("librdkafka", "kafka") url = "https://github.com/conan-...
recipes/cppkafka/all/conanfile.py
from conans import ConanFile, CMake, tools import functools import os required_conan_version = ">=1.43.0" class CppKafkaConan(ConanFile): name = "cppkafka" description = "Modern C++ Apache Kafka client library (wrapper for librdkafka)" topics = ("librdkafka", "kafka") url = "https://github.com/conan-...
0.333829
0.108448
from email.policy import default from . import db from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from . import login_manager from datetime import datetime import enum @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) ...
app/models.py
from email.policy import default from . import db from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from . import login_manager from datetime import datetime import enum @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) ...
0.423339
0.054274
from __future__ import unicode_literals import frappe from frappe.model.document import Document from datetime import timedelta,date import datetime import calendar import json import time def validate(doc, method): task_name = [] task = frappe.get_all("Task", {'project':doc.name}, "subject") for row in task: ...
cal_view_app/cal_view_app/custom_script/project/project.py
from __future__ import unicode_literals import frappe from frappe.model.document import Document from datetime import timedelta,date import datetime import calendar import json import time def validate(doc, method): task_name = [] task = frappe.get_all("Task", {'project':doc.name}, "subject") for row in task: ...
0.334481
0.183649
from PySide2 import QtCore, QtGui, QtWidgets from .slot import SlotItem, ConnectionItem class NodeItem(QtWidgets.QGraphicsItem): def __init__(self, view, data): super().__init__() self.setZValue(1) # Storage self.data = data self.slot_child = None self.slot_parent...
qt_tree/node.py
from PySide2 import QtCore, QtGui, QtWidgets from .slot import SlotItem, ConnectionItem class NodeItem(QtWidgets.QGraphicsItem): def __init__(self, view, data): super().__init__() self.setZValue(1) # Storage self.data = data self.slot_child = None self.slot_parent...
0.690663
0.102979
import asyncio import secrets import time from discord.utils import get from helpers.exceptions import LevelingBlacklistedUserException, PromotingYourselfForbiddenException, \ PromoCodeNotFoundException, UnknownException from helpers.spark_module import SparkModule from .settings import SETTINGS from .web import ...
modules/promo/__init__.py
import asyncio import secrets import time from discord.utils import get from helpers.exceptions import LevelingBlacklistedUserException, PromotingYourselfForbiddenException, \ PromoCodeNotFoundException, UnknownException from helpers.spark_module import SparkModule from .settings import SETTINGS from .web import ...
0.288469
0.053924
def interruptControl(symbol, event): global interruptVector global interruptHandler global interruptHandlerLock if event["value"] == True: Database.setSymbolValue("core", interruptVector, True) Database.setSymbolValue("core", interruptHandler, canInstanceName.getValue() + "_InterruptHan...
peripheral/can_6019/config/can.py
def interruptControl(symbol, event): global interruptVector global interruptHandler global interruptHandlerLock if event["value"] == True: Database.setSymbolValue("core", interruptVector, True) Database.setSymbolValue("core", interruptHandler, canInstanceName.getValue() + "_InterruptHan...
0.517083
0.275024
from subprocess import Popen, PIPE from os.path import isfile from json import loads from tkinter import Tk, messagebox, BOTH from model.Installation import INSTALLATION_FOLDER, LSHW_JSON_FILE from view.Components import JsonTreeView PROGRAM_TITLE = "Data Source Adapter" class Hardware: def __init__(self): ...
service/DataSource.py
from subprocess import Popen, PIPE from os.path import isfile from json import loads from tkinter import Tk, messagebox, BOTH from model.Installation import INSTALLATION_FOLDER, LSHW_JSON_FILE from view.Components import JsonTreeView PROGRAM_TITLE = "Data Source Adapter" class Hardware: def __init__(self): ...
0.310172
0.08141
import random from burp import IBurpExtender from burp import IIntruderPayloadGeneratorFactory from burp import IIntruderPayloadGenerator from java.util import List, ArrayList class BurpExtender(IBurpExtender, IIntruderPayloadGeneratorFactory): def registerExtenderCallbacks(self, callbacks): self._callb...
net/bhp_fuzzer.py
import random from burp import IBurpExtender from burp import IIntruderPayloadGeneratorFactory from burp import IIntruderPayloadGenerator from java.util import List, ArrayList class BurpExtender(IBurpExtender, IIntruderPayloadGeneratorFactory): def registerExtenderCallbacks(self, callbacks): self._callb...
0.500977
0.10004
import time import datetime import requests import logging, warnings FORMAT = '%(asctime)s %(message)s' logging.basicConfig(level="INFO", format=FORMAT) #warnings.filterwarnings('ignore') logger = logging.getLogger("switch_mgmt") HA_states_url = "http://<HOST IP ADDRESS>:8123/api/states/" HA_script_url = "http://<HOS...
switch_mgmt.py
import time import datetime import requests import logging, warnings FORMAT = '%(asctime)s %(message)s' logging.basicConfig(level="INFO", format=FORMAT) #warnings.filterwarnings('ignore') logger = logging.getLogger("switch_mgmt") HA_states_url = "http://<HOST IP ADDRESS>:8123/api/states/" HA_script_url = "http://<HOS...
0.172241
0.108472
import unittest from jsom import JsomParser, SINGLE_QUOTED_STRING, UNQUOTED_STRING, \ EMPTY_OBJECT_VALUE, TRAILING_COMMA_IN_OBJECT, TRAILING_COMMA_IN_ARRAY, \ ALL_WARNINGS class TestWarnings(unittest.TestCase): def setUp(self): self.parser = JsomParser() def test_single_quoted_string_warning...
jsom/tests/test_warnings.py
import unittest from jsom import JsomParser, SINGLE_QUOTED_STRING, UNQUOTED_STRING, \ EMPTY_OBJECT_VALUE, TRAILING_COMMA_IN_OBJECT, TRAILING_COMMA_IN_ARRAY, \ ALL_WARNINGS class TestWarnings(unittest.TestCase): def setUp(self): self.parser = JsomParser() def test_single_quoted_string_warning...
0.579281
0.520314
import re import logging import torch import faiss from tqdm import tqdm from typing import List from elasticsearch import Elasticsearch from transformers import (DPRContextEncoder, DPRContextEncoderTokenizer, DPRQuestionEncoder, DPRQuestionEncoderTokenizer) from chunker import DocumentChunker...
research/information_retrieval/elastic_integration/dense_ranking.py
import re import logging import torch import faiss from tqdm import tqdm from typing import List from elasticsearch import Elasticsearch from transformers import (DPRContextEncoder, DPRContextEncoderTokenizer, DPRQuestionEncoder, DPRQuestionEncoderTokenizer) from chunker import DocumentChunker...
0.604282
0.213131
__author__ = '<NAME>' from input_file_creator.write_cell_card.mlc_open import mlc_open_distance as mlcod from input_file_creator.write_cell_card.trcl import trcl_mlc def qi_bank_1(): qi_cell_1 = ('c Quarter Leaf Isocenter Bank 1 ' + '$' * 46 + '\n' + ' 130 3 -18 -101 104 105 -106 -109 -110' + '...
main/input_file_creator/write_cell_card/mlc_cell.py
__author__ = '<NAME>' from input_file_creator.write_cell_card.mlc_open import mlc_open_distance as mlcod from input_file_creator.write_cell_card.trcl import trcl_mlc def qi_bank_1(): qi_cell_1 = ('c Quarter Leaf Isocenter Bank 1 ' + '$' * 46 + '\n' + ' 130 3 -18 -101 104 105 -106 -109 -110' + '...
0.309024
0.107204
from pyomo.environ import * model = m = ConcreteModel() m.x1 = Var(within=Reals,bounds=(1E-6,1),initialize=0.187) m.x2 = Var(within=Reals,bounds=(1E-6,1),initialize=0.56) m.x3 = Var(within=Reals,bounds=(1E-6,1),initialize=0.253) m.x4 = Var(within=Reals,bounds=(40,90),initialize=72.957) m.x6 = Var(within=Reals,boun...
tests/examples/minlplib/ex14_2_4.py
from pyomo.environ import * model = m = ConcreteModel() m.x1 = Var(within=Reals,bounds=(1E-6,1),initialize=0.187) m.x2 = Var(within=Reals,bounds=(1E-6,1),initialize=0.56) m.x3 = Var(within=Reals,bounds=(1E-6,1),initialize=0.253) m.x4 = Var(within=Reals,bounds=(40,90),initialize=72.957) m.x6 = Var(within=Reals,boun...
0.232223
0.35502
__author__ = 'shahriyar' __copyright__ = 'Copyright 2014, <NAME>' from sqlalchemy import * from sqlalchemy.orm import relation, mapper, sessionmaker class Activity(object): pass class App(object): pass class Library(object): pass class Permission(object): pass class Provider(object): pass cl...
Source/GortGUIv2/Gort/pythonscripts/src/org/cmuchimps/gort/modules/pythonscripts/gortdb.py
__author__ = 'shahriyar' __copyright__ = 'Copyright 2014, <NAME>' from sqlalchemy import * from sqlalchemy.orm import relation, mapper, sessionmaker class Activity(object): pass class App(object): pass class Library(object): pass class Permission(object): pass class Provider(object): pass cl...
0.623606
0.078642
import copy import pytest from datasette.app import Datasette @pytest.mark.asyncio async def test_dashboard_views(datasette): dashboards = datasette._metadata["plugins"]["datasette-dashboards"] for slug, dashboard in dashboards.items(): response = await datasette.client.get(f"/-/dashboards/{slug}") ...
tests/test_dashboard_view.py
import copy import pytest from datasette.app import Datasette @pytest.mark.asyncio async def test_dashboard_views(datasette): dashboards = datasette._metadata["plugins"]["datasette-dashboards"] for slug, dashboard in dashboards.items(): response = await datasette.client.get(f"/-/dashboards/{slug}") ...
0.447219
0.404155
import os import sys import errno import platform import unittest class TestConfig(unittest.TestCase): def setUp(self): os.environ["_condor_FOO"] = "BAR" htcondor.reload_config() def test_config(self): self.assertEqual(htcondor.param["FOO"], "BAR") def test_reconfig(self): ...
src/python-bindings/tests/htcondor_version_tests.py
import os import sys import errno import platform import unittest class TestConfig(unittest.TestCase): def setUp(self): os.environ["_condor_FOO"] = "BAR" htcondor.reload_config() def test_config(self): self.assertEqual(htcondor.param["FOO"], "BAR") def test_reconfig(self): ...
0.275519
0.341335
from base64 import b64encode from functools import reduce from pprint import pformat from time import gmtime, strftime # parses the output of ffmpeg into a dictionary def ffmpeg_black_frames_to_json(lines): lines = [x.split("] ")[1].rstrip() for x in lines if "blackdetect" in x] lines = [x.split(" ") for x in...
tasks/black-frames/task/utils.py
from base64 import b64encode from functools import reduce from pprint import pformat from time import gmtime, strftime # parses the output of ffmpeg into a dictionary def ffmpeg_black_frames_to_json(lines): lines = [x.split("] ")[1].rstrip() for x in lines if "blackdetect" in x] lines = [x.split(" ") for x in...
0.542379
0.275922
import os import sys import tempfile from io import StringIO import unittest from mdgo.forcefield import * test_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_files") class FFcrawlerTest(unittest.TestCase): def test_chrome(self) -> None: with open(os.path.join(test_dir, "EMC.lmp")) ...
tests/test_forcefield.py
import os import sys import tempfile from io import StringIO import unittest from mdgo.forcefield import * test_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_files") class FFcrawlerTest(unittest.TestCase): def test_chrome(self) -> None: with open(os.path.join(test_dir, "EMC.lmp")) ...
0.250638
0.311924
import numpy as np from datetime import datetime from .routine import get_fix_string, get_fix_list from .routine import get_equal_strings, get_equal_lists from .models.base_model import MODEL_NAME_LENGTH UP_END = "┌" DOWN_END = "└" MIDDLE = "├" LAST = "┤" EMPTY = "│" START_END = "┐" SPACE = " " USELESS_SUBKEYS = { ...
topicnet/cooking_machine/pretty_output.py
import numpy as np from datetime import datetime from .routine import get_fix_string, get_fix_list from .routine import get_equal_strings, get_equal_lists from .models.base_model import MODEL_NAME_LENGTH UP_END = "┌" DOWN_END = "└" MIDDLE = "├" LAST = "┤" EMPTY = "│" START_END = "┐" SPACE = " " USELESS_SUBKEYS = { ...
0.704364
0.151718
import click import os import sys import logging import colorama from rich.console import Console from rich.table import Table from clipbit.script import Captions from clipbit.text_summary import summary as ts logger = logging.getLogger(__name__) colorama.init() console = Console() @click.command() @click.option( ...
clipbit/__main__.py
import click import os import sys import logging import colorama from rich.console import Console from rich.table import Table from clipbit.script import Captions from clipbit.text_summary import summary as ts logger = logging.getLogger(__name__) colorama.init() console = Console() @click.command() @click.option( ...
0.464902
0.25271
from typing import Mapping, Optional from pybel import BELGraph from pybel.dsl import Abundance, BaseEntity, NamedComplexAbundance from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, Text from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base from sqlalchemy.orm import backref, relat...
src/bio2bel_go/models.py
from typing import Mapping, Optional from pybel import BELGraph from pybel.dsl import Abundance, BaseEntity, NamedComplexAbundance from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, Text from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base from sqlalchemy.orm import backref, relat...
0.912709
0.159971
from src.cassandra.db_connector import CassandraConnector from src.kafka.utils import get_url_from_key, get_s3_key from src.utils import get_date_from_timestamp import json from cassandra import RequestExecutionException class DBWriter(object): def __init__(self): self.db = CassandraConnector() s...
src/cassandra/db_writer.py
from src.cassandra.db_connector import CassandraConnector from src.kafka.utils import get_url_from_key, get_s3_key from src.utils import get_date_from_timestamp import json from cassandra import RequestExecutionException class DBWriter(object): def __init__(self): self.db = CassandraConnector() s...
0.185394
0.062875
def migrate(): from datetime import datetime from django.db import connections from review.models import ProposalResult, promote_proposal from schedule.models import Slot, Session accepted_proposals = ProposalResult.objects.filter(accepted=True) accepted_proposals = accepted_propo...
pycon_project/migrations/008_create_sessions_slots.py
def migrate(): from datetime import datetime from django.db import connections from review.models import ProposalResult, promote_proposal from schedule.models import Slot, Session accepted_proposals = ProposalResult.objects.filter(accepted=True) accepted_proposals = accepted_propo...
0.461988
0.392104
import re import sys import argparse from pathlib import Path def clean_name(path): """ Assumes names of form path/to/foo_..._R[1,2]...fastq.* """ clean_path = Path(path) head = clean_path.name.split('_')[0] read = re.search(r"_(R[1-2])_", clean_path.name).group(1) ext = ''.join(clean_path...
src/link-data.py
import re import sys import argparse from pathlib import Path def clean_name(path): """ Assumes names of form path/to/foo_..._R[1,2]...fastq.* """ clean_path = Path(path) head = clean_path.name.split('_')[0] read = re.search(r"_(R[1-2])_", clean_path.name).group(1) ext = ''.join(clean_path...
0.320928
0.18228
import sys import threading import time import unittest import ptvsd.untangle from ptvsd.wrapper import ModulesManager class ModulesEventSink(object): def __init__(self): self.event_data = [] self._lock = threading.Lock() def send_event(self, event, **kwargs): with self._lock: ...
tests/ptvsd/test_modules_manager.py
import sys import threading import time import unittest import ptvsd.untangle from ptvsd.wrapper import ModulesManager class ModulesEventSink(object): def __init__(self): self.event_data = [] self._lock = threading.Lock() def send_event(self, event, **kwargs): with self._lock: ...
0.337313
0.211946
from collections import defaultdict, Counter from .dtype import Type, Function, Dead, Unknown from .infer import Context, GraphInferrer, ANYTHING, Inferrer from .ir import GraphCloner, is_apply, is_constant, Constant, \ succ_deeper, Graph from .prim import Primitive from .graph_utils import dfs from .utils import...
myia/specialize.py
from collections import defaultdict, Counter from .dtype import Type, Function, Dead, Unknown from .infer import Context, GraphInferrer, ANYTHING, Inferrer from .ir import GraphCloner, is_apply, is_constant, Constant, \ succ_deeper, Graph from .prim import Primitive from .graph_utils import dfs from .utils import...
0.767341
0.240384
import unittest import numpy as np from bio_rtd.chromatography import bt_curve, bt_load from bio_rtd.core import ChromatographyLoadBreakthrough from bio_rtd_test.aux_bio_rtd_test import TestLogger class DummyChromatographyLoadBreakthrough(ChromatographyLoadBreakthrough): POSSIBLE_KEY_GROUPS = [] OPTIONAL_KE...
bio_rtd_test/unit_test/chromatography/test_bt_load.py
import unittest import numpy as np from bio_rtd.chromatography import bt_curve, bt_load from bio_rtd.core import ChromatographyLoadBreakthrough from bio_rtd_test.aux_bio_rtd_test import TestLogger class DummyChromatographyLoadBreakthrough(ChromatographyLoadBreakthrough): POSSIBLE_KEY_GROUPS = [] OPTIONAL_KE...
0.672439
0.518059
from collections import OrderedDict from django.core.serializers.json import DjangoJSONEncoder from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.db.models import Q import json from djang...
teamModule/cms_plugins.py
from collections import OrderedDict from django.core.serializers.json import DjangoJSONEncoder from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.db.models import Q import json from djang...
0.253122
0.100437
from __future__ import print_function import platform import os from EBRAINS_RichEndpoint.Application_Companion.cpu import CPU class Platform: """ Provides the underlying Platform details. """ def __init__(self) -> None: self.__info = {} # Hardware specific details self.__info...
Application_Companion/underlying_platform.py
from __future__ import print_function import platform import os from EBRAINS_RichEndpoint.Application_Companion.cpu import CPU class Platform: """ Provides the underlying Platform details. """ def __init__(self) -> None: self.__info = {} # Hardware specific details self.__info...
0.730963
0.091382
import re class TokenKind: NEWLINES = 0 H_SPACES = 1 COMMENT = 2 LEFT_PAR = 10 RIGHT_PAR = 11 LEFT_BRACE = 12 RIGHT_BRACE = 13 LEFT_BRACKET = 14 RIGHT_BRACKET = 15 EQ = 20 LT = 21 GT = 22 SEMI_COL = 30 DOT = 31 COLON = 32 ID = 50 STRING = 51 ...
src/generator/python/protobuf/scanner.py
import re class TokenKind: NEWLINES = 0 H_SPACES = 1 COMMENT = 2 LEFT_PAR = 10 RIGHT_PAR = 11 LEFT_BRACE = 12 RIGHT_BRACE = 13 LEFT_BRACKET = 14 RIGHT_BRACKET = 15 EQ = 20 LT = 21 GT = 22 SEMI_COL = 30 DOT = 31 COLON = 32 ID = 50 STRING = 51 ...
0.633297
0.330809
import itertools import os import fnmatch import re import sys import argparse import ninja_syntax import gcc import llvm import msvc # --- util functions def flags(*iterables): return ' '.join(itertools.chain(*iterables)) def get_files(root, pattern): pattern = fnmatch.translate(pattern) for dir, dirs...
vendor/nonius-v1.1.2/tools/bootstrap.py
import itertools import os import fnmatch import re import sys import argparse import ninja_syntax import gcc import llvm import msvc # --- util functions def flags(*iterables): return ' '.join(itertools.chain(*iterables)) def get_files(root, pattern): pattern = fnmatch.translate(pattern) for dir, dirs...
0.258607
0.058912
import os from flask_script import Manager, Server, prompt_choices from flask_script.commands import ShowUrls, Clean from flask_migrate import Migrate, MigrateCommand from hospitalSystem import create_app from hospitalSystem.warmup import setup_db, update_perms, createsuperuser from hospitalSystem.models import db, U...
manage.py
import os from flask_script import Manager, Server, prompt_choices from flask_script.commands import ShowUrls, Clean from flask_migrate import Migrate, MigrateCommand from hospitalSystem import create_app from hospitalSystem.warmup import setup_db, update_perms, createsuperuser from hospitalSystem.models import db, U...
0.452294
0.069479
import pytest from memsql.common import database def test_connection_open(test_db_conn): assert test_db_conn.connected() def test_connection_close(test_db_conn): assert test_db_conn.connected() test_db_conn.close() assert not test_db_conn.connected() def test_reconnect(test_db_conn): assert test_...
memsql/common/test/test_database_adapters.py
import pytest from memsql.common import database def test_connection_open(test_db_conn): assert test_db_conn.connected() def test_connection_close(test_db_conn): assert test_db_conn.connected() test_db_conn.close() assert not test_db_conn.connected() def test_reconnect(test_db_conn): assert test_...
0.42668
0.414425
import logging from django.contrib.auth import get_user_model from django.utils import timezone from django.conf import settings from rest_framework import mixins, viewsets, permissions from rest_framework import status from rest_framework import validators from rest_framework.response import Response from rest_frame...
tests/views.py
import logging from django.contrib.auth import get_user_model from django.utils import timezone from django.conf import settings from rest_framework import mixins, viewsets, permissions from rest_framework import status from rest_framework import validators from rest_framework.response import Response from rest_frame...
0.539469
0.08819
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import math import numpy as np import sys vertices = ( (1.5, -1.5, -1.5), (1.5, 1.5, -1.5), (-1.5, 1.5, -1.5), (-1.5, -1.5, -1.5), (1.5, -1.5, 1.5), (1.5, 1.5, 1.5), (-1.5,...
aicontest_file.py
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import math import numpy as np import sys vertices = ( (1.5, -1.5, -1.5), (1.5, 1.5, -1.5), (-1.5, 1.5, -1.5), (-1.5, -1.5, -1.5), (1.5, -1.5, 1.5), (1.5, 1.5, 1.5), (-1.5,...
0.288068
0.446736
from __future__ import absolute_import import sys import functools from sentry.utils.strings import ( is_valid_dot_atom, soft_break, soft_hyphenate, tokens_from_name, codec_lookup, truncatechars ) ZWSP = u'\u200b' # zero width space SHY = u'\u00ad' # soft hyphen def test_codec_lookup(): def assert_ma...
tests/sentry/utils/test_strings.py
from __future__ import absolute_import import sys import functools from sentry.utils.strings import ( is_valid_dot_atom, soft_break, soft_hyphenate, tokens_from_name, codec_lookup, truncatechars ) ZWSP = u'\u200b' # zero width space SHY = u'\u00ad' # soft hyphen def test_codec_lookup(): def assert_ma...
0.562537
0.36018
import cv2 import numpy as np import time from matplotlib.patches import Rectangle import matplotlib.pyplot as plt def sse(array1, array2): return np.sum(np.power(array1.astype(np.float32) - array2.astype(np.float32), 2)) def mse(array1, array2): return np.mean(np.power(array1.astype(np.float32) - array2.ast...
week4/block_matching.py
import cv2 import numpy as np import time from matplotlib.patches import Rectangle import matplotlib.pyplot as plt def sse(array1, array2): return np.sum(np.power(array1.astype(np.float32) - array2.astype(np.float32), 2)) def mse(array1, array2): return np.mean(np.power(array1.astype(np.float32) - array2.ast...
0.272702
0.649454
import yaml from transible.plugins.os_ansible.const import DEFAULTS from transible.plugins.os_ansible.config import VARS_PATH class ExtraDumper(yaml.Dumper): """Custom dumper for YAML """ def increase_indent(self, flow=False, indentless=False): return super().increase_indent(flow, False) def ya...
transible/plugins/os_ansible/common.py
import yaml from transible.plugins.os_ansible.const import DEFAULTS from transible.plugins.os_ansible.config import VARS_PATH class ExtraDumper(yaml.Dumper): """Custom dumper for YAML """ def increase_indent(self, flow=False, indentless=False): return super().increase_indent(flow, False) def ya...
0.322846
0.232375
# -*- coding: utf-8 -*- import BigWorld import re from gui.mods.mod_mods_gui import browser, g_gui, inject from notification.NotificationListView import NotificationListView from notification.settings import NOTIFICATION_GROUP class Config(object): def __init__(self): self.ids = 'bookmarks' self...
mod_bookmarks/source/mod_bookmarks.py
# -*- coding: utf-8 -*- import BigWorld import re from gui.mods.mod_mods_gui import browser, g_gui, inject from notification.NotificationListView import NotificationListView from notification.settings import NOTIFICATION_GROUP class Config(object): def __init__(self): self.ids = 'bookmarks' self...
0.218836
0.205934
import matplotlib.pyplot as plt import numpy as np import os def get_hypnogram(y_pred, y_true=None, id_=None): def format_ax(ax): ax.set_xlabel("Period number") ax.set_ylabel("Sleep stage") ax.set_yticks(range(6)) ax.set_yticklabels(["Wake", "N1", "N2", "N3", "REM", "Unknown"]) ...
utime/evaluation/plotting.py
import matplotlib.pyplot as plt import numpy as np import os def get_hypnogram(y_pred, y_true=None, id_=None): def format_ax(ax): ax.set_xlabel("Period number") ax.set_ylabel("Sleep stage") ax.set_yticks(range(6)) ax.set_yticklabels(["Wake", "N1", "N2", "N3", "REM", "Unknown"]) ...
0.799481
0.476397
from __future__ import print_function from select import select import subprocess import logging import math import sys import os log = logging.getLogger("mth.utils") def execute(command, suppress_errors=False, out=subprocess.PIPE, io_mode="w+"): """ Executes given command, redirect stdout to file or returns...
framework/utils/console.py
from __future__ import print_function from select import select import subprocess import logging import math import sys import os log = logging.getLogger("mth.utils") def execute(command, suppress_errors=False, out=subprocess.PIPE, io_mode="w+"): """ Executes given command, redirect stdout to file or returns...
0.422743
0.179854
import torch.nn as nn from torch.nn.modules.batchnorm import _BatchNorm from ...cv_core import kaiming_init, constant_init from ..utils import brick as vn_layer from ..builder import BACKBONES @BACKBONES.register_module() class RRCSPDarknet53(nn.Module): # 用于递归导入权重 custom_layers = (vn_layer.Resblock_body, vn_...
mmdet/models/backbones/rr_cspdarknet53.py
import torch.nn as nn from torch.nn.modules.batchnorm import _BatchNorm from ...cv_core import kaiming_init, constant_init from ..utils import brick as vn_layer from ..builder import BACKBONES @BACKBONES.register_module() class RRCSPDarknet53(nn.Module): # 用于递归导入权重 custom_layers = (vn_layer.Resblock_body, vn_...
0.901953
0.299131
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('perfis', '0001_initial'), ('localidades_brasileiras', '0001_initial'), migrations.swappable_dependency(...
controle_colaboradores_api/apps/perfis/migrations/0002_initial.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('perfis', '0001_initial'), ('localidades_brasileiras', '0001_initial'), migrations.swappable_dependency(...
0.523664
0.1126
from paho.mqtt import client as mqtt_client import bluepy.btle as btle import time import datetime import argparse import signal import struct import sys import json #AIRWAVE CONFIGURATION serial_number = #Wave2 serial mac_addr = #Wave2 mac address data_interval = #fetch interval in seconds #MQTT CONFIGURATION broke...
airthings-main.py
from paho.mqtt import client as mqtt_client import bluepy.btle as btle import time import datetime import argparse import signal import struct import sys import json #AIRWAVE CONFIGURATION serial_number = #Wave2 serial mac_addr = #Wave2 mac address data_interval = #fetch interval in seconds #MQTT CONFIGURATION broke...
0.396185
0.105717
def eliminate_spaces(string): return string.replace(" ","") def cypher_creation(cypher): lowered_cypher = eliminate_spaces(cypher.lower()) new_alphabet = "" for char in lowered_cypher: if char not in new_alphabet: new_alphabet += char abc = "abcdefghiklmnopqrstuvwxyz" for l...
substitution_cyphers/playfair.py
def eliminate_spaces(string): return string.replace(" ","") def cypher_creation(cypher): lowered_cypher = eliminate_spaces(cypher.lower()) new_alphabet = "" for char in lowered_cypher: if char not in new_alphabet: new_alphabet += char abc = "abcdefghiklmnopqrstuvwxyz" for l...
0.39257
0.241573
import pdal import json import geopandas as gpd from pyproj import Transformer from .logs import log from shapely.geometry import Polygon, Point import os if (not os.path.isdir('./logs')): os.mkdir("./logs") logs_path = "./logs/get_data.logs" if not os.path.exists(logs_path): with open(logs_path, "w"): ...
usgslidar/get_data.py
import pdal import json import geopandas as gpd from pyproj import Transformer from .logs import log from shapely.geometry import Polygon, Point import os if (not os.path.isdir('./logs')): os.mkdir("./logs") logs_path = "./logs/get_data.logs" if not os.path.exists(logs_path): with open(logs_path, "w"): ...
0.302597
0.165323
# standard library from datetime import date # related import pytest # project from ottd_ctrl.const import DestType, NetworkAction from ottd_ctrl.packet import AdminChatPacket, AdminPacket, ServerDatePacket from ottd_ctrl.protocol import Date from ottd_ctrl.session import Session dummy_session_args = ('name', 'pass'...
tests/session_test.py
# standard library from datetime import date # related import pytest # project from ottd_ctrl.const import DestType, NetworkAction from ottd_ctrl.packet import AdminChatPacket, AdminPacket, ServerDatePacket from ottd_ctrl.protocol import Date from ottd_ctrl.session import Session dummy_session_args = ('name', 'pass'...
0.602763
0.31455
from datetime import datetime from xml.dom import minidom from xml.dom.minidom import Node from xml.etree import ElementTree from contextlib import closing import re import xbmcvfs # pylint: disable=import-error ENCODING = 'UTF-8' PLAYCOUNT_TAG = 'playcount' LAST_PLAYED_TAG = 'lastplayed' IO_ERROR_ENOENT = (2, 'No ...
resources/lib/borntogrill/kodi_nfo_updater.py
from datetime import datetime from xml.dom import minidom from xml.dom.minidom import Node from xml.etree import ElementTree from contextlib import closing import re import xbmcvfs # pylint: disable=import-error ENCODING = 'UTF-8' PLAYCOUNT_TAG = 'playcount' LAST_PLAYED_TAG = 'lastplayed' IO_ERROR_ENOENT = (2, 'No ...
0.248899
0.097562
# This program is licensed under the Apache License version 2. # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. from sqlalchemy import Table from typing import Optional from app.api import crud from app.db import accesses, users, sites, events, devices, media, insta...
src/app/api/crud/groups.py
# This program is licensed under the Apache License version 2. # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. from sqlalchemy import Table from typing import Optional from app.api import crud from app.db import accesses, users, sites, events, devices, media, insta...
0.779532
0.150496
import json import socket from pythonosc import ( dispatcher, osc_server, udp_client, ) from .message_hub import ( AbstractMessageHubBroker, AbstractMessageHubClient, MessageHubConnectionError, MessageHubPublishError, MessageHubStartError, ) class OscMessageHubBroker(AbstractMessageH...
osc.py
import json import socket from pythonosc import ( dispatcher, osc_server, udp_client, ) from .message_hub import ( AbstractMessageHubBroker, AbstractMessageHubClient, MessageHubConnectionError, MessageHubPublishError, MessageHubStartError, ) class OscMessageHubBroker(AbstractMessageH...
0.50415
0.054424
import numpy as np class Interpolator(object): def __init__(self): self.time = 0.0 self.segment_time = 0.0 self.segment = 0 self.segment_num = 0 self.is_interpolating = False def reset(self, position_list=None, time_list=None): """"Initialize int...
skrobot/interpolator.py
import numpy as np class Interpolator(object): def __init__(self): self.time = 0.0 self.segment_time = 0.0 self.segment = 0 self.segment_num = 0 self.is_interpolating = False def reset(self, position_list=None, time_list=None): """"Initialize int...
0.799951
0.311597
import sys import json import time from spdb.spatialdb import Cube, SpatialDB, SpdbError from spdb.project import BossResourceBasic from spdb.c_lib.ndtype import CUBOIDSIZE from spdb.c_lib.ndlib import XYZMorton from ndingest.settings.bosssettings import BossSettings from ndingest.ndingestproj.bossingestproj import ...
lambda/ingest_lambda.py
import sys import json import time from spdb.spatialdb import Cube, SpatialDB, SpdbError from spdb.project import BossResourceBasic from spdb.c_lib.ndtype import CUBOIDSIZE from spdb.c_lib.ndlib import XYZMorton from ndingest.settings.bosssettings import BossSettings from ndingest.ndingestproj.bossingestproj import ...
0.382141
0.139572
import argparse import json import os import time from azure.iot.device import IoTHubDeviceClient from bs4 import BeautifulSoup from dotenv import load_dotenv load_dotenv() try: device_connection_string = os.environ['DEVICE_CONNECTION_STRING'] except KeyError: device_connection_string = '' parser = argparse....
app.py
import argparse import json import os import time from azure.iot.device import IoTHubDeviceClient from bs4 import BeautifulSoup from dotenv import load_dotenv load_dotenv() try: device_connection_string = os.environ['DEVICE_CONNECTION_STRING'] except KeyError: device_connection_string = '' parser = argparse....
0.287368
0.053477
from typing import Dict, List, Union import six.moves.urllib as urllib from . import constants def _verify_topic( topic: str, subtopics: Union[str, List[str]] = None, feature: str = None ) -> None: """ Helper function to verify that a topic is for iothub and is targeted for a specific feature. :param...
python/helpers/topic_parser.py
from typing import Dict, List, Union import six.moves.urllib as urllib from . import constants def _verify_topic( topic: str, subtopics: Union[str, List[str]] = None, feature: str = None ) -> None: """ Helper function to verify that a topic is for iothub and is targeted for a specific feature. :param...
0.899419
0.414069
import cv2 import numpy as np bins = np.arange(256).reshape(256, 1) def hist_curve(im): h = np.zeros((300, 256, 3)) if len(im.shape) == 2: color = [(255, 255, 255)] elif im.shape[2] == 3: color = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] for ch, col in enumerate(color): hist_ite...
ch22-直方图/hist.py
import cv2 import numpy as np bins = np.arange(256).reshape(256, 1) def hist_curve(im): h = np.zeros((300, 256, 3)) if len(im.shape) == 2: color = [(255, 255, 255)] elif im.shape[2] == 3: color = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] for ch, col in enumerate(color): hist_ite...
0.287068
0.511046
import subprocess import os import uuid import hashlib import logging import basedefs import common_utils as utils import output_messages SELINUX_RW_LABEL = "public_content_rw_t" SHA_CKSUM_TAG = "_SHA_CKSUM" _preprocessLine = lambda line : unicode.encode(unicode(line), 'ascii', 'xmlcharrefreplace') def addNfsExport...
packaging/fedora/setup/nfsutils.py
import subprocess import os import uuid import hashlib import logging import basedefs import common_utils as utils import output_messages SELINUX_RW_LABEL = "public_content_rw_t" SHA_CKSUM_TAG = "_SHA_CKSUM" _preprocessLine = lambda line : unicode.encode(unicode(line), 'ascii', 'xmlcharrefreplace') def addNfsExport...
0.281998
0.084909
import os import re import json from os.path import join from torch.utils.data import Dataset class JsonFileDataset(Dataset): """ trainer 训练数据 文件名[0-9]+.json 数字按顺序依次递增 val 验证数据 文件名[0-9]+.json 数字按顺序依次递增 test 测试数据 文件名[0-9]+.json 数字按顺序依次递增 """ def __init__(self, split: str, path: s...
src/library/utils/datasets/jsonfile.py
import os import re import json from os.path import join from torch.utils.data import Dataset class JsonFileDataset(Dataset): """ trainer 训练数据 文件名[0-9]+.json 数字按顺序依次递增 val 验证数据 文件名[0-9]+.json 数字按顺序依次递增 test 测试数据 文件名[0-9]+.json 数字按顺序依次递增 """ def __init__(self, split: str, path: s...
0.368178
0.327803
from .motor_controller import MotorController from pidevices.hardware_interfaces.gpio_implementations import PiGPIO from collections import namedtuple from enum import Enum Channel = namedtuple('Channel',['E', 'M']) Pin = namedtuple('Pin', ['name', 'number']) class ChannelPos(Enum): LEFT = 0 RIGHT = 1 clas...
pidevices/actuators/dfrobot_motor_controller_pigpio.py
from .motor_controller import MotorController from pidevices.hardware_interfaces.gpio_implementations import PiGPIO from collections import namedtuple from enum import Enum Channel = namedtuple('Channel',['E', 'M']) Pin = namedtuple('Pin', ['name', 'number']) class ChannelPos(Enum): LEFT = 0 RIGHT = 1 clas...
0.927855
0.326969
import json import argparse from tornado import web, ioloop, queues, gen, process from server import ApiHandler, TranslatorWorker, initialize_workers, settings class ElgApiHandler(ApiHandler): def post(self, src_lang, target_lang): self.prepare_args() lang_pair = "{}-{}".format(src_lang, tar...
elg/elg_server.py
import json import argparse from tornado import web, ioloop, queues, gen, process from server import ApiHandler, TranslatorWorker, initialize_workers, settings class ElgApiHandler(ApiHandler): def post(self, src_lang, target_lang): self.prepare_args() lang_pair = "{}-{}".format(src_lang, tar...
0.179567
0.101367
from queue import Queue, Empty from threading import Thread, Semaphore from gridvm.network.nethandler import NetHandler from gridvm.network.protocol.packet import PacketType from gridvm.network.protocol.packet import Packet from gridvm.network.protocol.packet import make_packet class EchoCommunication: def __ini...
gridvm/simplescript/runtime/communication.py
from queue import Queue, Empty from threading import Thread, Semaphore from gridvm.network.nethandler import NetHandler from gridvm.network.protocol.packet import PacketType from gridvm.network.protocol.packet import Packet from gridvm.network.protocol.packet import make_packet class EchoCommunication: def __ini...
0.503174
0.068257
from django.db import transaction from django.utils import timezone, text from django.core.files.base import ContentFile from django.core.management.base import BaseCommand, CommandError from social_django.models import UserSocialAuth from ...models import User, Author, Thread, Post, Vote, Media from disqusapi import D...
management/commands/import_disqus.py
from django.db import transaction from django.utils import timezone, text from django.core.files.base import ContentFile from django.core.management.base import BaseCommand, CommandError from social_django.models import UserSocialAuth from ...models import User, Author, Thread, Post, Vote, Media from disqusapi import D...
0.301979
0.065665
import sys import os import time from typing import List, Tuple class IntCodeComputer(): def __init__(self, memory: List[int], inputs: List[int]): self.memory = list(memory) self.pointer = 0 self.inputs = inputs self.output = 0 self.running = True def run(self) -> int...
2019/05/py/run.py
import sys import os import time from typing import List, Tuple class IntCodeComputer(): def __init__(self, memory: List[int], inputs: List[int]): self.memory = list(memory) self.pointer = 0 self.inputs = inputs self.output = 0 self.running = True def run(self) -> int...
0.397588
0.31883
from packaging.version import Version, parse # NB: this test doesn't work for other cases because transformer tap # ratio and phase angle not supported for lpf from pypower.api import case30 as case from pypower.api import ppoption, runpf from pypower.ppver import ppver import pypsa pypower_version = parse(ppver()["...
test/test_lpf_against_pypower.py
from packaging.version import Version, parse # NB: this test doesn't work for other cases because transformer tap # ratio and phase angle not supported for lpf from pypower.api import case30 as case from pypower.api import ppoption, runpf from pypower.ppver import ppver import pypsa pypower_version = parse(ppver()["...
0.650578
0.308307
from src.Unit import Unit from src.Squad import Squad from src.PrintManager import PrintManager from src.Attack import Attack class AbstractUnit(Unit): _squad: Squad = None _health = None def __init__(self, squad): self._squad = squad self._health = squad.get_init_health() ...
src/AbstractUnit.py
from src.Unit import Unit from src.Squad import Squad from src.PrintManager import PrintManager from src.Attack import Attack class AbstractUnit(Unit): _squad: Squad = None _health = None def __init__(self, squad): self._squad = squad self._health = squad.get_init_health() ...
0.474144
0.132599
import os import xml.etree.ElementTree as ET import datasets _CITATION = """\ @article{luke2015hong, author={<NAME> and <NAME>}, title={The Hong Kong Cantonese corpus: design and uses}, journal={Journal of Chinese Linguistics}, year={2015}, pages={309-330}, month={12} } @misc{lee2020, author = {<NAME>}...
datasets/hkcancor/hkcancor.py
import os import xml.etree.ElementTree as ET import datasets _CITATION = """\ @article{luke2015hong, author={<NAME> and <NAME>}, title={The Hong Kong Cantonese corpus: design and uses}, journal={Journal of Chinese Linguistics}, year={2015}, pages={309-330}, month={12} } @misc{lee2020, author = {<NAME>}...
0.636579
0.41052
import abc import glob import logging import pathlib from typing import TYPE_CHECKING, Generator from ..defaults import Defaults, Key from ..errors import PageConfigError if TYPE_CHECKING: from .pages import PageConfig logger = logging.getLogger(__name__) class LazyMixin(abc.ABC): @property @abc.abst...
src/easel/site/pages/mixins.py
import abc import glob import logging import pathlib from typing import TYPE_CHECKING, Generator from ..defaults import Defaults, Key from ..errors import PageConfigError if TYPE_CHECKING: from .pages import PageConfig logger = logging.getLogger(__name__) class LazyMixin(abc.ABC): @property @abc.abst...
0.740925
0.138316
import hashlib import os import re import shutil import subprocess import tempfile from PIL import Image from lxml import etree from mwlib.log import Log from mwlib.pdf import utils log = Log("mwlib.pdf.html2pdf") def clean_tex(tex_src): tex_src = tex_src.lstrip().encode("utf-8") # mwlib return " " + tex...
mwlib/pdf/htmlfilters/tex.py
import hashlib import os import re import shutil import subprocess import tempfile from PIL import Image from lxml import etree from mwlib.log import Log from mwlib.pdf import utils log = Log("mwlib.pdf.html2pdf") def clean_tex(tex_src): tex_src = tex_src.lstrip().encode("utf-8") # mwlib return " " + tex...
0.27474
0.135518
import unittest import os import sys # add srcyr2lat to path so we can test locally try: from srcyr2lat import sr_cyr2lat, CYR_TO_LAT except ImportError: ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) sys.path.insert(0, ROOT) from srcyr2lat import sr_cyr2lat, CYR_TO_LAT ...
srcyr2lat/tests/__init__.py
import unittest import os import sys # add srcyr2lat to path so we can test locally try: from srcyr2lat import sr_cyr2lat, CYR_TO_LAT except ImportError: ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) sys.path.insert(0, ROOT) from srcyr2lat import sr_cyr2lat, CYR_TO_LAT ...
0.227813
0.596933
import json from django.contrib.auth.models import User from django.urls import reverse from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase from rest_framework import status from profiles.models import ProfileStatus from profiles.api.serializers import ProfileStatusSerialize...
setup_project/profiles/tests.py
import json from django.contrib.auth.models import User from django.urls import reverse from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase from rest_framework import status from profiles.models import ProfileStatus from profiles.api.serializers import ProfileStatusSerialize...
0.422862
0.137243
from django.core.mail import EmailMessage from django.core.management.base import BaseCommand, CommandError from django.template.loader import render_to_string from django.utils.translation import ugettext as _ from modoboa.admin import models as admin_models from modoboa.core.extensions import exts_pool from modoboa...
modoboa/core/management/commands/communicate_with_public_api.py
from django.core.mail import EmailMessage from django.core.management.base import BaseCommand, CommandError from django.template.loader import render_to_string from django.utils.translation import ugettext as _ from modoboa.admin import models as admin_models from modoboa.core.extensions import exts_pool from modoboa...
0.564579
0.073763
import os import matplotlib.pyplot as plt import matplotlib.image as mpimg import seaborn as sns %matplotlib inline plt.style.use('ggplot') def len_data(filename): anger_data = os.listdir(filename+'/anger') happy_data = os.listdir(filename+'/happy') sadness_data = os.listdir(filename+'/sadness') ...
preprocessing.py
import os import matplotlib.pyplot as plt import matplotlib.image as mpimg import seaborn as sns %matplotlib inline plt.style.use('ggplot') def len_data(filename): anger_data = os.listdir(filename+'/anger') happy_data = os.listdir(filename+'/happy') sadness_data = os.listdir(filename+'/sadness') ...
0.202838
0.161849
"""A basic Python 3 TCP echo server using socket module""" VERSION = "0.1" # Module imports. import os import sys import getopt import socket import signal # File name and path to this script. FILE = os.path.basename(__file__) PATH=os.path.dirname(os.path.abspath(__file__)) # Program usage. USAGE = f"""\ {FILE} vers...
python/echoserver.py
"""A basic Python 3 TCP echo server using socket module""" VERSION = "0.1" # Module imports. import os import sys import getopt import socket import signal # File name and path to this script. FILE = os.path.basename(__file__) PATH=os.path.dirname(os.path.abspath(__file__)) # Program usage. USAGE = f"""\ {FILE} vers...
0.302494
0.16388
# Standard Library Dependencies from unittest import mock # Used to fake results # Internal Dependencies from sdu.validation import * # Functionality that's being tested @mock.patch('sdu.validation.print') # Capture print() output @mock.patch('sdu.validation.input', side_effect = ["-1", "11", "5"]) # Capture i...
tests/validation_test.py
# Standard Library Dependencies from unittest import mock # Used to fake results # Internal Dependencies from sdu.validation import * # Functionality that's being tested @mock.patch('sdu.validation.print') # Capture print() output @mock.patch('sdu.validation.input', side_effect = ["-1", "11", "5"]) # Capture i...
0.921247
0.473657
import sys if '..' not in sys.path: sys.path.append('..') import argparse from lib.settings.calibration_settings_SF import * def make_calibration_parser(): parser = argparse.ArgumentParser() parser.add_argument("--seed", help="set seed") parser.add_argument("--filename", help="set filename; default ...
sim/lib/calibrate_parser_SF.py
import sys if '..' not in sys.path: sys.path.append('..') import argparse from lib.settings.calibration_settings_SF import * def make_calibration_parser(): parser = argparse.ArgumentParser() parser.add_argument("--seed", help="set seed") parser.add_argument("--filename", help="set filename; default ...
0.464659
0.152221
import unittest from unittest.mock import MagicMock from lxml import html from naotomori.cogs.source.manga.mangadex import MangaDex class TestMangaDex(unittest.TestCase): """Tests for the MangaDex""" def setUp(self): self.mangadex = MangaDex() def test_findMangaElements(self): """Test g...
test/test_mangadex.py
import unittest from unittest.mock import MagicMock from lxml import html from naotomori.cogs.source.manga.mangadex import MangaDex class TestMangaDex(unittest.TestCase): """Tests for the MangaDex""" def setUp(self): self.mangadex = MangaDex() def test_findMangaElements(self): """Test g...
0.500244
0.416737
from insights.parsers import samba_logs from insights.parsers.samba_logs import SAMBALog from insights.tests import context_wrap import doctest SAMBA_LOG_NORMAL = """ [2019/11/25 19:29:23.933547, 0] ../lib/util/become_daemon.c:138(daemon_ready) daemon_ready: STATUS=daemon 'smbd' finished starting up and ready to ser...
insights/parsers/tests/test_samba_logs.py
from insights.parsers import samba_logs from insights.parsers.samba_logs import SAMBALog from insights.tests import context_wrap import doctest SAMBA_LOG_NORMAL = """ [2019/11/25 19:29:23.933547, 0] ../lib/util/become_daemon.c:138(daemon_ready) daemon_ready: STATUS=daemon 'smbd' finished starting up and ready to ser...
0.481941
0.174059
__all__ = ['BaseContext', 'PluginManager'] import pkg_resources import logging import anyio import copy import sys from collections import namedtuple try: from contextlib import asynccontextmanager except ImportError: from async_generator import asynccontextmanager from functools import partial Plugin = na...
distmqtt/plugins/manager.py
__all__ = ['BaseContext', 'PluginManager'] import pkg_resources import logging import anyio import copy import sys from collections import namedtuple try: from contextlib import asynccontextmanager except ImportError: from async_generator import asynccontextmanager from functools import partial Plugin = na...
0.473657
0.107157
import os import sys import inspect filepath = os.path.abspath(inspect.getfile(inspect.currentframe())) currentdir = os.path.dirname(filepath) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) import constants import pandas as pd import itertools from scipy.stats import pearsonr def calculate_pea...
appyters/STEAP_post_processing_analysis/scripts/calculate_beta_correlation.py
import os import sys import inspect filepath = os.path.abspath(inspect.getfile(inspect.currentframe())) currentdir = os.path.dirname(filepath) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) import constants import pandas as pd import itertools from scipy.stats import pearsonr def calculate_pea...
0.518059
0.395718
import math import torch import random import unittest import itertools import contextlib from copy import deepcopy from itertools import repeat, product from functools import wraps import torch.nn as nn import torch.nn.functional as F import torch.nn.parallel as dp import torch.nn.utils.rnn as rnn_utils from torch.nn...
tests/test_padded_sequence.py
import math import torch import random import unittest import itertools import contextlib from copy import deepcopy from itertools import repeat, product from functools import wraps import torch.nn as nn import torch.nn.functional as F import torch.nn.parallel as dp import torch.nn.utils.rnn as rnn_utils from torch.nn...
0.779574
0.372363
from cloudify import ctx from cloudify.decorators import operation from cloudify.exceptions import NonRecoverableError from openstack_plugin_common import ( transform_resource_name, with_neutron_client, get_resource_id, is_external_resource, is_external_resource_not_conditionally_created, delet...
aria/multivim-plugin/src/main/python/multivim-plugin/neutron_plugin/network.py
from cloudify import ctx from cloudify.decorators import operation from cloudify.exceptions import NonRecoverableError from openstack_plugin_common import ( transform_resource_name, with_neutron_client, get_resource_id, is_external_resource, is_external_resource_not_conditionally_created, delet...
0.564699
0.065875
import matplotlib.pyplot as plt import params from ecm import CellDischargeData from ecm import CellTemperatureData from ecm import CellHppcData from ecm import CellEcm from ecm import ThermalModel from ecm import config_ax # Data files # ---------------------------------------------------------------------------- f...
examples/cell/discharge_vt.py
import matplotlib.pyplot as plt import params from ecm import CellDischargeData from ecm import CellTemperatureData from ecm import CellHppcData from ecm import CellEcm from ecm import ThermalModel from ecm import config_ax # Data files # ---------------------------------------------------------------------------- f...
0.505859
0.19477
# COMMAND ---------- # MAGIC %run ./configuration # COMMAND ---------- # MAGIC %md # MAGIC The csv file is provided in this repo # MAGIC import data to your databricks following this steps # MAGIC * Click the Icon "Data" in the sidebar. # MAGIC * Click the DBFS button at the top of the page. # MAGIC * Click t...
Data_Eng (1)/utilities.py
# COMMAND ---------- # MAGIC %run ./configuration # COMMAND ---------- # MAGIC %md # MAGIC The csv file is provided in this repo # MAGIC import data to your databricks following this steps # MAGIC * Click the Icon "Data" in the sidebar. # MAGIC * Click the DBFS button at the top of the page. # MAGIC * Click t...
0.411939
0.431524
from traps.abstract_trap import Coords, CoordsVar from traps.cylindrical_trap import CylindricalTrap from .abstract_penning_with_simple_electrode_trap import AbstractPenningTrapWithSimpleElectrodes from .voltage_enums import gen_voltage_enum import numpy as np _Voltages = gen_voltage_enum(0, 5) class Trappi...
traps/trapping_ring.py
from traps.abstract_trap import Coords, CoordsVar from traps.cylindrical_trap import CylindricalTrap from .abstract_penning_with_simple_electrode_trap import AbstractPenningTrapWithSimpleElectrodes from .voltage_enums import gen_voltage_enum import numpy as np _Voltages = gen_voltage_enum(0, 5) class Trappi...
0.552298
0.370852
import mobula from mobula.const import req @mobula.op.register class Conv2D: def __init__(self, channels, kernel_size, strides=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1): self.channels = channels self.kernel_size = kernel_size self.strides = strides self.padding = padding ...
opzoo/Convolution/Convolution.py
import mobula from mobula.const import req @mobula.op.register class Conv2D: def __init__(self, channels, kernel_size, strides=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1): self.channels = channels self.kernel_size = kernel_size self.strides = strides self.padding = padding ...
0.702836
0.553204
from oslo_policy import policy from cinder.policies import base GET_POLICY = "volume:get_volume_metadata" CREATE_POLICY = "volume:create_volume_metadata" DELETE_POLICY = "volume:delete_volume_metadata" UPDATE_POLICY = "volume:update_volume_metadata" IMAGE_METADATA_POLICY = "volume_extension:volume_image_metadata" IM...
cinder/policies/volume_metadata.py
from oslo_policy import policy from cinder.policies import base GET_POLICY = "volume:get_volume_metadata" CREATE_POLICY = "volume:create_volume_metadata" DELETE_POLICY = "volume:delete_volume_metadata" UPDATE_POLICY = "volume:update_volume_metadata" IMAGE_METADATA_POLICY = "volume_extension:volume_image_metadata" IM...
0.350533
0.096535
from typing import Any, Dict, List, Optional, Tuple import torch from pytorch_lightning.core.lightning import LightningModule from torch import tensor as T import torchcsprng as csprng from torchsynth import util as util from torchsynth.globals import SynthGlobals from torchsynth.module import ( ADSR, VCA, ...
torchsynth/synth.py
from typing import Any, Dict, List, Optional, Tuple import torch from pytorch_lightning.core.lightning import LightningModule from torch import tensor as T import torchcsprng as csprng from torchsynth import util as util from torchsynth.globals import SynthGlobals from torchsynth.module import ( ADSR, VCA, ...
0.948822
0.420064
from HartreeParticleDSL.c_types import c_int, c_double, c_float, c_int64_t, \ c_int32_t, c_int8_t, c_bool from HartreeParticleDSL.IO_modules.base_IO_module.IO_module import IO_Module from HartreeParticleDSL.backends.C_AOS.C_AOS import C_AOS from HartreeParticleDSL.backends.C_AOS.C...
src/HartreeParticleDSL/IO_modules/HDF5_IO/hdf5_IO.py
from HartreeParticleDSL.c_types import c_int, c_double, c_float, c_int64_t, \ c_int32_t, c_int8_t, c_bool from HartreeParticleDSL.IO_modules.base_IO_module.IO_module import IO_Module from HartreeParticleDSL.backends.C_AOS.C_AOS import C_AOS from HartreeParticleDSL.backends.C_AOS.C...
0.571527
0.209895
import itertools import spacy class JapaneseTokenizer: nlp = spacy.load("ja_ginza", disable=["JapaneseCorrector"]) def __init__(self): self._rids = [] # 捨てた単語置き場 @staticmethod def _isNum(token): return token.pos_ == "NUM" or token.like_num @staticmethod def _isSym(token): ...
JapaneseTokenizer.py
import itertools import spacy class JapaneseTokenizer: nlp = spacy.load("ja_ginza", disable=["JapaneseCorrector"]) def __init__(self): self._rids = [] # 捨てた単語置き場 @staticmethod def _isNum(token): return token.pos_ == "NUM" or token.like_num @staticmethod def _isSym(token): ...
0.473901
0.257812
__all__ = ['dipole_moment', 'dipole_moment_methods', 'dipole_moment_all_methods'] from chemicals.utils import PY37, source_path, os_path_join, can_load_data, mark_numba_incompatible from chemicals.data_reader import (register_df_source, data_source, ...
chemicals/dipole.py
__all__ = ['dipole_moment', 'dipole_moment_methods', 'dipole_moment_all_methods'] from chemicals.utils import PY37, source_path, os_path_join, can_load_data, mark_numba_incompatible from chemicals.data_reader import (register_df_source, data_source, ...
0.806205
0.281103
import os import sys import re import time import web from karesansui.lib.rest import Rest, auth from karesansui.db.access.machine import findbyhost1 from karesansui.lib.utils import get_ifconfig_info, dict_ksort, is_param from karesansui.lib.conf import read_conf, write_conf from karesansui.lib.const import FQDN_MI...
karesansui/gadget/hostby1networksettingsgeneral.py
import os import sys import re import time import web from karesansui.lib.rest import Rest, auth from karesansui.db.access.machine import findbyhost1 from karesansui.lib.utils import get_ifconfig_info, dict_ksort, is_param from karesansui.lib.conf import read_conf, write_conf from karesansui.lib.const import FQDN_MI...
0.308503
0.067056
"""Client and server classes corresponding to protobuf-defined services.""" import grpc from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 from spaceone.api.secret.v1 import secret_group_pb2 as spaceone_dot_api_dot_s...
venv/lib/python3.8/site-packages/spaceone/api/secret/v1/secret_group_pb2_grpc.py
"""Client and server classes corresponding to protobuf-defined services.""" import grpc from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 from spaceone.api.secret.v1 import secret_group_pb2 as spaceone_dot_api_dot_s...
0.670177
0.081556
import pytest from schemaperfect import SchemaBase, SchemaModuleGenerator @pytest.fixture def schema(): return { 'definitions': { 'Person': { 'properties': { 'name': {'type': 'string'}, 'age': {'type': 'integer'}, } ...
schemaperfect/tests/test_codegen.py
import pytest from schemaperfect import SchemaBase, SchemaModuleGenerator @pytest.fixture def schema(): return { 'definitions': { 'Person': { 'properties': { 'name': {'type': 'string'}, 'age': {'type': 'integer'}, } ...
0.670393
0.528898
import networkx as nx import matplotlib.pyplot as plt from networkx.readwrite.json_graph import tree import pydot import pymetis from networkx.drawing.nx_pydot import to_pydot from spydrnet_physical.util import (prepare_graph_from_nx, run_metis, write_metis_graph) # = = = = = = = = ...
examples/basic/partitioning_experiments.py
import networkx as nx import matplotlib.pyplot as plt from networkx.readwrite.json_graph import tree import pydot import pymetis from networkx.drawing.nx_pydot import to_pydot from spydrnet_physical.util import (prepare_graph_from_nx, run_metis, write_metis_graph) # = = = = = = = = ...
0.455441
0.350032
"""Tests for evaluating preprocessing.""" import unittest from typing import List import preprocess class TestPreprocess(unittest.TestCase): """Tests for evaluating preprocess.py.""" def test_preprocess_ud(self): 'Test loading in a ud data file.' infile = "testdata/test_wo_ud_input.txt" ...
preprocess_test.py
"""Tests for evaluating preprocessing.""" import unittest from typing import List import preprocess class TestPreprocess(unittest.TestCase): """Tests for evaluating preprocess.py.""" def test_preprocess_ud(self): 'Test loading in a ud data file.' infile = "testdata/test_wo_ud_input.txt" ...
0.589007
0.564519
# Uncomment this to still load settings configured via autoconfig.yml # config.load_autoconfig() config.bind('<Ctrl-1>', 'tab-focus 1') config.bind('<Ctrl-2>', 'tab-focus 2') config.bind('<Ctrl-3>', 'tab-focus 3') config.bind('<Ctrl-4>', 'tab-focus 4') config.bind('<Ctrl-5>', 'tab-focus 5') config.bind('<Ctrl-6>', 't...
.config/qutebrowser/config.py
# Uncomment this to still load settings configured via autoconfig.yml # config.load_autoconfig() config.bind('<Ctrl-1>', 'tab-focus 1') config.bind('<Ctrl-2>', 'tab-focus 2') config.bind('<Ctrl-3>', 'tab-focus 3') config.bind('<Ctrl-4>', 'tab-focus 4') config.bind('<Ctrl-5>', 'tab-focus 5') config.bind('<Ctrl-6>', 't...
0.647241
0.06357