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 logging import os import pickle from datetime import datetime import click_spinner import requests from bs4 import BeautifulSoup from slughorn.scraper.webdriver.TwitterWebdriver import * from slughorn.scraper.webspider.TwitterSpider import TwitterSpider log = logging.getLogger('slughorn') class TwitterScrape...
slughorn/scraper/TwitterScraper.py
import logging import os import pickle from datetime import datetime import click_spinner import requests from bs4 import BeautifulSoup from slughorn.scraper.webdriver.TwitterWebdriver import * from slughorn.scraper.webspider.TwitterSpider import TwitterSpider log = logging.getLogger('slughorn') class TwitterScrape...
0.523908
0.184731
from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column, Integer, String, Float from flask_marshmallow import Marshmallow from flask_jwt_extended import JWTManager, jwt_required, create_access_token from flask_mail import Mail, Message import os app = Flask(__nam...
src/views.py
from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column, Integer, String, Float from flask_marshmallow import Marshmallow from flask_jwt_extended import JWTManager, jwt_required, create_access_token from flask_mail import Mail, Message import os app = Flask(__nam...
0.3295
0.062531
import pickle import matplotlib.pyplot as plt import numpy as np import torch from scipy.stats import norm from tifffile import imread from torch.distributions import normal import divnoising.histNoiseModel dtype = torch.float def fastShuffle(series, num): length = series.shape[0] for i in range(num): ...
divnoising/gaussianMixtureNoiseModel.py
import pickle import matplotlib.pyplot as plt import numpy as np import torch from scipy.stats import norm from tifffile import imread from torch.distributions import normal import divnoising.histNoiseModel dtype = torch.float def fastShuffle(series, num): length = series.shape[0] for i in range(num): ...
0.89684
0.754327
from typing import List, Union from qutip import Qobj, sigmax, sigmay, sigmaz, qeye, tensor from os import path, getcwd, makedirs import numpy as np from fidelity_functions import get_pauli_basis def choose(n, k): return np.math.factorial(n)/(np.math.factorial(k)*np.math.factorial(np.int(n-k))) class GateObj: ...
utils.py
from typing import List, Union from qutip import Qobj, sigmax, sigmay, sigmaz, qeye, tensor from os import path, getcwd, makedirs import numpy as np from fidelity_functions import get_pauli_basis def choose(n, k): return np.math.factorial(n)/(np.math.factorial(k)*np.math.factorial(np.int(n-k))) class GateObj: ...
0.920249
0.610279
import psycopg2 from contextlib import contextmanager def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" try: return psycopg2.connect("dbname=tournament") except: print("Database Connection failed.") @contextmanager def get_cursor(): """ Query helper ...
tournament.py
import psycopg2 from contextlib import contextmanager def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" try: return psycopg2.connect("dbname=tournament") except: print("Database Connection failed.") @contextmanager def get_cursor(): """ Query helper ...
0.683314
0.294951
from dsbox.template.template import DSBoxTemplate from d3m.metadata.problem import TaskKeyword from dsbox.template.template_steps import TemplateSteps from dsbox.schema import SpecializedProblem import typing import numpy as np # type: ignore class LupiRfClassification(DSBoxTemplate): def __init__(self): ...
python/dsbox/template/template_files/loaded/LupiRfClassification.py
from dsbox.template.template import DSBoxTemplate from d3m.metadata.problem import TaskKeyword from dsbox.template.template_steps import TemplateSteps from dsbox.schema import SpecializedProblem import typing import numpy as np # type: ignore class LupiRfClassification(DSBoxTemplate): def __init__(self): ...
0.739705
0.344912
import cv2 import numpy as np import chainer_mask_rcnn from .. import image as image_module def visualize_label(lbl, img, class_names=None): lbl_viz1 = image_module.label2rgb( lbl, label_names=class_names, thresh_suppress=0.01) lbl_viz2 = image_module.label2rgb( lbl, img, label_names=class_n...
demos/instance_occlsegm/instance_occlsegm_lib/datasets/utils.py
import cv2 import numpy as np import chainer_mask_rcnn from .. import image as image_module def visualize_label(lbl, img, class_names=None): lbl_viz1 = image_module.label2rgb( lbl, label_names=class_names, thresh_suppress=0.01) lbl_viz2 = image_module.label2rgb( lbl, img, label_names=class_n...
0.452536
0.374819
import subprocess import tempfile import shutil import os import re import fasta_statter """ Generic assembler template for writing assembly bindings. Assembly Dispatch provides a number of relevant arguments (mostly geared around the requirements of Velvet, but this has proved to be robust for most complex de B...
template_assembler.py
import subprocess import tempfile import shutil import os import re import fasta_statter """ Generic assembler template for writing assembly bindings. Assembly Dispatch provides a number of relevant arguments (mostly geared around the requirements of Velvet, but this has proved to be robust for most complex de B...
0.284477
0.183283
from django.test import TestCase from django.contrib.auth.models import User from .models import * # Create your tests here. class LocationTestClass(TestCase): def setUp(self): self.location = Location(id=1, name='Test') def test_instance(self): self.assertTrue(isinstance(self.loca...
app/tests.py
from django.test import TestCase from django.contrib.auth.models import User from .models import * # Create your tests here. class LocationTestClass(TestCase): def setUp(self): self.location = Location(id=1, name='Test') def test_instance(self): self.assertTrue(isinstance(self.loca...
0.403332
0.36458
from moonfire_tokenomics.data.admc import admc from moonfire_tokenomics.data.amp import amp from moonfire_tokenomics.data.ampl import ampl from moonfire_tokenomics.data.anc import anc from moonfire_tokenomics.data.aot import aot from moonfire_tokenomics.data.atlas import atlas from moonfire_tokenomics.data.axs import a...
moonfire_tokenomics/data/__init__.py
from moonfire_tokenomics.data.admc import admc from moonfire_tokenomics.data.amp import amp from moonfire_tokenomics.data.ampl import ampl from moonfire_tokenomics.data.anc import anc from moonfire_tokenomics.data.aot import aot from moonfire_tokenomics.data.atlas import atlas from moonfire_tokenomics.data.axs import a...
0.516352
0.087408
import numpy as np import scipy.sparse as spsp import seaborn as sns import scedar.eda as eda import matplotlib as mpl mpl.use("agg", warn=False) # noqa import matplotlib.pyplot as plt import pytest class TestSparseSampleFeatureMatrix(object): """docstring for TestSparseSampleFeatureMatrix""" sfm5x10_arr =...
tests/test_eda/test_sparse_sfm.py
import numpy as np import scipy.sparse as spsp import seaborn as sns import scedar.eda as eda import matplotlib as mpl mpl.use("agg", warn=False) # noqa import matplotlib.pyplot as plt import pytest class TestSparseSampleFeatureMatrix(object): """docstring for TestSparseSampleFeatureMatrix""" sfm5x10_arr =...
0.319652
0.558327
import numpy as np import pandas as pd from skimage import morphology from skimage.morphology import binary_closing, binary_opening, disk, binary_dilation def run_length_encoding(x): dots = np.where(x.T.flatten() == 1)[0] run_lengths = [] prev = -2 for b in dots: if (b>prev+1): run_lengths.exte...
kaggle/src/functions.py
import numpy as np import pandas as pd from skimage import morphology from skimage.morphology import binary_closing, binary_opening, disk, binary_dilation def run_length_encoding(x): dots = np.where(x.T.flatten() == 1)[0] run_lengths = [] prev = -2 for b in dots: if (b>prev+1): run_lengths.exte...
0.373076
0.312882
import torch.nn as nn import torch from torch.autograd import Variable # VAE model class VAE(nn.Module): def __init__(self, z_dim, use_cuda, output_dim=400): super(VAE, self).__init__() self.z_dim = z_dim self.output_dim = output_dim self.use_cuda = use_cuda self.encoder ...
experiments/representation_analysis/models.py
import torch.nn as nn import torch from torch.autograd import Variable # VAE model class VAE(nn.Module): def __init__(self, z_dim, use_cuda, output_dim=400): super(VAE, self).__init__() self.z_dim = z_dim self.output_dim = output_dim self.use_cuda = use_cuda self.encoder ...
0.918265
0.530966
from env import JetBotEnv import torch import torch.nn as nn # Import the skrl components to build the RL system from skrl.models.torch import DeterministicModel, GaussianModel from skrl.memories.torch import RandomMemory from skrl.agents.torch.sac import SAC, SAC_DEFAULT_CONFIG from skrl.trainers.torch import Sequen...
docs/source/examples/isaacsim_jetbot.py
from env import JetBotEnv import torch import torch.nn as nn # Import the skrl components to build the RL system from skrl.models.torch import DeterministicModel, GaussianModel from skrl.memories.torch import RandomMemory from skrl.agents.torch.sac import SAC, SAC_DEFAULT_CONFIG from skrl.trainers.torch import Sequen...
0.924219
0.577317
import cgi import datetime import hashlib import http.server import json import logging from multiprocessing import Process import os import re import signal import socket import socketserver import time import traceback from urllib.parse import urlparse, urlencode, parse_qsl import uuid from kolejka.common.settings ...
kolejka/observer/server.py
import cgi import datetime import hashlib import http.server import json import logging from multiprocessing import Process import os import re import signal import socket import socketserver import time import traceback from urllib.parse import urlparse, urlencode, parse_qsl import uuid from kolejka.common.settings ...
0.283385
0.112259
from itertools import islice import logging import os from sqlalchemy import MetaData, Table, Column, Integer, String, create_engine from sqlalchemy.engine import reflection from sqlalchemy.orm import mapper, sessionmaker from sqlalchemy.sql.expression import or_ from .aggregating_scanner import Directory, MODEL D...
relascope/sqlalchemy.py
from itertools import islice import logging import os from sqlalchemy import MetaData, Table, Column, Integer, String, create_engine from sqlalchemy.engine import reflection from sqlalchemy.orm import mapper, sessionmaker from sqlalchemy.sql.expression import or_ from .aggregating_scanner import Directory, MODEL D...
0.712532
0.124133
import re from django.contrib.gis.geos import GEOSException from django.core.management.base import BaseCommand from django.db import InternalError from leasing.enums import AreaType, PlotType from leasing.models import Area, Lease from leasing.models.land_area import PlanUnit, PlanUnitIntendedUse, PlanUnitState, Pla...
leasing/management/commands/attach_areas.py
import re from django.contrib.gis.geos import GEOSException from django.core.management.base import BaseCommand from django.db import InternalError from leasing.enums import AreaType, PlotType from leasing.models import Area, Lease from leasing.models.land_area import PlanUnit, PlanUnitIntendedUse, PlanUnitState, Pla...
0.410402
0.281273
import os import sys #sys.path.append(os.path.dirname(__file__)) import numpy as np try: from .transforms import * from .dataloader import MyDataloader except: from transforms import * from dataloader import MyDataloader from torch.utils.data import DataLoader import matplotlib.pyplot as plt import tor...
code/dataloaders/nyu_dataloader.py
import os import sys #sys.path.append(os.path.dirname(__file__)) import numpy as np try: from .transforms import * from .dataloader import MyDataloader except: from transforms import * from dataloader import MyDataloader from torch.utils.data import DataLoader import matplotlib.pyplot as plt import tor...
0.459076
0.250448
from itertools import (accumulate, chain, cycle, islice) # repCycles :: String -> [String] def repCycles(s): '''Repeated sequences of characters in s.''' n = len(s) cs = list(s) return [ x for x in tail(inits(take(n // 2)(s))) if cs == take(n)(cycle(x)) ] # TEST -------...
lang/Python/rep-string-3.py
from itertools import (accumulate, chain, cycle, islice) # repCycles :: String -> [String] def repCycles(s): '''Repeated sequences of characters in s.''' n = len(s) cs = list(s) return [ x for x in tail(inits(take(n // 2)(s))) if cs == take(n)(cycle(x)) ] # TEST -------...
0.588061
0.316871
import pyshark import argparse from miscale import * HANDLE_VALUE_INDICATION = 0x1d HANDLE_VALUE_NOTIFICATION = 0x1b READ_RESPONSE = 0x0b READ_REQUEST = 0x0a WRITE_REQUEST = 0x12 CONNECT_REQ = 0x05 parser = argparse.ArgumentParser(description='BLE MI_SCALE protocol analyzer') parser.add_argument('-u', '--user', hel...
miscale_analyzer.py
import pyshark import argparse from miscale import * HANDLE_VALUE_INDICATION = 0x1d HANDLE_VALUE_NOTIFICATION = 0x1b READ_RESPONSE = 0x0b READ_REQUEST = 0x0a WRITE_REQUEST = 0x12 CONNECT_REQ = 0x05 parser = argparse.ArgumentParser(description='BLE MI_SCALE protocol analyzer') parser.add_argument('-u', '--user', hel...
0.145844
0.179405
import os import errno from ansible.module_utils._text import to_native from ansible.module_utils.basic import AnsibleModule ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} try: from OpenSSL import crypto except ImportError...
library/openssl_csr.py
import os import errno from ansible.module_utils._text import to_native from ansible.module_utils.basic import AnsibleModule ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} try: from OpenSSL import crypto except ImportError...
0.30013
0.088544
from PyQt5 import QtCore, QtWidgets, QtMultimedia class AudioDialog(QtWidgets.QDialog): def __init__(self, *args, **kwargs): super(AudioDialog, self).__init__(*args, **kwargs) self.setWindowTitle("Audio Devices") self.device_index = -1 self.device_rate_index = -1 self.device...
audiodialog.py
from PyQt5 import QtCore, QtWidgets, QtMultimedia class AudioDialog(QtWidgets.QDialog): def __init__(self, *args, **kwargs): super(AudioDialog, self).__init__(*args, **kwargs) self.setWindowTitle("Audio Devices") self.device_index = -1 self.device_rate_index = -1 self.device...
0.538498
0.070528
from __future__ import ( unicode_literals, print_function, division, absolute_import, ) # Make Py2's str equivalent to Py3's str = type('') try: range = xrange except NameError: pass import sys import threading from time import sleep from collections import deque from picamera.frames impo...
picamtracker/VideoWriter.py
from __future__ import ( unicode_literals, print_function, division, absolute_import, ) # Make Py2's str equivalent to Py3's str = type('') try: range = xrange except NameError: pass import sys import threading from time import sleep from collections import deque from picamera.frames impo...
0.314471
0.096706
import numpy as np # Even though the cityscape dataset provide the pixel wise labells of 30 classes but usually in most of the papers only 20 classes # are used for evaluation. So I added both of them cityscape_class_full = ['unlabeled', 'ego_vehicle', 'rectification_border', 'out_of_roi', 'static', 'dynamic', 'grou...
cityscape_color_pallet.py
import numpy as np # Even though the cityscape dataset provide the pixel wise labells of 30 classes but usually in most of the papers only 20 classes # are used for evaluation. So I added both of them cityscape_class_full = ['unlabeled', 'ego_vehicle', 'rectification_border', 'out_of_roi', 'static', 'dynamic', 'grou...
0.235724
0.570391
import numpy as np Imat = np.eye(2) def x_(nqubits, index): """Create an X gate Args: nqubits (int): The number of qubits on a quantum circuit index (int): The index of a qubit that a gate is applied Returns: ndarray : The matrix of an X gate """ matrix = 1 X = np.arra...
heqsim/hardware/basicgate.py
import numpy as np Imat = np.eye(2) def x_(nqubits, index): """Create an X gate Args: nqubits (int): The number of qubits on a quantum circuit index (int): The index of a qubit that a gate is applied Returns: ndarray : The matrix of an X gate """ matrix = 1 X = np.arra...
0.927552
0.907804
import numpy as np from scipy import linalg from scipy.stats import entropy import torch import torch.utils.data from torch import nn from torch.autograd import Variable from torch.nn import functional as F from torchvision.models.inception import inception_v3 class FIDInceptionModel(nn.Module): def __init__(self...
torchbench/image_generation/utils.py
import numpy as np from scipy import linalg from scipy.stats import entropy import torch import torch.utils.data from torch import nn from torch.autograd import Variable from torch.nn import functional as F from torchvision.models.inception import inception_v3 class FIDInceptionModel(nn.Module): def __init__(self...
0.945538
0.542136
# # Memory Usage: Operator Only import pandas as pd import torch as T from sys import path path.insert(0, '..') import fewbit # noqa # Define parameters of quantisation. # + BOUNDS = T.tensor([ -2.39798704e+00, -7.11248159e-01, -3.26290283e-01, -1.55338428e-04, 3.26182064e-01, 7.10855860e-01, 2.39811567e+...
notebooks/few-bit-backward/memory-usage-operation-only.py
# # Memory Usage: Operator Only import pandas as pd import torch as T from sys import path path.insert(0, '..') import fewbit # noqa # Define parameters of quantisation. # + BOUNDS = T.tensor([ -2.39798704e+00, -7.11248159e-01, -3.26290283e-01, -1.55338428e-04, 3.26182064e-01, 7.10855860e-01, 2.39811567e+...
0.371479
0.279018
import numpy as np from typing import Callable, Tuple from scipy.fft import rfft, rfftfreq from scipy.optimize import curve_fit from scipy.signal import find_peaks from scipy.signal.signaltools import correlate, correlation_lags from scipy.interpolate import UnivariateSpline SignalFunction = Callable[[np.ndarray, flo...
arduscope/fit_tools.py
import numpy as np from typing import Callable, Tuple from scipy.fft import rfft, rfftfreq from scipy.optimize import curve_fit from scipy.signal import find_peaks from scipy.signal.signaltools import correlate, correlation_lags from scipy.interpolate import UnivariateSpline SignalFunction = Callable[[np.ndarray, flo...
0.862178
0.631751
import os import pylzma import sys import struct import zlib def confirm(prompt, resp=False): """prompts for yes or no response from the user. Returns True for yes and False for no. 'resp' should be set to the default value assumed by the caller when user simply types ENTER. >>> confirm(prompt=...
swfzip.py
import os import pylzma import sys import struct import zlib def confirm(prompt, resp=False): """prompts for yes or no response from the user. Returns True for yes and False for no. 'resp' should be set to the default value assumed by the caller when user simply types ENTER. >>> confirm(prompt=...
0.08006
0.245322
from ailib.models.base_model import BaseModule import torch, torch.nn.functional as F from torch import ByteTensor, DoubleTensor, FloatTensor, HalfTensor, LongTensor, ShortTensor, Tensor from torch import nn, optim, as_tensor from torch.utils.data import BatchSampler, DataLoader, Dataset, Sampler, TensorDataset from to...
ailib/models/text_cls/cls_fasttext.py
from ailib.models.base_model import BaseModule import torch, torch.nn.functional as F from torch import ByteTensor, DoubleTensor, FloatTensor, HalfTensor, LongTensor, ShortTensor, Tensor from torch import nn, optim, as_tensor from torch.utils.data import BatchSampler, DataLoader, Dataset, Sampler, TensorDataset from to...
0.918972
0.526951
import random import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class Seq2Seq(nn.Module): EOS_token = 1 def __init__(self, input_size, output_size, hidden_size, embedding_size, n_layers=1, dropout_p=0.5, attention_length=30, ...
seq2seq.py
import random import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class Seq2Seq(nn.Module): EOS_token = 1 def __init__(self, input_size, output_size, hidden_size, embedding_size, n_layers=1, dropout_p=0.5, attention_length=30, ...
0.929943
0.423875
class _MPxCommand(object): """ Base class for custom commands. """ def __init__(*args, **kwargs): """ x.__init__(...) initializes x; see help(type(x)) for signature """ pass def doIt(*args, **kwargs): """ Called by Maya to...
maya/app/renderSetup/model/renderSetupPrivate.py
class _MPxCommand(object): """ Base class for custom commands. """ def __init__(*args, **kwargs): """ x.__init__(...) initializes x; see help(type(x)) for signature """ pass def doIt(*args, **kwargs): """ Called by Maya to...
0.635788
0.260466
from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager from decimal import Decimal from indicators.ema import * from bin.ohlcv import * import numpy as np import datetime def live_updates(intervals, ema_intervals, tokens, exchange, token_instances, alerts): bina...
bin/live_updates.py
from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager from decimal import Decimal from indicators.ema import * from bin.ohlcv import * import numpy as np import datetime def live_updates(intervals, ema_intervals, tokens, exchange, token_instances, alerts): bina...
0.512937
0.230996
import os import time import logging from bag.io import get_encoding from BPG.abstract_plugin import AbstractPlugin try: import cybagoa except ImportError: cybagoa = None class OAPlugin(AbstractPlugin): def __init__(self, config): AbstractPlugin.__init__(self, config) self.config = confi...
BPG/oa/core.py
import os import time import logging from bag.io import get_encoding from BPG.abstract_plugin import AbstractPlugin try: import cybagoa except ImportError: cybagoa = None class OAPlugin(AbstractPlugin): def __init__(self, config): AbstractPlugin.__init__(self, config) self.config = confi...
0.50415
0.054525
from aiohttp_json_api.schema import BaseSchema from aiohttp_json_api.fields import attributes, relationships from examples.fantasy.models import Author, Store, Book, Series, Photo, Chapter class AuthorSchema(BaseSchema): name = attributes.String() date_of_birth = attributes.Date() date_of_death = attribu...
examples/fantasy/schemas.py
from aiohttp_json_api.schema import BaseSchema from aiohttp_json_api.fields import attributes, relationships from examples.fantasy.models import Author, Store, Book, Series, Photo, Chapter class AuthorSchema(BaseSchema): name = attributes.String() date_of_birth = attributes.Date() date_of_death = attribu...
0.763572
0.241825
import h5py import numpy as np import torch from .dataset_thz import * class dataset_thz_perpixel(dataset_thz): # ----------------------------------------------------------------------- def __init__(self, path_data, device, verbose = True): super(dataset_thz_perpixel, self).__init__(path_data, device,...
MoAE/dataset/dataset_thz_perpixel.py
import h5py import numpy as np import torch from .dataset_thz import * class dataset_thz_perpixel(dataset_thz): # ----------------------------------------------------------------------- def __init__(self, path_data, device, verbose = True): super(dataset_thz_perpixel, self).__init__(path_data, device,...
0.691497
0.348701
from unittest.mock import Mock from django.test import TestCase from rest_framework import serializers from ..accounts.tests import ResidentFactory from ..buildings.tests import ApartmentFactory, BuildingFactory from .serializers import MessageSerializer class SerializerTests(TestCase): def test_validate_rec...
ownblock/ownblock/apps/messaging/tests.py
from unittest.mock import Mock from django.test import TestCase from rest_framework import serializers from ..accounts.tests import ResidentFactory from ..buildings.tests import ApartmentFactory, BuildingFactory from .serializers import MessageSerializer class SerializerTests(TestCase): def test_validate_rec...
0.536313
0.391639
import datetime from google.appengine.ext import ndb from testing_utils import testing from components import auth from components import auth_testing from cipd import acl class TestRepoServiceACL(testing.AppengineTestCase): def test_is_owner_writer_reader(self): mocked_roles = [] caller = auth.Identity...
appengine/chrome_infra_packages/cipd/test/acl_test.py
import datetime from google.appengine.ext import ndb from testing_utils import testing from components import auth from components import auth_testing from cipd import acl class TestRepoServiceACL(testing.AppengineTestCase): def test_is_owner_writer_reader(self): mocked_roles = [] caller = auth.Identity...
0.520496
0.459925
import re import inspect import simplejson from xml.sax.saxutils import quoteattr from functools import update_wrapper from babel import Locale, UnknownLocaleError from werkzeug.exceptions import MethodNotAllowed, BadRequest from werkzeug import Response, escape from solace.application import get_view from solace.urls...
solace/utils/api.py
import re import inspect import simplejson from xml.sax.saxutils import quoteattr from functools import update_wrapper from babel import Locale, UnknownLocaleError from werkzeug.exceptions import MethodNotAllowed, BadRequest from werkzeug import Response, escape from solace.application import get_view from solace.urls...
0.539954
0.064241
import re def decorate_all_methods(decorator): def decorate(cls): for attr in cls.__dict__: if callable(getattr(cls, attr)) and attr != '__init__': setattr(cls, attr, decorator(getattr(cls, attr))) return cls return decorate def camel_to_snake(key): camel_pat ...
plantpredict/utilities.py
import re def decorate_all_methods(decorator): def decorate(cls): for attr in cls.__dict__: if callable(getattr(cls, attr)) and attr != '__init__': setattr(cls, attr, decorator(getattr(cls, attr))) return cls return decorate def camel_to_snake(key): camel_pat ...
0.513912
0.230481
import io from pathlib import Path from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap from ruamel.yaml.representer import RepresenterError from ruamel.yaml.scalarstring import PreservedScalarString import logging, sys import pickle from capanno_utils.helpers.string_tools import get_shortened_id ...
capanno_utils/classes/cwl/common_workflow_language_mixins.py
import io from pathlib import Path from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap from ruamel.yaml.representer import RepresenterError from ruamel.yaml.scalarstring import PreservedScalarString import logging, sys import pickle from capanno_utils.helpers.string_tools import get_shortened_id ...
0.333395
0.141667
import lib from lib.common import group, calc_stat from collections import OrderedDict highlight_threshold = 0.025 IID_KEY = "validation/valid/accuracy/iid" GEN_KEY = "validation/test/accuracy/deeper" VAL_KEY = "validation/valid/accuracy/deeper_val" def format_res(r): # r = r.get() return f"{r.mean:.2f} $\...
paper/print_perf_table_ctl.py
import lib from lib.common import group, calc_stat from collections import OrderedDict highlight_threshold = 0.025 IID_KEY = "validation/valid/accuracy/iid" GEN_KEY = "validation/test/accuracy/deeper" VAL_KEY = "validation/valid/accuracy/deeper_val" def format_res(r): # r = r.get() return f"{r.mean:.2f} $\...
0.373647
0.267402
from datetime import timedelta from src.fetcher.fetcher_config import FetcherConfKey from src.fetcher.fetcher_item import FetcherItem from src.fetcher.fetcher_job import FetcherJob from src.fetcher import transformation from src.fetcher.fetcher_key import FetcherKey from src.fetcher.time_series import MaxTimeSeries ...
src/fetcher/froggit_wh2600_job.py
from datetime import timedelta from src.fetcher.fetcher_config import FetcherConfKey from src.fetcher.fetcher_item import FetcherItem from src.fetcher.fetcher_job import FetcherJob from src.fetcher import transformation from src.fetcher.fetcher_key import FetcherKey from src.fetcher.time_series import MaxTimeSeries ...
0.777553
0.120516
import genomepy import shutil import gzip import pytest import os from tempfile import mkdtemp, NamedTemporaryFile from time import sleep from platform import system travis = "TRAVIS" in os.environ and os.environ["TRAVIS"] == "true" @pytest.fixture(scope="module", params=["no-overwrite", "overwrite"]) def force(requ...
tests/test_5_install_options.py
import genomepy import shutil import gzip import pytest import os from tempfile import mkdtemp, NamedTemporaryFile from time import sleep from platform import system travis = "TRAVIS" in os.environ and os.environ["TRAVIS"] == "true" @pytest.fixture(scope="module", params=["no-overwrite", "overwrite"]) def force(requ...
0.303629
0.302523
def intersect(t1, t2): """Assumes t1 and t2 are tuples Returns a tuple containing elements that are in both t1 and t2""" result = () for e in t1: if e in t2: result += (e,) return result def findExtremeDivisors(n1, n2): """Assumes that n1 and n2 are positive in...
chapter5/chapter5.py
def intersect(t1, t2): """Assumes t1 and t2 are tuples Returns a tuple containing elements that are in both t1 and t2""" result = () for e in t1: if e in t2: result += (e,) return result def findExtremeDivisors(n1, n2): """Assumes that n1 and n2 are positive in...
0.701406
0.710274
import logging import os from enum import Enum import click import cv2 from imageai.Prediction.Custom import CustomImagePrediction, ModelTraining from helpers.opencv import opencv_video_capture # Show only errors in console logging.getLogger("tensorflow").setLevel(logging.ERROR) class ModelTypeEnum(Enum): """ ...
helpers/move_prediction.py
import logging import os from enum import Enum import click import cv2 from imageai.Prediction.Custom import CustomImagePrediction, ModelTraining from helpers.opencv import opencv_video_capture # Show only errors in console logging.getLogger("tensorflow").setLevel(logging.ERROR) class ModelTypeEnum(Enum): """ ...
0.725746
0.301645
import itertools from functools import partial import numpy as np from lined import iterize, Line, LineParametrized # --------------------------------------------------------------------------------------- # simple categorical map cat_map = {'a': [1, 2, 3], 'b': [4, 5, 6]} get_list_for_cat = cat_map.__getitem__ # to...
slink/examples/__init__.py
import itertools from functools import partial import numpy as np from lined import iterize, Line, LineParametrized # --------------------------------------------------------------------------------------- # simple categorical map cat_map = {'a': [1, 2, 3], 'b': [4, 5, 6]} get_list_for_cat = cat_map.__getitem__ # to...
0.484136
0.522019
import six from oslo_log import log from oslo_utils import units from delfin import exception from delfin.common import constants from delfin.drivers import driver from delfin.drivers.ibm.ds8k import rest_handler, alert_handler LOG = log.getLogger(__name__) class DS8KDriver(driver.StorageDriver): PORT_TYPE_MAP...
delfin/drivers/ibm/ds8k/ds8k.py
import six from oslo_log import log from oslo_utils import units from delfin import exception from delfin.common import constants from delfin.drivers import driver from delfin.drivers.ibm.ds8k import rest_handler, alert_handler LOG = log.getLogger(__name__) class DS8KDriver(driver.StorageDriver): PORT_TYPE_MAP...
0.371365
0.078078
from datetime import datetime from unittest import TestCase from vision.constant import * from vision.configuration_constant import * from vision.data_handler.idata_handler import IDataHandler from vision.registry_manager import RegistryManager from mock import Mock, patch mock_node_info = {'bootFwDate': "2018-10-9",...
inbm-vision/vision-agent/vision/tests/unit/test_registry_manager.py
from datetime import datetime from unittest import TestCase from vision.constant import * from vision.configuration_constant import * from vision.data_handler.idata_handler import IDataHandler from vision.registry_manager import RegistryManager from mock import Mock, patch mock_node_info = {'bootFwDate': "2018-10-9",...
0.642432
0.227985
import pickle as pkl import xlrd # 未知字,padding符号 UNK, PAD = "<UNK>", "<PAD>" # 文本数据处理方法定义(单行格式) def load_single_dataset(config, data, pad_size=32): # 打开词表 vocab = pkl.load(open(config.vocab_path, "rb")) content, label, title = data # 存储每一行内容 words_line = [] # 拼接title和content token = (lam...
Core/utils.py
import pickle as pkl import xlrd # 未知字,padding符号 UNK, PAD = "<UNK>", "<PAD>" # 文本数据处理方法定义(单行格式) def load_single_dataset(config, data, pad_size=32): # 打开词表 vocab = pkl.load(open(config.vocab_path, "rb")) content, label, title = data # 存储每一行内容 words_line = [] # 拼接title和content token = (lam...
0.147893
0.228479
import binascii import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import modbus from esphome.const import CONF_ADDRESS, CONF_ID, CONF_NAME, CONF_LAMBDA, CONF_OFFSET from esphome.cpp_helpers import logging from .const import ( CONF_BITMASK, CONF_BYTE_OFFSET, CONF_COM...
esphome/components/modbus_controller/__init__.py
import binascii import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import modbus from esphome.const import CONF_ADDRESS, CONF_ID, CONF_NAME, CONF_LAMBDA, CONF_OFFSET from esphome.cpp_helpers import logging from .const import ( CONF_BITMASK, CONF_BYTE_OFFSET, CONF_COM...
0.379838
0.127816
import numpy as np import os import cv2 from src.config import DATA_DIR, CLASSES, BATCH_SIZE, IMG_SIZE import matplotlib.pyplot as plt import matplotlib import tensorflow as tf from sklearn.model_selection import train_test_split matplotlib.use('TkAgg') IMG_PATH = os.path.join(DATA_DIR,'images') MASK_PATH = os.pat...
src/data.py
import numpy as np import os import cv2 from src.config import DATA_DIR, CLASSES, BATCH_SIZE, IMG_SIZE import matplotlib.pyplot as plt import matplotlib import tensorflow as tf from sklearn.model_selection import train_test_split matplotlib.use('TkAgg') IMG_PATH = os.path.join(DATA_DIR,'images') MASK_PATH = os.pat...
0.436142
0.435061
from pytorch3d.structures import Pointclouds from pytorch3d.renderer import compositing from pytorch3d.renderer.points import rasterize_points import numpy as np import torch from torch import nn import nvdiffrast.torch as dr from utils.defaults import DEFAULTS import os import pytorch3d class RasterizePointsXYsBle...
src/models/pcd_renderer.py
from pytorch3d.structures import Pointclouds from pytorch3d.renderer import compositing from pytorch3d.renderer.points import rasterize_points import numpy as np import torch from torch import nn import nvdiffrast.torch as dr from utils.defaults import DEFAULTS import os import pytorch3d class RasterizePointsXYsBle...
0.908277
0.65597
import unittest from numba.cuda.testing import (CUDATestCase, skip_if_cudadevrt_missing, skip_on_cudasim, skip_unless_cc_60) from numba.tests.support import captured_stdout @skip_if_cudadevrt_missing @skip_unless_cc_60 @skip_on_cudasim("cudasim doesn't support cuda import at non-top-l...
numba/cuda/tests/doc_examples/test_laplace.py
import unittest from numba.cuda.testing import (CUDATestCase, skip_if_cudadevrt_missing, skip_on_cudasim, skip_unless_cc_60) from numba.tests.support import captured_stdout @skip_if_cudadevrt_missing @skip_unless_cc_60 @skip_on_cudasim("cudasim doesn't support cuda import at non-top-l...
0.582254
0.418875
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Orgao, TipoLotacao, Lotacao from Chamados.models import Chamado, OcorrenciasChamado class CadastroOrgaoForm(forms.ModelForm): def __init__(self, *args, **kwargs): ...
sistemaDeGestaoDeServicosPublicos/Orgao/forms.py
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Orgao, TipoLotacao, Lotacao from Chamados.models import Chamado, OcorrenciasChamado class CadastroOrgaoForm(forms.ModelForm): def __init__(self, *args, **kwargs): ...
0.475849
0.106133
import logging from oslo_messaging._drivers.zmq_driver import zmq_address from oslo_messaging._drivers.zmq_driver import zmq_async from oslo_messaging._drivers.zmq_driver import zmq_names from oslo_messaging._drivers.zmq_driver import zmq_socket LOG = logging.getLogger(__name__) zmq = zmq_async.import_zmq() class...
oslo_messaging/_drivers/zmq_driver/client/publishers/zmq_pub_publisher.py
import logging from oslo_messaging._drivers.zmq_driver import zmq_address from oslo_messaging._drivers.zmq_driver import zmq_async from oslo_messaging._drivers.zmq_driver import zmq_names from oslo_messaging._drivers.zmq_driver import zmq_socket LOG = logging.getLogger(__name__) zmq = zmq_async.import_zmq() class...
0.508544
0.107672
from typing import Union import numpy from scipy.cluster import hierarchy import pyckmeans.distance class InvalidReorderMethod(Exception): '''InvalidReorderMethod''' class InvalidLinkageType(Exception): '''InvalidLinkageType''' REORDER_METHODS = ( 'GW', 'OLO', ) LINKAGE_TYPES = ( 'average', '...
pyckmeans/ordering/__init__.py
from typing import Union import numpy from scipy.cluster import hierarchy import pyckmeans.distance class InvalidReorderMethod(Exception): '''InvalidReorderMethod''' class InvalidLinkageType(Exception): '''InvalidLinkageType''' REORDER_METHODS = ( 'GW', 'OLO', ) LINKAGE_TYPES = ( 'average', '...
0.952075
0.600159
from contextlib import contextmanager from io import BytesIO import logging from pathlib import Path from queue import Queue from threading import Semaphore from typing import ( Any, cast, Callable, DefaultDict, Dict, List, Iterator, Optional, Tuple, ) # internal from vtelem.daemon....
vtelem/stream/writer.py
from contextlib import contextmanager from io import BytesIO import logging from pathlib import Path from queue import Queue from threading import Semaphore from typing import ( Any, cast, Callable, DefaultDict, Dict, List, Iterator, Optional, Tuple, ) # internal from vtelem.daemon....
0.833257
0.174656
import tensorflow as tf import numpy as np import scipy.io class pretrainedVGG19(object): """Pretrained VGG 19 for Neural Style Transfer. Args: height: int, height of input image width: int, width of input image channels: int, number of input image channels Attributes: graph: dict, {layer_name : tensor}, ...
vgg.py
import tensorflow as tf import numpy as np import scipy.io class pretrainedVGG19(object): """Pretrained VGG 19 for Neural Style Transfer. Args: height: int, height of input image width: int, width of input image channels: int, number of input image channels Attributes: graph: dict, {layer_name : tensor}, ...
0.892837
0.648814
from __future__ import annotations import apgorm from apgorm import Index, IndexType from .models import ( aschannel, guild, member, message, override, permrole, posrole, sb_message, starboard, user, vote, xprole, ) class Database(apgorm.Database): def __init__(s...
starboard/database/database.py
from __future__ import annotations import apgorm from apgorm import Index, IndexType from .models import ( aschannel, guild, member, message, override, permrole, posrole, sb_message, starboard, user, vote, xprole, ) class Database(apgorm.Database): def __init__(s...
0.711832
0.143068
# System imports # Google imports from google.appengine.api import users from google.appengine.ext import ndb # Local imports from scaffold import attentionpage import basehandler from subreview_lib import confreviewconfig, newscoringtask class NewScoreConfigPage(basehandler.BaseHandler): def get(self): ...
subreview_lib/newscoreconfigpage.py
# System imports # Google imports from google.appengine.api import users from google.appengine.ext import ndb # Local imports from scaffold import attentionpage import basehandler from subreview_lib import confreviewconfig, newscoringtask class NewScoreConfigPage(basehandler.BaseHandler): def get(self): ...
0.295636
0.081813
import telebot as tb from dbhelper import DBHelper import datetime bot = tb.TeleBot('944057887:AAEhF2Xp3lHFmc4ipZP8xNVExvzRI7BtL24') @bot.message_handler(commands=['start']) def start_message(message): bot.send_message(message.chat.id, 'Привет, давай-ка я поведаю о функционале!\n '+ 'Я призван для того чтобы ...
main.py
import telebot as tb from dbhelper import DBHelper import datetime bot = tb.TeleBot('944057887:AAEhF2Xp3lHFmc4ipZP8xNVExvzRI7BtL24') @bot.message_handler(commands=['start']) def start_message(message): bot.send_message(message.chat.id, 'Привет, давай-ка я поведаю о функционале!\n '+ 'Я призван для того чтобы ...
0.044608
0.218669
import sys import string import time import math import getopt flood_30_info = { 'pages' : [1,2,3,4,5,6,7,8], 'cycles': 1.0259 } flood_18_info = { 'pages' : [9,10,11,12,13,14,15], 'cycles': 1.0516 } flood_06_info = { 'pages' : [16,17,18,19,20,21], 'cycles': 1.0558 } ebb_30_info = { 'pa...
calculate.py
import sys import string import time import math import getopt flood_30_info = { 'pages' : [1,2,3,4,5,6,7,8], 'cycles': 1.0259 } flood_18_info = { 'pages' : [9,10,11,12,13,14,15], 'cycles': 1.0516 } flood_06_info = { 'pages' : [16,17,18,19,20,21], 'cycles': 1.0558 } ebb_30_info = { 'pa...
0.101628
0.154026
from logging import getLogger from ptrlib.util.encoding import * from ptrlib.pwn.tube import * import socket logger = getLogger(__name__) class Socket(Tube): def __init__(self, host, port, timeout=None): """Create a socket Create a new socket and establish a connection to the host. Args...
ptrlib/pwn/sock.py
from logging import getLogger from ptrlib.util.encoding import * from ptrlib.pwn.tube import * import socket logger = getLogger(__name__) class Socket(Tube): def __init__(self, host, port, timeout=None): """Create a socket Create a new socket and establish a connection to the host. Args...
0.784649
0.177579
import cookielib import urllib2 import urllib import httplib import urlparse '''网络数据查询实现类,负责网络数据交互,包括登陆和JSON数据获取''' class QueryCore(): def __init__(self, ctr): self.ctr = ctr self.setCookies() """ 设置cookie""" def setCookies(self): self.cookieFile = "cookies.txt" self.c...
queryCore.py
import cookielib import urllib2 import urllib import httplib import urlparse '''网络数据查询实现类,负责网络数据交互,包括登陆和JSON数据获取''' class QueryCore(): def __init__(self, ctr): self.ctr = ctr self.setCookies() """ 设置cookie""" def setCookies(self): self.cookieFile = "cookies.txt" self.c...
0.174094
0.083591
from django.contrib.gis.geos import GEOSGeometry, GeometryCollection from snapshottest import TestCase from .geometry_helpers import ewkt_from_feature_collection from rescape_python_helpers import ewkt_from_feature, geometry_from_feature, geometrycollection_from_feature_collection class GeometryHelepersTest(TestCase...
rescape_python_helpers/geospatial/geometry_helpers_test.py
from django.contrib.gis.geos import GEOSGeometry, GeometryCollection from snapshottest import TestCase from .geometry_helpers import ewkt_from_feature_collection from rescape_python_helpers import ewkt_from_feature, geometry_from_feature, geometrycollection_from_feature_collection class GeometryHelepersTest(TestCase...
0.68342
0.500671
from datetime import datetime from django.shortcuts import get_object_or_404 from django.views.generic import View from django.http import JsonResponse from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from utils.mixins import CsrfExemptMixi...
projects/webptspy/apps/tresult/views/execute/api.py
from datetime import datetime from django.shortcuts import get_object_or_404 from django.views.generic import View from django.http import JsonResponse from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from utils.mixins import CsrfExemptMixi...
0.312475
0.074973
import os import sys import csv import wget import zipfile import numpy as np import pandas as pd import torch from torch import nn import torchvision from torchvision import transforms, datasets from torch import distributions import ssl from sklearn.metrics import mean_squared_error ''' Helper functions for MCFlow ...
2_regression_with_missing_values/lib/MCFlowImputer/util.py
import os import sys import csv import wget import zipfile import numpy as np import pandas as pd import torch from torch import nn import torchvision from torchvision import transforms, datasets from torch import distributions import ssl from sklearn.metrics import mean_squared_error ''' Helper functions for MCFlow ...
0.619586
0.377283
import pytest METADATA_ENDPOINT = '/api/v1/metadata/' @pytest.mark.tendermint def test_get_metadata_with_empty_text_search(client): res = client.get(METADATA_ENDPOINT + '?search=') assert res.json == {'status': 400, 'message': 'text_search cannot be empty'} assert res.status_code ...
tests/web/test_metadata.py
import pytest METADATA_ENDPOINT = '/api/v1/metadata/' @pytest.mark.tendermint def test_get_metadata_with_empty_text_search(client): res = client.get(METADATA_ENDPOINT + '?search=') assert res.json == {'status': 400, 'message': 'text_search cannot be empty'} assert res.status_code ...
0.615203
0.377053
import copy import numpy as np import torch import torch.nn.functional as F from torch import nn device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # autoencoder for SVM-base models class Encoder(nn.Module): def __init__(self, dim, dataset="Abnormal"): super(Encoder, self).__init__() ...
models/caenb.py
import copy import numpy as np import torch import torch.nn.functional as F from torch import nn device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # autoencoder for SVM-base models class Encoder(nn.Module): def __init__(self, dim, dataset="Abnormal"): super(Encoder, self).__init__() ...
0.935597
0.611324
import markdown from flask import abort, flash, redirect, render_template, request from flask_babel import gettext as _ from flask_login import current_user, login_required from ..ext import db from ..forms.base import DeleteForm from ..models import Brew, TastingNote from ..utils.pagination import get_page from ..uti...
src/brewlog/tasting/views.py
import markdown from flask import abort, flash, redirect, render_template, request from flask_babel import gettext as _ from flask_login import current_user, login_required from ..ext import db from ..forms.base import DeleteForm from ..models import Brew, TastingNote from ..utils.pagination import get_page from ..uti...
0.331769
0.069827
from unittest import mock from oslo_config import cfg from kuryr.lib import constants as const from kuryr.lib import exceptions from kuryr.tests.unit import base from kuryr.lib.segmentation_type_drivers import vlan class VlanSegmentationDriverTest(base.TestCase): """Unit tests for VLAN segmentation driver."""...
kuryr/tests/unit/segmentation_type_drivers/test_vlan.py
from unittest import mock from oslo_config import cfg from kuryr.lib import constants as const from kuryr.lib import exceptions from kuryr.tests.unit import base from kuryr.lib.segmentation_type_drivers import vlan class VlanSegmentationDriverTest(base.TestCase): """Unit tests for VLAN segmentation driver."""...
0.791378
0.370681
from brownie import ZERO_ADDRESS, Contract, accounts, chain from brownie_tokens import MintableForkToken def load_contract(addr): if addr == ZERO_ADDRESS: return None try: cont = Contract(addr) except ValueError: cont = Contract.from_explorer(addr) return cont # Load Globals ...
scripts/rewards.py
from brownie import ZERO_ADDRESS, Contract, accounts, chain from brownie_tokens import MintableForkToken def load_contract(addr): if addr == ZERO_ADDRESS: return None try: cont = Contract(addr) except ValueError: cont = Contract.from_explorer(addr) return cont # Load Globals ...
0.676406
0.259602
import os import math import time import random from pprint import pprint import yaml import torch import torch.nn as nn import torch.optim as optim from torch import autograd from torch.autograd import Variable from torchvision import transforms from torchvision.utils import save_image from torch.util...
inference_causal_vae.py
import os import math import time import random from pprint import pprint import yaml import torch import torch.nn as nn import torch.optim as optim from torch import autograd from torch.autograd import Variable from torchvision import transforms from torchvision.utils import save_image from torch.util...
0.393502
0.225065
import pyfits as F import matplotlib.pyplot as P import numpy as N #filename1="scala_clap0_calibration_mirror_G1_new2.fits" filename1="scala_clap0_calibration_mirror_A1_3nm.fits" filename3="scala_clap1_calibration_mirror_C3.fits" filename2="scala_clap0_calibration_mirror_A2.fits" Fits1 = F.open(filename1) Fits2 ...
SCALA_scripts/plot_test.py
import pyfits as F import matplotlib.pyplot as P import numpy as N #filename1="scala_clap0_calibration_mirror_G1_new2.fits" filename1="scala_clap0_calibration_mirror_A1_3nm.fits" filename3="scala_clap1_calibration_mirror_C3.fits" filename2="scala_clap0_calibration_mirror_A2.fits" Fits1 = F.open(filename1) Fits2 ...
0.31342
0.349921
import os, sys, re from src.ompcply import lex, yacc, _gettabs, _print3000, _reset import wsgiref.handlers, logging from google.appengine.api import users from google.appengine.ext import webapp from src.functions import path2params, DjangoHandler from google.appengine.ext import webapp from google.appengine.e...
examples/appengine/src/m2py.py
import os, sys, re from src.ompcply import lex, yacc, _gettabs, _print3000, _reset import wsgiref.handlers, logging from google.appengine.api import users from google.appengine.ext import webapp from src.functions import path2params, DjangoHandler from google.appengine.ext import webapp from google.appengine.e...
0.11135
0.049382
import time import rospy from sensor_msgs.msg import Joy from geometry_msgs.msg import Vector3, Twist from std_msgs.msg import String class Watcher: def __init__(self): self.t0 = time.time() self.timeout = True self.mode = "manual" self.idle = False self.new_joy_msg = Fa...
src/roboclaw/src/safety_listener.py
import time import rospy from sensor_msgs.msg import Joy from geometry_msgs.msg import Vector3, Twist from std_msgs.msg import String class Watcher: def __init__(self): self.t0 = time.time() self.timeout = True self.mode = "manual" self.idle = False self.new_joy_msg = Fa...
0.573559
0.229363
# ====================================================================== # n u m b e r s . p y # ====================================================================== "A solver for the Advent of Code 2015 Day 12 puzzle" # ---------------------------------------------------------------------- ...
2015/12_JSAbacusFramework.io/abacus.py
# ====================================================================== # n u m b e r s . p y # ====================================================================== "A solver for the Advent of Code 2015 Day 12 puzzle" # ---------------------------------------------------------------------- ...
0.787564
0.485844
import torch import numpy as np import math from sklearn.metrics.pairwise import linear_kernel class MultiArmedBandit(): def __init__(self, cues=None, start_arm=0, end_arm=7, ctx_dim=2, num_rounds=10, normalize=True, best_arms=None, noise_per_arm=False, cue_per_epoch=False): default_cues = {'l...
tutorial_metarl/tasks/MultiArmedBandit.py
import torch import numpy as np import math from sklearn.metrics.pairwise import linear_kernel class MultiArmedBandit(): def __init__(self, cues=None, start_arm=0, end_arm=7, ctx_dim=2, num_rounds=10, normalize=True, best_arms=None, noise_per_arm=False, cue_per_epoch=False): default_cues = {'l...
0.687525
0.385259
# test_regionkey.py # @category Libraries # @author <NAME> <<EMAIL>> # @copyright 2017-2018 GENOMICS plc # @license MIT (see LICENSE) # @link https://github.com/genomicsplc/variantkey import pyvariantkey.variantkey as pyvk import numpy as np import os from unittest import TestCase # 0:chrom, 1:startp...
python-class/test/test_regionkey.py
# test_regionkey.py # @category Libraries # @author <NAME> <<EMAIL>> # @copyright 2017-2018 GENOMICS plc # @license MIT (see LICENSE) # @link https://github.com/genomicsplc/variantkey import pyvariantkey.variantkey as pyvk import numpy as np import os from unittest import TestCase # 0:chrom, 1:startp...
0.405449
0.522385
import asyncio import random import time from random import choice from string import ascii_letters from typing import Union, Optional import async_cleverbot as ac import discord from discord.ext import commands from discord.ext.commands.cooldowns import BucketType from lib import MemberID, Tokens from lib.classes.gam...
minato_namikaze/cogs/fun/games.py
import asyncio import random import time from random import choice from string import ascii_letters from typing import Union, Optional import async_cleverbot as ac import discord from discord.ext import commands from discord.ext.commands.cooldowns import BucketType from lib import MemberID, Tokens from lib.classes.gam...
0.68784
0.151435
import glob import gzip import json import os import pickle import time from chorus import v2000writer from chorus.draw.svg import SVG from chorus.model.graphmol import Compound from chorus.util.text import decode from tornado import gen from tornado.options import options from flashflood import static from flashflo...
ffws/handler.py
import glob import gzip import json import os import pickle import time from chorus import v2000writer from chorus.draw.svg import SVG from chorus.model.graphmol import Compound from chorus.util.text import decode from tornado import gen from tornado.options import options from flashflood import static from flashflo...
0.388154
0.121634
from dataclasses import dataclass, field from importlib.resources import path, read_text from typing import ( Literal, TypeVar, Optional, Union, Tuple, NamedTuple, Mapping, Dict, FrozenSet, ) from collections.abc import MutableMapping from functools import cached_property from json i...
cchdo/params/__init__.py
from dataclasses import dataclass, field from importlib.resources import path, read_text from typing import ( Literal, TypeVar, Optional, Union, Tuple, NamedTuple, Mapping, Dict, FrozenSet, ) from collections.abc import MutableMapping from functools import cached_property from json i...
0.894922
0.238495
import matplotlib.pyplot as plt import math import zipfile import os def generate_screenoverly_kml(overlay_image): """ generate and overlay kml """ # upper right overlay_kml = """<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://earth.google.com/kml/2.2"> <ScreenOverlay> <name>Radar Di...
scripts/direction_arrow.py
import matplotlib.pyplot as plt import math import zipfile import os def generate_screenoverly_kml(overlay_image): """ generate and overlay kml """ # upper right overlay_kml = """<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://earth.google.com/kml/2.2"> <ScreenOverlay> <name>Radar Di...
0.448668
0.462655
import logging,datetime from webapp.API.Response import Response from webapp.SessionsManager import Session, SessionsManager def historyDataDelete(id_session, id_user): response = Response(True) try: sm = SessionsManager(id_user) sm.load(id_session) # Remove session resul...
webapp/API/history.py
import logging,datetime from webapp.API.Response import Response from webapp.SessionsManager import Session, SessionsManager def historyDataDelete(id_session, id_user): response = Response(True) try: sm = SessionsManager(id_user) sm.load(id_session) # Remove session resul...
0.393385
0.11684
from argparse import ArgumentParser from collections import defaultdict, Counter, namedtuple import sys from warnings import warn import matplotlib.pyplot as plt from nltk.metrics.scores import precision, recall, f_measure from nltk.metrics.confusionmatrix import ConfusionMatrix import numpy as np from src.corpus imp...
src/evaluation.py
from argparse import ArgumentParser from collections import defaultdict, Counter, namedtuple import sys from warnings import warn import matplotlib.pyplot as plt from nltk.metrics.scores import precision, recall, f_measure from nltk.metrics.confusionmatrix import ConfusionMatrix import numpy as np from src.corpus imp...
0.527803
0.327776
from django.test import TestCase from unittest2 import skipIf from django.db import connection import json from datetime import datetime from dateutil import parser from django.utils import timezone from sqlshare_rest.util.db import get_backend from sqlshare_rest.test import missing_url from django.test.utils import ov...
sqlshare_rest/test/api/user_search.py
from django.test import TestCase from unittest2 import skipIf from django.db import connection import json from datetime import datetime from dateutil import parser from django.utils import timezone from sqlshare_rest.util.db import get_backend from sqlshare_rest.test import missing_url from django.test.utils import ov...
0.408159
0.188884
import urllib.request import re import os import csv topnum = 1; #获取网页源代码 def getHtml(url): page = urllib.request.urlopen(url); html = page.read(); return html; #通过正则表达式获取该网页下的每部电影的title def getName(html): nameList = re.findall(r'<span.*?class="title">(.*?)</span>', html, re.S); global topnum ...
douban_movie_scraper.py
import urllib.request import re import os import csv topnum = 1; #获取网页源代码 def getHtml(url): page = urllib.request.urlopen(url); html = page.read(); return html; #通过正则表达式获取该网页下的每部电影的title def getName(html): nameList = re.findall(r'<span.*?class="title">(.*?)</span>', html, re.S); global topnum ...
0.082071
0.111652
from components import MissingInputModal, MismatchModal, PlotPlaceHolder, DisplayControlCard from enum import Enum from operator import itemgetter from parsers import DatasetStates import plotly.graph_objects as go from plotly.colors import diverging from plotly.colors import sequential from loaders import DatasetRefer...
utils/plot_utils.py
from components import MissingInputModal, MismatchModal, PlotPlaceHolder, DisplayControlCard from enum import Enum from operator import itemgetter from parsers import DatasetStates import plotly.graph_objects as go from plotly.colors import diverging from plotly.colors import sequential from loaders import DatasetRefer...
0.742608
0.133839
import os, os.path import random import sqlite3 import string import time import cherrypy DB_STRING = "url.db" BASE_HOST_NAME = "http://localhost:8080/" class ShortUrlGenerator(object): @cherrypy.expose def index(self): return file('index.html') class ShortUrlWebService(object): exposed = True ...
webapp/server.py
import os, os.path import random import sqlite3 import string import time import cherrypy DB_STRING = "url.db" BASE_HOST_NAME = "http://localhost:8080/" class ShortUrlGenerator(object): @cherrypy.expose def index(self): return file('index.html') class ShortUrlWebService(object): exposed = True ...
0.413832
0.084682
import os import random import click import praw import requests from PIL import Image MIN_WIDTH = 1920 MIN_HEIGHT = 1200 MAX_RETRIES = 25 SUBS = [ 'wallpapers', 'wallpaper', 'earthporn', 'skylineporn', 'bigwallpapers', # 'nocontext_wallpapers', # 'gmbwallpapers', # 'NSFW_Wallpapers',...
Scripts/wallpaper.py
import os import random import click import praw import requests from PIL import Image MIN_WIDTH = 1920 MIN_HEIGHT = 1200 MAX_RETRIES = 25 SUBS = [ 'wallpapers', 'wallpaper', 'earthporn', 'skylineporn', 'bigwallpapers', # 'nocontext_wallpapers', # 'gmbwallpapers', # 'NSFW_Wallpapers',...
0.294824
0.069007
import os import pwd import json from src import config from src import plugin # aliases for path to use later on user = pwd.getpwuid(os.getuid())[0] path = "/home/"+user+"/.config" class Plugin(plugin.Base): @staticmethod def name() -> str: return "Visual Studio Code" @classmethod def a...
src/plugins/vscode.py
import os import pwd import json from src import config from src import plugin # aliases for path to use later on user = pwd.getpwuid(os.getuid())[0] path = "/home/"+user+"/.config" class Plugin(plugin.Base): @staticmethod def name() -> str: return "Visual Studio Code" @classmethod def a...
0.073413
0.100525
from subprocess import Popen, DEVNULL, TimeoutExpired import logging import argparse import json import os from os.path import join, exists import shutil import pathlib import tempfile root_dir = os.getcwd() workdir = join(root_dir, ".prep_dev_patch") logger = logging.getLogger("prep_dev_patch") prog_config = dict() ...
src/prep_dev_patch.py
from subprocess import Popen, DEVNULL, TimeoutExpired import logging import argparse import json import os from os.path import join, exists import shutil import pathlib import tempfile root_dir = os.getcwd() workdir = join(root_dir, ".prep_dev_patch") logger = logging.getLogger("prep_dev_patch") prog_config = dict() ...
0.312895
0.054803
from unittest import TestCase import os from musicscore.musicstream.streamvoice import SimpleFormat from musicscore.musictree.treescoretimewise import TreeScoreTimewise from tests.score_templates.xml_test_score import TestScore path = os.path.abspath(__file__).split('.')[0] class Test(TestCase): def setUp(self)...
tests/musicstream/test_grace.py
from unittest import TestCase import os from musicscore.musicstream.streamvoice import SimpleFormat from musicscore.musictree.treescoretimewise import TreeScoreTimewise from tests.score_templates.xml_test_score import TestScore path = os.path.abspath(__file__).split('.')[0] class Test(TestCase): def setUp(self)...
0.559049
0.420897
import ipywidgets as widgets from sage.misc.all import latex from sage.repl.rich_output.pretty_print import pretty_print from IPython.display import clear_output def cluster_interact(self, fig_size=1, circular=True, kind='seed'): r""" Start an interactive window for cluster seed mutations. Only in *Jupyt...
src/sage/combinat/cluster_algebra_quiver/interact.py
import ipywidgets as widgets from sage.misc.all import latex from sage.repl.rich_output.pretty_print import pretty_print from IPython.display import clear_output def cluster_interact(self, fig_size=1, circular=True, kind='seed'): r""" Start an interactive window for cluster seed mutations. Only in *Jupyt...
0.619471
0.538498
from __future__ import print_function, division, unicode_literals, absolute_import from .utils import * def test_wronskian(): """ Wronskian formula for W{P^m_lam(x), P^m_lam(-x)} """ for m,lam, x in [(3,0.75+0.1j,0.4), (0,0.75+0.1j,0.4), (25,0.75+0.1j,0.1)]: llp1 = lam*(lam+1) p = lam...
smerfs/tests/test_green.py
from __future__ import print_function, division, unicode_literals, absolute_import from .utils import * def test_wronskian(): """ Wronskian formula for W{P^m_lam(x), P^m_lam(-x)} """ for m,lam, x in [(3,0.75+0.1j,0.4), (0,0.75+0.1j,0.4), (25,0.75+0.1j,0.1)]: llp1 = lam*(lam+1) p = lam...
0.647575
0.568176
import collections import itertools import os import pickle import numpy as np import torch from sketchgraphs_models import training from sketchgraphs_models.graph import model as graph_model from sketchgraphs_models.nn import summary def _detach(x): if isinstance(x, torch.Tensor): return x.detach() ...
sketchgraphs_models/graph/train/harness.py
import collections import itertools import os import pickle import numpy as np import torch from sketchgraphs_models import training from sketchgraphs_models.graph import model as graph_model from sketchgraphs_models.nn import summary def _detach(x): if isinstance(x, torch.Tensor): return x.detach() ...
0.673514
0.277259
import argparse import dpkt import random import re import struct def main(): """ Main packet generator function """ parser = argparse.ArgumentParser() parser.add_argument('-t', dest = 'textFilename', action = 'store', help = 'Output text file') parser.add_argument('-p', dest = 'pcapF...
FPGA/Utilities/PacketGenerator/PacketGenerator.py
import argparse import dpkt import random import re import struct def main(): """ Main packet generator function """ parser = argparse.ArgumentParser() parser.add_argument('-t', dest = 'textFilename', action = 'store', help = 'Output text file') parser.add_argument('-p', dest = 'pcapF...
0.324878
0.077065
import numpy as np import pandas as pd import math # Logarithmic Mean Temperature Difference (LMTD) is used to determine the temperature driving force for heat transfer in flow systems. def heat_capacity(mass_flow_rate, cp): """ Calculates the heat_capacity given a mass_flow_rate and a specif_heat of a m...
files/lmtd.py
import numpy as np import pandas as pd import math # Logarithmic Mean Temperature Difference (LMTD) is used to determine the temperature driving force for heat transfer in flow systems. def heat_capacity(mass_flow_rate, cp): """ Calculates the heat_capacity given a mass_flow_rate and a specif_heat of a m...
0.918763
0.871748
from __future__ import print_function import os import cv2 import sys import time import uuid import json import glob import boto3 import flask import errno import shutil import datetime from PIL import Image from pathlib import Path from multiprocessing import Pool from collections import OrderedDict import traceb...
sagemaker/02-inference/source/predictor.py
from __future__ import print_function import os import cv2 import sys import time import uuid import json import glob import boto3 import flask import errno import shutil import datetime from PIL import Image from pathlib import Path from multiprocessing import Pool from collections import OrderedDict import traceb...
0.370681
0.079997