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 argparse import os import time import torch import torch.optim as optim import numpy as np import utils import Models.CNNs import Models.NNs from evaluate import evaluate from Models.data_loaders import fetch_dataloader # Set up command line arguments parser = argparse.ArgumentParser() parser.add_argument('-d...
train.py
import argparse import os import time import torch import torch.optim as optim import numpy as np import utils import Models.CNNs import Models.NNs from evaluate import evaluate from Models.data_loaders import fetch_dataloader # Set up command line arguments parser = argparse.ArgumentParser() parser.add_argument('-d...
0.835919
0.351367
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from habitat.core.embodied_task import Measure from habitat.core.registry import registry @registry.register_measure class CompositeReward(M...
habitat/tasks/rearrange/multi_task/composite_sensors.py
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from habitat.core.embodied_task import Measure from habitat.core.registry import registry @registry.register_measure class CompositeReward(M...
0.894881
0.141578
def barcode2(b1, b2, out_dir): fo = open(out_dir, 'w') bc_list = [" A1\tRound2_01\t/5Phos/CATCGGCGTACGACTAACGTGATATCCACGTGCTTGAG\tAACGTGAT\n", " A2\tRound2_02\t/5Phos/CATCGGCGTACGACTAAACATCGATCCACGTGCTTGAG\tAAACATCG\n", " A3\tRound2_03\t/5Phos/CATCGGCGTACGACTATGCCTAAATCCACGTGCTTGAG...
sdat/tools_bc/barcode2.py
def barcode2(b1, b2, out_dir): fo = open(out_dir, 'w') bc_list = [" A1\tRound2_01\t/5Phos/CATCGGCGTACGACTAACGTGATATCCACGTGCTTGAG\tAACGTGAT\n", " A2\tRound2_02\t/5Phos/CATCGGCGTACGACTAAACATCGATCCACGTGCTTGAG\tAAACATCG\n", " A3\tRound2_03\t/5Phos/CATCGGCGTACGACTATGCCTAAATCCACGTGCTTGAG...
0.353763
0.687105
import lx import lxifc import lxu.command import modo, tempfile, os class OD_PasteFromExternal(lxu.command.BasicCommand): def __init__(self): lxu.command.BasicCommand.__init__(self) def cmd_Flags(self): return lx.symbol.fCMD_MODEL | lx.symbol.fCMD_UNDO def basic_Enable(self, msg): ...
Modo/Kits/OD_ModoCopyPasteExternal/lxserv/cmd_pasteFromExternal.py
import lx import lxifc import lxu.command import modo, tempfile, os class OD_PasteFromExternal(lxu.command.BasicCommand): def __init__(self): lxu.command.BasicCommand.__init__(self) def cmd_Flags(self): return lx.symbol.fCMD_MODEL | lx.symbol.fCMD_UNDO def basic_Enable(self, msg): ...
0.27474
0.222795
from .optim import Optimizer class LearningRateScheduler(object): """ The base class of learning rate scheduler When writing a new scheduler, two functions should be implemented. - ```should_scheduler``` is used the return the condition to trigger the scheduler. - ```get_new_lr``` is the funct...
src/utils/lr_scheduler.py
from .optim import Optimizer class LearningRateScheduler(object): """ The base class of learning rate scheduler When writing a new scheduler, two functions should be implemented. - ```should_scheduler``` is used the return the condition to trigger the scheduler. - ```get_new_lr``` is the funct...
0.951757
0.892703
import threading as th from time import sleep from devices.device_reader import create_reader, AbstractReader class DeviceMonitor: def __init__(self, config=None): """Standard constructor Args: config ([dict], optional): [Dictionary providing information about devices. For every devi...
devices/device_monitor.py
import threading as th from time import sleep from devices.device_reader import create_reader, AbstractReader class DeviceMonitor: def __init__(self, config=None): """Standard constructor Args: config ([dict], optional): [Dictionary providing information about devices. For every devi...
0.768386
0.288578
import hashlib import pickle class AuthException(Exception): def __init__(self, username, user=None): super().__init__(username, user) self.username = username self.user = user class UserExists(AuthException): pass class PasswordtooShort(AuthException): pass class InvalidUsername...
loginbackend.py
import hashlib import pickle class AuthException(Exception): def __init__(self, username, user=None): super().__init__(username, user) self.username = username self.user = user class UserExists(AuthException): pass class PasswordtooShort(AuthException): pass class InvalidUsername...
0.429071
0.070113
import argparse import logging.handlers from configparser import ConfigParser from hotdogconfig import Configuration from hotdogcmdfactory import HotDogCmdFactory LOG_FILE_NAME = "hotdog.log" CFG_FILE_NAME = "config.ini" logger = logging.getLogger("ACE") formatter = logging.Formatter("%(asctime)s - %(name)s - %(leve...
main.py
import argparse import logging.handlers from configparser import ConfigParser from hotdogconfig import Configuration from hotdogcmdfactory import HotDogCmdFactory LOG_FILE_NAME = "hotdog.log" CFG_FILE_NAME = "config.ini" logger = logging.getLogger("ACE") formatter = logging.Formatter("%(asctime)s - %(name)s - %(leve...
0.33644
0.037538
from django.http import Http404 from collections import OrderedDict from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import permissions from utils import solr from utils.redisobjs import RedisObject from api i...
django/sierra/shelflist/views.py
from django.http import Http404 from collections import OrderedDict from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import permissions from utils import solr from utils.redisobjs import RedisObject from api i...
0.614972
0.10711
from django.template import loader from django.urls import NoReverseMatch, reverse from django.utils.module_loading import import_string import requests_mock from freezegun import freeze_time from mock import patch from rest_framework.test import APITestCase from openpersonen.api.tests.factory_models import ( Gez...
src/openpersonen/api/tests/views/test_ingeschrevenpersoon.py
from django.template import loader from django.urls import NoReverseMatch, reverse from django.utils.module_loading import import_string import requests_mock from freezegun import freeze_time from mock import patch from rest_framework.test import APITestCase from openpersonen.api.tests.factory_models import ( Gez...
0.47244
0.216198
from bs4 import BeautifulSoup import requests from lse.utils.cleaner import cleanQuery, formatHTMLNewLines from lse.utils.strikeamatch import compare_strings TIMEOUT = 5 class BaseEngine: def __init__(self): self.results = [] self.libparser = 'html5lib' self.queryString = 'q' def ...
lse/engines/__init__.py
from bs4 import BeautifulSoup import requests from lse.utils.cleaner import cleanQuery, formatHTMLNewLines from lse.utils.strikeamatch import compare_strings TIMEOUT = 5 class BaseEngine: def __init__(self): self.results = [] self.libparser = 'html5lib' self.queryString = 'q' def ...
0.406862
0.075244
from argparse import ArgumentParser from pathlib import Path import pickle import json from sklearn.metrics import f1_score import pandas as pd from grants_tagger.predict import predict def get_tags(data, annotator): tag_columns = [col for col in data.columns if annotator in col] tags = [] for _, row in...
grants_tagger/evaluate_mesh_on_grants.py
from argparse import ArgumentParser from pathlib import Path import pickle import json from sklearn.metrics import f1_score import pandas as pd from grants_tagger.predict import predict def get_tags(data, annotator): tag_columns = [col for col in data.columns if annotator in col] tags = [] for _, row in...
0.695235
0.202917
import argparse import os import subprocess import numpy as np from jinja2 import Template import datasets as ds import utils from vgg16 import vgg16_multilabel_hdf5 from utils import flip_labels as flip_label_matrix EXP_DIR = os.path.join('data', 'experiments', 'espgame') DS_DIR = os.path.join('data', 'ESP-Game') A...
data/experiments/espgame/main.py
import argparse import os import subprocess import numpy as np from jinja2 import Template import datasets as ds import utils from vgg16 import vgg16_multilabel_hdf5 from utils import flip_labels as flip_label_matrix EXP_DIR = os.path.join('data', 'experiments', 'espgame') DS_DIR = os.path.join('data', 'ESP-Game') A...
0.394084
0.101322
import torch import torch.nn as nn import os.path def train_ae( model, dataset, iterations=10, lr=0.001, device='cpu', save_fn="mnist-cae", load_path="./models/saved_models/mnist-cae.h5" ): """ Train autoencoder, or load from save file. mod...
cem/train.py
import torch import torch.nn as nn import os.path def train_ae( model, dataset, iterations=10, lr=0.001, device='cpu', save_fn="mnist-cae", load_path="./models/saved_models/mnist-cae.h5" ): """ Train autoencoder, or load from save file. mod...
0.868827
0.401072
import datetime from typing import Dict, List, Optional, Union import msrest.serialization from ._compute_management_client_enums import * class ApiError(msrest.serialization.Model): """Api error. :param details: The Api error details. :type details: list[~azure.mgmt.compute.v2020_09_30.models.ApiErro...
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2020_09_30/models/_models_py3.py
import datetime from typing import Dict, List, Optional, Union import msrest.serialization from ._compute_management_client_enums import * class ApiError(msrest.serialization.Model): """Api error. :param details: The Api error details. :type details: list[~azure.mgmt.compute.v2020_09_30.models.ApiErro...
0.907887
0.208985
import numpy as np import shared def test_auc(): """ Test combined calculation of PR-AUC and ROC-AUC """ predicted = [ [0.2, 0.3, 0.5], [0.2, 0.41, 0.39], [0.2, 0.1, 0.7], [0.8, 0.1, 0.1], [0.4, 0.3, 0.3], ] groundtruth = [ [1, 0, 0], [0...
test/test_shared.py
import numpy as np import shared def test_auc(): """ Test combined calculation of PR-AUC and ROC-AUC """ predicted = [ [0.2, 0.3, 0.5], [0.2, 0.41, 0.39], [0.2, 0.1, 0.7], [0.8, 0.1, 0.1], [0.4, 0.3, 0.3], ] groundtruth = [ [1, 0, 0], [0...
0.683631
0.746601
from rest_framework import viewsets from rest_framework.permissions import SAFE_METHODS from .models import Item, CustomizationGroup, CustomizationItem, ModifierGroup from .serializers import ItemCreateSerializer, ItemUpdateSerializer, CustomizationGroupCreateSerializer, \ CustomizationGroupUpdateSerializer, Modif...
v1/item/views.py
from rest_framework import viewsets from rest_framework.permissions import SAFE_METHODS from .models import Item, CustomizationGroup, CustomizationItem, ModifierGroup from .serializers import ItemCreateSerializer, ItemUpdateSerializer, CustomizationGroupCreateSerializer, \ CustomizationGroupUpdateSerializer, Modif...
0.604165
0.140956
import sys import struct import numpy as np from torch import tensor from torch.nn import functional as fn def convolution3d_f32(): para = [] # init the input data and parameters batch = int(np.random.randint(1, high=4, size=1)) in_channel = int(np.random.randint(2, high=8, size=1)) in_dept...
tests/python_ref/convolution3d.py
import sys import struct import numpy as np from torch import tensor from torch.nn import functional as fn def convolution3d_f32(): para = [] # init the input data and parameters batch = int(np.random.randint(1, high=4, size=1)) in_channel = int(np.random.randint(2, high=8, size=1)) in_dept...
0.232571
0.333761
import dask.dataframe as dd import pandas as pd import glob from rmcalyse.log_setup import add_logging_handlers from rmcalyse.framework import Framework f = Framework.from_yaml('rmcalyse/input.yaml') """filelist = glob.glob('/scratch/rmcalyse/rmcalyse/read_in/many/*.rmc6f') def strip_brackets(s): try: ...
testdask.py
import dask.dataframe as dd import pandas as pd import glob from rmcalyse.log_setup import add_logging_handlers from rmcalyse.framework import Framework f = Framework.from_yaml('rmcalyse/input.yaml') """filelist = glob.glob('/scratch/rmcalyse/rmcalyse/read_in/many/*.rmc6f') def strip_brackets(s): try: ...
0.080928
0.252062
import tkinter import os import csv import matplotlib import matplotlib.pyplot import matplotlib.image # Creation of first GUI asking for file name input class file_input: # Global variable so file_name can be used across modules def file_name(): global file_name file_name = [] # Creatio...
gui.py
import tkinter import os import csv import matplotlib import matplotlib.pyplot import matplotlib.image # Creation of first GUI asking for file name input class file_input: # Global variable so file_name can be used across modules def file_name(): global file_name file_name = [] # Creatio...
0.279238
0.137996
import sys def suggest_by_compound(compounds, reactions, reactions2run, max_reactions, verbose=False): """ Identify a set of reactions that you should add to your model for growth because they contain orphan compounds This is a slightly different approach to suggesting by compound. We look for "orpha...
PyFBA/gapfill/orphan_compound.py
import sys def suggest_by_compound(compounds, reactions, reactions2run, max_reactions, verbose=False): """ Identify a set of reactions that you should add to your model for growth because they contain orphan compounds This is a slightly different approach to suggesting by compound. We look for "orpha...
0.542379
0.748995
import logging from .udp_transmitter import UDPTransmitter from .transmitter import Transmitter from .udp_receiver import UDPReceiver from .receiver import Receiver from .message import Message log = logging.getLogger('nodes') class AbstractNode: def __init__(self): self.bindings = {self} def bind(...
src/gabby/node.py
import logging from .udp_transmitter import UDPTransmitter from .transmitter import Transmitter from .udp_receiver import UDPReceiver from .receiver import Receiver from .message import Message log = logging.getLogger('nodes') class AbstractNode: def __init__(self): self.bindings = {self} def bind(...
0.622574
0.095349
# Script to quickly apply forces to the nimbro_op model in Gazebo # Author: <NAME> import optparse from math import sin, cos import rospy from gazebo_msgs.srv import ApplyBodyWrench, ApplyBodyWrenchRequest from geometry_msgs.msg import Point, Wrench def polar2D_to_cartesian3D((r, theta)): return (r*cos(theta), r*s...
src/nimbro/scripts/gazebo_apply_force.py
# Script to quickly apply forces to the nimbro_op model in Gazebo # Author: <NAME> import optparse from math import sin, cos import rospy from gazebo_msgs.srv import ApplyBodyWrench, ApplyBodyWrenchRequest from geometry_msgs.msg import Point, Wrench def polar2D_to_cartesian3D((r, theta)): return (r*cos(theta), r*s...
0.506103
0.430566
import contextlib import os import re import shutil import subprocess import tempfile import unittest import yaml _APP_NAME = './slp-poly' @contextlib.contextmanager def TempDir(): temp_dir = tempfile.mkdtemp() try: yield temp_dir finally: shutil.rmtree(temp_dir) @contextlib.contextmanager def TempF...
src/try_out/slp_poly_test.py
import contextlib import os import re import shutil import subprocess import tempfile import unittest import yaml _APP_NAME = './slp-poly' @contextlib.contextmanager def TempDir(): temp_dir = tempfile.mkdtemp() try: yield temp_dir finally: shutil.rmtree(temp_dir) @contextlib.contextmanager def TempF...
0.491944
0.215155
from collections import Counter import spacy as spacy from tqdm import tqdm import ujson as json import sys from readerUtils import read_discussion_forum, read_reddit_data from typing import List def save_word_vector(counter=None, emb_file="./data/glove.840B.300d.txt", vec_size=300, num_vectors=2196017, tag="discuss...
setup.py
from collections import Counter import spacy as spacy from tqdm import tqdm import ujson as json import sys from readerUtils import read_discussion_forum, read_reddit_data from typing import List def save_word_vector(counter=None, emb_file="./data/glove.840B.300d.txt", vec_size=300, num_vectors=2196017, tag="discuss...
0.487063
0.218763
def show_landscape(Xgrid, Ygrid, Zgrid): """Plot the quasi-potential landscape. Parameters ---------- Xgrid: `numpy.ndarray` x-coordinates of the Grid produced from the meshgrid function. Ygrid: `numpy.ndarray` y-coordinates of the Grid produced from the meshgrid function. Zgrid: `numpy.ndarray` ...
dynamo/plot/scPotential.py
def show_landscape(Xgrid, Ygrid, Zgrid): """Plot the quasi-potential landscape. Parameters ---------- Xgrid: `numpy.ndarray` x-coordinates of the Grid produced from the meshgrid function. Ygrid: `numpy.ndarray` y-coordinates of the Grid produced from the meshgrid function. Zgrid: `numpy.ndarray` ...
0.844313
0.622258
from ..color import Color from . import Piece, King from src.core.classes.position import Position from src.utils import extract class PieceManager: """ """ piece_positions : dict[Piece, Position] _last_id : int def __init__(self) -> None: self._last_id = 0 self.piece_positions = ...
src/core/classes/pieces/piece_manager.py
from ..color import Color from . import Piece, King from src.core.classes.position import Position from src.utils import extract class PieceManager: """ """ piece_positions : dict[Piece, Position] _last_id : int def __init__(self) -> None: self._last_id = 0 self.piece_positions = ...
0.74872
0.367072
from flask.globals import current_app from yaspin import yaspin import logging import subprocess import configparser import os import sys import atexit import warnings import socket import emoji import time import sqlite3 import requests from logging.handlers import RotatingFileHandler from packaging import version fro...
warden/__main__.py
from flask.globals import current_app from yaspin import yaspin import logging import subprocess import configparser import os import sys import atexit import warnings import socket import emoji import time import sqlite3 import requests from logging.handlers import RotatingFileHandler from packaging import version fro...
0.314156
0.062474
import numpy as np import cv2 import os import sys import tensorflow as tf def mb_index(sample_n, img_n): index_matrix = np.zeros((sample_n, img_n)) for i in range(sample_n): index_tem = np.arange(img_n) np.random.shuffle(index_tem) index_matrix[i, :] = index_tem return ...
img_loading.py
import numpy as np import cv2 import os import sys import tensorflow as tf def mb_index(sample_n, img_n): index_matrix = np.zeros((sample_n, img_n)) for i in range(sample_n): index_tem = np.arange(img_n) np.random.shuffle(index_tem) index_matrix[i, :] = index_tem return ...
0.320502
0.237753
import json import string import random from hashlib import sha256 import logging import requests from proxy.request import send_request, Request from proxy.response import Response from resources.base import Resource logger = logging.getLogger() class AAFResource(Resource): def __init__(self, service): su...
middle_tier/plugins/aaf/endpoint.py
import json import string import random from hashlib import sha256 import logging import requests from proxy.request import send_request, Request from proxy.response import Response from resources.base import Resource logger = logging.getLogger() class AAFResource(Resource): def __init__(self, service): su...
0.327776
0.049108
import functools from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for ) from werkzeug.security import check_password_hash, generate_password_hash from funnel.db import get_db bp = Blueprint('auth', __name__, url_prefix='/auth') @bp.before_app_request def load...
funnel/auth.py
import functools from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for ) from werkzeug.security import check_password_hash, generate_password_hash from funnel.db import get_db bp = Blueprint('auth', __name__, url_prefix='/auth') @bp.before_app_request def load...
0.260672
0.053477
import os import hashlib class FileChecker(object): """ Several fit tests comparing file information and files. """ def __init__(self, info_path, info_checksum, info_size): self.info_path = info_path self.info_name = os.path.basename(info_path) self.info_checksum = info_checks...
filechecker.py
import os import hashlib class FileChecker(object): """ Several fit tests comparing file information and files. """ def __init__(self, info_path, info_checksum, info_size): self.info_path = info_path self.info_name = os.path.basename(info_path) self.info_checksum = info_checks...
0.350866
0.231821
import collections from typing import List, Dict import numpy as np from medtagger.types import SliceID from medtagger.database import models from medtagger.repositories import slices as SlicesRepository from medtagger.ground_truth import parsers from medtagger.ground_truth.algorithms.base import GeneratorAlgorithm ...
backend/medtagger/ground_truth/generator.py
import collections from typing import List, Dict import numpy as np from medtagger.types import SliceID from medtagger.database import models from medtagger.repositories import slices as SlicesRepository from medtagger.ground_truth import parsers from medtagger.ground_truth.algorithms.base import GeneratorAlgorithm ...
0.864968
0.591841
from django.template import Library from django.utils.html import format_html from sso.views.main import PAGE_VAR register = Library() DOT = '.' @register.simple_tag(takes_context=True) def selected(context, param_name, param_value, default=None): if param_name in context.request.GET: if context.request...
apps/sso/templatetags/list.py
from django.template import Library from django.utils.html import format_html from sso.views.main import PAGE_VAR register = Library() DOT = '.' @register.simple_tag(takes_context=True) def selected(context, param_name, param_value, default=None): if param_name in context.request.GET: if context.request...
0.422981
0.144239
class ConstantsObj(object): def __getattribute__(self,name): val=object.__getattribute__(self,name) if name.startswith('__'): return val else: return val() def add_drop_database(self): """--add-drop-database Add a DROP DATABASE statement before each CRE...
utils/mysqldump_const.py
class ConstantsObj(object): def __getattribute__(self,name): val=object.__getattribute__(self,name) if name.startswith('__'): return val else: return val() def add_drop_database(self): """--add-drop-database Add a DROP DATABASE statement before each CRE...
0.315209
0.14627
from __future__ import division import os import cv2 import numpy as np import scipy.io import scipy.ndimage import tensorflow as tf from keras import backend as K from .configs import gaussian_sigma from .configs import * def padding(img, shape_r=240, shape_c=320, channels=3): img_padded = np.zeros((shape_r, s...
utils/ultilities.py
from __future__ import division import os import cv2 import numpy as np import scipy.io import scipy.ndimage import tensorflow as tf from keras import backend as K from .configs import gaussian_sigma from .configs import * def padding(img, shape_r=240, shape_c=320, channels=3): img_padded = np.zeros((shape_r, s...
0.538983
0.31218
import boto3 import datetime import dateutil.parser as dp import sys import argparse ec2 = boto3.resource('ec2') def image_deregister(imageid): try: image = ec2.Image(imageid) image_date = image.creation_date except: print "ImageId not found, or you do not have permission to deregist...
ami-manager.py
import boto3 import datetime import dateutil.parser as dp import sys import argparse ec2 = boto3.resource('ec2') def image_deregister(imageid): try: image = ec2.Image(imageid) image_date = image.creation_date except: print "ImageId not found, or you do not have permission to deregist...
0.17575
0.097691
import pytest import requests_mock import requests import re from pupa.scrape.event import Event from lametro.events import LAMetroAPIEvent @pytest.mark.parametrize('api_status_name,scraper_assigned_status', [ ('Final', 'passed'), ('Final Revised', 'passed'), ('Final 2nd Revised', 'passed'), ('Draft...
tests/lametro/test_events.py
import pytest import requests_mock import requests import re from pupa.scrape.event import Event from lametro.events import LAMetroAPIEvent @pytest.mark.parametrize('api_status_name,scraper_assigned_status', [ ('Final', 'passed'), ('Final Revised', 'passed'), ('Final 2nd Revised', 'passed'), ('Draft...
0.488771
0.233925
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('project', '0001_initial'), ] operations = [ migrations.AlterField( model_name='activeproject', nam...
physionet-django/project/migrations/0002_auto_20181231_1623.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('project', '0001_initial'), ] operations = [ migrations.AlterField( model_name='activeproject', nam...
0.480479
0.088387
from __future__ import print_function, unicode_literals import os import sys from time import sleep try: import HTMLParser except ImportError: import html.parser as HTMLParser from .api import Fanfou, FanfouError from .oauth import OAuth, read_token_file from .oauth_dance import oauth_dance from .util import ...
fanpy/logger.py
from __future__ import print_function, unicode_literals import os import sys from time import sleep try: import HTMLParser except ImportError: import html.parser as HTMLParser from .api import Fanfou, FanfouError from .oauth import OAuth, read_token_file from .oauth_dance import oauth_dance from .util import ...
0.171789
0.049727
import globals as G import world.gen.layer.Layer import world.gen.mode import world.Dimension import world.Chunk import mod.ModMcpython class WorldGenerationHandler: def __init__(self): self.layers = {} self.features = {} self.configs = {} self.enable_generation = False sel...
world/gen/WorldGenerationHandler.py
import globals as G import world.gen.layer.Layer import world.gen.mode import world.Dimension import world.Chunk import mod.ModMcpython class WorldGenerationHandler: def __init__(self): self.layers = {} self.features = {} self.configs = {} self.enable_generation = False sel...
0.352425
0.120439
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import sys import tarfile import numpy as np from six.moves import urllib import pathlib from imageio import imread import tensorflow as tf import glob import scipy.misc import math import sys ...
util/inception_model.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import sys import tarfile import numpy as np from six.moves import urllib import pathlib from imageio import imread import tensorflow as tf import glob import scipy.misc import math import sys ...
0.382603
0.267469
import copy class InvadeAction: def __init__(self,country_from, country_to, troops, game_status, winner, reward): self.country_from = country_from self.country_to = country_to self.troops = troops self.game_status = game_status self.winner = winner self.reward = re...
action/action.py
import copy class InvadeAction: def __init__(self,country_from, country_to, troops, game_status, winner, reward): self.country_from = country_from self.country_to = country_to self.troops = troops self.game_status = game_status self.winner = winner self.reward = re...
0.633524
0.163479
import re from mongoframes.factory import blueprints from mongoframes.factory import makers from mongoframes.factory import quotas from mongoframes.factory.makers import selections as selection_makers from mongoframes.factory.makers import text as text_makers from tests.fixtures import * def test_maker(): """ ...
tests/factory/makers/test_makers.py
import re from mongoframes.factory import blueprints from mongoframes.factory import makers from mongoframes.factory import quotas from mongoframes.factory.makers import selections as selection_makers from mongoframes.factory.makers import text as text_makers from tests.fixtures import * def test_maker(): """ ...
0.764716
0.555315
import speech_recognition as sr import pyttsx3 import datetime import wikipedia import webbrowser import os import time import subprocess from ecapture import ecapture as ec import wolframalpha import json import requests import pyaudio engine=pyttsx3.init('sapi5') voices=engine.getProperty('voices')...
ArtificialIntelligence.py
import speech_recognition as sr import pyttsx3 import datetime import wikipedia import webbrowser import os import time import subprocess from ecapture import ecapture as ec import wolframalpha import json import requests import pyaudio engine=pyttsx3.init('sapi5') voices=engine.getProperty('voices')...
0.164987
0.072472
import typing as T import voluptuous as vol from . import expr, schedule, util from .room import Room from .thermostat import Thermostat from .window_sensor import WindowSensor from .stats import StatisticsZone def build_schedule_rule(rule: dict) -> schedule.Rule: """Builds and returns a schedule rule from the ...
hass_apps/heaty/config.py
import typing as T import voluptuous as vol from . import expr, schedule, util from .room import Room from .thermostat import Thermostat from .window_sensor import WindowSensor from .stats import StatisticsZone def build_schedule_rule(rule: dict) -> schedule.Rule: """Builds and returns a schedule rule from the ...
0.632616
0.217691
import os import random import pickle import time import torch import numpy as np import matplotlib.pyplot as plt from torch.autograd import grad import torch.nn.functional as F import preconditioned_stochastic_gradient_descent as psgd#download psgd from https://github.com/lixilinx/psgd_torch import utilities as U cl...
RBNR_lixilinx/train_svhn.py
import os import random import pickle import time import torch import numpy as np import matplotlib.pyplot as plt from torch.autograd import grad import torch.nn.functional as F import preconditioned_stochastic_gradient_descent as psgd#download psgd from https://github.com/lixilinx/psgd_torch import utilities as U cl...
0.28897
0.480844
import concurrent.futures import html import re import time import pandas as pd import requests """ Global Variables """ URLS = ["https://www.reddit.com/r/movies/comments/2isv8p/what_are_some_good_mindfuck_movies_like_inception/", "https://www.reddit.com/r/MovieSuggestions/comments/n5w7p3/movies_similar_to_in...
MehirStuff/RedditQuerying/parse_reddit_threads.py
import concurrent.futures import html import re import time import pandas as pd import requests """ Global Variables """ URLS = ["https://www.reddit.com/r/movies/comments/2isv8p/what_are_some_good_mindfuck_movies_like_inception/", "https://www.reddit.com/r/MovieSuggestions/comments/n5w7p3/movies_similar_to_in...
0.210117
0.210807
import json import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences import numpy as np vocab_size = 1000 embedding_dim = 16 max_length = 32 trunc_type = 'post' padding_type = 'post' oov_tok = "<OOV>" training_size = 350 with ...
sarcasm_classifier.py
import json import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences import numpy as np vocab_size = 1000 embedding_dim = 16 max_length = 32 trunc_type = 'post' padding_type = 'post' oov_tok = "<OOV>" training_size = 350 with ...
0.668664
0.450722
from lx16a import * from math import sin, cos, pi import time import xlwt import pandas as pd import numpy as np from xlwt import Workbook class RecordMotorData(): def __init__ (self, servo): self.servo = servo; self.id = []; self.angleOffset = []; self.physicalPos = []; self.virtualPos = []; self.temp = ...
TestMotor2ExcelHealthCheck.py
from lx16a import * from math import sin, cos, pi import time import xlwt import pandas as pd import numpy as np from xlwt import Workbook class RecordMotorData(): def __init__ (self, servo): self.servo = servo; self.id = []; self.angleOffset = []; self.physicalPos = []; self.virtualPos = []; self.temp = ...
0.220594
0.233619
import unohelper from com.sun.star.beans.MethodConcept import ALL as MethodConcept_ALL from com.sun.star.beans.PropertyConcept import ATTRIBUTES as PropertyConcept_ATTRIBUTES, PROPERTYSET as PropertyConcept_PROPERTYSET from com.sun.star.awt import XItemListener def enableRemoteDebugging(func): # デバッグサーバーに接続したい関数やメソッドに...
GUI/src/unodialogsample2.py
import unohelper from com.sun.star.beans.MethodConcept import ALL as MethodConcept_ALL from com.sun.star.beans.PropertyConcept import ATTRIBUTES as PropertyConcept_ATTRIBUTES, PROPERTYSET as PropertyConcept_PROPERTYSET from com.sun.star.awt import XItemListener def enableRemoteDebugging(func): # デバッグサーバーに接続したい関数やメソッドに...
0.280518
0.238983
import maya.OpenMayaMPx as OpenMayaMPx import maya.OpenMaya as OpenMaya from sys import * import re from string import * from types import * import maya.cmds as cmds def hasPadding(name): m = re.search('_(\d+)', name) return True if m != None and m.group(0) != "" else False def hasType(name): m = re.search('(PLY|...
py/NewtonRenaming.py
import maya.OpenMayaMPx as OpenMayaMPx import maya.OpenMaya as OpenMaya from sys import * import re from string import * from types import * import maya.cmds as cmds def hasPadding(name): m = re.search('_(\d+)', name) return True if m != None and m.group(0) != "" else False def hasType(name): m = re.search('(PLY|...
0.080789
0.109372
from __future__ import unicode_literals from collections import OrderedDict from attrdict import AttrDict from django.conf import settings from django.db import migrations from django.utils import timezone from mezzanine.core.models import CONTENT_STATUS_PUBLISHED initial_homepage_content = ''' <section> <q>And...
derrida/outwork/migrations/0002_initial_pages.py
from __future__ import unicode_literals from collections import OrderedDict from attrdict import AttrDict from django.conf import settings from django.db import migrations from django.utils import timezone from mezzanine.core.models import CONTENT_STATUS_PUBLISHED initial_homepage_content = ''' <section> <q>And...
0.42931
0.242676
from __future__ import division # needed for customized candlestick from matplotlib.finance from matplotlib.lines import Line2D from matplotlib.patches import Rectangle def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0, colorline=None): """ Modified from matplotlib....
cryptrade/candlestick.py
from __future__ import division # needed for customized candlestick from matplotlib.finance from matplotlib.lines import Line2D from matplotlib.patches import Rectangle def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0, colorline=None): """ Modified from matplotlib....
0.855218
0.490419
import json import os from typing import Any, Callable, Dict, Optional, Tuple, Union import reprlib ConfigKey = Tuple[Union[str, int], ...] AttrKey = Tuple[Union[str, int], ...] KeyPair = Tuple[ConfigKey, Optional[AttrKey]] ConfigType = Any Loader = Callable[[str], Any] DumpTrace = Tuple[KeyPair, ...] LoadTrace = Tup...
pytorch_pfn_extras/config.py
import json import os from typing import Any, Callable, Dict, Optional, Tuple, Union import reprlib ConfigKey = Tuple[Union[str, int], ...] AttrKey = Tuple[Union[str, int], ...] KeyPair = Tuple[ConfigKey, Optional[AttrKey]] ConfigType = Any Loader = Callable[[str], Any] DumpTrace = Tuple[KeyPair, ...] LoadTrace = Tup...
0.668556
0.133783
import time import terminaltables from paperspace.commands import common from paperspace.exceptions import BadResponseError class _MachinesCommandBase(common.CommandBase): def _log_message(self, response, success_msg_template, error_msg): if response.ok: try: handle = respons...
paperspace/commands/machines.py
import time import terminaltables from paperspace.commands import common from paperspace.exceptions import BadResponseError class _MachinesCommandBase(common.CommandBase): def _log_message(self, response, success_msg_template, error_msg): if response.ok: try: handle = respons...
0.433981
0.14734
import datetime from unittest.mock import patch, MagicMock import pytest import pyresample from . import utils def test_show(fakescene, fakearea, tmp_path): """Test showing a scene and area.""" import sattools.vis from satpy import Scene comps = ["raspberry", "blueberry"] chans = ["maroshki", ...
tests/test_vis.py
import datetime from unittest.mock import patch, MagicMock import pytest import pyresample from . import utils def test_show(fakescene, fakearea, tmp_path): """Test showing a scene and area.""" import sattools.vis from satpy import Scene comps = ["raspberry", "blueberry"] chans = ["maroshki", ...
0.565659
0.572185
'''Report on biosmaple ontology terms, including pulling organ_slims from two servers to compare''' '''use requests to handle the HTTP connection''' import requests '''use json to convert between Python dictionaries and JSON objects''' import json '''use jsonschema to validate objects against the JSON schemas''' impor...
ontology_report.py
'''Report on biosmaple ontology terms, including pulling organ_slims from two servers to compare''' '''use requests to handle the HTTP connection''' import requests '''use json to convert between Python dictionaries and JSON objects''' import json '''use jsonschema to validate objects against the JSON schemas''' impor...
0.187765
0.08318
import collections import numpy as np import matplotlib import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from matplotlib.ticker import MaxNLocator from api.data.NoteGroupType import NoteGroupType def get_basic_data_as_text(_map): lines = [] lines.append("duration (s): {:....
api/plotting/Helper.py
import collections import numpy as np import matplotlib import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from matplotlib.ticker import MaxNLocator from api.data.NoteGroupType import NoteGroupType def get_basic_data_as_text(_map): lines = [] lines.append("duration (s): {:....
0.692746
0.527073
from typing import Callable, List, Union, Tuple, Dict import numpy as np import torch from attrbench.lib import AttributionWriter from attrbench.lib.masking import Masker from attrbench.metrics import MaskerMetric from ._dataset import _DeletionDataset from .result import DeletionResult from ._get_predictions import ...
src/attrbench/metrics/deletion/deletion.py
from typing import Callable, List, Union, Tuple, Dict import numpy as np import torch from attrbench.lib import AttributionWriter from attrbench.lib.masking import Masker from attrbench.metrics import MaskerMetric from ._dataset import _DeletionDataset from .result import DeletionResult from ._get_predictions import ...
0.876449
0.377254
import numpy as np import astropy.units as u from ..spectra.spectrum1d import Spectrum1D from ..fitting.continuum import fit_generic_continuum def single_peak_continuum(): np.random.seed(0) x = np.linspace(0., 10., 200) y_single = 3 * np.exp(-0.5 * (x - 6.3)**2 / 0.1**2) y_single += np.random.normal...
specutils/tests/test_continuum.py
import numpy as np import astropy.units as u from ..spectra.spectrum1d import Spectrum1D from ..fitting.continuum import fit_generic_continuum def single_peak_continuum(): np.random.seed(0) x = np.linspace(0., 10., 200) y_single = 3 * np.exp(-0.5 * (x - 6.3)**2 / 0.1**2) y_single += np.random.normal...
0.821653
0.582877
import os import re import shutil import argparse def gen_chain(c_path, q_path): chain_id = 1 q_files = os.listdir(q_path) q_files.sort() q_list = [0] * len(q_files) max_id = len(q_files) - 1 for i in range(max_id,1,-1): if(q_list[i] != 1): chain_path = c_path + str(chain_i...
project/chain-id-line.py
import os import re import shutil import argparse def gen_chain(c_path, q_path): chain_id = 1 q_files = os.listdir(q_path) q_files.sort() q_list = [0] * len(q_files) max_id = len(q_files) - 1 for i in range(max_id,1,-1): if(q_list[i] != 1): chain_path = c_path + str(chain_i...
0.163379
0.161816
import json from collections import namedtuple import pytest TestCase = namedtuple("TestCase", ("expr", "data", "result")) with open("test/data/2.json", "rb") as f: data = json.load(f) @pytest.fixture( params=[ TestCase("$.*", data, list(data.values())), TestCase("$.book", data, [data["book...
test/conftest.py
import json from collections import namedtuple import pytest TestCase = namedtuple("TestCase", ("expr", "data", "result")) with open("test/data/2.json", "rb") as f: data = json.load(f) @pytest.fixture( params=[ TestCase("$.*", data, list(data.values())), TestCase("$.book", data, [data["book...
0.392104
0.6466
from pyecobee.ecobee_object import EcobeeObject class HouseDetails(EcobeeObject): """ This class has been auto generated by scraping https://www.ecobee.com/home/developer/api/documentation/v1/objects/HouseDetails.shtml Attribute names have been generated by converting ecobee property names from c...
pyecobee/objects/house_details.py
from pyecobee.ecobee_object import EcobeeObject class HouseDetails(EcobeeObject): """ This class has been auto generated by scraping https://www.ecobee.com/home/developer/api/documentation/v1/objects/HouseDetails.shtml Attribute names have been generated by converting ecobee property names from c...
0.863478
0.400573
from root.config.main import * import matplotlib.pyplot as plt from screws.freeze.main import FrozenOnly class _2dCSCG_ScalarField_Visualize_matplot(FrozenOnly): def __init__(self, cf): self._cf_ = cf self._mesh_ = self._cf_.mesh self._freeze_self_() @staticmethod def ___set_conto...
objects/CSCG/_2d/fields/scalar/visualize/matplot.py
from root.config.main import * import matplotlib.pyplot as plt from screws.freeze.main import FrozenOnly class _2dCSCG_ScalarField_Visualize_matplot(FrozenOnly): def __init__(self, cf): self._cf_ = cf self._mesh_ = self._cf_.mesh self._freeze_self_() @staticmethod def ___set_conto...
0.680985
0.29785
from sanic import Blueprint from sanic.log import logger from models.user import User from .user import userMultiAndScalarValidate from helpers.func import ( resJson, resType, lowerString, getUTCDate, is_hash_valid, validate_list, exceptionRaise ) from helpers.validator import registerUserVa...
sanicbe/src/views/auth.py
from sanic import Blueprint from sanic.log import logger from models.user import User from .user import userMultiAndScalarValidate from helpers.func import ( resJson, resType, lowerString, getUTCDate, is_hash_valid, validate_list, exceptionRaise ) from helpers.validator import registerUserVa...
0.330363
0.063048
import json from ibmcloud_python_sdk.config import params from ibmcloud_python_sdk.utils.common import query_wrapper as qw from ibmcloud_python_sdk.power import get_power_headers as headers from ibmcloud_python_sdk.utils.common import resource_not_found from ibmcloud_python_sdk.utils.common import resource_deleted from...
ibmcloud_python_sdk/power/pvm.py
import json from ibmcloud_python_sdk.config import params from ibmcloud_python_sdk.utils.common import query_wrapper as qw from ibmcloud_python_sdk.power import get_power_headers as headers from ibmcloud_python_sdk.utils.common import resource_not_found from ibmcloud_python_sdk.utils.common import resource_deleted from...
0.621311
0.109801
from web3 import Web3, HTTPProvider from web3.contract import ConciseContract import json class Web3Wrapper(object): DEFAULT_CONF = { 'chainId': 3, 'url': 'https://ropsten.infura.io/4gmRz0RyQUqgK0Q1jdu5', #'privatekey_path': 'keystore/UTC--2018-01-14T18-46-20.321874736Z--da83aee0f49802a33...
src/alphacar/web3_wrapper.py
from web3 import Web3, HTTPProvider from web3.contract import ConciseContract import json class Web3Wrapper(object): DEFAULT_CONF = { 'chainId': 3, 'url': 'https://ropsten.infura.io/4gmRz0RyQUqgK0Q1jdu5', #'privatekey_path': 'keystore/UTC--2018-01-14T18-46-20.321874736Z--da83aee0f49802a33...
0.415847
0.14253
import distutils.util import argparse import sys from pathlib import Path import yaml def preprocess_args_and_create_parser(): parser = argparse.ArgumentParser() parser.add_argument('--results_dir', help='results dir') parser.add_argument('--experiment_dir', help='Name for this experiment (will be a ti...
openkge/options.py
import distutils.util import argparse import sys from pathlib import Path import yaml def preprocess_args_and_create_parser(): parser = argparse.ArgumentParser() parser.add_argument('--results_dir', help='results dir') parser.add_argument('--experiment_dir', help='Name for this experiment (will be a ti...
0.428951
0.07921
# The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ...
zippy/benchmarks/src/benchmarks/python-graph/tests/unittests-filters.py
# The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ...
0.799755
0.373476
import numpy as np import h5py from sklearn.preprocessing import StandardScaler from scipy import signal as sig from pathlib import Path from net import RNN # LOADING def check_load(p="project_datasets/"): return Path(p+"pre_data.mat").exists() def save_pre_processed(X, y, Xval, yval, Xtest, ytest, p="project_d...
data.py
import numpy as np import h5py from sklearn.preprocessing import StandardScaler from scipy import signal as sig from pathlib import Path from net import RNN # LOADING def check_load(p="project_datasets/"): return Path(p+"pre_data.mat").exists() def save_pre_processed(X, y, Xval, yval, Xtest, ytest, p="project_d...
0.380529
0.483344
import pytest from httpx import AsyncClient from slugify import slugify from starlette import status from app import schemas from app.api.routers.articles import SLUG_NOT_FOUND from app.crud import crud_article, crud_comment from tests.utils.article import NOT_EXISTED_SLUG, create_test_article from tests.utils.comment...
tests/api/test_comments.py
import pytest from httpx import AsyncClient from slugify import slugify from starlette import status from app import schemas from app.api.routers.articles import SLUG_NOT_FOUND from app.crud import crud_article, crud_comment from tests.utils.article import NOT_EXISTED_SLUG, create_test_article from tests.utils.comment...
0.406273
0.245794
import numpy as np from scipy import sparse from scipy.ndimage import gaussian_filter import functools try: import rpy2 except (ImportError, RuntimeError): pass DEFAULT_BINNING = 1000 def tsv2csv(tsv, binning=DEFAULT_BINNING, output=None): matrix = np.genfromtxt(tsv, dtype=None, comments=None, delimite...
serpentine/benchmarks.py
import numpy as np from scipy import sparse from scipy.ndimage import gaussian_filter import functools try: import rpy2 except (ImportError, RuntimeError): pass DEFAULT_BINNING = 1000 def tsv2csv(tsv, binning=DEFAULT_BINNING, output=None): matrix = np.genfromtxt(tsv, dtype=None, comments=None, delimite...
0.53607
0.583233
import abc from typing import Any, Dict, List, Tuple, Optional from pidal.node.result.command import Command class Result(abc.ABC): @abc.abstractmethod def to_mysql(self): pass class ResultDescription(Result): def __init__(self, catalog: Optional[str], db: O...
pidal/node/result/result.py
import abc from typing import Any, Dict, List, Tuple, Optional from pidal.node.result.command import Command class Result(abc.ABC): @abc.abstractmethod def to_mysql(self): pass class ResultDescription(Result): def __init__(self, catalog: Optional[str], db: O...
0.79858
0.271593
import copy import itertools import json import locale import shutil import tempfile from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Callable, ClassVar, Dict, Iterator, List, Mapping, Optional, Set, Tuple, Union import numpy as np import pandas as pd from bs4...
sec_certs/dataset/common_criteria.py
import copy import itertools import json import locale import shutil import tempfile from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Callable, ClassVar, Dict, Iterator, List, Mapping, Optional, Set, Tuple, Union import numpy as np import pandas as pd from bs4...
0.559531
0.221751
from ibm_schematics.schematics_v1 import SchematicsV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator import requests import time import json from ibm_cloud_sdk_core import ApiException from src.common.functions import Color as Color class WorkspaceCreator: def __init__(self, cis_api_key, schematic...
src/iks/create_terraform_workspace.py
from ibm_schematics.schematics_v1 import SchematicsV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator import requests import time import json from ibm_cloud_sdk_core import ApiException from src.common.functions import Color as Color class WorkspaceCreator: def __init__(self, cis_api_key, schematic...
0.501953
0.15511
import commonware.log from cache_nuggets.lib import Token from rest_framework import serializers from rest_framework.exceptions import ParseError from rest_framework.generics import CreateAPIView, ListAPIView from rest_framework.response import Response from mkt.api.authentication import (RestOAuthAuthentication, ...
mkt/reviewers/api.py
import commonware.log from cache_nuggets.lib import Token from rest_framework import serializers from rest_framework.exceptions import ParseError from rest_framework.generics import CreateAPIView, ListAPIView from rest_framework.response import Response from mkt.api.authentication import (RestOAuthAuthentication, ...
0.516352
0.169475
from api.fields import HTMLTextField, EscapedTextField, HyphenatedTextField from brainstorming.models import Brainstorming, Idea, BrainstormingWatcher, IDEA_COLORS from brainstorming.permissions import can_edit_brainstorming, rated_idea, can_edit_idea from easy_thumbnails.files import get_thumbnailer from rest_framewor...
brainstorming/serializers.py
from api.fields import HTMLTextField, EscapedTextField, HyphenatedTextField from brainstorming.models import Brainstorming, Idea, BrainstormingWatcher, IDEA_COLORS from brainstorming.permissions import can_edit_brainstorming, rated_idea, can_edit_idea from easy_thumbnails.files import get_thumbnailer from rest_framewor...
0.666062
0.119897
from SQLBase import TableProxy, Query class WikimapPointsTable(TableProxy): def __init__(self, tablePath): super(WikimapPointsTable, self).__init__(tablePath, useCustomTypes=True) def create(self): self.execute(Query(u""" CREATE TABLE wikipoints ( wp_id ...
wikimap_ui/models/common/SQLTables.py
from SQLBase import TableProxy, Query class WikimapPointsTable(TableProxy): def __init__(self, tablePath): super(WikimapPointsTable, self).__init__(tablePath, useCustomTypes=True) def create(self): self.execute(Query(u""" CREATE TABLE wikipoints ( wp_id ...
0.507324
0.169646
import datetime from south.db import db from south.v2 import DataMigration from django.db import models, connection class Migration(DataMigration): def forwards(self, orm): cursor = connection.cursor() table_names = connection.introspection.get_table_list(cursor) # Nothing to migrate here ...
readme/migrations/0008_move_tags_to_custom_model.py
import datetime from south.db import db from south.v2 import DataMigration from django.db import models, connection class Migration(DataMigration): def forwards(self, orm): cursor = connection.cursor() table_names = connection.introspection.get_table_list(cursor) # Nothing to migrate here ...
0.336222
0.111217
from torch import nn from torch.nn import functional as F, init class ResidualBlock(nn.Module): def __init__(self, features, activation, zero_initialization=True, dropout_probability=0.1, use_batch_norm=True): super().__init__() self.activation = activation self.use_batch...
pytorch/models/energy.py
from torch import nn from torch.nn import functional as F, init class ResidualBlock(nn.Module): def __init__(self, features, activation, zero_initialization=True, dropout_probability=0.1, use_batch_norm=True): super().__init__() self.activation = activation self.use_batch...
0.967952
0.410756
import io import os import cv2 import numpy as np from PIL import Image from keras import backend from base64 import b64encode from keras.models import Model import matplotlib.pyplot as plt from keras_retinanet import models from keras_retinanet.utils.colors import label_color from keras_retinanet.utils.visualization i...
core.py
import io import os import cv2 import numpy as np from PIL import Image from keras import backend from base64 import b64encode from keras.models import Model import matplotlib.pyplot as plt from keras_retinanet import models from keras_retinanet.utils.colors import label_color from keras_retinanet.utils.visualization i...
0.809314
0.336672
import numpy as np #Differential Drive Robot Model #Input: #Input Vehicle parameters: #r_l = radius of the left wheel #r_r = radius of the right wheel #L = distance between the two wheels #Control Input parameters: #u_l = left wheel angular velocity #u_r = right wheel angular velocity #Robot State Input parameters #(x,...
Motion Models/python_versions/Motion_Model_Differential.py
import numpy as np #Differential Drive Robot Model #Input: #Input Vehicle parameters: #r_l = radius of the left wheel #r_r = radius of the right wheel #L = distance between the two wheels #Control Input parameters: #u_l = left wheel angular velocity #u_r = right wheel angular velocity #Robot State Input parameters #(x,...
0.679817
0.764078
import os from django.contrib.auth.models import Group, User from django.core.files.uploadedfile import SimpleUploadedFile from django.urls import reverse from rest_framework import status from .base import FVHAPITestCase from olmap import models from olmap.rest.permissions import REVIEWER_GROUP class OSMImageNotes...
django_server/olmap/rest/tests/osm_image_notes_tests.py
import os from django.contrib.auth.models import Group, User from django.core.files.uploadedfile import SimpleUploadedFile from django.urls import reverse from rest_framework import status from .base import FVHAPITestCase from olmap import models from olmap.rest.permissions import REVIEWER_GROUP class OSMImageNotes...
0.474144
0.236927
from __future__ import absolute_import from __future__ import unicode_literals from flask_security import UserMixin, RoleMixin from flask_security import utils as security_utils from sqlalchemy import Table, Column, Integer, String, DateTime, Boolean, ForeignKey from sqlalchemy.orm import relationship, backref from ...
ogreserver/models/user.py
from __future__ import absolute_import from __future__ import unicode_literals from flask_security import UserMixin, RoleMixin from flask_security import utils as security_utils from sqlalchemy import Table, Column, Integer, String, DateTime, Boolean, ForeignKey from sqlalchemy.orm import relationship, backref from ...
0.719778
0.105211
from rosidl_adapter.parser import parse_message_string def test_extract_message_comments(): # multi line file-level comment msg_spec = parse_message_string('pkg', 'Foo', '# comment 1\n#\n# comment 2\nbool value') assert len(msg_spec.annotations) == 1 assert 'comment' in msg_spec.annotations asser...
rosidl_adapter/test/test_extract_message_comments.py
from rosidl_adapter.parser import parse_message_string def test_extract_message_comments(): # multi line file-level comment msg_spec = parse_message_string('pkg', 'Foo', '# comment 1\n#\n# comment 2\nbool value') assert len(msg_spec.annotations) == 1 assert 'comment' in msg_spec.annotations asser...
0.601359
0.755986
from collections import deque from typing import Any, Tuple from rpcudp.protocol import RPCProtocol from swaplink import defaults from swaplink.abc import ISwaplinkProtocol, LinkType, Node, NodeAddr, ILinkStore from swaplink.errors import RPCError from swaplink.utils import random_choice_safe class SwaplinkProtocol...
swaplink/protocol.py
from collections import deque from typing import Any, Tuple from rpcudp.protocol import RPCProtocol from swaplink import defaults from swaplink.abc import ISwaplinkProtocol, LinkType, Node, NodeAddr, ILinkStore from swaplink.errors import RPCError from swaplink.utils import random_choice_safe class SwaplinkProtocol...
0.727298
0.120931
from scipy import signal import numpy as np import matplotlib.pyplot as plt import read_data_for_input as read_data def log_specgram(audio, sample_rate, window_size=20, step_size=10, eps=1e-10): nperseg = int(round(window_size * sample_rate / 1e3)) noverlap = int(round(step_size * sample_rate / 1e3)) freq...
show_sample_and_specgram.py
from scipy import signal import numpy as np import matplotlib.pyplot as plt import read_data_for_input as read_data def log_specgram(audio, sample_rate, window_size=20, step_size=10, eps=1e-10): nperseg = int(round(window_size * sample_rate / 1e3)) noverlap = int(round(step_size * sample_rate / 1e3)) freq...
0.59972
0.39712
from collections import namedtuple from operator import add,mul from PyQt6.QtGui import QPixmap, QColor, QBitmap from PyQt6.QtCore import Qt from helpers import Singleton RodRecord = namedtuple("RodRecord", ["pixmap", "pixmap_top", "durability", "neutron_emission", "neutron_self", "neutron_max", "neutron_div", "HUpe...
Fission Reactor Simulator/Assets.py
from collections import namedtuple from operator import add,mul from PyQt6.QtGui import QPixmap, QColor, QBitmap from PyQt6.QtCore import Qt from helpers import Singleton RodRecord = namedtuple("RodRecord", ["pixmap", "pixmap_top", "durability", "neutron_emission", "neutron_self", "neutron_max", "neutron_div", "HUpe...
0.542984
0.327749
import csv import pandas as pd from emoji import emojize def format_similar_names(similar_names, category): result, s = similar_names if category == "fish": s = f"{emojize(':fish:')} for '{s}'\n" elif category == "bug": s = f"{emojize(':bug:')} for '{s}'\n" else: s = "" len...
lib/critters.py
import csv import pandas as pd from emoji import emojize def format_similar_names(similar_names, category): result, s = similar_names if category == "fish": s = f"{emojize(':fish:')} for '{s}'\n" elif category == "bug": s = f"{emojize(':bug:')} for '{s}'\n" else: s = "" len...
0.269422
0.161552
from datetime import datetime import numpy as np from pup.common.constants import NUM_SECONDS_IN_DAY from pup.common.datatypes import Traj, Checkin from pup.common.enums import PricingType, DegradationType, ReconstructionMethod, TrajectoryIntervalType, \ PreviousPurchaseType from pup.config import Config from pup...
pup/voi/voi_utils.py
from datetime import datetime import numpy as np from pup.common.constants import NUM_SECONDS_IN_DAY from pup.common.datatypes import Traj, Checkin from pup.common.enums import PricingType, DegradationType, ReconstructionMethod, TrajectoryIntervalType, \ PreviousPurchaseType from pup.config import Config from pup...
0.768212
0.350394
import mxnet as mx from mxnet import nd, gluon, init, autograd from mxnet.gluon import data as gdata, loss as gloss, nn import matplotlib.pyplot as plt def dump_CNN(): threshold = 'relu' # 'relu' 'sigmoid' net = nn.Sequential() # nn.Sequential is subclass of nn.block with net.name_scope(): net.add...
code-ai/models-cnn-mxnet.py
import mxnet as mx from mxnet import nd, gluon, init, autograd from mxnet.gluon import data as gdata, loss as gloss, nn import matplotlib.pyplot as plt def dump_CNN(): threshold = 'relu' # 'relu' 'sigmoid' net = nn.Sequential() # nn.Sequential is subclass of nn.block with net.name_scope(): net.add...
0.761804
0.382949
import json, sys, os import codecs, datetime if __name__ == "__main__": DT = "2000-01-01" max = {} today = {} maxD = {} with codecs.open('/mnt/d/Twitediens/WTF-Snickers.json', 'r', encoding='utf-8', errors='ignore') as fullFile: for wi in fullFile: if len(wi) > 5: ...
max.py
import json, sys, os import codecs, datetime if __name__ == "__main__": DT = "2000-01-01" max = {} today = {} maxD = {} with codecs.open('/mnt/d/Twitediens/WTF-Snickers.json', 'r', encoding='utf-8', errors='ignore') as fullFile: for wi in fullFile: if len(wi) > 5: ...
0.108018
0.102305
import argparse from datetime import datetime from os.path import isabs, join from docqa import model_dir from docqa import trainer from docqa.data_processing.document_splitter import MergeParagraphs, ShallowOpenWebRanker from docqa.data_processing.multi_paragraph_qa import StratifyParagraphsBuilder, \ StratifyPara...
docqa/scripts/ablate_triviaqa_unfiltered.py
import argparse from datetime import datetime from os.path import isabs, join from docqa import model_dir from docqa import trainer from docqa.data_processing.document_splitter import MergeParagraphs, ShallowOpenWebRanker from docqa.data_processing.multi_paragraph_qa import StratifyParagraphsBuilder, \ StratifyPara...
0.460774
0.157169
from django.conf import settings from django.contrib.auth import authenticate from django.contrib.sites.models import Site from django.core.exceptions import PermissionDenied from django.db import models from django.utils.crypto import get_random_string from django.utils.encoding import force_text from django.utils.htt...
socialaccount/models.py
from django.conf import settings from django.contrib.auth import authenticate from django.contrib.sites.models import Site from django.core.exceptions import PermissionDenied from django.db import models from django.utils.crypto import get_random_string from django.utils.encoding import force_text from django.utils.htt...
0.550124
0.11187
import asyncio import logging import os from typing import List import pyppeteer import yarl from pyppeteer.browser import Browser from pyppeteer.errors import TimeoutError as PyppeteerTimeoutError from pyppeteer.page import Page from quart.local import LocalProxy log = logging.getLogger(__name__) CHROME_WS = os.get...
grobber/browser.py
import asyncio import logging import os from typing import List import pyppeteer import yarl from pyppeteer.browser import Browser from pyppeteer.errors import TimeoutError as PyppeteerTimeoutError from pyppeteer.page import Page from quart.local import LocalProxy log = logging.getLogger(__name__) CHROME_WS = os.get...
0.369998
0.053453
import unittest from unittest.mock import Mock from risk.risk_stratification import * class RiskClassificationTestMethod(unittest.TestCase): def setUp(self): self.fake_steve_buscemi = Patient('male', 61, 'no', 'yes', 25, 0, 'yes', 'no', 119, 78, 'no', 100, 70, 'no', 100, 60, 0) def test_risk_classifi...
tests/test_risk_stratification.py
import unittest from unittest.mock import Mock from risk.risk_stratification import * class RiskClassificationTestMethod(unittest.TestCase): def setUp(self): self.fake_steve_buscemi = Patient('male', 61, 'no', 'yes', 25, 0, 'yes', 'no', 119, 78, 'no', 100, 70, 'no', 100, 60, 0) def test_risk_classifi...
0.537527
0.66613
from dodge.components.component import Component from dodge.constants import ComponentType, EventType, EventParam from dodge.event import Event from dodge.components.position import Position class Inventory(Component): """ A component which can hold other entities, if they are marked with the Carryable component....
dodge/components/inventory.py
from dodge.components.component import Component from dodge.constants import ComponentType, EventType, EventParam from dodge.event import Event from dodge.components.position import Position class Inventory(Component): """ A component which can hold other entities, if they are marked with the Carryable component....
0.728072
0.188754
import torch def radial_slater( R, bas_n, bas_exp, xyz=None, derivative=0, jacobian=True): """Compute the radial part of STOs (or its derivative). Arguments: R {torch.tensor} -- distance between each electron and each atom bas_n {torch.tensor} -...
deepqmc/wavefunction/radial_functions.py
import torch def radial_slater( R, bas_n, bas_exp, xyz=None, derivative=0, jacobian=True): """Compute the radial part of STOs (or its derivative). Arguments: R {torch.tensor} -- distance between each electron and each atom bas_n {torch.tensor} -...
0.928547
0.85183
import math import random import inspect import pyglet from pyglet.gl import * orthoWidth = 1000 orthoHeight = 750 fieldHeight = 650 class Attribute: # Attribute in the gaming sense of the word, rather than of an object def __init__ (self, game): self.game = game # Attribute knows ...
assignments/pongTest.py
import math import random import inspect import pyglet from pyglet.gl import * orthoWidth = 1000 orthoHeight = 750 fieldHeight = 650 class Attribute: # Attribute in the gaming sense of the word, rather than of an object def __init__ (self, game): self.game = game # Attribute knows ...
0.528777
0.307046