content stringlengths 5 1.05M |
|---|
import os
import concurrent
import logging
import json
import random
import datetime
import asyncio
import aiohttp
from aiohttp import web
import aiohttp_session
import prometheus_client as pc
import pymysql
from prometheus_async.aio import time as prom_async_time
from prometheus_async.aio.web import server_stats
impor... |
import os
PIXEL = "\u2584"
def colored(red: int, green: int, blue: int, text: str) -> str:
return f"\033[38;2;{red};{green};{blue}m{text}"
def clear_console():
os.system("clear" if os.name == "posix" else "cls")
|
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from toolshare.models.tool import Tool
from toolshare.models.user import User
from toolshare.models.reservation import Reser... |
from click.testing import CliRunner
import deepdanbooru as dd
from deepdanbooru.commands.add_images_to_project import parse_tags, read_tag_file, copy_image_to_project, add_images_to_project
import pytest
from pathlib import Path
import sqlite3
from unittest.mock import MagicMock, Mock, patch
def test_parse_tags():
#... |
from aiogram.types import CallbackQuery
from aiogram_dialog import DialogManager, ShowMode
async def enable_send_mode(
event: CallbackQuery, button, dialog_manager: DialogManager, **kwargs
):
dialog_manager.show_mode = ShowMode.SEND
async def get_result(dialog_manager: DialogManager, **kwargs):
return {... |
import asyncio
import http.client
import json
import shutil
import ssl
import tempfile
import time
import unittest
from unittest import mock
import nats
from nats.aio.client import Client as NATS, __version__
from nats.aio.errors import *
from tests.utils import *
class HeadersTest(SingleServerTestCase):
@async... |
# from math import trunc
# n = float(input('Digite um número decimal: '))
# print(f'A parte inteira desse número é \033[32;1m{trunc(n)}\033[m')
num = float(input('Digite um valor: '))
print(f'A parte inteira desse número é \033[32;1m{int(num)}')
|
from ..core.q import Q
from ..core import Field
from ..core.api.special_values import Autogenerate, OMIT
from ..core.bindings import RelatedObjectBinding
from .dataset import Dataset, DatasetTypeBinder
from .treeq import TreeQBinder
class FilesystemBinder(DatasetTypeBinder):
def __init__(self, object_type, syste... |
import pytest
from ldap_filter import Filter
class TestFilterOutput:
def test_to_string(self):
filt = '(&(|(sn=ron)(sn=bob))(mail=*)(!(account=disabled)))'
parsed = Filter.parse(filt)
string = parsed.to_string()
assert string == filt
def test_string_typecast(self):
fil... |
#!/usr/bin/env python
# coding:utf-8
import os
import shutil
import zipfile
try:
import requests
except ImportError:
requests = None
print 'Project Creator depends on the "requests" lib.'
def download_lastest_src():
print 'Fetching the lastest version from github...'
r = requests.get('https://g... |
# pylint: disable=redefined-builtin,invalid-name
"""
Configuration file for the Sphinx documentation builder.
https://www.sphinx-doc.org/en/master/usage/configuration.html
"""
from typing import Final, Sequence
import os
import sys
# region Path setup
# If extensions (or modules to document with autodoc) are in anothe... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-09-28 05:40
from __future__ import unicode_literals
from django.db import migrations, models
import taiga.base.utils.time
class Migration(migrations.Migration):
dependencies = [
('projects', '0053_auto_20160927_0741'),
]
operations = [... |
import os
from ajenti.api import *
from ajenti.plugins.main.api import SectionPlugin
from ajenti.ui import on
from ajenti.ui.binder import Binder
from reconfigure.configs import ExportsConfig
from reconfigure.items.exports import ExportData, ClientData
@plugin
class Exports (SectionPlugin):
config_path = '/etc/... |
import sys
import json
import time
from pprint import pprint
from flask import request
from flask_bcrypt import Bcrypt
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from webapp import db
from webapp.blueprints.users.models import User
from webapp.blueprints.main.models import (
... |
import os
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import simpson
print(os.getcwd())
def joukowski_map(mu_x, mu_y, num_pt):
# center of circle in complex plane
comp_cent = np.array([mu_x, mu_y])
# radius of circle in complex plane /
# distance from center to point (-1,0)... |
"""Interface that defines a puzzle."""
class PuzzleInterface:
def execute(self) -> None:
"""Executes the puzzle"""
pass
|
from transformers import BertModel, BertForMaskedLM, DistilBertModel, DistilBertForMaskedLM
def get_kobert_model(cache_dir=None):
""" Return BertModel for Kobert """
if cache_dir is not None:
model = BertModel.from_pretrained(cache_dir)
else:
model = BertModel.from_pretrained('monologg/kob... |
# Copyright (c) 2013 Huan Do, http://huan.do
import ast
from constant_finder import ConstantFinder
from constant_changer import ConstantChanger
class ConstantVisitor(object):
"""Rename all constants and takes a note of it, so that
in the final phase we can inject an assignment node that
declares them.
... |
import logging, re
import sys
sys.path.append('')
from cube.io_utils.objects import Document
class Encodings:
def __init__(self, verbose=False):
self.word_list = {}
self.hol_word_list = []
self.char2int = {}
self.label2int = {}
self.labels = []
self.word2int = {}
... |
import factory
from unittest.mock import patch
from test_plus.test import TestCase
from studio.services import get_ai_list, post_import_ai
from studio.tests.factories import (
AiFactory,
AIImportJSON,
NameExistsFactory,
SuccessFactory,
UnauthorizedFactory
)
class TestAIList(TestCase):
def s... |
""" CSeq C Sequentialization Framework
mapper module
maps from variables in the input program to propositional variables in the propositional formula (based on our forked version of CBMC)
written by Omar Inverso.
"""
VERSION = 'labs_mapper-2020.05.19'
#VERSION = 'labs_mapper-2018.10.22' # forked from mapper-2018.... |
from __future__ import print_function, unicode_literals
import sys
import scipy.io
import scipy.misc
from cscPy.mano.network.Const import *
import cscPy.dataAugment.augment as augment
#sys.path.append('..')
import pickle
import os
from torch.utils.data import Dataset
from cscPy.mano.network.utils import *
from cscPy.... |
'''
Copyright 2017, Dell, Inc.
Author(s):
UCS test script that tests:
-The Poller workflow
-The Poller data
'''
import fit_path # NOQA: unused import
import unittest
from common import fit_common
from nosedep import depends
from nose.plugins.attrib import attr
import ucs_common
import flogging
logs = flogging.get_... |
import torch
import torch.nn as nn
from model.pointnetpp_segmodel_sea import PointNetPPInstSeg
from model.primitive_fitting_net_sea import PrimitiveFittingNet
# from model.pointnetpp_segmodel_cls_sea import InstSegNet
from model.pointnetpp_segmodel_cls_sea_v2 import InstSegNet
# from datasets.Indoor3DSeg_dataset impor... |
#!/usr/bin/python3
from termcolor import colored
from tabulate import tabulate
from threading import Thread
import time
import argparse
import sys
import errno
import os
import shutil
import subprocess
import signal
# Output directory for the downloaded files. Cleaned afterwards
# Be extra careful when changing that... |
#!/usr/bin/env python3
from pithy.xml import *
from utest import *
html = Xml(tag='html', lang='en-us')
head = html.append(Xml(tag='head', ch=[Xml(tag='title', ch=['TITLE'])]))
body = html.append(Xml(tag='body'))
div0 = body.append(Xml(tag='div', cl='DIV-CLASS', id='DIV-ID-0'))
p0 = div0.append(Xml(tag='p', ch=['Pa... |
#!/usr/bin/env python3
# -*- mode: python ; coding: utf-8 -*-
"""Tracks and analyses writing progress"""
import argparse
import datetime
import os.path
import sys
import uuid
from pathlib import Path
from tabulate import tabulate
from src.trak import core_methods
from src.trak.project import Project
from src.trak.sess... |
#!/usr/bin/env python
# coding=utf-8
"""
Ant Group
Copyright (c) 2004-2021 All Rights Reserved.
------------------------------------------------------
File Name : homo_enc.py
Author : Qizhi Zhang
Email: qizhi.zqz@antgroup.com
Create Time : 2021/9/29 下午3:19
Description : description what the main... |
# 약수의 개수와 덧셈
def solution(left, right):
answer=0
for num in range(left,right+1):
cnt = 0
for i in range(1,num+1):
if num%i == 0:
cnt += 1
if cnt%2 == 0:
answer += num
else:
answer -= num
return answer
'''
테스트 1 〉 통과 (19.56m... |
# Copyright (c) 2016 Ansible by Red Hat, Inc.
#
# This file is part of Ansible Tower, but depends on code imported from Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of ... |
__all__ = ['SolverOptions',
'SolverResultsOptions', 'SolverOdeOptions',
'McOptions']
from ..optionsclass import optionsclass
import multiprocessing
@optionsclass("solver")
class SolverOptions:
"""
Class of options for evolution solvers such as :func:`qutip.mesolve` and
:func:`qutip.m... |
import json
import random
import uuid
from time import sleep
import pandas as pd
from kafka import KafkaProducer
from config import config
def start_producing():
# init data loader
numerical_features = ["age", "fnlwgt", "capital_gain", "capital_loss", "hours_per_week"]
categorical_features = [
"... |
"""
Utitility functions for working with operators
"""
__all__ = [
'latex_align',
'collect_by_nc',
'collect_by_order',
'extract_operators',
'extract_operator_products',
'extract_all_operators',
'operator_order',
'operator_sort_by_order',
'drop_higher_order_terms',
'drop_terms_co... |
# uncompyle6 version 3.7.0
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:19:08) [MSC v.1500 32 bit (Intel)]
# Embedded file name: scripts/common/battle_results/event.py
from battle_results_constants import BATTLE_RESULT_ENTRY_TYPE as ENTRY_TYPE
from DictPackers impo... |
import numpy as np
import cv2 as cv
import sys
def threshold(path, reverse=False):
img = cv.imread(path)
if img is None:
return None
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
mod = cv.THRESH_BINARY
if reverse == True:
mod = cv.THRESH_BINARY_INV
ret, img_sh = cv.thres... |
r"""
=======
liionpack
=======
liionpack is a tool for simulating battery packs with pybamm. It can design the
pack with a combination of batteries connected in series and parallel or can
read a netlist.
"""
from .simulations import *
from .utils import *
from .netlist_utils import *
from .sim_utils import *
from .sol... |
#! /usr/bin/env python3
#
# Copyright 2019 California Institute of Technology
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... |
""" This module contains the non-standard mass values for blocks in Starmade"""
#: A Python dict of block IDs with non standard mass
#: In the form of <block_id>: <mass>
#: To get the mass of a block ID in Python, you can do:
#: NON_STANDARD_MASS.get(block_id, 0.1)
NON_STANDARD_MASS = {
5: 0.15,
15: 0.05,
... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : container.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 01/18/2018
#
# This file is part of Jacinle.
# Distributed under terms of the MIT license.
import copy
import collections
from .printing import kvformat, kvprint
__all__ = ['G', '... |
# -*- coding: utf-8 -*-
import unittest
from context import conflict2dict
class TestConflictParser(unittest.TestCase):
""" functional tests of conflict_parser"""
def test_default_xml_contains_rules(self):
res = conflict2dict()
self.assertIsNot(res, [])
def test_conflict2dict_ouput_type... |
import logging
from flask import jsonify, request
import flask_login
import mediacloud.error
from server import app, TOOL_API_KEY
from server.util.request import api_error_handler, argument_is_valid, arguments_required, json_error_response, \
form_fields_required
from server.views.topics.apicache import topic_stor... |
#
# Lockstep Platform SDK for Python
#
# (c) 2021-2022 Lockstep, Inc.
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# @author Lockstep Network <support@lockstep.io>
# @copyright 2021-2022 Lockstep, Inc.
# @link https://github.... |
from tests.unit_tests.running_modes.transfer_learning .test_transfer_learning import TestTransferLearning |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
backup_restore_pattern.py
Pixelblaze based LED controller for APA102/SK9822 LED Strips
Working Example using PixelblazeClient
NOTE: this implements a different way of using an async library!
MQTT interface for pixelblaze v3
N Waterton V 1.0 16th March 2021: In... |
import json
from . import config
def get_context_processor():
def sentry_contexts(request):
if request.user.is_authenticated:
user_context = json.dumps({
'email': request.user.email,
'id': request.user.id,
})
else:
user_context = ... |
from util import *
import numpy as np
from functools import reduce
global zzl_solution_file_a
def ReadAppResources(app_resources_file):
# this function read theapp resource
app_resfile = open(app_resources_file)
for line in app_resfile:
line = line.strip('\n')
vec_resource = line.split(',... |
# from __future__ import division
import numpy as np
from os import path as op
import gzip
import bz2
import glob
import json
import traceback # ,itertools
from ase.io import vasp as pv
# remove nested list by list(chain.from_iterable(list_of_lists))
from itertools import chain
import itertools as itr
from math import... |
from gevent import monkey
monkey.patch_all()
from flask import Flask
from TikTokApi import TikTokApi
api = TikTokApi.get_instance()
custom_verifyFp = "verify_kqv2svy0_gQARqKRo_fV40_4EW1_Bob0_RGCkXxCbfYTz"
app = Flask(__name__)
@app.route('/tiktok/<tiktok_id>', methods=['GET'])
def tiktok(tiktok_id):
tiktok_vide... |
# -*- coding: utf-8 -*-
# @author: Alexander Pitchford
# @email1: agp1@aber.ac.uk
# @email2: alex.pitchford@gmail.com
# @organization: Aberystwyth University
# @supervisor: Daniel Burgarth
"""
Utility functions for symplectic matrices
"""
import numpy as np
def calc_omega(n):
"""
Calculate the 2n x 2n Omega ... |
import pytest
import vaex
import numpy as np
import numpy.ma
df_a = vaex.from_arrays(a=np.array(['A', 'B', 'C']),
x=np.array([0., 1., 2.]),
y=np.ma.array([0., 9., 2.], mask=[False, True, False]),
m=np.ma.array([1, 2, 3], mask=[False, True, False])... |
#creating a text file
#opening in write mode
file=open("sam.txt","w")
#writing some content
file.write("hi")
file.write("\n")
file.write("We are participating in Py75 challenge")
file.write("\n")
file.write("It's so interesting")
#closing the opened file
file.close()
#write using appending mode
file=open("sam.txt"... |
import os
import logging
import torch
import collections
from torch.utils.data import Dataset
from torch.nn.utils.rnn import pad_sequence
logger = logging.getLogger(__file__)
def build_dataset(dataset, tokenizer):
logger.info("Tokenize and encode the dataset")
instances = collections.defaultdict(list)
fo... |
# pylint: disable=unused-argument, missing-function-docstring
from flask_discord_interactions import DiscordInteractionsBlueprint, Message, Embed
from flask_discord_interactions.models.command import ApplicationCommandType, CommandOptionType
from flask_discord_interactions.models.user import User
from flask_discord_int... |
"""
Copyright (c) 2014, Samsung Electronics Co.,Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and... |
"""
The archive method here is based on the dataloc system.
This is a system where when code is run a json file with the output directory
path is written in the repo.
- Pros
- Can handle general paths
- Cons
- requires a link to files
- Has trouble if experiments mix their output folders
"""
from .utilities imp... |
from flask import make_response, send_file, g, Response
import traceback, json, time, bson, os
# from views import setup
# from lib.utils.config import Settings
# from lib.utils.db import Manager
from appinit_backend.lib.modules import Modules
#
# settings = Settings(path="/home/cee-tools/", verify=False, instance=o... |
# Test slice assignment
l = list(range(6))
l[2:5] = ["x"]
assert l == [0, 1, 'x', 5]
l = list(range(7))
l[:5] = ["x"]
assert l == ['x', 5, 6]
l = list(range(6))
l[2:] = ["x"]
assert l == [0, 1, 'x']
l = list(range(6))
l[:] = ["x"]
assert l == ['x']
# Test slice deletion
l = list(range(6))
del l[2:5]
assert l == [... |
from akcrm.permissions import LazyPermissions
class PermissionsMiddleware(object):
def process_request(self, request):
setattr(request, 'PERMISSIONS', LazyPermissions(request))
|
#!/usr/bin/python
import sys
source_files = sys.argv[1].split(" ")
output_header_path = sys.argv[2]
tmp_dir = sys.argv[3] or "CMakeFiles/"
timestamps_path = tmp_dir + "model_refl_timestamps"
print("Updating reflection model")
print("Source files", source_files)
print("Output header", output_header_path)
print("Times... |
import streamlit as st
import tensorflow as tf
from PIL import Image, ImageOps
import numpy as np
st.set_option('deprecation.showfileUploaderEncoding', False)
# @st.cache(suppress_st_warning=True,allow_output_mutation=True)
def import_and_predict(image_data, model):
image = ImageOps.fit(image_data, (100,100),Imag... |
from datetime import datetime
from twogplus import db
class User(db.Model):
__tablename__ = "users"
id: int = db.Column(db.Integer, primary_key=True)
name: str = db.Column(db.Text, nullable=False)
created_at: datetime = db.Column(db.Date, nullable=False, default=db.func.now())
is_tested: bool = d... |
import os
import sys
import torch
import pandas as pd
import numpy as np
from torch.utils.data import Dataset
import warnings
warnings.filterwarnings('ignore')
class GenomeDataset(Dataset):
""" GWAS and nonGWAS SNP sequence dataset"""
def __init__(self, filename, seq_name=['seq_ref_1'], encode_mode="N_2_zero"... |
class TrainingConfig(object):
seed = 1
use_gpu = True
gpu_id = 0
epoch = 30
learning_rate = 1e-3
decay_rate = 0.5
decay_patience = 3
batch_size = 64
train_log = True
log_interval = 10
show_plot = False
f1_norm = ['macro', 'micro']
class ModelConfig(object):
word_dim... |
c,t = input().split()
c = int(c)
t = float(t)
if t>c+0.5 and c%5==0:
print("%.2f"%(t-c-0.5))
else:
print("%.2f"%t)
|
import os
images_dir = os.getenv("BACKEND_IMG_PATH", "images")
postgres_url = os.getenv("BACKEND_DB_URL", "")
|
def longestRun(L):
startpos = 0
endpos = 0
myList=[]
numtimes = 0
listindx = 0
if len(L) == 1:
return 1
while numtimes < len(L)-1: # number of times its starting through
if L[listindx+1] >= L[listindx]:
if startpos == ... |
#!/usr/bin/python
import jsonrpclib
import time
import ssl
from pprint import pprint
ssl._create_default_https_context = ssl._create_unverified_context
ip = '184.105.247.72'
port = '443'
username = 'admin1'
password = '99saturday'
switch_url = 'https://{}:{}@{}:{}'.format(username, password, ip, port)
switch_url ... |
from bottle import Bottle, run, route, static_file, request, response, template, redirect
import json
import time
import os
app = Bottle(__name__)
@app.route('/')
def root():
return static_file('index.html', root='templates')
@app.route('/index1')
def index1():
return static_file('inde... |
# Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the
# License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file ... |
# -*- coding: utf-8 -*-
"""
aux.plugin based on flask.ext
~~~~~~~~~
Redirect imports for extensions. This module basically makes it possible
for us to transition from flaskext.foo to flask_foo without having to
force all extensions to upgrade at the same time.
When a user does ``from flask.e... |
import setuptools
VERSION = 0.1
def get_description():
with open("README.md", "r") as md:
long_description = md.read()
return long_description
def get_requirements():
with open("requirements.txt") as f:
requirements = f.readlines()
return [i.replace(r"\n", "") for i in requirements]... |
from __future__ import annotations
from typing import List, Dict
class Rule:
def __init__(self, text: str):
parts = text.split(":")
if len(parts) != 2:
raise ValueError(f"cannot create Rule, syntax error (expected <index>: <description>) in {text}")
self.index = int(parts[0])
... |
"""
Copyright 2019, Institute for Systems Biology
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... |
from random import sample
n1 = str(input('Primeiro aluno: '))
n2 = str(input('Segundo aluno: '))
n3 = str(input('Terceiro aluno: '))
n4 = str(input('Quarto aluno: '))
lista = [n1, n2, n3, n4]
escolhido = sample(lista, 4)
print('Os sorteados para apresentarem os trabalhos \n{}: Primeiro \n{}: Segundo \n{}: Terceiro\n{}:... |
"""Test modules for nested-dict."""
|
# Copyright 2017-2020 EPAM Systems, Inc. (https://www.epam.com/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
from typing import Dict
with open("dane_geny.txt") as f:
lines = [line.strip() for line in f.readlines()]
genes: Dict[int, int] = {}
for line in lines:
l = len(line)
if l not in genes:
genes[l] = 1
else:
genes[l] += 1
print(f"liczba gatunków: {len(genes)}")
maks = 0
for v in genes.va... |
#!/usr/bin/env python3
from abc import (
ABCMeta as _ABCMeta,
abstractproperty as _abstractproperty,
)
class Event(metaclass=_ABCMeta):
pass
class QuitEvent(Event):
pass
class NavigateEvent(Event):
@_abstractproperty
def x(self) -> int:
raise NotImplementedError
@_abstract... |
import sys
import time
from PyQt5.QtWidgets import (QApplication, QWidget, QFrame, QGridLayout,
QProgressBar, QPushButton, QCalendarWidget,
QLabel)
from PyQt5.QtGui import QIcon, QFont, QColor
from PyQt5.QtCore import Qt, QBasicTimer, QDate
from Game_Run impo... |
import matplotlib.pyplot as plt
from src.configuration import *
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
colors = ['pink', 'lightgreen', 'lightblue', 'wheat', 'salmon']
day_label = 'Timetable'
fig_width = 10
fig_height = 6
def convert_hour(hour):
return STARTING_HOUR + hour * DIFFERENCE_B... |
"""The solaredge component."""
|
import procbridge.procbridge as procbridge
__all__ = ['ProcBridgeServer', 'ProcBridge']
|
from argparse import ArgumentParser
import torch
import torchmetrics
import pytorch_lightning as pl
from .model_selection import load_model
from .scheduler import WarmupCosineSchedule
class LitVisionTransformer(pl.LightningModule):
def __init__(self, args):
super().__init__()
self.args = args
... |
import torch
import torch.nn.functional as F
from torch import nn
class MLP_Net0(nn.Module):
def __init__(self):
super(MLP_Net0, self).__init__()
self.linear1 = nn.Linear(in_features=784, out_features=21)
self.linear2 = nn.Linear(in_features=21, out_features=10)
def forward(self, x):
... |
# namespace imports
import subprocess # noqa
# FIXME
#from gevent import subprocess
from gevent.queue import Queue # noqa
from gevent import Greenlet as Thread # noqa
from gevent import joinall, sleep # noqa
|
# -*- coding: utf-8 -*-
import unittest2
import redis
from apps.database.session import db, cache
from apps.controllers.router import app
from apps.database.models import Test
class TestDatabase(unittest2.TestCase):
def setUp(self):
self.app = app.test_client()
self.app.testing = True
tes... |
from flask import render_template, g, url_for, redirect, request, Response
from sqlalchemy import and_
from scrimmage import app, db
from scrimmage.models import User, Team, TeamJoinRequest, GameRequest, GameRequestStatus, Game, Announcement, Tournament
from scrimmage.decorators import login_required, team_required, ... |
from tensorflow.keras import callbacks as keras_callbacks
from glrec.utils import log
from glrec.train import utils as train_utils
class GsutilRsync(keras_callbacks.Callback):
def __init__(self, local_storage_dir, gs_storage_dir, **kwargs):
super().__init__(**kwargs)
self._local_storage_dir = loca... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The user's intents definitions. It serves as abstraction to separate NLU processing
logic from response processing routines. Allows to easy register in the system as many
intents as it needed.
"""
from chatbot1.command import GreetCommand, AddItemCommand, RemoveItem... |
import bpy
from bpy import context as context
fc_skList = [
'browInnerUp', 'browDown_L', 'browDown_R', 'browOuterUp_L', 'browOuterUp_R',
'eyeLookUp_L', 'eyeLookUp_R', 'eyeLookDown_L', 'eyeLookDown_R', 'eyeLookIn_L', 'eyeLookIn_R', 'eyeLookOut_L', 'eyeLookOut_R',
'eyeBlink_L', 'eyeBlink_R', 'eyeSquint_L', 'eyeSquin... |
# -*- coding: utf-8 -*-
"""
some function by metaphy,2007-04-03,copyleft
version 0.2
"""
import urllib, httplib, urlparse
import re
import random
"""judge url exists or not,by others"""
def httpExists(url):
host, path = urlparse.urlsplit(url)[1:3]
if ':' in host:
# port specified, try to use it
... |
import numpy as np
from uutils.torch_uu.metrics.cca.cca_core import get_cca_similarity
def svcca_with_keeping_fixed_dims(x: np.ndarray, y: np.ndarray, dims_to_keep: int,
epsilon: float = 1e-10, verbose: bool = False,
full_matrices: bool = False, kee... |
# -*- coding: utf-8 -*-
"""Module for single entry transformers."""
import logging
from collections import defaultdict
from operator import attrgetter
from ....core.models.base import RemoteInstance
from ....core.exceptions import DoesNotExistException, SkipField
from ....core.models.terminal import (
SshKey, Ident... |
__author__ = 'jitrixis'
from TVpy.Factory.toolsheds import Toolkit
class Arp:
def __init__(self):
self.__hwtype = 0x1
self.__ptype = 0x800
self.__hwlen = 6
self.__plen = 4
self.__op = 0x1
self.__hwsrc = '00:00:00:00:00:00'
self.__psrc = '0.0.0.0'
se... |
# todo make sure what they mean by desc undefined? None or empty? Answer: None :) it can never be empty but None is sometimes returned.
# I am implementing everything as dicts to speed up property creation
# Warning: value, get, set props of dest are PyJs types. Rest is Py!
def is_data_descriptor(desc):
return ... |
style = 'formatted'
print(f"this is a {style} string")
import math
r = 3.6
print(f"A circle with radius {r} gives the result {math.pi * r * r:.2f}") |
for index in range(1, int(input())+1): print("*" * index)
|
graph = dict()
graph['S'] = {}
graph['S']['A'] = 2
graph['S']['B'] = 2
graph['A'] = {}
graph['A']['B'] = 2
graph['B'] = {}
graph['B']['C'] = 2
graph['B']['E'] = 25
graph['C'] = {}
graph['C']['A'] = -15
graph['C']['E'] = 2
# graph['D'] = {}
# graph['D']['E'] = 1
graph['E'] = {}
inf = float('inf')
# costs = {}
# ... |
import numpy as np
import torch
from collections import defaultdict
import string
from sequence.data import traits
from enum import IntEnum
from typing import List, Dict, Optional, Union, Sequence
import functools
def lazyprop(fn):
attr_name = "_lazy_" + fn.__name__
@property
@functools.wraps(fn)
def... |
from aiogram import types
from aiogram.dispatcher.filters.builtin import CommandStart
from loader import dp, _
from src.stickers.dn_stickers import ryuk_hi
from src.utils.db_api import db_helpers
@dp.message_handler(CommandStart(), state='*')
async def bot_start(message: types.Message):
await message.answer_stic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.