id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
156348 | from app.services.steps import *
from flask import g, current_app
class SessionManager():
"""
Session manager is responsible for taking in a registrant and current step and then determining which step needs to be performed next.
"""
# initialize these as None, override them with init method if valid.
... |
156361 | import os
from typing import Any, Dict
name: str
env: Dict[Any, Any] = dict(os.environ)
def set_name(new_name: str) -> None:
global name
name = new_name
def set_env(env_to_set: dict) -> None:
global env
env.update(env_to_set)
def unset_env(env_to_unset: dict) -> None:
for k in env_to_unset:
... |
156411 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import six
import typing # NOQA: F401
from nixnet import _funcs
from nixnet import constants
class DbcAttributeCollection(collections.Mapping):
"""Collection for accessing DBC attribu... |
156413 | from queue import Queue
class Gate():
def __init__(self, id_num, gate_type, input_ids, gate_queue=None, ready=False, const_input=None):
self.id_num = id_num
self.gate_type = gate_type
self.input_ids = input_ids
self.inputs = {}
for in_id in input_ids:
self.inputs... |
156439 | import re
class HostDetailsWrapper:
"""Klasa pomocnicza - wrapper parsujacy dane z serwisu https://www.shodan.io/."""
def __init__(self, ip, host_details):
self.__ip = ip
self.__data = host_details
@property
def ip(self):
"""Atrybut zwracajacy adres ip hosta."""
retur... |
156504 | from bs4 import BeautifulSoup
import re
import time
import requests
headers0 = {'User-Agent':"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36"}
def Musappend(Mdict,Items):
for it in Items:
title=it('a')[0].get_text(strip=True)
date=it(class_... |
156506 | from ._legendre import Legendre, Legendre_Normalized
from ._laguerre import Laguerre
from ._hermite import Hermite, Hermite2
from ._chebyshev import Chebyshev, Chebyshev2
from ._jacobi import Jacobi
__all__ = ['Legendre', 'Legendre_Normalized', 'Laguerre', 'Hermite', 'Hermite2', 'Chebyshev', 'Chebyshev2', 'Jacobi'] |
156510 | import platform
if platform.system() == 'Darwin':
from mac_graph_traversal import *
else:
from graph_traversal import * |
156671 | import src.Exceptions as Exception
from src.Parser import Parser
from src.Interpreteur import Interpreteur
import time
import sys
import json
settings = json.load(open("settings.json", "r"))
ERROR_MESSAGE = settings["main"]["ERROR_MESSAGE"]
args = sys.argv
if len(sys.argv) < 2:
raise Exception.NotEnoughArguments(... |
156688 | import argparse
import os
import sys
import torch
from torch import nn
import torchtext
from torchtext import data
from torchtext import datasets
from eval_args import get_arg_parser
from performance import size_metrics
import utils
from models.components.binarization import (
Binarize,
)
def main() -> None:
... |
156709 | import json
from pathlib import Path
import typer
def get_skill_config(name=None):
app_dir = Path(typer.get_app_dir('skills-cli', force_posix=True))
config_file = app_dir / 'config.json'
if not app_dir.exists():
typer.echo('Creating default configuration')
app_dir.mkdir(parents=True)
... |
156723 | import unittest
from accelergy import helper_functions as hf
class TestHelperFunctions(unittest.TestCase):
def test_oneD_linear_interpolation(self):
""" linear interpolation on one hardware attribute """
# Rough estimation of simple ripple carry adder: E_adder = E_full_adder * bitwidth + E_misc
... |
156734 | n = int(input("Enter N: "))
l = []
for i in range(0 , n):
inp = int(input("Enter numbers: "))
l.append(inp)
l.sort()
a = 0
b = 0
for i in range(0 , n):
if i % 2 != 0:
a = a * 10 + l[i]
else:
b = b * 10 + l[i]
c = a + b
print(c)
|
156750 | import numpy as np
class HMM:
def __init__(self, A=None, B=None, pi=None):
self.A = A
self.B = B
self.pi = pi
def forward(self, O, detailed=False):
alpha = self.pi*self.B[:, O[0]]
if detailed:
print("alpha: {}".format(alpha))
for t in range(1, len(O))... |
156757 | import os
import unittest
import logging
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
from slicer.util import VTKObservationMixin
#
# SegmentCrossSectionArea
#
class SegmentCrossSectionArea(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.... |
156769 | import asyncio
import itertools
from typing import Optional, Dict, Any, Union, List
import logging
import websockets
import json
from web3 import Web3
from .subscription import Subscription
from .methods import RPCMethod
from .contract import DeployedContract
from .types import Wei, Address, HexString
from .transport ... |
156787 | from lxml import etree
def create_property_node(parentNode, key, value):
if value.startswith('"'):
propertyNode = etree.SubElement(parentNode, "Property", id=key, value=value.strip('"'), type="str")
else:
propertyNode = etree.SubElement(parentNode, "Property", id=key, value=value, type="num")
... |
156794 | import pytest
from metaspace.tests.utils import sm
def test_get_all_projects(sm):
projects = sm.projects.get_all_projects()
assert len(projects) > 0
def test_get_my_projects(sm):
projects = sm.projects.get_my_projects()
assert len(projects) > 0
assert all(p['currentUserRole'] for p in project... |
156795 | from pymusicdl.modules.common import common
from pymusicdl.modules.spotify_downloader import spotify_downloader
from pymusicdl.modules.ytDownloader import yt_downloader
from pymusicdl.modules.picker import * |
156823 | from pathlib import Path
import re
# ref: https://extendsclass.com/regex/e6adb72
empty_classdef = (
r"(?P<indent1> ?)class\s*(?P<class>\s*.+\s*):(?P<LF>\r?\n)(?P<indent2> +)''\r?\n"
)
re_classdef = re.compile(empty_classdef, flags=re.MULTILINE)
repl_classdef = r"\g<indent1>class \g<class>:\g<LF>\g<indent2>def __i... |
156827 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
try:
from pypandoc import convert
read_md = lambda f: convert(f, 'rst')
except ImportError:
print("warning: pypandoc module not found,"
"could not convert markdown README to RST")
read_md = lambda f... |
156838 | import numpy as N
from traits.api import (HasTraits, Array, Range, Instance, Enum)
from traitsui.api import View, Item
from chaco.api import (ArrayPlotData, Plot, PlotLabel, ColorMapper, gray, pink,
jet)
from chaco.default_colormaps import fix
from enable.api import ComponentEditor
from AwesomeColorMaps import awes... |
156876 | import os
from experiments.experiments import ModelSelectionExperiment
from nilmlab.lab import TimeSeriesLength
dirname = os.path.dirname(__file__)
single_building_exp_checkpoint = os.path.join(dirname, '../results/cv1h.csv')
exp = ModelSelectionExperiment(cv=5)
exp.set_ts_len(TimeSeriesLength.WINDOW_1_HOUR)
exp.set... |
156897 | from abc import abstractmethod
from numpy import eye, shape
from numpy.linalg import pinv
class Kernel(object):
def __init__(self):
pass
@abstractmethod
def kernel(self, X, Y=None):
raise NotImplementedError()
@staticmethod
def centering_matrix(n):
"""
Returns th... |
156971 | import ray
from environment.rrt import RRTWrapper
from environment import utils
from environment import RealTimeEnv
from utils import (
parse_args,
load_config,
create_policies,
exit_handler
)
from environment import TaskLoader
import pickle
from signal import signal, SIGINT
from numpy import mean
from ... |
157113 | p=21888242871839275222246405745257275088696311157297823662689037894645226208583
print("over 253 bit")
for i in range (10):
print(i, (p * i) >> 253)
def maxarg(x):
return x // p
print("maxarg")
for i in range(16):
print(i, maxarg(i << 253))
x=0x2c130429c1d4802eb8703197d038ebd5109f96aee333bd027963094f5bb33ad
y =... |
157118 | import hashlib
import json
import os
from argparse import ArgumentParser, Namespace
from collections import defaultdict
from copy import deepcopy
from functools import partial
from typing import Dict, List, Optional, Type
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch... |
157150 | from app.models.APNDevice import APNDevice
from app.instances import db
from app.instances.redis import redis_db
from app.models.User import User
from os import urandom
from uuid import UUID
from flask import g
pn_redis_id_prefix = 'pn-id:'
pn_redis_id_time = 60 * 2 # In seconds
def is_valid_webapn_version(version... |
157206 | from quart import jsonify, request
from quart_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity
)
from __main__ import app
from pkg.common import user
@app.route('/login', methods=['POST'])
async def login():
if not request.is_json:
return jsonify({"msg": "Missin... |
157207 | import numpy as np
import pytest
import psyneulink.core.components.functions.nonstateful.selectionfunctions as Functions
import psyneulink.core.globals.keywords as kw
import psyneulink.core.llvm as pnlvm
from psyneulink.core.globals.utilities import _SeededPhilox
np.random.seed(0)
SIZE=10
test_var = np.random.rand(SI... |
157216 | from Foundation import *
from AppKit import *
from PyObjCTools import AppHelper
from collections import deque
import contextlib
from enum import Enum
import os
from pathlib import Path
import shutil
import subprocess
import sys
from . import ezntfs
from . import __version__
def create_icon(symbol, description, fall... |
157254 | from data_vault import clean_line
from data_vault.parsing import unquote, bool_or_str
def test_clean_line():
pieces = clean_line('from module import a, b, c')
assert pieces == ['from', 'module', 'import', 'a,b,c']
# commas
pieces = clean_line('from "a/path/with/c,o,m,m,a,s" import a, b, c')
asser... |
157255 | import Confidential
message = Confidential('top secret text')
secret_field = Confidential.getDeclaredField('secret')
secret_field.setAccessible(True) # break the lock!
print 'message.secret =', secret_field.get(message)
|
157265 | import FWCore.ParameterSet.Config as cms
import FWCore.ParameterSet.VarParsing as VarParsing
from PhysicsTools.PatAlgos.tools.helpers import getPatAlgosToolsTask
import sys
process = cms.Process("Analyzer")
patAlgosToolsTask = getPatAlgosToolsTask(process)
## defining command line options
options = VarParsing.VarPar... |
157283 | import os
import torch
from torchvision import transforms
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def get_domains(dataset_name):
return globals()[dataset_name].DOMAINS
class ImageDataset(torch.utils.data.Dataset):
def __init__(self, file_path, image_dir, transform=None):
... |
157311 | from django import forms
from django.forms.extras.widgets import SelectDateWidget
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
import models
from django.forms.widgets import RadioSelect, CheckboxSelectMultiple
from systems.models im... |
157312 | from PIL import Image
from numpy import *
from scipy.ndimage import measurements,morphology
"""
This is the morphology counting objects example in Section 1.4.
"""
# load image and threshold to make sure it is binary
im = array(Image.open('../data/houses.png').convert('L'))
im = (im<128)
labels, nbr_objects = measu... |
157333 | import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Ruijie EG Easy Gateway Password Leak''',
"description": '''Ruijie EG Easy Gateway login.php has CLI command injection, which leads to the disclosure of administrator account and password vulnerability'... |
157335 | from functools import partial
from mkreports.md import MdProxy
def test_md_proxy(page_info):
md_proxy = MdProxy(page_info=page_info, md_defaults=dict(Table=dict(max_rows=1000)))
test_table = md_proxy.Table
assert isinstance(test_table, partial)
assert test_table.keywords["max_rows"] == 1000
|
157364 | import logging
from metadrive.component.road_network.node_road_network import NodeRoadNetwork
import numpy as np
from panda3d.core import TransparencyAttrib, LineSegs, NodePath
from metadrive.component.lane.circular_lane import CircularLane
from metadrive.component.map.base_map import BaseMap
from metadrive.component... |
157380 | from importlib import import_module
import celery
from girder_worker_utils import decorators
import six
from stevedore import extension
#: Defines the namespace used for plugin entrypoints
NAMESPACE = 'girder_worker_plugins'
def _handle_entrypoint_errors(mgr, entrypoint, exc):
raise exc
def get_extension_ma... |
157388 | from unittest.mock import MagicMock
import bspump.unittest
import bspump.common
class TestStringToBytesParser(bspump.unittest.ProcessorTestCase):
def test_string_to_bytes_parser(self):
events = {
(None, 'some string'),
(None, 'another string'),
(None, 'last string'),
}
self.set_up_processor(bspump.... |
157389 | import os
from pytorch_pretrained_bert.tokenization import BertTokenizer
import preprocess_pretraining
import torch
from utils import seek_random_offset
from random import random as rand
from random import randint, shuffle
class DataLoader():
""" Load sentence pair from corpus """
def __init__(self, file, ba... |
157390 | from django.urls import path
from . import views
from .views import AutoCreate
urlpatterns = [
path('owner/<int:owner_id>/', views.detail),
path('', AutoCreate.as_view())
] |
157402 | def login_required(func):
def not_logged_in(self, **kwargs):
self.send_login_required({'signin_required': 'you need to sign in'})
return
def check_user(self, **kwargs):
user = self.connection.user
if not user:
return not_logged_in(self, **kwargs)
return func(... |
157409 | from flask_restplus import Namespace, reqparse, Resource
from flask import make_response, jsonify
from controller.manager import *
import os
name_space = Namespace("case-runner", description="Case Runner")
runner_param = reqparse.RequestParser()
runner_param.add_argument("status", required=True, type=str, location="j... |
157419 | from AMZN import AMZN_BOT
from BSTBUY import BSTBUY_BOT
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from dotenv import load_dotenv
from selenium.common.exceptions import WebDriverException
import threading
import time
import os
load_dotenv()
USE_AMZN = os.getenv("USE_AMZN")
US... |
157447 | import numpy as np
import torch
import torchvision.utils as vutils
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
#import pandas as pd
import seaborn as sns
sns.set()
sns.set_style('whitegrid')
sns.set_palette('colorblind')
def convert_npimage_torchimage(image):
return 255*torch.transpo... |
157458 | from pyULIS4 import *
import math
# Keep in mind the coordinate system
# starts at (0;0) in the bottom left
# corner, since we are working in an
# OpenGL context.
pool = FThreadPool()
queue = FCommandQueue( pool )
fmt = Format_RGBA8
ctx = FContext( queue, fmt )
canvas = FBlock( 800, 600, fmt )
temp = F... |
157485 | import torch
import numpy as np
class FFNet(torch.nn.Module):
"""Simple class to implement a feed-forward neural network in PyTorch.
Attributes:
layers: list of torch.nn.Linear layers to be applied in forward pass.
activation: activation function to be applied between layers.
"""
... |
157528 | from library.api.db import EntityModel, db
class JobsRecord(EntityModel):
ACTIVE = 0
DISABLE = 1
job_id = db.Column(db.String(100)) # Job id
result = db.Column(db.String(1000)) # Job 结果
log = db.Column(db.Text) # Job log
|
157574 | import uuid
"""Class to create the cases s3 bucket for asset storage"""
class CaseBucket(object):
def __init__(self, case_number, region, client, resource):
self.region = region
self.case_number = case_number
self.client = client
self.s3 = resource.connect()
self.bucket = ... |
157603 | import logging
import os
import requests
from typing import Any, List, Optional, Text, Dict
import rasa.utils.endpoints as endpoints_utils
from rasa.shared.nlu.constants import ENTITIES, TEXT
from rasa.nlu.config import RasaNLUModelConfig
from rasa.nlu.extractors.extractor import EntityExtractor
from rasa.nlu.model im... |
157649 | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class Configuration(object):
def __init__(self, **kwargs):
self.defaults = kwargs
def __getattr__(self, k):
try:
return getattr(settings, k)
except AttributeError:
if k i... |
157659 | import gc
import os
import logging
import numpy as np
import tensorflow as tf
from nlp_toolkit.classifier import Classifier
from nlp_toolkit.labeler import Labeler
from nlp_toolkit.data import Dataset
from nlp_toolkit.config import YParams
logging.basicConfig(level=logging.INFO)
try:
import GPUtil
from keras.... |
157680 | class Solution:
def shortestWordDistance(self, words, word1, word2):
i1 = i2 = -1
res, same = float("inf"), word1 == word2
for i, w in enumerate(words):
if w == word1:
if same: i2 = i1
i1 = i
if i2 >= 0: res = min(res, i1 - i2)
... |
157683 | import os
import re
import glob
import numpy as np
import matplotlib.pylab as plt
import matplotlib
from scipy.spatial import ConvexHull
from scipy.interpolate import interp1d
from itertools import chain, count
from collections import defaultdict
from os import makedirs
from os.path import isdir, isfile,... |
157693 | ONTOLOGY_MINABLE = True
try:
import classifier.classifier as CSO
except:
ONTOLOGY_MINABLE = False
print("No CSO Classifier Present")
from typing import List
from .record import ArxivIdentity,Ontology,ArxivSematicParsedResearch
class OntologyMiner:
is_minable = ONTOLOGY_MINABLE
@staticmethod
... |
157755 | def is_palindrome(line: str) -> bool:
# Здесь реализация вашего решения
pass
print(is_palindrome(input().strip()))
|
157759 | import math
import os
import torch
import numpy as np
## Code taken from https://github.com/hassony2/kinetics_i3d_pytorch/blob/master/src/i3dpt.py
def get_padding_shape(filter_shape, stride, mod=0):
"""Fetch a tuple describing the input padding shape.
NOTES: To replicate "TF SAME" style padding, the padding ... |
157765 | line = input()
abbr = line[0]
for i in range(len(line)):
if line[i] == "-":
abbr += line[i+1]
print(abbr)
|
157777 | import hashlib
import json
import sys
import time
import types
import warnings
try:
from urllib.request import build_opener, HTTPRedirectHandler
from urllib.parse import urlencode
from urllib.error import URLError, HTTPError
string_types = str,
integer_types = int,
numeric_types = (int, float)
... |
157801 | from russian_g2p import Grapheme2Phoneme
from russian_g2p import Accentor
import json
import codecs
words = open('/home/a117/Документы/Linguistics/russian_g2p/corpus/wordlist')
words = words.readlines()
# words = ['я']
# acc = Accentor()
g2p = Grapheme2Phoneme()
new_simple_words = {}
with open('new', 'w') as f:
fo... |
157804 | from gamechangerml.src.search.sent_transformer.finetune import STFinetuner
from gamechangerml.configs.config import EmbedderConfig
from gamechangerml.api.utils.pathselect import get_model_paths
from gamechangerml.api.utils.logger import logger
import argparse
import os
from datetime import datetime
model_path_dict = g... |
157819 | from typing import Callable, Dict, Iterable, Optional, Tuple, Type
from urllib.parse import parse_qs, urlparse
import pytest
from rest_registration.utils.signers import URLParamsSigner
from tests.helpers.timer import Timer
def assert_valid_verification_url(
url: str,
expected_path: Optional[str] = N... |
157822 | from civil_registry.models import Citizen
from register.models import SMS
# Ripped from the DB but with some capitalization.
CARRIER_CODING = {2: 'Libyana',
3: 'AlMadar',
4: 'Thuraya'}
# The code could be refactored further to allow mixed case
# string values as in SMS.DIRECTION_CH... |
157846 | import yaml
# 填充默认设置
default_config = {
'debug_mode': False,
'save_manifest_file': True,
'output_path': './output',
'proxy': None,
'downloader_max_connection_number': 5,
'downloader_max_retry_number': 5,
'friendly_console_output': False,
'header': {
'referer': 'https://manhua.dm... |
157884 | import cvlog as log
import cv2
import numpy as np
from .utils import read_file, remove_dirs, get_html
def test_log_image():
remove_dirs('log/')
img = cv2.imread("tests/data/orange.png")
log.set_mode(log.Mode.LOG)
log.image(log.Level.ERROR, img)
logitem = get_html('log/cvlog.html').select('.log-list... |
157964 | import krpc
import time
conn = krpc.connect(name="UI Test")
vessel = conn.space_center.active_vessel
kerbin_frame = vessel.orbit.body.reference_frame
orb_frame = vessel.orbital_reference_frame
srf_frame = vessel.surface_reference_frame
surface_gravity = vessel.orbit.body.surface_gravity
current_roll = conn.add_stre... |
158006 | from .config import Config
from .lsi_text import Text
class LsiVisualTransforms():
def __init__(self):
"""
Visual Transforms (for item).
e.g. set color, set indent.
"""
# Set Config
self.config = Config()
def _add_indent_to_new_line(self, item, prev_status):
... |
158023 | import os
import sys
from JciHitachi import __author__, __version__
git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
requirements_txt_path = os.path.join(git_repo_path, "requirements.txt")
requirements_test_txt_path = os.path.join(git_repo_path, "requirements_test.txt")
sys.path.append(gi... |
158037 | import pygame
from .component import Component
from .colours import *
class EmoteComponent(Component):
def __init__(self,
# required parameters
image,
# optional parameters
timed=True,
timer=200,
):
self.key = 'emote'
# store the pa... |
158068 | from collections import defaultdict
import sys
def subArraylen(arr, n, K):
mp = defaultdict(lambda: 0)
mp[arr[0]] = 0
for i in range(1, n):
arr[i] = arr[i] + arr[i - 1]
mp[arr[i]] = i
ln = sys.maxsize
for i in range(n):
if(arr[i] < K):
continue
else:
... |
158074 | import pandas as pd
from .paramdb import *
from .file import *
from .utils import *
from doit.tools import run_once
def print_nested_df(orig):
dfs = [None]
def dedf(x):
if isinstance(x, pd.DataFrame):
i = len(dfs)
dfs.append(x)
return f"df{i}"
return x
dfs[0] = orig.applymap(dedf)
f... |
158121 | from bitmovin.utils import Serializable
from bitmovin.resources.enums import S3SignatureVersion
from . import AbstractOutput
class GenericS3Output(AbstractOutput, Serializable):
def __init__(self, access_key, secret_key, bucket_name, host, port=None, signature_version=None, ssl=None, id_=None, custom_data=None,
... |
158179 | from copy import copy
from typing import Union
import numpy as np
from fedot.core.data.data import InputData, OutputData
from fedot.core.data.multi_modal import MultiModalData
from fedot.core.operations.evaluation.operation_implementations.data_operations.ts_transformations import ts_to_table
from fedot.core.reposito... |
158181 | from PhysicsTools.Heppy.analyzers.objects.JetAnalyzer import JetAnalyzer
from PhysicsTools.Heppy.analyzers.objects.LeptonAnalyzer import LeptonAnalyzer
from PhysicsTools.Heppy.analyzers.objects.METAnalyzer import METAnalyzer
from PhysicsTools.Heppy.analyzers.objects.PhotonAnalyzer import PhotonAnalyzer
from PhysicsTool... |
158182 | def aio_documented_by(original):
def wrapper(target):
target.__doc__ = "Aio function: {original_doc}".format(original_doc=original.__doc__)
return target
return wrapper
def documented_by(original):
def wrapper(target):
target.__doc__ = original.__doc__
return target
r... |
158209 | import os
def delete_old_logs():
log_path = "logs"
error = False
for root, dirs, files in os.walk(log_path):
for file in files:
path = os.path.join(root, file)
try:
os.remove(path)
except Exception as e:
... |
158266 | import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 50)
y = np.cos(np.linspace(0, 0.5 * np.pi))
plt.title("curve")
plt.grid()
plt.xlim(-1, 1)
plt.ylim(-1.05, +1.05)
plt.plot(x, y)
plt.show()
|
158336 | from ndfinance.brokers.backtest import *
from ndfinance.core import BacktestEngine
from ndfinance.analysis.backtest.analyzer import BacktestAnalyzer
from ndfinance.analysis.technical import RateOfChange
from ndfinance.visualizers.backtest_visualizer import BasicVisualizer
from ndfinance.strategies.trend import ActualMo... |
158371 | def Qklnu(cfg,k,l,nu) : #function q=Qklnu(k,l,nu)
#
#% Computes Q, neccesary constant#% Computes Q, neccesary consta... |
158376 | from src.stores.amazon import *
class AmazonSimulation:
@staticmethod
def test(url):
page = get_page(url)
text = page.text
content = page.content
tree = html.fromstring(content)
price = get_price(tree)
mpn = get_mpn(text)
print(price)
print(mp... |
158390 | import torch
import torchvision
import os
from torch import optim
from torch.autograd import Variable
from model import Discriminator
from model import Generator
class Solver(object):
def __init__(self, config, data_loader):
self.generator = None
self.discriminator = None
self.g_optimizer ... |
158392 | import json
import random
from collections import defaultdict
import heapq
import pymysql.cursors
import os
# Connect to the database
import sys
connection = pymysql.connect(host=os.getenv("DB_HOST", "localhost"),
user=os.getenv("DB_USER", "root"),
password=os.... |
158429 | from logging import addLevelName
from multiprocessing import Event
# Our custom log severity. We need this because we want to see some special messages and on node the default log level
# of workers is set to WARNING (INFO would be too much noise). These messages are not errors nor warnings, but can help
# in some sit... |
158441 | from invoicing.latex.latex_templating import LatexTemplating
class LatexInvoice(LatexTemplating):
def generate(self, reference_code, company_name, company_address, created_at, total_cost, jobs):
template = self.latex_jinja_env.get_template('templates/Invoice.example.tex')
if len(jobs) == 0:
... |
158453 | from django.test import TestCase
from mock import patch
from digest.management.commands.import_importpython import ImportPythonParser
from digest.utils import MockResponse, read_fixture
class ImportPythonWeeklyTest(TestCase):
def setUp(self):
self.url = "http://importpython.com/newsletter/no/60/"
... |
158463 | import os
import random
from collections import defaultdict
import boto3
import pytest
from xoto3.dynamodb.update import versioned_diffed_update_item
from xoto3.dynamodb.utils.expressions import add_variables_to_expression
from xoto3.dynamodb.utils.table import extract_key_from_item, table_primary_keys
_TEST_TABLE_N... |
158464 | import unittest
from kbmodpy import kbmod as kb
class test_import(unittest.TestCase):
def setUp(self):
#kb.
pass
def test_something(self):
#self.assertGreater( a , b )
#self.assertEqual( a , b )
pass
|
158470 | import argparse
import logging
import os
import sys
import requests
from colorama import Fore, Style, init
from colorama.ansi import clear_screen
import grayskull
from grayskull.base.factory import GrayskullFactory
from grayskull.cli import CLIConfig
from grayskull.cli.parser import parse_pkg_name_version
from graysk... |
158543 | from .builder import build_feature_extractor # noqa 401
from .decoders import build_brick, build_bricks, build_decoder # noqa 401
from .encoders import build_backbone, build_encoder, build_enhance_module # noqa 401
|
158548 | import logging
from aiotasks import run_with_exceptions_and_logs, SharedConfig
def test_run_with_exceptions_and_logs_oks(monkeypatch):
logger = logging.getLogger("aiotasks")
class CustomLogger(logging.StreamHandler):
def __init__(self):
super(CustomLogger, self).__init__()
s... |
158557 | from __future__ import absolute_import
from sentry.models import AuditLogEntry
from sentry.web.frontend.base import OrganizationView
class OrganizationAuditLogView(OrganizationView):
required_scope = 'org:write'
def get(self, request, organization):
queryset = AuditLogEntry.objects.filter(
... |
158575 | class Atom(object):
""" """
def __init__(self, index, name=None, residue_index=-1, residue_name=None):
"""Create an Atom object
Args:
index (int): index of atom in the molecule
name (str): name of the atom (eg., N, CH)
residue_index (int): index of residue i... |
158580 | import json
class AstToken:
def __init__(self, lex_token):
self.name = lex_token.type
if lex_token.value != self.name:
self.value = lex_token.value
def __str__(self):
return json.dumps(self, cls=AstTokenEncoder)
class AstTokenList:
def __init__(self, tokens):
s... |
158581 | import unittest
import pandas as pd
from reamber.base import Hold
class TestHold(unittest.TestCase):
""" The purpose of this test is to test the architecture of Base. """
def setUp(self) -> None:
self.hold = Hold(offset=1000, column=1, length=1000)
# @profile
def test_type(self):
s... |
158584 | from django.urls import include, path
#
# On Reversing URLs
# =================
#
# Recommended Usage:
# Always use rest_framework.reverse.reverse, do not directly use django.urls.reverse.
# If a request object r is available, use reverse(name, request=r). With the name as defined
# in desecapi.urls.v1 or desecapi.ur... |
158590 | def method1(ll1, ll2, n1, n2):
hs = set()
for i in range(0, n1):
hs.add(ll1[i])
print("Intersection:")
for i in range(0, n2):
if ll2[i] in hs:
print(ll2[i], end=" ")
if __name__ == "__main__":
"""
from timeit import timeit
ll1 = [7, 1, 5, 2, 3, 6]
ll2 = [3, ... |
158668 | import ssl
import httpcore
import httpx
import pytest # noqa
from yarl import URL # noqa
from httpx_socks import (
ProxyType,
AsyncProxyTransport,
ProxyError,
ProxyConnectionError,
ProxyTimeoutError,
)
from tests.config import (
TEST_HOST_PEM_FILE, TEST_URL_IPV4, TEST_URL_IPV4_HTTPS, SOCKS5... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.