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
from types import GeneratorType from satori.objects import Object, Argument from satori.events.misc import flattenCoroutine from satori.events.protocol import Command, ProtocolError class Scheduler(Object): """Interface. Chooses which Client to run next. """ def next(self): """Return the next Cl...
satori.events/satori/events/client.py
from types import GeneratorType from satori.objects import Object, Argument from satori.events.misc import flattenCoroutine from satori.events.protocol import Command, ProtocolError class Scheduler(Object): """Interface. Chooses which Client to run next. """ def next(self): """Return the next Cl...
0.776665
0.137764
import asyncio import logging from pycoinnet.InvItem import InvItem, ITEM_TYPE_TX class TxHandler: def __init__(self, inv_collector, tx_store, tx_validator=lambda tx: True): self.inv_collector = inv_collector self.q = inv_collector.new_inv_item_queue() self.tx_store = tx_store sel...
pycoinnet/peergroup/TxHandler.py
import asyncio import logging from pycoinnet.InvItem import InvItem, ITEM_TYPE_TX class TxHandler: def __init__(self, inv_collector, tx_store, tx_validator=lambda tx: True): self.inv_collector = inv_collector self.q = inv_collector.new_inv_item_queue() self.tx_store = tx_store sel...
0.316158
0.1011
import argparse import json import pika import platform import sys import time from datetime import date from gpiozero import CPUTemperature parser = argparse.ArgumentParser() # Requires a json file for authentication paramters # debug is optional parser.add_argument('-j','--json', required=True, metavar='js...
mqtt_temp_client.py
import argparse import json import pika import platform import sys import time from datetime import date from gpiozero import CPUTemperature parser = argparse.ArgumentParser() # Requires a json file for authentication paramters # debug is optional parser.add_argument('-j','--json', required=True, metavar='js...
0.238373
0.063193
from optparse import make_option from django.conf import settings from django.contrib.sites.models import Site from django.core.management.base import BaseCommand, CommandError, NoArgsCommand from django.utils import translation from django.utils.translation import get_language_info import sys from fluent_pages.models ...
fluent_pages/management/commands/make_language_redirects.py
from optparse import make_option from django.conf import settings from django.contrib.sites.models import Site from django.core.management.base import BaseCommand, CommandError, NoArgsCommand from django.utils import translation from django.utils.translation import get_language_info import sys from fluent_pages.models ...
0.410284
0.081483
import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from match_info.match_info import MatchInfo, MatchInfoConfig import pytest class FakeBot: def __init__(self): self.match_info: MatchInfo = None self.new_game_called = 0 self.new_game_with_mmr_called = 0 ...
test/test_match_info.py
import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from match_info.match_info import MatchInfo, MatchInfoConfig import pytest class FakeBot: def __init__(self): self.match_info: MatchInfo = None self.new_game_called = 0 self.new_game_with_mmr_called = 0 ...
0.374333
0.315578
import re import json from itertools import count import datetime from collections import defaultdict from rdflib import Graph, Namespace, OWL, Literal, URIRef, BNode, XSD, RDFS, RDF from rdfalchemy import rdfSubject, rdfSingle, rdfMultiple bio = Namespace("http://purl.org/vocab/bio/0.1/") schema = Namespace('http://...
2rdf.py
import re import json from itertools import count import datetime from collections import defaultdict from rdflib import Graph, Namespace, OWL, Literal, URIRef, BNode, XSD, RDFS, RDF from rdfalchemy import rdfSubject, rdfSingle, rdfMultiple bio = Namespace("http://purl.org/vocab/bio/0.1/") schema = Namespace('http://...
0.246171
0.185136
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS from dotenv import load_dotenv import json import datetime import os import requests load_dotenv() DATABASE_PASSWORD = os.getenv("DATABASE_PASSWORD") API_URL = os.getenv("API_URL") travel_catalog_url = API_UR...
traval-backend/order/order.py
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS from dotenv import load_dotenv import json import datetime import os import requests load_dotenv() DATABASE_PASSWORD = os.getenv("DATABASE_PASSWORD") API_URL = os.getenv("API_URL") travel_catalog_url = API_UR...
0.438785
0.098512
from __future__ import division import glob import os import matplotlib #matplotlib.use('Qt4Agg') import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from stats import plot_result_difference_bars try: import cPickle as pickle except: import pickle def plot_stats(pr...
plot_stats.py
from __future__ import division import glob import os import matplotlib #matplotlib.use('Qt4Agg') import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from stats import plot_result_difference_bars try: import cPickle as pickle except: import pickle def plot_stats(pr...
0.68679
0.307364
from unittest import TestCase from textx import metamodel_from_file import converter.json_converter as converter converted_positive = """ { "rules": [ { "conditions": [ { "operator": ">=", "parameter": { "propert...
parser/tests/test_converter.py
from unittest import TestCase from textx import metamodel_from_file import converter.json_converter as converter converted_positive = """ { "rules": [ { "conditions": [ { "operator": ">=", "parameter": { "propert...
0.78609
0.38549
import requests from bs4 import BeautifulSoup import json import boto3 import json from datetime import datetime import os import common import match import watchlist import logging log = logging.getLogger() log.setLevel(logging.INFO) stop_words = ['One', 'morning', ',', 'when', 'Gregor', 'Samsa', 'woke', 'from', 'tro...
serverless/newsfeed.py
import requests from bs4 import BeautifulSoup import json import boto3 import json from datetime import datetime import os import common import match import watchlist import logging log = logging.getLogger() log.setLevel(logging.INFO) stop_words = ['One', 'morning', ',', 'when', 'Gregor', 'Samsa', 'woke', 'from', 'tro...
0.431824
0.182153
import os import csv import pickle import numpy as np import argparse def get_args(): parser = argparse.ArgumentParser('NTU RGB+D Dataset Preprocessing') parser.add_argument('--file-path', type=str, default='D:/nturgb+d_skeletons') return parser.parse_args() def csv2pickle(data, filename, base_dir='./...
two_stream_recurrent_neural_network_ntu_rgbd/ntu-dataset/ntu_dataset_main.py
import os import csv import pickle import numpy as np import argparse def get_args(): parser = argparse.ArgumentParser('NTU RGB+D Dataset Preprocessing') parser.add_argument('--file-path', type=str, default='D:/nturgb+d_skeletons') return parser.parse_args() def csv2pickle(data, filename, base_dir='./...
0.349644
0.173078
"""Remove""" """Template task in which you prevent something from falling so ball can roll into container.""" import numpy as np import phyre.creator as creator_lib import phyre.virtual_tools as vt @creator_lib.define_task_template( seed=range(1000), version="2", search_params=dict(required_flags=['BALL:G...
data/task_scripts/main/task01007.py
"""Remove""" """Template task in which you prevent something from falling so ball can roll into container.""" import numpy as np import phyre.creator as creator_lib import phyre.virtual_tools as vt @creator_lib.define_task_template( seed=range(1000), version="2", search_params=dict(required_flags=['BALL:G...
0.576542
0.503601
from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GL import _types as _cs # End users want this... from OpenGL.raw.GL._types import * from OpenGL.raw.GL import _errors from OpenGL.constant import Constant as _C import ctypes _EXTENSION_NAME = 'GL_VERSION_GL_4_6' def _f( function ): ...
env/Lib/site-packages/OpenGL/raw/GL/VERSION/GL_4_6.py
from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GL import _types as _cs # End users want this... from OpenGL.raw.GL._types import * from OpenGL.raw.GL import _errors from OpenGL.constant import Constant as _C import ctypes _EXTENSION_NAME = 'GL_VERSION_GL_4_6' def _f( function ): ...
0.347537
0.051439
from __future__ import unicode_literals from django.db import models, migrations import django.core.validators class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="Account", fields=[ ( "id",...
ditto/pinboard/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import models, migrations import django.core.validators class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="Account", fields=[ ( "id",...
0.672547
0.172974
import os import argparse import random from tqdm import tqdm import logging from typing import Dict logger = logging.getLogger(__name__) def get_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Sample Sentences from monolingual corpora to train tokenizer") parser.add_argume...
scripts/sample_tokenizer_sentences.py
import os import argparse import random from tqdm import tqdm import logging from typing import Dict logger = logging.getLogger(__name__) def get_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Sample Sentences from monolingual corpora to train tokenizer") parser.add_argume...
0.671686
0.185172
import numpy as np import andi import csv from tensorflow.keras.utils import Sequence """ Dataset generators """ def generate_tracks_regression(n, dimensions, min_T=5, max_T=1001): """ Generate tracks for training regression model Parameters: n: number of tracks to generate dimensions: number o...
andi_funcs.py
import numpy as np import andi import csv from tensorflow.keras.utils import Sequence """ Dataset generators """ def generate_tracks_regression(n, dimensions, min_T=5, max_T=1001): """ Generate tracks for training regression model Parameters: n: number of tracks to generate dimensions: number o...
0.929632
0.731011
import os import csv from pyparsing import Word, Combine, nums, alphas, Optional, Regex from collections import OrderedDict class ProxifierLog(object): def __init__(self, dataset): self.dataset = dataset self.proxifierlog_grammar = self.__get_proxifierlog_grammar() @staticmethod def __get...
nerlogparser/grammar/proxifierlog.py
import os import csv from pyparsing import Word, Combine, nums, alphas, Optional, Regex from collections import OrderedDict class ProxifierLog(object): def __init__(self, dataset): self.dataset = dataset self.proxifierlog_grammar = self.__get_proxifierlog_grammar() @staticmethod def __get...
0.569494
0.246851
import json, os, sys import numpy as np from collections import Counter file_path = os.path.abspath(__file__) sys.path.append(os.path.abspath(os.path.join(file_path, "..", "..", ".."))) from code_aculat.visualize.plot_tools import plot_points import pandas as pd from matplotlib import pyplot as plt def get_image2ann...
data_analyse/data_analyse_coco.py
import json, os, sys import numpy as np from collections import Counter file_path = os.path.abspath(__file__) sys.path.append(os.path.abspath(os.path.join(file_path, "..", "..", ".."))) from code_aculat.visualize.plot_tools import plot_points import pandas as pd from matplotlib import pyplot as plt def get_image2ann...
0.308503
0.28048
import os, logging, sys from collections import OrderedDict as odict import numpy as np log = logging.getLogger(__name__) from opticks.ana.bench import Bench from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable import matplotlib.pyplot as plt from opticks.ana.plot import init_rcParams init_...
ana/benchplot.py
import os, logging, sys from collections import OrderedDict as odict import numpy as np log = logging.getLogger(__name__) from opticks.ana.bench import Bench from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable import matplotlib.pyplot as plt from opticks.ana.plot import init_rcParams init_...
0.370339
0.334345
import asynctest import pytest from decimal import Decimal from market_values_api.services import MarketValuesService class TestMarketValuesService(object): @pytest.fixture def company_list(self): return ['CBA', 'ANZ', 'REA'] @pytest.fixture def market_values(self): return {'CBA': Dec...
tests/services/test_market_values_service.py
import asynctest import pytest from decimal import Decimal from market_values_api.services import MarketValuesService class TestMarketValuesService(object): @pytest.fixture def company_list(self): return ['CBA', 'ANZ', 'REA'] @pytest.fixture def market_values(self): return {'CBA': Dec...
0.424651
0.320875
from .asset_types import detect_asset_type, render_asset_html_tags, list_asset_types from webassets import Bundle, six from webassets.filter import get_filter __all__ = ('Package', 'PackageError') auto_filters = { "less": ("less", "css"), "coffee": ("coffeescript", "js"), "sass": ("sass", "css"), "s...
easywebassets/package.py
from .asset_types import detect_asset_type, render_asset_html_tags, list_asset_types from webassets import Bundle, six from webassets.filter import get_filter __all__ = ('Package', 'PackageError') auto_filters = { "less": ("less", "css"), "coffee": ("coffeescript", "js"), "sass": ("sass", "css"), "s...
0.712132
0.167593
from token import DEDENT, INDENT, NAME, NEWLINE, STRING, ENDMARKER from story5.parser import Parser class Rule: def __init__(self, name, alts): self.name = name self.alts = alts def __repr__(self): return f"Rule({self.name!r}, {self.alts})" def __eq__(self, other): if n...
story5/grammar.py
from token import DEDENT, INDENT, NAME, NEWLINE, STRING, ENDMARKER from story5.parser import Parser class Rule: def __init__(self, name, alts): self.name = name self.alts = alts def __repr__(self): return f"Rule({self.name!r}, {self.alts})" def __eq__(self, other): if n...
0.659953
0.27594
from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from core.github_utils import GithubSingleton PR_LINKED_ISSUE_URL = reverse('flowie:pr_linked_issue-view') class PRLinkedIssuePublicAPI(TestCase): """Tests for PR Linked...
backend/flowie/tests/test_pr_api.py
from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from core.github_utils import GithubSingleton PR_LINKED_ISSUE_URL = reverse('flowie:pr_linked_issue-view') class PRLinkedIssuePublicAPI(TestCase): """Tests for PR Linked...
0.430626
0.228071
import torch import torchvision import torch.nn.functional as F import torchvision.datasets as datasets import torchvision.transforms as transforms from torch import optim from torch import nn from torch.utils.data import DataLoader from tqdm import tqdm # Set device device = torch.device("cuda" if torch.cuda.is_...
RNN/Embedding/Embedding_RNN.py
import torch import torchvision import torch.nn.functional as F import torchvision.datasets as datasets import torchvision.transforms as transforms from torch import optim from torch import nn from torch.utils.data import DataLoader from tqdm import tqdm # Set device device = torch.device("cuda" if torch.cuda.is_...
0.943458
0.753603
import datetime import logging import os import sys import time from collections import namedtuple import click from dateutil.parser import parse import requests from mutualfunds import DailyNAVPS LOGFILE = 'runtime.log' TIMEOUT = 5 OUTDIR = 'Reports' def stringify_date(date): """Convert datetime object into hu...
main.py
import datetime import logging import os import sys import time from collections import namedtuple import click from dateutil.parser import parse import requests from mutualfunds import DailyNAVPS LOGFILE = 'runtime.log' TIMEOUT = 5 OUTDIR = 'Reports' def stringify_date(date): """Convert datetime object into hu...
0.207536
0.100834
from vitruncate import GT from numpy import * import matplotlib from matplotlib import pyplot from mpl_toolkits.mplot3d import Axes3D import matplotlib.patches as patches pyplot.rc('font', size=16) #set defaults so that the plots are readable pyplot.rc('axes', titlesize=16) pyplot.rc('axes', labelsize=16) pyplot.rc('x...
paper/figs.py
from vitruncate import GT from numpy import * import matplotlib from matplotlib import pyplot from mpl_toolkits.mplot3d import Axes3D import matplotlib.patches as patches pyplot.rc('font', size=16) #set defaults so that the plots are readable pyplot.rc('axes', titlesize=16) pyplot.rc('axes', labelsize=16) pyplot.rc('x...
0.39257
0.641085
import json import logging import pysnooper as psn from akshareinterface import Init, Index, Stocks, Futures, FuturesForeign, Options logging.basicConfig(level=logging.DEBUG,format='[%(asctime)s] %(filename)s [line:%(lineno)d] \ [%(levelname)s] %(message)s', datefmt='%Y-%m-%d(%a) %H:%M:%S') def tool_info()...
aksharetool.py
import json import logging import pysnooper as psn from akshareinterface import Init, Index, Stocks, Futures, FuturesForeign, Options logging.basicConfig(level=logging.DEBUG,format='[%(asctime)s] %(filename)s [line:%(lineno)d] \ [%(levelname)s] %(message)s', datefmt='%Y-%m-%d(%a) %H:%M:%S') def tool_info()...
0.241937
0.202502
from antlr4 import * from io import StringIO from typing.io import TextIO import sys from lexererr import * def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\n") buf.write("\61\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t") ...
tutorial/week6/problem2/src/main/mc/parser/.antlr/MCLexer.py
from antlr4 import * from io import StringIO from typing.io import TextIO import sys from lexererr import * def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\n") buf.write("\61\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t") ...
0.408159
0.338979
from django.views.generic import TemplateView from decharges.decharge.mixins import CheckConfigurationMixin, FederationRequiredMixin from decharges.decharge.models import ( TempsDeDecharge, UtilisationCreditDeTempsSyndicalPonctuel, UtilisationTempsDecharge, ) from decharges.decharge.views.utils import calc...
decharges/decharge/views/syndicats_a_relancer.py
from django.views.generic import TemplateView from decharges.decharge.mixins import CheckConfigurationMixin, FederationRequiredMixin from decharges.decharge.models import ( TempsDeDecharge, UtilisationCreditDeTempsSyndicalPonctuel, UtilisationTempsDecharge, ) from decharges.decharge.views.utils import calc...
0.414899
0.209348
import unittest from bacpypes.debugging import bacpypes_debugging, ModuleLogger from bacpypes.comm import ServiceAccessPoint, ApplicationServiceElement, bind from ..trapped_classes import TrappedServiceAccessPoint, \ TrappedApplicationServiceElement # some debugging _debug = 0 _log = ModuleLogger(globals()) # g...
tests/test_utilities/test_service_access_point.py
import unittest from bacpypes.debugging import bacpypes_debugging, ModuleLogger from bacpypes.comm import ServiceAccessPoint, ApplicationServiceElement, bind from ..trapped_classes import TrappedServiceAccessPoint, \ TrappedApplicationServiceElement # some debugging _debug = 0 _log = ModuleLogger(globals()) # g...
0.396886
0.239891
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.utils.timezone import tagging.fields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
posts/migrations/0001_initial.py
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.utils.timezone import tagging.fields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
0.57069
0.141815
from __future__ import print_function import sys from .util import is_a_tty class ColorPrinterMeta(type): def __init__(cls, *args, **kwargs): def _make_methods(_color): def _print(self, *a, **kw): kw["color"] = _color return self.print(*a, **kw) d...
src/local_settings/color_printer.py
from __future__ import print_function import sys from .util import is_a_tty class ColorPrinterMeta(type): def __init__(cls, *args, **kwargs): def _make_methods(_color): def _print(self, *a, **kw): kw["color"] = _color return self.print(*a, **kw) d...
0.606382
0.117193
import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import os test_stub = test_lib.lib_get_test_stub() test_obj_dict = test_state.TestStateDict() def test(): test_util.test_dsc('Create test vm with EIP and check.') ...
integrationtest/vm/virtualrouter/eip/test_check_download_on_eip_vm.py
import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import os test_stub = test_lib.lib_get_test_stub() test_obj_dict = test_state.TestStateDict() def test(): test_util.test_dsc('Create test vm with EIP and check.') ...
0.078124
0.353261
import datetime as dt import copy from enum import Enum from dataclasses import dataclass, field import uuid from typing import List, Optional, Dict, cast class VectorClockItem: """Stores the timestamp from a specific provider""" provider_id: "str" timestamp: "dt.datetime" def __init__(self, provide...
maestro/core/metadata.py
import datetime as dt import copy from enum import Enum from dataclasses import dataclass, field import uuid from typing import List, Optional, Dict, cast class VectorClockItem: """Stores the timestamp from a specific provider""" provider_id: "str" timestamp: "dt.datetime" def __init__(self, provide...
0.930229
0.507019
import pytest from eth_abi import encode_single from eth_tester import exceptions from web3 import Web3 ZERO_ADDRESS = "0x" + "0" * 40 SECRET = encode_single("bytes32", b"123456ab") HASHED_SECRET = Web3.solidityKeccak(["bytes32"], [SECRET]) MAX_FEE = 2 ** 64 - 1 WEEK_SECONDS = 60 * 60 * 24 * 7 def get_events_of_con...
tests/test_tl_swap.py
import pytest from eth_abi import encode_single from eth_tester import exceptions from web3 import Web3 ZERO_ADDRESS = "0x" + "0" * 40 SECRET = encode_single("bytes32", b"123456ab") HASHED_SECRET = Web3.solidityKeccak(["bytes32"], [SECRET]) MAX_FEE = 2 ** 64 - 1 WEEK_SECONDS = 60 * 60 * 24 * 7 def get_events_of_con...
0.677581
0.307235
import argparse import sys import logging import time import subprocess import socket import numpy import dask from distributed import Executor parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--tasks", type=int, default=1, help="") parser.add_argument( "--task-time-s...
benchmarking/benchmark.py
import argparse import sys import logging import time import subprocess import socket import numpy import dask from distributed import Executor parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--tasks", type=int, default=1, help="") parser.add_argument( "--task-time-s...
0.282196
0.109992
from em import molecule from em.dataset import metrics from mpi4py import MPI from mpi4py.futures import MPICommExecutor from concurrent.futures import wait import os import argparse import numpy as np import pandas as pd import copy import json from json import encoder from skimage.measure import regionprops import ...
em/src/dataset/data_augmentation.py
from em import molecule from em.dataset import metrics from mpi4py import MPI from mpi4py.futures import MPICommExecutor from concurrent.futures import wait import os import argparse import numpy as np import pandas as pd import copy import json from json import encoder from skimage.measure import regionprops import ...
0.351089
0.297291
from django.contrib.auth import authenticate from django import forms from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.urls import reverse from django.utils.safestring import mark_safe from .models import Profile, Device from phonenumber_field.formfields imp...
accounts/forms.py
from django.contrib.auth import authenticate from django import forms from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.urls import reverse from django.utils.safestring import mark_safe from .models import Profile, Device from phonenumber_field.formfields imp...
0.53048
0.090333
import os from urllib.request import urlopen import requests import tarfile import pandas as pd from typing import List from tqdm import tqdm from microsim.column_names import ColumnNames class Optimise: """ Functions to optimise the memory use of pandas dataframes. From https://medium.com/bigdatarepubli...
microsim/utilities.py
import os from urllib.request import urlopen import requests import tarfile import pandas as pd from typing import List from tqdm import tqdm from microsim.column_names import ColumnNames class Optimise: """ Functions to optimise the memory use of pandas dataframes. From https://medium.com/bigdatarepubli...
0.710628
0.371593
import numpy as np class WeightInitializer: def compute_fans(self, shape): """ func: compute_fans adapted from keras: https://github.com/fchollet/keras/blob/master/keras/initializers.py copyright held by fchollet(keras-team), 2017 as part of Keras project licence: MIT ""...
ztlearn/initializers.py
import numpy as np class WeightInitializer: def compute_fans(self, shape): """ func: compute_fans adapted from keras: https://github.com/fchollet/keras/blob/master/keras/initializers.py copyright held by fchollet(keras-team), 2017 as part of Keras project licence: MIT ""...
0.955371
0.701541
import os import sys import csv import random import pandas as pd import numpy as np _thisDir = os.path.dirname(os.path.abspath(__file__)).decode(sys.getfilesystemencoding()) _parentDir = os.path.abspath(os.path.join(_thisDir, os.pardir)) dataDir = _parentDir + '/data/' def get_trivia(): questions = pd.read_csv(_thi...
kangacuriositytask/utils.py
import os import sys import csv import random import pandas as pd import numpy as np _thisDir = os.path.dirname(os.path.abspath(__file__)).decode(sys.getfilesystemencoding()) _parentDir = os.path.abspath(os.path.join(_thisDir, os.pardir)) dataDir = _parentDir + '/data/' def get_trivia(): questions = pd.read_csv(_thi...
0.081918
0.169543
"""Service functions to handle athena connections.""" from django.template.loader import render_to_string from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from ontask import models from ontask.connection.services.crud import ( ConnectionTableAdmin, ConnectionTableSelect, ) f...
ontask/connection/services/athena.py
"""Service functions to handle athena connections.""" from django.template.loader import render_to_string from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from ontask import models from ontask.connection.services.crud import ( ConnectionTableAdmin, ConnectionTableSelect, ) f...
0.806434
0.227748
import math import cv2 import numpy as np from tqdm import tqdm from .base import Eval class SRN(Eval): '''Tests SRN ''' def __init__(self, dataset, model, ms=False, max_downsample=1): super(SRN, self).__init__(dataset, model, ms, max_downsample) def multi_scale_testing(self): large...
eval_core/srn.py
import math import cv2 import numpy as np from tqdm import tqdm from .base import Eval class SRN(Eval): '''Tests SRN ''' def __init__(self, dataset, model, ms=False, max_downsample=1): super(SRN, self).__init__(dataset, model, ms, max_downsample) def multi_scale_testing(self): large...
0.409575
0.160661
import dateutil.tz from datetime import datetime, date, timedelta import pytz from django.conf import settings from django.db.models.functions import TruncDay from django.utils.lru_cache import lru_cache from manabi.apps.flashcards.models import CardHistory _WEEKS_TO_REPORT = 9 def _start_of_today(user_timezone):...
manabi/apps/review_results/models.py
import dateutil.tz from datetime import datetime, date, timedelta import pytz from django.conf import settings from django.db.models.functions import TruncDay from django.utils.lru_cache import lru_cache from manabi.apps.flashcards.models import CardHistory _WEEKS_TO_REPORT = 9 def _start_of_today(user_timezone):...
0.651133
0.203628
import json import warnings import requests from .exceptions import ( InvalidSearchParamException, InvalidVersionException, InvalidUseFirstNameAliasException, InvalidAddressPurposeException, NPyIException, ) BASE_URI = "https://npiregistry.cms.hhs.gov/api/" VALID_SEARCH_PARAMS = ( "number", ...
npyi/npi.py
import json import warnings import requests from .exceptions import ( InvalidSearchParamException, InvalidVersionException, InvalidUseFirstNameAliasException, InvalidAddressPurposeException, NPyIException, ) BASE_URI = "https://npiregistry.cms.hhs.gov/api/" VALID_SEARCH_PARAMS = ( "number", ...
0.699562
0.200597
from dataclasses import dataclass from datetime import datetime from typing import Union from json import dumps from aiohttp import FormData from ..errors.message import SendMessageFailed from ..errors.channel import * @dataclass class Guild: """Guild class. Args: client (Client): Krema client. ...
src/models/guild.py
from dataclasses import dataclass from datetime import datetime from typing import Union from json import dumps from aiohttp import FormData from ..errors.message import SendMessageFailed from ..errors.channel import * @dataclass class Guild: """Guild class. Args: client (Client): Krema client. ...
0.890634
0.194081
from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase import json class ApiTests(APITestCase): fixtures = ['test.json'] def test_root_view_contains_link_to_documentation(self): url = reverse('root') response = self.client.get(url) ...
ticketapi/api/tests.py
from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase import json class ApiTests(APITestCase): fixtures = ['test.json'] def test_root_view_contains_link_to_documentation(self): url = reverse('root') response = self.client.get(url) ...
0.494385
0.228253
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys sys.path.append('./gen-py') from FacePi.ttypes import PersonEntry import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf from tensorflow.python.platform import gfile...
FacePi/src/FaceRecognition/TensorFlow/startTensor.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys sys.path.append('./gen-py') from FacePi.ttypes import PersonEntry import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf from tensorflow.python.platform import gfile...
0.356895
0.058239
import numpy as np import matplotlib.pyplot as plt plt.ion() #load dataset dataset = open('../data/input.txt','r').read() len_of_dataset = len(dataset) print('length of dataset:',len_of_dataset) vocab = set(dataset) len_of_vocab = len(vocab) print('length of vocab:',len_of_vocab) char_to_idx = {char:idx for idx,cha...
code/lstm_with_peephole_connections.py
import numpy as np import matplotlib.pyplot as plt plt.ion() #load dataset dataset = open('../data/input.txt','r').read() len_of_dataset = len(dataset) print('length of dataset:',len_of_dataset) vocab = set(dataset) len_of_vocab = len(vocab) print('length of vocab:',len_of_vocab) char_to_idx = {char:idx for idx,cha...
0.180431
0.326728
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'LedgerTagArgs', 'StreamKinesisConfigurationArgs', 'StreamTagArgs', ] @pulumi.input_type class LedgerTagArgs: def __init__(__self__, *, ...
sdk/python/pulumi_aws_native/qldb/_inputs.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'LedgerTagArgs', 'StreamKinesisConfigurationArgs', 'StreamTagArgs', ] @pulumi.input_type class LedgerTagArgs: def __init__(__self__, *, ...
0.870638
0.083255
import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.svm import SVR from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.neural_network import MLPClassifier from xgboost import XGBRFClassifier from lightgbm impo...
baseline_model_classifier.py
import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.svm import SVR from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.neural_network import MLPClassifier from xgboost import XGBRFClassifier from lightgbm impo...
0.621885
0.28768
import requests from eth_utils import to_hex from raiden.constants import DEFAULT_HTTP_REQUEST_TIMEOUT from raiden.exceptions import ServiceRequestFailed from raiden.utils import typing from raiden_contracts.utils.proofs import sign_one_to_n_iou def get_pfs_info(url: str) -> typing.Optional[typing.Dict]: try: ...
raiden/network/pathfinding.py
import requests from eth_utils import to_hex from raiden.constants import DEFAULT_HTTP_REQUEST_TIMEOUT from raiden.exceptions import ServiceRequestFailed from raiden.utils import typing from raiden_contracts.utils.proofs import sign_one_to_n_iou def get_pfs_info(url: str) -> typing.Optional[typing.Dict]: try: ...
0.601125
0.10316
import xml.etree.ElementTree as ET parsers = {} def getParser(langPath): global parsers if langPath not in parsers: parsers[langPath] = Parser(langPath) return parsers[langPath] class Parser: def __init__(self, langPath): #Initialize variables self.syllables = set() sel...
SyllableParser/parser.py
import xml.etree.ElementTree as ET parsers = {} def getParser(langPath): global parsers if langPath not in parsers: parsers[langPath] = Parser(langPath) return parsers[langPath] class Parser: def __init__(self, langPath): #Initialize variables self.syllables = set() sel...
0.450843
0.16872
import csv import datetime import FileUtil import json import os import sys from com.ziclix.python.sql import zxJDBC from org.slf4j import LoggerFactory from wherehows.common import Constant class OracleExtract: table_dict = {} table_output_list = [] field_output_list = [] sample_output_list = [] ignored...
wherehows-etl/src/main/resources/jython/OracleExtract.py
import csv import datetime import FileUtil import json import os import sys from com.ziclix.python.sql import zxJDBC from org.slf4j import LoggerFactory from wherehows.common import Constant class OracleExtract: table_dict = {} table_output_list = [] field_output_list = [] sample_output_list = [] ignored...
0.301362
0.103341
import bisect import os import sys EXPORT_RDR = True try: import rosbag except ImportError, e: print 'Failed to import rosbag, not exporting radar' EXPORT_RDR = False sys.path.append('../process') from GPSReader import GPSReader class FrameFinder: """ Creates a mapping from cloud to frames. """...
lidar/FrameFinder.py
import bisect import os import sys EXPORT_RDR = True try: import rosbag except ImportError, e: print 'Failed to import rosbag, not exporting radar' EXPORT_RDR = False sys.path.append('../process') from GPSReader import GPSReader class FrameFinder: """ Creates a mapping from cloud to frames. """...
0.26218
0.22288
from dolfin import * from dolfin_adjoint import * import numpy as np from scipy import io import ufl set_log_level(LogLevel.ERROR) from preprocessing import Preprocessing from ipopt_solver import IPOPTSolver, IPOPTProblem import Hs_regularization as Hs_reg try: from pyadjoint import ipopt # noqa: F401 except Im...
topopt/topopt.py
from dolfin import * from dolfin_adjoint import * import numpy as np from scipy import io import ufl set_log_level(LogLevel.ERROR) from preprocessing import Preprocessing from ipopt_solver import IPOPTSolver, IPOPTProblem import Hs_regularization as Hs_reg try: from pyadjoint import ipopt # noqa: F401 except Im...
0.504883
0.422981
from __future__ import (print_function, division, absolute_import, unicode_literals) from django.test import TestCase from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from ..models import Badge, FUNCTION_WITH_RELATED_MODEL, UserBadge from ..badge_registry impor...
badgificator/tests/test_functions_condition.py
from __future__ import (print_function, division, absolute_import, unicode_literals) from django.test import TestCase from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from ..models import Badge, FUNCTION_WITH_RELATED_MODEL, UserBadge from ..badge_registry impor...
0.382949
0.18543
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import codecs import shutil import zipfile import requests __all__ = [ "wget", "unzip", "rm", "mkdir", "rmdir", "mv" ] _CURRENT_FILE = os.path.dirname(__file__) def wget(url, sa...
PyCLUE/utils/utils/file_utils.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import codecs import shutil import zipfile import requests __all__ = [ "wget", "unzip", "rm", "mkdir", "rmdir", "mv" ] _CURRENT_FILE = os.path.dirname(__file__) def wget(url, sa...
0.338077
0.069479
import sys from pathlib import Path from collections import Counter from django.core.management.base import BaseCommand, CommandError from django.db.utils import DataError, OperationalError, IntegrityError from django_lr_loader.models import LightroomCatalog, LightroomImageFileInfo, ImageToFileInfo from django_fs_searc...
django_lr_loader/management/commands/match_images_to_file_system.py
import sys from pathlib import Path from collections import Counter from django.core.management.base import BaseCommand, CommandError from django.db.utils import DataError, OperationalError, IntegrityError from django_lr_loader.models import LightroomCatalog, LightroomImageFileInfo, ImageToFileInfo from django_fs_searc...
0.207455
0.157169
import random from django.core import validators from django.core.exceptions import ValidationError from django.db import models from django.forms.models import model_to_dict from model_utils.models import TimeFramedModel, TimeStampedModel from s3direct.fields import S3DirectField # pylint: disable=cyclic-import fr...
will_of_the_prophets/models.py
import random from django.core import validators from django.core.exceptions import ValidationError from django.db import models from django.forms.models import model_to_dict from model_utils.models import TimeFramedModel, TimeStampedModel from s3direct.fields import S3DirectField # pylint: disable=cyclic-import fr...
0.747432
0.197406
from __future__ import absolute_import, division, print_function import logging as log from traceback import format_exc from pprint import pformat from . import FormatProvider, providers __all__ = ['DictFormatProvider'] class DictFormatProvider(FormatProvider): """ Python dictionary format provider. ...
lib/confspec/providers/dict.py
from __future__ import absolute_import, division, print_function import logging as log from traceback import format_exc from pprint import pformat from . import FormatProvider, providers __all__ = ['DictFormatProvider'] class DictFormatProvider(FormatProvider): """ Python dictionary format provider. ...
0.668231
0.092237
import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("polaris", "0002_auto_20191125_1829"), ] operations = [ migrations.AlterField( model_name="asset", name="deposit_fee_fixed", ...
polaris/polaris/migrations/0003_auto_20191211_1512.py
import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("polaris", "0002_auto_20191125_1829"), ] operations = [ migrations.AlterField( model_name="asset", name="deposit_fee_fixed", ...
0.626924
0.195095
import ast import os import math import profiler as profiler class KNN: def __init__(self, kValue): self.K=kValue def classify(self, newProfile): existingProfiles=open('results/authorProfiles.txt') allDistances=dict() for lines in existingProfiles: lines=lines.strip() existingProfile=ast.literal_eval(...
src/kNN.py
import ast import os import math import profiler as profiler class KNN: def __init__(self, kValue): self.K=kValue def classify(self, newProfile): existingProfiles=open('results/authorProfiles.txt') allDistances=dict() for lines in existingProfiles: lines=lines.strip() existingProfile=ast.literal_eval(...
0.06469
0.092401
import gzip import logging from finntk.utils import ResourceMan, urlretrieve from finntk.vendor.conceptnet5.uri import concept_uri from shutil import copyfileobj import os from .base import MultilingualVectorSpace, RefType from .utils import get, get_tmpfile, load_word2vec_format, load logger = logging.getLogger(__nam...
finntk/emb/numberbatch.py
import gzip import logging from finntk.utils import ResourceMan, urlretrieve from finntk.vendor.conceptnet5.uri import concept_uri from shutil import copyfileobj import os from .base import MultilingualVectorSpace, RefType from .utils import get, get_tmpfile, load_word2vec_format, load logger = logging.getLogger(__nam...
0.386185
0.077169
import gtk import gobject COLUMN_NUMBER = 0 COLUMN_STRING = 1 COLUMN_BOOL = 2 data = [ [ 1, 'first row', True ], [ 2, 'second row', True ], [ 3, 'third row', True ], [ 4, 'fourth row', True ], [ 5, 'fifth row', True ], [ 6, 'sixth row', True ], [ 7, 'seventh row', None ], [ 8, 'eigth r...
test/samples/gtk/gtkliststore.py
import gtk import gobject COLUMN_NUMBER = 0 COLUMN_STRING = 1 COLUMN_BOOL = 2 data = [ [ 1, 'first row', True ], [ 2, 'second row', True ], [ 3, 'third row', True ], [ 4, 'fourth row', True ], [ 5, 'fifth row', True ], [ 6, 'sixth row', True ], [ 7, 'seventh row', None ], [ 8, 'eigth r...
0.219087
0.218836
from typing import Dict, Optional, Tuple import torch from torch import Tensor from torch.distributions import Distribution from torch.optim import RMSprop from memory import Memory from policy import Policy class Agent(): def __init__(self, observation_size: int, action_size: int, goal_size: int, hidden_size: in...
agent.py
from typing import Dict, Optional, Tuple import torch from torch import Tensor from torch.distributions import Distribution from torch.optim import RMSprop from memory import Memory from policy import Policy class Agent(): def __init__(self, observation_size: int, action_size: int, goal_size: int, hidden_size: in...
0.956462
0.621024
from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\28") buf.write("\u0163\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7") buf.write("\t\7\4\b\t\b\4...
grammar/sdplLexer.py
from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\28") buf.write("\u0163\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7") buf.write("\t\7\4\b\t\b\4...
0.284874
0.332256
import validators from itertools import chain from typing import Set, Union import urlfinderlib.helpers as helpers import urlfinderlib.tokenizer as tokenizer from urlfinderlib.url import URLList class TextUrlFinder: def __init__(self, blob: Union[bytes, str]): if isinstance(blob, str): blob...
urlfinderlib/finders/text.py
import validators from itertools import chain from typing import Set, Union import urlfinderlib.helpers as helpers import urlfinderlib.tokenizer as tokenizer from urlfinderlib.url import URLList class TextUrlFinder: def __init__(self, blob: Union[bytes, str]): if isinstance(blob, str): blob...
0.63624
0.195729
from sleekxmpp.plugins.base import base_plugin from rhobot.components.configuration import BotConfiguration from rhobot.components.storage import StoragePayload from foursquare_bot.components.configuration_enums import CLIENT_SECRET_KEY, IDENTIFIER_KEY from foursquare_bot.components.utilities import get_foursquare_venu...
foursquare_bot/components/foursquare_lookup.py
from sleekxmpp.plugins.base import base_plugin from rhobot.components.configuration import BotConfiguration from rhobot.components.storage import StoragePayload from foursquare_bot.components.configuration_enums import CLIENT_SECRET_KEY, IDENTIFIER_KEY from foursquare_bot.components.utilities import get_foursquare_venu...
0.610221
0.106226
from __future__ import annotations import logging import uuid from copy import deepcopy from typing import ( TYPE_CHECKING, Any, AsyncIterator, Dict, Iterator, List, Optional, Type, Union, ) from algoliasearch.search_client import SearchClient if TYPE_CHECKING: from types impo...
astropylibrarian/algolia/client.py
from __future__ import annotations import logging import uuid from copy import deepcopy from typing import ( TYPE_CHECKING, Any, AsyncIterator, Dict, Iterator, List, Optional, Type, Union, ) from algoliasearch.search_client import SearchClient if TYPE_CHECKING: from types impo...
0.913845
0.204898
# Commented out IPython magic to ensure Python compatibility. import pandas as pd import numpy as np import matplotlib.pyplot as plt # %matplotlib inline data = pd.read_csv("london_merged.csv") data """Metadata: - "timestamp" - timestamp field for grouping the data - "cnt" - the count of a new bike shares - "t1" - r...
London Bike Share Usage Prediction/london_bike_sharing_usage_prediction.py
# Commented out IPython magic to ensure Python compatibility. import pandas as pd import numpy as np import matplotlib.pyplot as plt # %matplotlib inline data = pd.read_csv("london_merged.csv") data """Metadata: - "timestamp" - timestamp field for grouping the data - "cnt" - the count of a new bike shares - "t1" - r...
0.639961
0.611121
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('seaborn-darkgrid') import argparse import csv import os import sys import pickle import numpy as np import pandas as pd from os.path import join from collections import defaultdict # matplotlib titlesize = 33 xsize = 30 ysize = 30 t...
scripts/mujoco_results.py
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('seaborn-darkgrid') import argparse import csv import os import sys import pickle import numpy as np import pandas as pd from os.path import join from collections import defaultdict # matplotlib titlesize = 33 xsize = 30 ysize = 30 t...
0.547706
0.408985
import cv2 import numpy as np from ..adapters import Adapter from ..config import StringField from ..representation import BackgroundMattingPrediction class ImageBackgroundMattingAdapter(Adapter): __provider__ = 'background_matting_with_pha_and_fgr' def process(self, raw, identifiers, frame_meta): i...
tools/accuracy_checker/openvino/tools/accuracy_checker/adapters/background_matting.py
import cv2 import numpy as np from ..adapters import Adapter from ..config import StringField from ..representation import BackgroundMattingPrediction class ImageBackgroundMattingAdapter(Adapter): __provider__ = 'background_matting_with_pha_and_fgr' def process(self, raw, identifiers, frame_meta): i...
0.550849
0.233368
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('climatemodels', '0094_auto_20190404_0854'), ] operations = [ migrations.AddField( model_name='biomes', name='compute_soil_ca...
isi_mip/climatemodels/migrations/0095_auto_20190408_1053.py
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('climatemodels', '0094_auto_20190404_0854'), ] operations = [ migrations.AddField( model_name='biomes', name='compute_soil_ca...
0.705075
0.211173
import nltk import sys import os import string import math FILE_MATCHES = 1 SENTENCE_MATCHES = 1 def main(): # Check command-line arguments if len(sys.argv) != 2: sys.exit("Usage: python questions.py corpus") # Calculate IDF values across files files = load_files(sys.argv[1]) file_words...
Intro To Artificial Intelligence/Projects/week6/questions/questions.py
import nltk import sys import os import string import math FILE_MATCHES = 1 SENTENCE_MATCHES = 1 def main(): # Check command-line arguments if len(sys.argv) != 2: sys.exit("Usage: python questions.py corpus") # Calculate IDF values across files files = load_files(sys.argv[1]) file_words...
0.501221
0.432303
from __future__ import division from collections import namedtuple import math Vector3 = namedtuple('Vector3', ['x', 'y', 'z']) Vector2 = namedtuple('Vector2', ['x', 'y']) def crossProduct(a, b): """ return normalized cross product """ x = a.y*b.z - a.z*b.y y = -(a.x*b.z - a.z*b.x) z = a.x*b.y -...
cadnano/extras/math/vector.py
from __future__ import division from collections import namedtuple import math Vector3 = namedtuple('Vector3', ['x', 'y', 'z']) Vector2 = namedtuple('Vector2', ['x', 'y']) def crossProduct(a, b): """ return normalized cross product """ x = a.y*b.z - a.z*b.y y = -(a.x*b.z - a.z*b.x) z = a.x*b.y -...
0.72027
0.746486
import h5py, yaml, re, cPickle, shutil from control4.misc.console_utils import mkdirp,yes_or_no from collections import OrderedDict import os.path as osp class ScriptRun(object): def __init__(self, info, script_name, run_idx, out_root): info = info.copy() self.info = info self.script_name ...
control4/bench/bench.py
import h5py, yaml, re, cPickle, shutil from control4.misc.console_utils import mkdirp,yes_or_no from collections import OrderedDict import os.path as osp class ScriptRun(object): def __init__(self, info, script_name, run_idx, out_root): info = info.copy() self.info = info self.script_name ...
0.199854
0.140395
import torch import torch.nn as nn import numpy as np import copy from typing import Any, ClassVar, Dict, List, Optional, Sequence, Type, Union from d3rlpy.models.encoders import EncoderFactory, Encoder, VectorEncoderWithAction, _create_activation, VectorEncoder class CustomVectorEncoder(VectorEncoder): def __in...
rl4rs/nets/cql/encoder.py
import torch import torch.nn as nn import numpy as np import copy from typing import Any, ClassVar, Dict, List, Optional, Sequence, Type, Union from d3rlpy.models.encoders import EncoderFactory, Encoder, VectorEncoderWithAction, _create_activation, VectorEncoder class CustomVectorEncoder(VectorEncoder): def __in...
0.95156
0.460532
from timo.decorators import timer from timo.utils import colored_print from timo.utils import equals from timo.utils import get_command_black_list from typing import List from typing import NoReturn import platform import subprocess import shlex class CommandRunner(object): """Perform tests.""" def _convert_...
timo/test_manager/command_runner.py
from timo.decorators import timer from timo.utils import colored_print from timo.utils import equals from timo.utils import get_command_black_list from typing import List from typing import NoReturn import platform import subprocess import shlex class CommandRunner(object): """Perform tests.""" def _convert_...
0.806777
0.2194
from viperid import app import unittest class ViperidTestCase(unittest.TestCase): contract_1 = { 'code': 'def foo(x: num) -> num:\n return x * 2' } def setUp(self): app.testing = True def test_compile_to_abi(self): result = {'result': [{'constant': False, 'inputs': [{'name...
backend/tests/tests_viperid.py
from viperid import app import unittest class ViperidTestCase(unittest.TestCase): contract_1 = { 'code': 'def foo(x: num) -> num:\n return x * 2' } def setUp(self): app.testing = True def test_compile_to_abi(self): result = {'result': [{'constant': False, 'inputs': [{'name...
0.445288
0.485478
import random from tools import binExtend, crc class networkLayer(object): """ networkLayer:ip package ipv4 """ def __init__(self): super(networkLayer, self).__init__() self.outEncodeData = [] # self.outDecodeData = [] self.pacSize = 146*8 + 32*5 self.ipHeaderDict = {} self.ipHeader = [] def netEncode...
chatroom/layers/networkLayer.py
import random from tools import binExtend, crc class networkLayer(object): """ networkLayer:ip package ipv4 """ def __init__(self): super(networkLayer, self).__init__() self.outEncodeData = [] # self.outDecodeData = [] self.pacSize = 146*8 + 32*5 self.ipHeaderDict = {} self.ipHeader = [] def netEncode...
0.149904
0.258718
import numpy as np import epipack as epk import numpy as np import networkx as nx def make_equal_length(arr_list): maxlen = max([len(a) for a in arr_list]) new_arr_list = [] for a in arr_list: dL = maxlen - len(a) if dL > 0: newa = np.concatenate((a, np.ones(dL)*a[-1])) ...
analysis_collection/tracing_sim/results_toy_model/simulation.py
import numpy as np import epipack as epk import numpy as np import networkx as nx def make_equal_length(arr_list): maxlen = max([len(a) for a in arr_list]) new_arr_list = [] for a in arr_list: dL = maxlen - len(a) if dL > 0: newa = np.concatenate((a, np.ones(dL)*a[-1])) ...
0.181372
0.266229
import numpy as np from torch import nn from torch.nn import functional as F class CELEBAgenerator(nn.Module): def __init__(self, args): super(CELEBAgenerator, self).__init__() self._name = 'celebaG' self.shape = (64, 64, 3) self.dim = args.dim preprocess = nn.Sequential( ...
generators.py
import numpy as np from torch import nn from torch.nn import functional as F class CELEBAgenerator(nn.Module): def __init__(self, args): super(CELEBAgenerator, self).__init__() self._name = 'celebaG' self.shape = (64, 64, 3) self.dim = args.dim preprocess = nn.Sequential( ...
0.957368
0.42483
import sqlalchemy import sqlalchemy.orm from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Student(Base): # type: ignore __tablename__ = 'student' id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True) name = sqlalchemy.Column(sqlalchemy.String(250), nullable=F...
src/grader_toolkit/gradebook.py
import sqlalchemy import sqlalchemy.orm from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Student(Base): # type: ignore __tablename__ = 'student' id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True) name = sqlalchemy.Column(sqlalchemy.String(250), nullable=F...
0.376738
0.112967
from .tool.func import * def main_func_setting_main(db_set): with get_db_connect() as conn: curs = conn.cursor() if admin_check() != 1: return re_error('/ban') setting_list = { 0 : ['name', 'Wiki'], 2 : ['frontpage', 'FrontPage'], 4 ...
route/main_func_setting_main.py
from .tool.func import * def main_func_setting_main(db_set): with get_db_connect() as conn: curs = conn.cursor() if admin_check() != 1: return re_error('/ban') setting_list = { 0 : ['name', 'Wiki'], 2 : ['frontpage', 'FrontPage'], 4 ...
0.248899
0.20834
from typing import Union, List, Tuple, Dict, Any from psycopg2 import sql, extensions from general_utils.postgres_utils import LocalhostCursor from general_utils.type_helpers import validate_is_int class Field(sql.Identifier): """ A composable instance for a field that allows it to work as an element in a q...
general_utils/sql_utils.py
from typing import Union, List, Tuple, Dict, Any from psycopg2 import sql, extensions from general_utils.postgres_utils import LocalhostCursor from general_utils.type_helpers import validate_is_int class Field(sql.Identifier): """ A composable instance for a field that allows it to work as an element in a q...
0.910613
0.468912
import re import sys if sys.version < '3': def u(x): return x.decode('utf-8') else: unicode = str def u(x): return x # Matches section start `interfaces {` rx_section = re.compile(r'^([\w\-]+) \{$', re.UNICODE) # Matches named section `ethernet eth0 {` rx_named_section = re.compile( ...
vyattaconfparser/parser.py
import re import sys if sys.version < '3': def u(x): return x.decode('utf-8') else: unicode = str def u(x): return x # Matches section start `interfaces {` rx_section = re.compile(r'^([\w\-]+) \{$', re.UNICODE) # Matches named section `ethernet eth0 {` rx_named_section = re.compile( ...
0.250088
0.402275
import paddle import paddle.nn as nn import paddle.nn.functional as F from paddle.vision.models import vgg16 from ppcd.models.layers import CAM, SAM class Vgg16Base(nn.Layer): # Vgg16 feature extraction backbone def __init__(self, in_channels=3): super(Vgg16Base, self).__init__() features = vg...
ppcd/models/dsifn.py
import paddle import paddle.nn as nn import paddle.nn.functional as F from paddle.vision.models import vgg16 from ppcd.models.layers import CAM, SAM class Vgg16Base(nn.Layer): # Vgg16 feature extraction backbone def __init__(self, in_channels=3): super(Vgg16Base, self).__init__() features = vg...
0.923212
0.291378
from pathlib import Path from typing import Union, Optional from collections import OrderedDict import re import math import torch from .. import Results as Results_ # old Results class class Results: """Class representing BCN training results. Attributes: epoch (int): The number of epochs the BCN model ...
bcn/v0/compat.py
from pathlib import Path from typing import Union, Optional from collections import OrderedDict import re import math import torch from .. import Results as Results_ # old Results class class Results: """Class representing BCN training results. Attributes: epoch (int): The number of epochs the BCN model ...
0.950698
0.439567
from ..base import disk from infi.pyutils.lazy import cached_method # pylint: disable=R0921 class LinuxDiskDrive(disk.DiskDrive): def __init__(self, storage_device, scsi_disk_path): super(LinuxDiskDrive, self).__init__() self._storage_device = storage_device self._scsi_disk_path = scsi_dis...
src/infi/storagemodel/linux/disk.py
from ..base import disk from infi.pyutils.lazy import cached_method # pylint: disable=R0921 class LinuxDiskDrive(disk.DiskDrive): def __init__(self, storage_device, scsi_disk_path): super(LinuxDiskDrive, self).__init__() self._storage_device = storage_device self._scsi_disk_path = scsi_dis...
0.459076
0.088347
import re import os from git import Repo, InvalidGitRepositoryError, NoSuchPathError from elifetools import utils as etoolsutils def repl(match): "Convert hex to int to unicode character" chr_code = int(match.group(1), 16) return chr(chr_code) def entity_to_unicode(string): """ Quick convert uni...
elifearticle/utils.py
import re import os from git import Repo, InvalidGitRepositoryError, NoSuchPathError from elifetools import utils as etoolsutils def repl(match): "Convert hex to int to unicode character" chr_code = int(match.group(1), 16) return chr(chr_code) def entity_to_unicode(string): """ Quick convert uni...
0.439026
0.254932
from threading import Thread import cv2 import numpy as np from pyzbar.pyzbar import decode from typing import List, Any, Union from security.database.firestore import Firestore from security.user.user import User from security.tts.messages import Messages from security.tts.text_to_speech import TTS from .util import ...
security/recognition/qr_recognizer.py
from threading import Thread import cv2 import numpy as np from pyzbar.pyzbar import decode from typing import List, Any, Union from security.database.firestore import Firestore from security.user.user import User from security.tts.messages import Messages from security.tts.text_to_speech import TTS from .util import ...
0.795539
0.192065
import logging import six.moves.urllib as urllib from algosec.api_clients.base import SoapAPIClient from algosec.errors import AlgoSecLoginError, AlgoSecAPIError from algosec.helpers import report_soap_failure logger = logging.getLogger(__name__) class FireFlowAPIClient(SoapAPIClient): """*FireFlow* SOAP API c...
algosec/api_clients/fire_flow.py
import logging import six.moves.urllib as urllib from algosec.api_clients.base import SoapAPIClient from algosec.errors import AlgoSecLoginError, AlgoSecAPIError from algosec.helpers import report_soap_failure logger = logging.getLogger(__name__) class FireFlowAPIClient(SoapAPIClient): """*FireFlow* SOAP API c...
0.763043
0.222267
import numpy as np def moving_average(x, window=3, mode='full'): ''' Calculate the moving average over an array. Summary ------- This function computes the running mean of an array. Padding is performed for the "left" side, not for the "right". Parameters ---------- x : array ...
torchutils/tools.py
import numpy as np def moving_average(x, window=3, mode='full'): ''' Calculate the moving average over an array. Summary ------- This function computes the running mean of an array. Padding is performed for the "left" side, not for the "right". Parameters ---------- x : array ...
0.932269
0.759894
import re import logging from bs4 import BeautifulSoup import requests from concurrent.futures import ThreadPoolExecutor def is_subseq(the_seq, the_string): rgx = re.compile('.*'.join([re.escape(x) for x in the_seq])) return rgx.search(the_string) def is_hero_searched(query, raw_name): name = raw_name.l...
app/scrape.py
import re import logging from bs4 import BeautifulSoup import requests from concurrent.futures import ThreadPoolExecutor def is_subseq(the_seq, the_string): rgx = re.compile('.*'.join([re.escape(x) for x in the_seq])) return rgx.search(the_string) def is_hero_searched(query, raw_name): name = raw_name.l...
0.342132
0.156169
import os import os.path import sys import json import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn="https://4ccfa35d8c424f2d87cc3aca96611bb6@o447032.ingest.sentry.io/5426444", integrations=[DjangoIntegration()], traces_sample_rate=1.0, # If you wish to ...
zedway/settings.py
import os import os.path import sys import json import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn="https://4ccfa35d8c424f2d87cc3aca96611bb6@o447032.ingest.sentry.io/5426444", integrations=[DjangoIntegration()], traces_sample_rate=1.0, # If you wish to ...
0.237576
0.066176
from sklearn.metrics import roc_auc_score import shap import numpy as np import skexplain from skexplain.common.importance_utils import to_skexplain_importance from tests import TestLR, TestRF TRUE_RANKINGS = np.array(["X_1", "X_2", "X_3", "X_4", "X_5"], dtype=object) class TestRankings(TestLR, TestRF): def te...
tests/test_feature_ranking.py
from sklearn.metrics import roc_auc_score import shap import numpy as np import skexplain from skexplain.common.importance_utils import to_skexplain_importance from tests import TestLR, TestRF TRUE_RANKINGS = np.array(["X_1", "X_2", "X_3", "X_4", "X_5"], dtype=object) class TestRankings(TestLR, TestRF): def te...
0.61855
0.500366
import cupy as cp from ArraysCollection import ArraysCollection import functools import math class DirectionalFilterBank(): """ Class that perform a directional filter bank, which means one step of the curvelet transform for one scale. The procedure was taken from the article the uniform discrete curvelet ...
curvelets.py
import cupy as cp from ArraysCollection import ArraysCollection import functools import math class DirectionalFilterBank(): """ Class that perform a directional filter bank, which means one step of the curvelet transform for one scale. The procedure was taken from the article the uniform discrete curvelet ...
0.922552
0.71566
# Pandas : pip install pandas # Matplotlib: pip install matplotlib # Numpy: pip install numpy # Ipython: pip install ipython import math import numpy as np import matplotlib.pyplot as plt # Given data S0=100 K=105 T=5 r=0.05 sig=0.3 # Function to get Option Price for a given M def getOptionPrice(M): dt = T/M...
Semester 6/MA 374 (Financial Engg. Lab)/Lab 1/180123062_ABSatyaprakash_q2 1.py
# Pandas : pip install pandas # Matplotlib: pip install matplotlib # Numpy: pip install numpy # Ipython: pip install ipython import math import numpy as np import matplotlib.pyplot as plt # Given data S0=100 K=105 T=5 r=0.05 sig=0.3 # Function to get Option Price for a given M def getOptionPrice(M): dt = T/M...
0.52074
0.603435
from __future__ import absolute_import, division, print_function, unicode_literals import six import os import numpy as np import matplotlib.pyplot as plt import livvkit from livvkit.util.LIVVDict import LIVVDict from livvkit.util import elements from livvkit.util import functions case_color = {'bench': '#d7191c'...
livvkit/components/numerics_tests/ismip.py
from __future__ import absolute_import, division, print_function, unicode_literals import six import os import numpy as np import matplotlib.pyplot as plt import livvkit from livvkit.util.LIVVDict import LIVVDict from livvkit.util import elements from livvkit.util import functions case_color = {'bench': '#d7191c'...
0.44071
0.275977