id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
99469 | from sqlalchemy import Boolean, Column, String
from sqlalchemy.dialects.mysql import INTEGER as Integer, TINYINT as TinyInteger
from ichnaea.models.base import _Model
class ApiKey(_Model):
"""
ApiKey model.
The allow_fallback and fallback columns determine if and what
fallback location provider shou... |
99501 | import codecs
from distutils.core import setup
def read(fname):
'''
Read a file from the directory where setup.py resides
'''
with codecs.open(fname, encoding='utf-8') as rfh:
return rfh.read()
try:
description = read('README.txt')
except:
description = read('README.md')
setup(
... |
99589 | def test():
a = 10
fun1 = lambda: a
fun1()
print(a)
a += 1
fun1()
print(a)
return fun1
fun = test()
print(f"Fun: {fun()}")
|
99591 | import jinja2
from sanic import response
from .util import get_banner
j2 = jinja2.Environment(
loader=jinja2.PackageLoader(__name__, "templates"),
autoescape=jinja2.select_autoescape(["html", "xml"]),
)
j2.globals.update({"len": len, "get_banner": get_banner})
def renderpost_filter(t, show_thread_link=Fal... |
99659 | description = 'system setup'
group = 'lowlevel'
sysconfig = dict(
cache='localhost',
instrument='ESTIA',
experiment='Exp',
datasinks=['conssink', 'filesink', 'daemonsink'],
)
modules = ['nicos.commands.standard']
includes = ['temp']
devices = dict(
ESTIA=device('nicos.devices.instrument.Instrum... |
99673 | import numpy as np
import torch
import torch.nn as nn
import torchtestcase
import unittest
from survae.transforms.bijections.coupling import *
from survae.nn.layers import ElementwiseParams, ElementwiseParams2d
from survae.tests.transforms.bijections import BijectionTest
class AdditiveCouplingBijectionTest(BijectionT... |
99681 | import asyncio
import logging
import socket
import websockets
from gabriel_protocol import gabriel_pb2
from collections import namedtuple
URI_FORMAT = 'ws://{host}:{port}'
logger = logging.getLogger(__name__)
websockets_logger = logging.getLogger(websockets.__name__)
# The entire payload will be printed if this is... |
99697 | from parler.models import TranslatableModel
from solo.models import SingletonModel
class SiteConfig(SingletonModel, TranslatableModel):
pass
def __str__(self) -> str:
return "Site Config"
|
99711 | import json
import logging
import time
from selenium.common.exceptions import NoSuchElementException
from seleniumwire import webdriver
import config
def get_valid_cookies(cookies_amount):
options = webdriver.FirefoxOptions()
options.headless = True
driver = webdriver.Firefox(options=options, e... |
99731 | def extractThehlifestyleCom(item):
'''
Parser for 'thehlifestyle.com'
'''
tstr = str(item['tags']).lower()
if 'review' in tstr:
return None
if 'actors' in tstr:
return None
if 'game' in tstr:
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "... |
99732 | import os
import json
import pytest
from test_api.run import create_app
@pytest.fixture(scope="session")
def app():
abs_file_path = os.path.abspath(os.path.dirname(__file__))
openapi_path = os.path.join(abs_file_path, "../", "openapi")
os.environ["SPEC_PATH"] = openapi_path
app = create_app()
r... |
99832 | from typing import Hashable
import pandas_flavor as pf
import pandas as pd
from janitor.utils import deprecated_alias
@pf.register_dataframe_method
@deprecated_alias(column="column_name")
def to_datetime(
df: pd.DataFrame, column_name: Hashable, **kwargs
) -> pd.DataFrame:
"""Convert column to a datetime typ... |
99848 | import tensorflow as tf
import numpy as np
from tqdm import tqdm
from tf_metric_learning.utils.index import AnnoyDataIndex
class AnnoyEvaluatorCallback(AnnoyDataIndex):
"""
Callback, extracts embeddings, add them to AnnoyIndex and evaluate them as recall.
"""
def __init__(
self,
mod... |
99864 | from HABApp.core.events import ValueChangeEventFilter, ValueUpdateEventFilter
from . import MqttValueChangeEvent, MqttValueUpdateEvent
class MqttValueUpdateEventFilter(ValueUpdateEventFilter):
_EVENT_TYPE = MqttValueUpdateEvent
class MqttValueChangeEventFilter(ValueChangeEventFilter):
_EVENT_TYPE = MqttValu... |
99891 | version https://git-lfs.github.com/spec/v1
oid sha256:995a5a4cc97102e151664561338b41fb57c93314e63da5958bc2a641355d7cc3
size 11926
|
99923 | import argparse
def get_arg_parser(parser=None):
"""Parse the command line arguments for merge using argparse
Args:
parser (argparse.ArgumentParser or CompliantArgumentParser):
an argument parser instance
Returns:
ArgumentParser: the argument parser instance
Notes:
i... |
99976 | from kivymd.uix.screen import MDScreen
class HomeScreen(MDScreen):
"""
Example Screen.
"""
|
99978 | import django_filters
from django.db.models import Q
from devices.enums import PasswordAlgorithm
from devices.models import Configuration, Platform
from utils.filters import (
BaseFilterSet,
CreatedUpdatedFilterSet,
NameSlugSearchFilterSet,
TagFilter,
)
class ConfigurationFilterSet(BaseFilterSet, Cre... |
99990 | from RestrictedPython import compile_restricted_eval
from RestrictedPython import compile_restricted_exec
import RestrictedPython.Guards
def _compile(compile_func, source):
"""Compile some source with a compile func."""
result = compile_func(source)
assert result.errors == (), result.errors
assert re... |
100017 | import queue
import struct
class CanIDService:
"""
Can ID service interface class.
This interface class has to be used to implement any can id based service that shall have be able to be
registered with the communication module :class:`test_framework.communication.communication`
"""
... |
100024 | from ..factory import Method
class getGroupsInCommon(Method):
user_id = None # type: "int32"
offset_chat_id = None # type: "int53"
limit = None # type: "int32"
|
100038 | import pytest
from usbq.plugins.hexdump import Hexdump
from usbq.usbmitm_proto import USBMessageDevice
from usbq.usbmitm_proto import USBMessageHost
@pytest.mark.parametrize('cls', [USBMessageDevice, USBMessageHost])
def test_hexdump(capsys, cls):
pkt = cls()
assert hasattr(pkt, 'content')
Hexdump().usbq... |
100053 | import platform
from pathlib import Path
import numpy as np
import torch
from spconv.pytorch import ops
from spconv.pytorch.conv import (SparseConv2d, SparseConv3d, SparseConvTranspose2d,
SparseConvTranspose3d, SparseInverseConv2d,
SparseInverseConv3d, SubMConv2d, Sub... |
100056 | from .async_find_opportunities import *
from .async_build_markets import *
from .bellman_multi_graph import bellman_ford_multi, NegativeWeightFinderMulti
from .bellmannx import bellman_ford, calculate_profit_ratio_for_path, NegativeWeightFinder, NegativeWeightDepthFinder, \
find_opportunities_on_exchange, get_start... |
100085 | from slack_sdk.web.async_client import AsyncWebClient
class AsyncUpdate:
"""`update()` utility to tell Slack the processing results of a `save` listener.
async def save(ack, view, update):
await ack()
values = view["state"]["values"]
task_name = values["task_name_inpu... |
100103 | import wx
class AuiManagerConfig(wx.Config):
"""
Custom wxConfig class to handle the main frame size and position, plus all
the the panes of the aui.
"""
def __init__(self, auiMgr, *args, **kwargs):
wx.Config.__init__(self, *args, **kwargs)
self.auiMgr = auiMgr
... |
100107 | import struct
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if root is None:
... |
100111 | from tir import Webapp
import unittest
class GFEA030(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGAGFE','05/12/2020','T1','D MG 01 ','78')
inst.oHelper.Program('GFEA030')
def test_GFEA030_CT001(self):
self.oHelper.SetButton('Incluir')
self.oHelpe... |
100125 | from sfaira.versions.topologies.mouse.embedding.ae import AE_TOPOLOGIES
from sfaira.versions.topologies.mouse.embedding.linear import LINEAR_TOPOLOGIES
from sfaira.versions.topologies.mouse.embedding.nmf import NMF_TOPOLOGIES
from sfaira.versions.topologies.mouse.embedding.vae import VAE_TOPOLOGIES
from sfaira.versions... |
100155 | from abc import ABC, abstractmethod
from enum import Enum
from typing import TYPE_CHECKING, Any, Callable, Union
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.vi_state import InputMode
if TYPE_CHECKING:
from .application import Application
__all__ = [
"CursorShape",
"Cursor... |
100164 | import random
from .samples import Sample
from .synthesizers import SAW
from .notes import C5
from .internals.chords import _CHORD_QUALITY
from .internals.scales import _SCALE_MODE
from .synth_server import (
SonicPi,
use_synth,
)
__debug = False
def synth(name, note=None, attack=None, decay=None,
sustain... |
100208 | import vcs
import cdms2
import os
import MV2
f = cdms2.open(os.path.join(vcs.sample_data, "clt.nc"))
s = f("clt", time=slice(0, 1), squeeze=1)
s = MV2.masked_less(s, 65.)
x = vcs.init()
gm = x.createisofill()
gm.missing = 252
x.plot(s, gm)
x.png(gm.g_name)
x.interact()
|
100231 | import numpy as np
class ClusterProcessor(object):
def __init__(self, dataset):
self.dataset = dataset
self.dtype = np.float32
def __len__(self):
return self.dataset.size
def build_adj(self, node, edge):
node = list(node)
abs2rel = {}
rel2abs = {}
... |
100236 | from pgmpy.models import MarkovModel
from pgmpy.factors.discrete import JointProbabilityDistribution, DiscreteFactor
from itertools import combinations
from flyingsquid.helpers import *
import numpy as np
import math
from tqdm import tqdm
import sys
import random
class Mixin:
'''
Functions to compute observabl... |
100237 | import numpy as np
from hand import Hand
iterations = 250000
starting_size = 8 #inclusive
mullto = 7 #inclusive
hand = Hand("decklists/affinity.txt")
hand_types = ["t1 2-drop", "t1 3-drop"]
hand_counts = np.zeros(((starting_size + 1) - mullto,len(hand_types)))
totals = np.zeros(((starting_size + 1) - mullto,1))
zero_... |
100288 | from django.db import models
from django.template.defaultfilters import title
from django.utils.datastructures import SortedDict
from calaccess_campaign_browser.templatetags.calaccesscampaignbrowser import (
jsonify
)
class BaseModel(models.Model):
class Meta:
abstract = True
def meta(self):
... |
100344 | import os
import pytest
from ozy import OzyError
from ozy.files import walk_up_dirs, get_ozy_dir
def test_ozy_dirs():
ozy_dir = get_ozy_dir()
assert ozy_dir is not None
home = os.environ['HOME']
del os.environ['HOME']
with pytest.raises(OzyError):
get_ozy_dir()
os.environ['HOME'] = h... |
100360 | class CommandError(Exception):
"""
Exception class indicating a problem while executing a stapler command.
"""
pass
OPTIONS = None # optparse options
def main(arguments=None):
from . import stapler
stapler.main(arguments)
|
100378 | import logging
from openpyxl import Workbook
from output.ReportBase import ReportBase
class RawMaturityAssessmentReport(ReportBase):
def createWorkbook(self, jobs, controllerData, jobFileName):
for reportType in ["apm", "brum", "mrum"]:
logging.info(f"Creating {reportType} Maturity Assessment... |
100404 | import SimpleHTTPServer
import SocketServer
import os
PORT = 8000
class Allow(SimpleHTTPServer.SimpleHTTPRequestHandler):
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file obje... |
100425 | import logging
from pyfcm import FCMNotification
from spacelaunchnow.config import keys
from spacelaunchnow import config
logger = logging.getLogger(__name__)
class EventNotificationHandler:
def __init__(self, debug=None):
if debug is None:
self.DEBUG = config.DEBUG
else:
... |
100529 | from setuptools import setup, Extension
from torch.utils import cpp_extension
import os
stonne_src_dir='../../stonne/src'
my_pwd=os.path.abspath(".")
include_dir=my_pwd+'/../../stonne/include/'
external_dir=my_pwd+'/../../stonne/external/'
list_of_src_files_to_link=['torch_stonne.cpp', '../../stonne/stonne_linker_sr... |
100535 | import numpy as np
from sklearn import model_selection
import typing as t
from copy import copy
from ..mltypes import RandomState
from ..data.dataset import Dataset
class DataSplit:
def get_splits(self, dataset: Dataset) -> t.Generator[t.Tuple[Dataset, Dataset], None, None]:
raise NotImplementedError
c... |
100563 | import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from app import sf_manager, app
from panels import opportunities, cases, leads
server = app.server
app.layout = html.Div(
[
html.Div(
className="row header",
... |
100566 | import numpy as np
from itertools import product
from deep_rlsp.envs.gridworlds.env import Env, Direction, get_grid_representation
class BasicRoomEnv(Env):
"""
Basic empty room with stochastic transitions. Used for debugging.
"""
def __init__(self, prob, use_pixels_as_observations=True):
sel... |
100609 | import datetime
import pytest
from tartiflette.scalar.builtins.time import ScalarTime
@pytest.mark.parametrize(
"value,should_raise_exception,expected",
[
(None, True, "Time cannot represent value: < None >."),
(True, True, "Time cannot represent value: < True >."),
(False, True, "Ti... |
100617 | import time
def newJson(json):
print(op('container1/record')[0])
if op('container1/record')[0] == 1:
jsonRecord = op('json_record')
jsonRecord[0,0] = int(time.time())
jsonRecord[0,1] = json
op('json_record_out').par.write.pulse()
return
|
100624 | from future.builtins import range
from .utils import memoize
from . import context
def redis_key(name, *args):
prefix = context.get_current_config()["redis_prefix"]
if name == "known_subqueues":
return "%s:ksq:%s" % (prefix, args[0].root_id)
elif name == "queue":
return "%s:q:%s" % (prefix, args[0].id)... |
100637 | from django.db import models
class AudioFileMixin(models.Model):
audio_file = models.FileField()
class Meta:
abstract = True
|
100678 | import sys, os, imp
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..')))
from pypy.tool import slaveproc
class IsolateSlave(slaveproc.Slave):
mod = None
def do_cmd(self, cmd):
cmd, data = cmd
if cmd == 'load':
assert self.mod is None
... |
100698 | from sys import platform as sys_pf
if sys_pf == 'darwin':
import matplotlib
matplotlib.use("TkAgg")
import unittest
import numpy.testing as np_test
from scripts.algorithms.polynomial_predictor import PolynomialPredictor
class PolynomialPredictorTests(unittest.TestCase):
def test_static_sequence(self):... |
100719 | import time
import numpy
def getNotes():
return {
"id1": {
"noteId": "id1",
"userId": "user1",
"content": str(numpy.array([1,2,3,4])),
"createdAt": int(time.time()),
},
"id2": {
"noteId": "id2",
"userId": "user2",
"... |
100742 | from nipype.interfaces.ants import N4BiasFieldCorrection
import sys
import os
import ast
if len(sys.argv) < 2:
print("INPUT from ipython: run n4_bias_correction input_image dimension n_iterations(optional, form:[n_1,n_2,n_3,n_4]) output_image(optional)")
sys.exit(1)
# if output_image is given
if len(sys.argv)... |
100744 | from tensorflow.python.framework import graph_util
from tensorflow.python.framework import graph_io
import tensorflow as tf
def convertMetaModelToPbModel(meta_model, pb_model):
# Step 1
# import the model metagraph
saver = tf.train.import_meta_graph(meta_model + '.meta', clear_devices=True)
# make tha... |
100758 | import os
import shutil
import numpy as np
import pandas as pd
import scipy.integrate, scipy.stats, scipy.optimize, scipy.signal
from scipy.stats import mannwhitneyu
import statsmodels.formula.api as smf
import pystan
def clean_folder(folder):
"""Create a new folder, or if the folder already exists,
delete a... |
100768 | from __future__ import unicode_literals
import frappe
def execute():
frappe.enqueue(assign, queue='long')
def assign():
users = frappe.get_all("User", {"user_type":"System User"})
for user in users:
user_roles = frappe.get_roles(user.name)
User = frappe.get_doc("User", {"name":user... |
100798 | from small_text.integrations.pytorch.exceptions import PytorchNotFoundError
try:
from small_text.integrations.transformers.datasets import TransformersDataset
from small_text.integrations.transformers.classifiers.classification import (
TransformerModelArguments,
TransformerBasedClassification,... |
100846 | from abc import ABCMeta, abstractmethod
class EqualizerTuning(object):
def __init__(self, playback_function, result_extractor, comparator, comparison_data_extractor=None):
"""
:param playback_function: A function that plays back the operation using the recording in the given id
:type playb... |
100882 | from django.contrib import admin
from django.urls import path, include
from .views import *
urlpatterns = [
path('tours/', TourView.as_view()),
path('tours/<int:tour_id>/', about_tour),
path('auth/', auth),
path('register/', register)
]
|
100907 | import nltk
from nltk.collocations import BigramCollocationFinder
from nltk.corpus import webtext
from nltk.metrics import BigramAssocMeasures
tokens=[t.lower() for t in webtext.words('grail.txt')]
words=BigramCollocationFinder.from_words(tokens)
print(words.nbest(BigramAssocMeasures.likelihood_ratio, 10))
|
100924 | class Solution:
def decodeString(self, s: str) -> str:
St = []
num = 0
curr = ''
for c in s:
if c.isdigit():
num = num*10 + int(c)
elif c == '[':
St.append([num, curr])
num = 0
curr = ''
... |
100930 | import os.path
import re
from numpy.distutils.core import setup, Extension
from numpy.distutils.system_info import get_info
def find_version(*paths):
fname = os.path.join(os.path.dirname(__file__), *paths)
with open(fname) as fp:
code = fp.read()
match = re.search(r"^__version__ = ['\"]([^'\"]*)['\... |
100954 | from coincurve import PrivateKey
from coincurve import PublicKey
from coincurve import verify_signature
SECPK1_N = (
115792089237316195423570985008687907852837564279074904382605163141518161494337
)
def sign_ecdsa(message, priv):
"""Gets ECDSA signature for message from private key."""
if not isinstance(... |
100955 | import random
import time
import datetime
from common.constants import DATE_ONLY_FORMAT
def tomorrow():
return datetime.datetime.now() + datetime.timedelta(days=1)
def generate_random_date(start, end, format=DATE_ONLY_FORMAT):
etime = time.mktime(time.strptime(end, format))
stime = time.mktime(time.str... |
100970 | arr=input("Enter array elements").split(' ')
arr=[int(x) for x in arr]
for i in range(len(arr)):
for j in range(len(arr)-1-i):
if(arr[j]>arr[j+1]):
arr[j],arr[j+1]=arr[j+1],arr[j]
print("Sorted array is:",arr)
"""
Problem Statement: Sort array using bubble sort technique
Sample Input/Output:... |
100993 | import os
import sys
import periphery
from .test import ptest, pokay, passert, AssertRaises
if sys.version_info[0] == 3:
raw_input = input
pwm_chip = None
pwm_channel = None
def test_arguments():
ptest()
# Invalid open types
with AssertRaises("invalid open types", TypeError):
periphery.PW... |
101001 | from django.contrib.auth.models import Group
from django.db.models import signals
from dms_plugins.pluginpoints import BeforeStoragePluginPoint, BeforeRetrievalPluginPoint, BeforeRemovalPluginPoint
from dms_plugins.workers import Plugin, PluginError
SECURITY_GROUP_NAME = 'security'
class GroupSecurityStore(Plugin, ... |
101022 | from lk_utils import relpath
from rich_click import Path
from ._vendor.rich_click_ext import click
@click.grp(help='PyPortable Installer command line interface.')
def cli():
pass
@click.cmd()
@click.arg('directory', default='.', type=Path())
def init(directory='.'):
"""
Initialize project with template... |
101025 | from toee import *
def OnBeginSpellCast(spell):
print "Ironthunder Horn OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
def OnSpellEffect(spell):
print "Ironthunder Horn OnSpellEffect"
targetsToRemove = []
... |
101031 | def perfect_square(x):
if (x == 0 or x == 1):
return x
i = 1
result = 1
while (result <= x):
i += 1
result = i * i
return i - 1
x = int(input('Enter no.'))
print(perfect_square(x))
|
101072 | class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
l1 = [int(s) for s in version1.split(".")]
l2 = [int(s) for s in version2.split(".")]
len1, len2 = len(l1), len(l2)
if len1 > len2:
l2 += [0] * (len1 - len2)
elif len1 < len2:
... |
101140 | import os
import unittest
import numpy as np
from pyNastran.bdf.bdf import BDF, BDFCard, CBAR, PBAR, PBARL, GRID, MAT1
from pyNastran.bdf.field_writer_8 import print_card_8
from pyNastran.bdf.mesh_utils.mass_properties import (
mass_properties, mass_properties_nsm) #mass_properties_breakdown
from pyNastran.bdf.c... |
101145 | from moviepy.editor import VideoFileClip
from davg.lanefinding.Pipeline import Pipeline
left_line = None
right_line = None
pipeline = Pipeline()
def lane_line_diag(img):
global left_line, right_line, pipeline
screen, left_line, right_line = pipeline.visualize_lanes_using_diagnostic_screen(img, left_line, righ... |
101150 | import requests
class RapidProClient:
def __init__(self, thread):
self.thread = thread
def send_reply(self, text):
response = requests.get(url=self.thread.chatbot.request_url, params={
'from': self.thread.uuid,
'text': text,
}, timeout=10)
return respo... |
101151 | prompt = """Translate to French (fr)
From English (es)
==========
Bramshott is a village with mediaeval origins in the East Hampshire district of Hampshire, England. It lies 0.9 miles (1.4 km) north of Liphook. The nearest railway station, Liphook, is 1.3 miles (2.1 km) south of the village.
----------
Bramshott est u... |
101191 | import os
from aztk.models.plugins.plugin_configuration import PluginConfiguration, PluginPort, PluginTargetRole
from aztk.models.plugins.plugin_file import PluginFile
dir_path = os.path.dirname(os.path.realpath(__file__))
def JupyterPlugin():
return PluginConfiguration(
name="jupyter",
ports=[Pl... |
101233 | import json, re
ontologies = ['ontocompchem', 'ontokin', 'wiki']
def process_puncutation(string):
# Load the regular expression library
# Remove punctuation
string_temp = re.sub('[-\n,.!?()\[\]0-9]', '', string)
# Convert the titles to lowercase
string_temp = string_temp.lower()
# Print out ... |
101244 | import pytest
from valid8.validation_lib import gt, gts, lt, lts, between, NotInRange, TooSmall, TooBig
def test_gt():
""" tests that the gt() function works """
assert gt(1)(1)
with pytest.raises(TooSmall):
gt(-1)(-1.1)
def test_gts():
""" tests that the gts() function works """
with p... |
101254 | import tensorflow as tf
from utils.bert import bert_utils
from loss import loss_utils
from utils.bert import albert_modules
from metric import tf_metrics
def classifier(config, seq_output,
input_ids,
sampled_ids,
input_mask,
num_labels,
dropout_prob,
**kargs):
"""
input_ids: origi... |
101294 | import torch
import shutil
import numpy as np
import matplotlib
matplotlib.use('pdf')
import matplotlib.pyplot as plt
# import cv2
from skimage.transform import resize
import torchvision.transforms as transforms
from sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score
class AverageMeter(obje... |
101315 | import unittest
from src.graph import Graph
from src.breadth_first_search import bfs
class BreadthFirstSearchTest(unittest.TestCase):
def test_bfs_parses_the_graph_in_order(self):
"""
Correctly explore the following graph:
_(a)--(c)--(e)
/ | / \ |
... |
101341 | from rest_framework.permissions import BasePermission, SAFE_METHODS, IsAdminUser
class IsAdminOrReadOnly(IsAdminUser):
def has_permission(self, request, view):
if request.method in SAFE_METHODS:
return True
return super().has_permission(request, view)
|
101345 | import torch
from torch.serialization import normalize_storage_type, location_tag, _should_read_directly
import io
import pickle
import pickletools
from .find_file_dependencies import find_files_source_depends_on
from ._custom_import_pickler import CustomImportPickler
from ._importlib import _normalize_path
import type... |
101380 | import math
import numpy as np
def quaternion_to_rotation_matrix(q):
# Original C++ Method defined in pba/src/pba/DataInterface.h
qq = math.sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
qw = qx = qy = qz = 0
if qq > 0: # NORMALIZE THE QUATERNION
qw = q[0] / qq
qx = q[1]... |
101388 | import numpy as np
import matplotlib.pyplot as plt
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(8,12))
# Plot pow with different settings
t = 1e-2
rcut = 5
settings = [
[2, rcut/(1/t*(1-t)) ** (1 / 2), 1],
[4, rcut/(1/t*(1-t)) ** (1 / 4), 1],
[8, rcut/(1/t*(1-t)) ** (1 / 8), 1],
]
rmin... |
101485 | from ._base import PDFItem
from .PDFShape import PDFShape
from .PDFImage import PDFImage
from .PDFText import PDFText
from .PDFXObject import PDFXObject |
101493 | from fireworks import FiretaskBase, FWAction, explicit_serialize, Workflow
from atomate.utils.utils import env_chk
from atomate.vasp.database import VaspCalcDb
from atomate.vasp.fireworks.approx_neb import ImageFW
from atomate.common.powerups import powerup_by_kwargs
__author__ = "<NAME>"
__email__ = "<EMAIL>"
@expl... |
101502 | from collections import deque
from csp.variable import Variable
from csp.constraint_problem import ConstraintProblem
def pc2(constraint_problem: ConstraintProblem) -> bool:
variable_diffvariable_neighbor_triplets = deque()
variables = constraint_problem.get_variables()
for var in variables:
for ne... |
101504 | import dataloader as dl
# Path to the ANI-1x data set
path_to_h5file = '/home/jujuman/Scratch/Research/ANI-1x1ccx/FINAL_CLEANED_DATA/ani1x-20190925_rz.h5'
# List of keys to point to requested data
data_keys = ['<KEY>','<KEY>'] # Original ANI-1x data (https://doi.org/10.1063/1.5023802)
#data_keys = ['<KEY>','<KEY>'] #... |
101505 | example_schema_array = {"type": "array", "items": {"type": "string"}}
example_array = ["string"]
example_schema_integer = {"type": "integer", "minimum": 3, "maximum": 5}
example_integer = 3
example_schema_number = {"type": "number", "minimum": 3, "maximum": 5}
example_number = 3.2
example_schema_object = {"type": "obje... |
101521 | import torch
import torch.nn as nn
import torchvision
class HopeNet(nn.Module):
# Hopenet with 3 output layers for yaw, pitch and roll
# Predicts Euler angles by binning and regression with the expected value
def __init__(self, block, layers, num_bins):
super(HopeNet, self).__init__()
if b... |
101538 | from requests import Request
from backend.database.objects import Game
from backend.blueprints.spa_api.service_layers.replay.json_tag import JsonTag
from backend.database.wrapper.tag_wrapper import TagWrapper
from tests.utils.location_utils import LOCAL_URL
from tests.utils.test_utils import check_array_equal
class ... |
101540 | from threading import Thread
from time import sleep
from PythonCard import model
import urllib
import re
def get_quote(symbol):
global quote
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('class="pr".*?>(.*?)<', conten... |
101541 | from __future__ import annotations
import yaml
from importlib.resources import read_text
from ...config.junos import JunosMetricConfiguration
from ...devices import junosdevice
from ...utitlities import create_list_from_dict
from .. import junos
from ..base import Collector
from . import base
class BGPCollector(Col... |
101558 | import unittest
import transaction
from pyramid import testing
from dbas.database import DBDiscussionSession
from dbas.database.discussion_model import StatementReference, Statement
from dbas.tests.utils import construct_dummy_request
from dbas.views import set_references, get_reference
class AjaxReferencesTest(uni... |
101574 | import pytest
from tagbot.web import app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
@app.route("/die")
def die():
raise Exception("!")
|
101588 | import gym
import numpy as np
import tensorflow as tf
from tensorflow import saved_model as sm
from easy_rl.utils.window_stat import WindowStat
from easy_rl.utils.gym_wrapper.atari_wrapper import make_atari, wrap_deepmind
import time
def main():
gym_env = gym.make("CartPole-v0")
atari_env = make_atari("PongN... |
101633 | import glob
import os
import numpy as np
import scipy
from scipy import signal
import fabio
import matplotlib.pyplot as plt
import center_approx
import integration
import peakfindingrem
import peakfinding
import scipy.optimize as optimize
import scipy.stats
from scipy import interpolate
from lmfit import minimize, ... |
101635 | import numpy as np
import datetime
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
import sklearn.metrics
from ops import add_features, augment_data
from sklearn.model_selection import tra... |
101657 | import collections
import warnings
import jax
import jax.numpy as np
FixedPointSolution = collections.namedtuple(
"FixedPointSolution",
"value converged iterations previous_value"
)
def unrolled(i, init_x, func, num_iter, return_last_two=False):
"""Repeatedly apply a function using a regular python loop... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.