id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
17351 | from vue.bridge import Object
import javascript
class VueDecorator:
__key__ = None
__parents__ = ()
__id__ = None
__value__ = None
def update(self, vue_dict):
base = vue_dict
for parent in self.__parents__:
base = vue_dict.setdefault(parent, {})
if self.__id__... |
17353 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import keras
from keras.models import Model, load_model
from keras import backend as K
from keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) # mute deprecation warnings
from kera... |
17355 | from setuptools import setup, find_packages
__name__ = "appJar"
__version__ = "0.94.0"
__author__ = "<NAME>"
__desc__ = "An easy-to-use, feature-rich GUI wrapper for tKinter. Designed specifically for use in the classroom, but powerful enough to be used anywhere."
__author_email__ = "<E... |
17375 | list1 = [10,9,3,7,2,1,23,1,561,1,1,96,1]
def cmp1(x,y):
if x == 1 or y==1:
c = y-x
else:
c = x-y
return c
list1.sort(cmp = cmp1)
print list1 |
17395 | from artemis.general.dict_ops import cross_dict_dicts, merge_dicts
__author__ = 'peter'
def test_cross_dict_dicts():
assert cross_dict_dicts({'a':{'aa': 1}, 'b':{'bb': 2}}, {'c': {'cc': 3}, 'd': {'dd': 4}}) == {
('a','c'):{'aa':1, 'cc':3},
('a','d'):{'aa':1, 'dd':4},
('b','c'):{'bb':2, 'c... |
17405 | import os
import json
from common import update_json_file, get_logger, exec_cmd
from yamlparser import Parser
from pathlib import Path
logger = get_logger("update-image")
# Functions that work to update gluu_versions.json
def determine_final_official_and_dev_version(tag_list):
"""
Determine official version... |
17447 | import unittest
import os
import sys
import StringIO
path = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../lvsm')))
from lvsm.modules import keepalived
class Keepalived(unittest.TestCase):
"""Tests for the functionality of the keepalive... |
17460 | import pytest
import re
import unittest
import metric_learn
import numpy as np
from sklearn import clone
from test.test_utils import ids_metric_learners, metric_learners, remove_y
from metric_learn.sklearn_shims import set_random_state, SKLEARN_AT_LEAST_0_22
def remove_spaces(s):
return re.sub(r'\s+', '', s)
def ... |
17472 | from collections import namedtuple
import pytest
from nesta.packages.examples.example_package import some_func
@pytest.fixture
def mocked_row():
def _mocked_row(*, id, name):
Row = namedtuple('Row', ['id', 'name'])
return Row(id=id, name=name)
return _mocked_row
class TestSomeFunc:
def... |
17486 | from .db import db
from .userfollower import UserFollower
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from sqlalchemy import Table, Column, Integer, ForeignKey, or_
from .directmessage import DirectMessage
from .userequipment import UserEquipment
from .equ... |
17499 | import math
import time
from compas_fab.backends import RosClient
from compas.artists import Artist
from compas.geometry import Frame
with RosClient("localhost") as client:
robot = client.load_robot(load_geometry=True)
group = robot.main_group_name
frame = Frame((0.4, 0.3, 0.05), (-1, 0, 0), (0, 1, 0))
... |
17502 | import PIL
import numpy as np
def to_grayscale(img):
return np.dot(img, [0.299, 0.587, 0.144])
def zero_center(img):
return img - 127.0
def crop(img, bottom=12, left=6, right=6):
height, width = img.shape
return img[0: height - bottom, left: width - right]
def save(img, path):
pil_img = PIL.... |
17540 | from abc import ABC as Contract, abstractmethod
class AuthContract(Contract):
@abstractmethod
def user(self):
pass
@abstractmethod
def save(self):
pass
@abstractmethod
def delete(self):
pass
|
17580 | import tensorflow as tf
from detection.utils.misc import *
class PyramidROIAlign(tf.keras.layers.Layer):
def __init__(self, pool_shape, **kwargs):
'''
Implements ROI Pooling on multiple levels of the feature pyramid.
Attributes
---
pool_shape: (height, width) of the o... |
17590 | import argparse
import os.path as osp
from glob import glob
import cv2
import pandas as pd
from tqdm import tqdm
from gwd.converters import kaggle2coco
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--image-pattern", default="/data/SPIKE_images/*jpg")
parser.add_argument("--an... |
17617 | import trio
import os
import json
from itertools import count
# Experiment with generating Chrome Event Trace format, which can be browsed
# through chrome://tracing or other mechanisms.
#
# Screenshot: https://files.gitter.im/python-trio/general/fp6w/image.png
#
# Trace format docs: https://docs.google.com/document/d... |
17625 | from __future__ import print_function
import tensorflow as tf
import numpy as np
from collections import namedtuple, OrderedDict
from subprocess import call
import scipy.io.wavfile as wavfile
import argparse
import codecs
import timeit
import struct
import toml
import re
import sys
import os
def _int64_feature(value)... |
17627 | import xNormal
xNormal.run("piano_high.obj", "piano_low.obj", "piano.png", width=256, height=256, gen_normals = True, gen_ao = True) |
17631 | from copy import deepcopy
from typing import Tuple
import jax.numpy as jnp
from jax.scipy.linalg import cho_factor, cho_solve
from multipledispatch import dispatch
from .types import Array
def I(n: int) -> Array:
"""
Compute an n x n identity matrix.
:param n: The size of of the matrix.
:return: An ... |
17632 | import os
def replace_version(old_version, new_version):
if not isinstance(old_version, tuple) or not isinstance(new_version, tuple):
raise ValueError("`old_version` and `new_version` must be a version tuple. Eg: (1.2.3)")
major, minor, micro = old_version[:3]
old_version = f'{major}.{minor}.{mic... |
17670 | from plumbum import local
import benchbuild as bb
from benchbuild.environments.domain.declarative import ContainerImage
from benchbuild.source import HTTP
from benchbuild.utils.cmd import make, tar
class XZ(bb.Project):
""" XZ """
VERSION = '5.2.1'
NAME = 'xz'
DOMAIN = 'compression'
GROUP = 'benc... |
17703 | import logging
import math
import re
import time
import dask
import numpy as np
import requests
import json
import xml.etree.ElementTree as ET
from falconcv.data.scraper.scraper import ImagesScraper
from falconcv.util import ImageUtil
logger = logging.getLogger(__name__)
FLICKR_ENDPOINT = "https://www.flickr.com/servic... |
17709 | from .version import VersionViewSet, DeployVersionViewSet
__all__ = ["VersionViewSet", "DeployVersionViewSet"]
|
17711 | from ast import literal_eval
from collections import Counter
from typing import Dict, Optional
from anndata import AnnData
from spatialtis.config import Config, analysis_list
from ...utils import doc
from ..base import graph_position_interactive, graph_position_static
from .utils import query_df
@doc
def community... |
17779 | from datetime import datetime
from pathlib import Path
import pytz
import kobuddy
def get_test_db():
# db = Path(__file__).absolute().parent.parent / 'KoboShelfes' / 'KoboReader.sqlite.0'
db = Path(__file__).absolute().parent / 'data' / 'kobo_notes' / 'input' / 'KoboReader.sqlite'
return db
# a bit meh, ... |
17843 | import wx
import cv2
#----------------------------------------------------------------------
# Panel to display image from camera
#----------------------------------------------------------------------
class WebcamPanel(wx.Window): # wx.Panel, wx.Control
def __init__(self, parent, camera, fps=15, flip=Fals... |
17848 | def arg_to_step(arg):
if isinstance(arg, str):
return {'run': arg}
else:
return dict(zip(['run', 'parameters', 'cache'], arg))
def steps(*args):
return [arg_to_step(arg) for arg in args]
|
17858 | import numpy as np
import scipy.stats as stats
from UQpy.Distributions.baseclass.Distribution import Distribution
class DistributionContinuous1D(Distribution):
"""
Parent class for univariate continuous probability distributions.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
... |
17861 | import requests
import re
import time
import random
import pprint
import os
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3858.0 Safari/537.36"}
def youdict(threadName, q):
res = []
index = 0
url = q.get(timeout = 2)
... |
17876 | from abc import ABC, abstractmethod
class MarioGame(ABC):
@abstractmethod
def getPort(self) -> int:
pass
@abstractmethod
def initGame(self):
pass
@abstractmethod
def stepGame(self, left: bool, right: bool, down: bool, speed: bool, jump: bool):
pass
@abstractmetho... |
17881 | from malaya_speech.utils import (
check_file,
load_graph,
generate_session,
nodes_session,
)
from malaya_speech.model.tf import UNET, UNETSTFT, UNET1D
def load(model, module, quantized=False, **kwargs):
path = check_file(
file=model,
module=module,
keys={'model': 'model.pb... |
17900 | import importlib.metadata
import logging
import os
import shutil
from typing import Dict, Any, List
import click
from sqlalchemy import text
from dbd.log.dbd_exception import DbdException
from dbd.config.dbd_profile import DbdProfile
from dbd.config.dbd_project import DbdProject
from dbd.executors.model_executor impo... |
17975 | import os
import sys
cwd = os.getcwd()
sys.path.append(cwd)
import pickle
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from plot.helper import plot_task, plot_weights, plot_rf_z_max, plot_rf_quad, plot_vector_traj
tasks = [
'com_pos', 'com_vel', 'chassis_quat', 'ch... |
18106 | import justpy as jp
from .group import Group
class Row(Group):
def __init__(self):
'''Row Element
Provides a container which arranges its child in a row.
'''
view = jp.QDiv(classes='row items-start', style='gap: 1em', delete_flag=False)
super().__init__(view)
|
18164 | from rest_framework import status
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from ..permissions import IsAuthenticated
from django.core.cache import cache
from django.conf import settings
from ..authentication import TokenAuthentication
from ..app_settings import (... |
18169 | from .utils import TestCase
from .utils import build_and_test_module
from .utils import transpile_source
class Test(TestCase):
def test_compare(self):
with self.assertRaises(SystemExit):
build_and_test_module('compare')
def test_assert_between(self):
self.assert_transpile_raises(... |
18190 | from .. import db
from .base import BaseModel
class ChildDatum(BaseModel):
__tablename__ = 'child_data'
# fields
parent_id = db.Column(db.Integer, db.ForeignKey('data.id'), nullable=False)
datum_id = db.Column(db.Integer, db.ForeignKey('data.id'), nullable=False)
name = db.Column(db.String(length... |
18194 | import multiprocessing as mp
class ModuleRecursion(object):
"""Class to handle recursion.
Simple class to handle tracking and storing prior
sub-domains discovred.
"""
def __init__(self):
"""class init.
"""
self.recursion_queue = mp.Queue()
def add_subdomain(self, domain):
"""add subdomain to Q.
... |
18223 | from .constants import SPECIAL_TOKENS
try:
import re2 as re
except ImportError:
import re
def twitter_sentiment_token_matching(token):
"""Special token matching function for twitter sentiment data."""
if 'URL_TOKEN' in SPECIAL_TOKENS and re.match(r'https?:\/\/[^\s]+', token):
return SPECIAL_TO... |
18226 | import datetime
from dateutil.parser import parse
from mongoengine import DateTimeField, FileField
from mongoengine.connection import DEFAULT_CONNECTION_NAME
#from mongoengine.python_support import str_types
from six import string_types as str_types
import io
from django.conf import settings
if settings.FILE_DB == se... |
18269 | import numpy as np
import matplotlib.pyplot as plt
#Dahlquist test
#sol1ex = lambda t: np.exp(-t)
#sol2ex = lambda t: np.exp(-2*t)
#oscillator 1
sol1ex = lambda t: np.cos(t**2/2)
sol2ex = lambda t: np.sin(t**2/2)
#oscillator 2
#sol1ex = lambda t: np.exp(np.sin(t**2))
#sol2ex = lambda t: np.exp(np.cos(t**2))
name = 'O... |
18287 | import requests
from bs4 import BeautifulSoup
import json
def loadMasterStock():
url = "http://www.supremenewyork.com/mobile_stock.json"
user = {"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Version/10.0 Mobile/14D27 Safari/602.1"}
# user = {"User-Ag... |
18294 | from typing import Optional
from algorithms.basic_testing import BasicTesting
from simulator.controllers.main_controller import MainController
from simulator.controllers.map.map_controller import MapController
from simulator.controllers.gui.gui_controller import GuiController
from simulator.models.main_model import M... |
18326 | import copy
import logging
import numpy as np
import six
import tensorflow as tf
from functools import wraps
from contextlib import contextmanager
from .backend_base import BackendBase, FunctionBase, DeviceDecorator
try:
from tensorflow.contrib.distributions import fill_triangular
except:
print("Cannot find fi... |
18367 | from __future__ import division
import pandas as pd
import numpy as np
import calendar
import os.path as op
import sys
from datetime import datetime
from dateutil.relativedelta import relativedelta
from scipy.stats import percentileofscore
from scipy.stats import scoreatpercentile, pearsonr
from math import *
import t... |
18407 | from abc import ABCMeta, abstractmethod
import torch
import torch.nn.functional as F
from addict import Dict
from mmtrack.models import TRACKERS
@TRACKERS.register_module()
class BaseTracker(metaclass=ABCMeta):
"""Base tracker model.
Args:
momentums (dict[str:float], optional): Momentums to update ... |
18472 | import torch
import torchvision
import torchvision.transforms as transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from model_utils import *
class down(nn.Module):
"""
A class for creating neural network blocks containing layers:
Average P... |
18475 | import sys
from PySide2.QtWidgets import QApplication
from PySide2.QtGui import QColor
from pivy import quarter, coin, graphics, utils
class ConnectionMarker(graphics.Marker):
def __init__(self, points):
super(ConnectionMarker, self).__init__(points, True)
class ConnectionPolygon(graphics.Polygon):
s... |
18477 | import numpy as np
np.deprecate(1) # E: No overload variant
np.deprecate_with_doc(1) # E: incompatible type
np.byte_bounds(1) # E: incompatible type
np.who(1) # E: incompatible type
np.lookfor(None) # E: incompatible type
np.safe_eval(None) # E: incompatible type
|
18517 | import unittest
import zserio
from testutils import getZserioApi
class Bit4RangeCheckTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.api = getZserioApi(__file__, "with_range_check_code.zs",
extraArgs=["-withRangeCheckCode"]).bit4_range_check
def testB... |
18536 | from bitmovin_api_sdk.encoding.encodings.muxings.mp3.mp3_api import Mp3Api
from bitmovin_api_sdk.encoding.encodings.muxings.mp3.customdata.customdata_api import CustomdataApi
from bitmovin_api_sdk.encoding.encodings.muxings.mp3.information.information_api import InformationApi
from bitmovin_api_sdk.encoding.encodings.m... |
18558 | from __future__ import print_function
from sympy import symbols, Matrix
from galgebra.printer import xpdf, Format
def main():
Format()
a = Matrix ( 2, 2, ( 1, 2, 3, 4 ) )
b = Matrix ( 2, 1, ( 5, 6 ) )
c = a * b
print(a,b,'=',c)
x, y = symbols ( 'x, y' )
d = Matrix ( 1, 2, ( x ** 3, y ** 3... |
18571 | from collections import defaultdict
from celery.task import task
from pandas import concat, DataFrame
from bamboo.core.aggregator import Aggregator
from bamboo.core.frame import add_parent_column, join_dataset
from bamboo.core.parser import Parser
from bamboo.lib.datetools import recognize_dates
from bamboo.lib.jsont... |
18572 | import inviwopy
from inviwopy.glm import *
v1 = vec3(1,2,3)
v2 = size2_t(4,5)
m1 = mat4(1)
m2 = mat3(0,1,0,-1,0,0,0,0,2)
v3 = m2 * v1
v4 = vec4(1,2,3,4)
w = v4.w
a = v4.a
q = v4.q
z = v4.z
b = v4.b
p = v4.p
y = v4.y
g = v4.g
t = v4.t
x = v4.x
r = v4.r
s = v4.s
|
18601 | from typing import List
import asyncio
import inspect
import logging
import uuid
import aio_pika
import aio_pika.exceptions
from .base import BaseRPC
from .common import RPCError, RPCHandler, RPCRequest, RPCResponse
class RPC(BaseRPC):
HEARTBEAT_INTERVAL = 300
def __init__(
self,
url: str =... |
18643 | from torch import Tensor, nn
from ...base import VisionModule
class ClassificationModule(VisionModule):
"""Base Classification Module class"""
def __init__(
self,
encoder: nn.Module,
head: nn.Module,
in_channels: int = 3,
n_classes: int = 1000,
**kwargs
):... |
18647 | from elasticsearch import TransportError
from sanic import Blueprint
from sanic.request import Request
from sanic.response import HTTPResponse, json
from ..connections import get_client
rest_bp = Blueprint('rest')
def format_es_exception(e: TransportError):
return json({"status_code": e.status_code,
... |
18693 | from __future__ import print_function
import numpy as np
import argparse
import glob
import os
import errno
import math
import cv2
from random import shuffle
from shutil import copyfile
parser = argparse.ArgumentParser(
description="create training/test/validation sets from video list"
)
parser.add_argument("--vi... |
18707 | import os
import sys
import json
import argparse
import numpy as np
sys.path.append('Camera_Intrinsics_API/')
from get_camera_intrinsics import CameraIntrinsicsHelper
if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
"--input_dir",
type=str,
default='dat... |
18721 | class register:
plugin_dict = {}
plugin_name = []
@classmethod
def register(cls, plugin_name):
def wrapper(plugin):
cls.plugin_dict[plugin_name] = plugin
return plugin
return wrapper |
18785 | import dateutil
import pytest
from testsuite.plugins import mockserver
from testsuite.utils import json_util
NOW = dateutil.parser.parse('2019-09-19-13:04:00.000000')
MOCKSERVER_INFO = mockserver.MockserverInfo(
'localhost', 123, 'http://localhost:123/', None,
)
MOCKSERVER_SSL_INFO = mockserver.MockserverInfo(
... |
18805 | import sys, os
external_libs = {'Cleverhans v1.0.0': "externals/cleverhans",
'Tensorflow-Model-Resnet': "externals/tensorflow-models",
}
project_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
for lib_name, lib_path in external_libs.iteritems():
lib_path = os... |
18815 | import torch
from torch import nn
class FlowSequential(nn.Sequential):
"""Forward pass with log determinant of the Jacobian."""
def forward(self, input, context=None):
total_log_prob = torch.zeros(input.size(0), device=input.device)
for block in self._modules.values():
input, log_prob = block(input,... |
18819 | from app.blogging import bp
from datetime import datetime
from flask import flash, redirect, url_for
from flask_login import current_user
@bp.before_request
def protect():
'''
Registers new function to Flask-Blogging Blueprint that protects
updates to make them only viewable by paid subscribers.
'''
... |
18828 | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i = 0
for num in list(arr):
if i >= len(arr): break
arr[i] = num
if not num:
i += 1
... |
18834 | try:
from rpython.rlib.debug import make_sure_not_resized # pylint: disable=W
except ImportError:
"NOT_RPYTHON"
def make_sure_not_resized(_):
pass
|
18878 | import tensorflow as tf
from data.BaseReader import BaseReader
import numpy as np
class Base2DReader(BaseReader):
# inherit from BaseReader, implement different 2D cropping (cropping from 2D)
def __init__(self, objtype=0, shuffle=True, batch_size=1, crop_noise=False):
super(Base2DReader, self).__init... |
18907 | import sys
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # NOQA
import seaborn # NOQA
from spherecluster import sample_vMF
plt.ion()
n_clusters = 3
mus = np.random.randn(3, n_clusters)
mus, r = np.linalg.qr(mus, mode='reduced')
kappas = [15, 15, 15]
num_points_per... |
18932 | class GlobalOptions:
""" Class to evaluate global options for example: project path"""
@staticmethod
def evaluate_project_path(path):
""" Method to parse the project path provided by the user"""
first_dir_from_end = None
if path[-1] != "/":
path = path + "/"
new_p... |
18941 | from src.commons.big_query.copy_job_async.result_check.result_check_request import \
ResultCheckRequest
from src.commons.big_query.copy_job_async.task_creator import TaskCreator
class BigQueryJobReference(object):
def __init__(self, project_id, job_id, location):
self.project_id = project_id
s... |
18943 | from django.contrib import admin, messages
from django.shortcuts import render
from django.utils.translation import gettext_lazy as _
from inline_actions.actions import DefaultActionsMixin, ViewAction
from inline_actions.admin import InlineActionsMixin, InlineActionsModelAdminMixin
from . import forms
from .models im... |
18997 | import ipywidgets as widgets
from traitlets import Unicode, Int, validate
import os
import json
from datetime import datetime,timedelta
from IPython.display import Javascript
from IPython.display import HTML
from cognipy.ontology import Ontology
from IPython.display import clear_output
_JS_initialized = False
def _In... |
19063 | import json
from django.core.management.base import BaseCommand
from 臺灣言語平臺.正規化團隊模型 import 正規化sheet表
from django.conf import settings
class Command(BaseCommand):
help = '加sheet的json'
def add_arguments(self, parser):
parser.add_argument(
'服務帳戶json',
type=str,
hel... |
19150 | class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [inf] * (amount + 1)
dp[0] = 0
for coin in coins:
for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] != inf else -1
|
19156 | import pytest
from ..model_base_test import ModelBaseTest
from tests.sampleresponse.cardless_credit import cardless_credit_payment_response
from xendit.models import CardlessCredit, CardlessCreditType
# fmt: off
class TestCreateCardlessCreditPayment(ModelBaseTest):
@pytest.fixture
def default_cardles... |
19175 | class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
parent=[i for i in range(len(row))]
for i in range(1,len(row),2):
parent[i]-=1
def findpath(u,parent):
if parent[u]!=u:
parent[u]=findpath(parent[u],parent)
... |
19209 | import pytest
from wikidict.render import parse_word
from wikidict.utils import process_templates
@pytest.mark.parametrize(
"word, pronunciations, gender, etymology, definitions",
[
("ababalhar", [], "", ["De baba."], ["<i>(popular)</i> babar; conspurcar"]),
(
"alguém",
... |
19271 | import os
import uuid
import logging
import json
from json import JSONEncoder
from pythonjsonlogger import jsonlogger
from datetime import datetime
from logging.config import dictConfig
# Custom JSON encoder which enforce standard ISO 8601 format, UUID format
class ModelJsonEncoder(JSONEncoder):
def default(self,... |
19315 | import iota_client
client = iota_client.Client()
print(
client.get_output("a22cba0667c922cbb1f8bdcaf970b2a881ccd6e88e2fcce50374de2aac7c37720000")
) |
19318 | from datetime import datetime
{
datetime(2019, 12, 30, 0, 0): 35,
datetime(2020, 1, 6, 0, 0): 27,
datetime(2020, 1, 13, 0, 0): 39,
datetime(2020, 1, 20, 0, 0): 120,
datetime(2020, 1, 27, 0, 0): 73,
datetime(2020, 2, 3, 0, 0): 48,
datetime(2020, 2, 10, 0, 0): 35,
datetime(2020, 2, 17, 0,... |
19320 | import numpy as np
from numpy import genfromtxt
import matplotlib.pyplot as plt
import os
time_steps = 8760
file_name = "../input_data/Ecofys_ECN_heating_profiles.csv"
data = zip(*genfromtxt(file_name, delimiter=','))
names = ["tussenwoning_laag", "tussenwoning_midden", "tussenwoning_hoog",
"hoekwoning_laa... |
19357 | import inspect
import functools
from gridengine import job, dispatch, schedulers
# ----------------------------------------------------------------------------
# Partial
# ----------------------------------------------------------------------------
def isexception(x):
"""Test whether the value is an Exception instan... |
19368 | import unittest
from yapper import create_app, db
from yapper.blueprints.user.models import User, Role
class TestUserAddToDb(unittest.TestCase):
def setUp(self):
self.app = create_app('test')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
def... |
19375 | import re
import logging
logger = logging.getLogger(__name__)
def get_sorted_pair(a, b):
# ensure citation pair is always in same order
if a > b:
return (a, b)
else:
return (b, a)
def to_label(t, labels):
if t in labels:
return t
else:
return 'other'
def normal... |
19379 | bl_info = {
"name": "Import Fromsoft FLVER models",
"description":
"Import models from various Fromsoft games such as Dark Souls",
"author": "<NAME>",
"version": (0, 1, 0),
"blender": (2, 80, 0),
"category": "Import-Export",
"location": "File > Import",
"warning": "",
"... |
19434 | from setuptools import setup, find_packages
setup(
name = "imgdup",
version = "1.3",
packages = find_packages(),
scripts = ['imgdup.py'],
install_requires = ['pillow>=2.8.1'],
# metadata for upload to PyPI
author = "<NAME>",
author_email = "<EMAIL>",
description = "Visual similarity... |
19444 | import logging
from http import cookiejar as http_cookiejar
from http.cookiejar import http2time # type: ignore
from typing import Any # noqa
from typing import Dict # noqa
from urllib.parse import parse_qs
from urllib.parse import urlsplit
from urllib.parse import urlunsplit
from oic.exception import UnSupported
f... |
19456 | import decimal
import hashlib
import json
import requests
import tempfile
import uuid
import os
from tqdm import tqdm
from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor
def sha256_for_file(f, buf_size=65536):
pos = f.tell()
dgst = hashlib.sha256()
while True:
data = f.read(bu... |
19466 | import logging
import couchdb
from collections import deque
from threading import Thread
from pylons import config
from lr.lib import SpecValidationException, helpers as h
from lr.lib.couch_change_monitor import BaseChangeHandler
from lr.model import ResourceDataModel
from couchdb import ResourceConflict
from lr.lib.re... |
19479 | import ctypes
import ctypes.util
libc = ctypes.CDLL(ctypes.util.find_library('c'))
# Get network device's name
def if_indextoname (index):
if not isinstance (index, int):
raise TypeError ('Index must be an integer.')
libc.if_indextoname.argtypes = [ctypes.c_uint32, ctypes.c_char_p]
libc.if_indexto... |
19485 | from __future__ import annotations
__all__ = ("executor",)
import inspect
import sys
from asyncio import get_running_loop
from concurrent.futures import Executor
from functools import partial, wraps
from typing import Awaitable, Callable, TypeVar, overload
from asphalt.core import Context
if sys.version_info >= (3,... |
19538 | import json
import gen.Types
def loader(f):
return json.load(open('../GenerateDatas/json/' + f + ".json", 'r'), encoding="utf-8")
tables = gen.Types.Tables(loader)
print(tables)
r = tables.TbFullTypes.getDataList()[0].__dict__
print(r)
|
19575 | import time
import typing
import requests
from sys import stderr
from datetime import datetime
from packettotal_sdk import packettotal_api
class SearchTools(packettotal_api.PacketTotalApi):
def __init__(self, api_key: str):
"""
:param api_key: An API authentication token
"""
sup... |
19578 | from unittest.mock import Mock, patch
import pandas as pd
from sdgym.s3 import is_s3_path, parse_s3_path, write_csv, write_file
def test_is_s3_path_with_local_dir():
"""Test the ``sdgym.s3.is_s3_path`` function with a local directory.
If the path is not an s3 path, it should return ``False``.
Input:
... |
19584 | import csv
import sys
from pathlib import Path
from abc import abstractmethod
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import common.tf_utils as tf_utils
import metrics.manager as metric_manager
from common.model_loader import Ckpt
from common.utils import format_text
from common.utils import ... |
19625 | import argparse
import os
import csv
import random
from utils import ensure_dir, get_project_path
from collections import defaultdict
# POS-tag for irrelevant tag selection
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
__author__ = "<NAME>"
def write_tsv(intention_dir_path, filenam... |
19636 | from decimal import Decimal
from typing import List, Any
from common.Enums import SortingType
from models import Message
from .engine import db_engine, DBEngine
class MessageDAO:
def __init__(self, engine: DBEngine):
self.engine = engine
@staticmethod
def __make_insert_values_from_messages_array... |
19660 | import numpy as np
import tensorflow as tf
from tqdm import trange
from fedsimul.utils.model_utils import batch_data
from fedsimul.utils.tf_utils import graph_size
from fedsimul.utils.tf_utils import process_grad
class Model(object):
'''
This is the tf model for the MNIST dataset with multiple class learner ... |
19703 | import os
import yaml
import copy
import logging
from pathlib import Path
import torch
from torch.nn import *
from torch.optim import *
import torch.distributed as dist
from torch.optim.lr_scheduler import *
from torch.nn.parallel import DistributedDataParallel
from utils.metrics import *
from models import _get_mode... |
19705 | from graph_peak_caller.multiplegraphscallpeaks import MultipleGraphsCallpeaks
from graph_peak_caller.intervals import Intervals
from graph_peak_caller import Configuration
from graph_peak_caller.reporter import Reporter
from offsetbasedgraph import GraphWithReversals as Graph, \
DirectedInterval, IntervalCollection... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.