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.path from unittest import TestCase import numpy as np import pandas as pd from ipycli.notebookmanager import NotebookManager from IPython.utils.tempdir import TemporaryDirectory class TestCLI(TestCase): def __init__(self, *args, **kwargs): TestCase.__init__(self, *args, **kwargs) def runT...
ipycli/tests/test_cli.py
import os.path from unittest import TestCase import numpy as np import pandas as pd from ipycli.notebookmanager import NotebookManager from IPython.utils.tempdir import TemporaryDirectory class TestCLI(TestCase): def __init__(self, *args, **kwargs): TestCase.__init__(self, *args, **kwargs) def runT...
0.377426
0.371194
from enum import Enum from dsp_lab import * class Process(Enum): DSP_OPEN_FILE = 0 DSP_SAVE_FILE = 1 DSP_PLOT_TIME_DOMAIN = 2 DSP_PLOT_FREQUENCY_DOMAIN = 3 DSP_FILTER = 4 DSP_ROOT_MEAN_SQUARE_ERROR = 5 def banner(): """ Banner initial """ print("------------------------------...
signal_processing_lab.py
from enum import Enum from dsp_lab import * class Process(Enum): DSP_OPEN_FILE = 0 DSP_SAVE_FILE = 1 DSP_PLOT_TIME_DOMAIN = 2 DSP_PLOT_FREQUENCY_DOMAIN = 3 DSP_FILTER = 4 DSP_ROOT_MEAN_SQUARE_ERROR = 5 def banner(): """ Banner initial """ print("------------------------------...
0.619586
0.143968
__version__ = "0.7.0" from __future__ import print_function import config import yaml import html2text from os import path as p from itertools import imap, repeat from flask import Flask, g, render_template, url_for, Response, request from flask.ext.bootstrap import Bootstrap from flask.ext.markdown import Markdown ...
app/__init__.py
__version__ = "0.7.0" from __future__ import print_function import config import yaml import html2text from os import path as p from itertools import imap, repeat from flask import Flask, g, render_template, url_for, Response, request from flask.ext.bootstrap import Bootstrap from flask.ext.markdown import Markdown ...
0.357568
0.055183
import gtk import gobject import tempfile import os from plugins import get_plugin_by_type from file_chooser_dlg import File_Chooser, FILE_CHOOSER_TYPE_FILE from camera import Camera, Camera_Exception, DEFAULT_RESOLUTION from support import warning, debug from ossupport import xclose, xremove from proximateprotocol im...
pic_choose_dlg.py
import gtk import gobject import tempfile import os from plugins import get_plugin_by_type from file_chooser_dlg import File_Chooser, FILE_CHOOSER_TYPE_FILE from camera import Camera, Camera_Exception, DEFAULT_RESOLUTION from support import warning, debug from ossupport import xclose, xremove from proximateprotocol im...
0.381911
0.050635
import RPi.GPIO as GPIO import time import sys import subprocess, os import signal import pygame from pygame.locals import * pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag os.environ["SDL_FBDEV"] = "/dev/fb1" os.environ["SDL_MOUSEDEV"] = "/dev/input/touchscreen" os.environ["SDL_MOUSEDRV"]...
launcher.py
import RPi.GPIO as GPIO import time import sys import subprocess, os import signal import pygame from pygame.locals import * pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag os.environ["SDL_FBDEV"] = "/dev/fb1" os.environ["SDL_MOUSEDEV"] = "/dev/input/touchscreen" os.environ["SDL_MOUSEDRV"]...
0.061073
0.065995
"""Implements a class to be used for unit testing. """ import datetime from tlsmate.cert_chain import CertChain from tlsmate.server_profile import SPObject, ProfileSchema, ServerProfileSchema from tlsmate import utils from marshmallow import fields import pytest class SPUnitTest(SPObject): pass class SPUnitTes...
tests/modules/test_module_server_profile.py
"""Implements a class to be used for unit testing. """ import datetime from tlsmate.cert_chain import CertChain from tlsmate.server_profile import SPObject, ProfileSchema, ServerProfileSchema from tlsmate import utils from marshmallow import fields import pytest class SPUnitTest(SPObject): pass class SPUnitTes...
0.650023
0.486941
import json import os from shutil import rmtree from tempfile import mkdtemp from couchapp.localdoc import LocalDoc def test_load_ignores_non_exist(): doc = LocalDoc('/mock/app', create=False) assert doc.ignores == [] class testIgnores(object): def setUp(self): self.dir = mkdtemp() def t...
tests/test_localdoc.py
import json import os from shutil import rmtree from tempfile import mkdtemp from couchapp.localdoc import LocalDoc def test_load_ignores_non_exist(): doc = LocalDoc('/mock/app', create=False) assert doc.ignores == [] class testIgnores(object): def setUp(self): self.dir = mkdtemp() def t...
0.398875
0.222162
import re from studioqt import QtCore class SearchFilter(QtCore.QObject): searchChanged = QtCore.Signal() class Operator: OR = " or " AND = " and " def __init__(self, pattern, spaceOperator=Operator.AND): """ :type pattern: str :type spaceOperator: SearchFilter....
zfused_maya/zfused_maya/tool/animation/studiolibrary/packages/studioqt/widgets/searchwidget/searchfilter.py
import re from studioqt import QtCore class SearchFilter(QtCore.QObject): searchChanged = QtCore.Signal() class Operator: OR = " or " AND = " and " def __init__(self, pattern, spaceOperator=Operator.AND): """ :type pattern: str :type spaceOperator: SearchFilter....
0.742608
0.342984
import os import json from datetime import datetime from ckan.lib.redis import connect_to_redis def get_config(config_name): """ Retrieves a specific section of the config by its name. The config is retrieved from Redis, as it is cached there for up to 24 hours. :param str config_name: the name of ...
ckanext/dataoverheid/logic/helpers/config.py
import os import json from datetime import datetime from ckan.lib.redis import connect_to_redis def get_config(config_name): """ Retrieves a specific section of the config by its name. The config is retrieved from Redis, as it is cached there for up to 24 hours. :param str config_name: the name of ...
0.656438
0.305918
from django.shortcuts import render,redirect from post.models import Post, Comment # 向上取整 from math import ceil from post.helper import page_cach,read_count from post.helper import top_n from user.helper import login_required # Create your views here. # 帖子列表操作 @page_cach(60) def post_list(request): # 获取到当前的页码 p...
post/views.py
from django.shortcuts import render,redirect from post.models import Post, Comment # 向上取整 from math import ceil from post.helper import page_cach,read_count from post.helper import top_n from user.helper import login_required # Create your views here. # 帖子列表操作 @page_cach(60) def post_list(request): # 获取到当前的页码 p...
0.28279
0.066055
import os import re import logging import traceback from subprocess import call from time import time from pyramid.view import view_config from pyramid.response import Response from mist.monitor import config from mist.monitor import methods from mist.monitor import graphite from mist.monitor.model import get_all_ma...
src/mist/monitor/views.py
import os import re import logging import traceback from subprocess import call from time import time from pyramid.view import view_config from pyramid.response import Response from mist.monitor import config from mist.monitor import methods from mist.monitor import graphite from mist.monitor.model import get_all_ma...
0.649912
0.069985
import os import sys import unittest import PRESUBMIT sys.path.append( os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '..')) from PRESUBMIT_test_mocks import (MockInputApi, MockOutputApi, MockAffectedFile) class AccessibilityEventsTestIncludesAndroidTest(unittest.TestCase): #...
content/test/data/accessibility/PRESUBMIT_test.py
import os import sys import unittest import PRESUBMIT sys.path.append( os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '..')) from PRESUBMIT_test_mocks import (MockInputApi, MockOutputApi, MockAffectedFile) class AccessibilityEventsTestIncludesAndroidTest(unittest.TestCase): #...
0.405449
0.131507
import numpy as np import tensorflow as tf from tensorflow.contrib.framework.python.ops import arg_scope import net.nn as nn def vq_encoder_spec(x, ema=None, nr_channel=128, nr_res_block=2, nr_res_channel=64, embedding_dim=64, num_embeddings=512, commitment_cost=0.25, decay=0.99, is_training=False...
net/vqvae.py
import numpy as np import tensorflow as tf from tensorflow.contrib.framework.python.ops import arg_scope import net.nn as nn def vq_encoder_spec(x, ema=None, nr_channel=128, nr_res_block=2, nr_res_channel=64, embedding_dim=64, num_embeddings=512, commitment_cost=0.25, decay=0.99, is_training=False...
0.79999
0.403684
import numpy as np from settings import same_grid_dist_ratio class SudokuVideo: def __init__(self, grid): self.grid_raw = grid self.grid = np.zeros((9, 9), dtype=int) self.init_grid(grid) self.grid_solved = np.zeros((9, 9), dtype=int) self.isConfident = False self...
src/solving_objects/SudokuVideo.py
import numpy as np from settings import same_grid_dist_ratio class SudokuVideo: def __init__(self, grid): self.grid_raw = grid self.grid = np.zeros((9, 9), dtype=int) self.init_grid(grid) self.grid_solved = np.zeros((9, 9), dtype=int) self.isConfident = False self...
0.638723
0.258095
from logging import getLogger from pymcuprog.pymcuprog_errors import PymcuprogError from . import constants class UpdiDatalink: """ UPDI data link class handles the UPDI data protocol within the device """ LDCS_RESPONSE_BYTES = 1 def __init__(self): self.logger = getLogger(__name__) ...
pymcuprog/serialupdi/link.py
from logging import getLogger from pymcuprog.pymcuprog_errors import PymcuprogError from . import constants class UpdiDatalink: """ UPDI data link class handles the UPDI data protocol within the device """ LDCS_RESPONSE_BYTES = 1 def __init__(self): self.logger = getLogger(__name__) ...
0.765155
0.259718
import numpy as np from cloudvolume import CloudVolume from .cube import Cube from .error import CVDBError class CloudVolumeDB: """ Wrapper interface for cloudvolume read access to bossDB. """ def __init__(self, cv_config=None): self.cv_config = cv_config # Main READ interface method ...
cvdb/cloudvolumedb.py
import numpy as np from cloudvolume import CloudVolume from .cube import Cube from .error import CVDBError class CloudVolumeDB: """ Wrapper interface for cloudvolume read access to bossDB. """ def __init__(self, cv_config=None): self.cv_config = cv_config # Main READ interface method ...
0.863334
0.421373
import os import zipfile import pathlib from time import time from io import BytesIO import requests from psycopg2 import sql from flask import Blueprint, request, jsonify, send_file from app.config import config from app.auth_utils import auth_user from Database.postgres import Postgres_db from Drive.tools import a...
backend/Drive/manage_storage.py
import os import zipfile import pathlib from time import time from io import BytesIO import requests from psycopg2 import sql from flask import Blueprint, request, jsonify, send_file from app.config import config from app.auth_utils import auth_user from Database.postgres import Postgres_db from Drive.tools import a...
0.252016
0.093306
import sys from instrument_lookup import hex_to_instrument, instrument_to_hex class MIDIFile: MTrk = ["4d", "54", "72", "6b"] MThd = ["4d", "54", "68", "06"] END_TRACK = ["ff", "2f", "00"] def __init__(self): self.hex_array = [] self.meta_events = {} def read_file(self, input_fi...
pymiditools.py
import sys from instrument_lookup import hex_to_instrument, instrument_to_hex class MIDIFile: MTrk = ["4d", "54", "72", "6b"] MThd = ["4d", "54", "68", "06"] END_TRACK = ["ff", "2f", "00"] def __init__(self): self.hex_array = [] self.meta_events = {} def read_file(self, input_fi...
0.434221
0.452475
import datetime import json import os from flask import jsonify from flask import request from flask.views import MethodView from common.config import DOC_DIR, DOC_TEMPLATE_DIR from common.constant import EFFECT_TIME_NOW class ResignDirectorHandler(MethodView): methods = ['GET', 'POST'] def post(self): ...
handlers/resign_director_handler.py
import datetime import json import os from flask import jsonify from flask import request from flask.views import MethodView from common.config import DOC_DIR, DOC_TEMPLATE_DIR from common.constant import EFFECT_TIME_NOW class ResignDirectorHandler(MethodView): methods = ['GET', 'POST'] def post(self): ...
0.139543
0.160496
import json import argparse import string def get_parser(): # Get parser for command line arguments. parser = argparse.ArgumentParser(description="Twitter Downloader") parser.add_argument("-fn", "--fname", dest="fname") parser.add_argument("-d", ...
pretty_required_json.py
import json import argparse import string def get_parser(): # Get parser for command line arguments. parser = argparse.ArgumentParser(description="Twitter Downloader") parser.add_argument("-fn", "--fname", dest="fname") parser.add_argument("-d", ...
0.35488
0.134747
from __future__ import absolute_import, print_function import uuid from invenio_pidstore.models import PersistentIdentifier from invenio_records_rest.schemas import Nested, StrictKeysMixin from invenio_records_rest.schemas.fields import DateString, GenFunction, \ SanitizedHTML, SanitizedUnicode from marshmallow i...
invenio_communities/marshmallow/json.py
from __future__ import absolute_import, print_function import uuid from invenio_pidstore.models import PersistentIdentifier from invenio_records_rest.schemas import Nested, StrictKeysMixin from invenio_records_rest.schemas.fields import DateString, GenFunction, \ SanitizedHTML, SanitizedUnicode from marshmallow i...
0.505127
0.17522
import asyncio def merge_nodes(a, b): """Recursively and non-destructively merges two nodes. Returns the newly created node. """ if a is None: return b if b is None: return a if a[0] > b[0]: a, b = b, a return a[0], merge_nodes(b, a[2]), a[1] def pop_node(root):...
skewheap/__init__.py
import asyncio def merge_nodes(a, b): """Recursively and non-destructively merges two nodes. Returns the newly created node. """ if a is None: return b if b is None: return a if a[0] > b[0]: a, b = b, a return a[0], merge_nodes(b, a[2]), a[1] def pop_node(root):...
0.781414
0.661732
import platform import time from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.select import Select from selenium.webdriver.support import expected_conditions as EC from selenium.w...
cuahsi_base/site_element.py
import platform import time from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.select import Select from selenium.webdriver.support import expected_conditions as EC from selenium.w...
0.559771
0.194559
# Import modules import pytest import numpy as np # Import from package from pyswarms.single import GlobalBestPSO, LocalBestPSO, GeneralOptimizerPSO from pyswarms.discrete import BinaryPSO from pyswarms.utils.functions.single_obj import sphere_func from pyswarms.backend.topology import Star, Ring, Pyramid, Random, Von...
tests/optimizers/conftest.py
# Import modules import pytest import numpy as np # Import from package from pyswarms.single import GlobalBestPSO, LocalBestPSO, GeneralOptimizerPSO from pyswarms.discrete import BinaryPSO from pyswarms.utils.functions.single_obj import sphere_func from pyswarms.backend.topology import Star, Ring, Pyramid, Random, Von...
0.721449
0.516291
import cuflow as cu import dip import sot __VERSION__ = "1.0.0" """ RPi dimensions: https://www.raspberrypi.org/documentation/hardware/raspberrypi/mechanical/rpi_MECH_4b_4p0.pdf | GPIO | pin | color | function | | ---- | --- | ------ | ------------------- | | 14 | 8 | yellow | C2C: RESET |...
pihat.py
import cuflow as cu import dip import sot __VERSION__ = "1.0.0" """ RPi dimensions: https://www.raspberrypi.org/documentation/hardware/raspberrypi/mechanical/rpi_MECH_4b_4p0.pdf | GPIO | pin | color | function | | ---- | --- | ------ | ------------------- | | 14 | 8 | yellow | C2C: RESET |...
0.428353
0.438424
import configparser import wmi import csv import logging import logging.handlers import os import sys from ServerObj import ServerObj from Storage import * path_current_directory = os.path.dirname(__file__) path_config_file = os.path.join(path_current_directory, 'config.ini') config = configparser.ConfigPa...
ServerAgent.py
import configparser import wmi import csv import logging import logging.handlers import os import sys from ServerObj import ServerObj from Storage import * path_current_directory = os.path.dirname(__file__) path_config_file = os.path.join(path_current_directory, 'config.ini') config = configparser.ConfigPa...
0.075766
0.037187
from typing import ContextManager from ipywidgets import widgets from puzzle.constraints import constraints from puzzle.problems import problem from puzzle.puzzlepedia import _bind, _common, _widget_util, \ annotation_widget, \ debug_data_widget, meta_problem, table_widget from puzzle.puzzlepedia._bind import wid...
src/puzzle/puzzlepedia/problem_widget.py
from typing import ContextManager from ipywidgets import widgets from puzzle.constraints import constraints from puzzle.problems import problem from puzzle.puzzlepedia import _bind, _common, _widget_util, \ annotation_widget, \ debug_data_widget, meta_problem, table_widget from puzzle.puzzlepedia._bind import wid...
0.632957
0.140661
import json from django.urls import reverse from rest_framework.test import APITestCase, APIClient from core.models import Author from core.tests.factories import AuthorFactory from users.tests.factories import UserFactory, TokenFactory class AuthorUpdateTestCase(APITestCase): def setUp(self): self.clie...
core/tests/test_author_update.py
import json from django.urls import reverse from rest_framework.test import APITestCase, APIClient from core.models import Author from core.tests.factories import AuthorFactory from users.tests.factories import UserFactory, TokenFactory class AuthorUpdateTestCase(APITestCase): def setUp(self): self.clie...
0.431345
0.123471
# Copyright 2020 <NAME> # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ Python version of tokenizer.pl """ import sys import codecs import argparse def io_wrapper(io_str, mode): """ Wrapper for IO stream """ if io_str != "-": std = False stream = codecs.open(io...
utils/tokenizer.py
# Copyright 2020 <NAME> # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ Python version of tokenizer.pl """ import sys import codecs import argparse def io_wrapper(io_str, mode): """ Wrapper for IO stream """ if io_str != "-": std = False stream = codecs.open(io...
0.45641
0.196537
import sqlite3 class UserRepository: def __init__(self, config): connection = config["Database"]["connection"] assert connection self.connection_string = connection def _connection(self): return sqlite3.connect(self.connection_string) def list_user(self): """ ...
back/facades/UserRepository.py
import sqlite3 class UserRepository: def __init__(self, config): connection = config["Database"]["connection"] assert connection self.connection_string = connection def _connection(self): return sqlite3.connect(self.connection_string) def list_user(self): """ ...
0.520496
0.228146
import struct import unittest from datasketch.partition_minhash import PartitionMinHash, BetterWeightedPartitionMinHash class FakeHash(object): def __init__(self, h): ''' Initialize with an integer ''' self.h = h def digest(self): ''' Return the bytes represen...
test/partition_minhash_test.py
import struct import unittest from datasketch.partition_minhash import PartitionMinHash, BetterWeightedPartitionMinHash class FakeHash(object): def __init__(self, h): ''' Initialize with an integer ''' self.h = h def digest(self): ''' Return the bytes represen...
0.709623
0.572185
import six import logging import numpy as np import re if not six.PY2: basestring = str def is_string(s): """判断是否是字符串 """ return isinstance(s, basestring) def strQ2B(ustring): """全角符号转对应的半角符号 """ rstring = '' for uchar in ustring: inside_code = ord(uchar) # 全角空格直接转...
bert4keras/snippets.py
import six import logging import numpy as np import re if not six.PY2: basestring = str def is_string(s): """判断是否是字符串 """ return isinstance(s, basestring) def strQ2B(ustring): """全角符号转对应的半角符号 """ rstring = '' for uchar in ustring: inside_code = ord(uchar) # 全角空格直接转...
0.334916
0.361306
import pandas as pd import re import os from pptx import Presentation from pptx.util import Inches, Pt from pptx.enum.shapes import MSO_SHAPE from pptx.enum.text import PP_ALIGN from pptx.dml.color import RGBColor from pptx.oxml.xmlchemy import OxmlElement d = '' # Glasswall palette dark_blue ...
upwork-devs/Lwasampijja-Baker/make_ppt.py
import pandas as pd import re import os from pptx import Presentation from pptx.util import Inches, Pt from pptx.enum.shapes import MSO_SHAPE from pptx.enum.text import PP_ALIGN from pptx.dml.color import RGBColor from pptx.oxml.xmlchemy import OxmlElement d = '' # Glasswall palette dark_blue ...
0.519034
0.125762
from django.conf import settings from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from django.contrib import messages from django.core.cache import caches from django.views.decorators.cache import cache_page from django.contrib.postgres.search import SearchVector fro...
posters/views.py
from django.conf import settings from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from django.contrib import messages from django.core.cache import caches from django.views.decorators.cache import cache_page from django.contrib.postgres.search import SearchVector fro...
0.216674
0.061819
import os import warnings import dj_database_url import raven import yaml from django.urls import reverse_lazy from promgen.plugins import apps_from_setuptools from promgen.version import __version__ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os...
promgen/settings.py
import os import warnings import dj_database_url import raven import yaml from django.urls import reverse_lazy from promgen.plugins import apps_from_setuptools from promgen.version import __version__ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os...
0.331444
0.059401
import re import csv import hashlib import numpy as np from .errors import AnnotationsError GENESETS_TIDYCSV_HEADER = [ "gene_set_description", "gene_set_name", "differential_expression" ] def read_gene_sets_tidycsv(gs_locator, context=None): """ Read & parse the Tidy CSV format, applying v...
backend/common/genesets.py
import re import csv import hashlib import numpy as np from .errors import AnnotationsError GENESETS_TIDYCSV_HEADER = [ "gene_set_description", "gene_set_name", "differential_expression" ] def read_gene_sets_tidycsv(gs_locator, context=None): """ Read & parse the Tidy CSV format, applying v...
0.580709
0.475118
from typing import List, Dict, Any from pydantic import ValidationError from starlette.exceptions import HTTPException from robot_server.service.json_api.errors import ErrorResponse, Error, \ ErrorSource class V1HandlerError(Exception): """An exception raised in order to produce a V1BasicResponse response""...
robot-server/robot_server/service/errors.py
from typing import List, Dict, Any from pydantic import ValidationError from starlette.exceptions import HTTPException from robot_server.service.json_api.errors import ErrorResponse, Error, \ ErrorSource class V1HandlerError(Exception): """An exception raised in order to produce a V1BasicResponse response""...
0.857186
0.196209
import time import grovepi class Grove4DigitDisplay: def __init__(self, pin = 5): """ initialize 4 digit display at pin = 5 by default connect to grovePi port D5 """ self.display = pin grovepi.pinMode(self.display, "OUTPUT") grovepi.fourDigit_init(self.display) def setBrightness(self, value = 0): ...
cloudmesh/pi/grove_4_digit_display.py
import time import grovepi class Grove4DigitDisplay: def __init__(self, pin = 5): """ initialize 4 digit display at pin = 5 by default connect to grovePi port D5 """ self.display = pin grovepi.pinMode(self.display, "OUTPUT") grovepi.fourDigit_init(self.display) def setBrightness(self, value = 0): ...
0.39036
0.548915
from typing import ( Optional, Tuple, ) import numpy as np from packaging import version from pandas.core.exchange.dataframe_protocol import ( Buffer, DlpackDeviceType, ) _NUMPY_HAS_DLPACK = version.parse(np.__version__) >= version.parse("1.22.0") class PandasBuffer(Buffer): """ Data in the...
pandas/core/exchange/buffer.py
from typing import ( Optional, Tuple, ) import numpy as np from packaging import version from pandas.core.exchange.dataframe_protocol import ( Buffer, DlpackDeviceType, ) _NUMPY_HAS_DLPACK = version.parse(np.__version__) >= version.parse("1.22.0") class PandasBuffer(Buffer): """ Data in the...
0.871064
0.285339
from __future__ import absolute_import, print_function from django.utils.translation import gettext_lazy as _ from django.conf import settings from django.db import models from django.db.models.signals import post_delete from django.dispatch import receiver from model_utils.models import TimeStampedModel from rest_fr...
src/server/oasisapi/portfolios/models.py
from __future__ import absolute_import, print_function from django.utils.translation import gettext_lazy as _ from django.conf import settings from django.db import models from django.db.models.signals import post_delete from django.dispatch import receiver from model_utils.models import TimeStampedModel from rest_fr...
0.579757
0.069038
import sys import os import argparse import importlib import getpass from datetime import datetime import logging import subprocess import socket import boto3 from click import echo from drift.management.gittools import get_branch, get_commit, get_repo_url, get_git_version from drift.utils import pretty, set_pretty_s...
drift/management/__init__.py
import sys import os import argparse import importlib import getpass from datetime import datetime import logging import subprocess import socket import boto3 from click import echo from drift.management.gittools import get_branch, get_commit, get_repo_url, get_git_version from drift.utils import pretty, set_pretty_s...
0.388618
0.06216
import sys from PyQt5 import QtCore, QtGui, QtWidgets, uic import database_receita from datetime import date, datetime qt_tela_inicial = "telas/tela_gerenciar_fabricacao.ui" Ui_MainWindow, QtBaseClass = uic.loadUiType(qt_tela_inicial) class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): ...
tela_gerenciar_fabricacao.py
import sys from PyQt5 import QtCore, QtGui, QtWidgets, uic import database_receita from datetime import date, datetime qt_tela_inicial = "telas/tela_gerenciar_fabricacao.ui" Ui_MainWindow, QtBaseClass = uic.loadUiType(qt_tela_inicial) class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): ...
0.089338
0.112186
import json import sys import argparse import requests import datetime from markdown import markdown from weasyprint import HTML from thehive4py.api import TheHiveApi HTML_TEMPLATE = u""" <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="./codehilite.css"> <...
case-to-pdf/case2pdf.py
import json import sys import argparse import requests import datetime from markdown import markdown from weasyprint import HTML from thehive4py.api import TheHiveApi HTML_TEMPLATE = u""" <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="./codehilite.css"> <...
0.341143
0.08043
import os import re import redis class RedisClient(object): """ Redis Client """ WIKI_AUGMENTED_DB = 3 WIKI_PAGE_DB = 4 WIKI_SEARCH_DB = 5 def __init__(self, db: int = 0, decode_responses: bool = True): """ Created: 29-May-2019 ...
python/base/core/dmo/redis_client.py
import os import re import redis class RedisClient(object): """ Redis Client """ WIKI_AUGMENTED_DB = 3 WIKI_PAGE_DB = 4 WIKI_SEARCH_DB = 5 def __init__(self, db: int = 0, decode_responses: bool = True): """ Created: 29-May-2019 ...
0.509276
0.1178
from fabric.api import env from fabric.api import settings from cloudferrylib.utils import cmd_cfg from cloudferrylib.utils import driver_transporter from cloudferrylib.utils import rbd_util from cloudferrylib.utils import utils LOG = utils.get_log(__name__) class SSHCephToCeph(driver_transporter.DriverTransport...
cloudferrylib/utils/drivers/ssh_ceph_to_ceph.py
from fabric.api import env from fabric.api import settings from cloudferrylib.utils import cmd_cfg from cloudferrylib.utils import driver_transporter from cloudferrylib.utils import rbd_util from cloudferrylib.utils import utils LOG = utils.get_log(__name__) class SSHCephToCeph(driver_transporter.DriverTransport...
0.258794
0.128662
import logging from argparse import ArgumentParser from datetime import datetime from lib.base_test import StatelessTest from lib.gtpu import GTPU from lib.utils import list_port_status from lib.xnt import analysis_report_pcap from scapy.layers.all import IP, TCP, UDP, Ether from trex_stl_lib.api import STLPktBuilder...
trex-scripts/tests/int_single_flow.py
import logging from argparse import ArgumentParser from datetime import datetime from lib.base_test import StatelessTest from lib.gtpu import GTPU from lib.utils import list_port_status from lib.xnt import analysis_report_pcap from scapy.layers.all import IP, TCP, UDP, Ether from trex_stl_lib.api import STLPktBuilder...
0.561696
0.110136
import backend.container_service.cluster_tools.constants from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Tool', fields=[ ...
bcs-ui/backend/container_service/cluster_tools/migrations/0001_initial.py
import backend.container_service.cluster_tools.constants from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Tool', fields=[ ...
0.416559
0.197987
import talos as ta import pandas as pd from talos.model.normalizers import lr_normalizer from keras.models import Sequential from keras.layers import Dropout, Dense from keras.optimizers import Adam, Nadam from keras.activations import softmax from keras.losses import categorical_crossentropy, logcosh x, y = ta.datas...
playground/talos_reporting_sample.py
import talos as ta import pandas as pd from talos.model.normalizers import lr_normalizer from keras.models import Sequential from keras.layers import Dropout, Dense from keras.optimizers import Adam, Nadam from keras.activations import softmax from keras.losses import categorical_crossentropy, logcosh x, y = ta.datas...
0.879082
0.392599
import os import numpy as np import tensorflow as tf from tensorflow.keras import Model from tensorflow.estimator import ( Estimator, ModeKeys, TrainSpec, EvalSpec, EstimatorSpec, ) from galileo.platform.default_values import DefaultValues from galileo.platform.log import log from galileo.platfor...
galileo/framework/tf/python/estimator_trainer.py
import os import numpy as np import tensorflow as tf from tensorflow.keras import Model from tensorflow.estimator import ( Estimator, ModeKeys, TrainSpec, EvalSpec, EstimatorSpec, ) from galileo.platform.default_values import DefaultValues from galileo.platform.log import log from galileo.platfor...
0.74512
0.210868
import builtins import inspect import sys from collections import deque from typing import Any, Callable, Dict, List, Optional, Union, cast from pydoc_fork import settings from pydoc_fork.inspector.custom_types import TypeLike from pydoc_fork.inspector.utils import ( _split_list, classify_class_attrs, clas...
pydoc_fork/reporter/format_class.py
import builtins import inspect import sys from collections import deque from typing import Any, Callable, Dict, List, Optional, Union, cast from pydoc_fork import settings from pydoc_fork.inspector.custom_types import TypeLike from pydoc_fork.inspector.utils import ( _split_list, classify_class_attrs, clas...
0.593374
0.136206
from flask import Flask from flask import render_template from flask import Response import sqlite3 import random import io from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure app = Flask(__name__) @app.route("/") def cv_index(): cvs = get_cv() re...
main.py
from flask import Flask from flask import render_template from flask import Response import sqlite3 import random import io from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure app = Flask(__name__) @app.route("/") def cv_index(): cvs = get_cv() re...
0.404155
0.155431
from typing import Tuple import matplotlib.pyplot as plt import pandas as pd from polar_bearings.opt_pah_finder_robotics.potential_field_planning import ( potential_field_planning, ) def main( filepath: str = "ice_thickness_01-01-2020.csv", rescaling_factor: int = 2, grid_size: float = 0.1, robo...
polar_bearings/opt_pah_finder_robotics/navigate_ice.py
from typing import Tuple import matplotlib.pyplot as plt import pandas as pd from polar_bearings.opt_pah_finder_robotics.potential_field_planning import ( potential_field_planning, ) def main( filepath: str = "ice_thickness_01-01-2020.csv", rescaling_factor: int = 2, grid_size: float = 0.1, robo...
0.937139
0.640776
from QuantTorch.functions.terner_connect import TernaryConnectDeterministic, TernaryConnectStochastic import torch import pytest def equals(a, b, epsilon=1e-12): return torch.all(torch.lt( torch.abs(a-b), epsilon )) def test_terner_connect_det_forward(): x_1 = torch.Tensor([0.75,0.5,0.25,0.0,-1,-0.2]) ...
tests/implementations/Terner/function_test.py
from QuantTorch.functions.terner_connect import TernaryConnectDeterministic, TernaryConnectStochastic import torch import pytest def equals(a, b, epsilon=1e-12): return torch.all(torch.lt( torch.abs(a-b), epsilon )) def test_terner_connect_det_forward(): x_1 = torch.Tensor([0.75,0.5,0.25,0.0,-1,-0.2]) ...
0.735547
0.644589
import os import pytest from intervaltree import Interval from viridian_workflow import self_qc, primers this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, "data", "primers") class StatsTest: def __init__(self, fail): self.fail = fail self.log = [] se...
tests/self_qc_test.py
import os import pytest from intervaltree import Interval from viridian_workflow import self_qc, primers this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, "data", "primers") class StatsTest: def __init__(self, fail): self.fail = fail self.log = [] se...
0.449876
0.703282
import os import sys import logging from argparse import ArgumentParser ROOT = os.path.dirname(os.path.realpath(__file__)) # Try to load modules from our current env first sys.path.insert(0, os.path.join(ROOT, "..")) from burpui_monitor.tools.logging import logger logger.init_logger(config=dict(level=logging.CRITIC...
pkgs/burp-ui-monitor/burpui_monitor-decoy/__main__.py
import os import sys import logging from argparse import ArgumentParser ROOT = os.path.dirname(os.path.realpath(__file__)) # Try to load modules from our current env first sys.path.insert(0, os.path.join(ROOT, "..")) from burpui_monitor.tools.logging import logger logger.init_logger(config=dict(level=logging.CRITIC...
0.294114
0.064418
import argparse import csv import math import pathlib import sys from typing import List from pynapl.APL import APL from pynapl.APLPyConnect import Connection LANGUAGES = ["en", "fr", "es", "pt"] DATA_FOLDER = pathlib.Path(__file__).parent / "data" FILE_NAME_TEMPLATE = "{lang}_trigram_count_filtered.tsv" def init_d...
demos/language_recogniser/recogniser.py
import argparse import csv import math import pathlib import sys from typing import List from pynapl.APL import APL from pynapl.APLPyConnect import Connection LANGUAGES = ["en", "fr", "es", "pt"] DATA_FOLDER = pathlib.Path(__file__).parent / "data" FILE_NAME_TEMPLATE = "{lang}_trigram_count_filtered.tsv" def init_d...
0.627837
0.373762
import filecmp import os import shutil import tempfile import unittest import json_summary_combiner class TestJsonSummaryCombiner(unittest.TestCase): def setUp(self): self._test_data_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'test_data', 'combiner') self._actual_html_dir = t...
ct/py/json_summary_combiner_test.py
import filecmp import os import shutil import tempfile import unittest import json_summary_combiner class TestJsonSummaryCombiner(unittest.TestCase): def setUp(self): self._test_data_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'test_data', 'combiner') self._actual_html_dir = t...
0.363082
0.152694
from heapq import heappush, heappop # The Maze # DFS is faster to get to destination class Solution(object): def hasPath(self, maze, start, destination): """ :type maze: List[List[int]] :type start: List[int] :type destination: List[int] :rtype: bool """ visi...
algorithms/bfs/the_maze.py
from heapq import heappush, heappop # The Maze # DFS is faster to get to destination class Solution(object): def hasPath(self, maze, start, destination): """ :type maze: List[List[int]] :type start: List[int] :type destination: List[int] :rtype: bool """ visi...
0.736021
0.624379
import random humanMales = ['Kharmat', 'Dalba', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] humanFemales = ['Vurnan', 'Ulbuh', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'Share Bhalme', '<NAME>', '<NAME>'] halflingMales = ['<NAME>', '<...
namegen.py
import random humanMales = ['Kharmat', 'Dalba', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] humanFemales = ['Vurnan', 'Ulbuh', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'Share Bhalme', '<NAME>', '<NAME>'] halflingMales = ['<NAME>', '<...
0.084259
0.095687
# Import necessary libraries import subprocess # Runs commands and gets output import socket # Used to test internet connection import os # Used to run system commands and checks if run as root user import getpass # Used to hide user input in password field # Check if the user that executed this program is...
software/python/basics/setup_wpa_enterprise.py
# Import necessary libraries import subprocess # Runs commands and gets output import socket # Used to test internet connection import os # Used to run system commands and checks if run as root user import getpass # Used to hide user input in password field # Check if the user that executed this program is...
0.263315
0.077832
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from wishlist import exceptions class WishListItem(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='wishlist_items', verbose_name=_('Owner'), on_d...
wishlist/models.py
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from wishlist import exceptions class WishListItem(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='wishlist_items', verbose_name=_('Owner'), on_d...
0.565299
0.07333
from rnd_game import RNDGame from player import Player from rpsls_game import RockPaperScissorsLizardSpockGame def enter_username(): while True: try: username_input = str(input().strip()) return username_input break except: print("please insert a use...
menu_starter.py
from rnd_game import RNDGame from player import Player from rpsls_game import RockPaperScissorsLizardSpockGame def enter_username(): while True: try: username_input = str(input().strip()) return username_input break except: print("please insert a use...
0.293607
0.220531
import itertools import random import subprocess import os from absl import logging, flags, app from multiprocessing import Queue, Manager from pathos import multiprocessing import traceback import time import sys log_dir = sys.argv[1] num_gpus = 2 max_worker_num = num_gpus * 1 + 1 nb_train_steps = 400 meta_update_freq...
run_socialbot_evals.py
import itertools import random import subprocess import os from absl import logging, flags, app from multiprocessing import Queue, Manager from pathos import multiprocessing import traceback import time import sys log_dir = sys.argv[1] num_gpus = 2 max_worker_num = num_gpus * 1 + 1 nb_train_steps = 400 meta_update_freq...
0.239883
0.105995
import matplotlib.pyplot as plt import matplotlib import numpy as np import pandautils as pup from sklearn.metrics import roc_curve import cPickle def plotROC(test_ntuple_path):#, picklename): ''' Definition: ----------- Plot a ROC curve comparison between the old mv2c10 contained in the branch and the newly eval...
trackjets/plotROC.py
import matplotlib.pyplot as plt import matplotlib import numpy as np import pandautils as pup from sklearn.metrics import roc_curve import cPickle def plotROC(test_ntuple_path):#, picklename): ''' Definition: ----------- Plot a ROC curve comparison between the old mv2c10 contained in the branch and the newly eval...
0.439627
0.457621
import csv import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.patches import Rectangle FRAME_DELTA = 500 # milliseconds animationYear = 1999 fig, ax, = plt.subplots() animationTitle = ax.text(0.5, 0.85, "", transform=ax.transAxes, ha="center", fontsize=20)...
Food Imports/foodImportsAnimation.py
import csv import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.patches import Rectangle FRAME_DELTA = 500 # milliseconds animationYear = 1999 fig, ax, = plt.subplots() animationTitle = ax.text(0.5, 0.85, "", transform=ax.transAxes, ha="center", fontsize=20)...
0.347759
0.530723
from .Dark_Neuron_CNN import Dark_Neuron import tensorflow as tf # Powerful Framework for Deep Learning import os # For Searching Folder within the system from .models import Create_Model, Train_Model # Script containing Different Models from .Preprocessing_Image import P...
build/lib/DarkNeurons/Classification.py
from .Dark_Neuron_CNN import Dark_Neuron import tensorflow as tf # Powerful Framework for Deep Learning import os # For Searching Folder within the system from .models import Create_Model, Train_Model # Script containing Different Models from .Preprocessing_Image import P...
0.636127
0.389605
from django.shortcuts import render from django.views import View import requests ACCUWEATHER_API_KEY = "<KEY>" ACCUWEATHER_CITY_URL = "http://dataservice.accuweather.com/locations/v1/cities/search?apikey={}&q={}&language=en-us" ACCUWEATHER_WEATHER_URL = "http://dataservice.accuweather.com/currentconditions/v1/{}?api...
weather/weather/views.py
from django.shortcuts import render from django.views import View import requests ACCUWEATHER_API_KEY = "<KEY>" ACCUWEATHER_CITY_URL = "http://dataservice.accuweather.com/locations/v1/cities/search?apikey={}&q={}&language=en-us" ACCUWEATHER_WEATHER_URL = "http://dataservice.accuweather.com/currentconditions/v1/{}?api...
0.586523
0.087759
class Queue: """ Queue is a collection of entities that are maintained in a sequence and can be modified by the addition of entities at one end of the sequence and removal from the other end of the sequence. The order in which elements come off of a queue are First In, First Out (FIFO). https://...
queue/library/queue.py
class Queue: """ Queue is a collection of entities that are maintained in a sequence and can be modified by the addition of entities at one end of the sequence and removal from the other end of the sequence. The order in which elements come off of a queue are First In, First Out (FIFO). https://...
0.898944
0.912942
import re from datetime import datetime from sqlalchemy import Column,Integer, String, DateTime, Sequence, Index, \ UniqueConstraint from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Lexicon(Base): __tablename__ = 'lexicon_2_1' id = Column(Integer, Sequence('user...
utils/dictionary/lexicon.py
import re from datetime import datetime from sqlalchemy import Column,Integer, String, DateTime, Sequence, Index, \ UniqueConstraint from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Lexicon(Base): __tablename__ = 'lexicon_2_1' id = Column(Integer, Sequence('user...
0.452778
0.24159
import cv2 import numpy as np from src.DroneVision.DroneVision_src.imgProcessing.frameTools.frameTools import GetShape from src.DroneVision.DroneVision_src.hardware.imageTools import GetImage, RealTimePlot from src.DroneVision.DroneVision_src.hardware.PyQtImage import PyQtImage from CameraCalibration import CameraCalib...
src/DroneVision/DroneVision_src/imgProcessing/CameraCalibration/StereoCalibration.py
import cv2 import numpy as np from src.DroneVision.DroneVision_src.imgProcessing.frameTools.frameTools import GetShape from src.DroneVision.DroneVision_src.hardware.imageTools import GetImage, RealTimePlot from src.DroneVision.DroneVision_src.hardware.PyQtImage import PyQtImage from CameraCalibration import CameraCalib...
0.570092
0.273975
from sys import stdout, stderr import csv from argparse import ArgumentParser from io import TextIOWrapper from copy import deepcopy from datetime import timedelta from dateutil import parser def command_line_options()->dict: parser = ArgumentParser(prog="obd_log_to_csv", description="""Te...
obd_log_to_csv/csv_to_delta_csv.py
from sys import stdout, stderr import csv from argparse import ArgumentParser from io import TextIOWrapper from copy import deepcopy from datetime import timedelta from dateutil import parser def command_line_options()->dict: parser = ArgumentParser(prog="obd_log_to_csv", description="""Te...
0.504394
0.374648
DOCUMENTATION = ''' --- module: foreman_image short_description: - Manage Foreman images using Foreman API v2. description: - Create, update and and delete Foreman images using Foreman API v2 options: name: description: Image name as used in Foreman required: true state: description: image state re...
foreman_image.py
DOCUMENTATION = ''' --- module: foreman_image short_description: - Manage Foreman images using Foreman API v2. description: - Create, update and and delete Foreman images using Foreman API v2 options: name: description: Image name as used in Foreman required: true state: description: image state re...
0.564339
0.452657
from django.contrib.auth import get_user_model, authenticate from rest_framework import serializers from core.models import CommunityMember, Community class RegisterSerializer(serializers.ModelSerializer): """ serializer for register class """ class Meta: model = get_user_model() fields = ('n...
app/userauth/serializers.py
from django.contrib.auth import get_user_model, authenticate from rest_framework import serializers from core.models import CommunityMember, Community class RegisterSerializer(serializers.ModelSerializer): """ serializer for register class """ class Meta: model = get_user_model() fields = ('n...
0.695028
0.071656
# imports __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/tinkeringtech/rda5807m.git" import time # Registers definitions FREQ_STEPS = 10 RADIO_REG_CHIPID = 0x00 RADIO_REG_CTRL = 0x02 RADIO_REG_CTRL_OUTPUT = 0x8000 RADIO_REG_CTRL_UNMUTE = 0x4000 RADIO_REG_CTRL_MONO = 0x2000 RADIO_REG_CTRL_BASS = 0x1000 ...
rda5807m.py
# imports __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/tinkeringtech/rda5807m.git" import time # Registers definitions FREQ_STEPS = 10 RADIO_REG_CHIPID = 0x00 RADIO_REG_CTRL = 0x02 RADIO_REG_CTRL_OUTPUT = 0x8000 RADIO_REG_CTRL_UNMUTE = 0x4000 RADIO_REG_CTRL_MONO = 0x2000 RADIO_REG_CTRL_BASS = 0x1000 ...
0.551815
0.38798
import numpy as np import tensorflow as tf from keras import layers, models from keras.utils.generic_utils import register_keras_serializable from keras.utils.tf_utils import shape_type_conversion from scipy import ndimage from vit_keras import vit from ...backbone.utils import patch_config from ...common import ConvBn...
segme/model/tri_trans/transformer.py
import numpy as np import tensorflow as tf from keras import layers, models from keras.utils.generic_utils import register_keras_serializable from keras.utils.tf_utils import shape_type_conversion from scipy import ndimage from vit_keras import vit from ...backbone.utils import patch_config from ...common import ConvBn...
0.926204
0.363816
from cores import cor, limpa from espacos import tio, tracos def calculoImposto(taxas): #informações das ações acao = input('Digite o código da ação: ') valorAcao = float(input('Digite o valor da operação: ')) tipo = input('C/V? ').upper() print() #Cálculo do imposto porcentagemL = taxas[0...
Pacote download/ImpostoAcoes.py
from cores import cor, limpa from espacos import tio, tracos def calculoImposto(taxas): #informações das ações acao = input('Digite o código da ação: ') valorAcao = float(input('Digite o valor da operação: ')) tipo = input('C/V? ').upper() print() #Cálculo do imposto porcentagemL = taxas[0...
0.262369
0.436862
import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from persine.bridges.youtube import YoutubeBridge @pytest.fixture def driver(): options = Options() options.add_argument("--headless") options.add_argument("--mute-audio") # options.add_extension("ublock...
tests/bridges/test_yt_bridge.py
import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from persine.bridges.youtube import YoutubeBridge @pytest.fixture def driver(): options = Options() options.add_argument("--headless") options.add_argument("--mute-audio") # options.add_extension("ublock...
0.519521
0.325815
__author__ = "Alex 'CubOfJudahsLion' Feterman" __url__ = ("blender", "http://www.blender.org", "Author's homepage, http://geocities.com/cubofjudahslion") __version__ = "0.1.2" __bpydoc__ = """\ xmesh_import.py | Python Script for Blender3D | imports a VegaStrike .xmesh Copyright (C)2005 Alex 'CubOfJudahsLion' Feterma...
vegastrike/objconv/blender_xmesh_import.py
__author__ = "Alex 'CubOfJudahsLion' Feterman" __url__ = ("blender", "http://www.blender.org", "Author's homepage, http://geocities.com/cubofjudahslion") __version__ = "0.1.2" __bpydoc__ = """\ xmesh_import.py | Python Script for Blender3D | imports a VegaStrike .xmesh Copyright (C)2005 Alex 'CubOfJudahsLion' Feterma...
0.343892
0.112113
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed un...
utilities.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed un...
0.870817
0.507812
import utils from utils.unit_conversions import lin_to_db, db_to_lin, kft_to_km import matplotlib.pyplot as plt import numpy as np from scipy import stats import seaborn as sns import atm import prop import detector def make_all_figures(close_figs=False): """ Call all the figure generators for this chapter ...
make_figures/chapter3.py
import utils from utils.unit_conversions import lin_to_db, db_to_lin, kft_to_km import matplotlib.pyplot as plt import numpy as np from scipy import stats import seaborn as sns import atm import prop import detector def make_all_figures(close_figs=False): """ Call all the figure generators for this chapter ...
0.840848
0.564339
import sys from sys import stderr import argparse import yaml import fontforge parser = argparse.ArgumentParser(description='Merges glyphs from ' 'several fonts, as specified in config.') parser.add_argument('-c', '--config', type=str, required=False, help='Config file in json or yml format. If misse...
bin/font_merge.py
import sys from sys import stderr import argparse import yaml import fontforge parser = argparse.ArgumentParser(description='Merges glyphs from ' 'several fonts, as specified in config.') parser.add_argument('-c', '--config', type=str, required=False, help='Config file in json or yml format. If misse...
0.193757
0.070592
import json import logging import voluptuous as vol from homeassistant.components.media_player import ( DEVICE_CLASS_SPEAKER, SUPPORT_PLAY_MEDIA, MediaPlayerDevice, ) from homeassistant.const import ATTR_ENTITY_ID from homeassistant.helpers import config_validation as cv from homeassistant.helpers.dispatch...
custom_components/fullykiosk/media_player.py
import json import logging import voluptuous as vol from homeassistant.components.media_player import ( DEVICE_CLASS_SPEAKER, SUPPORT_PLAY_MEDIA, MediaPlayerDevice, ) from homeassistant.const import ATTR_ENTITY_ID from homeassistant.helpers import config_validation as cv from homeassistant.helpers.dispatch...
0.661923
0.084003
import cv2 from __init__ import Square, predictor, detector, vfps, size from facefrontal import facefrontal, warp_mapping import numpy as np padw = 95 detw = 130 def getGaussianPyr(img, layers): g = img.astype(np.float64) pyramid = [g] for i in range(layers): g = cv2.pyrDown(g) ...
composite.py
import cv2 from __init__ import Square, predictor, detector, vfps, size from facefrontal import facefrontal, warp_mapping import numpy as np padw = 95 detw = 130 def getGaussianPyr(img, layers): g = img.astype(np.float64) pyramid = [g] for i in range(layers): g = cv2.pyrDown(g) ...
0.533154
0.356195
import numpy as np import torch class ReplayBuffer(object): """Buffer to store environment transitions.""" def __init__(self, obs_shape, t_obs_shape, action_shape, capacity, device): self.capacity = capacity self.device = device # the proprioceptive obs is stored as float32, pixels o...
buffers/replay_buffer.py
import numpy as np import torch class ReplayBuffer(object): """Buffer to store environment transitions.""" def __init__(self, obs_shape, t_obs_shape, action_shape, capacity, device): self.capacity = capacity self.device = device # the proprioceptive obs is stored as float32, pixels o...
0.826046
0.407923
from ..api import Extension, helpers from ..log import logger from ..templates import isort_cfg, pre_commit_config class PreCommit(Extension): """Generate pre-commit configuration file""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to p...
.eggs/PyScaffold-3.1-py3.9.egg/pyscaffold/extensions/pre_commit.py
from ..api import Extension, helpers from ..log import logger from ..templates import isort_cfg, pre_commit_config class PreCommit(Extension): """Generate pre-commit configuration file""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to p...
0.765769
0.13134
from autosense.autodiff.autotensor import autoTensor, Node import torch from autosense.neural.param import Weight, Initializer import autosense.autodiff.functional as F import torch.nn.init as torchInit class Layer(object): """Abstract class that is inherited by all types of layers""" def __call__(self): ...
autosense/neural/layers.py
from autosense.autodiff.autotensor import autoTensor, Node import torch from autosense.neural.param import Weight, Initializer import autosense.autodiff.functional as F import torch.nn.init as torchInit class Layer(object): """Abstract class that is inherited by all types of layers""" def __call__(self): ...
0.890604
0.33292
import numpy as np from scipy.special import lpmv, gamma, hyp1f1, legendre from scipy.special.orthogonal import genlaguerre from scipy.misc import factorial import sh, spf # default parameters values _default_radial_order = spf._default_radial_order _default_angular_rank = sh._default_rank _default_zeta = spf._defau...
qspace/bases/mspf.py
import numpy as np from scipy.special import lpmv, gamma, hyp1f1, legendre from scipy.special.orthogonal import genlaguerre from scipy.misc import factorial import sh, spf # default parameters values _default_radial_order = spf._default_radial_order _default_angular_rank = sh._default_rank _default_zeta = spf._defau...
0.90198
0.571527
from selenium import webdriver from time import sleep class Filler(object): def __init__(self, key_pairs, submit_element, url_list, testing_mode): self.testing_mode = testing_mode self.key_pairs = key_pairs self.submit_element = submit_element self.url_list = url_list self....
automator/filler.py
from selenium import webdriver from time import sleep class Filler(object): def __init__(self, key_pairs, submit_element, url_list, testing_mode): self.testing_mode = testing_mode self.key_pairs = key_pairs self.submit_element = submit_element self.url_list = url_list self....
0.212722
0.059921
import os import sys import fcntl import errno import subprocess import typing import threading from . import utils, const, _pidlock from .exceptions import UpdaterInvalidHookCommandError def __run_command(command): def _fthread(file): while True: line = file.readline() if not line...
svupdater/hook.py
import os import sys import fcntl import errno import subprocess import typing import threading from . import utils, const, _pidlock from .exceptions import UpdaterInvalidHookCommandError def __run_command(command): def _fthread(file): while True: line = file.readline() if not line...
0.23926
0.101411
from django.conf import settings from django.conf.urls import include, url from django.views.decorators.cache import cache_page from .feeds import ArticleFeed from .views import SourceSearchView, HomepageView, SlackMessageView from haystack.forms import SearchForm from haystack.query import SearchQuerySet from haystac...
source/base/urls.py
from django.conf import settings from django.conf.urls import include, url from django.views.decorators.cache import cache_page from .feeds import ArticleFeed from .views import SourceSearchView, HomepageView, SlackMessageView from haystack.forms import SearchForm from haystack.query import SearchQuerySet from haystac...
0.358241
0.11353
# See TRANSFORMATIONS.md file for details import json from pierky.p2es.errors import P2ESError # Parse list of conditions c against data d. # Returns: True | False (conditions matched / did not match). # Raises exceptions: yes. def parse_conditions_list(c, d): if not c: raise P2ESError('Empty list') ...
pierky/p2es/transformations.py
# See TRANSFORMATIONS.md file for details import json from pierky.p2es.errors import P2ESError # Parse list of conditions c against data d. # Returns: True | False (conditions matched / did not match). # Raises exceptions: yes. def parse_conditions_list(c, d): if not c: raise P2ESError('Empty list') ...
0.569613
0.320476
class WarthogError(Exception): """Base for all errors raised by the Warthog library.""" def __init__(self, msg): super(WarthogError, self).__init__() self.msg = msg def __str__(self): return self.msg class WarthogConfigError(WarthogError): """Base for errors raised while pars...
warthog/exceptions.py
class WarthogError(Exception): """Base for all errors raised by the Warthog library.""" def __init__(self, msg): super(WarthogError, self).__init__() self.msg = msg def __str__(self): return self.msg class WarthogConfigError(WarthogError): """Base for errors raised while pars...
0.930553
0.064477
import logging from util.bleu import Bleu # validating metrics: bleu (referenced open codes on Github) class MetricWrapper: " Validate Metrics wrapper. " def __init__(self, index2words, start_symbol, end_symbol, pad_symbol, metric=Bleu()): ''' Args: index2words: (dict)...
util/metricwrapper.py
import logging from util.bleu import Bleu # validating metrics: bleu (referenced open codes on Github) class MetricWrapper: " Validate Metrics wrapper. " def __init__(self, index2words, start_symbol, end_symbol, pad_symbol, metric=Bleu()): ''' Args: index2words: (dict)...
0.489503
0.237852
from django.template.base import VariableDoesNotExist EXCLUDE_EXCEPTIONS = [ VariableDoesNotExist, ] # Lowercase only EXCLUDE_PHRASES = [ 'invalid http_host header', ] def filter_exc_by_type(record): """Exclude blacklisted exception types.""" if record.exc_info: exc = record.exc_info[1] ...
webapp/webapp/settings/log/config.py
from django.template.base import VariableDoesNotExist EXCLUDE_EXCEPTIONS = [ VariableDoesNotExist, ] # Lowercase only EXCLUDE_PHRASES = [ 'invalid http_host header', ] def filter_exc_by_type(record): """Exclude blacklisted exception types.""" if record.exc_info: exc = record.exc_info[1] ...
0.558086
0.099602
""" collect network device data via napalm and write it to influxdb """ import logging from influxdb import InfluxDBClient from napalm import get_network_driver from .get_interfaces_counters import get_interfaces_counters from .get_optics import get_optics class NapalmInflux(object): """ the NapalmInflux c...
napalm_influx/napalm_influx.py
""" collect network device data via napalm and write it to influxdb """ import logging from influxdb import InfluxDBClient from napalm import get_network_driver from .get_interfaces_counters import get_interfaces_counters from .get_optics import get_optics class NapalmInflux(object): """ the NapalmInflux c...
0.538255
0.294373
from itertools import combinations from fcapsy.decorators import metadata from fcapsy import Concept, Context @metadata(name='RiceSiffConcepts', short_name='RSConcepts') def concept_subset(context: Context, similarity_measure) -> list: """ Experimental implementation of Rice, <NAME>., and <NAME>. "Cluste...
fcapsy/algorithms/rice_siff.py
from itertools import combinations from fcapsy.decorators import metadata from fcapsy import Concept, Context @metadata(name='RiceSiffConcepts', short_name='RSConcepts') def concept_subset(context: Context, similarity_measure) -> list: """ Experimental implementation of Rice, <NAME>., and <NAME>. "Cluste...
0.770465
0.284999
import uuid import django.contrib.postgres.indexes import django.contrib.postgres.search import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("backend", "0001"), ] operations = [ migrations.CreateModel( ...
{{ cookiecutter.project_slug }}/backend/migrations/0002.py
import uuid import django.contrib.postgres.indexes import django.contrib.postgres.search import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("backend", "0001"), ] operations = [ migrations.CreateModel( ...
0.446012
0.170819
import os from oscar.defaults import * from oscar import OSCAR_MAIN_TEMPLATE_DIR from oscar import get_core_apps from decouple import config, Csv import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SITE...
oscar_project/settings.py
import os from oscar.defaults import * from oscar import OSCAR_MAIN_TEMPLATE_DIR from oscar import get_core_apps from decouple import config, Csv import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SITE...
0.368974
0.063832
import argparse import json import os import sys import time import requests MAX_FAIL = 5 PAGESIZE = 2000 VERSION = 0.1 # Interval in seconds between successive requests WAIT_PERIOD = 5 class OutputManager: def __init__(self, verbose=False): self.verbose = verbose def print(self, string): if...
nvdget.py
import argparse import json import os import sys import time import requests MAX_FAIL = 5 PAGESIZE = 2000 VERSION = 0.1 # Interval in seconds between successive requests WAIT_PERIOD = 5 class OutputManager: def __init__(self, verbose=False): self.verbose = verbose def print(self, string): if...
0.209227
0.100392
from Crypto.Cipher import AES from Crypto import Random from ironic_neutron_plugin import config from neutron.db import model_base from neutron.db import models_v2 from neutron.openstack.common import log as logging import sqlalchemy as sa from sqlalchemy import orm as sa_orm import base64 LOG = logging.getLogger...
ironic_neutron_plugin/db/models.py
from Crypto.Cipher import AES from Crypto import Random from ironic_neutron_plugin import config from neutron.db import model_base from neutron.db import models_v2 from neutron.openstack.common import log as logging import sqlalchemy as sa from sqlalchemy import orm as sa_orm import base64 LOG = logging.getLogger...
0.609408
0.191252