id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3296956 | import facebook
from . import FacebookTestCase
class FacebookParseSignedRequestTestCase(FacebookTestCase):
cookie = (
"Z6pnNcY-TePEBA7IfKta6ipLgrig53M7DRGisKSybBQ."
"<KEY>DLV<KEY>"
"M090T3BSRGtpT1k4UDNlOWgwYzZRNFFuMEFFQnVqR1M3ZEV5LXNtbUt5b3pD"
"dHdhZy1kRmVYNmRUbi12dVBfQVNtek5Rbjlka... |
3296998 | import xml.etree.ElementTree as ET
from programy.dialog.sentence import Sentence
from programy.parser.template.nodes.word import TemplateWordNode
from programytest.parser.base import ParserTestsBaseClass
class PatternMatcherBaseClass(ParserTestsBaseClass):
def add_pattern_to_graph(self, pattern, topic="*", that... |
3297032 | from setuptools import setup, Extension
setup(
use_scm_version={
"tag_regex": r"^(?P<version>[vV]?\d+(?:\.\d+){0,2}[^\+]*)(?:\+.*)?$"
},
ext_modules=[
Extension("jntajis._jntajis", ["src/jntajis/_jntajis.pyx"]),
],
)
|
3297121 | from z3 import *
x, y = Ints('x y')
solve([y == x + 1, ForAll([y], Implies(y <= 0, x < y))])
solve([y == x + 1, ForAll([y], Implies(y <= 0, x > y))])
|
3297122 | import pytest
from spellbot.models import Channel, Guild
from spellbot.services import AwardsService, NewAward
from tests.fixtures import Factories
@pytest.mark.asyncio
class TestServiceAwards:
async def test_give_awards_first_award(
self,
guild: Guild,
channel: Channel,
factories... |
3297161 | from .bert_ft_compare import *
from .bert_ft_compare_multi import *
from .agent import *
from .dual_bert_compare import *
from .dual_bert_comp import *
|
3297163 | from awsimple import is_mock, S3Access
from test_awsimple import test_awsimple_str
def test_mock():
s3_access = S3Access(test_awsimple_str)
assert is_mock() == s3_access.is_mocked() # make sure that the AWSAccess instance is actually using mocking
|
3297201 | from evaluation.inception import InceptionScore
import re
import cv2
import numpy as np
import pandas as pd
import matplotlib
from sg2im.data import deprocess_batch, imagenet_deprocess
from sg2im.data.utils import decode_image
matplotlib.use('Agg')
from sg2im.meta_models import MetaGeneratorModel
import argparse, os
im... |
3297205 | import os.path as osp
from setuptools import find_packages, setup
def get_version():
# From: https://github.com/facebookresearch/iopath/blob/master/setup.py
# Author: Facebook Research
init_py_path = osp.join(
osp.abspath(osp.dirname(__file__)), "graphwar", "version.py"
)
init_... |
3297238 | from __future__ import absolute_import, print_function, division
import os
import unittest
import sys
from numpy.testing.nosetester import NoseTester
# This class contains code adapted from NumPy,
# numpy/testing/nosetester.py,
# Copyright (c) 2005-2011, NumPy Developers
class TheanoNoseTester(NoseTester):
"""
... |
3297306 | import argparse
import time
import torch.nn as nn
import sys
import numpy as np
from attacks.image_save_runner import ImageSaveAttackRunner
from attacks.selective_universal import SelectiveUniversal
from attacks.cw_inspired import CWInspired
from dataset import Dataset
from models import create_ensemble
from models.m... |
3297346 | import insightconnect_plugin_runtime
from .schema import CombineArraysInput, CombineArraysOutput, Input, Output, Component
# Custom imports below
class CombineArrays(insightconnect_plugin_runtime.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="combine_arrays",
... |
3297368 | r"""
This model calculates the scattering from fractal-like aggregates based
on the Mildner reference.
Definition
----------
The scattering intensity $I(q)$ is calculated as
.. math::
:nowrap:
\begin{align*}
I(q) &= \text{scale} \times P(q)S(q) + \text{background} \\
P(q) &= F(qR)^2 \\
F(x) &= \... |
3297376 | class Solution:
def reverseOnlyLetters(self, S: str) -> str:
a = list(S)
i, j = 0, len(S) - 1
while True:
while i < j and not a[i].isalpha():
i += 1
while i < j and not a[j].isalpha():
j -= 1
if i >= j:
break
a[i], a[j] = a[j], a[i]
i += 1
j -= 1... |
3297389 | import logging
import pytest
import time
from tests.common.dualtor.control_plane_utils import verify_tor_states
from tests.common.dualtor.data_plane_utils import send_t1_to_server_with_action, send_server_to_t1_with_action # lgtm[py/unused-import]
from tests.common.dualtor.dual_tor_uti... |
3297410 | import anndata
import gzip
import os
import pandas as pd
import scipy.io
import tarfile
def load(data_dir, **kwargs):
fn = os.path.join(data_dir, "GSE164378_RAW.tar")
adatas = []
with tarfile.open(fn) as tar:
samples = ['GSM5008737_RNA_3P', 'GSM5008738_ADT_3P']
for sample in samples:
... |
3297457 | import json
import logging
import pytest
import mappyfile
from mappyfile.parser import Parser
from mappyfile.transformer import MapfileToDict
from mappyfile.pprint import PrettyPrinter
def test_includes():
p = Parser()
ast = p.parse_file('./tests/samples/include1.map')
m = MapfileToDict()
d = (m.tra... |
3297476 | class BaseClass(object):
def __init__(self):
self._spam = 5
@property
def spam(self):
"""BaseClass.getter"""
return self._spam
@spam.setter
def spam(self, value):
self._spam = value
@spam.deleter
def spam(self):
del self._spam
class PropertyDocBase... |
3297506 | import functools
from typing import Optional, Tuple
IMAGE_UNAVAILABLE_SVG = """
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="0 0 200 200" width="200pt" height="200pt"><defs><clipPath id="_clipPath_eSdCSpw1sB1xWp7flmMoZ0WjTPwPpzQh"><rect width="20... |
3297529 | from abc import ABC, abstractmethod
from enum import Enum, auto
from resotolib.core.ca import TLSData
from resotolib.graph import Graph
from resotolib.core import resotocore
from resotolib.core.actions import CoreActions
from resotolib.args import ArgumentParser
from resotolib.config import Config
from resotolib.logger... |
3297530 | from qtpy.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QPushButton, QTextEdit, QFileDialog, QRadioButton
from qtpy.QtGui import QIcon
from ryven.main.nodes_package import NodesPackage
from ryven.main.utils import abs_path_from_package_dir, abs_path_from_ryven_dir
from ryven.gui.styling.window_theme import apply... |
3297549 | import os
import django
import pytest
from django.contrib.auth import get_user_model
def pytest_configure():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
django.setup()
admin_username = 'real_test_admin'
admin_pass = '<PASSWORD>'
user_username = 'real_test_user'
user_email = '<EMAIL>'
user_... |
3297594 | import json
import logging
import sys
from datetime import datetime
import boto3
from job_requester import JobRequester
from job_requester import Message
"""
How tests are executed:
- Put tickets on the request queue, in-progress pool and dead letter queue; create Message objects (request identifiers)
that corresp... |
3297650 | from network import *
import tensorflow as tf
def generate(input_shape, num_labels):
return Network("TopCoderShallow",
input_shape,
[num_labels],
[ConvolutionLayer(7, 7, 1, 1, 32),
PoolingLayer(3, 3, 2, 2),
Convolutio... |
3297665 | import asyncio
from contextlib import asynccontextmanager
from typing import Any
from typing import Callable
from typing import Optional
from typing import Union
import attr
from yui.api import SlackAPI
from yui.bot import Bot
from yui.cache import Cache
from yui.config import Config
from yui.config import DEFAULT
fr... |
3297674 | from runners.python import Submission
class BadouralixSubmission(Submission):
def run(self, s):
# :param s: input in string format
# :return: solution flag
step_size = int(s)
max_iter = 2017
buffer = [0]
current_position = 0
for i in range(1, max_iter + 1):
current_position += step_size
current_... |
3297678 | from typing import List, Optional
from bsmetadata.preprocessing_tools.html_parser.filters_and_cleaners import TextAndMetadataCleaner
from bsmetadata.preprocessing_tools.html_parser.objects import TagToRemoveWithContent
def get_clean_text_and_metadata(
html_str,
tags_to_remove_with_content: Optional[List[TagT... |
3297696 | import pandas as pd
import numpy as np
import ast
import sys
fdata_template = '../../data/fma_metadata/{}'
modeldata_template = '../../in/metadata/{}'
graphs_template = '../../out/graphs/{}'
genres_fpath = fdata_template.format('genres.csv')
tracks_fpath = fdata_template.format('tracks.csv')
class DataSize:
"""... |
3297704 | import unittest
from vr900connector.model import HotWater, HeatingMode
class HotWaterTest(unittest.TestCase):
def test_get_active_mode_on(self):
hot_water = HotWater('id', 'Test', None, 5.0, 7.0, HeatingMode.ON)
active_mode = hot_water.active_mode
self.assertEqual(HeatingMode.ON, activ... |
3297725 | import uvicore
from app1.models.contact import Contact
from uvicore.auth.models.user import User
from uvicore.auth.models.group import Group
from uvicore.auth.models.role import Role
from uvicore.support.dumper import dump, dd
@uvicore.seeder()
async def seed():
uvicore.log.item('Seeding table users')
# Get ... |
3297770 | from collections import namedtuple
from jinja2 import Environment
from jinja2 import FileSystemLoader
from psycopg2.extras import RealDictCursor
from tilequeue.query import DBConnectionPool
from tilequeue.transform import calculate_padded_bounds
import sys
TemplateSpec = namedtuple('TemplateSpec', 'template start_zoo... |
3297799 | from uuid import uuid4
from changes.config import db
from changes.models.author import Author
from changes.testutils import APITestCase
class AuthorBuildListTest(APITestCase):
def test_simple(self):
fake_author_id = uuid4()
project = self.create_project()
self.create_build(project)
... |
3297837 | from django import forms
from django.utils.translation import ugettext_lazy as _
from userena.contrib.umessages.fields import CommaSeparatedUserField
from userena.contrib.umessages.models import Message, MessageRecipient
import datetime
class ComposeForm(forms.Form):
to = CommaSeparatedUserField(label=_("To"))
... |
3297845 | from crypto.constants import TRANSACTION_IPFS, TRANSACTION_TYPE_GROUP
from crypto.transactions.builder.base import BaseTransactionBuilder
class IPFS(BaseTransactionBuilder):
transaction_type = TRANSACTION_IPFS
def __init__(self, ipfs_id, fee=None):
"""Create an ipfs transaction
Args:
... |
3297850 | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class ourwindow2(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Deep Docking")
Gtk.Window.set_default_size(self, 400,325)
Gtk.Window.set_position(self, Gtk.WindowPosition.CENTER)
#o... |
3297868 | from elasticsearch import Elasticsearch
import os
import zipfile
import shutil
import urllib.request
import logging
import lzma
import json
import tarfile
import hashlib
logger = logging.getLogger(__name__)
# index settings with analyzer to automatically remove stop words
index_settings = {
"settings": {
... |
3297870 | import gym
import unittest
from datetime import datetime
from gym.envs.registration import register
register(
id='simglucose-adult1-v0',
entry_point='simglucose.envs:T1DSimEnv',
kwargs={'patient_name': 'adult#001'}
)
class TestSeed(unittest.TestCase):
def test_changing_seed_generates_different_result... |
3297871 | def doubleChar(str):
new_str = ''
for i in str:
new_str += i*2
return new_str
res = doubleChar()
print(res)
|
3297878 | class SSLConfig(object):
def __init__(self):
self.selfCertPath = None
self.selfCertPwd = None
self.trustCAPath = None
self.trustCAPwd = None
def getSelfCertPath(self):
return self.selfCertPath
def setSelfCertPath(self, selfCertPath):
self.selfCertPath = sel... |
3297880 | from __future__ import print_function
from six import iteritems
import netCDF4
import os
import uuid
from .. import utils
import numpy as np
import collections
from scipy import interpolate
from scipy.signal import decimate
class QncException(Exception):
pass
def to_str(s):
if not isinstance(s,str) and isins... |
3297892 | from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi_asyncalchemy.models import *
async def get_biggest_cities(session: AsyncSession) -> list[City]:
result = await session.execute(select(City).order_by(City.population.desc()).limit(20))
return result.scalars().all()
def... |
3297893 | import machine
try:
from display import *
display.clear()
except:
pass
try:
import music
music.stop(6)
except:
pass
try:
import neopixel
rgb = neopixel.NeoPixel(machine.Pin(17), 3, timing = True)
rgb[0] = (0, 0, 0)
rgb[1] = (0, 0, 0)
... |
3297903 | import lief
#binary = lief.parse("/usr/bin/ls")
#library = lief.parse("/usr/lib/libc.so.6")
import sys
bin_name = sys.argv[1]
#binary = lief.parse("a.out")
binary = lief.parse(bin_name)
print(binary.imported_functions)
#print(library.exported_functions)
hooksfile = ""
for sym in binary.imported_symbols:
asse... |
3297916 | import codecs
import multiprocessing
import os
from collections import Counter
from typing import List, Optional
import numpy as np
from nltk.tokenize import word_tokenize
from tqdm import tqdm
from utils.data_util import (
load_json,
load_lines,
load_pickle,
save_pickle,
time_to_index,
)
PAD, UN... |
3297945 | import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import names
def word_feats(words):
return dict([(word, True) for word in words])
positive_vocab = [ 'awesome', 'outstanding', 'fantastic', 'terrific', 'good', 'nice', 'great', ':)' ]
negative_vocab = [ 'bad', 'terrible',... |
3297964 | from jsonpointer import resolve_pointer
def find_pipeline(path):
from . import pipelines
if len(path) < 2:
raise ValueError("Path doesn't have enough parts.")
obj_type = path.pop(0)
if obj_type != 'dataSources':
raise ValueError("Path doesn't start with 'dataSources'.")
pipeline... |
3297976 | import os
import inference.model_utils as model_utils
import inference.utils as utils
from jsonschema import validate
from inference.model import ModelConfig
from io import BytesIO
import mxnet as mx
import asyncio
import json
from PIL import Image, ImageDraw, ImageFont
from inference.base_inference_engine ... |
3298033 | class Solution:
def canPartitionKSubsets(self, nums, k):
def dfs(i, sums):
if i == n:
return True
for j in range(k):
if sums[j] + nums[i] <= target:
sums[j] += nums[i]
if dfs(i + 1, sums):
... |
3298045 | description = 'setup for the LAUE html status monitor'
group = 'special'
_expcolumn = Column(
Block(
'Experiment',
[
BlockRow(
Field(name = 'Proposal', key = 'exp/proposal', width = 7),
Field(
name = 'Title',
key = ... |
3298056 | class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def __repr__(self):
if not self:
return "{}()".format(self.__class__.__name__)
return "{}({})".format(self.__class__.__name__, self.value)
class LinkedList:
def ... |
3298127 | from __future__ import absolute_import, division, print_function
import os
import time
import boost_adaptbx.boost.optional # import dependency
import boost_adaptbx.boost.python as bp
bp.import_ext("scitbx_random_ext")
import scitbx_random_ext
def get_random_seed():
try:
result = (os.getpid() * (2**16)) \
... |
3298128 | import numpy as np
import os
import cv2
import scipy
import random
SMILE_FOLDER = './data/smile_data/'
GENDER_FOLDER = './data/gender_data_101/'
AGE_FOLDER = './data/age_data_101/'
NUM_SMILE_IMAGE = 4000
SMILE_SIZE = 48
EMOTION_SIZE = 48
def getSmileImage():
print('Load smile image...................')
X1 = ... |
3298130 | from collections import namedtuple
from veros.variables import Variable
from veros.settings import Setting
VerosPlugin = namedtuple(
"VerosPlugin",
[
"name",
"module",
"setup_entrypoint",
"run_entrypoint",
"settings",
"variables",
"diagnostics",
],
)... |
3298139 | from gi.repository import Gtk
from gaphas.view import GtkView
class Zoom:
def __init__(self, matrix):
self.matrix = matrix
self.x0 = 0
self.y0 = 0
self.sx = 1.0
self.sy = 1.0
def begin(self, x0, y0):
self.x0 = x0
self.y0 = y0
self.sx = self.mat... |
3298141 | import os
from selenium import webdriver
class Request:
def __init__(self, base_url):
self._driver_path = os.path.join(os.curdir, 'phantomjs/bin/phantomjs')
self._base_url = base_url
self._driver = webdriver.PhantomJS(self._driver_path)
def fetch_data(self, forecast, area):
ur... |
3298143 | from functools import reduce
import torch
import torch.nn as nn
from torchvision.models import resnext50_32x4d, resnext101_32x8d
class LambdaBase(nn.Sequential):
def __init__(self, fn, *args):
super(LambdaBase, self).__init__(*args)
self.lambda_func = fn
def forward_prepare(self, input):
... |
3298185 | graph = dict()
graph['A'] = ['B', 'S']
graph['B'] = ['A']
graph['S'] = ['A','G','C']
graph['D'] = ['C']
graph['G'] = ['S','F','H']
graph['H'] = ['G','E']
graph['E'] = ['C','H']
graph['F'] = ['C','G']
graph['C'] = ['D','S','E','F']
def depth_first_search(graph, root):
visited_vertices = list() ... |
3298206 | from tkinter import *
from src.exceptions import AlreadySelectedError
from src.base_game import Board
class GUI:
def __init__(self, against_cpu=False):
self.root = Tk()
self.root.title("tic-tac-toe")
self.against_cpu = against_cpu
self.init_board()
self.init_elements()
... |
3298210 | from datetime import datetime
from typing import Any, Dict, List, Optional, Set, Union
from iso8601 import iso8601
from paralleldomain.decoding.common import DecoderSettings
from paralleldomain.decoding.decoder import DatasetDecoder, SceneDecoder
from paralleldomain.decoding.frame_decoder import FrameDecoder
from par... |
3298233 | from flask import Flask, request, jsonify
from py_imessage import imessage
app = Flask(__name__)
@app.route('/api/send', methods=['GET', 'POST'])
def send_message():
# import pdb; pdb.set_trace();
phone = request.form.get("phone")
text = request.form.get("text")
if text:
message = text
el... |
3298237 | import numpy as np
import torch
import torch.nn as nn
import progressbar
import time
import copy
def initialization(init_method, W, is_tensor=True):
""" Initializes the provided tensor.
Parameters:
-----------
* init_method : str (default = 'glorot_uniform')
Initialization method to use.... |
3298260 | import os
from locust import HttpUser, TaskSet, task, between, constant
import image_data
class APIUser(HttpUser):
wait_time = between(1, 10)
@task(int(os.getenv("GET_HEALTH_RATIO", 0)))
def get_health(self):
self.client.get(url="/health", verify=False)
@task(int(os.getenv("GET_HEALTH_ALL_RA... |
3298300 | import torch
import torch.nn as nn
import random
import numpy as np
import torchvision
import imp
import time
from models.pretrained_vgg import customCNN2
from models.pretrained_vgg import customCNN
from models.cnn import CNN
import models.soft_attention as soft_attention
import torch.nn.functional as f
cla... |
3298399 | from django.db.models import Count, Q
import rest_framework.serializers as serializers
from discussion.models import Endorsement, Flag, Vote
from researchhub.serializers import DynamicModelFieldSerializer
from utils.http import get_user_from_request
from utils.sentry import log_error
class EndorsementSerializer(seri... |
3298430 | import itertools
import datetime
import json
import connexion.problem
from services.bitshares_websocket_client import client as bitshares_ws_client
from services.bitshares_elasticsearch_client import client as bitshares_es_client
from services.cache import cache
import es_wrapper
import config
def _bad_request(detail)... |
3298469 | try:
#python3
import tkinter
except ImportError:
#python2
import Tkinter as tkinter
import time
import datetime
import math
import os
import linecache
#----- Variablen
Datum = datetime.datetime.now().strftime("%Y-%m-%d")
#Datei = "/tmp/"+str(Datum)+"_Messdaten.csv"
Datei = "/tmp/Messdaten.csv"
Bild1 = ... |
3298488 | from __future__ import division
import argparse
import numpy as np
from itertools import izip
#from utils._alpha_variance import run_alpha_variance
#from utils._jackknife_variance import run_jackknife_variance
from nested_sampling import compute_heat_capacity, get_energies
def main():
parser = argparse.Argumen... |
3298492 | import torch
from inference_mnist_model import Net
def main():
pytorch_model = Net()
pytorch_model.load_state_dict(torch.load('pytorch_model.pt'))
pytorch_model.eval()
dummy_input = torch.zeros(280 * 280 * 4)
torch.onnx.export(pytorch_model, dummy_input, 'onnx_model.onnx', verbose=True)
if __name__ == '_... |
3298505 | import typing as tp
import cocos.numerics as cn
import numba
import numpy as np
def _select_vectorized_log_fun_for_base(base: float, gpu: bool = False) -> tp.Callable:
if base == 2:
if gpu:
return cn.log2
else:
return np.log2
if base == np.e:
if gpu:
... |
3298533 | from __future__ import absolute_import, print_function, division
import os
import glob
import numpy as np
import six
class NfS(object):
"""`NfS <http://ci2cv.net/nfs/index.html>`_ Dataset.
Publication:
``Need for Speed: A Benchmark for Higher Frame Rate Object Tracking``,
<NAME>, <NAME>, <NA... |
3298563 | from copy import deepcopy
import numpy as np
import torch
from torch import nn
from transformers import BertModel, BertTokenizer, BertConfig
class BERT(nn.Module):
def __init__(self, config):
super(BERT, self).__init__()
self.config = config
self.bert_config = BertConfig.from_pretrained('be... |
3298565 | import os
import pickle
import numpy as np
import random
import cv2
from keras.preprocessing import image
from dataset_script.events_to_img import padzero
random.seed(99999)
def load_data(main_path, pkl_file):
try:
print 'Loading pickle file ....', os.path.join(main_path, pkl_file)
X, Y = pickle.... |
3298601 | from typing import Optional
from pathlib import Path
from spacy.cli.evaluate import evaluate
from spacy.cli._util import Arg, Opt, import_code
import typer
def evaluate_cli(
# fmt: off
model: str = Arg(..., help="Model name or path"),
data_path: Path = Arg(..., help="Location of binary evaluation data in ... |
3298610 | class Solution:
def myAtoi(self, str: str) -> int:
str = str.strip()
negative = False
if str and str[0] == '-':
negative = True
if str and (str[0 ] == '+' or str[0] == '-'):
str = str[1:]
if not str:
return 0
digits = {i fo... |
3298633 | import os, json, sys
import os.path as osp
import argparse
import warnings
from tqdm import tqdm
import numpy
import time
import numpy as np
from skimage.io import imsave
from skimage.util import img_as_ubyte
from skimage.transform import resize
import torch
from utils.model_saving_loading import str2bool
from models.... |
3298712 | from pycromanager import Acquisition, multi_d_acquisition_events
import numpy as np
def hook_fn(event):
return event
with Acquisition(
directory="/Users/henrypinkard/tmp",
name="acquisition_name",
post_camera_hook_fn=hook_fn,
) as acq:
acq.acquire(multi_d_acquisition_events(10))
|
3298747 | def suma(a,b):
return a + b
def resta(a,b):
return a - b
def multiplica(a,b):
return a * b
def divida(a,b):
return a/b |
3298774 | import numpy as np
from sklearn import cluster
def gaussian_sp(delta_t, miu, sigma=65):
x, u, sig = delta_t, miu, sigma
p = np.exp(-(x-u)**2 / (2*sig**2))
p = max(0.0001, p)
return p
def flat_gaussian_sp(delta_t, miu, sigma=30):
if delta_t <= 0:
return 0.0001
else:
x, u, sig =... |
3298797 | from ztag.annotation import *
class MRV1Server(Annotation):
protocol = protocols.HTTP
subprotocol = protocols.HTTP.GET
port = None
def process(self, obj, meta):
s = obj["headers"]["server"]
if s.startswith("Mrvl"):
meta.local_metadata.product = "Mrvl"
v = s.sp... |
3298836 | import numpy as np
from UCTB.model import ARIMA
from UCTB.dataset import NodeTrafficLoader
from UCTB.evaluation import metric
data_loader = NodeTrafficLoader(dataset='ChargeStation', city='Beijing')
prediction = []
for i in range(data_loader.station_number):
print('*********************************... |
3298870 | import time
from os import path
from os.path import expanduser
from fabric.api import env, put, run, sudo, task
from fabric.context_managers import prefix
from fabric.contrib.project import rsync_project
from fabric.operations import local, run
with open(expanduser('~') + '/ansible-playbooks/env/bvspca.py', 'r') as c... |
3298886 | import numpy as np
from tqdm import tqdm
import pandas as pd
import torch
import sys
sys.path.append('./util_tools')
from acc_utils import melodySplit, chordSplit, computeTIV, chord_shift, cosine, cosine_rhy, accomapnimentGeneration
sys.path.append('./models')
from model import DisentangleVAE
import os
os.environ[... |
3298903 | from .SpecificCoTAbstract import SpecificCoTAbstract
class SendDropPoint(SpecificCoTAbstract):
def __init__(self):
self.define_variables()
self.setType("DropPoint") |
3298919 | import time
import os
import argparse
import cv2
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim import lr_scheduler
from torchvision import datasets, transforms, utils
from tensorboardX import SummaryWriter
from utils import *
from model import *
from P... |
3298920 | import pkg_resources
import yaml
import datetime
import os
from track import models
from track.data import FIELD_MAPPING
from babel.dates import format_date
# For use in templates.
def register(app):
###
# Context processors and filters.
def scan_date():
latest = models.Report.latest()
if... |
3298942 | import matplotlib.pyplot as plt
import numpy as np
def plot_image(image, shape=[256, 256], cmap="Greys_r"):
plt.imshow(image.reshape(shape), cmap=cmap, interpolation="nearest")
plt.axis("off")
plt.show()
def movingaverage(values,window):
weights = np.repeat(1.0,window)/window
smas = np.convolve(values,... |
3299023 | from .converter import BaseConverter
from .exceptions import AnnotationConversionError, MarshmallowAnnotationError
from .registry import TypeRegistry, field_factory, registry, scheme_factory
from .scheme import AnnotationSchema, AnnotationSchemaMeta
__version__ = "2.4.1"
__author__ = "<NAME>"
__license__ = "MIT"
|
3299043 | import sys
if "../" not in sys.path:
sys.path.append("../")
from envs.continuousDoubleAuction_env import continuousDoubleAuctionEnv
def test_random():
num_of_traders = 4
init_cash = 1000000
tick_size = 1
tape_display_length = 10
max_step = 10000
e = continuousDoubleAuctionEnv(num_of_trade... |
3299085 | import os
import sys
import json
import codecs
import shutil
import time
from datetime import datetime, date
import multiprocessing
import threading
if getattr(sys, 'frozen', False):
if sys.platform == "darwin":
rootdir = os.getcwd()
else:
rootdir = os.path.dirname(sys.executable)
else:
roo... |
3299113 | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=True, backtrace=False, diagnose=True)
code = """
if True:
a = 5
b = 7 *
"""
try:
exec(code)
except SyntaxError:
logger.exception("")
|
3299120 | from django.urls import path
from .views import TestView
urlpatterns = [
path('', TestView.as_view()),
]
|
3299158 | import cursive_re
from cursive_re import *
domain_name = one_or_more(any_of(in_range("a", "z") + in_range("0", "9") + text("-")))
domain = domain_name + zero_or_more(text(".") + domain_name)
path_segment = zero_or_more(none_of("/"))
path = zero_or_more(text("/") + path_segment)
url = (
group(one_or_more(any_of(in_... |
3299169 | import re
from .notes_processor import NotesProcessor
from itertools import groupby
from operator import itemgetter
from utils import cidict, tag_re, replace_section
import logging
log = logging.getLogger(__name__)
class Backlinker(NotesProcessor):
def __init__(self, **options):
self.options = {
'backlinks_headi... |
3299209 | import csv #from s2q1.py
# function from s2q2.py
def open_with_csv(filename, d='\t'):
data = []
with open(filename, encoding='utf-8') as tsvin:
tie_reader = csv.reader(tsvin, delimiter=d)
for row in tie_reader:
data.append(row)
return data
def filter_col_by_string(the_data, field, filter_condition... |
3299224 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
from DQM.L1TMonitorClient.L1TOccupancyTestParameters_cff import *
l1tOccupancyClient = DQMEDHarvester("L1TOccupancyClient",
verbose = cms.bool(False),
testParams = cms.VPSet(
#----------------------------------... |
3299230 | from flask import Flask,render_template,request,send_file,send_from_directory
import numpy as np
import pandas as pd
import sklearn.metrics as m
from keras.utils.np_utils import to_categorical
import os
import cv2
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers... |
3299231 | import asyncio
import json
import re
import time
import datetime
from aioredis import ReplyError
from discord import NotFound
from tortoise.query_utils import Q
from Bot import GearBot
from Util import Pages, Utils, Translator, GearbotLogging, Emoji, ReactionManager
from database.DatabaseConnector import Infraction
... |
3299242 | from math import floor
from cached_property import cached_property
from devito import TimeFunction, silencio
from examples.seismic.acoustic import GradientOperator
from examples.checkpointing.checkpoint import DevitoCheckpoint, CheckpointOperator
from examples.seismic.acoustic.gradient_example import GradientExample
f... |
3299243 | import numpy as np
from dagster import Out, op
from hacker_news.ops.user_story_matrix import IndexedCooMatrix
from pandas import DataFrame
from scipy.sparse import coo_matrix, csc_matrix, csr_matrix
from sklearn.decomposition import TruncatedSVD
@op(
out=Out(
io_manager_key="warehouse_io_manager",
... |
3299270 | import numpy as np
import torch
import torch.nn as nn
from models.modules import build_mlp, SoftAttention, PositionalEncoding, create_mask, proj_masking
class Regretful(nn.Module):
"""
The model for the regretful agent (CVPR 2019)
The Regretful Agent: Heuristic-Aided Navigation through Progress Estimat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.