id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3292115 | from django.conf import settings
from django.shortcuts import render
from django.db.models import Count, Avg, Min, Max, Q
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView, View
from interac... |
3292136 | from __future__ import unicode_literals
import time
import hmac
import hashlib
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
ExtractorError,
float_or_none,
int_or_none,
sanitized_Request,
urlencode_postdata,
xpath_text,
)
class AtresPlayerI... |
3292149 | from openai_ros import robot_gazebo_env
class MyRobotEnv(robot_gazebo_env.RobotGazeboEnv):
"""Superclass for all Robot environments.
"""
def __init__(self):
"""Initializes a new Robot environment.
"""
# Variables that we give through the constructor.
# Internal Vars
... |
3292173 | from gevent import monkey
monkey.patch_all()
import os
os.sys.stdout.write(f'\x1b]2;{os.path.basename(__name__)}\x07\n')
from scibot.bookmarklet import main
app = main()
|
3292249 | import argparse
import collections
import os
from inspect import currentframe
from easydict import EasyDict as edict
frame = currentframe().f_back
while frame.f_code.co_filename.startswith('<frozen'):
frame = frame.f_back
import_from = frame.f_code.co_filename
eval_mode = 0 if 'eval' not in import_from else 1
tra... |
3292273 | import os.path as osp
import csv
import lemoncheesecake.api as lcc
from lemoncheesecake.matching import *
PROJECT_DIR = osp.join(osp.dirname(__file__), "..")
@lcc.suite("suite")
class suite:
@lcc.test("test")
@lcc.parametrized(csv.DictReader(open(osp.join(PROJECT_DIR, "data.csv"))))
def test(self, phras... |
3292304 | class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
sums = [0] + list(itertools.accumulate(nums))
return max(map(operator.sub, sums[k:], sums)) / k
|
3292355 | import torch
from torch import nn
from torch.nn.utils import spectral_norm
from generators.common import blocks
class Wrapper:
@staticmethod
def get_args(parser):
parser.add('--embed_padding', type=str, default='zero', help='zero|reflection')
parser.add('--embed_num_blocks', type=int, default=6... |
3292372 | import argparse
import pandas as pd
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('csvfile', type=str)
return parser.parse_args()
def main():
args = parse_args()
df = pd.read_csv(args.csvfile)
for fold in df['outer'].unique():
train_df = df[df.outer != fol... |
3292376 | class UnknownError(Exception):
pass
class ImageCheckError(Exception):
pass
class ImageAuthenticationError(ImageCheckError):
pass
class ImageNameError(ImageCheckError):
pass
|
3292405 | import segmentation_models_pytorch as smp
import torch
class CombinedLoss(smp.utils.base.Loss):
"""
"""
__name__ = 'loss'
def __init__(
self,
loss_modules,
loss_weights,
**kwargs
):
assert len(loss_modules) == len(loss_weights)
super().__init__(**k... |
3292412 | from __future__ import (
absolute_import, division, print_function, unicode_literals
)
import logging
import argparse
import csv
import os
from doppelganger import (
inputs,
Accuracy,
CleanedData,
Configuration,
HouseholdAllocator,
SegmentedData,
BayesianNetworkModel,
Population,
... |
3292416 | import torch
import torch.nn as nn
from deepproblog.utils.standard_networks import MLP
class EncodeModule(nn.Module):
def __init__(self, in_size, mid_size, out_size, activation=None):
super().__init__()
if activation == "tanh":
self.mlp = MLP(in_size, mid_size, out_size, activation=nn... |
3292430 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import namedtuple
import os
__PATH__ = os.path.abspath(os.path.dirname(__file__))
import tensorflow as tf
import numpy as np
import h5py
import colorlog
from utils import vocab_utils, etc_uti... |
3292466 | import pandas as pd
import bayesianpy
from bayesianpy.network import Builder as builder
import logging
import os
import matplotlib.pyplot as plt
# Demonstrates one-class classification/ unsupervised clustering to identify the likelihood that a sample has been
# generated by the particular model. Useful for building ... |
3292484 | import cv2
import math
import time
import numpy as np
import util
from config_reader import config_reader
from scipy.ndimage.filters import gaussian_filter
from model import get_testing_model
tic=0
# visualize
colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0],
[0,... |
3292490 | import re
from collections import OrderedDict
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
class Scope(object):
def __init__(self, key=None, brace='{', flags='', old_scope=None):
assert brace == '{' or brace == '['
self.brace = brace
self.is_nested... |
3292492 | from functools import reduce
from typing import NamedTuple, Tuple
from . import anndata
class ElementRef(NamedTuple):
parent: "anndata.AnnData"
attrname: str
keys: Tuple[str, ...] = ()
def __str__(self) -> str:
return f".{self.attrname}" + "".join(map(lambda x: f"['{x}']", self.keys))
@... |
3292494 | from lux.utils import test
class TestOpenApi(test.AppTestCase):
config_file = 'tests.rest'
config_params = dict(
API_URL=dict(
BASE_PATH='/v1',
TITLE='test api',
DESCRIPTION='this is just a test api'
)
)
def test_api(self):
app = self.app
... |
3292523 | import asyncio
import inspect
class TaskRunner():
def __init__(self):
self.loop = asyncio.get_event_loop()
self.running_tasks = set()
def run(self, func, *args):
if (func, *args) in self.running_tasks:
return False
self.running_tasks.add((func, *args))
def ... |
3292562 | from .bycython import eval
def distance(*args, **kwargs):
""""An alias to eval"""
return eval(*args, **kwargs)
__all__ = ('eval', 'distance')
|
3292573 | from django.db import models
# Create your models here.
class Schedule(models.Model):
airline = models.CharField(max_length=200)
flight_no = models.CharField(max_length=10)
trip_type = models.CharField(max_length=50)
departure_airport = models.CharField(max_length=10)
... |
3292609 | import os
import shutil
import warnings
from neo.Utils.WalletFixtureTestCase import WalletFixtureTestCase
from neo.Wallets.utils import to_aes_key
from neo.Implementations.Wallets.peewee.UserWallet import UserWallet
from neo.Core.UInt160 import UInt160
from neo.Prompt.Commands.SC import CommandSC
from neo.Prompt.Prompt... |
3292616 | class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
hourAngle = ((hour % 12) + (minutes / 60)) * 30
minuteAngle = (minutes % 60) * 6
diff = abs(hourAngle - minuteAngle)
return min(diff, 360 - diff) |
3292638 | import os
from tqdm import tqdm
import torch
import torchvision
import numpy as np
import random
import cv2
import logging
from .backbones import count_parameters
class FaceEmbeddingModel:
def __init__(self, backbone, header, loss):
self.backbone = backbone
self.header = header
self.lo... |
3292680 | from config import config
class WorkerProvider(object):
def add_task(self, func, *args, **kwargs):
''' Performs a task asynchronously.
:param func: A function to call asynchronously
:param args: Positional arguments to send to the function
:param kwargs: Keyword arguments to ... |
3292732 | import unittest
from minq import *
class LSCanary(object):
"""
Use this as a dummy stream initializer to make sure streams aren't
issuing queries when they shouldn't
"""
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __iter__(self):
ra... |
3292763 | from typing import Optional, Tuple
import numpy as np
from .metrics import sdr_loss, sdr, bss_eval_sources
def si_sdr_loss(
est: np.ndarray,
ref: np.ndarray,
zero_mean: Optional[bool] = False,
clamp_db: Optional[float] = None,
pairwise: Optional[bool] = False,
) -> np.ndarray:
return sdr_loss... |
3292780 | import torch
from torch.utils.data import RandomSampler
from pathlib import Path
import sys
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0].parents[0].parents[0] # CogKGE root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add CogKGE root directory to PATH
from cogkge imp... |
3292793 | import json
import traceback
from datetime import datetime
from sqlalchemy import func
from apps.auth.models.users import User
from apps.jobs.models.jobs import JobsRecord
from apps.project.business.assets import PhoneBorrowBusiness, PhoneBusiness
from apps.project.business.credit import CreditBusiness
from apps.proj... |
3292805 | import plotly.express as px
import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html
from .workout import WORKOUTS
COLORS = {"graph_bg": "#1E1E1E", "text": "#696969"}
def layout_config_panel(current_user):
"""The Dash app layout for the user config panel"""
... |
3292815 | from typing import Any, List, Optional
from fugue import FugueWorkflow
from tune import (
TUNE_OBJECT_FACTORY,
NonIterativeObjectiveLocalOptimizer,
Space,
TrialReport,
optimize_noniterative,
)
from tune._utils import from_base64
from tune.constants import TUNE_REPORT, TUNE_REPORT_METRIC
from tune_... |
3292820 | from .bootstrap import Bootstrap
from .linear import LinearGaussianObservations
from .base import Proposal
from .linearized import Linearized
from .local_linearization import LocalLinearization
|
3292832 | import requests
from clutch import Client as tClient
from deluge_client import DelugeRPCClient
from qbittorrent import Client as qClient
from .helpers import fetch_torrent_url, convert_to_torrent
class torrent:
def __init__(self, id, description, media_type, seeders, leechers, download, size):
self.id = id... |
3292851 | import pandas as pd
import numpy as np
from bayes_opt import BayesianOptimization
from sklearn.base import BaseEstimator
import seldon.pipeline.cross_validation as cf
import logging
logger = logging.getLogger(__name__)
class BayesOptimizer(BaseEstimator):
"""
sklearn wrapper for BayesianOptimization module
... |
3292870 | import inspect
from typing import Any
from typing import Callable
from typing import Optional
from typing import TYPE_CHECKING
from typing import TypeVar
from ddtrace.vendor import wrapt
from .deprecation import deprecated
if TYPE_CHECKING:
import ddtrace
F = TypeVar("F", bound=Callable[..., Any])
def iswra... |
3292882 | import math
import sys
import pygame
from lcp_physics.physics.bodies import Circle, Rect, Hull
from lcp_physics.physics.constraints import TotalConstraint, FixedJoint
from lcp_physics.physics.forces import ExternalForce, Gravity, vert_impulse, hor_impulse
from lcp_physics.physics.utils import Defaults, Recorder
from ... |
3292889 | from mythril.laser.plugin.interface import LaserPlugin
from abc import ABC, abstractmethod
from typing import Optional
class PluginBuilder(ABC):
""" PluginBuilder
The plugin builder interface enables construction of Laser plugins
"""
name = "Default Plugin Name"
def __init__(self):
sel... |
3292891 | import unittest
from mock import patch
from floyd.client.files import get_unignored_file_paths
from tests.client.mocks import mock_fs1
class TestFilesClientGetUnignoredFilePaths(unittest.TestCase):
"""
Tests FileClient get_unignored_file_paths()
"""
@patch('floyd.client.files.os.walk', side_effect=moc... |
3292918 | import unittest
from rxbp.init.initobserverinfo import init_observer_info
from rxbp.observerinfo import ObserverInfo
from rxbp.observers.pairwiseobserver import PairwiseObserver
from rxbp.testing.tobservable import TObservable
from rxbp.testing.tobserver import TObserver
class TestPairwiseObserver(unittest.TestCase)... |
3292929 | from dell_runtime import DellRuntimeProvider
from qiskit import QuantumCircuit
import os
import logging
logging.basicConfig(level=logging.DEBUG)
RUNTIME_PROGRAM = """
# This code is part of qiskit-runtime.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a co... |
3292971 | from collections import Sequence
from itertools import chain
import numpy
from ..base import SearchAlgorithm
from ..connection.splitter import ConnectionSplitter, split_space, transform_suboutput
class ThompsonSampling(SearchAlgorithm):
"""Conditional subspaces exploration strategy.
Thompson sampling ... |
3293006 | import collections
import itertools
import sys
import numpy as np
import pysal as ps
from mpi4py import MPI
from globalsort import globalsort
if __name__ == '__main__':
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
#Phase I: Compute Hi bounds and sort the points - this get the points local to the cores ... |
3293021 | import numpy as np
import trimesh
from pychop3d.configuration import Configuration
def evaluate_nparts_objective(trees, path):
"""Collect the "number of parts" objective for a set of trees
"""
theta_0 = trees[0].nodes[0].n_parts
for tree in trees:
node = tree.get_node(path)
tree.objec... |
3293068 | from behave import when, then
def get_first_followup_row(context):
"""A helper function used by different steps
"""
selector = '.followups tr.form_submission'
rows = context.browser.find_elements_by_css_selector(selector)
return rows[0]
@when('I add a note on the first application that says')
de... |
3293083 | from checkov.common.models.enums import CheckCategories, CheckResult
from checkov.kubernetes.base_spec_check import BaseK8Check
class DefaultNamespace(BaseK8Check):
def __init__(self):
# CIS-1.5 5.7.4
name = "The default namespace should not be used"
# default Service Account and Service/... |
3293146 | from .loss import EvidentialLossSumOfSquares
from .paper_loss import PaperEvidentialLossSumOfSquares
|
3293230 | from pysc2.lib.protocol import ProtocolError
from sc2reaper.score_extraction import get_score
from sc2reaper.state_extraction import get_state
from sc2reaper.action_extraction import get_actions
STEP_MULTIPLIER = 24
# active_frames = [0, 24, 48]
# saltos = [1, 1, 1...,1, 1, 1, 24, 1, 1, 1...]
def jumps(active_fram... |
3293292 | import pyroomacoustics as pra
import numpy as np
from pydub import AudioSegment
from sklearn.utils import shuffle
from glob import glob
import random
import json
import malaya_speech.train as train
import malaya_speech.config
import malaya_speech.train.model.transducer as transducer
import malaya_speech.train.model.con... |
3293319 | import json
# from werkzeug import Response
from functools import wraps
from flask import request, Response
from mrq.context import get_current_config
from mrq.utils import MongoJSONEncoder
def jsonify(*args, **kwargs):
""" jsonify with support for MongoDB ObjectId
"""
return Response(
json.dumps(... |
3293341 | from datetime import timedelta
from django.test.testcases import TestCase
from autoemails import admin
from autoemails.tests.base import FakeRedisTestCaseMixin, dummy_job
ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60
class TestJobResultsLongTTL(FakeRedisTestCaseMixin, TestCase):
def setUp(self):
super().set... |
3293349 | import FWCore.ParameterSet.Config as cms
gctInternJetProducer = cms.EDProducer("L1GctInternJetProducer",
internalJetSource = cms.InputTag("gctDigis"),
centralBxOnly = cms.bool(True)
)
|
3293357 | import numpy as np
import cv2, os, argparse
from glob import glob
from tqdm import tqdm
from plate_number import random_select, generate_plate_number_white, generate_plate_number_yellow_xue
from plate_number import generate_plate_number_black_gangao, generate_plate_number_black_shi, generate_plate_number_black_ling
fr... |
3293395 | from PyObjCTools.TestSupport import *
import objc
import array
import sys
from Foundation import *
from PyObjCTest.testhelper import PyObjC_TestClass3
if sys.version_info[0] == 3:
buffer = memoryview
def array_frombytes(a, b):
return a.frombytes(b)
def array_tobytes(a):
return a.tobytes(... |
3293446 | class IFCExportOptions(object,IDisposable):
"""
IFC Export options.
IFCExportOptions(from: IFCExportOptions)
IFCExportOptions()
"""
def AddOption(self,name,value):
"""
AddOption(self: IFCExportOptions,name: str,value: str)
Adds a new named option to the options structure.
na... |
3293453 | import os
from typing import Dict
from .parser import parser # parser(directory).parser(module)
from .utils import check_path
from .exceptions import InvalidKeyError
class PrefsBase:
FIRST_LINE = "#PREFS"
SEPARATOR_CHAR = "="
ENDER_CHAR = "\n"
CONTINUER_CHAR = ">"
COMMENT_CHAR = "#"
INDENT_CHAR = "\t"
KEY_PAT... |
3293509 | from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class IfWirelessSSIDAuthRemote(RemoteModel):
"""
This table list out the entries of WirelessSSID Authentication.
| ``IfWirelessSSIDAuthID:`` The internal NetMRI identifier of the Wireless SSID Authentication... |
3293519 | import os
from compile_utils import _remove_files_conflicting_with_decompile, _replace_renamed_files
from decompilation_method import S4PyDecompilationMethod
from settings import custom_scripts_for_decompile_source, game_folder, decompile_method_name, custom_scripts_for_decompile_destination, should_decompile_ea_scrip... |
3293539 | import os
import imageio
import yaml
import torch
import torchvision
from torch.utils.data.dataset import Subset
from torchvision.transforms import (CenterCrop, Compose, RandomHorizontalFlip, Resize, ToTensor)
class BigDataset(torch.utils.data.Dataset):
def __init__(self, folder):
self.folder = folder
... |
3293564 | class Solution:
def totalNQueens(self, n: int) -> int:
self.count = 0
def dfs(cols, pie, na, row):
if row >= n:
self.count += 1
return
bits = (~(cols|pie|na)) & ((1<<n) - 1)
while bits:
p = bits & -bits
bits = bits & (bits - 1)
dfs(cols|p, (pie|p)<<1, ... |
3293585 | import os
from multiprocessing import Pool
def run(idx, test_img_dst_path, test_img_names, img_names):
fw = open(os.path.join(test_img_dst_path, "images_list" + "_" + str(idx) + ".txt"), "w")
img_name = img_names[idx][:-5]
for te_img in test_img_names:
if img_name in te_img:
fw.write(t... |
3293586 | from tir import Webapp
import unittest
from tir.technologies.apw_internal import ApwInternal
import datetime
import time
DateSystem = datetime.datetime.today().strftime('%d/%m/%Y')
DateVal = datetime.datetime(2120, 5, 17)
"""-------------------------------------------------------------------
/*/{Protheus.doc} PLSA298T... |
3293593 | from .delete_nth import *
from .flatten import *
from .garage import *
from .josephus import *
from .longest_non_repeat import *
from .max_ones_index import *
from .merge_intervals import *
from .missing_ranges import *
from .move_zeros import *
from .plus_one import *
from .rotate import *
from .summarize_ranges impor... |
3293660 | from abc import ABC, abstractmethod
__all__ = ["OdometryProvider"]
class OdometryProvider(ABC):
r"""Base class for all odometry providers.
Your providers should also subclass this class. You should override the `provide()` method.
"""
def __init__(self, *params):
r"""Initializes internal Od... |
3293698 | import json
def dict_to_json(value: dict) -> str:
return json.dumps(value, indent=2)
def json_to_dict(value: str) -> dict:
return json.loads(value)
|
3293716 | from unittest import TestCase
import os
import shutil
from foster.build import Build
from foster.test import Test
class TestTestCase(TestCase):
def setUp(self):
root = os.path.join(os.path.dirname(__file__), 'frames', 'init')
os.chdir(root)
def test_test_command_does_not_run_if_package_is_n... |
3293748 | from random import *
N = 100
n = randrange(2,N+1)
m = randrange(1,1+(n*(n+1)))
print n,m
for i in xrange(m):
a = randrange(1,n+1)
b = randrange(1,n+1)
print a, b
|
3293755 | from .demoproject.settings import *
ROOT_URLCONF = 'demoproject.demoproject.urls'
ADMIN_TOOLS_MENU = 'demoproject.menu.CustomMenu'
ADMIN_TOOLS_INDEX_DASHBOARD = 'demoproject.dashboard.CustomIndexDashboard'
ADMIN_TOOLS_APP_INDEX_DASHBOARD = 'demoproject.dashboard.CustomAppIndexDashboard'
FIXTURE_DIRS = (
'demop... |
3293757 | import sys
import os
import numpy as np
from scipy import ndimage as ndimage
from matplotlib import image as mpimg
import cv2
input_filename = sys.argv[1]
output_filename = sys.argv[2]
img = mpimg.imread(input_filename)
output_image = ndimage.gaussian_filter(img, sigma=2)
output_image = output_image.astype('uint16')... |
3293801 | from discord import Client, Message
from src.utils.readConfig import getLanguageConfig
import embedLib.help.anonymityBoard as help
languageConfig = getLanguageConfig()
async def getHelpForAnnomity(self: Client, message: Message):
embed = help.getEmbed()
await message.channel.send(embed=embed) |
3293802 | import logging
from colorlog import ColoredFormatter
def get_logger(name=__name__):
logger_base = logging.getLogger(name)
logger_base.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler()
color_formatter = ColoredFormatter('%(log_color)s[%(module)-15s][%(funcName)-15s][%(levelname)-8s] %(me... |
3293824 | import unittest
from conjur.data_object.host_resource_data import HostResourceData
class HostResourceDataTest(unittest.TestCase):
def test_host_data_constructor(self):
mock_action = None
mock_host_to_update = None
host_resource_data = HostResourceData(action=mock_action, host_to_update=mo... |
3293855 | import numpy as np
import os
from astronomaly.base.base_pipeline import PipelineStage
try:
from keras.models import load_model
from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
except ImportError:
print("Failed to import Keras. Deep learning will be unava... |
3293863 | import re
class InputValidator:
@staticmethod
def is_cve_code(data):
if re.match("CVE-\d{4}-\d+", data):
return True
return False
|
3293923 | result = "subpackage_1"
class PackageBSubpackage1Object_0:
__slots__ = ["obj"]
def __init__(self, obj):
self.obj = obj
def return_result(self):
return result
|
3293938 | import pya
# Netlist extraction will merge straight+bend sections into waveguide (1),
# or extract each bend, straight section, etc. (0)
#WAVEGUIDE_extract_simple = 1
SIMPLIFY_NETLIST_EXTRACTION = True
# Create GUI's
from .core import WaveguideGUI, MonteCarloGUI, Net, Component
WG_GUI = WaveguideGUI()
MC_GUI = MonteC... |
3293953 | from distutils.core import setup
setup(name='ftrobopy',
description='Python Interface for Fischertechnik ROBOTICS TXT Controller',
version='1.80',
author='<NAME>',
author_email='<NAME>',
url='https://github.com/ftrobopy/ftrobopy',
download_url='https://github.com/ftrobopy/ftrobopy/a... |
3293965 | import threading, time
from MongoDB import MongoDB
class Quick_update(object):
def __init__(self, update_rank_list):
self.db = MongoDB(update_rank_list=update_rank_list)
self.target_dict = {}
# print('Update once when initialized & take a look at time')
start_time = time.time()
... |
3293975 | from django.contrib import admin
from .models import FirstAnswerReview,FirstQuestionReview
from .models import LateAnswerReview
# from .models import QuestionEdit
from .models import CloseQuestionVotes, ReviewQuestionReOpenVotes
from .models import ReviewCloseVotes,ReOpenQuestionVotes,QuestionEditVotes
from .models im... |
3294003 | def problem3_7(csv_pricefile, flower):
import csv
fin = open(csv_pricefile)
#fout = open(new_name,'w',newline = '')
#ct = 0
#tot_weight = 0.0
for row in csv.reader(fin):
#print(row[0]," ",row[1])
if row[0] == flower:
print(row[1])
fin.close()
#fout.close()
#c... |
3294078 | from django import template
import decimal
register = template.Library()
@register.filter
def demand_collections_difference(demand, collection):
if demand is None:
demand = 0
if collection is None:
collection = 0
diff = decimal.Decimal(decimal.Decimal(demand) - decimal.Decimal(collection))... |
3294084 | from .mixture import Labels, CRPLabels, Mixture, MixtureDistribution, CollapsedMixture, CRPMixture
from .factor_analysis import FactorAnalysis |
3294089 | from typing import List, Union
from aiogram.dispatcher.filters import BaseFilter
from aiogram.types import TelegramObject
from pydantic import validator
from sqlalchemy.orm import Session
from app.domain.access_levels.models.access_level import LevelName
from app.domain.user.dto.user import User
class AccessLevelFi... |
3294126 | import Task
import Utils
from TaskGen import extension, before, feature
import hashlib, sys, os
# NOTE: This must be included explicitly prior to any modules with fields that set [(resource) = true].
# Otherwise field_desc.GetOptions().ListFields() will return [] for the first loaded module
# Strange error and probabl... |
3294146 | from flask import Flask, render_template, jsonify, json, url_for, request, redirect, Response, flash, abort, make_response, send_file
import requests
import io
import os
import csv
import datetime
import investmentportfolio
print ('Running Portfolio Analyze')
app = Flask(__name__)
# On IBM Cloud, get the port number ... |
3294154 | from . import fields
from .fields import BaseField
from .helpers import Pluck
from .nested import Nested
from .schema import ModelSchema, ModelSchemaMeta
|
3294202 | import itertools
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report,confusion_matrix
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
... |
3294211 | import json
import click
from libraries import (
annoy_example,
catboost_example,
fastai_example,
gensim_example,
keras_example,
lightgbm_example,
mxnet_example,
onnx_example,
prophet_example,
pytorch_example,
pytorch_lightning_example,
raw_file_example,
sklearn_exa... |
3294226 | import torch
from eqv_transformer.classfier import Classifier
from eqv_transformer.eqv_attention import EquivariantTransformer
from lie_conv.lieGroups import SE3, SE2, SO3, T, Trivial
# from lie_conv.datasets import SE3aug
from forge import flags
flags.DEFINE_boolean(
"data_augmentation",
False,
"Apply... |
3294241 | from unittest import TestCase
from SEAL import SplineFunction
from SEAL.lib import evaluate_blossom
class TestEvaluateBlossom(TestCase):
def test_evaluate_blossom(self):
p = 2
t = [0, 0, 0, 1, 2, 2, 2]
c = [-1, 1, -1, 1]
f = SplineFunction(p, t, c)
cases = [(2, 0.5), (2,... |
3294251 | import logging
from dotenv import find_dotenv, dotenv_values
def load_config():
""" Load the variables from the .env file
Returns:
.env variables(dict)
"""
logger = logging.getLogger(__name__)
dot_env_path = find_dotenv(raise_error_if_not_found=True)
logger.info(f"Found config in {do... |
3294259 | import inspect
def arg_list(fn):
return list(inspect.signature(fn).parameters.keys())
def calling_module():
frm = inspect.stack()[1]
mod = inspect.getmodule(frm[0])
return mod
def calling_module_name():
mod = calling_module()
return mod.__name__
|
3294264 | import argparse
from act.actiontype import ActionType
from arguments import Arguments
from sample.languagetype import LanguageType
from settings import *
from utils import inout
class ArgsParser:
def __init__(self):
self.parser = argparse.ArgumentParser()
self.init_arguments()
self.argume... |
3294290 | import datetime
from context_manager.db_context_manager import DBContextManager
from util.constants import QUERIES
def export_results(data, controller_name, trajectory_name, database_path):
def get_table_name(controller, trajectory, date_time):
return '_'.join([controller,
trajec... |
3294291 | from .model import MAB, SAB, ISAB, PMA, SetTransformerEncoder, SetTransformerDecoder, SetTransformer |
3294304 | from appannie.util import format_request_data
class Keyword(object):
EXPLORER_ENDPOINT = '/apps/{market}/keywords/explorer'
RANKED_ENDPOINT = '/apps/{market}/app/{product_id}/keywords/ranked'
PERFORMANCE_ENDPOINT = '/apps/{market}/app/{product_id}/keywords/ranks'
def __init__(self, http_client, marke... |
3294313 | from django.db import models
import reversion
from tally_ho.apps.tally.models.ballot import Ballot
from tally_ho.apps.tally.models.center import Center
from tally_ho.apps.tally.models.station import Station
from tally_ho.apps.tally.models.tally import Tally
from tally_ho.libs.models.base_model import BaseModel
class... |
3294322 | import lightgbm as lgbm
import numpy as np
import pandas as pd
from sklearn.model_selection import KFold
from tqdm import tqdm
X_train = pd.read_pickle("data/train.pkl")
X_test = pd.read_pickle("data/test.pkl")
y_train = np.log1p(X_train.pop("quantity"))
X_train = X_train.astype(np.float32)
X_test = X_test.astype(np... |
3294354 | from django import forms
from utilities.forms import BootstrapMixin, ExpandableIPAddressField
__all__ = (
'IPAddressBulkCreateForm',
)
class IPAddressBulkCreateForm(BootstrapMixin, forms.Form):
pattern = ExpandableIPAddressField(
label='Address pattern'
)
|
3294396 | import asyncio
import bisect
import random
from . import logger, util
from .constants import ValueType
from .encodings import ValueRepresentation
"""
Update interval between update runs (in seconds).
"""
DEFAULT_UPDATE_FREQUENCY = 5
"""
Interval between reinit runs (in seconds).
"""
DEFAULT_REINIT_RATE = 60
class ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.