code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import logging import re from typing import Any, AsyncIterator, List, Optional, Text, Tuple import faker from faker import Faker from rasa.shared.importers.rasa import RasaFileImporter from rasa.shared.nlu.training_data import loading from rasa.shared.nlu.training_data.entities_parser import find_entities_in_training_...
rasam/importers/placeholder.py
import logging import re from typing import Any, AsyncIterator, List, Optional, Text, Tuple import faker from faker import Faker from rasa.shared.importers.rasa import RasaFileImporter from rasa.shared.nlu.training_data import loading from rasa.shared.nlu.training_data.entities_parser import find_entities_in_training_...
0.830697
0.526525
from __future__ import absolute_import from .bridge_sampler import (bridge_sampler, bridge_sampler_relative_mse_estimate) from .sampler_diagnostics import (estimate_convergence_rate, estimate_stationary_distribution, rjm...
src/reanalysis_dbns/models/__init__.py
from __future__ import absolute_import from .bridge_sampler import (bridge_sampler, bridge_sampler_relative_mse_estimate) from .sampler_diagnostics import (estimate_convergence_rate, estimate_stationary_distribution, rjm...
0.847495
0.156685
from django import forms from django.utils.translation import gettext as _ class ProfileForm(forms.Form): email = forms.EmailField(label=_("Email address"), max_length=150) first_name = forms.CharField(label=_("First name"), max_length=150, required=False) last_name = forms.CharField(label=_("Last name"),...
app/core/forms.py
from django import forms from django.utils.translation import gettext as _ class ProfileForm(forms.Form): email = forms.EmailField(label=_("Email address"), max_length=150) first_name = forms.CharField(label=_("First name"), max_length=150, required=False) last_name = forms.CharField(label=_("Last name"),...
0.439988
0.084947
import itertools import inspect from util.commands.formatter import HelpFormatter, Paginator from util.commands.core import Command class RichFormatter(HelpFormatter): def _add_subcommands_to_page(self, max_width, commands): for name, command in commands: if name in command.aliases: ...
util/proformatter.py
import itertools import inspect from util.commands.formatter import HelpFormatter, Paginator from util.commands.core import Command class RichFormatter(HelpFormatter): def _add_subcommands_to_page(self, max_width, commands): for name, command in commands: if name in command.aliases: ...
0.660829
0.227942
import numpy as np import pandas as pd import astropy.stats as aps import astropy.coordinates as coord import astropy.units as u from astropy.coordinates.builtin_frames.galactocentric \ import get_matrix_vectors import warnings from astropy.utils.exceptions import AstropyWarning warnings.simplefilter('ignore', cat...
aviary/inference.py
import numpy as np import pandas as pd import astropy.stats as aps import astropy.coordinates as coord import astropy.units as u from astropy.coordinates.builtin_frames.galactocentric \ import get_matrix_vectors import warnings from astropy.utils.exceptions import AstropyWarning warnings.simplefilter('ignore', cat...
0.909766
0.580114
# Copyright (c) 2013, <NAME> # All rights reserved. # Complete license can be found in the LICENSE file. from mvc import Controller from pyxrd.generic.controllers import BaseController from pyxrd.probabilities.views import get_correct_probability_views from pyxrd.probabilities.models import RGbounds def get_correc...
pyxrd/probabilities/controllers.py
# Copyright (c) 2013, <NAME> # All rights reserved. # Complete license can be found in the LICENSE file. from mvc import Controller from pyxrd.generic.controllers import BaseController from pyxrd.probabilities.views import get_correct_probability_views from pyxrd.probabilities.models import RGbounds def get_correc...
0.78785
0.180883
import logging from functools import partial from typing import List import hoomd import hoomd.md as md from .params import SimulationParams logger = logging.getLogger(__name__) def set_integrator(sim_params: SimulationParams, prime_interval: int=33533, crystal: bool=False, ...
statdyn/simulation/helper.py
import logging from functools import partial from typing import List import hoomd import hoomd.md as md from .params import SimulationParams logger = logging.getLogger(__name__) def set_integrator(sim_params: SimulationParams, prime_interval: int=33533, crystal: bool=False, ...
0.760384
0.276182
# Script pro generaci playlistu z OTA služby O2TV # *********************************************** # Script je odvozen z Kodi addon service.playlist.o2tv, # který byl vytvořen z původního addon autora <NAME>. import os import time import urllib3 import common as c import config as cfg from o2tvgo import Authenti...
playlist.py
# Script pro generaci playlistu z OTA služby O2TV # *********************************************** # Script je odvozen z Kodi addon service.playlist.o2tv, # který byl vytvořen z původního addon autora <NAME>. import os import time import urllib3 import common as c import config as cfg from o2tvgo import Authenti...
0.236164
0.114121
import argparse import sys import os import cv2 import numpy as np from src import lib parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', help="Input image path", required=True) parser.add_argument('-o', '--outdir', help="Output directory", required=True) parser.add_argument( '-m', '--model'...
src/tools/predict.py
import argparse import sys import os import cv2 import numpy as np from src import lib parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', help="Input image path", required=True) parser.add_argument('-o', '--outdir', help="Output directory", required=True) parser.add_argument( '-m', '--model'...
0.306423
0.098686
import pygame from pygame.locals import * import time import random size = 40 class Apple: def __init__(self, parent_screen): # loading the apple image self.parent_screen = parent_screen self.apple = pygame.image.load("resources/apple.jpg").convert() self.x = size*4 self.y ...
snake_game/main.py
import pygame from pygame.locals import * import time import random size = 40 class Apple: def __init__(self, parent_screen): # loading the apple image self.parent_screen = parent_screen self.apple = pygame.image.load("resources/apple.jpg").convert() self.x = size*4 self.y ...
0.401923
0.290377
import config import common, importlib, out, os, time import traceback import pprint import restart as _restart modname = "admin" async def dump(self, chan, source, msg): """ dump the contents of self to a file for debugging purposes. """ if len(msg) < 1: await out.msg(self, modname, cha...
mod/admin.py
import config import common, importlib, out, os, time import traceback import pprint import restart as _restart modname = "admin" async def dump(self, chan, source, msg): """ dump the contents of self to a file for debugging purposes. """ if len(msg) < 1: await out.msg(self, modname, cha...
0.311636
0.107297
import logging import os from megalinter import Reporter, config, utils class TextReporter(Reporter): name = "TEXT" report_type = "detailed" scope = "linter" def __init__(self, params=None): # report_type is simple by default self.report_type = "simple" super().__init__(param...
megalinter/reporters/TextReporter.py
import logging import os from megalinter import Reporter, config, utils class TextReporter(Reporter): name = "TEXT" report_type = "detailed" scope = "linter" def __init__(self, params=None): # report_type is simple by default self.report_type = "simple" super().__init__(param...
0.143938
0.07373
__all__ = [ "build_train_batch", "build_valid_batch", "build_infer_batch", "train_dl", "valid_dl", "infer_dl", ] from icevision.imports import * from icevision.models.utils import * def train_dl(dataset, batch_tfms=None, **dataloader_kwargs) -> DataLoader: """A `DataLoader` with a custom ...
icevision/models/ross/efficientdet/dataloaders.py
__all__ = [ "build_train_batch", "build_valid_batch", "build_infer_batch", "train_dl", "valid_dl", "infer_dl", ] from icevision.imports import * from icevision.models.utils import * def train_dl(dataset, batch_tfms=None, **dataloader_kwargs) -> DataLoader: """A `DataLoader` with a custom ...
0.948052
0.828904
# # s_rand_ols_estim [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_rand_ols_estim&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ExFactBayesOLSEstim). # + import matplotl...
scripts/sources/s_rand_ols_estim.py
# # s_rand_ols_estim [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_rand_ols_estim&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ExFactBayesOLSEstim). # + import matplotl...
0.717012
0.794783
import numpy as np import tensorflow as tf import classifier.cnn.model as model import classifier.cnn.input as input import classifier.common.report as report EPOCH_COUNT = 1 BATCH_SIZE = 1 def main(argv): print("Building graph...") tf.reset_default_graph() dataset, _ = input.create_filename_dataset(a...
code/classifier/cnn/test.py
import numpy as np import tensorflow as tf import classifier.cnn.model as model import classifier.cnn.input as input import classifier.common.report as report EPOCH_COUNT = 1 BATCH_SIZE = 1 def main(argv): print("Building graph...") tf.reset_default_graph() dataset, _ = input.create_filename_dataset(a...
0.462473
0.2786
import sqlite3 import tkinter from tkinter import ttk class Database(object): def __init__(self, filename, table): self.connection = sqlite3.connect(filename) with self.connection: self.connection.row_factory = sqlite3.Row self.cursor = self.connection.cursor() ...
transmute_antipsychotics.py
import sqlite3 import tkinter from tkinter import ttk class Database(object): def __init__(self, filename, table): self.connection = sqlite3.connect(filename) with self.connection: self.connection.row_factory = sqlite3.Row self.cursor = self.connection.cursor() ...
0.24599
0.116261
def registerSpeedTreeIn(): """ Registers a new SpeedTreeIn node type using the NodeTypeBuilder utility class. """ from Katana import Nodes3DAPI from Katana import FnAttribute, FnGeolibServices def buildSpeedTreeInOpChain(node, interface): """ Defines the callback function u...
Procedurals/speedtreeKit/speedtreeOp/source/RegisterSpeedTreeInNode.py
def registerSpeedTreeIn(): """ Registers a new SpeedTreeIn node type using the NodeTypeBuilder utility class. """ from Katana import Nodes3DAPI from Katana import FnAttribute, FnGeolibServices def buildSpeedTreeInOpChain(node, interface): """ Defines the callback function u...
0.785597
0.469885
import logging from datetime import datetime import dateutil.relativedelta from django.core.exceptions import ObjectDoesNotExist from django.core.cache import cache from django.utils.timezone import utc from models import Device, Configuration, DeviceConfiguration, Sensor, SensorValue, SensorValueDaily logger = log...
server/functions.py
import logging from datetime import datetime import dateutil.relativedelta from django.core.exceptions import ObjectDoesNotExist from django.core.cache import cache from django.utils.timezone import utc from models import Device, Configuration, DeviceConfiguration, Sensor, SensorValue, SensorValueDaily logger = log...
0.369429
0.120051
from portality.lib import dataobj from portality import models from portality.api.v1.data_objects.common_journal_application import OutgoingCommonJournalApplication # we only have outgoing journals for the moment JOURNAL_STRUCT = { "objects": ["bibjson", "admin"], "fields": { "id": {"coerce": "unicode...
portality/api/v1/data_objects/journal.py
from portality.lib import dataobj from portality import models from portality.api.v1.data_objects.common_journal_application import OutgoingCommonJournalApplication # we only have outgoing journals for the moment JOURNAL_STRUCT = { "objects": ["bibjson", "admin"], "fields": { "id": {"coerce": "unicode...
0.651798
0.352759
import torch import torch.nn as nn import torch.utils.data as data from torchsummary import summary from dataset.datasets import ModelNet40 from model.TNet import input_transform_feature,feature_transform import torch.nn.functional as F device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') class PointN...
model/pointnet.py
import torch import torch.nn as nn import torch.utils.data as data from torchsummary import summary from dataset.datasets import ModelNet40 from model.TNet import input_transform_feature,feature_transform import torch.nn.functional as F device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') class PointN...
0.872075
0.560012
"""Конструкции для работы с API.""" from functools import partial from collections import namedtuple import re import inspect from yadic.container import Container as _Container from yadic.util import deep_merge as _deep_merge from pynch.util import load_configs as _load_configs from pynch import validators as _valid...
src/pynch/core.py
"""Конструкции для работы с API.""" from functools import partial from collections import namedtuple import re import inspect from yadic.container import Container as _Container from yadic.util import deep_merge as _deep_merge from pynch.util import load_configs as _load_configs from pynch import validators as _valid...
0.656328
0.232332
import requests import datetime class AzureCidrDownloader(): def get_timestamps(self): ''' Return a list of timestamps from the past 7 days, because Azure IP tables updates once every week. The thought is that within 7 days, at least one link will drop for all Azure tables. ''' format = '%Y%m%d...
src/dl/download_azure.py
import requests import datetime class AzureCidrDownloader(): def get_timestamps(self): ''' Return a list of timestamps from the past 7 days, because Azure IP tables updates once every week. The thought is that within 7 days, at least one link will drop for all Azure tables. ''' format = '%Y%m%d...
0.64512
0.252857
import typing import json import asyncio from collections import deque from starlette.websockets import WebSocket from .JsPyTextSocket import JsPyTextSocket, JsPyError from . import JsPyBackground __all__ = ['push_nowait', 'push', 'pop', 'shift', 'add_callback', 'clear_callback', 'is_empty', 'get_keys', ...
JsMeetsStarlette/JsPyQueue.py
import typing import json import asyncio from collections import deque from starlette.websockets import WebSocket from .JsPyTextSocket import JsPyTextSocket, JsPyError from . import JsPyBackground __all__ = ['push_nowait', 'push', 'pop', 'shift', 'add_callback', 'clear_callback', 'is_empty', 'get_keys', ...
0.61555
0.311676
import pandas as pd import numpy as np from io import BytesIO #, StringIO from zipfile import ZipFile from urllib.request import urlopen from database.base import Session, engine, Base class IpedsFile: __url_base = 'https://nces.ed.gov/ipeds/datacenter/data/' def __init__(self, year): self.year = year...
netfile/ipeds_file.py
import pandas as pd import numpy as np from io import BytesIO #, StringIO from zipfile import ZipFile from urllib.request import urlopen from database.base import Session, engine, Base class IpedsFile: __url_base = 'https://nces.ed.gov/ipeds/datacenter/data/' def __init__(self, year): self.year = year...
0.360939
0.113187
import pytest from nagare.renderers import html_base as html def test_html1(): h = html.Renderer() assert h.div(h.p('test')).tostring() == b'<div><p>test</p></div>' with pytest.raises(AttributeError): h.foo def test_head(): """ XHTML namespace unit test - HTMLRender - init - test if head ...
tests/test_html.py
import pytest from nagare.renderers import html_base as html def test_html1(): h = html.Renderer() assert h.div(h.p('test')).tostring() == b'<div><p>test</p></div>' with pytest.raises(AttributeError): h.foo def test_head(): """ XHTML namespace unit test - HTMLRender - init - test if head ...
0.603932
0.446072
import glm import camera import buffer import scene import ray import intersection_record as ir import sys import math import onb import material from random import random class PathTracer(object): """ PathTracer ( camera (Camera), scene (Scene), bg_color (vec3), buffer(Buffer) ) This is where the images will be r...
pathtracer.py
import glm import camera import buffer import scene import ray import intersection_record as ir import sys import math import onb import material from random import random class PathTracer(object): """ PathTracer ( camera (Camera), scene (Scene), bg_color (vec3), buffer(Buffer) ) This is where the images will be r...
0.343012
0.275812
import os import numpy as np import matplotlib.pyplot as plt from Algorithms.NSGA2.NSGAII_core import * iterations = 30 delay = 0.01 population_size = 10 generation_size = 10 save = False pause = 1 def new_point(): return np.random.random(), np.random.random() def prepare_plot(phase, pause): plt.pause(pau...
AnalysisTools/NSGAII_example.py
import os import numpy as np import matplotlib.pyplot as plt from Algorithms.NSGA2.NSGAII_core import * iterations = 30 delay = 0.01 population_size = 10 generation_size = 10 save = False pause = 1 def new_point(): return np.random.random(), np.random.random() def prepare_plot(phase, pause): plt.pause(pau...
0.269806
0.420838
from __future__ import division import os from os.path import abspath import sys import shutil sys.path.append(os.path.dirname(abspath(__file__))+'/../') import elution as el import utils as ut MSB_EXT = '.prot_count_uniqpeps_FDR0010' PQ_FILE = 'ISO_QUAN/quantification-protein-intensity.txt' PQ_OUTFILE = 'quantificati...
scripts/pepquant_post.py
from __future__ import division import os from os.path import abspath import sys import shutil sys.path.append(os.path.dirname(abspath(__file__))+'/../') import elution as el import utils as ut MSB_EXT = '.prot_count_uniqpeps_FDR0010' PQ_FILE = 'ISO_QUAN/quantification-protein-intensity.txt' PQ_OUTFILE = 'quantificati...
0.228329
0.18159
# TODO: module cleanup! maybe break it up in a package # dicts instead of if, elif,else all over the place. # helper functions instead of everything on the execute method. # str.format() + dicts instead of inline % op all over the place. # remove/manage debug print calls. # self.__class__.attr? use ...
bpy_lambda/2.78/scripts/addons_contrib/amaranth/scene/debug.py
# TODO: module cleanup! maybe break it up in a package # dicts instead of if, elif,else all over the place. # helper functions instead of everything on the execute method. # str.format() + dicts instead of inline % op all over the place. # remove/manage debug print calls. # self.__class__.attr? use ...
0.263979
0.271828
import numpy as np import tensorflow as tf from models.model import Model class FeatureModel(Model): """ Model to hold hand-crafted features """ pronouns_m = ["he", "him", "his"] pronouns_f = ["she", "her", "hers"] inverse_words = ["not", "n't"] def __init__(self, word_to_id, **kwargs):...
project-2/src/models/feature_model.py
import numpy as np import tensorflow as tf from models.model import Model class FeatureModel(Model): """ Model to hold hand-crafted features """ pronouns_m = ["he", "him", "his"] pronouns_f = ["she", "her", "hers"] inverse_words = ["not", "n't"] def __init__(self, word_to_id, **kwargs):...
0.79653
0.479869
import unittest import os from tgext.mailer._compat import ( text_type, StringIO, _qencode, ) from email.encoders import ( _bencode, ) class TestAttachment(unittest.TestCase): def _makeOne(self, **kw): from tgext.mailer.message import Attachment return Attachment(**kw) ...
tgext/mailer/tests/test_message.py
import unittest import os from tgext.mailer._compat import ( text_type, StringIO, _qencode, ) from email.encoders import ( _bencode, ) class TestAttachment(unittest.TestCase): def _makeOne(self, **kw): from tgext.mailer.message import Attachment return Attachment(**kw) ...
0.489259
0.304261
import sys sys.path.append("..") from fastNLP.loader.config_loader import ConfigLoader, ConfigSection from fastNLP.core.trainer import SeqLabelTrainer from fastNLP.loader.dataset_loader import TokenizeDatasetLoader, BaseLoader from fastNLP.core.preprocess import SeqLabelPreprocess, load_pickle from fastNLP.saver.mode...
test/test_cws.py
import sys sys.path.append("..") from fastNLP.loader.config_loader import ConfigLoader, ConfigSection from fastNLP.core.trainer import SeqLabelTrainer from fastNLP.loader.dataset_loader import TokenizeDatasetLoader, BaseLoader from fastNLP.core.preprocess import SeqLabelPreprocess, load_pickle from fastNLP.saver.mode...
0.403214
0.229018
from flask import Flask from flask import render_template from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) #app.config['SECRET_KEY'] = '' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.app_db' app_db = SQLAlchemy(app) # User class(table) for app_db class User(app_...
app/app.py
from flask import Flask from flask import render_template from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) #app.config['SECRET_KEY'] = '' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.app_db' app_db = SQLAlchemy(app) # User class(table) for app_db class User(app_...
0.408867
0.046681
from __future__ import print_function import binascii import hashlib import hmac import os import struct # keysize is in number of bytes keysize = 32 hash_func = hashlib.sha256 # Realistically iv size and signature size don't have to be the same size # as the encryption key. hexB = lambda s: binascii.hexlify(s) un...
hashcrypt/hashcrypt.py
from __future__ import print_function import binascii import hashlib import hmac import os import struct # keysize is in number of bytes keysize = 32 hash_func = hashlib.sha256 # Realistically iv size and signature size don't have to be the same size # as the encryption key. hexB = lambda s: binascii.hexlify(s) un...
0.621311
0.444987
# Copyright (c) 2020, 2022 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ import contextlib import inspect import os from typing import Dict, Optional from ads.common.config import DEFAULT_CONFIG_PATH, DEFAULT_CONFIG_PROFILE, Con...
ads/config.py
# Copyright (c) 2020, 2022 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ import contextlib import inspect import os from typing import Dict, Optional from ads.common.config import DEFAULT_CONFIG_PATH, DEFAULT_CONFIG_PROFILE, Con...
0.805058
0.094845
from Utils import Environment from Utils import Constants class Calculator: LDPI = 120 MDPI = 160 HDPI = 240 XHDPI = 320 XXHDPI = 480 XXXHDPI = 640 def __init__(self,forDeviceDensity): self.mForDeviceDensity = forDeviceDensity self.mprofileMap = {} def getPx(self, d...
Utils/DipCalculator.py
from Utils import Environment from Utils import Constants class Calculator: LDPI = 120 MDPI = 160 HDPI = 240 XHDPI = 320 XXHDPI = 480 XXXHDPI = 640 def __init__(self,forDeviceDensity): self.mForDeviceDensity = forDeviceDensity self.mprofileMap = {} def getPx(self, d...
0.424889
0.266322
import asyncio import inspect import zmq import zmq.asyncio from distutils.version import LooseVersion from ssdaq import sslogger if LooseVersion("17") > LooseVersion(zmq.__version__): zmq.asyncio.install() class ReceiverServer: """ Base class for receivers. Implements some of the boilerplate code t...
ssdaq/core/receiver_server.py
import asyncio import inspect import zmq import zmq.asyncio from distutils.version import LooseVersion from ssdaq import sslogger if LooseVersion("17") > LooseVersion(zmq.__version__): zmq.asyncio.install() class ReceiverServer: """ Base class for receivers. Implements some of the boilerplate code t...
0.760384
0.177169
'''Test checkers''' import unittest import omnilint_test_common as common class TestCheckers(unittest.TestCase): def test_json(self): errs = common.checkthis( 'json', '.json', ''' { "x": "asdf", "y": 9, "z": false } ''') self.assertEqual(errs, []) errs = c...
tests/test_checkers.py
'''Test checkers''' import unittest import omnilint_test_common as common class TestCheckers(unittest.TestCase): def test_json(self): errs = common.checkthis( 'json', '.json', ''' { "x": "asdf", "y": 9, "z": false } ''') self.assertEqual(errs, []) errs = c...
0.311322
0.424412
from pycam.Geometry import TransformableContainer from pycam.Geometry.Model import ContourModel from pycam.Geometry.Line import Line from pycam.Geometry.PointUtils import padd TEXT_ALIGN_LEFT = 0 TEXT_ALIGN_CENTER = 1 TEXT_ALIGN_RIGHT = 2 class Letter(TransformableContainer): def __init__(self, lines): ...
pycam/pycam/Geometry/Letters.py
from pycam.Geometry import TransformableContainer from pycam.Geometry.Model import ContourModel from pycam.Geometry.Line import Line from pycam.Geometry.PointUtils import padd TEXT_ALIGN_LEFT = 0 TEXT_ALIGN_CENTER = 1 TEXT_ALIGN_RIGHT = 2 class Letter(TransformableContainer): def __init__(self, lines): ...
0.676406
0.254416
import enum from collections import OrderedDict from flask import request from .errors import FormError, FormValueError, ValidationError class Field(): _default = None def __new__(cls, *args, **kwargs): if 'init' in kwargs: kwargs.pop('init') return super().__new__(cls) ...
src/exts/jsonform/main.py
import enum from collections import OrderedDict from flask import request from .errors import FormError, FormValueError, ValidationError class Field(): _default = None def __new__(cls, *args, **kwargs): if 'init' in kwargs: kwargs.pop('init') return super().__new__(cls) ...
0.570331
0.110184
import torch import torch.nn as nn import torch.nn.functional as F from NeuralBlocks.blocks.convnorm import ConvNorm from NeuralBlocks.blocks.convnormrelu import ConvNormRelu class unetDown(nn.Module): def __init__(self, in_channels, out_channels, norm=None): super(unetDown, self).__init__() """ ...
models/unet.py
import torch import torch.nn as nn import torch.nn.functional as F from NeuralBlocks.blocks.convnorm import ConvNorm from NeuralBlocks.blocks.convnormrelu import ConvNormRelu class unetDown(nn.Module): def __init__(self, in_channels, out_channels, norm=None): super(unetDown, self).__init__() """ ...
0.9191
0.489442
import unittest from nzmath.permute import * a1 = Permute([2, 3, 1, 4]) a2 = Permute([1, 3, 2, 0, 4], 0) a3 = Permute([3, 4, 1, 0, 2], 0) a4 = Permute(['b', 'c', 'a', 'd', 'e'], 1) a5 = Permute(['@', '$', '~', '^', '#'], ['#', '$', '@', '^', '~']) a6 = Permute({'a':'b', 'b':'c', 'c':'a', 'd':'d', 'e':'e'}) b1 = ExPe...
test/testPermute.py
import unittest from nzmath.permute import * a1 = Permute([2, 3, 1, 4]) a2 = Permute([1, 3, 2, 0, 4], 0) a3 = Permute([3, 4, 1, 0, 2], 0) a4 = Permute(['b', 'c', 'a', 'd', 'e'], 1) a5 = Permute(['@', '$', '~', '^', '#'], ['#', '$', '@', '^', '~']) a6 = Permute({'a':'b', 'b':'c', 'c':'a', 'd':'d', 'e':'e'}) b1 = ExPe...
0.581184
0.938237
from urllib.parse import urljoin from django.conf import settings from django.contrib.auth.tokens import default_token_generator from django.template.loader import render_to_string from django.urls import reverse from django.utils.encoding import force_bytes from django.utils.formats import date_format from django.uti...
ephios/core/services/notifications/types.py
from urllib.parse import urljoin from django.conf import settings from django.contrib.auth.tokens import default_token_generator from django.template.loader import render_to_string from django.urls import reverse from django.utils.encoding import force_bytes from django.utils.formats import date_format from django.uti...
0.583322
0.088308
from tensorflow.keras.layers import Dense, Concatenate from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam import tensorflow as tf import numpy as np from huskarl.policy import Greedy, GaussianEpsGreedy from huskarl.core import Agent import huskarl.memory class A2C(Agent): """Adva...
huskarl/agent/a2c.py
from tensorflow.keras.layers import Dense, Concatenate from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam import tensorflow as tf import numpy as np from huskarl.policy import Greedy, GaussianEpsGreedy from huskarl.core import Agent import huskarl.memory class A2C(Agent): """Adva...
0.829492
0.513363
from functools import singledispatch from operator import attrgetter import unittest def dispatch(table, dispatch_method=attrgetter('__call__'), attr_joiner='__o__'): def dispatching(ty, recv, spec_table): def R(this, that): r = recv(this) m = dispatch_method(r) D = s...
dispatching/dispatching.py
from functools import singledispatch from operator import attrgetter import unittest def dispatch(table, dispatch_method=attrgetter('__call__'), attr_joiner='__o__'): def dispatching(ty, recv, spec_table): def R(this, that): r = recv(this) m = dispatch_method(r) D = s...
0.4917
0.223229
import click import pandas as pd import numpy as np from os import mkdir from os.path import basename, join from functools import partial DATA_TYPES_NUMERIC = ('int', 'float') FINAL_LIST = [ 'study_id', 'host_scientific_name', 'latitude_deg', 'longitude_deg', 'envo_biome_3', 'empo_3', 'temperature...
code/07-env-effects-corr/clean_map_emp.py
import click import pandas as pd import numpy as np from os import mkdir from os.path import basename, join from functools import partial DATA_TYPES_NUMERIC = ('int', 'float') FINAL_LIST = [ 'study_id', 'host_scientific_name', 'latitude_deg', 'longitude_deg', 'envo_biome_3', 'empo_3', 'temperature...
0.458106
0.341692
import numpy as np class CubeDataset: def __init__(self, opt, mu, A, new_noise=False, norm=True, num_examples=3000): super().__init__() self.opt = opt self.mu = np.reshape(mu, (3, 1)) self.A = A self.num_point = opt['num_point'] self.cube_template = opt['base_scale'...
data/CubeDatset.py
import numpy as np class CubeDataset: def __init__(self, opt, mu, A, new_noise=False, norm=True, num_examples=3000): super().__init__() self.opt = opt self.mu = np.reshape(mu, (3, 1)) self.A = A self.num_point = opt['num_point'] self.cube_template = opt['base_scale'...
0.538741
0.422386
from __future__ import print_function, absolute_import from .cid_utbase import cid_UTBase from futoin.cid.rmstool import RmsTool from futoin.cid.util import executil as _executil from futoin.cid.util import pathutil as _pathutil from futoin.cid.util import install as _install import os import subprocess import glob ...
tests/cid_rmshost_test.py
from __future__ import print_function, absolute_import from .cid_utbase import cid_UTBase from futoin.cid.rmstool import RmsTool from futoin.cid.util import executil as _executil from futoin.cid.util import pathutil as _pathutil from futoin.cid.util import install as _install import os import subprocess import glob ...
0.359252
0.072505
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.impo...
pysnmp/Dell-BANNER-MIB.py
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.impo...
0.293303
0.139338
from collections import OrderedDict import numpy as np from PIL import Image import torch from torch import nn from torchvision import datasets, transforms, models def import_transfrom(data_dir): train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' ...
util_functions.py
from collections import OrderedDict import numpy as np from PIL import Image import torch from torch import nn from torchvision import datasets, transforms, models def import_transfrom(data_dir): train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' ...
0.520009
0.63114
class Octopus: def __init__(self,filename): with open(filename,'r') as input_file: rows = [line.strip('\n') for line in input_file] self.max_y = len(rows) self.grid = [] for r in rows: cols = [int(c) for c in r] self.grid.append...
2021/Day11/octopus.py
class Octopus: def __init__(self,filename): with open(filename,'r') as input_file: rows = [line.strip('\n') for line in input_file] self.max_y = len(rows) self.grid = [] for r in rows: cols = [int(c) for c in r] self.grid.append...
0.473414
0.270733
import os import sys import shutil import logging import unittest import copy from distutils.version import LooseVersion from collections import namedtuple from mock import patch from mock import MagicMock from mock import call from intelhex import IntelHex from pyedbglib.hidtransport.hidtransportbase import HidTool ...
pymcuprog/tests/test_backend.py
import os import sys import shutil import logging import unittest import copy from distutils.version import LooseVersion from collections import namedtuple from mock import patch from mock import MagicMock from mock import call from intelhex import IntelHex from pyedbglib.hidtransport.hidtransportbase import HidTool ...
0.475118
0.137735
from typing import Any, Callable, Iterable, Optional, Tuple from .init_args import init_args from .key_swap import key_swap __all__ = [ 'ExtraKeysError', '_get_dict', 'InitArgsError', 'marshal_dict', 'unmarshal_dict', 'marshal_list', 'unmarshal_list', ] def _get_dict( obj: Any, ) ->...
pymarshal/util/marshal.py
from typing import Any, Callable, Iterable, Optional, Tuple from .init_args import init_args from .key_swap import key_swap __all__ = [ 'ExtraKeysError', '_get_dict', 'InitArgsError', 'marshal_dict', 'unmarshal_dict', 'marshal_list', 'unmarshal_list', ] def _get_dict( obj: Any, ) ->...
0.86681
0.221477
import argparse import socket import threading import time from urllib import request as urequest def cmd_parser(): # 返回为app.py准备的command line parser parser = argparse.ArgumentParser(description="To display your experiment logs in html.") parser.add_argument('-d', '--log_dir', help='Where to read logs. T...
toolbox/web/log_app/server/app_utils.py
import argparse import socket import threading import time from urllib import request as urequest def cmd_parser(): # 返回为app.py准备的command line parser parser = argparse.ArgumentParser(description="To display your experiment logs in html.") parser.add_argument('-d', '--log_dir', help='Where to read logs. T...
0.2587
0.05151
from __future__ import (absolute_import, division, print_function, unicode_literals) import json import math import os import select import subprocess import struct import sys import time try: from select import PIPE_BUF except ImportError: # PIPE_BUF is not available on Python 2.6 ...
asv/util.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import json import math import os import select import subprocess import struct import sys import time try: from select import PIPE_BUF except ImportError: # PIPE_BUF is not available on Python 2.6 ...
0.656438
0.345574
import skil_client from skil_client.rest import ApiException as api_exception class WorkSpace: """WorkSpace Workspaces are a collection of features that enable different tasks such as conducting experiments, training models, and test different dataset transforms. Workspaces are distinct from Deploym...
skil/workspaces.py
import skil_client from skil_client.rest import ApiException as api_exception class WorkSpace: """WorkSpace Workspaces are a collection of features that enable different tasks such as conducting experiments, training models, and test different dataset transforms. Workspaces are distinct from Deploym...
0.722429
0.433981
import unittest from sqlbuilder import smartsql from ascetic import exceptions, validators from ascetic.databases import databases from ascetic.mappers import Mapper, mapper_registry from ascetic.relations import ForeignKey Author = Book = None class TestMapper(unittest.TestCase): maxDiff = None create_s...
ascetic/tests/test_mappers.py
import unittest from sqlbuilder import smartsql from ascetic import exceptions, validators from ascetic.databases import databases from ascetic.mappers import Mapper, mapper_registry from ascetic.relations import ForeignKey Author = Book = None class TestMapper(unittest.TestCase): maxDiff = None create_s...
0.508056
0.197967
from __future__ import unicode_literals from permission.compat import six def get_perm_codename(perm, fail_silently=True): """ Get permission codename from permission-string. Examples -------- >>> get_perm_codename('app_label.codename_model') 'codename_model' >>> get_perm_codename('app_la...
src/permission/utils/permissions.py
from __future__ import unicode_literals from permission.compat import six def get_perm_codename(perm, fail_silently=True): """ Get permission codename from permission-string. Examples -------- >>> get_perm_codename('app_label.codename_model') 'codename_model' >>> get_perm_codename('app_la...
0.871598
0.179135
import discord from discord.ext import commands from ext.context import Context import os import subprocess from utils.utils import paginate from contextlib import redirect_stdout import textwrap import traceback import inspect import datetime import io class Owner: """Core class for owner commands""" def __in...
cogs/owner.py
import discord from discord.ext import commands from ext.context import Context import os import subprocess from utils.utils import paginate from contextlib import redirect_stdout import textwrap import traceback import inspect import datetime import io class Owner: """Core class for owner commands""" def __in...
0.451327
0.270349
import os import numpy as np from lava.core.generic.process import Process from lava.processes.generic.dense import Dense from lava.processes.generic.lif import LIF from lava.core.generic.enums import Backend class DatasetBuffer: def __init__(self, **kwargs): dataset_path = kwargs.pop('dataset_path', 'd...
nets/mnist_execvar_io.py
import os import numpy as np from lava.core.generic.process import Process from lava.processes.generic.dense import Dense from lava.processes.generic.lif import LIF from lava.core.generic.enums import Backend class DatasetBuffer: def __init__(self, **kwargs): dataset_path = kwargs.pop('dataset_path', 'd...
0.628635
0.317506
from abc import ABC, abstractmethod from typing import Any import torch import torch.nn as nn from torch import Tensor from .functions import * # This is a work-in-progress attempt to use type aliases to indicate the shapes of tensors. # T = 50 (TBTT length) # B = 50 (batch size) # I = 1/3/10 (IW...
pydreamer/models/common.py
from abc import ABC, abstractmethod from typing import Any import torch import torch.nn as nn from torch import Tensor from .functions import * # This is a work-in-progress attempt to use type aliases to indicate the shapes of tensors. # T = 50 (TBTT length) # B = 50 (batch size) # I = 1/3/10 (IW...
0.940285
0.468669
import json import boto3 from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer s3 = boto3.client('s3') def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3'][...
aws/lambda/sentiment-analysis/lambda_function.py
import json import boto3 from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer s3 = boto3.client('s3') def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3'][...
0.325842
0.114591
import mock from openstack.cloud import inventory import openstack.config from openstack.tests import fakes from openstack.tests.unit import base class TestInventory(base.TestCase): def setUp(self): super(TestInventory, self).setUp() @mock.patch("openstack.config.loader.OpenStackConfig") @mock...
openstack/tests/unit/cloud/test_inventory.py
import mock from openstack.cloud import inventory import openstack.config from openstack.tests import fakes from openstack.tests.unit import base class TestInventory(base.TestCase): def setUp(self): super(TestInventory, self).setUp() @mock.patch("openstack.config.loader.OpenStackConfig") @mock...
0.638385
0.296323
import numpy as np import os import sys sys.path.append('/home/jonfrey/PLR/src/') sys.path.append('/home/jonfrey/PLR/src/dense_fusion') from math import pi from PIL import Image from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from helper import re_quat, compose_quat, rotation_angle from est...
src/helper/postprocess.py
import numpy as np import os import sys sys.path.append('/home/jonfrey/PLR/src/') sys.path.append('/home/jonfrey/PLR/src/dense_fusion') from math import pi from PIL import Image from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from helper import re_quat, compose_quat, rotation_angle from est...
0.25303
0.290383
import logging import logging.handlers import ConfigParser import StringIO config = ConfigParser.RawConfigParser() content = """ [server] hostname=localhost url_port=8440 secured_url_port=8441 [agent] prefix=/tmp/ambari-agent [services] [stack] installprefix=/tmp upgradeScriptsDir=/var/lib/ambari-agent/upgrade_sta...
ambari-agent/src/main/python/ambari_agent/AmbariConfig.py
import logging import logging.handlers import ConfigParser import StringIO config = ConfigParser.RawConfigParser() content = """ [server] hostname=localhost url_port=8440 secured_url_port=8441 [agent] prefix=/tmp/ambari-agent [services] [stack] installprefix=/tmp upgradeScriptsDir=/var/lib/ambari-agent/upgrade_sta...
0.130313
0.039527
from math import atan2, sqrt from functools import partial, partialmethod from itertools import starmap from operator import and_, or_, xor, invert from typing import Tuple, Optional class Color(object): __slots__ = ('_color') _RGBfmt = frozenset({'RGB', 'float'}) _HSLfmt = frozenset({'HSL', 'luminance'}) ...
colorconv.py
from math import atan2, sqrt from functools import partial, partialmethod from itertools import starmap from operator import and_, or_, xor, invert from typing import Tuple, Optional class Color(object): __slots__ = ('_color') _RGBfmt = frozenset({'RGB', 'float'}) _HSLfmt = frozenset({'HSL', 'luminance'}) ...
0.80479
0.161883
import math,time,multiprocessing import Pyro4,imp,time,sys,os,psutil import Library import sqlite3 as sqlite import datetime as dt import subprocess from signal import * from subprocess import * import random from collections import OrderedDict from Library import getHomepath, readBackfuzzPath #perhaps needs to be s...
emulators/run_backfuzz.py
import math,time,multiprocessing import Pyro4,imp,time,sys,os,psutil import Library import sqlite3 as sqlite import datetime as dt import subprocess from signal import * from subprocess import * import random from collections import OrderedDict from Library import getHomepath, readBackfuzzPath #perhaps needs to be s...
0.233008
0.123524
from litex.build.generic_platform import * from litex.build.altera import AlteraPlatform from litex.build.altera.programmer import USBBlaster # IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk ("clk50", 0, Pins("T2"), IOStandard("3.3-V LVTTL")),...
litex_boards/platforms/qmtech_ep4ce15.py
from litex.build.generic_platform import * from litex.build.altera import AlteraPlatform from litex.build.altera.programmer import USBBlaster # IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk ("clk50", 0, Pins("T2"), IOStandard("3.3-V LVTTL")),...
0.368065
0.207054
import displayio __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Display_Shapes.git" class RoundRect(displayio.TileGrid): """A round-corner rectangle, top left corner is (x, y) and size of width, height. r is the radius of the rounded corner. Stroke is used for the...
adafruit_display_shapes/roundrect.py
import displayio __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Display_Shapes.git" class RoundRect(displayio.TileGrid): """A round-corner rectangle, top left corner is (x, y) and size of width, height. r is the radius of the rounded corner. Stroke is used for the...
0.792785
0.442396
import sys import itertools class BubbleDetection: # Bubble (in a de Bruijn graph) is defined as a pair of short # non-overlapping disjoint paths between some vertces V and W. def __init__(self, k, t, reads): self.k = k self.threshold = t self.graph = {} self.paths = {} ...
week3/Bubble Detection.py
import sys import itertools class BubbleDetection: # Bubble (in a de Bruijn graph) is defined as a pair of short # non-overlapping disjoint paths between some vertces V and W. def __init__(self, k, t, reads): self.k = k self.threshold = t self.graph = {} self.paths = {} ...
0.38122
0.417361
__all__ = ['default_configs', 'model_funcs', 'splits', 'get_model', 'EfficientNetB1', 'EfficientNetB2', 'EfficientNetB3', 'EfficientNetB4', 'EfficientNetB5', 'EfficientNetB6', 'EfficientNetB7', 'efficientnet_config', 'efficientnetb1', 'efficientnetb2', 'efficientnetb3', 'efficientnetb4', ...
dev/local/classification/models.py
__all__ = ['default_configs', 'model_funcs', 'splits', 'get_model', 'EfficientNetB1', 'EfficientNetB2', 'EfficientNetB3', 'EfficientNetB4', 'EfficientNetB5', 'EfficientNetB6', 'EfficientNetB7', 'efficientnet_config', 'efficientnetb1', 'efficientnetb2', 'efficientnetb3', 'efficientnetb4', ...
0.611962
0.282092
from typing import Dict from unittest.mock import patch from pandas import DataFrame, read_csv from edfi_google_classroom_extractor.api.usage import request_all_usage_as_df from tests.helper import merged_dict # Empty string is the default value for this env variables ENV_START_DATE = "" ENV_END_DATE = "" def dataf...
src/google-classroom-extractor/tests/api/usage/test_usage_db_sync.py
from typing import Dict from unittest.mock import patch from pandas import DataFrame, read_csv from edfi_google_classroom_extractor.api.usage import request_all_usage_as_df from tests.helper import merged_dict # Empty string is the default value for this env variables ENV_START_DATE = "" ENV_END_DATE = "" def dataf...
0.729038
0.354154
import logging from collections import defaultdict import sparv.util as util from sparv import (AllDocuments, AnnotationAllDocs, Config, Corpus, Export, ExportInput, OutputCommonData, exporter, installer) from sparv.util.mysql_wrapper import MySQL log = logging.getLogger(__name__) # Path to the c...
sparv/modules/korp/lemgram_index.py
import logging from collections import defaultdict import sparv.util as util from sparv import (AllDocuments, AnnotationAllDocs, Config, Corpus, Export, ExportInput, OutputCommonData, exporter, installer) from sparv.util.mysql_wrapper import MySQL log = logging.getLogger(__name__) # Path to the c...
0.613352
0.110952
from googlecloudsdk.api_lib.deployment_manager import dm_v2_util from googlecloudsdk.calliope import base from googlecloudsdk.core import log from googlecloudsdk.core import properties from googlecloudsdk.third_party.apitools.base.py import list_pager class List(base.Command): """List manifests in a deployment. ...
lib/surface/deployment_manager/manifests/list.py
from googlecloudsdk.api_lib.deployment_manager import dm_v2_util from googlecloudsdk.calliope import base from googlecloudsdk.core import log from googlecloudsdk.core import properties from googlecloudsdk.third_party.apitools.base.py import list_pager class List(base.Command): """List manifests in a deployment. ...
0.716318
0.10581
from typing import List import pytest from thinc.api import fix_random_seed, Adam, set_dropout_rate from thinc.api import Ragged, reduce_mean, Logistic, chain, Relu from numpy.testing import assert_array_equal, assert_array_almost_equal import numpy from spacy.ml.models import build_Tok2Vec_model, MultiHashEmbed, Maxou...
spacy/tests/test_models.py
from typing import List import pytest from thinc.api import fix_random_seed, Adam, set_dropout_rate from thinc.api import Ragged, reduce_mean, Logistic, chain, Relu from numpy.testing import assert_array_equal, assert_array_almost_equal import numpy from spacy.ml.models import build_Tok2Vec_model, MultiHashEmbed, Maxou...
0.726523
0.468122
from __future__ import print_function from P13pt.mascril.measurement import MeasurementBase from P13pt.mascril.parameter import Sweep, String, Folder, Boolean from P13pt.mascril.progressbar import progressbar_wait from P13pt.drivers.bilt import Bilt, BiltVoltageSource, BiltVoltMeter from P13pt.drivers.anritsuvna import...
P13pt/mascril/modules/vna_capa_Anritsu.py
from __future__ import print_function from P13pt.mascril.measurement import MeasurementBase from P13pt.mascril.parameter import Sweep, String, Folder, Boolean from P13pt.mascril.progressbar import progressbar_wait from P13pt.drivers.bilt import Bilt, BiltVoltageSource, BiltVoltMeter from P13pt.drivers.anritsuvna import...
0.468304
0.170025
from difflib import SequenceMatcher from classification.models import NotMealTags from classification.tagger.recipe_tagger import RecipeTagger from crawler.data_cleaners.daily_menu.filters.base_filter import BaseFilter class NoMealFilter(BaseFilter): def __init__(self): self.no_meal_tags = [] sel...
daily_menu/crawler/data_cleaners/daily_menu/filters/no_meal.py
from difflib import SequenceMatcher from classification.models import NotMealTags from classification.tagger.recipe_tagger import RecipeTagger from crawler.data_cleaners.daily_menu.filters.base_filter import BaseFilter class NoMealFilter(BaseFilter): def __init__(self): self.no_meal_tags = [] sel...
0.678327
0.259075
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by <NAME> # -------------------------------------------------------- """Test a Fast R-CNN network on an image database.""" import _init_paths fro...
tools/test_net.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by <NAME> # -------------------------------------------------------- """Test a Fast R-CNN network on an image database.""" import _init_paths fro...
0.715722
0.126138
# ****************************************** PathwayProjection ***************************************************** """ Contents -------- * `PathwayProjection_Overview` * `PathwayProjection_Creation` * `PathwayProjection_Structure` - `PathwayProjection_Sender` - `PathwayProjection_Receiver` *...
psyneulink/core/components/projections/pathway/pathwayprojection.py
# ****************************************** PathwayProjection ***************************************************** """ Contents -------- * `PathwayProjection_Overview` * `PathwayProjection_Creation` * `PathwayProjection_Structure` - `PathwayProjection_Sender` - `PathwayProjection_Receiver` *...
0.711932
0.432183
{ 'targets': [ { 'target_name': 'node-juce-native', 'sources': [ 'src/main.cc', 'addon/JuceLibraryCode/include_juce_core.cpp', 'addon/JuceLibraryCode/include_juce_data_structures.cpp', 'addon/JuceLibraryCode/include_juce_events.cpp', 'addon/JuceLibraryCode/inclu...
binding.gyp
{ 'targets': [ { 'target_name': 'node-juce-native', 'sources': [ 'src/main.cc', 'addon/JuceLibraryCode/include_juce_core.cpp', 'addon/JuceLibraryCode/include_juce_data_structures.cpp', 'addon/JuceLibraryCode/include_juce_events.cpp', 'addon/JuceLibraryCode/inclu...
0.260013
0.101679
from .settings import * # often used libraries INSTALLED_APPS += [ 'django_cleanup', 'widget_tweaks', 'corsheaders' ] # allauth INSTALLED_APPS += [ 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth...
djps/base.py
from .settings import * # often used libraries INSTALLED_APPS += [ 'django_cleanup', 'widget_tweaks', 'corsheaders' ] # allauth INSTALLED_APPS += [ 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth...
0.226869
0.070272
import sys import click from askanna.core import client from askanna.core.dataclasses import Variable class VariableGateway: def __init__(self, *args, **kwargs): self.client = client self.project = None self.cache = {} self.base_url = self.client.config.remote + "variable/" d...
askanna/core/variable.py
import sys import click from askanna.core import client from askanna.core.dataclasses import Variable class VariableGateway: def __init__(self, *args, **kwargs): self.client = client self.project = None self.cache = {} self.base_url = self.client.config.remote + "variable/" d...
0.280814
0.08886
from tfchain.polyfill.encoding.jsmods.sprintfjs import api as sprintfjs def to_int(str, base=None): x = None __pragma__("js", "{}", """ x = parseInt(str, base); """) return x def from_int(x): str = None __pragma__("js", "{}", """ str = x.toString(); """) return str def to_utf8...
src/tfchain/polyfill/encoding/str.py
from tfchain.polyfill.encoding.jsmods.sprintfjs import api as sprintfjs def to_int(str, base=None): x = None __pragma__("js", "{}", """ x = parseInt(str, base); """) return x def from_int(x): str = None __pragma__("js", "{}", """ str = x.toString(); """) return str def to_utf8...
0.535098
0.140661
from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import * # NOQA import numpy as np import scipy.integrate import scipy.interpolate def integrate_cumtrapz(data, dx, **kwargs): """ Performs first order integration of data using ...
IRIS_data_download/IRIS_download_support/obspy/signal/differentiate_and_integrate.py
from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import * # NOQA import numpy as np import scipy.integrate import scipy.interpolate def integrate_cumtrapz(data, dx, **kwargs): """ Performs first order integration of data using ...
0.890091
0.517998
import contextlib import os import shutil import subprocess import sys import tempfile import urllib.request import xml.etree.ElementTree as ET """Fetch and install missing Mikero's tools""" toms_depot = 'http://tom4897.info/app/tools/community/' disk_location = r'C:\Program Files (x86)\Mikero\DePboTools\bin' + '\\' ...
tools/install_mikeros_tools.py
import contextlib import os import shutil import subprocess import sys import tempfile import urllib.request import xml.etree.ElementTree as ET """Fetch and install missing Mikero's tools""" toms_depot = 'http://tom4897.info/app/tools/community/' disk_location = r'C:\Program Files (x86)\Mikero\DePboTools\bin' + '\\' ...
0.245899
0.082734
import sys, time, os from datetime import datetime from prettytable import PrettyTable from modules.get_aiq_inputs import get_inputs_logs as get_inputs from modules.connect_auth_aiq import web_login, build_headers, build_connect from modules.get_aiq_customer import parse_customer from modules.parser import parse_...
aiq_cluster_events.py
import sys, time, os from datetime import datetime from prettytable import PrettyTable from modules.get_aiq_inputs import get_inputs_logs as get_inputs from modules.connect_auth_aiq import web_login, build_headers, build_connect from modules.get_aiq_customer import parse_customer from modules.parser import parse_...
0.10307
0.097048
import json import warnings import pulumi import pulumi.runtime from .. import utilities, tables class Model(pulumi.CustomResource): arn: pulumi.Output[str] """ The Amazon Resource Name (ARN) assigned by AWS to this model. """ containers: pulumi.Output[list] """ Specifies containers in the...
sdk/python/pulumi_aws/sagemaker/model.py
import json import warnings import pulumi import pulumi.runtime from .. import utilities, tables class Model(pulumi.CustomResource): arn: pulumi.Output[str] """ The Amazon Resource Name (ARN) assigned by AWS to this model. """ containers: pulumi.Output[list] """ Specifies containers in the...
0.741768
0.141637
from __future__ import division import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt isis = np.loadtxt("data/ISIs_gsdT36gh02.txt.gz") Vtraces = [np.loadtxt("data/Vtrace-gsd%04.0f.txt"%(g*1e4)) for g in (0.21,0.23,0.245,0.263,0.28,0.315)] time=np.arange(0,4,0.00005) ...
Figures/Figure5/Figure5-gsd bifurcation.py
from __future__ import division import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt isis = np.loadtxt("data/ISIs_gsdT36gh02.txt.gz") Vtraces = [np.loadtxt("data/Vtrace-gsd%04.0f.txt"%(g*1e4)) for g in (0.21,0.23,0.245,0.263,0.28,0.315)] time=np.arange(0,4,0.00005) ...
0.259638
0.369969
from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse from django.contrib.auth.models import AnonymousUser from django.test import RequestFactory from tally_ho.apps.tally.views import data_entry as views from tally_ho.libs.permissions import groups from tally_ho.libs.tests.te...
tally_ho/apps/tally/tests/views/test_data_entry.py
from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse from django.contrib.auth.models import AnonymousUser from django.test import RequestFactory from tally_ho.apps.tally.views import data_entry as views from tally_ho.libs.permissions import groups from tally_ho.libs.tests.te...
0.481941
0.289447
import os import sys from logger import logger from datetime import datetime, timedelta from time import mktime from calendar import timegm from emojis import get_random_emoji ignoreWords = os.environ.get('IGNORE_WORDS') IGNORE_WORDS = [i.lower().strip() for i in ignoreWords.split(',')] if ignoreWords else [] ignoreL...
helpers/tools.py
import os import sys from logger import logger from datetime import datetime, timedelta from time import mktime from calendar import timegm from emojis import get_random_emoji ignoreWords = os.environ.get('IGNORE_WORDS') IGNORE_WORDS = [i.lower().strip() for i in ignoreWords.split(',')] if ignoreWords else [] ignoreL...
0.256459
0.144601
import argparse as ap import yaml import sys import os # From this project from shakemap_utils import download_shakemapgrid def get_args(): # Get the input arguments parser = ap.ArgumentParser(description='Download a USGS ShakeMap', formatter_class=ap.ArgumentDefaultsHelpForma...
scripts/find_and_download_shakemap.py
import argparse as ap import yaml import sys import os # From this project from shakemap_utils import download_shakemapgrid def get_args(): # Get the input arguments parser = ap.ArgumentParser(description='Download a USGS ShakeMap', formatter_class=ap.ArgumentDefaultsHelpForma...
0.306942
0.101589
import pandas as pd import pytest from esmtools.timeutils import TimeUtilAccessor def test_timeutils_accessor(annual_gregorian): """Test that the `timeutils` accessor can be called.""" # Calling the TimeUtilAccessor directly in the first instance to not trigger # F401 (importing unused module) from flake...
esmtools/tests/test_timeutils.py
import pandas as pd import pytest from esmtools.timeutils import TimeUtilAccessor def test_timeutils_accessor(annual_gregorian): """Test that the `timeutils` accessor can be called.""" # Calling the TimeUtilAccessor directly in the first instance to not trigger # F401 (importing unused module) from flake...
0.897617
0.668258
import pickle import string import numpy as np from gensim.models import word2vec, Word2Vec from keras.preprocessing.sequence import pad_sequences def build_tag2id(tags, tag2id_filepath): """ Build the dictionary mapping from tag to id :param tags: the BIO tags :param tag2id_filepath: the output pat...
word2vec_bilstm_crf/data_utils.py
import pickle import string import numpy as np from gensim.models import word2vec, Word2Vec from keras.preprocessing.sequence import pad_sequences def build_tag2id(tags, tag2id_filepath): """ Build the dictionary mapping from tag to id :param tags: the BIO tags :param tag2id_filepath: the output pat...
0.694717
0.393735
import pandas as pd def csv_parser(df, mapping_csv): """Selects and renames columns according to a CSV file that defines the parsing rules. Arguments: --------- ``df``: DataFrame The Raw Dataframe we want to use import into OSM. ``mapping_csv``: String The pa...
osmi_helpers/data_gathering.py
import pandas as pd def csv_parser(df, mapping_csv): """Selects and renames columns according to a CSV file that defines the parsing rules. Arguments: --------- ``df``: DataFrame The Raw Dataframe we want to use import into OSM. ``mapping_csv``: String The pa...
0.860428
0.597931
from copy import deepcopy from eth2spec.test.context import spec_state_test, with_all_phases from eth2spec.test.helpers.state import ( next_epoch, next_slot, state_transition_and_sign_block, ) from eth2spec.test.helpers.block import apply_empty_block, sign_block from eth2spec.test.helpers.attestations impo...
test_libs/pyspec/eth2spec/test/phase_0/epoch_processing/test_process_crosslinks.py
from copy import deepcopy from eth2spec.test.context import spec_state_test, with_all_phases from eth2spec.test.helpers.state import ( next_epoch, next_slot, state_transition_and_sign_block, ) from eth2spec.test.helpers.block import apply_empty_block, sign_block from eth2spec.test.helpers.attestations impo...
0.796728
0.557484
import grakn import re from Bio.SeqIO.FastaIO import SimpleFastaParser from util import insert_if_non_existent, insert_anyway ''' 1. creates a Grakn session to talk to the 'proteins' keyspace 2. inserts the database entity named 'UniProt' 3. for each protein stored in target-protein-sequences.fasta, inser...
blast/migrate.py
import grakn import re from Bio.SeqIO.FastaIO import SimpleFastaParser from util import insert_if_non_existent, insert_anyway ''' 1. creates a Grakn session to talk to the 'proteins' keyspace 2. inserts the database entity named 'UniProt' 3. for each protein stored in target-protein-sequences.fasta, inser...
0.347316
0.222521
import webob.exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.openstack.common import log as logging ALIAS = 'extensions' LOG = logging.getLogger(__name__) # V2.1 does not support XML but we need to keep an entry in the # /extensions information returned to the user for ba...
nova/api/openstack/compute/plugins/v3/extension_info.py
import webob.exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.openstack.common import log as logging ALIAS = 'extensions' LOG = logging.getLogger(__name__) # V2.1 does not support XML but we need to keep an entry in the # /extensions information returned to the user for ba...
0.638948
0.060919
from couchdbkit.exceptions import ResourceNotFound from datetime import timedelta from django.utils.translation import ugettext as _, ugettext_noop from corehq.apps.users.models import CouchUser from custom.succeed.reports import * from custom.succeed.reports.patient_details import PatientDetailsReport from dimagi.util...
custom/succeed/reports/patient_interactions.py
from couchdbkit.exceptions import ResourceNotFound from datetime import timedelta from django.utils.translation import ugettext as _, ugettext_noop from corehq.apps.users.models import CouchUser from custom.succeed.reports import * from custom.succeed.reports.patient_details import PatientDetailsReport from dimagi.util...
0.38827
0.051702
import imghdr from django.core.files.uploadedfile import InMemoryUploadedFile from data_django.exec_sql import exec_dql_query def is_valid_image_upload(city: str, image: InMemoryUploadedFile) -> bool: """Returns whether the passed request is a valid image upload request. Parameters ---------- city: s...
amos/django_orchestrator/api/validator.py
import imghdr from django.core.files.uploadedfile import InMemoryUploadedFile from data_django.exec_sql import exec_dql_query def is_valid_image_upload(city: str, image: InMemoryUploadedFile) -> bool: """Returns whether the passed request is a valid image upload request. Parameters ---------- city: s...
0.827654
0.480052
from drawables import Drawable from utils import FRAMERATE import pygame import sys __all__ = ['SceneManager', 'Scene'] def is_quit_event(ev): if ev.type is pygame.QUIT: return True if ev.type is pygame.KEYDOWN: if ev.key is pygame.K_ESCAPE and pygame.key.get_mods() & pygame.KMOD_SHIFT: ...
scenes/base.py
from drawables import Drawable from utils import FRAMERATE import pygame import sys __all__ = ['SceneManager', 'Scene'] def is_quit_event(ev): if ev.type is pygame.QUIT: return True if ev.type is pygame.KEYDOWN: if ev.key is pygame.K_ESCAPE and pygame.key.get_mods() & pygame.KMOD_SHIFT: ...
0.345216
0.166134