id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1652499 | import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim.optimizer
from torch.optim import lr_scheduler
from torch.utils.tensorboard import SummaryWriter
import augmentations
import torch_resizer
import utils
class Network: # The base network
def __init__(self, config, devic... |
1652523 | import os
from airflow.configuration import conf
from ewah.dag_factories import dags_from_yml_file
for dag in dags_from_yml_file(conf.get("core", "dags_folder") + os.sep + "dags.yml"):
# Must add the individual DAGs to the global namespace,
# otherwise airflow does not find the DAGs!
globals()[dag._dag_id... |
1652590 | from ..base import BaseTopazTest
class TestTrueObject(BaseTopazTest):
def test_name(self, space):
space.execute("TrueClass")
def test_to_s(self, space):
w_res = space.execute("return true.to_s")
assert space.str_w(w_res) == "true"
def test_inspect(self, space):
w_res = sp... |
1652599 | from haystack import indexes
from mozdns.mx.models import MX
from mozdns.mozdns_index import MozdnsIndex
class MXIndex(MozdnsIndex, indexes.Indexable):
server = indexes.CharField(model_attr='server')
def get_model(self):
return MX
|
1652650 | from lumen.sources import Source
def test_resolve_module_type():
assert Source._get_type('lumen.sources.base.Source') is Source
|
1652664 | import asyncio
import json
import logging
import aiohttp
from demonhunter.core.loggers.logfile import FileLogger
class BaseHandler:
# https://svn.nmap.org/nmap/nmap-service-probes
def save_data(self, data):
if self.honeypot.sqlite:
self.save_in_sqlite(data)
if self.honeypot.logfi... |
1652721 | import argparse
import logging
from pathlib import Path
from subs2cia.sources import get_and_partition_streams, AVSFile, Stream
from pprint import pprint
def get_args():
parser = argparse.ArgumentParser(description=f'frame capture manual testing')
parser.add_argument('-V', '--video', metavar='<input file>', ... |
1652731 | from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
from __future__ import print_function
from collections import defaultdict as dd
import numpy as np
import sklearn
from torch.utils.data import Dataset
from core.utils import feature_utils
from core.utils imp... |
1652736 | import sys
from pathlib import Path
sys.path.append("..")
from energym import make
from energym.envs.utils.kpi import KPI
from energym.envs.utils.weather import EPW, MOS
def test_can_run_gym_interface_on_apartments_thermal():
env = make("ApartmentsThermal-v0")
episodes = 2
n_steps_per_episode = 100
... |
1652760 | import pytest
from fragile.core.utils import get_plangym_env
class TestUtils:
def test_get_plangym_env(self):
class dummy_shape:
shape = (2, 2)
class DummyEnv:
def __init__(self):
class dummy_n:
n = 1
self.action_space ... |
1652824 | from periphery import I2C
def main():
print("i2c connection test")
# Open i2c-2 controller
i2c = I2C("/dev/i2c-2")
print("Write to I2C")
readbuffer = bytearray(19)
# Create a list of messages to send to slave
# First message is example of writing string
# Second message reads byt... |
1652833 | import torch.nn as nn
import torch
import math
class GCN(nn.Module):
def __init__(self, hid_size=256):
super(GCN, self).__init__()
self.hid_size = hid_size
self.W = nn.Parameter(torch.FloatTensor(self.hid_size, self.hid_size//2).cuda())
self.b = nn.Parameter(torch.... |
1652841 | from Engine.GUI import *
EnabledHealerFriend = False
class HealerFriend:
def __init__(self, root):
self.HealerFriend = GUI('HealerFriend', 'Module: Healer Friend')
self.HealerFriend.DefaultWindow('DefaultWindow')
def SetHealerFriend():
global EnabledHealerFriend
i... |
1652869 | from __future__ import division
import numpy as np
from numpy import pi, exp
from ..Contour import Contour
from ..Paths import ComplexLine, ComplexArc
class AnnulusSector(Contour):
"""
A sector of an annulus in the complex plane.
Parameters
----------
center : complex
The center of the annulus sector.
radii ... |
1652895 | import numpy as np
from nilabels.tools.detections.get_segmentation import intensity_segmentation, otsu_threshold, MoG_array
# ----- Test get segmentation ----
def test_intensity_segmentation_1():
im_array = np.random.randint(0, 5, [10, 10], np.uint8)
output_segm = intensity_segmentation(im_array)
# if... |
1652935 | import argparse
import csv
import cPickle as pickle
import collections
from HTMLParser import HTMLParser
import operator
import re
import json
import sklearn.preprocessing
# Taken from
# https://github.com/tensorflow/tensorflow/blob/16254e75e2fe4bb0f879b45fbad0c4b62c028011/tensorflow/models/rnn/translate/data_utils.p... |
1652951 | from datetime import datetime
from eth_utils import to_checksum_address
import datetime as dt
from src.queries import getAllAllocations, getActiveAllocations, getClosedAllocations, getAllocationDataById, \
getCurrentBlock
from src.helpers import initialize_rpc, initializeRewardManagerContract, ANYBLOCK_ANALYTICS_ID... |
1652961 | import os
from optparse import make_option
from uliweb.core.commands import Command, get_answer
class DirCommand(Command):
name = 'dir'
args = 'directory [,...]'
help = 'Clear all files or file patterns in dirs.'
option_list = (
make_option('-e', '--extension', dest='extensions', action='append... |
1652986 | import requests
import rdflib
from whyis import nanopub
import datetime
import pytz
import dateutil.parser
from dateutil.tz import tzlocal
from werkzeug.datastructures import FileStorage
from werkzeug.http import http_date
from setlr import FileLikeFromIter
import re
import os
from requests_testadapter import Resp
impo... |
1653010 | import tensorflow as tf
def training(loss, learning_rate, global_step):
#This motif is needed to hook up the batch_norm updates to the training
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
optimizer = tf.train.AdamOptimizer(learning_rate=learni... |
1653036 | import glob
import os
import random
import numpy as np
from scipy.misc import imread
from refinement_net.core.Measures import compute_measures_for_binary_segmentation_single_image, IOU
from refinement_net.datasets import DataKeys
from refinement_net.datasets.DAVIS import DAVIS
from refinement_net.datasets.Dataset imp... |
1653050 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from functools import partial
import numpy as np
import cv2
from lib.show_images import debugShowBoxes
class BaseContoursHeatmap(object):
cv_thresh = cv2.THRESH_BINARY
cv_contour_method = cv2.CHAIN... |
1653081 | from _groupsig import lib, ffi
from . import constants
import base64
def gml_init(code):
"""
Initializes a Group Membership List (GML) for schemes of the given type.
Parameters:
code: The code of the scheme.
Returns:
A native object representing the GML. Throws an Exception on erro... |
1653096 | import torch
from loguru import logger
def pad_batch(h_node, batch, max_input_len, get_mask=False):
num_batch = batch[-1] + 1
num_nodes = []
masks = []
for i in range(num_batch):
mask = batch.eq(i)
masks.append(mask)
num_node = mask.sum()
num_nodes.append(num_node)
... |
1653126 | import networkx as nx
import numpy as np
class ClusteringCoeff:
"""
Concatenates to each node attribute the clustering coefficient of the
corresponding node.
"""
def __call__(self, graph):
if "a" not in graph:
raise ValueError("The graph must have an adjacency matrix")
... |
1653143 | import click
from commands.load_metadata.all import all
from commands.load_metadata.continents import continents
from commands.load_metadata.countries import countries
from commands.load_metadata.economic_blocs import economic_blocs
from commands.load_metadata.establishments import establishments
from commands.load_me... |
1653175 | from itertools import combinations_with_replacement
import numpy as np
from scipy.stats import chisquare
from pandas_genomics.arrays.utils import required_ploidy
from pandas_genomics.scalars import MISSING_IDX
class InfoMixin:
"""
Genotype Mixin containing functions for calculating various information
"... |
1653215 | import doctest
from insights.parsers import ls_ocp_cni_openshift_sdn
from insights.parsers.ls_ocp_cni_openshift_sdn import LsOcpCniOpenshiftSdn
from insights.tests import context_wrap
LS_CNI_OPENSHIFT_SDN = """
total 52
-rw-r--r--. 1 root root 64 Aug 5 23:26 10.130.0.102
-rw-r--r--. 1 root root 64 Aug 5 23:26 10.13... |
1653274 | from __future__ import division, print_function, absolute_import
import time
import os.path
import datetime
from sklearn.linear_model import LogisticRegression, LinearRegression, SGDClassifier, SGDRegressor
from rep.metaml._cache import CacheHelper
from rep.metaml.cache import CacheClassifier, CacheRegressor, cache_hel... |
1653292 | import pylab
#set line width
pylab.rcParams['lines.linewidth'] = 6
#set general font size
pylab.rcParams['font.size'] = 12
#set font size for labels on axes
pylab.rcParams['axes.labelsize'] = 18
#set size of numbers on x-axis
pylab.rcParams['xtick.major.size'] = 5
#set size of numbers on y-axis
pylab.rcParams['ytick.... |
1653439 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.painters import painters
def test_painters():
"""Test module painters.py by downloading
painters.csv and testing shape of
extracted data h... |
1653457 | import numpy as np
# ParaMol imports
from ParaMol.System.system import *
from ParaMol.MM_engines.openmm import *
# ParaMol Tasks imports
from ParaMol.Tasks.parametrization import *
from ParaMol.Tasks.ab_initio_properties import *
from ParaMol.Utils.settings import *
# ------------------------------------------------... |
1653471 | import threading
import time
from kivy.app import App
from kivy.lang import Builder
import threading
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
Builder.load_string('''
<Thread>:
Button:
text: "use thread"
on_release: root.First_thre... |
1653482 | t = int(input())
while t:
S = list(map(str, input().split(' ')))
for i in S:
if i == 'not':
print('Real Fancy')
break
else:
print('regularly fancy')
t = t-1 |
1653483 | import pexpect
p = pexpect.spawn(["login"])
p.expect("login:")
p.sendline("wrong")
p.expect("Password:")
p.sendline("wrong")
p.expect("Login incorrect")
|
1653513 | def f():
some_global: int
print(some_global)
# EXPECTED:
[
...,
CODE_START('f'),
~LOAD_CONST('int'),
]
|
1653518 | import os
# Set the default data directory to be the one this file's directory + data/
data_dir = os.path.dirname(os.path.realpath(__file__))
data_dir = os.path.realpath(os.path.join(data_dir, 'data'))
# Spacy model name
spacy_model_name = 'en_core_web_sm'
|
1653535 | import logging
import inspect
import json
import os
import urlparse
import pylons.config as config
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
import ckanext.hdx_theme.helpers.auth as auth
from ckanext.hdx_theme.helpers.redirection_middleware import RedirectionMiddleware
from ckanext.hdx_th... |
1653573 | import os
from contextlib import contextmanager
import requests_mock
mydir = os.path.dirname(__file__)
URL_TO_RESPONSE_FILE_MAP = {
('https://kartta.hel.fi/ws/geoserver/avoindata/wfs'
'?service=WFS&version=2.0.0&request=GetCapabilities'): (
'wfs_capabilities_response.xml'),
('https://kartta.he... |
1653579 | import os
import time
import h5py
from collections import OrderedDict
import numpy as np
from env.jaco.two_jaco import TwoJacoEnv
from env.transform_utils import quat_dist
class TwoJacoPlaceEnv(TwoJacoEnv):
def __init__(self, **kwargs):
self.name = 'two-jaco-place'
super().__init__('two_jaco_pic... |
1653597 | from vk_raid_defender.cli import cli
if __name__ == '__main__':
cli.main()
else:
raise ImportError('этот модуль должен использоваться только для запуска программы')
|
1653605 | import os
import sys
import shutil
import unittest
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
import chazutsu.datasets
from tests.dataset_base_test import DatasetTestCase
class TestSquad(DatasetTestCase):
def test_download_v1_1(self):
r_train = chazutsu.datasets.SQuAD(
k... |
1653652 | import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import numpy as np
n_iter=0
def group_weight(module):
group_decay = []
group_no_decay = []
for m in module.modules():
if isinstance(m, nn.Linear):
group_decay.append(m.weight)
... |
1653693 | from typing import Dict
from typing import List
from botocore.paginate import Paginator
class DescribeDirectoryConfigs(Paginator):
def paginate(self, DirectoryNames: List = None, PaginationConfig: Dict = None) -> Dict:
"""
Creates an iterator that will paginate through responses from :py:meth:`App... |
1653696 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY=os.environ.get('SECRET_KEY') or '<KEY>';
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = True
@staticmethod
def init_app(app):
pass
class DevelopmntConfig(Config):
Debug = 0
SQLALCHEMY_DATABASE_UR... |
1653724 | import torch
import torch.nn.functional as F
from models.baseModule import BaseNet
from models.EventUnet import EventUnet
from models.FrameUnet import FrameUnet
from models.FuseNet import FuseNet
import math
class Generator(BaseNet):
def __init__(self, cfg):
super(Generator, self).__init__(cfg.netInitType... |
1653736 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
DEPENDENCIES = [] # 'scipy', 'numpy', 'vtk']
TEST_DEPENDENCIES = [] # 'pytest']
VERSION = "1.0"
URL = "https://github.com/KVSlab/morphMan.git"
setuptools.setup(
name="morphman",
version=VERSION,
license="GPL",
au... |
1653744 | from .zenipy import (
message,
error,
warning,
question,
entry,
password,
zlist,
file_selection,
calendar,
color_selection,
scale
)
|
1653755 | import sys
from markdown import markdown as _m
PREAMBLE = r"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Mate">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Verdana">
<link rel="stylesheet" href="https://maxcdn.boot... |
1653770 | expected_output = {
'vrfs':{
'VRF':{
'vrf_id':5,
'vrf_state':'Up',
'reason':'--'
},
'VRF1':{
'vrf_id':3,
'vrf_state':'Up',
'reason':'--'
},
'VRF2':{
'vrf_id':4,
'vrf_state':'Up',
'reason':'--'
},
... |
1653781 | import argparse
import numpy as np
from paz.backend.image import load_image, show_image, resize_image
from paz.backend.camera import Camera
from paz.pipelines import DetectMiniXceptionFER
from paz.pipelines import DetectFaceKeypointNet2D32
from paz.pipelines import HeadPoseKeypointNet2D32
from paz.pipelines import S... |
1653784 | from ._pymimkl import *
# importing wrapped models
from .average_mkl import AverageMKL
from .easy_mkl import EasyMKL
from .umkl_knn import UMKLKNN
# cleanup unused objects
del(EasyMKL_)
del(UMKLKNN_)
del(AverageMKL_)
|
1653812 | import os
import json
import random
src_path = 'data/original/twisty'
meta_path = os.path.join(src_path, 'TwiSty-NL.json')
data_dir = os.path.join(src_path, 'users_id')
out_dir = 'data/prepared/twisty'
num_tweets = 200
def tweet_text(tweet, replace_ents=True):
text = tweet['text']
if replace_ents:
... |
1653820 | import logging
import os
import subprocess
from git.exc import NoSuchPathError
from assigner.roster_util import get_filtered_roster
from assigner.backends import RepoError
from assigner.backends.decorators import requires_config_and_backend
from assigner import progress
help = "Add and commit changes to student repo... |
1653830 | from .neobaseextractor import NeoBaseRecordingExtractor
try:
import neo
HAVE_NEO = True
except ImportError:
HAVE_NEO = False
class MCSRawRecordingExtractor(NeoBaseRecordingExtractor):
extractor_name='mcsrawRecoding'
mode='file'
NeoRawIOClass='RawMCSRawIO'
|
1653834 | import numpy as np
from typing import Callable
import lcs.agents.xcs as xcs
class Configuration(xcs.Configuration):
def __init__(self,
number_of_actions: int, # theta_mna it is actually smart to make it equal to number of actions
lmc: int = 100,
lem: float = 1... |
1653842 | import bin_plots
import sys
import xarray as xr
import matplotlib.pyplot as plt
import numpy as np
path, output = sys.argv[1:]
ds = xr.open_dataset(path)
fig, axs = plt.subplots(1, 3, figsize=(7, 2), constrained_layout=True)
bin_plots.plot_row(ds, axs=axs)
bin_plots.set_row_titles(axs, ["a) Count\n", "b) Predicted\nP... |
1653868 | from click.testing import CliRunner
import responses
from ugoira.cli import ugoira
from ugoira.lib import get_metadata_url
def test_download(
ugoira_id,
meta_body,
small_zip_url,
big_zip_url,
small_image_zip,
big_image_zip,
):
"""Test for command download"""
@responses.activate
... |
1654028 | import json
import numpy as np
import tensorflow as tf
from .xlnet import build_xlnet
__all__ = [
'build_model_from_config',
'load_model_weights_from_checkpoint',
'load_trained_model_from_checkpoint',
]
def checkpoint_loader(checkpoint_file):
def _loader(name):
return tf.train.load_variable(... |
1654040 | class error(Exception):
pass
def as_fd(f):
if not isinstance(f, (int, long)):
try:
fileno = f.fileno
except AttributeError:
raise TypeError("argument must be an int, or have a fileno() method.")
f = f.fileno()
if not isinstance(f, (int, long)):
... |
1654051 | import time
class FixedBucket:
'''
Fixed size FIFO container.
'''
def __init__(self, size):
self._data = [None] * size
self._cur = 0
self._size = size
self._flag_full = False
def put(self, v):
self._data[self._cur] = v
self._cur += 1
if sel... |
1654060 | import torch
import numpy as np
import matplotlib.pyplot as plt
def plot_curve(train_matrix, test_matrix, t_grid, train_grid):
plt.figure(figsize=(5, 5))
truth_grid = t_grid[:,t_grid[0,:].argsort()]
t_truth_grid = train_grid[:,train_grid[0,:].argsort()]
x = truth_grid[0, :]
y = truth_grid[1, :]
... |
1654068 | import subprocess
import pysurvive
import sys
import os
from gooey import Gooey, GooeyParser
@Gooey(tabbed_groups=True,
image_dir=os.path.dirname(os.path.realpath(__file__)) + "/images",
use_cmd_args=True,
program_name="pysurvive",
richtext_controls=True,
clear_before_run=True)
def ... |
1654071 | from sklearn.datasets import load_digits
from MulticoreTSNE import MulticoreTSNE as TSNE
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot as plt
import scipy
import torch
import numpy as np
#digits = load_digits()
query_path = '.'
result_n = scipy.io.loadmat(query_path+'/query_result_normal.mat')
... |
1654074 | from datetime import datetime
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String
from sqlalchemy.schema import Index
from freight.config import db
from freight.db.types.json import JSONEncodedDict
class TaskStatus(object):
unknown = 0
pending = 1
in_progress = 2
finished = 3
fai... |
1654080 | import os
from setuptools import setup
install_requires = [
'django>1.11',
'six'
]
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
CHANGELOG = open(os.path.join(os.path.dirname(__file__), 'CHANGELOG.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.... |
1654110 | from functools import singledispatchmethod
from typing import Union
from UE4Parse.BinaryReader import BinaryStream
# TODO Implement EGuidFormats
class FGuid:
position: int
A: int
B: int
C: int
D: int
@singledispatchmethod
def __init__(self, reader: BinaryStream):
self.A = reader.... |
1654135 | from django.contrib.auth import get_user_model
from django.db import models
from baserow.contrib.database.table.models import Table
from baserow.core.mixins import CreatedAndUpdatedOnMixin
User = get_user_model()
class RowComment(CreatedAndUpdatedOnMixin, models.Model):
"""
A user made comment on a specific... |
1654144 | from qttable import QTable
from qt import SIGNAL,PYSIGNAL
class TableEdit(QTable):
def __init__(self, parent=None):
QTable.__init__(self, parent)
self.data = None
def setData(self, data):
self.removeColumns(range(self.numCols()))
self.removeRows(range(self.numRows()))
... |
1654205 | from .docusaurus_writer import DocusaurusWriter, DocusaurusTranslator
from docutils.io import StringOutput
from io import open
from munch import munchify
from os import path
from sphinx.builders import Builder
from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.osutil import ensuredir,... |
1654209 | from lyrebird import application
from .. import checker
class OnResponseUpstreamHandler:
def __call__(self, rules=None, *args, **kw):
def func(origin_func):
func_type = checker.TYPE_ON_RESPONSE_UPSTREAM
if not checker.scripts_tmp_storage.get(func_type):
checker.scr... |
1654221 | import pytest
import helpers
import pqclean
@pytest.mark.parametrize(
'implementation',
pqclean.Scheme.all_implementations(),
ids=str,
)
@helpers.filtered_test
def test_preprocessor(implementation: pqclean.Implementation):
cfiles = implementation.cfiles()
hfiles = implementation.hfiles()
erro... |
1654266 | from django.contrib import admin
from . import models
admin.site.register(models.Device)
admin.site.register(models.Port)
|
1654296 | import bpy
from bpy.props import *
from ...nodes.BASE.node_base import RenderNodeBase
from mathutils import Color, Vector
def update_node(self, context):
if self.operate_type == 'COMBINE':
self.remove_output('x')
self.remove_output('y')
self.remove_output('z')
self.remove_input('in... |
1654299 | import pytest
import json
from easier68k.core.models.list_file import ListFile
from easier68k.assembler.assembler import parse
import os.path
def test_basic_test_input():
script_dir = os.path.dirname(__file__) # The directory the current file is in
# Test
with open(os.path.join(script_dir, 'basic_test_i... |
1654320 | def name_func(func, _, params):
return f'{func.__name__}_{"_".join(str(arg) for arg in params.args)}'
def get_enc_params(dtype):
if dtype == "float32":
return "PCM_F", 32
if dtype == "int32":
return "PCM_S", 32
if dtype == "int16":
return "PCM_S", 16
if dtype == "uint8":
... |
1654354 | import operator
def factorial(n):
"""Calculate n factorial"""
return reduce(operator.mul, range(2, n+1), 1)
def intersection(*sets):
"""Get the intersection of all input sets"""
return reduce(set.intersection, sets)
def union(*sets):
"""Get the union of all input sets"""
return reduce(set.uni... |
1654367 | from compas.geometry import distance_point_point
from compas_cem.optimization.constraints import FloatConstraint
__all__ = ["DeviationEdgeLengthConstraint"]
class DeviationEdgeLengthConstraint(FloatConstraint):
"""
Make a deviation edge reach a target length.
"""
def __init__(self, edge=None, lengt... |
1654388 | import torch
from torch.nn import ReLU, Tanh, CrossEntropyLoss, Sigmoid, SELU, MSELoss, L1Loss, SmoothL1Loss, NLLLoss, BCELoss
from torch.optim import Adam, SGD, RMSprop, Adagrad
from torch.utils.data.dataset import Dataset
activations = {
"relu": ReLU(),
"tanh": Tanh(),
"sigmoid": Sigmoid(),
"selu":... |
1654391 | from spotdl.download.tracking_file_handler import DownloadTracker
from spotdl.download.progress_ui_handler import DisplayManager
from spotdl.download.ffmpeg import convert, has_correct_version
from spotdl.download.embed_metadata import set_id3_data
from spotdl.download.downloader import DownloadManager
|
1654396 | from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def render_plugin_preview(context, plugin):
request = context['request']
try:
content_renderer = request.toolbar.content_renderer
except AttributeError:
from cms.plugin_rendering import Co... |
1654434 | from examples.datasets.data.train_example_data import train_example_data
from neuralogic.core import Relation, Template, Var, Term, Dataset
dataset = Dataset()
template = Template()
# Naive trains - one big example
# fmt: off
shapes = [Term.ellipse, Term.rectangle, Term.bucket, Term.hexagon, Term.u_shaped]
roofs ... |
1654460 | import re
from threading import Thread
from flask import current_app
from flask_mail import Message
from .extensions import mail
base_prefix = '/api'
default_page_size = 10
default_chat_page_size = 25
response_delay = 1.5
def send_email_async(app, message):
with app.app_context():
mail.send(message)
... |
1654464 | from mermaid_demos.rdmm_synth_data_generation.create_poly import Poly
import numpy as np
class Rectangle(Poly):
def __init__(self,setting,scale=1.):
name, img_sz, center_pos, height, width, rotation = setting['name'],setting['img_sz'], setting['center_pos'], setting['height'], setting['width'], setting['rot... |
1654495 | from datetime import timedelta
from sqlalchemy.sql import func
from flask import current_app, request
from typing import List
from zeus.api.utils import stats
from zeus.config import db
from zeus.models import Build, Repository, Revision
from zeus.utils import timezone
from zeus.vcs import vcs_client
from .base_repos... |
1654513 | from bitmovin_api_sdk.encoding.encodings.keyframes.keyframes_api import KeyframesApi
from bitmovin_api_sdk.encoding.encodings.keyframes.keyframe_list_query_params import KeyframeListQueryParams
|
1654590 | from direct.directnotify import DirectNotifyGlobal
from pirates.distributed.DistributedInteractiveAI import DistributedInteractiveAI
from pirates.movement.DistributedMovingObjectAI import DistributedMovingObjectAI
from pirates.quest.DistributedQuestGiverAI import DistributedQuestGiverAI
class DistributedReputationAvat... |
1654604 | import torch.utils.data
from data.base_data_loader import BaseDataLoader
def CreateDataLoader(args):
data_loader = CustomDatasetDataLoader()
data_loader.initialize(args)
return data_loader
def CreateDataset(args):
dataset = None
from data.single_dataset import TestDataset
dataset = TestDatas... |
1654632 | import torch
import torch.nn.functional as F
from ..models.mingpt import GPT, CGPT, NoiseInjection
from tools.utils import to_cuda
from models import load_network, save_network, print_network
from tqdm import tqdm
from ..modules.vmf import nll_vMF
class Transformer(torch.nn.Module):
def __init__(self, o... |
1654638 | from Orange.classification import (
SVMLearner as SVCLearner,
LinearSVMLearner as LinearSVCLearner,
NuSVMLearner as NuSVCLearner,
)
from Orange.modelling import SklFitter
from Orange.regression import SVRLearner, LinearSVRLearner, NuSVRLearner
__all__ = ["SVMLearner", "LinearSVMLearner", "NuSVMLearner"]
... |
1654690 | from smtplib import SMTPException
from django.core.management.base import BaseCommand
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from agony import settings
from agony.models import QandA
def process():
responses_to_send = Qa... |
1654694 | import os
import csv
__all__ = ["evaluate", "evaluate_dataset"]
def evaluate(
args,
model,
train_loader,
val_loader,
test_loader,
device,
metrics,
custom_header=None,
):
header = []
results = []
loaders = dict(train=train_loader, validation=val_loader, test=test_loader)... |
1654743 | from torch import optim
import os, sys, argparse
from experiments import APHYNITYExperiment
from networks import *
from forecasters import *
from utils import init_weights
from datasets import init_dataloaders
__doc__ = '''Training APHYNITY.'''
def cmdline_args():
# Make parser object
p = argparse.Argume... |
1654745 | from django.http import HttpResponse
from django.conf import settings
import base64
class BasicAuthMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for ... |
1654757 | from abc import ABCMeta , abstractmethod
from math import cos , sin
import taichi as ti
from helper_functions import clamp , distance , distance_sqr
from basic_types import Vector , Float , Int
"""
TODO: Not well complete .
1. bounding_box query
2. ray intersects check
"""
@ti.data_oriented
class Ray:
... |
1654770 | from a10sdk.common.A10BaseClass import A10BaseClass
class SessionList(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param protocol: {"type": "string", "format": "string"}
:param forward_source: {"type": "string", "format": "string"}
:param age: {"type": "numbe... |
1654801 | COLOR_PACK_LIGHT_GREEN_TO_DARK_PURPLE = 1
# lower (light green=59) to max (dark purple=28)
DARK_PURPLE = 28
LIGHT_GREEN = 59
COLOR_PACK_CITRON_TO_VIOLET = 2
CITRON = 0
VIOLET = 28
class ColorPalette(object):
@staticmethod
def get_color_from_percent_between_0_1(pct, color_pack=COLOR_PACK_LIGHT_GREEN_TO_DARK_P... |
1654842 | import logging
import os
import zipfile
from celery import shared_task
from django.conf import settings
from django.db.utils import OperationalError, ProgrammingError, InternalError
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from daiquiri.core.tasks import Task
cl... |
1654846 | import sys
from pathlib import Path
file = Path(__file__).resolve()
parent, root = file.parent, file.parents[1]
sys.path.append(str(root))
try:
sys.path.remove(str(parent))
except ValueError: # Already removed
pass
import streamlit as st
from util.release_helper import create_static_notes
VERSION = '.'.join(... |
1654889 | from __future__ import print_function
from future.utils import native_str
from builtins import str
from builtins import range
#import mermaid.set_pyreg_paths
import matplotlib as matplt
from mermaid.config_parser import MATPLOTLIB_AGG
if MATPLOTLIB_AGG:
matplt.use('Agg')
import matplotlib.pyplot as plt
import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.