id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11496117 | import random
import sys
from nekoyume.battle.simul import DummyBattle
def main():
seed = 1
if len(sys.argv) >= 2:
seed = int(sys.argv[1])
simulator = DummyBattle(random.Random(seed))
simulator.logger.print = True
simulator.simulate()
if __name__ == '__main__':
main()
|
11496141 | import os
from _pytest.capture import CaptureFixture
from kaldi_helpers.input_scripts.clean_json import *
from kaldi_helpers.script_utilities import write_data_to_json_file
EXAMPLE_JSON_DATA = [
{"transcript": "Comment t'appelles tu?"},
{"transcript": "Je m'appelle François."},
{"transcript": "Est-ce tu a ... |
11496151 | import logging
from typing import TypeVar
from jmetal.lab.visualization import InteractivePlot
LOGGER = logging.getLogger('Sequoya')
S = TypeVar('S')
class MSAPlot(InteractivePlot):
def export_to_html(self, filename: str) -> None:
html_string = '''
<!DOCTYPE html>
<html lang="en">
... |
11496183 | from typing import Generator
from contextlib import contextmanager
from subprocess import CompletedProcess
from pathlib import Path
from tempfile import TemporaryDirectory
from . import run
class Git:
def __init__(self, root: str = '.') -> None:
self._root = root
self.path = Path(root)
def _run(self, *ar... |
11496195 | import json
import os
import pickle
def load_tasks(dir_path, task_num=None):
tasks, filenames = [], [os.path.join(dir_path, f) for f in os.listdir(dir_path)]
for filename in filenames:
if filename.endswith(".json"):
with open(filename, encoding="utf-8") as f:
dt = f.read().... |
11496222 | from create_grids import create_grids
from create_ics import create_ics
from run_model import run_model
from stress_divergence_scaling import stress_divergence_scaling
from error_analysis_stress_divergence import error_analysis_stress_divergence
create_grids()
create_ics()
run_model()
stress_divergence_scaling()
e... |
11496230 | import asyncio
from datetime import datetime
from typing import Optional, Union, Any
from aiohttp import ClientSession
from .questions import QuestionsCategory, parse_questions_category
from .requester import Requester
class Questionnaire:
def __init__(self, categories: list[QuestionsCategory]):
self._c... |
11496294 | from __future__ import division
import numpy as np
import scipy.spatial.distance as ssd
import settings
import tps
import solver
import lfd.registration
if lfd.registration._has_cuda:
from lfd.tpsopt.batchtps import batch_tps_rpm_bij, GPUContext, TgtContext
class Registration(object):
def __init__(self, demo,... |
11496299 | from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from oscar_docdata.dashboard.app import application as docdata_dashboard_app
from oscar.app import a... |
11496334 | from PySide import QtGui
f=QtGui.QApplication.font()
f.pointSize()
f.setPointSize(10) # replace 10 with whatever size you want for 2k to 4k monitors
f=QtGui.QApplication.setFont(f) |
11496373 | import os
from twill.utils import gather_filenames
def test_gather_dir():
this_dir = os.path.dirname(__file__)
test_gather = os.path.join(this_dir, 'test_gather')
cwd = os.getcwd()
os.chdir(test_gather)
try:
files = gather_filenames(('.',))
if os.sep != '/':
files = [... |
11496404 | import unittest, test.support
from test.support.script_helper import assert_python_ok, assert_python_failure
import sys, io, os
import struct
import subprocess
import textwrap
import warnings
import operator
import codecs
import gc
import sysconfig
import platform
import locale
numruns = 0
try:
import threading
exc... |
11496447 | from binaryninja_cortex.platforms import MCU
class Chip(MCU):
NAME="VF6XX"
IRQ=MCU.IRQ+ [
"NVIC_CPU2CPU_INT0_IRQ",
"NVIC_CPU2CPU_INT1_IRQ",
"NVIC_CPU2CPU_INT2_IRQ",
"NVIC_CPU2CPU_INT3_IRQ",
"NVIC_DIRECTED0_SEMA4_IRQ",
"NVIC_DIRECTED1_MCM_IRQ",
"NVIC_DIRE... |
11496452 | from abc import ABC
from typing import Tuple, Union
import numpy as np
from slick_dnn.autograd import Autograd, Context
class Reshape(Autograd):
def __init__(self, *new_shape):
self.new_shape = new_shape
def forward(self, ctx, tensor):
ctx.save_for_back(tensor.shape)
return np.resha... |
11496472 | from django.db import models
import hashlib, datetime
class Zip(models.Model):
filename = models.CharField(max_length=20, primary_key=True)
password = models.CharField(max_length=40)
date_created = models.DateTimeField(auto_now_add=True)
def encrypt(self, text):
h = hashlib.sha1()
h.u... |
11496517 | from uuid import UUID, uuid4
import ujson as json
from flask import Flask, jsonify
from flask.json import JSONEncoder
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, UUID):
return str(obj)
return JSONEncoder.default(self, obj)
def encode(self, o):... |
11496542 | import moviepy.editor as mp
clip = mp.AudioFileClip("insert_path_to_webm_file").subclip()
clip.write_audiofile("insert_path_to_save_mp3_file")
clip.close()
|
11496618 | try:
# For distributions
from ._version_lock import version # type: ignore # pylint: disable=unused-import
except ImportError:
# For development trees
from os import environ
from os.path import dirname, join
try:
from dulwich.porcelain import describe # type: ignore
except ImportError:
from subprocess imp... |
11496700 | from keras import optimizers
DEFAULT_OPTIMIZER = 'adam'
def get_optimizer(config):
"""Return optimizer specified by configuration."""
config = vars(config)
name = config.get('optimizer', DEFAULT_OPTIMIZER)
optimizer = optimizers.get(name) # Default parameters
lr = config.get('learning_rate')
... |
11496733 | class Solution:
def halvesAreAlike(self, s: str) -> bool:
def isVowel(char):
return char in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
def getNumberOfVowels(s):
count = 0
for char in s:
count += (1 if isVowel(char) else 0)
retur... |
11496765 | from packaging.version import parse
from qtpy import QT_VERSION
from qtpy.QtCore import Qt, Signal
from qtpy.QtWidgets import QComboBox, QCompleter
class SearchComboBox(QComboBox):
"""
ComboCox with completer for fast search in multiple options
"""
if parse(QT_VERSION) < parse("5.14.0"):
text... |
11496778 | from fabric.colors import green as _green, yellow as _yellow, red as _red
from settings import cloud_connections, DEFAULT_PROVIDER
from ghost_log import log
from ghost_tools import get_aws_connection_data, GCallException, boolify
from ghost_tools import b64decode_utf8, get_ghost_env_variables
from ghost_tools import ... |
11496811 | from graphviz import Digraph
import os
def create_graph(filepath: str, nodes_data: dict, show: bool, legend=False):
"""
Visualizes the energy system as graph.
Creates, using the library Graphviz, a graph containing all
components and connections from "nodes_data" and returns this as
... |
11496830 | import random
class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
while True:
v1, v2 = random.sample(A, 2)
if v1 == v2:
return v1
|
11496838 | from setuptools import find_packages, setup
with open('README.md', 'r') as readme:
long_description = readme.read()
setup(
name='stacksort',
version='0.1.0',
author='<NAME> <<EMAIL>',
long_description=long_description,
long_description_content_type='text/markdown',
packages=find_packages()... |
11496850 | from test import multibytecodec_support
import unittest
class TestCP949Map(multibytecodec_support.TestBase_Mapping, unittest.TestCase):
encoding = 'cp949'
mapfileurl = 'http://www.pythontest.net/unicode/CP949.TXT'
class TestEUCKRMap(multibytecodec_support.TestBase_Mapping, unittest.TestCase):
encoding =... |
11496853 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
requirements = {
"package": [
"PyYAML>=5",
"six",
],
"test": [
"nose",
"mock",
"pytest",
"pytest-mock",
"pytest-pudb",
... |
11496871 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import xml.etree.ElementTree as ET
import numpy as np
import re
import math
FILE_PATH = os.path.dirname(os.path.realpath(__file__))
DATA_PATH = os.path.join(FILE_PATH, "../data/")
LABEL_DATA_PATH = ... |
11496874 | from channels.base import Channel, ChannelsError, ChannelAttachment, ChannelBoard, ChannelThread
from channels.base import ChannelPost, SettingDefinition, Client, PostingError
import requests
import re
import urllib
class FourChanClient(Client):
def __init__(self, channel_name, client_id):
super().__init... |
11496931 | import FWCore.ParameterSet.Config as cms
process = cms.Process("DBGeometryTest")
#process.load("DetectorDescription.OfflineDBLoader.test.cmsIdealGeometryForWrite_cfi")
process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1)
... |
11496935 | fi=open('GSE109125_Gene_count_table.csv.uniq.rpk')
fo=open('GSE109125_Gene_count_table.csv.uniq.rpk.pure','w')
#fi.readline()
header=fi.readline().rstrip().split('\t')
h=[]
for one in header:
h.append(one.split('#')[0])
header=h
G={}
i=1
while i<len(header):
if header[i] in G:
G[header[i]].append(i)
... |
11496956 | name ="Tom"
age = 16
print("Hello Myname is "+name+" and I am "+str(age))
print("Hello Myname is {} and I am {}".format(name,age))
print("Hello Myname is {0} and My age is {1}".format(name,age))
# 最常用 fstring
print(f"Hello Myname is {name} and I am {age+1}") |
11496959 | import sublime
import re
import os
ALIAS_SETTING = "alias"
DEFAULT_INITIAL_SETTING = "default_initial"
AUTOFILL_RENAME = "autofill_path_the_existing"
USE_CURSOR_TEXT_SETTING = "use_cursor_text"
SHOW_FILES_SETTING = "show_files"
SHOW_PATH_SETTING = "show_path"
DEFAULT_ROOT_SETTING = "default_root"
DEFAULT_PATH_SETTING ... |
11497000 | from typing import List
import lab as B
from lab import dispatch
from lab.util import abstract
from plum import Union
@dispatch
@abstract()
def take_along_axis(a: B.Numeric, index: B.Numeric, axis: int = 0):
"""
Gathers elements of `a` along `axis` at `index` locations.
"""
@dispatch
@abstract()
def fr... |
11497032 | from __future__ import with_statement # this is to work with python2.5
from pyps import workspace
from terapyps import workspace as teraw, Maker
workspace.delete("addcst")
with teraw("addcst.c", name="addcst", deleteOnClose=False, recoverInclude=False) as w:
for f in w.fun:
f.terapix_code_generation(debug=T... |
11497084 | import numpy as np
import torch
from PIL import Image, ImageEnhance
import pickle
import random
import os
import torchvision.transforms as transforms
import json
def augment_image(image):
if (random.random() < 0.5):
image = image.transpose(Image.FLIP_LEFT_RIGHT)
enhancer = ImageEnhance.Brightness(imag... |
11497088 | import ik
import unittest
class TestVec3(unittest.TestCase):
def test_default_construct(self):
v = ik.Vec3()
self.assertEqual(v.x, 0.0)
self.assertEqual(v.y, 0.0)
self.assertEqual(v.z, 0.0)
def test_construct_with_two_values(self):
v = ik.Vec3(1, 2)
self.assertE... |
11497144 | import os
from django.utils.translation import ugettext_lazy as _
import environ
import rollbar
# Initialize environ
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
env = environ.Env(DEBUG=(bool, False),)
env_file_path = os.path.join(BASE_DIR, '.env')
environ.Env.read_env(env_file_path) # rea... |
11497225 | from dart.client.python.dart_client import Dart
from dart.model.dataset import Column, DatasetData, Dataset, DataFormat, FileFormat, RowFormat, DataType, Compression, \
LoadType
if __name__ == '__main__':
dart = Dart('localhost', 5000)
assert isinstance(dart, Dart)
dataset = dart.save_dataset(Dataset(... |
11497230 | import argparse
import csv
import re
# import modules needed for logging
import logging
import os
import random
logger = logging.getLogger(__name__) # module logger
def parse_arguments():
"""
Function to parse command line arguements
from the user
Returns
-------
opts : dict
command... |
11497259 | import numpy as np
import concurrent.futures
from operator import itemgetter
from sim_exp import arrival_rate_upperbound
from mapper import *
from policygrad_learning import *
from q_learning import *
# ############################################ Scher ########################################### #
class Scher(obje... |
11497272 | import logging
from itertools import chain
from contextlib import ExitStack
from typing import List, Optional, Type
from mangum.protocols import HTTPCycle, LifespanCycle
from mangum.handlers import ALB, HTTPGateway, APIGateway, LambdaAtEdge
from mangum.exceptions import ConfigurationError
from mangum.types import (
... |
11497281 | import unittest
from flow_py_sdk.cadence import Address, String, Int
from flow_py_sdk.tx import Tx, TxSignature, ProposalKey
class TestTx(unittest.TestCase):
def test_transaction_rlp_encoding_is_consistent(self):
cases = [
{
"name": "Complete transaction",
"tx"... |
11497297 | import re
from decimal import Decimal
from urllib.parse import urlencode
import aiohttp
from ...box import box
from ...command import argument
from ...event import Message
from ...utils import json
QUERY_RE = re.compile(
r'^(\d+(?:\.\d+)?)\s*(\S+)(?:\s+(?:to|->|=)\s+(\S+))?$', re.IGNORECASE
)
SHORTCUT_TABLE: dic... |
11497303 | from setuptools import setup, find_packages
import iarm
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
long_description.replace('\r', '') # PyPi doesnt like '\r\n', only '\n'
except:
long_description = open('README.md').read()
setup(name=iarm.__title__,
version=iar... |
11497319 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
from collections import namedtuple
from typing import Optional
import numpy as np
import pyspiel
from open_spiel.python.algorithms import get_all_states
from open_spiel.python.algorithms.best_re... |
11497332 | from bibliopixel.animation import animation
from bibliopixel.colors import COLORS
"""
This is an example Animation class which has a single field -
`color` with the default value `COLORS.green`.
You can edit this as you like, add and remove fields and
write Python code in general.
"""
class Example26(animation.Anim... |
11497401 | import numpy as np
import pylab
from scipy import sparse
import regreg.api as rr
Y = np.random.standard_normal(500); Y[100:150] += 7; Y[250:300] += 14
loss = rr.quadratic.shift(-Y, coef=0.5)
sparsity = rr.l1norm(len(Y), 1.4)
# TODO should make a module to compute typical Ds
D = sparse.csr_matrix((np.identity(500) +... |
11497410 | import uvicore
from uvicore.auth.models.role import Role
from uvicore.support.dumper import dump, dd
from uvicore.auth.models.permission import Permission
@uvicore.seeder()
async def seed():
uvicore.log.item('Seeding table roles')
# Get all permissions
perms = await Permission.query().key_by('name').get(... |
11497432 | class SomeClass:
x: int
s: str
z: str
w = 2
@classmethod
def setUpClass(cls):
cls.x = 10
cls.s = "hello"
cls.z = "bye"
def test_something(self):
print(self.s + ", world!")
print(self.z)
def test_something_else(self):
assert self.w != 1
|
11497470 | from datetime import datetime, date
from marqeta.response_models.text_value import TextValue
from marqeta.response_models.text_value import TextValue
from marqeta.response_models import datetime_object
import json
import re
class Text(object):
def __init__(self, json_response):
self.json_response = json_r... |
11497492 | from fastinference.models.Tree import Tree
def optimize(model, **kwargs):
"""Performs swap optimization. Swaps two child nodes if the probability to visit the left tree is smaller than the probability to visit the right tree. This way, the probability to visit the left tree is maximized which in-turn improves the ... |
11497522 | import math
import random
import numpy as np
import pygame
import pygame.freetype
from gamescript import commonscript
from gamescript.tactical import rangeattack, longscript
from pathfinding.core.diagonal_movement import DiagonalMovement
from pathfinding.core.grid import Grid
from pathfinding.finder.a_star import ASta... |
11497544 | import pyodbc
from infrastructure.connection.database.connectors.DatabaseConnector import DatabaseConnector
from models.configs.DatabaseConfig import DatabaseConfig
class MssqlDbConnector(DatabaseConnector):
def __init__(self, database_config: DatabaseConfig):
self.database_config: DatabaseConfig = databa... |
11497545 | def extractWwwFringeoctopusCom(item):
'''
Parser for 'www.fringeoctopus.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('TWQQF', 'Transmigration wi... |
11497589 | import serial
import time
import os
# Opens com port and bin file to be read
ser = serial.Serial('COM6', baudrate = 9600, timeout = None)
F = open("bin1.bin", "rb")
# Saves fileSize as int that fits into a byte
fileSize = int(os.path.getsize("bin1.bin")/256)
# Wait for Arduino
time.sleep(2)
def main():
write... |
11497594 | import paho.mqtt.client as mqtt #import the client1
import time
import random
import socket
import os
import sys
import s3upload as s3
uuidCoral = str(os.getenv('MAC1'))
Active = True
Unit = 'Local'
#######################################################
## Initialize Variables ##
######... |
11497617 | import os
import mimetypes
import base64
def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
if unit == '':
return '%3.0f %s%s' % (num, unit, suffix)
else:
return '%3.1f %s%s' % (num, uni... |
11497640 | import pytest
from brownie import accounts, reverts
from settings import *
# reset the chain after every test case
@pytest.fixture(autouse=True)
def isolation(fn_isolation):
pass
@pytest.fixture(scope='function')
def test_deploy_nft(nft_factory):
name = "Non Fungible Token"
symbol = "NFT"
fee = 0.1 * ... |
11497660 | class APIError(Exception):
"""Raised when unexpected server error."""
class ParametersError(Exception):
"""Raised when invalid parameters are used in a query"""
|
11497676 | from pathlib import Path
import numpy as np
import pytest
from hnswlib_searcher import HnswlibSearcher
from jina import Document, DocumentArray, Executor
_DIM = 10
@pytest.fixture
def two_elem_index():
index = HnswlibSearcher(dim=_DIM, metric='l2')
da = DocumentArray(
[
Document(id='a', ... |
11497680 | import tqdm
import cv2
import argparse
import numpy as np
import torch
import human_inst_seg
# this can be install by:
# pip install git+https://github.com/Project-Splinter/streamer_pytorch --upgrade
import streamer_pytorch as streamer
parser = argparse.ArgumentParser(description='.')
parser.add_argument(
'--came... |
11497717 | import smtplib, ssl
class EmailAlert:
smtp_server = "mailrelay.tugraz.at"
port = 587 # For starttls
sender_email = "<EMAIL>"
receiver_email = "<EMAIL>"
password = "<PASSWORD>"
def __init__(self, password, smtp_server="mailrelay.tugraz.at", port=587, sender_email="<EMAIL>", receiver_email="<EMAIL>"):
self.smt... |
11497736 | import unittest
import torch
from torch import nn
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../experiments')))
import rgcn
class TestExps(unittest.TestCase):
def test_sumsparse(self):
indices = torch.tensor([[0, 1, 2, 0], [0, 1, 2, 1]], dtype=torc... |
11497774 | import pytest
from mugen.video.segments.VideoSegment import VideoSegment
from tests import DATA_PATH
@pytest.fixture
def shinsekai_segment() -> VideoSegment:
return VideoSegment(f'{DATA_PATH}/video/shinsekai.mp4')
|
11497780 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with ... |
11497794 | from datetime import datetime, timedelta, timezone
from functools import partial
from unittest.mock import Mock
from uuid import UUID
import pytest
import trio
import trio.hazmat
from trio_websocket import open_websocket, serve_websocket
from . import assert_elapsed, assert_max_elapsed, assert_min_elapsed
from starbe... |
11497795 | import pytest
from stere.strategy.element_strategy import ElementStrategy
def test_element_strategy_find():
elem = ElementStrategy('dummy', '//fake')
with pytest.raises(NotImplementedError):
elem._find_all()
|
11497892 | from pytest import mark
from twisted.internet import defer
from twisted.trial import unittest
from scrapy import signals, Request, Spider
from scrapy.utils.test import get_crawler, get_from_asyncio_queue
from tests.mockserver import MockServer
class ItemSpider(Spider):
name = 'itemspider'
def start_request... |
11497897 | import numpy as np
import PIL
def resize(img, size):
# Same resize method as torchvision
H, W = size
img = img.transpose(1, 2, 0).astype(np.uint8)
p = PIL.Image.fromarray(img, mode='RGB')
p = np.array(p.resize((W, H)))
return p.transpose(2, 0, 1).astype(np.float32)
if __name__ == '__main__':... |
11497907 | from tests.package.test_python import TestPythonPackageBase
class TestPythonTwisted(TestPythonPackageBase):
config = TestPythonPackageBase.config
sample_scripts = ["tests/package/sample_python_twisted.py"]
def run_sample_scripts(self):
cmd = "netstat -ltn 2>/dev/null | grep 0.0.0.0:1234"
... |
11497913 | def getNames():
names = ['Christopher', 'Susan', 'Danny']
newName = input('Enter last guest: ')
names.append(newName)
return names
def printNames(names):
for name in names:
print(name)
return |
11497947 | import urllib.parse
from customers.decorators import customer_required
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import cache_page
from .forms i... |
11497956 | from sympy import symbols, cos, sin
from sympy.plotting import plot3d_parametric_line
u = symbols('u')
|
11497962 | import unittest
try:
import submission
except ImportError:
pass
class Test1(unittest.TestCase):
def test_passes(self):
"""This test should pass"""
self.assertTrue(submission.return_true())
def test_fails(self):
"""This test should fail"""
self.assertTrue(submission.re... |
11497979 | import thread
import logging
import os
import datetime
def initLogging(logfile_prefix, level_name, log_name):
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
datefmt='%Y-%m-%d %H:%M:%S'
## -- Create L... |
11498001 | import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
class GaussRankTransform(nn.Module):
def __init__(self, data: torch.Tensor, eps=1e-6):
super(GaussRankTransform, self).__init__()
tformed = self._erfinv(data, eps)
data, sort_idx = data.sort()
sel... |
11498046 | from typing import Any, Callable, Mapping
from helpers.transport.interface import MessageBus
class LocalMessageBus(MessageBus):
def __init__(self):
self.event_handler: Mapping[str, Callable[[Any], Any]] = {}
def shutdown(self):
pass
def handle(self, event_name: str) -> Callable[..., ... |
11498064 | import urllib.request
import os.path
import matplotlib.pyplot as plt
def download_pretrained_model():
# Download pre-trained model if necessary
if not os.path.isfile('CIFAR10_plain.pt'):
if not os.path.exists('./temp'):
os.makedirs('./temp')
urllib.request.urlretrieve('https://nc.... |
11498094 | import io
from lxml import objectify, etree
import pathlib
import pytest
import tempfile
import re
from hescorehpxml import (
HPXMLtoHEScoreTranslator,
main
)
both_hescore_min = [
'hescore_min_v3',
'hescore_min'
]
def get_example_xml_tree_elementmaker(filebase):
rootdir = pathlib.Path(__file__).... |
11498127 | from flask import Blueprint, Response, redirect, render_template, request
from app import database
from app.config import BASE_URL, GITHUB_URL, SPOTIFY__LOGIN
from app.utils import generate_token, get_user_info
auth = Blueprint("auth", __name__, template_folder="templates")
@auth.route("/login")
def login():
re... |
11498140 | import numpy as np
from PIL import Image
import tensorflow as tf
class ImageClassifier(object):
def __init__(self, FLAGS):
self.FLAGS = FLAGS
# Creates graph from saved GraphDef.
self.create_graph()
# Creates node id --> English label lookup.
self.label_map = self.create_... |
11498152 | def msg_too_expensive_dim(method_name, dim):
return('%s method is too expensive to be '
'run for matrices with dimension '
'greater than %d.' % (method_name, dim))
|
11498166 | import mock
import pytest
from dmaws.utils import (
DEFAULT_TEMPLATES_PATH,
merge_dicts,
template, template_string, LazyTemplateMapping,
mkdir_p,
)
from jinja2 import UndefinedError
class TestMergeDicts(object):
def test_simple_dicts(self):
assert merge_dicts({"a": 1}, {"b": 2}) == {"a": ... |
11498221 | from twisted.trial import unittest
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet import reactor
from ooni.utils.socks import TrueHeadersSOCKS5Agent
class TestSocks(unittest.TestCase):
def test_create_agent(self):
proxyEndpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 90... |
11498259 | import os
import argparse
import enum
import tarfile
import abc
def get_pretrained_model(destination):
"""
Obtains a ready to use style_transfer model file.
Args:
destination: path to where the file should be stored
"""
url = "https://storage.googleapis.com/download.magenta.tensorflow.org/m... |
11498291 | import bisect
class PriorityQueue:
def __init__(self):
self.queue = []
def append(self,data,priority):
"""append a new element to the queue according to its priority"""
bisect.insort(self.queue,(priority,data))
def pop(self,n):
"""pop the hightest element of the queue. The n argument is
here to follow the... |
11498328 | from emailrep import EmailRep
import argparse
import json
class bcolors:
OKGREEN = "\033[92m"
FAIL = "\033[91m"
BOLD = "\033[1m"
ENDC = "\033[0m"
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--email", type=str, required=True, help="Email")
return parser... |
11498399 | from __future__ import annotations
from reamber.base.Property import list_props
from reamber.base.lists.notes.HitList import HitList
from reamber.sm.SMMine import SMMine
from reamber.sm.lists.notes.SMNoteList import SMNoteList
@list_props(SMMine)
class SMMineList(HitList[SMMine], SMNoteList[SMMine]):
...
|
11498419 | class ElectricalSetting(Element,IDisposable):
""" The ElectricalSetting class represents an instance of element of electrical settings. """
def AddDistributionSysType(self,name,phase,phaseConfig,numWire,volLineToLine,volLineToGround):
"""
AddDistributionSysType(self: ElectricalSetting,name: str,phase: Electri... |
11498420 | from inkplate6_PLUS import Inkplate
from image import *
import time
display = Inkplate(Inkplate.INKPLATE_1BIT)
#main function used by micropython
if __name__ == "__main__":
display.begin()
display.tsInit(1)
display.drawRect(450, 350, 100, 100, display.BLACK)
display.display()
counter = 0
... |
11498447 | import torch
import torch.nn.functional as F
from torch import nn
from torch.nn import CrossEntropyLoss
from arch.model_cityscapes import SqueezeNASNetCityscapesHyperparameters, ASPP_Lite, ASPP, Conv_BN_ReLU
from search.arch_search import SuperNetwork
from search.model_search import SuperNetworkSqueezeNASNet
class S... |
11498502 | def main():
import sys
from poseidon_cli.cli import PoseidonShell
p_shell = PoseidonShell()
if '-c' in sys.argv:
while sys.argv.pop(0) != '-c':
pass
p_shell.onecmd(' '.join(sys.argv))
else:
p_shell.cmdloop()
|
11498503 | import os,sys
# change the path accoring to the test folder in system
#sys.path.append('/home/ubuntu/setup/src/fogflow/test/UnitTest/v1')
from datetime import datetime
import copy
import json
import requests
import time
import pytest
import data_ngsi10
import sys
# change it by broker ip and port
brokerIp="http://loca... |
11498519 | import argparse
import json
import os
import shutil
from chainerui.utils.tempdir import tempdir
def convert_dict(conditions):
if isinstance(conditions, argparse.Namespace):
return vars(conditions)
return conditions
def save_args(conditions, out_path):
"""A util function to save experiment condi... |
11498567 | import numpy as np
def random_subset(iterator, k):
result = iterator[:k]
i = k
tmp_it = iterator[k:]
for item in tmp_it:
i = i + 1
s = int(np.random.random() * i)
if s < k:
result[s] = item
return result
def generate_imbalance(X, y, positive_label=1, ir=2):
... |
11498667 | import copy
import typing
from pathlib import Path
import click
import vpype as vp
# Load the default config
vp.CONFIG_MANAGER.load_config_file(str(Path(__file__).parent / "bundled_configs.toml"))
def invert_axis(document: vp.Document, invert_x: bool, invert_y: bool):
"""Inverts none, one or both axis of the d... |
11498682 | from amlearn.utils.data import read_lammps_dump
from amlearn.featurize.pipeline import FeaturizePipeline
from amlearn.featurize.nearest_neighbor import VoroNN, DistanceNN
from amlearn.featurize.short_range_order import \
DistanceInterstice, VolumeAreaInterstice
from amlearn.featurize.medium_range_order import MRO
... |
11498688 | import numpy
import sys
with open(sys.argv[1], "r") as fp, \
open(sys.argv[1] + ".sort", "w") as fw:
line_list = []
bleu_list = []
for line in fp:
if "BLEU=" not in line:
continue
line = line.strip()
line_list.append(line)
idx = line.index("BLEU=")
b... |
11498696 | from PIL import Image
from abc import ABC, abstractmethod
import torch
from plan2scene.common.image_description import ImageDescription
from plan2scene.evaluation.metrics import AbstractPairedMetric, AbstractUnpairedMetric
"""
A matcher pairs a predicted texture with a ground truth reference crop (if available).
The ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.