code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import os import sys import time import json import random import itertools import subprocess def expjson( root_dir, experiment_id, epoch = None, iteration = None, columns = {}, meta = {}, tag = '', name = None, git_revision = True, git_http = None ): if git_revision is True: try: git_revision, git_co...
exphtml.py
import os import sys import time import json import random import itertools import subprocess def expjson( root_dir, experiment_id, epoch = None, iteration = None, columns = {}, meta = {}, tag = '', name = None, git_revision = True, git_http = None ): if git_revision is True: try: git_revision, git_co...
0.215681
0.105211
from functools import partial from uuid import uuid4 from shakenfist import baseobject from shakenfist.baseobject import ( DatabaseBackedObject as dbo, DatabaseBackedObjectIterator as dbo_iter) from shakenfist import blob from shakenfist import etcd from shakenfist import exceptions from shakenfist import log...
shakenfist/artifact.py
from functools import partial from uuid import uuid4 from shakenfist import baseobject from shakenfist.baseobject import ( DatabaseBackedObject as dbo, DatabaseBackedObjectIterator as dbo_iter) from shakenfist import blob from shakenfist import etcd from shakenfist import exceptions from shakenfist import log...
0.616936
0.167015
import numpy as np import nlopt as nl from .types import Folds from dora.regressors.gp import predict from dora.regressors.gp import linalg from dora.regressors.gp import types import sklearn.cluster as skcluster import scipy.interpolate as interp from scipy.spatial import Delaunay import scipy.stats as stats from scip...
dora/regressors/gp/train.py
import numpy as np import nlopt as nl from .types import Folds from dora.regressors.gp import predict from dora.regressors.gp import linalg from dora.regressors.gp import types import sklearn.cluster as skcluster import scipy.interpolate as interp from scipy.spatial import Delaunay import scipy.stats as stats from scip...
0.564579
0.387864
from django import forms from budgets.models import Budget class WilburForm(forms.Form): def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(WilburForm, self).__init__(*args, **kwargs) class BudgetForm(WilburForm): category = forms.ModelChoiceField( ...
budgets/forms.py
from django import forms from budgets.models import Budget class WilburForm(forms.Form): def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(WilburForm, self).__init__(*args, **kwargs) class BudgetForm(WilburForm): category = forms.ModelChoiceField( ...
0.622804
0.080973
# Obtains all user input and loops the program def userInput(): # Initialize variables selectContinue = 'Y' selectPuzzle = 0 # User inputs anything other than no while(not(selectContinue == 'N' or selectContinue == 'n')): # User selects a puzzle print "Please select a Sudoku Puzzle. [1-25]: ...
SudokuSolver.py
# Obtains all user input and loops the program def userInput(): # Initialize variables selectContinue = 'Y' selectPuzzle = 0 # User inputs anything other than no while(not(selectContinue == 'N' or selectContinue == 'n')): # User selects a puzzle print "Please select a Sudoku Puzzle. [1-25]: ...
0.453988
0.323701
import os import argparse import importlib from natsort import natsorted from tqdm import tqdm, trange from collections import Counter import numpy as np from imageio import imwrite from scipy.spatial.transform import Rotation from lib.misc.pano_lsd_align import rotatePanorama, panoEdgeDetection import torch import t...
evaluate/previous_works/HoHoNet/test_depth.py
import os import argparse import importlib from natsort import natsorted from tqdm import tqdm, trange from collections import Counter import numpy as np from imageio import imwrite from scipy.spatial.transform import Rotation from lib.misc.pano_lsd_align import rotatePanorama, panoEdgeDetection import torch import t...
0.651577
0.203846
from ariadne_jwt.utils import get_payload from ariadne_jwt.shortcuts import create_refresh_token, get_refresh_token from ..testcases import SchemaTestCase from ..decorators import override_jwt_settings from ..context_managers import back_to_the_future, refresh_expired class TokenAuthTests(SchemaTestCase): @overr...
tests/refresh_token/test_mutations.py
from ariadne_jwt.utils import get_payload from ariadne_jwt.shortcuts import create_refresh_token, get_refresh_token from ..testcases import SchemaTestCase from ..decorators import override_jwt_settings from ..context_managers import back_to_the_future, refresh_expired class TokenAuthTests(SchemaTestCase): @overr...
0.532425
0.177847
import numpy as np from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_raises from sklearn.dummy import DummyClassifier from sklearn.dummy import DummyRegressor def _check_p...
python/sklearn/sklearn/tests/test_dummy.py
import numpy as np from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_raises from sklearn.dummy import DummyClassifier from sklearn.dummy import DummyRegressor def _check_p...
0.760473
0.765199
async def help_handler(bot, message): msg = str(message.content).split(" ") command = msg[0:2] devRole = message.guild.get_role(678262267279572993) try: # main help if len(command) < 2 or command[1] == "": response = await help_main() # get all the different Help pa...
src/commands/help.py
async def help_handler(bot, message): msg = str(message.content).split(" ") command = msg[0:2] devRole = message.guild.get_role(678262267279572993) try: # main help if len(command) < 2 or command[1] == "": response = await help_main() # get all the different Help pa...
0.537041
0.49469
from typing import Any, Dict, List, Optional import numpy as np import pandas as pd from pandas.testing import assert_frame_equal import pytest import altair_transform @pytest.fixture def data() -> pd.DataFrame: rand = np.random.RandomState(42) df = pd.DataFrame( { "x": rand.randint(0, 1...
altair_transform/transform/tests/test_regression.py
from typing import Any, Dict, List, Optional import numpy as np import pandas as pd from pandas.testing import assert_frame_equal import pytest import altair_transform @pytest.fixture def data() -> pd.DataFrame: rand = np.random.RandomState(42) df = pd.DataFrame( { "x": rand.randint(0, 1...
0.876436
0.695435
import cv2 import numpy as np from torch import nn import torch try: from utils import SaveOutput except: from src.utils import SaveOutput class GradCam(): def __init__(self, model, module, device): self.device = device self.module = module.to(device) self.model = model.to(device...
src/explainers.py
import cv2 import numpy as np from torch import nn import torch try: from utils import SaveOutput except: from src.utils import SaveOutput class GradCam(): def __init__(self, model, module, device): self.device = device self.module = module.to(device) self.model = model.to(device...
0.643665
0.332608
import numpy as np from ... import utils from ..base import BaseAlg class ModelR(BaseAlg): """ The sender learns a model of the receiver and best responds to that model """ def __init__( self, n_state, n_mess, n_act, n_runs, alpha0=0.1, eps0=0....
signaling-games/algs/model_agents/model_r.py
import numpy as np from ... import utils from ..base import BaseAlg class ModelR(BaseAlg): """ The sender learns a model of the receiver and best responds to that model """ def __init__( self, n_state, n_mess, n_act, n_runs, alpha0=0.1, eps0=0....
0.783036
0.293544
from django.contrib.auth.models import User from django.db.models import Q from rest_framework import serializers, ISO_8601 from rest_framework.validators import UniqueValidator, UniqueTogetherValidator from driver.models import Driver, DriverAppUser, GPSLogNew, OTP, GPSDevice, GPSDeviceLog, TracknovateGPSDevice, \ ...
web/transiq/restapi/serializers/driver.py
from django.contrib.auth.models import User from django.db.models import Q from rest_framework import serializers, ISO_8601 from rest_framework.validators import UniqueValidator, UniqueTogetherValidator from driver.models import Driver, DriverAppUser, GPSLogNew, OTP, GPSDevice, GPSDeviceLog, TracknovateGPSDevice, \ ...
0.725065
0.135261
from in_rdbms_helper import params_fac from in_rdbms_helper import main_prepare from in_rdbms_helper import mst_2_str from utils import tstamp import datetime import time from utils import DBBase from utils import wait from utils import cats from imagenetcat import MODEL_SELECTION_TABLE from imagenetcat import MODEL_SE...
src/run_mop.py
from in_rdbms_helper import params_fac from in_rdbms_helper import main_prepare from in_rdbms_helper import mst_2_str from utils import tstamp import datetime import time from utils import DBBase from utils import wait from utils import cats from imagenetcat import MODEL_SELECTION_TABLE from imagenetcat import MODEL_SE...
0.370795
0.128881
import numpy as np from ..hrf import spm_hrf def _put(a, ind, v, mode='raise'): """np.put, not in-place.""" arr = a.copy() np.put(arr, ind, v, mode) return arr def detection_power(X, tr, contrasts=None, weights=None): """Estimate detection power of design matrix. Parameters ----------...
fmritools/design/efficiency.py
import numpy as np from ..hrf import spm_hrf def _put(a, ind, v, mode='raise'): """np.put, not in-place.""" arr = a.copy() np.put(arr, ind, v, mode) return arr def detection_power(X, tr, contrasts=None, weights=None): """Estimate detection power of design matrix. Parameters ----------...
0.705379
0.762645
import sys import operator from multiprocessing import Process, Lock import argparse import nltk import common import fileio import nltk_analyze import make_wordcloud import tokenizer import dialogues import sentiments import translations # TODO-list # TODO: # Topics. Maybe LDA (?) APP_NAME="lingval" VERSION_MAJOR...
main.py
import sys import operator from multiprocessing import Process, Lock import argparse import nltk import common import fileio import nltk_analyze import make_wordcloud import tokenizer import dialogues import sentiments import translations # TODO-list # TODO: # Topics. Maybe LDA (?) APP_NAME="lingval" VERSION_MAJOR...
0.232484
0.092237
import numpy as np from . import node2vec from .utils import dim_reduction class ATTRCOMB(object): def __init__(self, graph, dim, comb_method='concat', comb_with='deepWalk', number_walks=10, walk_length=80, window=10, workers=8): self.g = graph self.dim = dim self.number_walks = number_wa...
src/libnrl/attrcomb.py
import numpy as np from . import node2vec from .utils import dim_reduction class ATTRCOMB(object): def __init__(self, graph, dim, comb_method='concat', comb_with='deepWalk', number_walks=10, walk_length=80, window=10, workers=8): self.g = graph self.dim = dim self.number_walks = number_wa...
0.486332
0.24625
from flask import request, current_app from flask_restplus import Resource from sqlalchemy_filters import apply_sort, apply_pagination, apply_filters from sqlalchemy import desc, cast, NUMERIC, func, or_ from werkzeug.exceptions import BadRequest from app.extensions import api from app.api.utils.access_decorators impo...
services/core-api/app/api/variances/resources/variance_resource.py
from flask import request, current_app from flask_restplus import Resource from sqlalchemy_filters import apply_sort, apply_pagination, apply_filters from sqlalchemy import desc, cast, NUMERIC, func, or_ from werkzeug.exceptions import BadRequest from app.extensions import api from app.api.utils.access_decorators impo...
0.713432
0.120129
from datasets import load_dataset, load_metric, Dataset from transformers import AutoModelForQuestionAnswering, Trainer from config import Config from data_preparation import QAPreparer def evaluate(model_id: str, language: str) -> dict: # Load XQuAD xquad = load_dataset('xquad', f'xquad.{language}', split=...
src/eval.py
from datasets import load_dataset, load_metric, Dataset from transformers import AutoModelForQuestionAnswering, Trainer from config import Config from data_preparation import QAPreparer def evaluate(model_id: str, language: str) -> dict: # Load XQuAD xquad = load_dataset('xquad', f'xquad.{language}', split=...
0.851382
0.411406
import sys, dia # sys.path.insert(0, 'd:/graph/dia/dia') class DumpRenderer : def __init__ (self) : pass def begin_render (self, data, filename) : # DiagramData self.f = open(filename, "w") self.f.write("Data: " + str(data) + "\n") self.f.write("Extents: "+ str(data.extents) + "\n") self.f.write("active...
interfaces/dia/plug-ins/python/export-render.py
import sys, dia # sys.path.insert(0, 'd:/graph/dia/dia') class DumpRenderer : def __init__ (self) : pass def begin_render (self, data, filename) : # DiagramData self.f = open(filename, "w") self.f.write("Data: " + str(data) + "\n") self.f.write("Extents: "+ str(data.extents) + "\n") self.f.write("active...
0.195364
0.184473
from __future__ import absolute_import, print_function import os import os.path from libpebble2.communication.transports.websocket import WebsocketTransport, MessageTargetPhone from libpebble2.communication.transports.websocket.protocol import ( WebSocketInstallBundle, WebSocketInstallStatus) from libpebble2.ex...
pebble_tool/commands/data_logging.py
from __future__ import absolute_import, print_function import os import os.path from libpebble2.communication.transports.websocket import WebsocketTransport, MessageTargetPhone from libpebble2.communication.transports.websocket.protocol import ( WebSocketInstallBundle, WebSocketInstallStatus) from libpebble2.ex...
0.231093
0.111241
import collections import logging import mkdocs.utils from jinja2 import Environment from mkdocs.plugins import BasePlugin from mkdocs.structure.nav import Navigation, Section from mkdocs.structure.pages import Page from . import SectionPage, rewrites __all__ = ["SectionIndexPlugin"] log = logging.getLogger(f"mkdoc...
mkdocs_section_index/plugin.py
import collections import logging import mkdocs.utils from jinja2 import Environment from mkdocs.plugins import BasePlugin from mkdocs.structure.nav import Navigation, Section from mkdocs.structure.pages import Page from . import SectionPage, rewrites __all__ = ["SectionIndexPlugin"] log = logging.getLogger(f"mkdoc...
0.289874
0.094636
import threading import struct import bluetooth class MotionTracker(object): """Class to track movement from MPU6050 Bluetooth device. """ def __init__(self, bd_addr, port=1): """Initialization for tracker object. Args: bd_addr (str) : Bluetooth address port (int,...
src/motiontracker.py
import threading import struct import bluetooth class MotionTracker(object): """Class to track movement from MPU6050 Bluetooth device. """ def __init__(self, bd_addr, port=1): """Initialization for tracker object. Args: bd_addr (str) : Bluetooth address port (int,...
0.663669
0.260678
import argparse import os import torch class BaseOptions(): def __init__(self): self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) self.parser.add_argument('--dataroot', required=True, help='path to images (should have subfolders trainA, trainB, valA, ...
options.py
import argparse import os import torch class BaseOptions(): def __init__(self): self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) self.parser.add_argument('--dataroot', required=True, help='path to images (should have subfolders trainA, trainB, valA, ...
0.730482
0.117623
from flask import Flask, render_template, request, redirect, escape, session, url_for, flash import database, hashlib, models, time, datetime, json from database import db_session from models import User, Message app = Flask(__name__) @app.teardown_appcontext def shutdown_session(exception=None): db_session.re...
chatta.py
from flask import Flask, render_template, request, redirect, escape, session, url_for, flash import database, hashlib, models, time, datetime, json from database import db_session from models import User, Message app = Flask(__name__) @app.teardown_appcontext def shutdown_session(exception=None): db_session.re...
0.356671
0.066055
import os import sys import numpy as np import matplotlib.pylab as plt from agent import Qlearner, SARSAlearner from environment import Game #delete this ''' Plots the rewards ''' def plot_agent_reward(rewards): plt.plot(np.cumsum(rewards)) plt.title('Agent Cumulative Reward vs. Iteration') plt.ylabel('Re...
play.py
import os import sys import numpy as np import matplotlib.pylab as plt from agent import Qlearner, SARSAlearner from environment import Game #delete this ''' Plots the rewards ''' def plot_agent_reward(rewards): plt.plot(np.cumsum(rewards)) plt.title('Agent Cumulative Reward vs. Iteration') plt.ylabel('Re...
0.185873
0.326755
from DataObjects.Architecture.ClassFlatArchitecture import FlatArchitecture from DataObjects.FlowDataTypes.ClassBaseAccess import BaseAccess from DataObjects.ClassMultiDict import MultiDict from DataObjects.Transitions.ClassTransitionv2 import Transition_v2 from Backend.Murphi.BaseConfig import BaseConfig from Backen...
Backend/Murphi/MurphiModular/StateMachines/GenMurphiAccess.py
from DataObjects.Architecture.ClassFlatArchitecture import FlatArchitecture from DataObjects.FlowDataTypes.ClassBaseAccess import BaseAccess from DataObjects.ClassMultiDict import MultiDict from DataObjects.Transitions.ClassTransitionv2 import Transition_v2 from Backend.Murphi.BaseConfig import BaseConfig from Backen...
0.675122
0.254915
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py', '../_base_/swa.py' ] # model settings model = dict( type='CascadeRCNN', pretrained='https://download.openmmlab.com/pretrain/third_party/res2net101_v1d_26w_4s_mmdetv2-f0a600f9.pth', backbone=di...
configs/cascade_rcnn/config.py
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py', '../_base_/swa.py' ] # model settings model = dict( type='CascadeRCNN', pretrained='https://download.openmmlab.com/pretrain/third_party/res2net101_v1d_26w_4s_mmdetv2-f0a600f9.pth', backbone=di...
0.313
0.163679
import argparse import collections import glob import gzip import itertools import json import multiprocessing as mp import tarfile import traceback import os import numpy as np import tqdm import zstandard as zstd from sketchgraphs.data.sketch import Sketch from sketchgraphs.data import flat_array def _load_json(p...
sketchgraphs/pipeline/make_sketch_dataset.py
import argparse import collections import glob import gzip import itertools import json import multiprocessing as mp import tarfile import traceback import os import numpy as np import tqdm import zstandard as zstd from sketchgraphs.data.sketch import Sketch from sketchgraphs.data import flat_array def _load_json(p...
0.596786
0.161916
from __future__ import print_function import ConfigParser import collections import hashlib import json import logging as log import multiprocessing as mp import signal import os import sys import time import shutil from StringIO import StringIO from Crypto import Random from docoptcfg import DocoptcfgFileError fro...
ansible/environments/prod/gce_googleapiclient.py
from __future__ import print_function import ConfigParser import collections import hashlib import json import logging as log import multiprocessing as mp import signal import os import sys import time import shutil from StringIO import StringIO from Crypto import Random from docoptcfg import DocoptcfgFileError fro...
0.429908
0.056392
import requests_html import requests import execjs import time import json import re import hashlib # coding=UTF-8 from PIL import Image import numpy as np from io import BytesIO def getpoint(imgcontent, position): img = Image.open(BytesIO(imgcontent)) img.save('download.png') w, h = img.s...
crack.py
import requests_html import requests import execjs import time import json import re import hashlib # coding=UTF-8 from PIL import Image import numpy as np from io import BytesIO def getpoint(imgcontent, position): img = Image.open(BytesIO(imgcontent)) img.save('download.png') w, h = img.s...
0.101145
0.100481
from polygraphy import mod, util from polygraphy.backend.base import BaseLoader from polygraphy.logger import G_LOGGER onnxrt = mod.lazy_import("onnxruntime") @mod.export(funcify=True) class SessionFromOnnx(BaseLoader): """ Functor that builds an ONNX-Runtime inference session. """ def __init__(self...
tools/Polygraphy/polygraphy/backend/onnxrt/loader.py
from polygraphy import mod, util from polygraphy.backend.base import BaseLoader from polygraphy.logger import G_LOGGER onnxrt = mod.lazy_import("onnxruntime") @mod.export(funcify=True) class SessionFromOnnx(BaseLoader): """ Functor that builds an ONNX-Runtime inference session. """ def __init__(self...
0.870858
0.196055
from django import forms from django.contrib.auth.models import User from pagedown.widgets import PagedownWidget from .models import Post, Profile class PostForm(forms.ModelForm): publish = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Post fields = [ "title",...
post/forms.py
from django import forms from django.contrib.auth.models import User from pagedown.widgets import PagedownWidget from .models import Post, Profile class PostForm(forms.ModelForm): publish = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Post fields = [ "title",...
0.414069
0.085978
import logging from django.conf import settings from django.core.management import call_command from django.db.models import Prefetch from huey.contrib.djhuey import db_task, db_periodic_task from huey import crontab from .models import ( Transcript, TranscriptPhrase, TranscriptPhraseVote, TranscriptPhraseCor...
mla_game/apps/transcript/tasks.py
import logging from django.conf import settings from django.core.management import call_command from django.db.models import Prefetch from huey.contrib.djhuey import db_task, db_periodic_task from huey import crontab from .models import ( Transcript, TranscriptPhrase, TranscriptPhraseVote, TranscriptPhraseCor...
0.437343
0.205475
import json import html import docopt import yaml template = """\ # Zwift Workout File Reference This page describes the XML elements (tags) and attributes that can be used in [Zwift workout files][zwift-support-workouts]. It's automatically generated by analysing all of the workouts included with Zwift. It's inten...
zwift_zwo_docs/render_docs.py
{code}\
0.411584
0.359645
import kv2 import pprint example_input = r''' <!-- dmx encoding keyvalues2 1 format dmx 18 --> "DmElement" { "id" "elementid" "d1d1ffff-18a8-4fa7-ac0c-b436a32e5004" "name" "string" "untitled" "testarray" "element_array" [ "element" "6a1cd593-a1bf-48d2-843a-cc7c8f3ae05e", "element" "e6f90bc8-3b4c-4ea2-b863-c5c...
test.py
import kv2 import pprint example_input = r''' <!-- dmx encoding keyvalues2 1 format dmx 18 --> "DmElement" { "id" "elementid" "d1d1ffff-18a8-4fa7-ac0c-b436a32e5004" "name" "string" "untitled" "testarray" "element_array" [ "element" "6a1cd593-a1bf-48d2-843a-cc7c8f3ae05e", "element" "e6f90bc8-3b4c-4ea2-b863-c5c...
0.139602
0.201008
import threading import time from threading import RLock from typing import List, Dict, Tuple import predictor from cloud_controller import THROUGHPUT_ENABLED, THROUGHPUT_PERCENTILES, DEFAULT_HARDWARE_ID class MultiPredictor: """ A wrapper around a collection of Predictor instances. Creates and trains new pr...
cloud_controller/aggregator/multipredictor.py
import threading import time from threading import RLock from typing import List, Dict, Tuple import predictor from cloud_controller import THROUGHPUT_ENABLED, THROUGHPUT_PERCENTILES, DEFAULT_HARDWARE_ID class MultiPredictor: """ A wrapper around a collection of Predictor instances. Creates and trains new pr...
0.912843
0.366136
import sys,os APPS_HOME = "/usr/local/bin/" # where rcorrector is located RCORRECTOR_CMD = 'perl '+APPS_HOME+"/Rcorrector/run_rcorrector.pl" # Basic command to call rcorrector def rcorrector_se(se_fq,num_cores,DIR): if DIR == ".": DIR = os.getcwd() if os.path.isabs(DIR) == False: DIR = os.path.abspath(DIR) if D...
src/pdc2/scripts/rcorrector_wrapper.py
import sys,os APPS_HOME = "/usr/local/bin/" # where rcorrector is located RCORRECTOR_CMD = 'perl '+APPS_HOME+"/Rcorrector/run_rcorrector.pl" # Basic command to call rcorrector def rcorrector_se(se_fq,num_cores,DIR): if DIR == ".": DIR = os.getcwd() if os.path.isabs(DIR) == False: DIR = os.path.abspath(DIR) if D...
0.031972
0.129403
from .ast import Node # ------------------------------------------------------------------------------ class CompilationUnit(Node): attrs = ("package", "imports", "types") class Import(Node): attrs = ("path", "static", "wildcard") class Documented(Node): attrs = ("documentation",) class Declaration...
javalang/tree.py
from .ast import Node # ------------------------------------------------------------------------------ class CompilationUnit(Node): attrs = ("package", "imports", "types") class Import(Node): attrs = ("path", "static", "wildcard") class Documented(Node): attrs = ("documentation",) class Declaration...
0.750187
0.407245
from .maps import Map from .geometry import ( clean, get_intersection, kind_mapping, ) from .projection import project from logging.handlers import QueueHandler, QueueListener from shapely.geometry import shape from shapely.geos import TopologicalError import datetime import logging import math import multi...
pandarus/intersections.py
from .maps import Map from .geometry import ( clean, get_intersection, kind_mapping, ) from .projection import project from logging.handlers import QueueHandler, QueueListener from shapely.geometry import shape from shapely.geos import TopologicalError import datetime import logging import math import multi...
0.553988
0.248352
from bs4 import BeautifulSoup import requests from requests.exceptions import ConnectionError, HTTPError, Timeout import pickle import vim import sys import os import re import tex_handler AT_CODER_BASE_URL = 'https://atcoder.jp' AT_CODER_LOGIN_URL = AT_CODER_BASE_URL + '/login' class AtVimCoder: def __init__(self):...
python3/at_vim_coder.py
from bs4 import BeautifulSoup import requests from requests.exceptions import ConnectionError, HTTPError, Timeout import pickle import vim import sys import os import re import tex_handler AT_CODER_BASE_URL = 'https://atcoder.jp' AT_CODER_LOGIN_URL = AT_CODER_BASE_URL + '/login' class AtVimCoder: def __init__(self):...
0.053132
0.096068
import psycopg2 import os import requests import json import time import arrow import logging from typing import List, Tuple, Dict, Any from collections import defaultdict from apscheduler.schedulers.blocking import BlockingScheduler from telegram_bot import Bot logging.basicConfig(format='%(asctime)s %(levelname)s ...
batch_process_data.py
import psycopg2 import os import requests import json import time import arrow import logging from typing import List, Tuple, Dict, Any from collections import defaultdict from apscheduler.schedulers.blocking import BlockingScheduler from telegram_bot import Bot logging.basicConfig(format='%(asctime)s %(levelname)s ...
0.483405
0.095223
from . import Region from index import db, es from application.models import Area, CensusReport from ..utils.converter import to_dict_from_model from application.utils.esquery import EsqueryHelper from application.utils.type import CENSUS_REPORT_TYPE_MSA import json class MsaRegion(Region): area = None def __...
application/region/msa.py
from . import Region from index import db, es from application.models import Area, CensusReport from ..utils.converter import to_dict_from_model from application.utils.esquery import EsqueryHelper from application.utils.type import CENSUS_REPORT_TYPE_MSA import json class MsaRegion(Region): area = None def __...
0.372277
0.220794
import math import os import unittest from collections import OrderedDict import ROOT from PyAnalysisTools.PlottingUtils.PlotConfig import PlotConfig import PyAnalysisTools.PlottingUtils.PlotConfig as pcm from PyAnalysisTools.base import InvalidInputError from PyAnalysisTools.base.ProcessConfig import ProcessConfig fr...
tests/unit/TestPlotConfig.py
import math import os import unittest from collections import OrderedDict import ROOT from PyAnalysisTools.PlottingUtils.PlotConfig import PlotConfig import PyAnalysisTools.PlottingUtils.PlotConfig as pcm from PyAnalysisTools.base import InvalidInputError from PyAnalysisTools.base.ProcessConfig import ProcessConfig fr...
0.58439
0.431285
import numpy as np from scipy import ndimage from sHAM import nu_CWS import gc def find_index_first_dense(list_weights): i = 0 for w in list_weights: if len(w.shape)==2: return i i += 1 def idx_matrix_to_matrix(idx_matrix,centers): return centers[idx_matrix.reshape(-1,1)].re...
sHAM_package/sHAM/nu_PWS.py
import numpy as np from scipy import ndimage from sHAM import nu_CWS import gc def find_index_first_dense(list_weights): i = 0 for w in list_weights: if len(w.shape)==2: return i i += 1 def idx_matrix_to_matrix(idx_matrix,centers): return centers[idx_matrix.reshape(-1,1)].re...
0.276593
0.361925
from __future__ import division, print_function __author__ = "<NAME> <<EMAIL>>" # Standard library import os import logging import operator from itertools import groupby # Third-party import numpy as np from scipy import polyval, polyfit, optimize, integrate, c_ from scipy.special import wofz __all__ = [ 'gaus...
tellurics/ews.py
from __future__ import division, print_function __author__ = "<NAME> <<EMAIL>>" # Standard library import os import logging import operator from itertools import groupby # Third-party import numpy as np from scipy import polyval, polyfit, optimize, integrate, c_ from scipy.special import wofz __all__ = [ 'gaus...
0.87576
0.484502
from pathlib import Path import json from .utils import write_jsonfile, check_accessmode class MetaData: """Dictionary-like access to disk based metadata. If there is no metadata, the metadata file does not exist, rather than being empty. This saves a block of disk space (potentially 4kb). """ ...
darr/metadata.py
from pathlib import Path import json from .utils import write_jsonfile, check_accessmode class MetaData: """Dictionary-like access to disk based metadata. If there is no metadata, the metadata file does not exist, rather than being empty. This saves a block of disk space (potentially 4kb). """ ...
0.797123
0.215598
import logging from textwrap import dedent from mccole.accounting import Info from mccole.include import inclusion_to_html def test_include_text_with_badly_formatted_spec(caplog): info = Info(src="./page.md") spec = ' whatever="a.txt" ' with caplog.at_level(logging.WARNING): html = inclusion_to...
tests/test_include.py
import logging from textwrap import dedent from mccole.accounting import Info from mccole.include import inclusion_to_html def test_include_text_with_badly_formatted_spec(caplog): info = Info(src="./page.md") spec = ' whatever="a.txt" ' with caplog.at_level(logging.WARNING): html = inclusion_to...
0.443118
0.349033
import os from pyteomics import mzid, mzml import pandas as pd import numpy as np import glob """ Identically as how we did with the training data set, we randomly divided the test files into different folders, then we generated different data frames and stored all of them in one single hdf file as our validation daat...
Deep learning/merge_validation_set.py
import os from pyteomics import mzid, mzml import pandas as pd import numpy as np import glob """ Identically as how we did with the training data set, we randomly divided the test files into different folders, then we generated different data frames and stored all of them in one single hdf file as our validation daat...
0.156749
0.247919
from functools import partial from scipy import stats from nnweaver import * from nnweaver.validation import * def test_split_generator(): x = y = np.arange(0, 10, 1) result = list(splits_generator(x, y, [4, 6])) np.testing.assert_array_equal(result[1][0], [4, 5, 6, 7, 8, 9]) np.testing.assert_array...
test/validation_test.py
from functools import partial from scipy import stats from nnweaver import * from nnweaver.validation import * def test_split_generator(): x = y = np.arange(0, 10, 1) result = list(splits_generator(x, y, [4, 6])) np.testing.assert_array_equal(result[1][0], [4, 5, 6, 7, 8, 9]) np.testing.assert_array...
0.84338
0.64653
import codecs import orcid_api from lxml import objectify import pprint import os.path import time from config import DATAPATH token='' def getToken(): global token if token=='': token = orcid_api.get_access_token(scope='/read-public', sandbox=False) return token def search_to_file(...
orcid-usage/search.py
import codecs import orcid_api from lxml import objectify import pprint import os.path import time from config import DATAPATH token='' def getToken(): global token if token=='': token = orcid_api.get_access_token(scope='/read-public', sandbox=False) return token def search_to_file(...
0.084733
0.053157
import re import sys import logging import jnpr.junos # create logger for this script LOGGER = logging.getLogger('netsvc.py') LOGGER.setLevel(logging.DEBUG) CH = logging.StreamHandler() CH.setLevel(logging.DEBUG) FORMATTER = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', ...
juniper_official/Chassis/netsvc.py
import re import sys import logging import jnpr.junos # create logger for this script LOGGER = logging.getLogger('netsvc.py') LOGGER.setLevel(logging.DEBUG) CH = logging.StreamHandler() CH.setLevel(logging.DEBUG) FORMATTER = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', ...
0.384565
0.083853
from runners.helpers import log from runners.helpers import db from runners.helpers.dbconfig import ROLE as SA_ROLE from datetime import datetime import requests from urllib.error import HTTPError from .utils import yaml_dump PAGE_SIZE = 5 CONNECTION_OPTIONS = [ { 'name': 'api_token', 'title': ...
src/connectors/meraki_devices.py
from runners.helpers import log from runners.helpers import db from runners.helpers.dbconfig import ROLE as SA_ROLE from datetime import datetime import requests from urllib.error import HTTPError from .utils import yaml_dump PAGE_SIZE = 5 CONNECTION_OPTIONS = [ { 'name': 'api_token', 'title': ...
0.314682
0.088505
# Copyright (c) 2013 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, ...
lldb_quick_look.py
# Copyright (c) 2013 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, ...
0.588061
0.223007
import sys as _sys from apodeixi.controllers.util.skeleton_controller import SkeletonController from apodeixi.knowledge_base.tests_integration.post_update_skeleton import Post_and_Update_Skeleton class Test_BasicPostingFlows(Post_an...
src/apodeixi/knowledge_base/tests_integration/test_basic_posting_flows.py
import sys as _sys from apodeixi.controllers.util.skeleton_controller import SkeletonController from apodeixi.knowledge_base.tests_integration.post_update_skeleton import Post_and_Update_Skeleton class Test_BasicPostingFlows(Post_an...
0.180395
0.17113
# $Id: Wb6Status.py 2934 2008-11-13 11:01:52Z graham.klyne $ """ Module to handle and decode WebBrick status queries """ import xml.dom import xml.dom.minidom import WebBrickLibs.WbDefs as WbDefs from WebBrickLibs.WbAccess import GetHTTPData from MiscLib.DomHelpers import * from MiscLib.Logging import Trace, ...
WebBrickLibs/WebBrickLibs/Wb6Status.py
# $Id: Wb6Status.py 2934 2008-11-13 11:01:52Z graham.klyne $ """ Module to handle and decode WebBrick status queries """ import xml.dom import xml.dom.minidom import WebBrickLibs.WbDefs as WbDefs from WebBrickLibs.WbAccess import GetHTTPData from MiscLib.DomHelpers import * from MiscLib.Logging import Trace, ...
0.482429
0.268456
from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import cint, cstr from frappe.model.document import Document import json class CustomerVisit(Document): def onload(self): for d in frappe.db.get_values( "Customer", self.customer, ...
salesman_visit_tracker/salesman_visit_tracker/doctype/customer_visit/customer_visit.py
from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import cint, cstr from frappe.model.document import Document import json class CustomerVisit(Document): def onload(self): for d in frappe.db.get_values( "Customer", self.customer, ...
0.581897
0.17515
import matplotlib.pyplot as plt import numpy as np from scipy import ndimage as ndi import cv2 import os from skimage import data from skimage.util import img_as_float from skimage.filters import gabor_kernel import utility_functions from sklearn.metrics import accuracy_score, confusion_matrix, auc, roc_curve image_na...
Solution3/Code/GaborFilterDistClassifier.py
import matplotlib.pyplot as plt import numpy as np from scipy import ndimage as ndi import cv2 import os from skimage import data from skimage.util import img_as_float from skimage.filters import gabor_kernel import utility_functions from sklearn.metrics import accuracy_score, confusion_matrix, auc, roc_curve image_na...
0.210279
0.360799
from os import system, name from time import sleep from datetime import date from datetime import datetime import numpy as np import pandas as pd custCatalog = [] custMultiplier = [] custTotal = 0 custCash = 0 def clear(): if name == 'nt': _ = system('cls') def inputCustomerCatalog(): openCata...
program.py
from os import system, name from time import sleep from datetime import date from datetime import datetime import numpy as np import pandas as pd custCatalog = [] custMultiplier = [] custTotal = 0 custCash = 0 def clear(): if name == 'nt': _ = system('cls') def inputCustomerCatalog(): openCata...
0.096919
0.064979
from datetime import datetime from django.db import migrations, models import django.utils.timezone def merge_article_date_and_time(apps, schema_editor): Article = apps.get_model("news", "Article") for article in Article.objects.all(): article.publication_time = datetime.combine(article.pub_date, art...
news/migrations/0017_use_datetime_instead_of_date_and_time.py
from datetime import datetime from django.db import migrations, models import django.utils.timezone def merge_article_date_and_time(apps, schema_editor): Article = apps.get_model("news", "Article") for article in Article.objects.all(): article.publication_time = datetime.combine(article.pub_date, art...
0.463201
0.162413
import os os.environ['GLOG_minloglevel'] = '2' # Supressing caffe printouts of network initialisation import caffe import numpy as np top_dir, tail = os.path.split(os.path.dirname(os.path.realpath(__file__))) # Global dictionary containing class number : name pairs CLASS_LIST = {0: "brick", 1: "car...
material_segmentation/minc_classify.py
import os os.environ['GLOG_minloglevel'] = '2' # Supressing caffe printouts of network initialisation import caffe import numpy as np top_dir, tail = os.path.split(os.path.dirname(os.path.realpath(__file__))) # Global dictionary containing class number : name pairs CLASS_LIST = {0: "brick", 1: "car...
0.53777
0.267641
import argparse from dataclasses import dataclass import logging import os import signal import sys import time from typing import Dict from rdr_service.services.daemon import Daemon from rdr_service.services.gcp_config import RdrEnvironment from rdr_service.services.gcp_utils import build_gcp_instance_connection_name...
rdr_service/services/gcp_db_daemon.py
import argparse from dataclasses import dataclass import logging import os import signal import sys import time from typing import Dict from rdr_service.services.daemon import Daemon from rdr_service.services.gcp_config import RdrEnvironment from rdr_service.services.gcp_utils import build_gcp_instance_connection_name...
0.474388
0.106412
import numpy as np import sys from scipy.sparse import csr_matrix from scipy.sparse.csgraph import shortest_path import seaborn as sns import matplotlib.pyplot as plt sys.path.append("..") import pyroc import data def main(): np.random.seed(17) genes = data.mouse_common_genes() go_sets = data.load_g...
03_coexp_ppi/01_make_go_curves.py
import numpy as np import sys from scipy.sparse import csr_matrix from scipy.sparse.csgraph import shortest_path import seaborn as sns import matplotlib.pyplot as plt sys.path.append("..") import pyroc import data def main(): np.random.seed(17) genes = data.mouse_common_genes() go_sets = data.load_g...
0.364778
0.394551
from enum import Enum from django.db import models from bot.authorities import UserAuthority # Create your models here. class TaskImportance(Enum): '''タスクの重要度''' High = "高" Middle = "中" Low = "低" def get_choices_from_enum(source_enum): '''列挙体から選択肢を取得''' return [(item.name, item.name) for ...
bot/models.py
from enum import Enum from django.db import models from bot.authorities import UserAuthority # Create your models here. class TaskImportance(Enum): '''タスクの重要度''' High = "高" Middle = "中" Low = "低" def get_choices_from_enum(source_enum): '''列挙体から選択肢を取得''' return [(item.name, item.name) for ...
0.388386
0.309428
import pytest from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By @pytest.fixture(scope="session") def driver(request): options = webdriver.ChromeOptions() options...
task_9/task_9_1.py
import pytest from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By @pytest.fixture(scope="session") def driver(request): options = webdriver.ChromeOptions() options...
0.31321
0.131285
"""Celery tasks for geonode.services""" import time import logging from hashlib import md5 from django.template.defaultfilters import slugify from . import models from . import enumerations from .serviceprocessors import base, get_service_handler from geonode.celery_app import app from geonode.layers.models import L...
geonode/geonode/services/tasks.py
"""Celery tasks for geonode.services""" import time import logging from hashlib import md5 from django.template.defaultfilters import slugify from . import models from . import enumerations from .serviceprocessors import base, get_service_handler from geonode.celery_app import app from geonode.layers.models import L...
0.26569
0.080141
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workflow', '0009_auto_20170307_0537'), ] operations = [ migrations.AlterModelOptions( name='contact', options={'ordering': (...
workflow/migrations/0010_auto_20170315_0944.py
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workflow', '0009_auto_20170307_0537'), ] operations = [ migrations.AlterModelOptions( name='contact', options={'ordering': (...
0.642096
0.185357
from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.shortcuts import render_to_response from django.template import RequestContext from forms import TopicForm, PostForm from models import Topic, Post from tagging.mode...
forum/views.py
from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.shortcuts import render_to_response from django.template import RequestContext from forms import TopicForm, PostForm from models import Topic, Post from tagging.mode...
0.397938
0.07579
import time from datetime import datetime from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.utils import timezone from api.applications.models import CountryOnApplication from api.audit_trail.models import Audit from api.audit_trail.enums import AuditType from api...
api/audit_trail/streams/service.py
import time from datetime import datetime from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.utils import timezone from api.applications.models import CountryOnApplication from api.audit_trail.models import Audit from api.audit_trail.enums import AuditType from api...
0.292797
0.209146
import pickle import sys from pathlib import Path import numpy as np import toml file_name = Path(sys.argv[1]) uncert_cut = float(sys.argv[2]) snemo_version = int(sys.argv[3]) mass_index = snemo_version + 1 file_directory = Path.cwd()/file_name.parent data = pickle.load(open(file_name, 'rb')) print(data['n_sne'])...
rdr2019/cut_JLA.py
import pickle import sys from pathlib import Path import numpy as np import toml file_name = Path(sys.argv[1]) uncert_cut = float(sys.argv[2]) snemo_version = int(sys.argv[3]) mass_index = snemo_version + 1 file_directory = Path.cwd()/file_name.parent data = pickle.load(open(file_name, 'rb')) print(data['n_sne'])...
0.106284
0.209712
import unittest from binaryaudit import util class UtilTestSuite(unittest.TestCase): def test_no_sn(self): sn = "" fn = "/some/path/to/myexe" adir = "/hello/buildhistory/packages/cortexa57-poky-linux/somepkg/binaryaudit/abixml" expected = "/hello/buildhistory/packages/cort...
tests/test_util.py
import unittest from binaryaudit import util class UtilTestSuite(unittest.TestCase): def test_no_sn(self): sn = "" fn = "/some/path/to/myexe" adir = "/hello/buildhistory/packages/cortexa57-poky-linux/somepkg/binaryaudit/abixml" expected = "/hello/buildhistory/packages/cort...
0.312895
0.216291
import sys from typing import Optional from xml.etree import ElementTree import click import yaml from r2k.cli import cli_utils, logger from r2k.config import config from r2k.unicode import strip_common_unicode_chars @click.command("import") @cli_utils.config_path_option() @click.argument("opml-path", required=True...
r2k/cli/feed/feed_import.py
import sys from typing import Optional from xml.etree import ElementTree import click import yaml from r2k.cli import cli_utils, logger from r2k.config import config from r2k.unicode import strip_common_unicode_chars @click.command("import") @cli_utils.config_path_option() @click.argument("opml-path", required=True...
0.571408
0.176423
from enum import Enum from typing import Callable from typing import Dict from typing import List from typing import Tuple from adventofcode_2020.utils import Coordinate class Bearing(Enum): NORTH: int = 0 WEST: int = 1 SOUTH: int = 2 EAST: int = 3 class Action(Enum): NORTH: str = "N" SOUTH...
src/adventofcode_2020/day_12.py
from enum import Enum from typing import Callable from typing import Dict from typing import List from typing import Tuple from adventofcode_2020.utils import Coordinate class Bearing(Enum): NORTH: int = 0 WEST: int = 1 SOUTH: int = 2 EAST: int = 3 class Action(Enum): NORTH: str = "N" SOUTH...
0.885179
0.552178
import numpy as np from self_supervised.env_wrapper.pixel_wrapper import PixelNormalizedBoxEnvWrapper def pixel_rollout( env: PixelNormalizedBoxEnvWrapper, agent, max_path_length=np.inf, render=False, render_kwargs=None, ): """ The following value for the following keys...
diayn_seq_code_revised/data_collector/pixel_rollout.py
import numpy as np from self_supervised.env_wrapper.pixel_wrapper import PixelNormalizedBoxEnvWrapper def pixel_rollout( env: PixelNormalizedBoxEnvWrapper, agent, max_path_length=np.inf, render=False, render_kwargs=None, ): """ The following value for the following keys...
0.579162
0.323995
import numpy as np class FeaturesExtractor: def __init__(self): self.__n_features = None def features(self, patterns): pass def n_features(self): return self.__n_features def _set_n_features(self, n): self.__n_features = n class AllPeaksExtractor(FeaturesExtractor...
canon/pattern/feature_extractor.py
import numpy as np class FeaturesExtractor: def __init__(self): self.__n_features = None def features(self, patterns): pass def n_features(self): return self.__n_features def _set_n_features(self, n): self.__n_features = n class AllPeaksExtractor(FeaturesExtractor...
0.797911
0.392046
from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse, reverse_lazy fro...
expenses/views/expense.py
from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse, reverse_lazy fro...
0.446012
0.117927
name = 'pokemon' DATA = '''\ # names Bulbasaur Ivysaur Venusaur Charmander Charmeleon Charizard Squirtle Wartortle Blastoise Caterpie Metapod Butterfree Weedle Kakuna Beedrill Pidgey Pidgeotto Pidgeot Rattata Raticate Spearow Fearow Ekans Arbok Pikachu Raichu Sandshrew Sandslash Nidoran_female Nidorina Nidoqueen Nidora...
metasyntactic/themes/pokemon.py
name = 'pokemon' DATA = '''\ # names Bulbasaur Ivysaur Venusaur Charmander Charmeleon Charizard Squirtle Wartortle Blastoise Caterpie Metapod Butterfree Weedle Kakuna Beedrill Pidgey Pidgeotto Pidgeot Rattata Raticate Spearow Fearow Ekans Arbok Pikachu Raichu Sandshrew Sandslash Nidoran_female Nidorina Nidoqueen Nidora...
0.235372
0.140749
import tensorflow as tf """ 随机数生成函数 """ random_normal = tf.random_normal """ 正态分布是具有两个参数μ和σ2的连续型随机变量的分布,第一参数μ是遵从正态分布的随机变量的均值,第二个参数σ2是此随机变量的方差,所以正态分布记作N(μ,σ2 )。 遵从正态分布的随机变量的概率规律为取μ邻近的值的概率大,而取离μ越远的值的概率越小;σ越小,分布越集中在μ附近,σ越大,分布越分散。 从正态分布中输出随机值。 参数: shape: 一维的张量,也是输出的张量。 mean: 正态分布的均值。 stddev: 正态分布的标准差。 dty...
PYSTUDY/ml/tensorflowlib.py
import tensorflow as tf """ 随机数生成函数 """ random_normal = tf.random_normal """ 正态分布是具有两个参数μ和σ2的连续型随机变量的分布,第一参数μ是遵从正态分布的随机变量的均值,第二个参数σ2是此随机变量的方差,所以正态分布记作N(μ,σ2 )。 遵从正态分布的随机变量的概率规律为取μ邻近的值的概率大,而取离μ越远的值的概率越小;σ越小,分布越集中在μ附近,σ越大,分布越分散。 从正态分布中输出随机值。 参数: shape: 一维的张量,也是输出的张量。 mean: 正态分布的均值。 stddev: 正态分布的标准差。 dty...
0.272315
0.50891
import os import copy import datetime import warnings from matplotlib import pyplot as plt import matplotlib as mpl import seaborn as sns import pandas as pd import numpy as np import math from datetime import datetime import random from sklearn.feature_extraction.text import TfidfVectorizer, CountVec...
code/nn_model/act_use_all_mlp.py
import os import copy import datetime import warnings from matplotlib import pyplot as plt import matplotlib as mpl import seaborn as sns import pandas as pd import numpy as np import math from datetime import datetime import random from sklearn.feature_extraction.text import TfidfVectorizer, CountVec...
0.474144
0.137417
import os import sys import numpy as np import scipy.io import wfdb from data import Subject def __load_file(file_path: str, file_name: str) -> []: """ Args: file_path: E.g path to the folder on the server file_name: Name of the file Returns: Array with raw time series data. Descri...
src/data/physionet_challenge/load_data_physionet.py
import os import sys import numpy as np import scipy.io import wfdb from data import Subject def __load_file(file_path: str, file_name: str) -> []: """ Args: file_path: E.g path to the folder on the server file_name: Name of the file Returns: Array with raw time series data. Descri...
0.585338
0.515437
from typing import Type, List, Tuple, Dict, Any import pytest from pydantic import BaseModel, ValidationError from ensysmod.model import EnergyComponentType from ensysmod.schemas.energy_storage import EnergyStorageCreate, EnergyStorageUpdate schemas_with_discharge_rate_required: List[Tuple[Type[BaseModel], Dict[str,...
tests/validators/test_discharge_rate_validator.py
from typing import Type, List, Tuple, Dict, Any import pytest from pydantic import BaseModel, ValidationError from ensysmod.model import EnergyComponentType from ensysmod.schemas.energy_storage import EnergyStorageCreate, EnergyStorageUpdate schemas_with_discharge_rate_required: List[Tuple[Type[BaseModel], Dict[str,...
0.916004
0.534855
from unittest import skip from mock import MagicMock, Mock from test import * from cosmos.rbac.service import * from cosmos.dataservice.objectservice import * class ObjectServiceTest(LoggedTestCase): def _get_admin_role(self): for role in WELL_KNOWN_ROLES: if role.sid == ADMIN_USER_ROLE_SID...
test/dataservice/test_objectservice.py
from unittest import skip from mock import MagicMock, Mock from test import * from cosmos.rbac.service import * from cosmos.dataservice.objectservice import * class ObjectServiceTest(LoggedTestCase): def _get_admin_role(self): for role in WELL_KNOWN_ROLES: if role.sid == ADMIN_USER_ROLE_SID...
0.61057
0.180413
import sys import time import os # Manipulation + Draw + CLI import numpy as np import pygame import pygame.gfxdraw import fire from tqdm import trange, tqdm # Dev from pprint import pprint as pp # Default colors COLOR_BLACK = (0, 0, 0) # Pygame Constants TIME_DELTA = 0.001 TIME_EVENT_ID = pygame.USEREVENT+1 WIDTH ...
prototypes/orbit/replay_simulation.py
import sys import time import os # Manipulation + Draw + CLI import numpy as np import pygame import pygame.gfxdraw import fire from tqdm import trange, tqdm # Dev from pprint import pprint as pp # Default colors COLOR_BLACK = (0, 0, 0) # Pygame Constants TIME_DELTA = 0.001 TIME_EVENT_ID = pygame.USEREVENT+1 WIDTH ...
0.464416
0.292943
import numpy as np from scipy.optimize import least_squares def xyfit(data, calibration_data): """Return the fit of the voltage data and its parameters. Args: data: An array containing the position of the sample, the amplitude of the voltage measured by the lock-in amplifier, ...
ac_susceptibility/xyfit.py
import numpy as np from scipy.optimize import least_squares def xyfit(data, calibration_data): """Return the fit of the voltage data and its parameters. Args: data: An array containing the position of the sample, the amplitude of the voltage measured by the lock-in amplifier, ...
0.933302
0.901097
"""TcEx Runtime App Test Case""" import os from six import string_types from .test_case import TestCase class TestCaseJob(TestCase): """App TestCase Class""" _output_variables = None redis_client = None @staticmethod def create_shelf_dir(shelf_path): """Create a directory in log with the...
tcex/testing/test_case_job.py
"""TcEx Runtime App Test Case""" import os from six import string_types from .test_case import TestCase class TestCaseJob(TestCase): """App TestCase Class""" _output_variables = None redis_client = None @staticmethod def create_shelf_dir(shelf_path): """Create a directory in log with the...
0.667256
0.212549
#Basic inetd server import sys,struct,socket,traceback,json,os,Md5,logging,time import Config import Logger __author__ = "<EMAIL>" CHECKDIR = 0x0004 CHECKFILE = 0x0003 config = Config.getInstance() BASEPATH = config.get('server', 'storagedir') LOGFILE = config.get('server', 'log') '''配置日志''' config = Config.getInsta...
broom/Broomd.py
#Basic inetd server import sys,struct,socket,traceback,json,os,Md5,logging,time import Config import Logger __author__ = "<EMAIL>" CHECKDIR = 0x0004 CHECKFILE = 0x0003 config = Config.getInstance() BASEPATH = config.get('server', 'storagedir') LOGFILE = config.get('server', 'log') '''配置日志''' config = Config.getInsta...
0.133458
0.065515
from pyfiglet import figlet_format import random fonts = ['1943____', '3-d', '3x5', '4x4_offr', '5lineoblique', '5x7', '5x8', '64f1____', '6x10', '6x9', 'acrobatic', 'advenger', 'alligator2', 'alligator', 'alphabet', 'aquaplan', 'arrows', 'asc_____', 'ascii___', 'assalt_m', 'asslt__m', 'atc_____', 'a...
asciiart.py
from pyfiglet import figlet_format import random fonts = ['1943____', '3-d', '3x5', '4x4_offr', '5lineoblique', '5x7', '5x8', '64f1____', '6x10', '6x9', 'acrobatic', 'advenger', 'alligator2', 'alligator', 'alphabet', 'aquaplan', 'arrows', 'asc_____', 'ascii___', 'assalt_m', 'asslt__m', 'atc_____', 'a...
0.318379
0.287193
import numpy as np import torch from torch_utils import training_stats from torch_utils import misc import torch.distributed as dist from torch_utils.ops import conv2d_gradfix from einops import rearrange import torch.nn as nn import torch.nn.functional as F def DiffAugment(x, policy='color,translation,cutout', ch...
src/training/diffaugment.py
import numpy as np import torch from torch_utils import training_stats from torch_utils import misc import torch.distributed as dist from torch_utils.ops import conv2d_gradfix from einops import rearrange import torch.nn as nn import torch.nn.functional as F def DiffAugment(x, policy='color,translation,cutout', ch...
0.643777
0.662196
import base64 from datetime import datetime from datetime import timedelta import json import re from common import diff from common.blame import Blame from common.blame import Region from common.cache_decorator import Cached from common.change_log import ChangeLog from common.change_log import FileChangeInfo from co...
appengine/findit/common/git_repository.py
import base64 from datetime import datetime from datetime import timedelta import json import re from common import diff from common.blame import Blame from common.blame import Region from common.cache_decorator import Cached from common.change_log import ChangeLog from common.change_log import FileChangeInfo from co...
0.58522
0.147863
__author__ = 'huangjin' import tornado.ioloop import tornado.gen import greenlet import sys class Watcher(object): """ 这里传递过来的都是一些就绪的事件 watcher 用来替换 libev 中的 watcher 直接实例化一个 Watcher(fd, event) 对象,可以替换 greenify.pyx.wait_gevent 中的 hub.loop.io(fd, event) """ def __init__(self, fd, event): ...
tornado_adapter.py
__author__ = 'huangjin' import tornado.ioloop import tornado.gen import greenlet import sys class Watcher(object): """ 这里传递过来的都是一些就绪的事件 watcher 用来替换 libev 中的 watcher 直接实例化一个 Watcher(fd, event) 对象,可以替换 greenify.pyx.wait_gevent 中的 hub.loop.io(fd, event) """ def __init__(self, fd, event): ...
0.331228
0.182225
from __future__ import print_function import gcode_cmd import cnc_path import cnc_routine class SurfaceBase(cnc_routine.SafeZRoutine): """ Base class for surfacing routines. """ def __init__(self,param): super(SurfaceRaster,self).__init__(param) class SurfaceRasterXY(SurfaceBase): """ ...
py2gcode/cnc_surface.py
from __future__ import print_function import gcode_cmd import cnc_path import cnc_routine class SurfaceBase(cnc_routine.SafeZRoutine): """ Base class for surfacing routines. """ def __init__(self,param): super(SurfaceRaster,self).__init__(param) class SurfaceRasterXY(SurfaceBase): """ ...
0.787032
0.377655
__author__ = "<NAME>" import sys, urllib, scipy, pylab import numpy as np from urllib.request import urlopen import matplotlib.pyplot as plot from itertools import groupby from collections import OrderedDict #Çok ilginç bir şekilde bunu yazmayınca "label types" listesini [R,M] yerine [M,R] şeklinde veriyor!!! ...
Extracting Data and A Little Statistic of the Data.py
__author__ = "<NAME>" import sys, urllib, scipy, pylab import numpy as np from urllib.request import urlopen import matplotlib.pyplot as plot from itertools import groupby from collections import OrderedDict #Çok ilginç bir şekilde bunu yazmayınca "label types" listesini [R,M] yerine [M,R] şeklinde veriyor!!! ...
0.231527
0.228565
import utils import functions as func from commands.base import Cmd help_text = [ [ ("Usage:", "<PREFIX><COMMAND> `N`"), ("Description:", "Set the default user limit for channels created by a particular primary channel, " "without editing the primary channel itself.\n\n" ...
commands/defaultlimit.py
import utils import functions as func from commands.base import Cmd help_text = [ [ ("Usage:", "<PREFIX><COMMAND> `N`"), ("Description:", "Set the default user limit for channels created by a particular primary channel, " "without editing the primary channel itself.\n\n" ...
0.46563
0.138928
import datetime import falcon from falcon import testing import pytest from aa.app import create_application from aa.unit.info import * @pytest.fixture() def client(): return testing.TestClient(create_application()) def test_get_a_land_battle_template(client): result = client.simulate_get('/land-battle') ...
aa/test_web_api.py
import datetime import falcon from falcon import testing import pytest from aa.app import create_application from aa.unit.info import * @pytest.fixture() def client(): return testing.TestClient(create_application()) def test_get_a_land_battle_template(client): result = client.simulate_get('/land-battle') ...
0.560854
0.551453
import json import warnings import pulumi import pulumi.runtime from typing import Union from . import utilities, tables class LookupProjectsResult: """ A collection of values returned by lookupProjects. """ def __init__(__self__, is_finance=None, name_regex=None, output_file=None, projects=None, tota...
sdk/python/pulumi_ucloud/lookup_projects.py
import json import warnings import pulumi import pulumi.runtime from typing import Union from . import utilities, tables class LookupProjectsResult: """ A collection of values returned by lookupProjects. """ def __init__(__self__, is_finance=None, name_regex=None, output_file=None, projects=None, tota...
0.749454
0.06663
import os import random import torch import numpy as np from faker import Faker from loguru import logger from transformers import GPT2LMHeadModel, GPT2Tokenizer MODEL_NAME = os.environ.get('MODEL_NAME', 'gpt2') if MODEL_NAME.lower() == 'gpt2': logger.debug('***** Running basic GPT2 pretrained weights *****') ...
api/text_model.py
import os import random import torch import numpy as np from faker import Faker from loguru import logger from transformers import GPT2LMHeadModel, GPT2Tokenizer MODEL_NAME = os.environ.get('MODEL_NAME', 'gpt2') if MODEL_NAME.lower() == 'gpt2': logger.debug('***** Running basic GPT2 pretrained weights *****') ...
0.270673
0.125547
import random import pytest from datetime import datetime, timedelta, timezone from laceworksdk.api.vulnerability import VulnerabilityAPI # Build start/end times current_time = datetime.now(timezone.utc) start_time = current_time - timedelta(days=6) start_time = start_time.strftime("%Y-%m-%dT%H:%M:%SZ") end_time =...
tests/api/v1/test_vulnerability.py
import random import pytest from datetime import datetime, timedelta, timezone from laceworksdk.api.vulnerability import VulnerabilityAPI # Build start/end times current_time = datetime.now(timezone.utc) start_time = current_time - timedelta(days=6) start_time = start_time.strftime("%Y-%m-%dT%H:%M:%SZ") end_time =...
0.417984
0.162513
from utils import get_key, get_quote, clean_db from keepAlive import keep_alive from replit import db import datetime import os import discord from dotenv import load_dotenv load_dotenv() client = discord.Client() add_words = ['lose', 'victory'] def add_value(value): key = get_key() if key in db.keys(): ...
bot/main.py
from utils import get_key, get_quote, clean_db from keepAlive import keep_alive from replit import db import datetime import os import discord from dotenv import load_dotenv load_dotenv() client = discord.Client() add_words = ['lose', 'victory'] def add_value(value): key = get_key() if key in db.keys(): ...
0.168515
0.100613
import rospy import socket import select from time import sleep from sensor_msgs.msg import Joy stembotConn = None def joyCB(event): surge = event.axes[4] turn = event.axes[3] heave = event.axes[1] if abs(turn) < .05: turn = 0 if abs(surge) < .05: surge = 0 if abs(heave) < ...
src/stembot/scripts/stembot_driver.py
import rospy import socket import select from time import sleep from sensor_msgs.msg import Joy stembotConn = None def joyCB(event): surge = event.axes[4] turn = event.axes[3] heave = event.axes[1] if abs(turn) < .05: turn = 0 if abs(surge) < .05: surge = 0 if abs(heave) < ...
0.142918
0.156943
import subprocess import urllib2 import json import os.path import sys def req_url(q, start_index=1, max_results=50, order_by='published', duration=None, v=2, alt='jsonc'): url = "https://gdata.youtube.com/feeds/api/videos?q=%s" % q if start_index: url += "&start-index=%i" % start_index ...
death_extractor/youtube.py
import subprocess import urllib2 import json import os.path import sys def req_url(q, start_index=1, max_results=50, order_by='published', duration=None, v=2, alt='jsonc'): url = "https://gdata.youtube.com/feeds/api/videos?q=%s" % q if start_index: url += "&start-index=%i" % start_index ...
0.152001
0.088033