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 os.path
import tensorflow as tf
from tensorflow import flags
import datasets
flags.DEFINE_integer('epochs', -1,
'Epochs of training data, or -1 to continue indefinitely.')
flags.DEFINE_integer('image_height', 256, 'Image height in pixels.')
flags.DEFINE_integer('image_width', 256, 'Image w... | stereomag/loader.py | import os.path
import tensorflow as tf
from tensorflow import flags
import datasets
flags.DEFINE_integer('epochs', -1,
'Epochs of training data, or -1 to continue indefinitely.')
flags.DEFINE_integer('image_height', 256, 'Image height in pixels.')
flags.DEFINE_integer('image_width', 256, 'Image w... | 0.883374 | 0.409162 |
import torch
import torch.nn as nn
from alibi.models.pytorch.model import Model
from typing import List, Union
class AE(Model):
"""
Autoencoder. Standard autoencoder architecture. The model is composed from two submodules, the encoder and
the decoder. The forward pass consist of passing the input to the ... | alibi/models/pytorch/autoencoder.py | import torch
import torch.nn as nn
from alibi.models.pytorch.model import Model
from typing import List, Union
class AE(Model):
"""
Autoencoder. Standard autoencoder architecture. The model is composed from two submodules, the encoder and
the decoder. The forward pass consist of passing the input to the ... | 0.941203 | 0.712432 |
import enum
from itertools import groupby
from typing import List, Optional
from opentrons.hardware_control.types import BoardRevision
class PinDir(enum.Enum):
rev_input = enum.auto()
input = enum.auto()
output = enum.auto()
class GPIOPin:
@classmethod
def build(cls, name: str, in_out: PinDir, ... | api/src/opentrons/drivers/rpi_drivers/types.py | import enum
from itertools import groupby
from typing import List, Optional
from opentrons.hardware_control.types import BoardRevision
class PinDir(enum.Enum):
rev_input = enum.auto()
input = enum.auto()
output = enum.auto()
class GPIOPin:
@classmethod
def build(cls, name: str, in_out: PinDir, ... | 0.816333 | 0.179279 |
from pymongo import MongoClient
import psycopg2
from pprint import pprint
import os
class MongoDbConnection:
def __init__(self):
self.mongo()
def mongo(self):
try:
if os.environ['OUTSIDE_NETWORK'] == '1':
self.host = 'localhost'
self.port = 5550
... | analysis/DataSourceSlim.py | from pymongo import MongoClient
import psycopg2
from pprint import pprint
import os
class MongoDbConnection:
def __init__(self):
self.mongo()
def mongo(self):
try:
if os.environ['OUTSIDE_NETWORK'] == '1':
self.host = 'localhost'
self.port = 5550
... | 0.291989 | 0.087058 |
import numpy as np
import pytest
import xarray as xr
import zarr
import xsimlab as xs
from xsimlab.stores import DummyLock, ZarrSimulationStore
from zarr.util import object_codecs
@pytest.fixture(params=["directory", zarr.MemoryStore])
def zobject(request, tmpdir):
if request.param == "directory":
return... | xsimlab/tests/test_stores.py | import numpy as np
import pytest
import xarray as xr
import zarr
import xsimlab as xs
from xsimlab.stores import DummyLock, ZarrSimulationStore
from zarr.util import object_codecs
@pytest.fixture(params=["directory", zarr.MemoryStore])
def zobject(request, tmpdir):
if request.param == "directory":
return... | 0.516352 | 0.555918 |
import grpc
import pytest
from google.protobuf import empty_pb2
from couchers import errors
from couchers.models import User
from proto import api_pb2
from tests.test_fixtures import ( # noqa
api_session,
db,
generate_user,
make_friends,
make_user_block,
make_user_invisible,
session_scope,... | app/backend/src/tests/test_visible_users.py | import grpc
import pytest
from google.protobuf import empty_pb2
from couchers import errors
from couchers.models import User
from proto import api_pb2
from tests.test_fixtures import ( # noqa
api_session,
db,
generate_user,
make_friends,
make_user_block,
make_user_invisible,
session_scope,... | 0.355104 | 0.3358 |
import datetime
from sqlalchemy import (
Integer,
String,
DateTime,
Boolean,
event,
)
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from temboardui.model import tables
Model = declarative_base()
def validate_int(value):
if value is None:
... | temboardui/model/orm.py | import datetime
from sqlalchemy import (
Integer,
String,
DateTime,
Boolean,
event,
)
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from temboardui.model import tables
Model = declarative_base()
def validate_int(value):
if value is None:
... | 0.498291 | 0.361982 |
from timeit import default_timer
import pandas
from sklearn import preprocessing
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.metrics import plot_confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.prepr... | src/ann.py | from timeit import default_timer
import pandas
from sklearn import preprocessing
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.metrics import plot_confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.prepr... | 0.7181 | 0.497315 |
"""Adding implementation tests
"""
from zope.testing import renormalizing
import re
import doctest
import unittest
import zope.interface
import zope.security.checker
from zope.browsermenu.interfaces import AddMenu
from zope.browsermenu.interfaces import IMenuItemType, IBrowserMenu
from zope.component.interfaces import... | src/zope/app/container/browser/tests/test_adding.py | """Adding implementation tests
"""
from zope.testing import renormalizing
import re
import doctest
import unittest
import zope.interface
import zope.security.checker
from zope.browsermenu.interfaces import AddMenu
from zope.browsermenu.interfaces import IMenuItemType, IBrowserMenu
from zope.component.interfaces import... | 0.643777 | 0.247476 |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# M... | vega/algorithms/nas/modnas/contrib/callback/metrics_stats.py |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# M... | 0.912341 | 0.161949 |
from phanterpwa.tools import interpolate, sass_change_vars, sass_map_vars
from phanterpwa.third_parties.xss import xssescape
from phanterpwa.i18n import Translator
from xml.sax import saxutils
import json
from copy import copy
import os
import re
__all__ = ["XmlConstructor"]
XML_SAMPLE = '''class XML(XmlConstructor, ... | phanterpwa/xmlconstructor.py | from phanterpwa.tools import interpolate, sass_change_vars, sass_map_vars
from phanterpwa.third_parties.xss import xssescape
from phanterpwa.i18n import Translator
from xml.sax import saxutils
import json
from copy import copy
import os
import re
__all__ = ["XmlConstructor"]
XML_SAMPLE = '''class XML(XmlConstructor, ... | 0.586641 | 0.081593 |
import pymongo
from pymongo import Connection
from xml.sax.saxutils import escape
import re
class OsmApi:
def __init__(self):
self.client = Connection()
def getNodesQuery(self, query):
cursor = self.client.osm.nodes.find(query)
nodes = {}
for row in cursor:
nodes[r... | map_server.py | import pymongo
from pymongo import Connection
from xml.sax.saxutils import escape
import re
class OsmApi:
def __init__(self):
self.client = Connection()
def getNodesQuery(self, query):
cursor = self.client.osm.nodes.find(query)
nodes = {}
for row in cursor:
nodes[r... | 0.244634 | 0.266367 |
import socket
import os
realpit = []
shadowpit = []
depth = []
def changeplayer():
if player == 1:
player = 2
elif:
player = 1
def choose(x, player, pit = []):
if pit[x] or x==13 or x=6:
pass
else:
hold = pit[x]
now = x
pit[x] = 0
while 1:
now += 1
now = now%14
if player == 1 and now==13:
... | resources/views/user/client.py | import socket
import os
realpit = []
shadowpit = []
depth = []
def changeplayer():
if player == 1:
player = 2
elif:
player = 1
def choose(x, player, pit = []):
if pit[x] or x==13 or x=6:
pass
else:
hold = pit[x]
now = x
pit[x] = 0
while 1:
now += 1
now = now%14
if player == 1 and now==13:
... | 0.014427 | 0.210097 |
import unittest
import pyspark
from pyspark.sql import SQLContext
from pyspark.sql import SparkSession
from pyspark.sql.functions import desc
from mock import patch, MagicMock
from src.ExtractCCLinks import CCLinks
import shutil
import os.path
import botocore
import json
from io import StringIO
import types
class Wa... | tests/test_ExtractCCLinks.py |
import unittest
import pyspark
from pyspark.sql import SQLContext
from pyspark.sql import SparkSession
from pyspark.sql.functions import desc
from mock import patch, MagicMock
from src.ExtractCCLinks import CCLinks
import shutil
import os.path
import botocore
import json
from io import StringIO
import types
class Wa... | 0.299925 | 0.169664 |
LS_KEY_TYPE = "type"
LS_KEY_EXPIRES = "expires"
LS_KEY_TTL = "ttl"
LS_KEY_URI = "uri"
LS_KEY_STATE = "state"
#Type Values
LS_VALUE_TYPE_SERVICE = "service"
LS_VALUE_TYPE_HOST = "host"
LS_VALUE_TYPE_INTERFACE = "interface"
LS_VALUE_TYPE_PERSON = "person"
#State Values
LS_VALUE_STATE = ["registered", "renewed", "delete... | sls_client/constants.py | LS_KEY_TYPE = "type"
LS_KEY_EXPIRES = "expires"
LS_KEY_TTL = "ttl"
LS_KEY_URI = "uri"
LS_KEY_STATE = "state"
#Type Values
LS_VALUE_TYPE_SERVICE = "service"
LS_VALUE_TYPE_HOST = "host"
LS_VALUE_TYPE_INTERFACE = "interface"
LS_VALUE_TYPE_PERSON = "person"
#State Values
LS_VALUE_STATE = ["registered", "renewed", "delete... | 0.37777 | 0.039676 |
import pandas as pd
import numpy as np
import torch
import re
import os
import spacy
from scipy import spatial
import csv
import sys
from unidecode import unidecode
from collections import defaultdict
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorize... | tfidf.calculation_cases.py |
import pandas as pd
import numpy as np
import torch
import re
import os
import spacy
from scipy import spatial
import csv
import sys
from unidecode import unidecode
from collections import defaultdict
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorize... | 0.134122 | 0.189915 |
import glob
import os
import shutil
from universal_build import build_utils
HERE = os.path.abspath(os.path.dirname(__file__))
REACT_WEBAPP_COMPONENT = "react-webapp"
DOCS_COMPONENT = "docs"
PYTHON_LIB_COMPONENT = "python-lib"
DOCKER_COMPONENT = "docker"
def main(args: dict) -> None:
"""Execute all component bu... | examples/build.py | import glob
import os
import shutil
from universal_build import build_utils
HERE = os.path.abspath(os.path.dirname(__file__))
REACT_WEBAPP_COMPONENT = "react-webapp"
DOCS_COMPONENT = "docs"
PYTHON_LIB_COMPONENT = "python-lib"
DOCKER_COMPONENT = "docker"
def main(args: dict) -> None:
"""Execute all component bu... | 0.352536 | 0.046616 |
from hypernlp.framework_config import Config
if Config.framework == 'tensorflow':
import tensorflow as tf
from tensorflow.keras import backend as K
elif Config.framework == 'pytorch':
import torch.nn as nn
import torch
else:
raise TypeError("Unsupported framework: '{}'".format(Config.framework))
d... | hypernlp/nlp/tools/loss.py | from hypernlp.framework_config import Config
if Config.framework == 'tensorflow':
import tensorflow as tf
from tensorflow.keras import backend as K
elif Config.framework == 'pytorch':
import torch.nn as nn
import torch
else:
raise TypeError("Unsupported framework: '{}'".format(Config.framework))
d... | 0.768386 | 0.349588 |
import argparse
import sys
import pymapd
from heavy.thrift.ttypes import TDashboard
def getOptions(args=None):
parser = argparse.ArgumentParser(description='Basic benchmark for system tables')
parser.add_argument('--host', help='OmniSci server address', default='localhost')
parser.add_argument('--port', h... | Benchmarks/scripts/bench_system_tables.py | import argparse
import sys
import pymapd
from heavy.thrift.ttypes import TDashboard
def getOptions(args=None):
parser = argparse.ArgumentParser(description='Basic benchmark for system tables')
parser.add_argument('--host', help='OmniSci server address', default='localhost')
parser.add_argument('--port', h... | 0.331012 | 0.075824 |
import json
from alipay.aop.api.constant.ParamConstants import *
class AnttechOceanbaseTestplatformTaskQueryModel(object):
def __init__(self):
self._end_time = None
self._palyer = None
self._run_task_retry = None
self._run_task_time_out_minutes = None
self._start_time = N... | alipay/aop/api/domain/AnttechOceanbaseTestplatformTaskQueryModel.py | import json
from alipay.aop.api.constant.ParamConstants import *
class AnttechOceanbaseTestplatformTaskQueryModel(object):
def __init__(self):
self._end_time = None
self._palyer = None
self._run_task_retry = None
self._run_task_time_out_minutes = None
self._start_time = N... | 0.459076 | 0.222616 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import argparse
import model
import math
import numpy as np
import sys
def word_drop(model, batch, y_preds, num_classes, device):
inputs = batch[0]
losses = torch.zeros(inputs.shape)
target = None
... | src/attacks/word_bug/scoring.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import argparse
import model
import math
import numpy as np
import sys
def word_drop(model, batch, y_preds, num_classes, device):
inputs = batch[0]
losses = torch.zeros(inputs.shape)
target = None
... | 0.598312 | 0.444987 |
import pandas as pd
import numpy as np
import re
f1 = pd.read_table("gene.gff3",sep="\t",header=None)
df1 = pd.DataFrame(f1)
df1.columns = ['chr','Database','feature','start','end','label1','strand','label2','info']
##根据feature的列提取含有gene的字符串
df1_gene = df1[df1['feature'].str.contains('gene')]
####基因区域
df1_gene = df1... | GeneFeature.py | import pandas as pd
import numpy as np
import re
f1 = pd.read_table("gene.gff3",sep="\t",header=None)
df1 = pd.DataFrame(f1)
df1.columns = ['chr','Database','feature','start','end','label1','strand','label2','info']
##根据feature的列提取含有gene的字符串
df1_gene = df1[df1['feature'].str.contains('gene')]
####基因区域
df1_gene = df1... | 0.154058 | 0.272384 |
import features
import datetime
get_element = features.get_element # parser
class Event:
def __init__(self, e_id: int, title='', last_news_date='', last_news_title='', calendar='', next_round_title='',
next_round_date='', status='', last_update=datetime.datetime.now()):
"""
Info... | scrapper.py | import features
import datetime
get_element = features.get_element # parser
class Event:
def __init__(self, e_id: int, title='', last_news_date='', last_news_title='', calendar='', next_round_title='',
next_round_date='', status='', last_update=datetime.datetime.now()):
"""
Info... | 0.765418 | 0.258932 |
import tornado.web
from consoleme.config import config
from consoleme.lib.plugins import get_plugin_by_name
log = config.get_logger("consoleme")
stats = get_plugin_by_name(config.get("plugins.metrics"))()
class BaseException(Exception):
def __init__(self, msg: str = "") -> None:
self.msg = msg
l... | consoleme/exceptions/exceptions.py | import tornado.web
from consoleme.config import config
from consoleme.lib.plugins import get_plugin_by_name
log = config.get_logger("consoleme")
stats = get_plugin_by_name(config.get("plugins.metrics"))()
class BaseException(Exception):
def __init__(self, msg: str = "") -> None:
self.msg = msg
l... | 0.629091 | 0.054929 |
from quixstreaming import StreamingClient, ParameterData, StreamEndType, StreamReader
import threading
import signal
import pandas as pd
import time
# Create a client. Client helps you to create input reader or output writer for specified topic.
client = QuixStreamingClient('{placeholder:token}')
# Change consumer gr... | python/model/Data-Filtering/main.py | from quixstreaming import StreamingClient, ParameterData, StreamEndType, StreamReader
import threading
import signal
import pandas as pd
import time
# Create a client. Client helps you to create input reader or output writer for specified topic.
client = QuixStreamingClient('{placeholder:token}')
# Change consumer gr... | 0.511961 | 0.229104 |
import webbrowser
import os
import re
import csv
def load_templates(path):
with open(path, 'r') as content_file:
return content_file.read()
def get_movies(filename):
movies = []
with open(filename, 'rU') as csvfile:
reader = csv.DictReader(csvfile)
for movie in reader:
... | p1/MovieTrailerWebsite.py | import webbrowser
import os
import re
import csv
def load_templates(path):
with open(path, 'r') as content_file:
return content_file.read()
def get_movies(filename):
movies = []
with open(filename, 'rU') as csvfile:
reader = csv.DictReader(csvfile)
for movie in reader:
... | 0.365343 | 0.093595 |
from __future__ import annotations
import typing as ty
import pygame as pg
from loguru import logger
from .label import Label
from ..anchor import Anchor
from ..events import ButtonClickEvent
if ty.TYPE_CHECKING:
from ..types import CordFunction, ButtonCallback
from ..group import Group
class Button(Label... | DOM/base/widgets/button.py | from __future__ import annotations
import typing as ty
import pygame as pg
from loguru import logger
from .label import Label
from ..anchor import Anchor
from ..events import ButtonClickEvent
if ty.TYPE_CHECKING:
from ..types import CordFunction, ButtonCallback
from ..group import Group
class Button(Label... | 0.739705 | 0.283447 |
from __future__ import division
import numpy as np
import rxcs
class randMult(rxcs._RxCSobject):
def __init__(self, *args):
rxcs._RxCSobject.__init__(self) # Make it a RxCS object
self.strRxCSgroup = 'Signal generator' # Name of group of RxCS modules
self.strModuleName = 'Ra... | rxcs/sig/randMult.py | from __future__ import division
import numpy as np
import rxcs
class randMult(rxcs._RxCSobject):
def __init__(self, *args):
rxcs._RxCSobject.__init__(self) # Make it a RxCS object
self.strRxCSgroup = 'Signal generator' # Name of group of RxCS modules
self.strModuleName = 'Ra... | 0.774967 | 0.499207 |
# readinglistsort.py: A simple Python app that allows you to quickly sort a long reading list so that the books you're most interested in end up on top. To make this work, replace the variable 'readingListFile' with the location of your reading list text file.
import random
from pathlib import Path
import pyautogui
... | readingListSort.py |
# readinglistsort.py: A simple Python app that allows you to quickly sort a long reading list so that the books you're most interested in end up on top. To make this work, replace the variable 'readingListFile' with the location of your reading list text file.
import random
from pathlib import Path
import pyautogui
... | 0.305076 | 0.412353 |
import numpy as np
import theano as theano
import theano.tensor as T
from theano.gradient import grad_clip
from theano.compile.debugmode import DebugMode
import time
import operator
import layers
import data
import constants
import arguments
import util
args = arguments.parse()
token2index, index2token = data.load_m... | model.py | import numpy as np
import theano as theano
import theano.tensor as T
from theano.gradient import grad_clip
from theano.compile.debugmode import DebugMode
import time
import operator
import layers
import data
import constants
import arguments
import util
args = arguments.parse()
token2index, index2token = data.load_m... | 0.66769 | 0.288929 |
import requests
import json
from janda.utils.parser import *
BASE_URL = Api()
class Pururin(object):
"""Pururin API wrapper
Methods
-------
get: function
Gets doujin from id
get_random: function
Gets random doujin
search: function
Searches doujin by tags / artist / ... | janda/pururin.py | import requests
import json
from janda.utils.parser import *
BASE_URL = Api()
class Pururin(object):
"""Pururin API wrapper
Methods
-------
get: function
Gets doujin from id
get_random: function
Gets random doujin
search: function
Searches doujin by tags / artist / ... | 0.807499 | 0.282951 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('brownbags', '0002_auto_20200415_0146'),
]
operations = [
migrations.AddField(
model_name='shop',
name='category_sel',
f... | brownbags/migrations/0003_auto_20200418_0040.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('brownbags', '0002_auto_20200415_0146'),
]
operations = [
migrations.AddField(
model_name='shop',
name='category_sel',
f... | 0.435421 | 0.101411 |
import os
import re
from collections import OrderedDict
import savu.plugins.utils as pu
import doc.create_plugin_doc as pdoc
def create_plugin_template_downloads(savu_base_path):
"""Inside plugin_examples/plugin_templates/general
If the file begins with 'plugin_template' then select it
Read the lines of... | doc/create_plugin_template_doc.py | import os
import re
from collections import OrderedDict
import savu.plugins.utils as pu
import doc.create_plugin_doc as pdoc
def create_plugin_template_downloads(savu_base_path):
"""Inside plugin_examples/plugin_templates/general
If the file begins with 'plugin_template' then select it
Read the lines of... | 0.532425 | 0.2027 |
apiAttachAvailable = u'API forefindes'
apiAttachNotAvailable = u'Optaget'
apiAttachPendingAuthorization = u'Afventer godkendelse'
apiAttachRefused = u'Afvist'
apiAttachSuccess = u'Succes'
apiAttachUnknown = u'Ukendt'
budDeletedFriend = u'Slettet fra liste over kontaktpersoner'
budFriend = u'Ven'
budNeverBeenFriend = u'... | Skype4Py/lang/da.py | apiAttachAvailable = u'API forefindes'
apiAttachNotAvailable = u'Optaget'
apiAttachPendingAuthorization = u'Afventer godkendelse'
apiAttachRefused = u'Afvist'
apiAttachSuccess = u'Succes'
apiAttachUnknown = u'Ukendt'
budDeletedFriend = u'Slettet fra liste over kontaktpersoner'
budFriend = u'Ven'
budNeverBeenFriend = u'... | 0.138171 | 0.048858 |
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class GlanceCreateImageMetadataRequestBody:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The k... | huaweicloud-sdk-ims/huaweicloudsdkims/v2/model/glance_create_image_metadata_request_body.py |
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class GlanceCreateImageMetadataRequestBody:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The k... | 0.478285 | 0.109325 |
import sys
import os
import shutil
import gluon.contrib.simplejson
from datetime import datetime
sys.path.append(os.path.abspath('./../'))
from modules import fflock_globals
from modules import fflock_utility
master_color = "#317b80"
storage_color = "#609194"
warning_color = "#DD0000"
slave_color = "#92dce0"
busy_col... | web2py/applications/fflock/controllers/default.py |
import sys
import os
import shutil
import gluon.contrib.simplejson
from datetime import datetime
sys.path.append(os.path.abspath('./../'))
from modules import fflock_globals
from modules import fflock_utility
master_color = "#317b80"
storage_color = "#609194"
warning_color = "#DD0000"
slave_color = "#92dce0"
busy_col... | 0.231267 | 0.15393 |
"""Tests for wikigraphs.data.paired_dataset."""
from absl.testing import absltest
from wikigraphs.data import io_tools
from wikigraphs.data import paired_dataset
from wikigraphs.data import tokenizers
from wikigraphs.data import wikitext
WIKITEXT_ROOT = '/tmp/data/wikitext-103'
WIKIGRAPHS_ROOT = '/tmp/data/wikigraph... | wikigraphs/wikigraphs/data/paired_dataset_test.py | """Tests for wikigraphs.data.paired_dataset."""
from absl.testing import absltest
from wikigraphs.data import io_tools
from wikigraphs.data import paired_dataset
from wikigraphs.data import tokenizers
from wikigraphs.data import wikitext
WIKITEXT_ROOT = '/tmp/data/wikitext-103'
WIKIGRAPHS_ROOT = '/tmp/data/wikigraph... | 0.755186 | 0.572125 |
import sys
import aiohttp
import ReSpider.setting as setting
from ReSpider.http import Response
from ReSpider.extend.logger import LogMixin
from ._ssl import SSLFactory
if sys.version_info >= (3, 8):
from asyncio.exceptions import TimeoutError
else:
from asyncio import TimeoutError
sslgen = SSLFac... | ReSpider/core/downloader/handlers.py |
import sys
import aiohttp
import ReSpider.setting as setting
from ReSpider.http import Response
from ReSpider.extend.logger import LogMixin
from ._ssl import SSLFactory
if sys.version_info >= (3, 8):
from asyncio.exceptions import TimeoutError
else:
from asyncio import TimeoutError
sslgen = SSLFac... | 0.297266 | 0.049704 |
import os
from absl.testing import absltest
from note_seq import encoder_decoder
from note_seq.protobuf import compare
from note_seq.protobuf import music_pb2
from google.protobuf import descriptor_pool
from google.protobuf import text_format
# Shortcut to text annotation types.
BEAT = music_pb2.NoteSequence.TextAn... | note_seq/testing_lib.py | import os
from absl.testing import absltest
from note_seq import encoder_decoder
from note_seq.protobuf import compare
from note_seq.protobuf import music_pb2
from google.protobuf import descriptor_pool
from google.protobuf import text_format
# Shortcut to text annotation types.
BEAT = music_pb2.NoteSequence.TextAn... | 0.729809 | 0.47171 |
import sys
import math
from PyQt5 import QtCore, QtGui, QtWidgets
from sectograph import resources, entities, datetime as dt # FONT_ADJUST
FONT_ADJUST = 0 if sys.platform == "darwin" else -4
class DayEvent(QtWidgets.QWidget):
def __init__(
self,
parent: QtWidgets.QWidget,
theme: resourc... | sectograph/widgets/day_event.py | import sys
import math
from PyQt5 import QtCore, QtGui, QtWidgets
from sectograph import resources, entities, datetime as dt # FONT_ADJUST
FONT_ADJUST = 0 if sys.platform == "darwin" else -4
class DayEvent(QtWidgets.QWidget):
def __init__(
self,
parent: QtWidgets.QWidget,
theme: resourc... | 0.27338 | 0.104204 |
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from matplotlib import pyplot
from sklearn.mo... | Week 13 - RNN & LSTM/prediction.py | import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from matplotlib import pyplot
from sklearn.mo... | 0.357568 | 0.342159 |
import json
from datetime import datetime, timedelta
import pytz
from django.urls import reverse
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from helium.auth.tasks import expire_auth_tokens
from helium.auth.tests.helpers import userhe... | helium/auth/tests/testcasetasks.py | import json
from datetime import datetime, timedelta
import pytz
from django.urls import reverse
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from helium.auth.tasks import expire_auth_tokens
from helium.auth.tests.helpers import userhe... | 0.371821 | 0.118436 |
from tests.chart_tests.helm_template_generator import render_chart
import pytest
from tests import supported_k8s_versions, get_containers_by_name
@pytest.mark.parametrize(
"kube_version",
supported_k8s_versions,
)
class TestPrometheusNodeExporterDaemonset:
def test_prometheus_node_exporter_service_default... | tests/chart_tests/test_prometheus_node_exporter.py | from tests.chart_tests.helm_template_generator import render_chart
import pytest
from tests import supported_k8s_versions, get_containers_by_name
@pytest.mark.parametrize(
"kube_version",
supported_k8s_versions,
)
class TestPrometheusNodeExporterDaemonset:
def test_prometheus_node_exporter_service_default... | 0.752922 | 0.393269 |
import BFS
import Medium
from Bipartite import isBipartite
from UnionFind import UnionFind
from StrongConnectivity import StronglyConnectedComponents
from Graphs import isUndirected
import unittest
def PartialCubeEdgeLabeling(G):
"""
Label edges of G by their equivalence classes in a partial cube structure.
... | PartialCube.py | import BFS
import Medium
from Bipartite import isBipartite
from UnionFind import UnionFind
from StrongConnectivity import StronglyConnectedComponents
from Graphs import isUndirected
import unittest
def PartialCubeEdgeLabeling(G):
"""
Label edges of G by their equivalence classes in a partial cube structure.
... | 0.645679 | 0.624007 |
import unittest
from tests.tf_test_common import ConvNetMaker
from tf_blade.gpu.tf_to_trt import Tf2TrtOpt
from tf_blade.util.tf_conversion_util import TRT_SUPPORTED_LIST
from tf_blade.util.tf_import_helper import tf
tf.disable_v2_behavior()
class Tf2TrtPlusTest(unittest.TestCase):
def setUp(self) -> None:
... | tensorflow_blade/tests/gpu/tf_to_trt_test.py |
import unittest
from tests.tf_test_common import ConvNetMaker
from tf_blade.gpu.tf_to_trt import Tf2TrtOpt
from tf_blade.util.tf_conversion_util import TRT_SUPPORTED_LIST
from tf_blade.util.tf_import_helper import tf
tf.disable_v2_behavior()
class Tf2TrtPlusTest(unittest.TestCase):
def setUp(self) -> None:
... | 0.608478 | 0.431165 |
import logging
import traceback
from sqlalchemy.sql import select
from database import get_engine, engine_disposal, ionosphere_table_meta
# @added 20210426 - Feature #4014: Ionosphere - inference
# Add a global method to query the DB for enabled (or disabled) features
# profiles from the ionosphere table row
def g... | skyline/functions/database/queries/get_ionosphere_fp_ids_for_full_duration.py | import logging
import traceback
from sqlalchemy.sql import select
from database import get_engine, engine_disposal, ionosphere_table_meta
# @added 20210426 - Feature #4014: Ionosphere - inference
# Add a global method to query the DB for enabled (or disabled) features
# profiles from the ionosphere table row
def g... | 0.576542 | 0.126353 |
import InstrumentDriver
from VISA_Driver import VISA_Driver
import visa
from InstrumentConfig import InstrumentQuantity
import numpy as np
import string
__version__ = "0.0.1"
class Error(Exception):
pass
class Driver(VISA_Driver):
""" This class implements the Triton 200 driver"""
def performOpen(sel... | Oxford IPS120/Oxford IPS120.py |
import InstrumentDriver
from VISA_Driver import VISA_Driver
import visa
from InstrumentConfig import InstrumentQuantity
import numpy as np
import string
__version__ = "0.0.1"
class Error(Exception):
pass
class Driver(VISA_Driver):
""" This class implements the Triton 200 driver"""
def performOpen(sel... | 0.536556 | 0.159675 |
"""
Copyright 2019 Datacom Systems Limited
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 ag... | src/datacom_dns_azure/dns_azure.py | """
Copyright 2019 Datacom Systems Limited
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 ag... | 0.868213 | 0.247578 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(primary_key=True, verbose_n... | emassage/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(primary_key=True, verbose_n... | 0.669529 | 0.219902 |
import json
from django.core import management
from allegation.tests.views.base import OfficerAllegationApiTestBase
from allegation.factories import (
OfficerFactory, OfficerAllegationFactory)
class OfficerAllegationOfficerApiTestCase(OfficerAllegationApiTestBase):
def test_response_format(self):
res... | allegation/tests/views/test_officer_allegation_officer_api_view.py | import json
from django.core import management
from allegation.tests.views.base import OfficerAllegationApiTestBase
from allegation.factories import (
OfficerFactory, OfficerAllegationFactory)
class OfficerAllegationOfficerApiTestCase(OfficerAllegationApiTestBase):
def test_response_format(self):
res... | 0.3512 | 0.135403 |
class CompactSet:
def __init__(self, numbers = None, bits = None):
self.bits = bits or 0
if numbers:
for n in numbers:
self.add(n)
def add(self, n):
self.bits |= 1 << n
def remove(self, n):
self.bits &= ~(1 << n)
def clear(self):
... | recipes/Python/577660_Representing_set_compact/recipe-577660.py | class CompactSet:
def __init__(self, numbers = None, bits = None):
self.bits = bits or 0
if numbers:
for n in numbers:
self.add(n)
def add(self, n):
self.bits |= 1 << n
def remove(self, n):
self.bits &= ~(1 << n)
def clear(self):
... | 0.7237 | 0.429728 |
import json
import os
import sys
import tempfile
from copy import deepcopy
from pathlib import Path
import pytest
from pytest import approx
from nncf import NNCFConfig
from tests.common.helpers import PROJECT_ROOT
from tests.common.helpers import TEST_ROOT
from tests.common.helpers import get_cli_dict_args
from tests... | tests/torch/test_compression_training.py | import json
import os
import sys
import tempfile
from copy import deepcopy
from pathlib import Path
import pytest
from pytest import approx
from nncf import NNCFConfig
from tests.common.helpers import PROJECT_ROOT
from tests.common.helpers import TEST_ROOT
from tests.common.helpers import get_cli_dict_args
from tests... | 0.534127 | 0.197097 |
from sirius_sdk.agent.aries_rfc.base import AriesProtocolMessage, RegisterMessage
from typing import List, Union
class CoordinateMediationMessage(AriesProtocolMessage, metaclass=RegisterMessage):
"""Aries feature 0211 Message implementation
https://github.com/hyperledger/aries-rfcs/blob/master/features/0211-... | sirius_sdk/agent/aries_rfc/feature_0211_mediator_coordination_protocol/messages.py | from sirius_sdk.agent.aries_rfc.base import AriesProtocolMessage, RegisterMessage
from typing import List, Union
class CoordinateMediationMessage(AriesProtocolMessage, metaclass=RegisterMessage):
"""Aries feature 0211 Message implementation
https://github.com/hyperledger/aries-rfcs/blob/master/features/0211-... | 0.791861 | 0.176317 |
from datetime import date
todays_date = date.today()
print(todays_date)
print(todays_date.month, todays_date.day, todays_date.year)
print(todays_date.weekday())
# ISO format is a string format, yyyy-mm-dd
# ---------------------------
# date_object.isoformat() does the same thing as str(date_object)
from datetime i... | Python Programming/08. Python Standard Library/Date_Time_Timestamp.py |
from datetime import date
todays_date = date.today()
print(todays_date)
print(todays_date.month, todays_date.day, todays_date.year)
print(todays_date.weekday())
# ISO format is a string format, yyyy-mm-dd
# ---------------------------
# date_object.isoformat() does the same thing as str(date_object)
from datetime i... | 0.68637 | 0.266602 |
from numpy import log2
from copy import deepcopy
from utils import *
from . import bot_utils
from .dialog_management_components import *
from . import config as cfg
from . import entity_checker
from .actions.ActionFactory import ActionFactory
from .actions import confirmation_requests as confirm
from .actions.Action... | src/DialogManager.py |
from numpy import log2
from copy import deepcopy
from utils import *
from . import bot_utils
from .dialog_management_components import *
from . import config as cfg
from . import entity_checker
from .actions.ActionFactory import ActionFactory
from .actions import confirmation_requests as confirm
from .actions.Action... | 0.512937 | 0.291914 |
def xgcd( x, y ):
old_r, r = (x, y)
old_s, s = (1, 0)
old_t, t = (0, 1)
while r != 0:
quotient = old_r // r
old_r, r = (r, old_r - quotient * r)
old_s, s = (s, old_s - quotient * s)
old_t, t = (t, old_t - quotient * t)
return old_s, old_t, old_r # a, b, g
class Fie... | code/algebra.py | def xgcd( x, y ):
old_r, r = (x, y)
old_s, s = (1, 0)
old_t, t = (0, 1)
while r != 0:
quotient = old_r // r
old_r, r = (r, old_r - quotient * r)
old_s, s = (s, old_s - quotient * s)
old_t, t = (t, old_t - quotient * t)
return old_s, old_t, old_r # a, b, g
class Fie... | 0.534612 | 0.451871 |
from datetime import datetime, timedelta
from pulsar.api import HttpRedirect, Http404
from pulsar.apps import http
from pulsar.apps.http import HttpClient
__all__ = ['OAuth1', 'OAuth2', 'OAuthApi', 'OAuth2Api']
Accounts = {}
class OAuthMeta(type):
def __new__(cls, name, bases, attrs):
abstract = att... | lux/ext/oauth/oauth.py | from datetime import datetime, timedelta
from pulsar.api import HttpRedirect, Http404
from pulsar.apps import http
from pulsar.apps.http import HttpClient
__all__ = ['OAuth1', 'OAuth2', 'OAuthApi', 'OAuth2Api']
Accounts = {}
class OAuthMeta(type):
def __new__(cls, name, bases, attrs):
abstract = att... | 0.663124 | 0.060418 |
import datetime
import logging
from django.core.serializers.base import SerializationError
from django.contrib.gis.serializers.geojson import Serializer as GeoSerializer
from influxdb_metrics.loader import log_metric
from apps.utils import AliasSerializerMixin
LOG = logging.getLogger('transmission')
class TrackingD... | apps/shipments/geojson.py | import datetime
import logging
from django.core.serializers.base import SerializationError
from django.contrib.gis.serializers.geojson import Serializer as GeoSerializer
from influxdb_metrics.loader import log_metric
from apps.utils import AliasSerializerMixin
LOG = logging.getLogger('transmission')
class TrackingD... | 0.653901 | 0.149749 |
import json
import boto3
import cfnresponse
from botocore.exceptions import ClientError
import time
rds_data = boto3.client('rds-data')
rds_client = boto3.client('rds')
s3 = boto3.resource('s3')
def create(properties, physical_id):
print("Create Event and Properties: {}".format(json.dumps(properties)))
cluster =... | 6-serverless-graphql-stack/backend/custom-resource-code/index.py | import json
import boto3
import cfnresponse
from botocore.exceptions import ClientError
import time
rds_data = boto3.client('rds-data')
rds_client = boto3.client('rds')
s3 = boto3.resource('s3')
def create(properties, physical_id):
print("Create Event and Properties: {}".format(json.dumps(properties)))
cluster =... | 0.172416 | 0.07117 |
import socket
import ssl
import tempfile
import time
import mock
from oslo_serialization import jsonutils
import six
from six.moves import http_client
from manila import exception
from manila.share.drivers.quobyte import jsonrpc
from manila import test
class FakeResponse(object):
def __init__(self, status, bod... | manila/tests/share/drivers/quobyte/test_jsonrpc.py |
import socket
import ssl
import tempfile
import time
import mock
from oslo_serialization import jsonutils
import six
from six.moves import http_client
from manila import exception
from manila.share.drivers.quobyte import jsonrpc
from manila import test
class FakeResponse(object):
def __init__(self, status, bod... | 0.522202 | 0.10235 |
import argparse
import os
from dataset import *
from models.cnn_block_frame_flow import CNNBlockFrameFlow
from train_helper import *
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Block Frame&Flow ConvNet")
parser.add_argument("--dataset_dir", type=str, default="data",
... | main/train_cnn_block_frame_flow.py | import argparse
import os
from dataset import *
from models.cnn_block_frame_flow import CNNBlockFrameFlow
from train_helper import *
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Block Frame&Flow ConvNet")
parser.add_argument("--dataset_dir", type=str, default="data",
... | 0.576065 | 0.152032 |
from __future__ import absolute_import
from flask import json
from six import BytesIO
from tapi_server.models.tapi_odu_deg_thr import TapiOduDegThr # noqa: E501
from tapi_server.models.tapi_odu_odu_common_pac import TapiOduOduCommonPac # noqa: E501
from tapi_server.models.tapi_odu_odu_connection_end_point_spec imp... | RI/flask_server/tapi_server/test/test_tapi_odu_controller.py |
from __future__ import absolute_import
from flask import json
from six import BytesIO
from tapi_server.models.tapi_odu_deg_thr import TapiOduDegThr # noqa: E501
from tapi_server.models.tapi_odu_odu_common_pac import TapiOduOduCommonPac # noqa: E501
from tapi_server.models.tapi_odu_odu_connection_end_point_spec imp... | 0.500732 | 0.068351 |
import argparse
import json
import numpy as np
import os
import shutil
import sqlite3
import sys
import types
import torch
from utils import translate_descriptors, build_hybrid_database, match_features, geometric_verification, reconstruct, blob_to_array, compute_extra_stats
sys.path.append(os.getcwd())
from l... | local-feature-evaluation/reconstruction_pipeline_embed.py | import argparse
import json
import numpy as np
import os
import shutil
import sqlite3
import sys
import types
import torch
from utils import translate_descriptors, build_hybrid_database, match_features, geometric_verification, reconstruct, blob_to_array, compute_extra_stats
sys.path.append(os.getcwd())
from l... | 0.475605 | 0.139396 |
from enum import Enum
from functools import lru_cache, wraps
from typing import (
Any,
Callable,
Collection,
Mapping,
Optional,
Sequence,
Type,
Union,
cast,
overload,
)
from apischema.aliases import Aliaser
from apischema.cache import cache
from apischema.conversions.conversions... | apischema/serialization/__init__.py | from enum import Enum
from functools import lru_cache, wraps
from typing import (
Any,
Callable,
Collection,
Mapping,
Optional,
Sequence,
Type,
Union,
cast,
overload,
)
from apischema.aliases import Aliaser
from apischema.cache import cache
from apischema.conversions.conversions... | 0.791741 | 0.116412 |
import os
import shutil
import pandas as pd
import pytest
from omegaconf import OmegaConf
from omegaconf.dictconfig import DictConfig
from universal_data_catalog.data_catalog import DataCatalog
from universal_data_catalog.types import ConfigDict
@pytest.fixture(autouse=True)
def run_around_tests():
assert os.pa... | test/test_pandas_provider.py | import os
import shutil
import pandas as pd
import pytest
from omegaconf import OmegaConf
from omegaconf.dictconfig import DictConfig
from universal_data_catalog.data_catalog import DataCatalog
from universal_data_catalog.types import ConfigDict
@pytest.fixture(autouse=True)
def run_around_tests():
assert os.pa... | 0.377196 | 0.492615 |
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from plotly.subplots import make_subplots
from scipy.cluster.hierarchy import l... | omb/apps/cell_type_dmr_browser.py | import dash_bootstrap_components as dbc
import dash_core_components as dcc
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from plotly.subplots import make_subplots
from scipy.cluster.hierarchy import l... | 0.630799 | 0.311126 |
import os
from unittest import skip
from django.core.urlresolvers import reverse
from django.core.files.storage import get_storage_class
from pyxform.errors import PyXFormError
from onadata.apps.main.views import show
from onadata.apps.main.tests.test_base import TestBase
from onadata.apps.logger.models import XForm
... | onadata/apps/main/tests/test_form_errors.py | import os
from unittest import skip
from django.core.urlresolvers import reverse
from django.core.files.storage import get_storage_class
from pyxform.errors import PyXFormError
from onadata.apps.main.views import show
from onadata.apps.main.tests.test_base import TestBase
from onadata.apps.logger.models import XForm
... | 0.47098 | 0.309689 |
import sys
import os.path
from matplotlib import pyplot as plt
import numpy as np
# Proteus native probe
proteus_gauge_file = 'combined_gauge_0_0.5_sample_all.csv'
# Paraview probe
paraview_gauge_file = 'probe_0.5_0.5_0.csv'
global interactive
interactive = True
def parse_proteus_gauge_fields(header):
def parse_... | 2d/benchmarks/quiescent_water_probe_benchmark/ProbePlot.py | import sys
import os.path
from matplotlib import pyplot as plt
import numpy as np
# Proteus native probe
proteus_gauge_file = 'combined_gauge_0_0.5_sample_all.csv'
# Paraview probe
paraview_gauge_file = 'probe_0.5_0.5_0.csv'
global interactive
interactive = True
def parse_proteus_gauge_fields(header):
def parse_... | 0.393269 | 0.42316 |
from pprint import pformat
from six import iteritems
import re
class MetaRelationshipDefinition(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
... | intersight/models/meta_relationship_definition.py | from pprint import pformat
from six import iteritems
import re
class MetaRelationshipDefinition(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
... | 0.700383 | 0.133021 |
OFF = 0
LOW = 0
CLEAR = 0
ON = 1
HIGH = 1
SET = 1
TIMEOUT = 2
# gpio edges
RISING_EDGE = 0
FALLING_EDGE = 1
EITHER_EDGE = 2
# gpio modes
INPUT = 0
OUTPUT = 1
ALT0 = 4
ALT1 = 5
ALT2 = 6
ALT3 = 7
ALT4 = 3
ALT5 = 2
# gpio Pull Up Down
PUD_OFF = 0
PUD_DOWN = 1
PUD_UP = 2
# script run status
PI_SCRIPT_INITING = 0... | apigpio/ctes.py |
OFF = 0
LOW = 0
CLEAR = 0
ON = 1
HIGH = 1
SET = 1
TIMEOUT = 2
# gpio edges
RISING_EDGE = 0
FALLING_EDGE = 1
EITHER_EDGE = 2
# gpio modes
INPUT = 0
OUTPUT = 1
ALT0 = 4
ALT1 = 5
ALT2 = 6
ALT3 = 7
ALT4 = 3
ALT5 = 2
# gpio Pull Up Down
PUD_OFF = 0
PUD_DOWN = 1
PUD_UP = 2
# script run status
PI_SCRIPT_INITING = 0... | 0.198841 | 0.07333 |
import logging
from towerlib.towerlibexceptions import InvalidValue
from .core import (Entity,
validate_max_length)
__author__ = '''<NAME> <<EMAIL>>'''
__docformat__ = '''google'''
__date__ = '''2018-01-03'''
__copyright__ = '''Copyright 2018, <NAME>'''
__credits__ = ["<NAME>"]
__license__ = '''MIT... | towerlib/entities/inventory_source.py | import logging
from towerlib.towerlibexceptions import InvalidValue
from .core import (Entity,
validate_max_length)
__author__ = '''<NAME> <<EMAIL>>'''
__docformat__ = '''google'''
__date__ = '''2018-01-03'''
__copyright__ = '''Copyright 2018, <NAME>'''
__credits__ = ["<NAME>"]
__license__ = '''MIT... | 0.794903 | 0.164014 |
import os
import numpy
# scipy.special for the sigmoid function expit()
from scipy import special
# neural network class definition
class neuralNetwork:
# initialise the neural network
def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
# set number of nodes in each input, hidd... | uchkin_diploma/__init__.py | import os
import numpy
# scipy.special for the sigmoid function expit()
from scipy import special
# neural network class definition
class neuralNetwork:
# initialise the neural network
def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
# set number of nodes in each input, hidd... | 0.617974 | 0.650856 |
from jpype import *
from PatentCrawler.util.settings import CRFPOSModelPath, CRFCWSModelPath, CRFNERModelPath
class HanLPAPI:
"""
HanLP Java 工具包的调用接口
"""
HanLP = None
def __init__(self):
"""
类的初始化,启动JVM
"""
startJVM(getDefaultJVMPath(), "-Djava.class.path=D:\\javawo... | util/pyhlp.py | from jpype import *
from PatentCrawler.util.settings import CRFPOSModelPath, CRFCWSModelPath, CRFNERModelPath
class HanLPAPI:
"""
HanLP Java 工具包的调用接口
"""
HanLP = None
def __init__(self):
"""
类的初始化,启动JVM
"""
startJVM(getDefaultJVMPath(), "-Djava.class.path=D:\\javawo... | 0.391988 | 0.124559 |
from typing import List
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
plt.style.use("./Styles/Scientific.mplstyle")
import cv2
import numpy as np
def plot_histogram(img, bins: int=256, vmin: int=0, vmax: int=255):
histogram = cv2.calcHist([img], [], None, [bins], [vmin, vmax])
hi... | Python/histogram.py | from typing import List
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
plt.style.use("./Styles/Scientific.mplstyle")
import cv2
import numpy as np
def plot_histogram(img, bins: int=256, vmin: int=0, vmax: int=255):
histogram = cv2.calcHist([img], [], None, [bins], [vmin, vmax])
hi... | 0.850189 | 0.69344 |
import pandas as pd
import numpy as np
import datetime as dt
from pathlib import Path
%matplotlib inline
# Reading whale returns
# Rading the whale returs dataset using the pandas built in function read_csv and converting the Date column into datetime format.
df = pd.read_csv('./Resources/whale_returns.csv',index_col... | whale.py | import pandas as pd
import numpy as np
import datetime as dt
from pathlib import Path
%matplotlib inline
# Reading whale returns
# Rading the whale returs dataset using the pandas built in function read_csv and converting the Date column into datetime format.
df = pd.read_csv('./Resources/whale_returns.csv',index_col... | 0.645455 | 0.500793 |
from enum import Enum
import json
from os.path import join
from absl import app
from absl import flags
from absl import logging
from tqdm import tqdm
FLAGS = flags.FLAGS
flags.DEFINE_string('data_root', '', 'root directory for data.')
flags.DEFINE_string('table_file', '', '')
flags.DEFINE_string('sql_file', '', '')... | exec_acc/code/parse_ours.py |
from enum import Enum
import json
from os.path import join
from absl import app
from absl import flags
from absl import logging
from tqdm import tqdm
FLAGS = flags.FLAGS
flags.DEFINE_string('data_root', '', 'root directory for data.')
flags.DEFINE_string('table_file', '', '')
flags.DEFINE_string('sql_file', '', '')... | 0.363873 | 0.378 |
import mock
from werkzeug.exceptions import TooManyRequests
from tests.helpers.unittest_base import BaseTestCase
class FlaskAppConfigTest(BaseTestCase):
def __init__(self, *args, **kwargs):
super(FlaskAppConfigTest, self).__init__(*args, **kwargs)
self.uses_database = False
def setUp(self, w... | tests/api_tests/test_general_api_configuration.py | import mock
from werkzeug.exceptions import TooManyRequests
from tests.helpers.unittest_base import BaseTestCase
class FlaskAppConfigTest(BaseTestCase):
def __init__(self, *args, **kwargs):
super(FlaskAppConfigTest, self).__init__(*args, **kwargs)
self.uses_database = False
def setUp(self, w... | 0.664214 | 0.206214 |
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from users.models import User
class Category(models.Model):
""" Модель категорий произведений """
name = models.CharField(max_length=50)
slug = models.SlugField(unique=True)
def __str__(self):
... | api_yamdb/reviews/models.py | from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from users.models import User
class Category(models.Model):
""" Модель категорий произведений """
name = models.CharField(max_length=50)
slug = models.SlugField(unique=True)
def __str__(self):
... | 0.526099 | 0.184804 |
from stickylink import *
from widthXfillXdecoration import *
from LHS import *
from MT_pre__VirtualDevice import *
from MT_pre__EcuInstance import *
from MT_pre__trace_link import *
from MT_pre__SystemMapping import *
from MT_pre__directLink_S import *
from MT_pre__ECU import *
from MT_pre__SwcToEcuMapping import *
fro... | GM2AUTOSAR_MM/backward_matchers/models/ConnECU2VirtualDevice_Back_Complete_MDL.py | from stickylink import *
from widthXfillXdecoration import *
from LHS import *
from MT_pre__VirtualDevice import *
from MT_pre__EcuInstance import *
from MT_pre__trace_link import *
from MT_pre__SystemMapping import *
from MT_pre__directLink_S import *
from MT_pre__ECU import *
from MT_pre__SwcToEcuMapping import *
fro... | 0.465387 | 0.07921 |
__author__ = "<NAME>"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright (C) 2019, Nokia"
__license__ = "BSD-3"
from numpy import Inf
from typing import List
class ArrivalCurve:
"""
The ArrivalCurve class encodes token-bucket arrival curves.
:math:`\\alpha: t \\mapst... | NCBounds/ArrivalCurve.py |
__author__ = "<NAME>"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright (C) 2019, Nokia"
__license__ = "BSD-3"
from numpy import Inf
from typing import List
class ArrivalCurve:
"""
The ArrivalCurve class encodes token-bucket arrival curves.
:math:`\\alpha: t \\mapst... | 0.939318 | 0.432902 |
import datetime
from typing import Optional
import recurrence
from django.contrib.auth.models import User
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy as _
from recurrence.fields import Rec... | applications/models.py | import datetime
from typing import Optional
import recurrence
from django.contrib.auth.models import User
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy as _
from recurrence.fields import Rec... | 0.750187 | 0.13229 |
# In[4]:
import numpy as np
def sigmoidfun(x):
return 1.0/(1.0 + np.exp(-x))
def sigmoid_primefun(x):
return sigmoidfun(x)*(1.0-sigmoidfun(x))
def tanh(x):
return np.tanh(x)
def tanh_prime(x):
return 1.0 - x**2
class NeuralNetwork:
def __init__(self, layers, activation='tanh'):
if activ... | Chapter 07/Chap7_2.py |
# In[4]:
import numpy as np
def sigmoidfun(x):
return 1.0/(1.0 + np.exp(-x))
def sigmoid_primefun(x):
return sigmoidfun(x)*(1.0-sigmoidfun(x))
def tanh(x):
return np.tanh(x)
def tanh_prime(x):
return 1.0 - x**2
class NeuralNetwork:
def __init__(self, layers, activation='tanh'):
if activ... | 0.712532 | 0.646488 |
from bs4 import BeautifulSoup
from puppetboard import app
from . import MockDbQuery
def test_first_test():
assert app is not None
def test_no_env(client, mock_puppetdb_environments):
rv = client.get('/nonexistent/')
assert rv.status_code == 404
def test_offline_mode(client, mocker,
... | test/test_app.py | from bs4 import BeautifulSoup
from puppetboard import app
from . import MockDbQuery
def test_first_test():
assert app is not None
def test_no_env(client, mock_puppetdb_environments):
rv = client.get('/nonexistent/')
assert rv.status_code == 404
def test_offline_mode(client, mocker,
... | 0.414899 | 0.222711 |
from unittest import TestCase
import giant.rotations as at
from giant.camera import Camera
from giant.camera_models import PinholeModel
from giant.image import OpNavImage
from giant.image_processing import pixel_level_peak_finder_2d
import giant.image_processing as gimp
import giant.ray_tracer.shapes as g_shapes
... | unittests/relativeopnav/test_cross_correlation.py | from unittest import TestCase
import giant.rotations as at
from giant.camera import Camera
from giant.camera_models import PinholeModel
from giant.image import OpNavImage
from giant.image_processing import pixel_level_peak_finder_2d
import giant.image_processing as gimp
import giant.ray_tracer.shapes as g_shapes
... | 0.696165 | 0.574992 |
from __future__ import print_function, division
import numpy as np
from netlearner.utils import min_max_scale, measure_prediction
from netlearner.utils import permutate_dataset
from netlearner.rbm import RestrictedBoltzmannMachine
from preprocess.nslkdd import generate_dataset
import tensorflow as tf
from math import c... | rbm_kfold_nsl.py | from __future__ import print_function, division
import numpy as np
from netlearner.utils import min_max_scale, measure_prediction
from netlearner.utils import permutate_dataset
from netlearner.rbm import RestrictedBoltzmannMachine
from preprocess.nslkdd import generate_dataset
import tensorflow as tf
from math import c... | 0.733547 | 0.301285 |
import operator
import discord
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
from .exceptions import APIBadRequest, APIError, APINotFound
class CommerceMixin:
@commands.group(case_insensitive=True)
async def tp(self, ctx):
"""Commands related to tradingpost""... | guildwars2/commerce.py | import operator
import discord
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
from .exceptions import APIBadRequest, APIError, APINotFound
class CommerceMixin:
@commands.group(case_insensitive=True)
async def tp(self, ctx):
"""Commands related to tradingpost""... | 0.465387 | 0.132262 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from layers.backbone.resnet import *
## net ######################################################################
class ResnetClass(nn.Module):
def load_pretrain(self, pretrain_file):
print('loading pretrain...%s' % pretrain_fil... | networks/resnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from layers.backbone.resnet import *
## net ######################################################################
class ResnetClass(nn.Module):
def load_pretrain(self, pretrain_file):
print('loading pretrain...%s' % pretrain_fil... | 0.848204 | 0.182681 |
import const
import re
import urllib.request
from skill import Skill
class Hiscores(object):
def __init__(self, username, type=const.AccountType.NORMAL):
self.username = username
self._url = const.BASE_URL + const.HISCORE_URLS[type] + "?player="
self.update()
def update(self):
... | modules/py/hiscores.py | import const
import re
import urllib.request
from skill import Skill
class Hiscores(object):
def __init__(self, username, type=const.AccountType.NORMAL):
self.username = username
self._url = const.BASE_URL + const.HISCORE_URLS[type] + "?player="
self.update()
def update(self):
... | 0.472197 | 0.170128 |
from django.db import models
class HomeHealth18(models.Model):
""" Defines the HomeHealth Model for 2018, derived from the model class. """
# Metadata
class Meta:
""" Set parameters for admin app"""
ordering = ["DUPERSID"]
verbose_name_plural = "HomeHealth18"
DUID = models.C... | meps_db/components/models/home_health_models.py | from django.db import models
class HomeHealth18(models.Model):
""" Defines the HomeHealth Model for 2018, derived from the model class. """
# Metadata
class Meta:
""" Set parameters for admin app"""
ordering = ["DUPERSID"]
verbose_name_plural = "HomeHealth18"
DUID = models.C... | 0.533641 | 0.192615 |
import pandas as pd
# GLOBAL VARIABLES
_ROUND_TO = 3
def calculate_actual_win_pct(school, games):
"""
A function to calculate the winning percentage as
# games won / # games plated
Args:
school (str): team to return actual winning % for
games (DataFrame from get_games()): output of ... | collegebaseball/win_pct.py | import pandas as pd
# GLOBAL VARIABLES
_ROUND_TO = 3
def calculate_actual_win_pct(school, games):
"""
A function to calculate the winning percentage as
# games won / # games plated
Args:
school (str): team to return actual winning % for
games (DataFrame from get_games()): output of ... | 0.77928 | 0.539772 |
class Autoformat(object):
"""
Autoformats any wikitext into something readable
"""
def __init__(self, wikitext):
self.text = wikitext
self.summaries = ['[[Wiktionary:Firafitry_ny_teny_iditra|Firafitra]]']
# TODO
def _replace_jereo_template(self):
new_txt = self.text
... | api/autoformatter.py |
class Autoformat(object):
"""
Autoformats any wikitext into something readable
"""
def __init__(self, wikitext):
self.text = wikitext
self.summaries = ['[[Wiktionary:Firafitry_ny_teny_iditra|Firafitra]]']
# TODO
def _replace_jereo_template(self):
new_txt = self.text
... | 0.207135 | 0.260881 |
from . import SolidFireClusterAPI, GetHighestAPIVersion, InvalidArgumentError, UnknownObjectError
from .logutil import GetLogger
def _refresh(fn):
"""Decorator to refresh the attributes of this object from the cluster"""
def wrapper(self, *args, **kwargs):
self.Refresh()
fn(self, *args, **kwarg... | libsf/sfaccount.py | from . import SolidFireClusterAPI, GetHighestAPIVersion, InvalidArgumentError, UnknownObjectError
from .logutil import GetLogger
def _refresh(fn):
"""Decorator to refresh the attributes of this object from the cluster"""
def wrapper(self, *args, **kwargs):
self.Refresh()
fn(self, *args, **kwarg... | 0.703957 | 0.204699 |
# In[1]:
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import time
import math
from collections import OrderedDict
# In[2]:
def createGraph(depotNodes ,requiredEdges, numNodes, show=True):
G = nx.Graph()
edges = []
pos = {}
reqPos = {}
s = [1, 1, 2, 2, 3, 3, 4, 4, 4... | Heuristic based Approaches/Augment Merge Algorithm/augment_merge.py |
# In[1]:
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import time
import math
from collections import OrderedDict
# In[2]:
def createGraph(depotNodes ,requiredEdges, numNodes, show=True):
G = nx.Graph()
edges = []
pos = {}
reqPos = {}
s = [1, 1, 2, 2, 3, 3, 4, 4, 4... | 0.231093 | 0.542379 |
import functools
import itertools
import threading
import typing as t
EVENT_EXISTS_ITEM = 2 ** 0
EVENT_UPDATE_ITEM = 2 ** 1
class Event(list):
def __call__(self, *args, **kwargs):
for item in self:
item(*args, **kwargs)
_KT = t.TypeVar('_KT') # Key type.
_VT = t.TypeVar('_VT') # Value typ... | dimensigon/utils/talkback.py | import functools
import itertools
import threading
import typing as t
EVENT_EXISTS_ITEM = 2 ** 0
EVENT_UPDATE_ITEM = 2 ** 1
class Event(list):
def __call__(self, *args, **kwargs):
for item in self:
item(*args, **kwargs)
_KT = t.TypeVar('_KT') # Key type.
_VT = t.TypeVar('_VT') # Value typ... | 0.386648 | 0.084758 |
import os
import requests
from libvirt import libvirtError
from subprocess import call, STDOUT
from settings import CACHE_DIR
from .util import md5sum
from .libguestfs import GuestFSUtil
from .libvrt import wvmConnect, wvmStorage
try:
from subprocess import DEVNULL
except ImportError:
DEVNULL = open(os.devnull,... | src/lib/images.py | import os
import requests
from libvirt import libvirtError
from subprocess import call, STDOUT
from settings import CACHE_DIR
from .util import md5sum
from .libguestfs import GuestFSUtil
from .libvrt import wvmConnect, wvmStorage
try:
from subprocess import DEVNULL
except ImportError:
DEVNULL = open(os.devnull,... | 0.314577 | 0.06357 |
import gym
# Create Enviroment
env = gym.make('MountainCar-v0')
print(env.reset())
print(env.action_space)
print(env.action_space.n)
print(env.observation_space.shape[0])
"""
for t in range(1000):
random_action = env.action_space.sample()
env.step(random_action) #randomly move left or right
... | cartpole.py | import gym
# Create Enviroment
env = gym.make('MountainCar-v0')
print(env.reset())
print(env.action_space)
print(env.action_space.n)
print(env.observation_space.shape[0])
"""
for t in range(1000):
random_action = env.action_space.sample()
env.step(random_action) #randomly move left or right
... | 0.433502 | 0.319466 |
from pyramid.response import Response
from pyramid.renderers import render_to_response
from pyramid.httpexceptions import HTTPNotFound
from . import CONFIG_MODELS
class PageView(object):
def __init__(self, context, request):
self.request = request
self.context = context
self.page = conte... | pyramid_pages/views.py | from pyramid.response import Response
from pyramid.renderers import render_to_response
from pyramid.httpexceptions import HTTPNotFound
from . import CONFIG_MODELS
class PageView(object):
def __init__(self, context, request):
self.request = request
self.context = context
self.page = conte... | 0.607081 | 0.059866 |
import copy
from onnx import onnx_ml_pb2 as xpb2
# merge merges two graphs
from sclblonnx import check, clean, delete_output
from sclblonnx.utils import _print, _output_details, _input_details
def merge(
sg1: xpb2.GraphProto,
sg2: xpb2.GraphProto,
outputs: [],
inputs: [],
_ve... | sclblonnx/merge.py | import copy
from onnx import onnx_ml_pb2 as xpb2
# merge merges two graphs
from sclblonnx import check, clean, delete_output
from sclblonnx.utils import _print, _output_details, _input_details
def merge(
sg1: xpb2.GraphProto,
sg2: xpb2.GraphProto,
outputs: [],
inputs: [],
_ve... | 0.597256 | 0.623635 |
from flask import Flask, request, render_template, redirect
from math import floor
from sqlite3 import OperationalError
import string
import sqlite3
try:
from urllib.parse import urlparse # Python 3
str_encode = str.encode
except ImportError:
from urlparse import urlparse # Python 2
str_encode = str
t... | app.py | from flask import Flask, request, render_template, redirect
from math import floor
from sqlite3 import OperationalError
import string
import sqlite3
try:
from urllib.parse import urlparse # Python 3
str_encode = str.encode
except ImportError:
from urlparse import urlparse # Python 2
str_encode = str
t... | 0.447219 | 0.096195 |
# Gather breast cancer data
from sklearn.datasets import load_breast_cancer
breast_cancer = load_breast_cancer()
breast_cancer_data = breast_cancer.data
breast_cancer_labels = breast_cancer.target
# Prepare data as pandas dataframe
import numpy as np
labels = np.reshape(breast_cancer_labels,(569,1))
final_breast_... | StandardAlgorithms/BreastCancerSuppVecAnalysis.py |
# Gather breast cancer data
from sklearn.datasets import load_breast_cancer
breast_cancer = load_breast_cancer()
breast_cancer_data = breast_cancer.data
breast_cancer_labels = breast_cancer.target
# Prepare data as pandas dataframe
import numpy as np
labels = np.reshape(breast_cancer_labels,(569,1))
final_breast_... | 0.699562 | 0.891952 |