code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import argparse
import os
from colorama import Fore, Style, init as coloramainit
import sys
def osType():
osCheck=sys.platform
if osCheck == 'linux':
return "Linux"
elif osCheck == 'win32':
return "Windows"
elif osCheck == "darwin":
return "MacOS"
else:
return "Unkno... | scavenger.py | import argparse
import os
from colorama import Fore, Style, init as coloramainit
import sys
def osType():
osCheck=sys.platform
if osCheck == 'linux':
return "Linux"
elif osCheck == 'win32':
return "Windows"
elif osCheck == "darwin":
return "MacOS"
else:
return "Unkno... | 0.091725 | 0.061537 |
from datetime import datetime
from discord import Embed
from utils.classes import Hero, Const, Player, Stats, Team
from utils import config, library
from utils.library import leagues
def add_thumbnail(hero: Hero, embed):
ext = '.png'
thumb_url = 'https://nexuscompendium.com/images/portraits/'
hero_name =... | utils/library/embeds.py | from datetime import datetime
from discord import Embed
from utils.classes import Hero, Const, Player, Stats, Team
from utils import config, library
from utils.library import leagues
def add_thumbnail(hero: Hero, embed):
ext = '.png'
thumb_url = 'https://nexuscompendium.com/images/portraits/'
hero_name =... | 0.325092 | 0.167951 |
import csv
lines = ['LINE_WN', 'LINE_WM', 'LINE_WSEA', 'LINE_WS', 'LINE_P', 'LINE_S',
'LINE_T', 'LINE_N', 'LINE_I', 'LINE_PX', 'LINE_NW', 'LINE_J', 'LINE_SL']
class GlobalVariables:
def __init__(self):
self.LinesStations = {} # 各營運路線車站於運行圖中的位置,用於運行線的繪製
self.LinesStationsFor... | basic_data.py | import csv
lines = ['LINE_WN', 'LINE_WM', 'LINE_WSEA', 'LINE_WS', 'LINE_P', 'LINE_S',
'LINE_T', 'LINE_N', 'LINE_I', 'LINE_PX', 'LINE_NW', 'LINE_J', 'LINE_SL']
class GlobalVariables:
def __init__(self):
self.LinesStations = {} # 各營運路線車站於運行圖中的位置,用於運行線的繪製
self.LinesStationsFor... | 0.098985 | 0.202759 |
import shutil
import os
import mimetypes
import magic
from uuid import UUID
from pathlib import Path
from muria import config, logger
class FormStore(object):
"""
Store file upload via mutlipart/form-data request.
Currently does not support "multiple" files input,
only save one file per field name.
... | muria/util/file.py |
import shutil
import os
import mimetypes
import magic
from uuid import UUID
from pathlib import Path
from muria import config, logger
class FormStore(object):
"""
Store file upload via mutlipart/form-data request.
Currently does not support "multiple" files input,
only save one file per field name.
... | 0.36376 | 0.128936 |
from protocolbuffers import Consts_pb2
from interactions import ParticipantType
from interactions.payment.payment_info import PaymentBusinessRevenueType, BusinessPaymentInfo
from sims4.tuning.tunable import AutoFactoryInit, HasTunableSingletonFactory, TunableEnumEntry, TunableReference, OptionalTunable, TunablePercent
... | S4/S4 Library/simulation/interactions/payment/payment_dest.py | from protocolbuffers import Consts_pb2
from interactions import ParticipantType
from interactions.payment.payment_info import PaymentBusinessRevenueType, BusinessPaymentInfo
from sims4.tuning.tunable import AutoFactoryInit, HasTunableSingletonFactory, TunableEnumEntry, TunableReference, OptionalTunable, TunablePercent
... | 0.618204 | 0.111241 |
from decimal import Decimal
import pytest
from brownie import Contract
from brownie import accounts
from brownie import web3
from hexbytes import HexBytes
from web3 import contract
from config.constants import ARB_ETH_USD_CHAINLINK
from config.constants import ARB_KEEPER_ACL
from config.constants import ARB_SLP_WBTC_... | integration_tests/test_arbitrum_harvester.py | from decimal import Decimal
import pytest
from brownie import Contract
from brownie import accounts
from brownie import web3
from hexbytes import HexBytes
from web3 import contract
from config.constants import ARB_ETH_USD_CHAINLINK
from config.constants import ARB_KEEPER_ACL
from config.constants import ARB_SLP_WBTC_... | 0.41253 | 0.244464 |
from .abstract import (
AbstractDovType,
AbstractDovSubType,
)
class BoorMethode(AbstractDovSubType):
_name = 'boormethode'
_rootpath = './/boring/details/boormethode'
_fields = [{
'name': 'diepte_methode_van',
'source': 'xml',
'sourcefield': '/van',
'definition':... | pydov/types/boring.py | from .abstract import (
AbstractDovType,
AbstractDovSubType,
)
class BoorMethode(AbstractDovSubType):
_name = 'boormethode'
_rootpath = './/boring/details/boormethode'
_fields = [{
'name': 'diepte_methode_van',
'source': 'xml',
'sourcefield': '/van',
'definition':... | 0.680772 | 0.253405 |
from abc import ABC, abstractmethod
from decimal import Decimal
from ..database.ptf_allocation import PtfAllocation
from ..database.instrument import Instrument
from .. import utils
from .. import datafeed
class PortfolioBaseClass(ABC):
"""
Abstract class used by modules that manage the portfolio costru... | alchemist_lib/portfolio/portfolio.py | from abc import ABC, abstractmethod
from decimal import Decimal
from ..database.ptf_allocation import PtfAllocation
from ..database.instrument import Instrument
from .. import utils
from .. import datafeed
class PortfolioBaseClass(ABC):
"""
Abstract class used by modules that manage the portfolio costru... | 0.715424 | 0.302868 |
from __future__ import annotations
from pathlib import Path
from typing import Union
import requests as req
import logging
import hashlib
import os
class ApiHandler:
class NoAccess(Exception): pass
class Unknown(Exception): pass
_api_handler_hosts = {}
def __init_subclass__(cls, **kwargs: str) -> No... | mc_mod_getter/utils/ApiHandler.py | from __future__ import annotations
from pathlib import Path
from typing import Union
import requests as req
import logging
import hashlib
import os
class ApiHandler:
class NoAccess(Exception): pass
class Unknown(Exception): pass
_api_handler_hosts = {}
def __init_subclass__(cls, **kwargs: str) -> No... | 0.69946 | 0.089773 |
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import matplotlib.colors as mcl
import matplotlib.lines as lines
import matplotlib.text as text
class GraphData():
'''
Attributes
----------
min: int
lowest value across whole dataset
max: int
... | lcs/plot/GraphData.py | import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import matplotlib.colors as mcl
import matplotlib.lines as lines
import matplotlib.text as text
class GraphData():
'''
Attributes
----------
min: int
lowest value across whole dataset
max: int
... | 0.652131 | 0.495361 |
class DL_BM_Arch:
""" Deep Learning Model Class
:param model_type: Type of model to be used for training 3D CNN with MSE loss, 3D CNN with hetreoskedastic aleatoric loss, 3D CNN with a mixture density network (GMM) output
:type model_type: str (required)
:param output_dimension: Number of output nodes for ... | model_selection/dl_models.py | class DL_BM_Arch:
""" Deep Learning Model Class
:param model_type: Type of model to be used for training 3D CNN with MSE loss, 3D CNN with hetreoskedastic aleatoric loss, 3D CNN with a mixture density network (GMM) output
:type model_type: str (required)
:param output_dimension: Number of output nodes for ... | 0.893478 | 0.942401 |
from flask import request
from assemblyline.common import forge
from assemblyline.common.str_utils import safe_str
from assemblyline.odm.models.tagging import Tagging
from assemblyline_ui.config import STORAGE, UI_MESSAGING, config
from assemblyline_ui.api.base import api_login, make_api_response, make_subapi_bluepri... | assemblyline_ui/api/v4/system.py | from flask import request
from assemblyline.common import forge
from assemblyline.common.str_utils import safe_str
from assemblyline.odm.models.tagging import Tagging
from assemblyline_ui.config import STORAGE, UI_MESSAGING, config
from assemblyline_ui.api.base import api_login, make_api_response, make_subapi_bluepri... | 0.566019 | 0.082883 |
import itertools
from collections import ChainMap
from django.contrib.auth import get_user_model
from rest_framework.test import APITestCase
from courses.models import Course
from courses.services import Status, StatusMessage
from courses.tests.base import DatasetMixin, JWTAuthMixin
User = get_user_model()
class R... | calyx/src/courses/tests/views/test_requirement_status_view.py | import itertools
from collections import ChainMap
from django.contrib.auth import get_user_model
from rest_framework.test import APITestCase
from courses.models import Course
from courses.services import Status, StatusMessage
from courses.tests.base import DatasetMixin, JWTAuthMixin
User = get_user_model()
class R... | 0.470007 | 0.280429 |
"""validate utility functions"""
import os
import datetime
from collections import defaultdict
from pysper import util
def test_extract_node_name():
"""simple test of split handling in a path"""
my_node = util.extract_node_name(os.path.join("exy", "abc", "nodes", "my_node"))
assert my_node == "my_node"
... | tests/test_util.py |
"""validate utility functions"""
import os
import datetime
from collections import defaultdict
from pysper import util
def test_extract_node_name():
"""simple test of split handling in a path"""
my_node = util.extract_node_name(os.path.join("exy", "abc", "nodes", "my_node"))
assert my_node == "my_node"
... | 0.66628 | 0.714217 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import pathlib
import pickle
home_path = pathlib.Path('.').resolve()
while home_path.name != "membership_inference_attack":
home_path = home_path.parent
data_path = home_path/'data'
class CategoricalEmbeddings(nn.Module):
def __init__(self, col... | src/models/federal_model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import pathlib
import pickle
home_path = pathlib.Path('.').resolve()
while home_path.name != "membership_inference_attack":
home_path = home_path.parent
data_path = home_path/'data'
class CategoricalEmbeddings(nn.Module):
def __init__(self, col... | 0.917797 | 0.283245 |
import math
import numpy
from phydat import phycon
# Tunneling expressions
def transmission_coefficient(enes, valpha, rxn_freq):
""" Calculate the tunneling transmission coefficients at Es.
"""
kes = ()
for ene in enes:
kes += (_transmission_coefficient(ene, valpha, rxn_freq),)
return ke... | automol/reac/tunnel.py | import math
import numpy
from phydat import phycon
# Tunneling expressions
def transmission_coefficient(enes, valpha, rxn_freq):
""" Calculate the tunneling transmission coefficients at Es.
"""
kes = ()
for ene in enes:
kes += (_transmission_coefficient(ene, valpha, rxn_freq),)
return ke... | 0.781539 | 0.672113 |
import dataclasses
from typing import List, Tuple
@dataclasses.dataclass
class EventRange:
type: str
min_value: int
max_value: int
@dataclasses.dataclass
class Event:
type: str
value: int
class Codec:
"""Encode and decode events.
Useful for declaring what certain ranges of a vocabulary should be us... | mt3/event_codec.py | import dataclasses
from typing import List, Tuple
@dataclasses.dataclass
class EventRange:
type: str
min_value: int
max_value: int
@dataclasses.dataclass
class Event:
type: str
value: int
class Codec:
"""Encode and decode events.
Useful for declaring what certain ranges of a vocabulary should be us... | 0.949681 | 0.614654 |
import usb.core
import usb.util
import time, struct
from hidapi import hidapi
import ctypes
from elftools.elf.elffile import ELFFile
pid_runtime = 0x6080
pid_bootloader = 0x6084
e = ELFFile(open('arcin.elf'))
firmware = ''
for segment in sorted(e.iter_segments(), key = lambda x: x.header.p_paddr):
if segment.he... | autotest.py |
import usb.core
import usb.util
import time, struct
from hidapi import hidapi
import ctypes
from elftools.elf.elffile import ELFFile
pid_runtime = 0x6080
pid_bootloader = 0x6084
e = ELFFile(open('arcin.elf'))
firmware = ''
for segment in sorted(e.iter_segments(), key = lambda x: x.header.p_paddr):
if segment.he... | 0.147801 | 0.122891 |
import re
from aiogram import types
from aiogram.dispatcher import filters, FSMContext
from app.misc import dp, bot
from app.states import FridgeProductState
from app.states.state_fridge_add_photo import FridgeAddPhotoState, FridgeAddPhotoCheckState
from app.states.state_shop_list_product import ShopListProductState
... | app/handlers/callback/add_product_photo.py | import re
from aiogram import types
from aiogram.dispatcher import filters, FSMContext
from app.misc import dp, bot
from app.states import FridgeProductState
from app.states.state_fridge_add_photo import FridgeAddPhotoState, FridgeAddPhotoCheckState
from app.states.state_shop_list_product import ShopListProductState
... | 0.302391 | 0.089296 |
from gengine.app.tests.base import BaseDBTest
from gengine.app.tests.helpers import create_user, create_achievement, create_variable, create_goals, create_goal_properties, create_goal_evaluation_cache
from gengine.app.model import Achievement, User, Goal, Value
class TestEvaluateGoal(BaseDBTest):
def test_comput... | gengine/app/tests_old/test_goal.py | from gengine.app.tests.base import BaseDBTest
from gengine.app.tests.helpers import create_user, create_achievement, create_variable, create_goals, create_goal_properties, create_goal_evaluation_cache
from gengine.app.model import Achievement, User, Goal, Value
class TestEvaluateGoal(BaseDBTest):
def test_comput... | 0.587825 | 0.222986 |
from datetime import timedelta
from json import loads
from typing import Any, Optional
from django.contrib.auth import update_session_auth_hash
from django.db.models.query import QuerySet
from django.db.transaction import atomic
from django.db.utils import IntegrityError
from django.urls import reverse_lazy
from djang... | authentik/core/api/users.py | from datetime import timedelta
from json import loads
from typing import Any, Optional
from django.contrib.auth import update_session_auth_hash
from django.db.models.query import QuerySet
from django.db.transaction import atomic
from django.db.utils import IntegrityError
from django.urls import reverse_lazy
from djang... | 0.798854 | 0.093182 |
import rdflib
import requests
import yaml
import os
import timeit
from collections import defaultdict
from SPARQLWrapper import SPARQLWrapper, JSON, BASIC, POST
from tqdm import tqdm
from acdh_arche_pyutils.utils import (
camel_to_snake,
create_query_sting,
id_from_uri
)
class ArcheApiClient():
"""Mai... | acdh_arche_pyutils/client.py | import rdflib
import requests
import yaml
import os
import timeit
from collections import defaultdict
from SPARQLWrapper import SPARQLWrapper, JSON, BASIC, POST
from tqdm import tqdm
from acdh_arche_pyutils.utils import (
camel_to_snake,
create_query_sting,
id_from_uri
)
class ArcheApiClient():
"""Mai... | 0.661376 | 0.09886 |
def validate_battlefield(field):
num_cells = 0
for row in field:
num_cells += sum(row)
if num_cells != 20:
return False
for row in range(1, 9):
for col in range(1, 9):
if field[row][col] == 1:
if any([field[row-1][col-1] == 1,
... | Python/3 kyu/Battleship Field Validator/validate.py | def validate_battlefield(field):
num_cells = 0
for row in field:
num_cells += sum(row)
if num_cells != 20:
return False
for row in range(1, 9):
for col in range(1, 9):
if field[row][col] == 1:
if any([field[row-1][col-1] == 1,
... | 0.174481 | 0.731119 |
import os
import pandas as pd
import numpy as np
import random
from CellData import CellData
from scipy import stats
# For reproducibility
random.seed(0)
np.random.seed(0)
os.chdir(open("../data_dir").read().strip())
# Load fixed order of perts and cell types
perts = pd.read_csv("Hodos/their_data/hodos_data_large_ten... | hodos/10_folds_their_data_eval.py | import os
import pandas as pd
import numpy as np
import random
from CellData import CellData
from scipy import stats
# For reproducibility
random.seed(0)
np.random.seed(0)
os.chdir(open("../data_dir").read().strip())
# Load fixed order of perts and cell types
perts = pd.read_csv("Hodos/their_data/hodos_data_large_ten... | 0.487307 | 0.190667 |
import copy
from collections import defaultdict
import inspect
from typing import Any, Callable, List, Optional, Union
__all__ = ['get', 'register', 'all']
__MODS__ = defaultdict(lambda: {})
def get(group_name: str, name: Optional[str]=None) -> Any:
"""
:param group_name(str): group name of the class or... | mlutils/mod.py | import copy
from collections import defaultdict
import inspect
from typing import Any, Callable, List, Optional, Union
__all__ = ['get', 'register', 'all']
__MODS__ = defaultdict(lambda: {})
def get(group_name: str, name: Optional[str]=None) -> Any:
"""
:param group_name(str): group name of the class or... | 0.742422 | 0.133669 |
import time
import struct
# Get this file from BLUEPAD32_SRC/tools/circuitpython/
import bluepad32
import board
import busio
from digitalio import DigitalInOut
from micropython import const
# If you are using a board with pre-defined ESP32 Pins:
#esp32_cs = DigitalInOut(board.ESP_CS)
#esp32_ready = DigitalInOut(boar... | tools/circuitpython/code_test.py | import time
import struct
# Get this file from BLUEPAD32_SRC/tools/circuitpython/
import bluepad32
import board
import busio
from digitalio import DigitalInOut
from micropython import const
# If you are using a board with pre-defined ESP32 Pins:
#esp32_cs = DigitalInOut(board.ESP_CS)
#esp32_ready = DigitalInOut(boar... | 0.292191 | 0.182626 |
from collections import defaultdict
from typing import DefaultDict, List, Type, Tuple, Dict
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpRequest
from django.utils.functional import cached_property
from d... | dataporten/models.py | from collections import defaultdict
from typing import DefaultDict, List, Type, Tuple, Dict
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpRequest
from django.utils.functional import cached_property
from d... | 0.774498 | 0.204918 |
class Restaurante:
"""Essa classe tenta representar um restaurante."""
def __init__(self, nome_do_restaurante: str, tipo_de_cozinha: str):
"""
-> Inicializa os atributos da classe contendo
o nome e o tipo de cozinha do restaurante.
:param nome_do_restaurante: Nome do restaurante... | CursoIntensivoPython/curso-intensivo-python-master/capitulo_09/exercicios/sorveteria.py | class Restaurante:
"""Essa classe tenta representar um restaurante."""
def __init__(self, nome_do_restaurante: str, tipo_de_cozinha: str):
"""
-> Inicializa os atributos da classe contendo
o nome e o tipo de cozinha do restaurante.
:param nome_do_restaurante: Nome do restaurante... | 0.605566 | 0.5144 |
import os
import socket
import ftplib
DIR = os.path.dirname(os.path.abspath(__file__)) # default
FILE = "test.png" # default
class BinaryFTPClient: # Client initiates file request from server
_socket: socket
def __init__(self, filename: str = FILE):
self.packet = ftplib.PacketData()
sel... | client.py |
import os
import socket
import ftplib
DIR = os.path.dirname(os.path.abspath(__file__)) # default
FILE = "test.png" # default
class BinaryFTPClient: # Client initiates file request from server
_socket: socket
def __init__(self, filename: str = FILE):
self.packet = ftplib.PacketData()
sel... | 0.377082 | 0.08043 |
import os
import json
import shutil
import random
import pathlib
from tempfile import mkdtemp
from threading import Thread
from twisted.internet import reactor
from twisted.internet import task
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from ..util import get_picture
from ... | dnap/scraper/scrape.py |
import os
import json
import shutil
import random
import pathlib
from tempfile import mkdtemp
from threading import Thread
from twisted.internet import reactor
from twisted.internet import task
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from ..util import get_picture
from ... | 0.326701 | 0.087097 |
import numpy as np
import os
import mitsuba
mitsuba.set_variant('scalar_rgb')
from mitsuba.core import MemoryMappedFile
def test01_open_read_only(tmpdir):
tmp_file = os.path.join(str(tmpdir), "mmap_test")
with open(tmp_file, "w") as f:
f.write('hello!')
mmap = MemoryMappedFile(tmp_file)
assert... | src/libcore/tests/test_mmap.py | import numpy as np
import os
import mitsuba
mitsuba.set_variant('scalar_rgb')
from mitsuba.core import MemoryMappedFile
def test01_open_read_only(tmpdir):
tmp_file = os.path.join(str(tmpdir), "mmap_test")
with open(tmp_file, "w") as f:
f.write('hello!')
mmap = MemoryMappedFile(tmp_file)
assert... | 0.383064 | 0.45744 |
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup as soup
from selenium import webdriver
import requests
import time
class NetflixScraper:
def __init__(self, username, password):
self.username = username
self.password = password
self.driver = webdriver.Firefox(executable_path="C:\ge... | netflix_catalogue.py | from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup as soup
from selenium import webdriver
import requests
import time
class NetflixScraper:
def __init__(self, username, password):
self.username = username
self.password = password
self.driver = webdriver.Firefox(executable_path="C:\ge... | 0.188249 | 0.087798 |
import re
from acapi.resources.acquialist import AcquiaList
from acapi.resources.database import Database
class DatabaseList(AcquiaList):
"""Dictionary of Acquia Cloud API database resources keyed by name."""
def __init__(self, base_uri, auth, *args, **kwargs):
"""Constructor."""
super(Data... | acapi/resources/databaselist.py |
import re
from acapi.resources.acquialist import AcquiaList
from acapi.resources.database import Database
class DatabaseList(AcquiaList):
"""Dictionary of Acquia Cloud API database resources keyed by name."""
def __init__(self, base_uri, auth, *args, **kwargs):
"""Constructor."""
super(Data... | 0.79166 | 0.094887 |
import os
import sys
import time
import shutil
import re
"""
Educational purpose only
=============================
Created By: EH
"""
file_dir = " "
dir_name = " "
html_image = " "
image_clean1 = " "
image_clean2 = " "
def check_system():
if sys.platform == "linux" or sys.platform == ... | trackside.py | import os
import sys
import time
import shutil
import re
"""
Educational purpose only
=============================
Created By: EH
"""
file_dir = " "
dir_name = " "
html_image = " "
image_clean1 = " "
image_clean2 = " "
def check_system():
if sys.platform == "linux" or sys.platform == ... | 0.066089 | 0.053059 |
from ..warc import WARCReader, WARCHeader, WARCRecord, WARCFile
from StringIO import StringIO
class TestWARCHeader:
def test_attrs(self):
h = WARCHeader({
"WARC-Type": "response",
"WARC-Record-ID": "<record-1>",
"WARC-Date": "2000-01-02T03:04:05Z",
"Content-... | warc_to_mongo/warc/tests/test_warc.py | from ..warc import WARCReader, WARCHeader, WARCRecord, WARCFile
from StringIO import StringIO
class TestWARCHeader:
def test_attrs(self):
h = WARCHeader({
"WARC-Type": "response",
"WARC-Record-ID": "<record-1>",
"WARC-Date": "2000-01-02T03:04:05Z",
"Content-... | 0.571647 | 0.394259 |
from pymc import *
from numpy.testing import *
from pymc.graph import *
import nose
DIR = 'testresults'
def mymodel():
@stochastic
def A(value=0):
return 0.
@deterministic
def B(mom = 3, dad=A):
return 0.
@stochastic
def C(value=0, mom = A, dad = B):
return 0.
F ... | pymc/tests/test_graph.py | from pymc import *
from numpy.testing import *
from pymc.graph import *
import nose
DIR = 'testresults'
def mymodel():
@stochastic
def A(value=0):
return 0.
@deterministic
def B(mom = 3, dad=A):
return 0.
@stochastic
def C(value=0, mom = A, dad = B):
return 0.
F ... | 0.347094 | 0.352285 |
from ten_armed_testbed import Bandit, simulate
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from tqdm import trange
class NonstationaryBandit(Bandit):
# @k_arm: # of arms
# @epsilon: probability for exploration in epsilon-greedy algorithm
# @initial: initial estimation for each ac... | chapter02/exercise.py | from ten_armed_testbed import Bandit, simulate
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from tqdm import trange
class NonstationaryBandit(Bandit):
# @k_arm: # of arms
# @epsilon: probability for exploration in epsilon-greedy algorithm
# @initial: initial estimation for each ac... | 0.748904 | 0.664731 |
u"""
3Dバウンディングボックスクラス。
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ...common import *
from ...pyutils.immutables import OPTIONAL_MUTATOR_DICT as _MUTATOR_DICT
from .vector import _newV
import maya.api.OpenMaya as _api2
from math import sqrt
__a... | python/cymel/core/datatypes/python/boundingbox.py | u"""
3Dバウンディングボックスクラス。
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ...common import *
from ...pyutils.immutables import OPTIONAL_MUTATOR_DICT as _MUTATOR_DICT
from .vector import _newV
import maya.api.OpenMaya as _api2
from math import sqrt
__a... | 0.657318 | 0.324048 |
import os
import pytest
import torch
from pytorch_lightning import Trainer
from torch.utils.data import DataLoader, Dataset
from flash.core.data.data_source import DefaultDataKeys
from flash.core.utilities.imports import _IMAGE_AVAILABLE
from flash.image import ObjectDetector
def collate_fn(samples):
return {ke... | tests/image/detection/test_model.py | import os
import pytest
import torch
from pytorch_lightning import Trainer
from torch.utils.data import DataLoader, Dataset
from flash.core.data.data_source import DefaultDataKeys
from flash.core.utilities.imports import _IMAGE_AVAILABLE
from flash.image import ObjectDetector
def collate_fn(samples):
return {ke... | 0.705278 | 0.557966 |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from tensorforce.agents import Agent
class BatchAgent(Agent):
"""
The `BatchAgent` class implements a batch memory which generally implies on-policy
experience collection and updates.
"""
... | tensorforce/agents/batch_agent.py |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from tensorforce.agents import Agent
class BatchAgent(Agent):
"""
The `BatchAgent` class implements a batch memory which generally implies on-policy
experience collection and updates.
"""
... | 0.952053 | 0.558929 |
from io import BytesIO
import matplotlib.pyplot as plt
from reportlab.lib.units import inch
from reportlab.platypus import Table, TableStyle, Image, Paragraph, Frame
from metrics.portfolio import PORTFOLIO, Portfolio
from reporter.pdf_style import BLOCK_HEADER_STYLE, LINE_COLOR, LINE_WIDTH, BOLD_FONT, BlockPosition
... | src/reporter/portfolio_structure.py |
from io import BytesIO
import matplotlib.pyplot as plt
from reportlab.lib.units import inch
from reportlab.platypus import Table, TableStyle, Image, Paragraph, Frame
from metrics.portfolio import PORTFOLIO, Portfolio
from reporter.pdf_style import BLOCK_HEADER_STYLE, LINE_COLOR, LINE_WIDTH, BOLD_FONT, BlockPosition
... | 0.547464 | 0.452959 |
import pandas as pd
import numpy as np
from numpy import zeros
from pandas import DataFrame, get_dummies
import keras
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Dropout, Bidirectional, Embedding, LSTM, Conv... | stressPredict-BiRNN-LSTM.py | import pandas as pd
import numpy as np
from numpy import zeros
from pandas import DataFrame, get_dummies
import keras
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Dropout, Bidirectional, Embedding, LSTM, Conv... | 0.709019 | 0.413418 |
from flask import Blueprint
from flask import redirect, request, \
render_template, url_for, flash
from app.models import *
from flask.views import MethodView
from flask_login import current_user, login_required
from app import loginManager
from common.mockservermeth import get_token_data
from error_message import ... | app/mock/views.py | from flask import Blueprint
from flask import redirect, request, \
render_template, url_for, flash
from app.models import *
from flask.views import MethodView
from flask_login import current_user, login_required
from app import loginManager
from common.mockservermeth import get_token_data
from error_message import ... | 0.341253 | 0.060557 |
import bluetooth
from PyOBEX.client import Client
import pyrebase
import requests
import os
import json
import random
home = os.path.expanduser('~')
url = 'scouting-2018-houston'
config = {
'apiKey': 'mykey',
'authDomain': url + '.firebaseapp.com',
'databaseURL': 'https://' + url + '.firebaseio.com/',
'storageBu... | createQRFile.py | import bluetooth
from PyOBEX.client import Client
import pyrebase
import requests
import os
import json
import random
home = os.path.expanduser('~')
url = 'scouting-2018-houston'
config = {
'apiKey': 'mykey',
'authDomain': url + '.firebaseapp.com',
'databaseURL': 'https://' + url + '.firebaseio.com/',
'storageBu... | 0.153042 | 0.102664 |
import asyncio
import asynctest
from neko2 import libneko
class PropertyTest(asynctest.TestCase):
def test_read_only_property(self):
class Klass1:
@libneko.properties.read_only_property
def foo(self):
return 22
k = Klass1()
self.assertEqual(22, k.... | libneko/test/test_properties.py | import asyncio
import asynctest
from neko2 import libneko
class PropertyTest(asynctest.TestCase):
def test_read_only_property(self):
class Klass1:
@libneko.properties.read_only_property
def foo(self):
return 22
k = Klass1()
self.assertEqual(22, k.... | 0.732496 | 0.446555 |
import sys
import curses
import asyncio
from signal import signal, SIGINT
from typing import Tuple, List, Any
from .widget import Widget, Event, MOUSE_EVENTS, Target
from .palette import DefaultPalette, Palette
class Application(Widget):
def __init__(self, palette: Palette = None, **context) -> None:
supe... | widark/application.py | import sys
import curses
import asyncio
from signal import signal, SIGINT
from typing import Tuple, List, Any
from .widget import Widget, Event, MOUSE_EVENTS, Target
from .palette import DefaultPalette, Palette
class Application(Widget):
def __init__(self, palette: Palette = None, **context) -> None:
supe... | 0.505127 | 0.195517 |
import unittest
from flask import Flask
from google.appengine.ext import ndb
import db
import purchases
from application import app
import funds
import committees
from role_types import RoleType
class TestPurchases(unittest.TestCase):
def setUp(self):
self.dbstate = ndb.clone()
def tearDown(self):
... | test/test_purchases.py | import unittest
from flask import Flask
from google.appengine.ext import ndb
import db
import purchases
from application import app
import funds
import committees
from role_types import RoleType
class TestPurchases(unittest.TestCase):
def setUp(self):
self.dbstate = ndb.clone()
def tearDown(self):
... | 0.26923 | 0.166235 |
import itertools
import numpy as np
import implementations as impl
import costs
def batch_iter(y, tx, batch_size, num_batches=1, shuffle=True):
"""Generate a minibatch iterator for a dataset.
Takes as input two iterables (here the output desired values 'y' and the input data 'tx')
Outputs an iterator whi... | project1/src/util/modifiers.py | import itertools
import numpy as np
import implementations as impl
import costs
def batch_iter(y, tx, batch_size, num_batches=1, shuffle=True):
"""Generate a minibatch iterator for a dataset.
Takes as input two iterables (here the output desired values 'y' and the input data 'tx')
Outputs an iterator whi... | 0.864768 | 0.640636 |
__author__ = "<NAME>"
__copyright__ = """(C) 2021 ACK CYFRONET AGH,
This software is released under the MIT license cited in 'LICENSE.txt'."""
import os
import sys
import subprocess
from os.path import expanduser
import pytest
script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.dirna... | test/integration/storagerouter_helper_test/storagerouter_helper_test.py |
__author__ = "<NAME>"
__copyright__ = """(C) 2021 ACK CYFRONET AGH,
This software is released under the MIT license cited in 'LICENSE.txt'."""
import os
import sys
import subprocess
from os.path import expanduser
import pytest
script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.dirna... | 0.38445 | 0.228641 |
from django.shortcuts import render
from django.shortcuts import get_object_or_404, render,redirect
from .models import Business, NeighbourHood, Post, Profile
from django.contrib.auth.decorators import login_required
from.forms import UpdateProfileForm,NeighbourhoodForm,PostForm,BusinessForm
from django.contrib.auth.mo... | neighboor/views.py | from django.shortcuts import render
from django.shortcuts import get_object_or_404, render,redirect
from .models import Business, NeighbourHood, Post, Profile
from django.contrib.auth.decorators import login_required
from.forms import UpdateProfileForm,NeighbourhoodForm,PostForm,BusinessForm
from django.contrib.auth.mo... | 0.323273 | 0.070176 |
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'GL_ARB_shader_atomic_counters'
def _f( ... | deep-rl/lib/python2.7/site-packages/OpenGL/raw/GL/ARB/shader_atomic_counters.py | from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'GL_ARB_shader_atomic_counters'
def _f( ... | 0.370225 | 0.054224 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def tax_sums(journal_df, months=None):
""" Returns a DataFrame with sales and tax rates -
If a number or list is passed to 'months', only the sales
of the corresponding months will be used.
Example: tax_sums(... | num_3.py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def tax_sums(journal_df, months=None):
""" Returns a DataFrame with sales and tax rates -
If a number or list is passed to 'months', only the sales
of the corresponding months will be used.
Example: tax_sums(... | 0.284974 | 0.635251 |
import argparse
import time
import sys
def install_qt4a_driver(args):
from qt4a.androiddriver.adb import ADB
from qt4a.androiddriver.androiddriver import copy_android_driver
device_list = ADB.list_device()
if len(device_list) == 0:
raise RuntimeError('No Android device found'... | qt4a/management.py | import argparse
import time
import sys
def install_qt4a_driver(args):
from qt4a.androiddriver.adb import ADB
from qt4a.androiddriver.androiddriver import copy_android_driver
device_list = ADB.list_device()
if len(device_list) == 0:
raise RuntimeError('No Android device found'... | 0.127625 | 0.066418 |
import os
import sys
from twisted.internet.protocol import Protocol, ProcessProtocol
from twisted.internet.defer import fail, gatherResults, maybeDeferred, succeed
from twisted.internet.task import Cooperator, deferLater
from twisted.internet.main import CONNECTION_DONE
from twisted.internet import reactor, interfaces... | src/twisted/trial/_dist/test/test_disttrial.py | import os
import sys
from twisted.internet.protocol import Protocol, ProcessProtocol
from twisted.internet.defer import fail, gatherResults, maybeDeferred, succeed
from twisted.internet.task import Cooperator, deferLater
from twisted.internet.main import CONNECTION_DONE
from twisted.internet import reactor, interfaces... | 0.379953 | 0.17172 |
"""Perform a functional test for client helper functions."""
import os
import pytest
import orion.core.cli
from orion.core.worker.consumer import Consumer
def test_interrupt(storage, monkeypatch, capsys):
"""Test interruption from within user script."""
monkeypatch.chdir(os.path.dirname(os.path.abspath(__fi... | tests/functional/client/test_cli_client.py | """Perform a functional test for client helper functions."""
import os
import pytest
import orion.core.cli
from orion.core.worker.consumer import Consumer
def test_interrupt(storage, monkeypatch, capsys):
"""Test interruption from within user script."""
monkeypatch.chdir(os.path.dirname(os.path.abspath(__fi... | 0.593609 | 0.440168 |
# Copyright 2019 Machine Zone, Inc. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from kubespec import context
from kubespec import types
from kubespec.k8s import base
from kubespec.k8s import resource
from kubespec.k8s import v1 as k8sv1
f... | kubespec/k8s/metrics/v1alpha1.py |
# Copyright 2019 Machine Zone, Inc. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from kubespec import context
from kubespec import types
from kubespec.k8s import base
from kubespec.k8s import resource
from kubespec.k8s import v1 as k8sv1
f... | 0.925171 | 0.191687 |
from __future__ import print_function
'''
download all NIPS2017 papers and create index.html for them
'''
import time
import json
import sys
import os
import six
from six.moves import urllib
from bs4 import BeautifulSoup
papers_page = "https://papers.nips.cc/book/advances-in-neural-information-processing-systems-3... | scripts/nips_2017.py | from __future__ import print_function
'''
download all NIPS2017 papers and create index.html for them
'''
import time
import json
import sys
import os
import six
from six.moves import urllib
from bs4 import BeautifulSoup
papers_page = "https://papers.nips.cc/book/advances-in-neural-information-processing-systems-3... | 0.142948 | 0.10026 |
import datetime
import pytest
from composer.core.time import Time, Timestamp, TimeUnit
@pytest.mark.parametrize("time_string,expected_value,expected_unit", [
["1ep", 1, TimeUnit.EPOCH],
["2ba", 2, TimeUnit.BATCH],
["3e10sp", 3 * 10**10, TimeUnit.SAMPLE],
["4tok", 4, TimeUnit.TOKEN],
["0.5dur", ... | tests/test_time.py |
import datetime
import pytest
from composer.core.time import Time, Timestamp, TimeUnit
@pytest.mark.parametrize("time_string,expected_value,expected_unit", [
["1ep", 1, TimeUnit.EPOCH],
["2ba", 2, TimeUnit.BATCH],
["3e10sp", 3 * 10**10, TimeUnit.SAMPLE],
["4tok", 4, TimeUnit.TOKEN],
["0.5dur", ... | 0.875853 | 0.881513 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
import potions.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... | potions/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
import potions.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... | 0.495361 | 0.158695 |
import os
import argparse
import pandas as pd
from tqdm import tqdm
from rdkit import Chem
import sys
import rdkit.Chem.Descriptors as descr
parser = argparse.ArgumentParser()
parser.add_argument('-i', type=str, help="path to directory containing mol2 files")
parser.add_argument('-o', type=str, help="path to director... | scripts/mol_to_smiles.py | import os
import argparse
import pandas as pd
from tqdm import tqdm
from rdkit import Chem
import sys
import rdkit.Chem.Descriptors as descr
parser = argparse.ArgumentParser()
parser.add_argument('-i', type=str, help="path to directory containing mol2 files")
parser.add_argument('-o', type=str, help="path to director... | 0.107473 | 0.144903 |
from ctypes import *
from enum import Enum, IntEnum, IntFlag
class EventReasonCode(Enum):
TEXTBUF_FULL = 101
TEXTBUF_FLUSH = 102
TEXTBUF_CLOSE = 103
RAWBUF_FULL = 201
RAWBUF_FLUSH = 202
RAWBUF_CLOSE = 203
PH_LABEL = 301
BOOKMARK = 302
AUTO_BOOKMARK = 303
class ResultCode(Enum):
... | pyvcroid2/aitalk.py | from ctypes import *
from enum import Enum, IntEnum, IntFlag
class EventReasonCode(Enum):
TEXTBUF_FULL = 101
TEXTBUF_FLUSH = 102
TEXTBUF_CLOSE = 103
RAWBUF_FULL = 201
RAWBUF_FLUSH = 202
RAWBUF_CLOSE = 203
PH_LABEL = 301
BOOKMARK = 302
AUTO_BOOKMARK = 303
class ResultCode(Enum):
... | 0.336876 | 0.098123 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'GetTopicSubscriptionsResult',
'AwaitableGetTopicSubscriptionsResult',
'get_topic_subscriptions',
]
@pulumi.output_type
clas... | sdk/python/pulumi_alicloud/mns/get_topic_subscriptions.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'GetTopicSubscriptionsResult',
'AwaitableGetTopicSubscriptionsResult',
'get_topic_subscriptions',
]
@pulumi.output_type
clas... | 0.822688 | 0.122549 |
from . import Payment
from collections import namedtuple
InvoiceItem = namedtuple('InvoiceItem', 'name quantity unit_price \
total_price description')
class Invoice(Payment):
"""Payment invoice"""
def __init__(self, store=None):
"""Create an invoice
Accepts list... | paydunya/invoice.py | from . import Payment
from collections import namedtuple
InvoiceItem = namedtuple('InvoiceItem', 'name quantity unit_price \
total_price description')
class Invoice(Payment):
"""Payment invoice"""
def __init__(self, store=None):
"""Create an invoice
Accepts list... | 0.882877 | 0.377139 |
from typing import Dict, List # isort:skip
import logging
import os
import sys
from urllib.parse import quote_plus
from urllib.request import Request, urlopen
from tqdm import tqdm
from catalyst.dl import utils
from catalyst.dl.core import LoggerCallback, RunnerState
from catalyst.dl.utils.formatters import TxtMetri... | catalyst/dl/callbacks/logging.py | from typing import Dict, List # isort:skip
import logging
import os
import sys
from urllib.parse import quote_plus
from urllib.request import Request, urlopen
from tqdm import tqdm
from catalyst.dl import utils
from catalyst.dl.core import LoggerCallback, RunnerState
from catalyst.dl.utils.formatters import TxtMetri... | 0.628179 | 0.174903 |
import sys
from . import CPyExtTestCase, CPyExtFunction, CPyExtFunctionOutVars, unhandled_error_compare, GRAALPYTHON
__dir__ = __file__.rpartition("/")[0]
def _reference_importmodule(args):
return __import__(args[0], fromlist=["*"])
class TestMisc(CPyExtTestCase):
def compile_module(self, name):
t... | graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_misc.py |
import sys
from . import CPyExtTestCase, CPyExtFunction, CPyExtFunctionOutVars, unhandled_error_compare, GRAALPYTHON
__dir__ = __file__.rpartition("/")[0]
def _reference_importmodule(args):
return __import__(args[0], fromlist=["*"])
class TestMisc(CPyExtTestCase):
def compile_module(self, name):
t... | 0.402979 | 0.268887 |
import pandas as pd
import os
from os import listdir
from os.path import isfile, join
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipe... | tests/tests/third_exp.py | import pandas as pd
import os
from os import listdir
from os.path import isfile, join
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipe... | 0.61832 | 0.540257 |
import logging
from bosch_thermostat_client.const import (
RESULT,
URI,
VALUE,
INTERVAL,
RECORDINGS,
RECORDING,
TEMP_CELSIUS,
ENERGY_KILO_WATT_HOUR,
)
from .sensor import Sensor
from bosch_thermostat_client.exceptions import DeviceException
from datetime import datetime, timedelta
_LOG... | bosch_thermostat_client/sensors/recording.py | import logging
from bosch_thermostat_client.const import (
RESULT,
URI,
VALUE,
INTERVAL,
RECORDINGS,
RECORDING,
TEMP_CELSIUS,
ENERGY_KILO_WATT_HOUR,
)
from .sensor import Sensor
from bosch_thermostat_client.exceptions import DeviceException
from datetime import datetime, timedelta
_LOG... | 0.698227 | 0.12544 |
from oslo_config import cfg
from oslo_log import log as logging
from nca47.agent import cli_driver
from nca47.agent import dns_driver
from nca47.agent import firewall_driver
from nca47.common import exception
from nca47.common.i18n import _
LOG = logging.getLogger(__name__)
DRIVER_OPTS = [
cfg.StrOpt('dns_driver'... | nca47/agent/__init__.py | from oslo_config import cfg
from oslo_log import log as logging
from nca47.agent import cli_driver
from nca47.agent import dns_driver
from nca47.agent import firewall_driver
from nca47.common import exception
from nca47.common.i18n import _
LOG = logging.getLogger(__name__)
DRIVER_OPTS = [
cfg.StrOpt('dns_driver'... | 0.351089 | 0.044183 |
from math import sqrt
from typing import List
vector = List[float]
def add(v: vector, w: vector) -> vector:
"""adds corresponding elemets."""
assert len(v) == len(w), "vectors must be of same length."
return[ v_i + w_i for v_i, w_i in zip(v, w) ]
assert add([1, 2, 3], [4, 5, 6]) == [5, 7, 9]
def sub... | vectors_operations.py | from math import sqrt
from typing import List
vector = List[float]
def add(v: vector, w: vector) -> vector:
"""adds corresponding elemets."""
assert len(v) == len(w), "vectors must be of same length."
return[ v_i + w_i for v_i, w_i in zip(v, w) ]
assert add([1, 2, 3], [4, 5, 6]) == [5, 7, 9]
def sub... | 0.948787 | 0.824991 |
import os
from django.conf import settings
from programy.clients.embed.datafile import EmbeddedDataFileBot
class AimlChatbot(EmbeddedDataFileBot):
"""Definition of the AIML chatbot class.
This class acts as the bridge between the server and the chatbot
engine. It also provides methods to handle the clien... | chatbotapp/chatbot/botbrain/aimlbot.py | import os
from django.conf import settings
from programy.clients.embed.datafile import EmbeddedDataFileBot
class AimlChatbot(EmbeddedDataFileBot):
"""Definition of the AIML chatbot class.
This class acts as the bridge between the server and the chatbot
engine. It also provides methods to handle the clien... | 0.669853 | 0.26402 |
import os.path
from Modelizer import *
from ConvertOsim2Biorbd import *
from Converter import *
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
class ToolMenu(tk.Menu):
def __init__(self, mainmenubar, *args, **kwargs):
tk.Menu.__init__(self, mainmenubar, *args, **kwargs)
... | ModelEditor/Model_Editor.py | import os.path
from Modelizer import *
from ConvertOsim2Biorbd import *
from Converter import *
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
class ToolMenu(tk.Menu):
def __init__(self, mainmenubar, *args, **kwargs):
tk.Menu.__init__(self, mainmenubar, *args, **kwargs)
... | 0.463201 | 0.06492 |
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
import datetime
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from alembic import op
from ggrc.migrations import utils
from ggrc.migrations.utils import migrator
# revision identifiers, use... | src/ggrc/migrations/versions/20190423_f2428adea671_add_recipients_field_for_program.py | # disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
import datetime
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from alembic import op
from ggrc.migrations import utils
from ggrc.migrations.utils import migrator
# revision identifiers, use... | 0.510008 | 0.097907 |
import logging
import json
import boto3
# Lambda Powertools
from aws_lambda_powertools import Logger
from aws_lambda_powertools import Tracer
# Specify desired resource types to validate
APPLICABLE_RESOURCES = ["AWS::ApiGateway::RestApi", "AWS::Lambda::Function"]
# Lambda Powertools
logger = Logger()
tracer = Tracer(... | security-config-rules/sam-app/checkRequiredTags/lambda_function.py | import logging
import json
import boto3
# Lambda Powertools
from aws_lambda_powertools import Logger
from aws_lambda_powertools import Tracer
# Specify desired resource types to validate
APPLICABLE_RESOURCES = ["AWS::ApiGateway::RestApi", "AWS::Lambda::Function"]
# Lambda Powertools
logger = Logger()
tracer = Tracer(... | 0.490236 | 0.121712 |
__all__ = ['PreprocessDicom', 'AddChannel', 'ImageBlock3D', 'MaskBlock3D', 'ImageDataLoaders3D', 'get_volumetric_files',
'supported_extensions', 'SegmentationDataLoaders3D']
# Cell
# default_exp data
import SimpleITK as sitk
import re
import pathlib
import torchvision
from fastai.basics import *
from fas... | faimed3d/data.py |
__all__ = ['PreprocessDicom', 'AddChannel', 'ImageBlock3D', 'MaskBlock3D', 'ImageDataLoaders3D', 'get_volumetric_files',
'supported_extensions', 'SegmentationDataLoaders3D']
# Cell
# default_exp data
import SimpleITK as sitk
import re
import pathlib
import torchvision
from fastai.basics import *
from fas... | 0.795062 | 0.58059 |
from django.shortcuts import get_object_or_404
from django.db.models import Q
from todo.models import Grp, Lst
from v2_todo.forms import GrpForm, LstForm
from v2_hier.params import set_article_visible, set_aside_visible
from v2_hier.search import SearchResult
def group_add(user, app_name, name):
grp = Grp.objects... | v2_hier/grp_lst.py | from django.shortcuts import get_object_or_404
from django.db.models import Q
from todo.models import Grp, Lst
from v2_todo.forms import GrpForm, LstForm
from v2_hier.params import set_article_visible, set_aside_visible
from v2_hier.search import SearchResult
def group_add(user, app_name, name):
grp = Grp.objects... | 0.221351 | 0.058642 |
from dns import resolver, rdtypes
import os
import sys
from data.config import *
from common.utils.printdata import *
from common.log.log_util import LogUtil as log
from error.CDNQueryError import CDNQueryError
import data.data as data
logger = log.getLogger(__name__)
class CDNDetect(object):
dns_list = ["8.8.8.... | common/moudle/cdn_detect.py | from dns import resolver, rdtypes
import os
import sys
from data.config import *
from common.utils.printdata import *
from common.log.log_util import LogUtil as log
from error.CDNQueryError import CDNQueryError
import data.data as data
logger = log.getLogger(__name__)
class CDNDetect(object):
dns_list = ["8.8.8.... | 0.257112 | 0.080069 |
import pandas as pd
from scipy import stats
import numpy as np
import re
from mne.utils import warn
import nilearn
def glm_to_tidy(raw, statistic, design_matrix):
"""
Exports GLM regression or contrast results in tidy format.
Creates a long pandas data frame from regression results or contrast
as com... | mne_nirs/utils/_io.py | import pandas as pd
from scipy import stats
import numpy as np
import re
from mne.utils import warn
import nilearn
def glm_to_tidy(raw, statistic, design_matrix):
"""
Exports GLM regression or contrast results in tidy format.
Creates a long pandas data frame from regression results or contrast
as com... | 0.742235 | 0.577674 |
__author__ = '<NAME>'
from abc import ABC, abstractmethod
from threading import current_thread
from company import Company, process_company_name
from subject import StockCenter, Subject
class Observer(ABC):
"""
Abstract Observer class.
"""
__slots__ = []
@abstractmethod
def update(self, sub... | 4-Behavioral Patterns/11-Observer Pattern/Stock Example/Python/observer.py | __author__ = '<NAME>'
from abc import ABC, abstractmethod
from threading import current_thread
from company import Company, process_company_name
from subject import StockCenter, Subject
class Observer(ABC):
"""
Abstract Observer class.
"""
__slots__ = []
@abstractmethod
def update(self, sub... | 0.771672 | 0.17245 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import *
import imp
import os
import sys
from genestack_client import make_connection... | docs/source/make_shell_docs.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import *
import imp
import os
import sys
from genestack_client import make_connection... | 0.532911 | 0.089375 |
#---------------------------------------
# Script Import Libraries
#---------------------------------------
import clr
clr.AddReference("IronPython.Modules.dll")
import os
import codecs
import json
import re
try:
from streamlabs_stub import *
except:
pass
#---------------------------------------
# Script Info... | Phobia_StreamlabsSystem.py | #---------------------------------------
# Script Import Libraries
#---------------------------------------
import clr
clr.AddReference("IronPython.Modules.dll")
import os
import codecs
import json
import re
try:
from streamlabs_stub import *
except:
pass
#---------------------------------------
# Script Info... | 0.384565 | 0.146057 |
import argparse
import logging
import signal
import sys
import os
from configparser import ConfigParser
from threading import Timer
import praw
PACKAGE_DIR = os.path.dirname(__file__)
PACKAGE_PARENT_DIR = os.path.dirname(PACKAGE_DIR)
if PACKAGE_PARENT_DIR not in sys.path:
sys.path.append(PACKAGE_PARENT_DIR)
from... | src/main.py | import argparse
import logging
import signal
import sys
import os
from configparser import ConfigParser
from threading import Timer
import praw
PACKAGE_DIR = os.path.dirname(__file__)
PACKAGE_PARENT_DIR = os.path.dirname(PACKAGE_DIR)
if PACKAGE_PARENT_DIR not in sys.path:
sys.path.append(PACKAGE_PARENT_DIR)
from... | 0.198142 | 0.073397 |
import json
from urllib.parse import urlparse
import requests
import re
def get(url: str) -> dict:
"""
text、videos
"""
data = {}
# headers = {
# "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
# ... | extractor/huoshan.py | import json
from urllib.parse import urlparse
import requests
import re
def get(url: str) -> dict:
"""
text、videos
"""
data = {}
# headers = {
# "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
# ... | 0.23118 | 0.06028 |
from django.db import models
from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User, Group, Permission
from django.forms import ModelForm, TextInput
from django.http import HttpRespons... | django_boot/admin.py | from django.db import models
from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User, Group, Permission
from django.forms import ModelForm, TextInput
from django.http import HttpRespons... | 0.439747 | 0.065785 |
from tkinter import Tk, Checkbutton, Label, IntVar, X, Button, BOTTOM
class ModSelectionGui:
MACRO_RUNNING = 'Macro running'
MACRO_STOPPED = 'Macro stopped'
def __init__(self):
self.__build_gui()
def start(self):
self.root.mainloop()
def __build_gui(self):
self.global_pa... | mod_selection_gui.py | from tkinter import Tk, Checkbutton, Label, IntVar, X, Button, BOTTOM
class ModSelectionGui:
MACRO_RUNNING = 'Macro running'
MACRO_STOPPED = 'Macro stopped'
def __init__(self):
self.__build_gui()
def start(self):
self.root.mainloop()
def __build_gui(self):
self.global_pa... | 0.531209 | 0.07221 |
import torch
import torch.nn as nn
def init_params(net):
"""
Init layer parameters.
:param net:
:return:
"""
for m in net.modules():
if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight)
if m.bias is not None:
... | src/net_base.py | import torch
import torch.nn as nn
def init_params(net):
"""
Init layer parameters.
:param net:
:return:
"""
for m in net.modules():
if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight)
if m.bias is not None:
... | 0.959828 | 0.560854 |
import numpy as np
"""
This code was written by eduardo not pat!!!! Someday pat will understand this
but that day is not today!!!!
"""
def ind2gen(index, n):
'''Return a genotype of length n that encodes the index in binary'''
# For example, ind2gen(255,8) = [1, 1, 1, 1, 1, 1, 1, 1]
genotype = np.zeros(n... | sbgas/NK.py | import numpy as np
"""
This code was written by eduardo not pat!!!! Someday pat will understand this
but that day is not today!!!!
"""
def ind2gen(index, n):
'''Return a genotype of length n that encodes the index in binary'''
# For example, ind2gen(255,8) = [1, 1, 1, 1, 1, 1, 1, 1]
genotype = np.zeros(n... | 0.533884 | 0.395105 |
from imp import reload
from nltk.corpus import stopwords
from collections import Counter
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import nltk,re,pprint
import sys,glob,os
import operator, string, argparse, math, random
import matplotlib.pyplot as plot
class flingP... | build/lib/fling/flingPretrained.py | from imp import reload
from nltk.corpus import stopwords
from collections import Counter
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import nltk,re,pprint
import sys,glob,os
import operator, string, argparse, math, random
import matplotlib.pyplot as plot
class flingP... | 0.153169 | 0.266226 |
import argparse
import os
import pkg_resources
from pyhound.hound import Client
DEFAULT_ENDPOINT = 'http://localhost:6080/'
VERSION = pkg_resources.get_distribution('pyhound').version
def parse_args():
parser = argparse.ArgumentParser(
prog="pyhound",
description="A command-line client for Houn... | pyhound/cli.py | import argparse
import os
import pkg_resources
from pyhound.hound import Client
DEFAULT_ENDPOINT = 'http://localhost:6080/'
VERSION = pkg_resources.get_distribution('pyhound').version
def parse_args():
parser = argparse.ArgumentParser(
prog="pyhound",
description="A command-line client for Houn... | 0.502197 | 0.089494 |
"""The app module, containing the app factory function."""
from flask import Flask, jsonify
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import default_exceptions
from api import commands, user
from api.extensions import bcrypt, db, migrate
from api.settings import ProdConfig
from api.user im... | api/app.py | """The app module, containing the app factory function."""
from flask import Flask, jsonify
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import default_exceptions
from api import commands, user
from api.extensions import bcrypt, db, migrate
from api.settings import ProdConfig
from api.user im... | 0.760028 | 0.212222 |
import sys
import logging
from .config import load_config
from .utils import get_debug, key_exists
from .build import imports, classes, readme, functions, setup_py
LIB_NAME = "Doby"
LIB_URL = "https://github.com/rorymurdock/doby"
class Doby:
"""Framework for making REST API libraries"""
def __init__(
... | doby/doby.py | import sys
import logging
from .config import load_config
from .utils import get_debug, key_exists
from .build import imports, classes, readme, functions, setup_py
LIB_NAME = "Doby"
LIB_URL = "https://github.com/rorymurdock/doby"
class Doby:
"""Framework for making REST API libraries"""
def __init__(
... | 0.367497 | 0.073463 |
# Copyright (c) 2007-2009, Enthought, Inc.
# License: BSD Style.
"""
A Traits UI editor that wraps a WX calendar panel.
"""
from __future__ import print_function
from traits.api import HasTraits, Date, List, Str
from traitsui.api import View, Item, DateEditor, Group
class DateEditorDemo(HasTraits):
""" Demo ... | TraitsUI/examples/Date_editor_demo.py |
# Copyright (c) 2007-2009, Enthought, Inc.
# License: BSD Style.
"""
A Traits UI editor that wraps a WX calendar panel.
"""
from __future__ import print_function
from traits.api import HasTraits, Date, List, Str
from traitsui.api import View, Item, DateEditor, Group
class DateEditorDemo(HasTraits):
""" Demo ... | 0.83868 | 0.1526 |
import unittest
from Homework_5.Exercise_1 import ITEmployee
class TestInitExceptions(unittest.TestCase):
def test_birth_year_exp(self):
with self.assertRaises(ValueError):
self.slave = ITEmployee(full_name="<NAME>", birth_year = 1800)
def test_space(self):
with self.assertRaises(Ex... | Exercise_4.py | import unittest
from Homework_5.Exercise_1 import ITEmployee
class TestInitExceptions(unittest.TestCase):
def test_birth_year_exp(self):
with self.assertRaises(ValueError):
self.slave = ITEmployee(full_name="<NAME>", birth_year = 1800)
def test_space(self):
with self.assertRaises(Ex... | 0.500732 | 0.458894 |
from typing import List
from Core.Base.BaseValidation import BaseValidation
from Core.DatabaseFactory.DatabaseType import DatabaseType
from Model.Bot import BotDataModel
from Model.QnA import QnADataModel
from Utils.DatabaseUtils import DatabaseHelper
from .KnowledgePage import KnowledgePage
class Knowledg... | python/GUI/POM/KnowledgePage/KnowledgeValidation.py | from typing import List
from Core.Base.BaseValidation import BaseValidation
from Core.DatabaseFactory.DatabaseType import DatabaseType
from Model.Bot import BotDataModel
from Model.QnA import QnADataModel
from Utils.DatabaseUtils import DatabaseHelper
from .KnowledgePage import KnowledgePage
class Knowledg... | 0.765199 | 0.269443 |
from __future__ import unicode_literals
import os
import re
from django import forms
from django.utils.datastructures import SortedDict
from crowdflower import default_job_cml_path, price_class_handler
from form_fields import DatetimeField, ListField
from models import Dialogue
import settings
class CustomFieldsF... | transcription/forms.py |
from __future__ import unicode_literals
import os
import re
from django import forms
from django.utils.datastructures import SortedDict
from crowdflower import default_job_cml_path, price_class_handler
from form_fields import DatetimeField, ListField
from models import Dialogue
import settings
class CustomFieldsF... | 0.40204 | 0.143128 |
from django import forms
from .models import UserAccount, Profile
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from django.forms.widgets import TextInput
class RegisterUserForm(UserCreationForm):
email = forms.EmailField(
max_length=200, help_t... | authentication/forms.py | from django import forms
from .models import UserAccount, Profile
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from django.forms.widgets import TextInput
class RegisterUserForm(UserCreationForm):
email = forms.EmailField(
max_length=200, help_t... | 0.414425 | 0.075892 |
import struct
import tempfile
import shutil
def extractwadatabase():
ctx.gui_setMainLabel("Status: Trying to attach wa database")
result={}
for datadir in ["/data/com.whatsapp/databases/wa.db","/com.whatsapp/databases/wa.db","/data/user/150/com.whatsapp/databases/wa.db"]:
if (ctx.fs_isFil... | MobileRevelator/python/android_whatsapp.py |
import struct
import tempfile
import shutil
def extractwadatabase():
ctx.gui_setMainLabel("Status: Trying to attach wa database")
result={}
for datadir in ["/data/com.whatsapp/databases/wa.db","/com.whatsapp/databases/wa.db","/data/user/150/com.whatsapp/databases/wa.db"]:
if (ctx.fs_isFil... | 0.035872 | 0.04807 |
from unittest import SkipTest
from collections import OrderedDict
import numpy as np
from holoviews.element import RGB
from holoviews.element.comparison import ComparisonTestCase
from hvplot import patch
try:
import xarray as xr
except:
raise SkipTest('XArray not available')
else:
patch('xarray')
class T... | hvplot/tests/testgridplots.py | from unittest import SkipTest
from collections import OrderedDict
import numpy as np
from holoviews.element import RGB
from holoviews.element.comparison import ComparisonTestCase
from hvplot import patch
try:
import xarray as xr
except:
raise SkipTest('XArray not available')
else:
patch('xarray')
class T... | 0.777215 | 0.651895 |
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense
from collections import deque
import random
from keras.optimizers import Adam
import h5py
class Learner:
def __init__(self, state_space_size, action_space_size, exploration):
self.state_size = state_space_si... | scripts/Dqn.py | import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense
from collections import deque
import random
from keras.optimizers import Adam
import h5py
class Learner:
def __init__(self, state_space_size, action_space_size, exploration):
self.state_size = state_space_si... | 0.648689 | 0.27431 |
import os
import dj_database_url
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse_lazy
def get_env_variable(var_name):
""" Get the environment variable or return exception """
try:
return os.environ[var_name]
except KeyError:
error_msg =... | qc/settings.py |
import os
import dj_database_url
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse_lazy
def get_env_variable(var_name):
""" Get the environment variable or return exception """
try:
return os.environ[var_name]
except KeyError:
error_msg =... | 0.327668 | 0.051558 |
import pandas as pd
import numpy as np
import json
import re
import ast
class DataFormatting():
def format_pr(self, json_obj):
# pr = pd.DataFrame(json_obj)
pr = json_obj
pr_data = []
pr_body = None
for index, row in pr.iterrows():
if index == 0:
... | ci_evaluator/ml/service/formatting/data_formatting.py |
import pandas as pd
import numpy as np
import json
import re
import ast
class DataFormatting():
def format_pr(self, json_obj):
# pr = pd.DataFrame(json_obj)
pr = json_obj
pr_data = []
pr_body = None
for index, row in pr.iterrows():
if index == 0:
... | 0.221856 | 0.268001 |