content stringlengths 5 1.05M |
|---|
from src.commands.functions import schedule
from src import command_system
from src import db_context
def execute(user_id):
return schedule.get_schedule(
group=db_context.get_group_name_by_user_id(user_id))
schedule_command = command_system.Command()
schedule_command.keys = [
'расписание', 'sch', '... |
import logging
import os
import unittest
from configparser import ConfigParser
from mop.azure.utils.create_configuration import change_dir, OPERATIONSPATH, TESTVARIABLES
from dotenv import load_dotenv
from mop.azure.plugins.execution import Execution
from mop.azure.plugins.pypolicy.glbl_pr_sec_databricks_vnetfilter_s... |
#! python3
"""
This script finds and downloads data from three libraries for reaction rates.
These libraries are REACLIB, BRUSLIB and EXFOR. As the websites do not supply
an easy way of requesting the data, the script uses URL-manipulation,
HTML-scraping and website interaction to find the download link. As the
reader... |
__author__ = 'Willem'
import operator
import random
import logging
def identity(x): return x
# ------------------------ Max Fcns and Sorting -----------------------------
def get_iterable_of_arg_val_tuples(data : "Sequence or dict",
key=None):
if isinstance(data, (list, tuple... |
# -*- coding: UTF-8 -*-
# File: symbolic_functions.py
import tensorflow as tf
import numpy as np
from ..utils.develop import deprecated
# __all__ = ['get_scalar_var']
def sum_absolute_difference(pred, label, name='sum_abs_diff_by_dp'):
"""
Args:
pred: shape [B, C]
label: shape [B, C]
... |
import os
import io
import hashlib
from base64 import standard_b64encode
from six.moves.urllib.request import urlopen, Request
from six.moves.urllib.error import HTTPError
from infi.pyutils.contexts import contextmanager
from infi.pypi_manager import PyPI, DistributionNotFound
from logging import getLogger
logger = ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains definitions for asset in Artella
"""
from __future__ import print_function, division, absolute_import
__author__ = "Tomas Poveda"
__license__ = "MIT"
__maintainer__ = "Tomas Poveda"
__email__ = "tpovedatd@gmail.com"
import os
import logging
im... |
''' Flags for the model '''
import tensorflow as tf
def load_flags(mode = 'train'):
flags = tf.app.flags
flags.DEFINE_integer('nfilt', 40, 'Number of filters in mel specta')
flags.DEFINE_float('keep-prob', 0.8, 'Keep probability for dropout')
flags.DEFINE_integer('max-output-len', 200, 'Maximum output ... |
from .transform import transform
|
import jinja2
import wataru.settings as settings
import sys
_env = None
_abspath = None
def setenv(abspath):
me = sys.modules[__name__]
if me._env is None:
me._env = jinja2.Environment (
loader = jinja2.FileSystemLoader(abspath, encoding='utf-8')
)
me._abspath = abspath
de... |
'''
Importing the necessary libraries and the flask app for testing
'''
from app import app
import unittest
from flask_testing import TestCase
class FlaskTestcase(unittest.TestCase):
#set up the app
def setUp(self):
app.config['TESTING'] = True
app.config['DEBUG'] = False
... |
import types
def miss(thing):
""" Little Miss - A minimal SS prove of concept """
def decorator(fun):
def decorated(*args, **kwargs):
if _is_fun(thing):
return _apply_fun(thing, fun, args, kwargs)
return _apply_value(thing, fun, args, kwargs)
return deco... |
from algosdk import encoding
from utils.util import getAppGlobalState
def test_report(client, scripts, accounts, deployed_contract):
"""Test report() method on contract"""
scripts.stake()
state = getAppGlobalState(client, deployed_contract.id)
assert state[b"num_reports"] == 0
query_id = b"1"
... |
#Process level parallelism for shell commands
import os
from os.path import join, basename, split, splitext
import sys
from os import makedirs
from glob import glob
import subprocess as sp
import time
import re
import logging
import argparse
from multiprocessing import Pool
import functools
from tqdm import tqdm
loggi... |
"""
Order.py
PURPOSE:
Create the Order object so that players can create orders to command vessels.
"""
from typing import Tuple
from Settings import PURPLE, DEFAULT
class TraditionalOrder:
"""
The general command class used in Traditional Battleship to plan player
moves.
Attribute(s):
- order_... |
from rest_framework import serializers
from .models import Question
from .models import Answer
class QuestionSerializer(serializers.ModelSerializer):
author = serializers.ReadOnlyField(source='author.username')
class Meta:
model = Question
fields = ('slug', 'time', 'text', 'author')
class Ans... |
# This file is part of the
# Arcovid19 (https://ivco19.github.io/).
# Copyright (c) 2020, Arcovid Team
# License: BSD-3-Clause
# Full Text: https://raw.githubusercontent.com/ivco19/epyRba/master/LICENSE
# =============================================================================
# DOCS
# =======================... |
""" Utilities fo data validation """
# Authors:
# Wilson Rocha Lacerda Junior <wilsonrljr@outlook.com>
# License: BSD 3 clause
import numpy as np
import numbers
# copy-pasted/adpted from scikit-learn utils/validation.py
def check_random_state(seed):
"""Turn `seed` into a `np.random.RandomState` instanc... |
def download_materials():
import subprocess
import sys
subprocess.check_call([sys.executable, "-m", "pip", "install", 'numpy'])
subprocess.check_call([sys.executable, "-m", "pip", "install", 'matplotlib'])
subprocess.check_call([sys.executable, "-m", "pip", "install", 'art'])
start_menu()
impor... |
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#
# Copyright (C) 2016 Cinc-th
#
# All rights reserved.
#
# This software is licensed as described in the file COPYING.txt, which
# you should have received as part of this distribution.
#
from setuptools import setup
setup(
name='BlackFlatTheme',
version='1.0... |
import termninja_db as db
import aioredis
import sanic_jwt
import os
from sanic import Sanic
from sanic.response import json, text, HTTPResponse
from sanic.exceptions import InvalidUsage, NotFound, ServerError
from .user import bp as user_bp
from .game import bp as game_bp
from .rounds import bp as round_bp
app = San... |
import math
scale = 10
def angle(ux,uy,vx,vy):
""" Calculate angle of two vectors """
try:
cos = 1.0*(ux*vx + uy*vy)/(math.sqrt(ux*ux+uy*uy)*math.sqrt(vx*vx+vy*vy))
except ZeroDivisionError:
print "ZDE"
return 0
try:
angle = math.acos(cos)
except ValueError:
if cos>0.99:
angle=0
if cos<0.01:
an... |
import random
name1 = str(input('Student 1: '))
name2 = str(input('Student 2: '))
name3 = str(input('Student 3: '))
name4 = str(input('Student 4: '))
list = [name1, name2, name3, name4]
random.shuffle(list)
print('The appearance order will be: {} '.format(list))
print(list)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-14 04:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('DataVortex', '0009_auto_20160214_0549'),
]
operations = [
migrations.AddField(... |
import flask_skeleton
from flask_skeleton.models import db, User
# pylint: disable=invalid-name
app = flask_skeleton.create_app({
'SECRET_KEY': 'completely_unsafe_dev_key',
'DEBUG': True,
'TESTING': True
})
def run():
app.run(host='0.0.0.0', port=5000)
def reset_db():
with app.app_context():
... |
import os
import MySQLdb
import datetime
def connect_db():
db_host = os.environ['db_host']
db_user = os.environ['db_user']
db_pw = os.environ['db_pw']
db_name=os.environ['db_name']
db = MySQLdb.connect(db_host, db_user, db_pw, db_name)
return db
def close_db(db):
db.close()
def list_lib_n... |
# -*- coding: latin-1 -*-
#
# Copyright 2015-2015 Ghent University
#
# This file is part of vsc-filesystems,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),... |
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'account'
urlpatterns = [
url(r'^signup/$', views.signup, name='signup'),
url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'),
url(r'^login/$', auth_views.LoginView.as_view()... |
from distutils import log
from weaverbird.backends.sql_translator.steps.utils.query_transformation import (
build_selection_query,
get_query_for_date_extract,
)
from weaverbird.backends.sql_translator.types import (
SQLPipelineTranslator,
SQLQuery,
SQLQueryDescriber,
SQLQueryExecutor,
SQLQu... |
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
from moredata.enricher import Enricher, EnricherBuilder
from moredata.enricher.elasticsearch_connector import (
ElasticsearchConnector,
IndexHandler,
ReindexHandler,
Pipeline,
PipelineHandler,
PolicyHandler,
Policy,
)
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright INRIA
# Contributors: Wahiba Taouali (Wahiba.Taouali@inria.fr)
# Nicolas P. Rougier (Nicolas.Rougier@inria.fr)
#
# This software is governed by the CeCILL license under... |
from django import forms
from .models import Comment_To_Node, Comment_To_Edge #Node, Edge
from captcha.fields import ReCaptchaField
class CommentFormForNode(forms.ModelForm):
captcha = ReCaptchaField()
class Meta:
model = Comment_To_Node
fields = ('text',)
class CommentFormForEdge(forms.ModelF... |
#Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto
p = int(input("Qual o preço do produto? "))
d = p * 0.95
print ("O preço original deste produto é R$: {} com desconto de 5% você pagará R$: {}".format(p,d))
|
from __future__ import annotations
from tatsu.exceptions import CodegenError
from tatsu.codegen.cgbase import ( # noqa
DelegatingRenderingFormatter,
ModelRenderer,
NullModelRenderer,
CodeGenerator,
)
def codegen(model, target='python'):
if target.lower() == 'python':
from tatsu.codegen i... |
# syntactic parsing
from jsonrpclib.jsonrpc import ServerProxy
import requests
from tree_rules import *
import subprocess
import re
import os
class OpenNLP:
def __init__(self, host='localhost', port=8080):
uri = "http://%s:%d" % (host, port)
self.server = ServerProxy(uri)
def parse(self, text)... |
from esper import Processor, World
import script
from ecs.components.blinded import Blinded
from ecs.components.message import Message
from ecs.components.monster import Monster
class BlindedProcessor(Processor):
"""Handles the Blinded monster status effect."""
def process(self):
self.world: World
... |
# -*- coding: utf-8 -*-
def resort120(x,antenna_flagx):
d_f_copy3 = [[0 for i in range(360)] for j in range(181)] # 对三扇区天线水平方向系数重新排序
# 对三扇区天线水平方向系数重新排序
if antenna_flagx == 1: ## 120度天线
for j in range(120):
for i in range(181):
d_f_copy3[i][j] = x[i][j + 120] ## ... |
import sys
import subprocess
import os
import glob
import contextlib
from pathlib import Path
import fv3config
from .logs import handle_fv3_log
runfile = Path(__file__).parent.parent / "main.py"
@contextlib.contextmanager
def cwd(path):
cwd = os.getcwd()
os.chdir(path)
yield
os.chdir(cwd)
def find... |
zaimportuj unittest
zaimportuj gc
zaimportuj sys
zaimportuj weakref
z unittest.test.support zaimportuj LoggingResult, TestEquality
### Support code dla Test_TestSuite
################################################################
klasa Test(object):
klasa Foo(unittest.TestCase):
def test_1(self): dale... |
from thermidor import ClustererSocket
from sklearn.cluster import KMeans
from ..functions import labeled_data_joiner
class KMeansSocket(ClustererSocket):
'''Class which allows for passing `means_`
into `KMeans` from `GaussianMixtureModel`
[or any other object which has a `means_`
attribute].
... |
import os
from commitizen.cz.cz_base import BaseCommitizen
from whaaaaat import Validator, ValidationError
__all__ = ['JiraSmartCz']
class RequiredValidator(Validator):
def validate(self, document, *args, **kwargs):
if not document.text:
raise ValidationError(
message='This f... |
def benchmark_reversed_range():
import ubelt as ub
import pandas as pd
import timerit
import itertools as it
methods = []
def custom_reversed_range_v1(start, stop):
final = stop - 1
for idx in range(stop - start):
yield final - idx
def custom_reversed_range_v... |
from tkinter import *
from random import choice
from string import printable
class Interface(Frame):
def __init__(self, master):
super(Interface, self).__init__(master)
self.pack(expand = True)
self.body(None, 13)
def body(self, f , s):
self.header = Label(self, font ... |
# -*- coding: utf-8 -*-
"""
This file contains functions to detect fractures based on different features.
"""
import glob
import os
import matplotlib.pyplot as plt
import numpy as np
import preprocessing as pp
# directory where the audio fles reside
rawDataPath = os.path.join("..","rawData")
# extract all filename... |
"""
# Sumarry
- Syntax
- Frozen
- Optimizations
"""
from dataclasses import dataclass
from math import asin, cos, radians, sin, sqrt
## Syntax
@dataclass
class Position:
local:str
lat:float
lon:float
def distance_to(self, other):
r = 6371 # Earth radius in kilometers
lam_1, lam_2 = r... |
#!/usr/bin/env python
import os
import sys
# Add the project to the path
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
PROJECT_MODULE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
PROJECT_APPS_PATH = os.path.join(PROJECT_MODULE_PATH, 'ehb_service/apps')
PROJECT_ROOT, PROJECT_MOD... |
### This code is for comparing the performance of L2, L1 regularized
### RFSVM and KSVM.
import csv
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.kernel_approximation import RBFSampler
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import tr... |
#!/usr/bin/env python3
# (C) 2022 GoodData Corporation
from __future__ import annotations
import argparse
import fileinput
import re
from collections import OrderedDict
from datetime import date
from pathlib import Path
from typing import AnyStr, Pattern
COPYRIGHT_RE: re.Pattern[AnyStr] = re.compile(r"GoodData Corpor... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Address
admin.site.register(Address)
|
# Spotify API accessed via Spotipy library https://spotipy.readthedocs.io/en/2.19.0/
from crypt import methods
import os
import re
import sqlite3
import time
from urllib.request import HTTPBasicAuthHandler
import requests
import json
from flask import Flask, Response, flash, make_response, redirect, render_template, ... |
# -*- encoding: utf-8 -*-
#
#
# Copyright (C) 2002-2004 Jörg Lehmann <joergl@users.sourceforge.net>
# Copyright (C) 2003-2011 Michael Schindler <m-schindler@users.sourceforge.net>
# Copyright (C) 2002-2011 André Wobst <wobsta@users.sourceforge.net>
#
# This file is part of PyX (http://pyx.sourceforge.net/).
#
# PyX is ... |
from collections import OrderedDict
from datetime import datetime
import io
import json
import os
import shutil
import unicodecsv
import unittest
from sqlalchemy import Column
from sqlalchemy import Table
from sqlalchemy import types
from sqlalchemy import Unicode
from unittest import mock
import responses
import yaml... |
from flask import jsonify
import json
class SQLAlchemyService:
def __init__(self, db, model):
self.db = db
self.model = model
# Optional: validation before insert in db
# def _isinstance(self, obj, raise_error=True):
# rv = isinstance(obj, self.__model__)
# if... |
from collections import defaultdict
from utils.args import get_args
from utils.utils_graph import gen_adjacency_mat, get_degree_matrix, getER_vec
import os
import numpy as np
from utils.batcher.incar_batcher_sep_vocab_bert import InCarBatcher
from nltk.corpus import stopwords
import string
import torch
from unidecode i... |
import unittest
from datetime import datetime
from main import GitHubAnalyzer, AnalyseException
class TestDate(unittest.TestCase):
def test_correct_date(self):
self.assertEqual(GitHubAnalyzer.get_input_date_by_format('2020-10-10'), datetime(year=2020, month=10, day=10))
def test_wrong_date(self):
... |
from setuptools import setup, find_packages
setup(
name='lateral-py',
version='0.0.1',
description='python interface to Lateral\'s APIs',
url='https://github.com/lateral/lateral-py',
author='Christoph Schock',
author_email='christoph@lateral.io',
license='MIT',
packages=find_packages()... |
#!/usr/bin/env python3
from pytablewriter import MarkdownTableWriter
import subprocess
exit_code = subprocess.call("./get_versions.sh")
with open("docs/r_packages.txt", "r") as f:
r_pkg = [l.strip().split() for l in f.readlines()]
writer = MarkdownTableWriter()
writer.table_name = "Available R Packages"
writer... |
from flask import render_template
from . import MAIN
@MAIN.route('/')
def index():
'''
View root function that returns the index page
'''
return render_template('index.html')
|
import megaind as ind
import time
def flash_seq(n, delay=0.1, stack=0):
for i in range(n):
for j in range(4):
ind.setLed(stack, j + 1, 1)
time.sleep(delay)
for j in range(4):
ind.setLed(stack, j + 1, 0)
time.sleep(delay)
def flash(n, ... |
# -*- coding: utf-8 -*-
# author: https://github.com/Zfour
import json
import yaml
from bs4 import BeautifulSoup
from request_data import request
data_pool = []
def load_config():
f = open('_config.yml', 'r', encoding='utf-8')
ystr = f.read()
ymllist = yaml.load(ystr, Loader=yaml.FullLoader)
return... |
import sys
import os
import datetime
import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as colors
from matplotlib import dates
from pprint import pprint
import sqlite3
import calendar
from datetime import datetime
from datetime import timedelta
import ma... |
#
# PySNMP MIB module Unisphere-Data-Frame-Relay-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-Frame-Relay-CONF
# Produced by pysmi-0.3.4 at Mon Apr 29 21:24:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from ydb.public.api.protos import ydb_experimental_pb2 as ydb_dot_public_dot_api_dot_protos_dot_ydb__experimental__pb2
class ExperimentalServiceStub(object):
... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.db import models
from django.contrib.postgres.fields import JSONField
from django_extensions.db.fields import AutoSlugField
from mptt.models import MPTTModel, TreeForeignKey
from register.constants import RELATIONSHIPS
class TimestampedUserModel(m... |
import os
from os.path import isfile, join
import PIL
from PIL import Image
import tensorflow as tf
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from model.utils import ModelConfig
from preprocessing.utils import plot_batch
def crop_to_rectangular(image):
""" Crops longer dimension to ma... |
# ******************************************************************************
# Copyright 2017-2018 Intel Corporation
#
# 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.apa... |
import docstringtest
def test_docstringtest():
docstringtest.testModule(docstringtest)
|
from typing import Any, Callable, Generic, Optional
from fpylib.functors.functor import _S, _T
from fpylib.curring import currify
class Monad(Generic[_T]):
"""
This is a implementation of the Monad law:
- Unit or Return .
- Bind (>>=) or (>>) here.
"""
def __init__(self, value: Optional[_T] ... |
# https://stepik.org/lesson/2232/step/7?unit=929
# Sample Input 1:
# 480
# Sample Output 1:
# 8
# 0
# Sample Input 2:
# 512
# Sample Output 2:
# 8
# 32
total_minutes = int (input())
hours_to_sleep = total_minutes // 60
minutes_to_sleep = total_minutes % 60
print(hours_to_sleep)
print(minutes_to_sleep)
|
import typing
from typing_extensions import Literal
import pydantic
import stackprinter
stackprinter.set_excepthook(style="darkbg2")
from crypto_dom.definitions import TIMESTAMP_MS
from crypto_dom.binance.definitions import RECV_WINDOW, ASSET
# ============================================================
# USER UNI... |
from . import client, logger
|
__author__ = 'jtromo'
#Developed at : SEFCOM Labs by James Romo
#With assistance from : JJ SEO and Clinton Dsouza
from bluetooth import *
import threading
import time
from Crypto.Cipher import AES
import base64
import os
from math import *
# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SI... |
# Generated by Django 2.0 on 2017-12-17 12:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
opera... |
from unittest import TestCase
from {{cookiecutter.package_name}}.controllers.health_controller import HealthController
class TestHealthController(TestCase):
def setUp(self):
self.health_controller = HealthController()
def test_live_status(self):
self.assertEqual(self.health_controller.live()... |
from logging import ERROR
def test_mutate_empty(gitrepo):
assert gitrepo.repo.mutate() is True
def test_mutate_addition(gitrepo):
assert gitrepo.repo.status.clean is True
gitrepo.write('file', 'content')
status = gitrepo.repo.status
assert status.clean is False
assert 'file' in status.untr... |
import requests
from scrapy.selector import Selector
import MySQLdb
conn = MySQLdb.connect(host="127.0.0.1", user="root", passwd="", db="article_spider", charset="utf8")
curcor = conn.cursor()
def crawl_ips():
# 爬取西刺的免费代理
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537... |
from setuptools import setup
setup(
name='animalai_train',
version='1.0.5',
description='Animal AI competition training library',
url='https://github.com/beyretb/AnimalAI-Olympics',
author='Benjamin Beyret',
author_email='bb1010@ic.ac.uk',
classifiers=[
'Intended Audience :: Develo... |
import os
# This will set the value since it's not already set
os.environ.setdefault('UNSET_VAR', 'UNSET_VAR_VALUE')
# This value will not be set since it's already passed
# in from the command line
os.environ.setdefault('SET_VAR', 'SET_VAR_VALUE')
print('UNSET_VAR:' + os.environ.get('UNSET_VAR', ''))
print('SET_VA... |
from datetime import timedelta, datetime
from django.shortcuts import render, get_object_or_404, redirect
from django.core.urlresolvers import reverse
from django.http import Http404
from django.contrib import auth
from django.contrib import messages
from django.utils.translation import ugettext as _
from django.views... |
from ibis.backends.pyarrow.datatypes import to_pyarrow_type # noqa
|
from terra_sdk.client.lcd import LCDClient, PaginationOptions
terra = LCDClient(
url="https://bombay-lcd.terra.dev/",
chain_id="bombay-12",
)
pagOpt = PaginationOptions(limit=2, count_total=True)
def test_allowances():
result, _ = terra.feegrant.allowances(
"terra17lmam6zguazs5q5u6z5mmx76uj63gld... |
import os
import data.utils as data_utils
from data.custom_dataset_dataloader import CustomDatasetDataLoader
from data.class_aware_dataset_dataloader import ClassAwareDataLoader
from config.config import cfg
def prepare_data_CAN():
dataloaders = {}
train_transform = data_utils.get_transform(True)
test_tran... |
import os
import logging
from subprocess import list2cmdline
from vcp import VCP
from .message import Request, Response, MalformedMessageException
logger = logging.getLogger(__name__)
class CommandServer(object):
def __init__(self, absinthe_config):
self.__vcp = VCP()
self.__absinthe_config = absi... |
from django.db import models
import datetime
# Импортируем настройки приложения polls
from polls import settings
# Create your models here.
class Question(models.Model):
"""Вопрос"""
title = models.CharField(max_length=200, verbose_name="Вопрос")
date_published = models.DateTimeField(verbose_name="Дата пу... |
# General stuff:
import sys
import os
import numpy as np
import math
import pandas as pd
from datetime import date
from tqdm import tqdm_notebook
from scipy.stats import pearsonr
# Plotting:
from matplotlib import pyplot as plt
import seaborn as sns
import matplotlib.cm as cm
import matplotlib as mpl
def convert_size... |
#! /usr/bin/env python3
# encoding: utf-8
import sys
import logging
import asyncio
sys.path.insert(0, '../..')
from gs2d import SerialInterface, Futaba
# ログ設定
logging.basicConfig()
logging.getLogger('gs2d').setLevel(level=logging.DEBUG)
async def main(loop):
try:
# Initialize SerialInterface & servo ob... |
# This file is part of the NESi software.
#
# Copyright (c) 2020
# Original Software Design by Ilya Etingof <https://github.com/etingof>.
#
# Software adapted by inexio <https://github.com/inexio>.
# - Janis Groß <https://github.com/unkn0wn-user>
# - Philip Konrath <https://github.com/Connyko65>
# - Alexander Dincher <... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-29 23:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('engine', '0002_domain'),
]
operations = [
... |
import json
import os
import torch
from model import EncoderCNN, DecoderRNN
from torchvision import transforms
from data_loader import Dataset
from pycocotools.coco import COCO
def evaluate(args):
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.485, 0.45... |
from marshmallow import EXCLUDE, fields
from aries_cloudagent.messaging.agent_message import AgentMessage, AgentMessageSchema
from aries_cloudagent.messaging.models.base import BaseModel, BaseModelSchema
from ..message_types import PROTOCOL_PACKAGE, READ_DID
from ..utils.regex import MYDATA_DID
HANDLER_CLASS = (
... |
# Twisted Goodies:
# Miscellaneous add-ons and improvements to the separately maintained and
# licensed Twisted (TM) asynchronous framework. Permission to use the name was
# graciously granted by Twisted Matrix Laboratories, http://twistedmatrix.com.
#
# Copyright (C) 2006-2007 by Edwin A. Suominen, http://www.eepatent... |
"""
Utilities for downloading and unpacking the CelebA dataset, originally published
by Krizhevsky et al. and hosted here: https://www.cs.toronto.edu/~kriz/cifar.html
"""
import os
import sys
import tarfile
from six.moves import urllib
import numpy as np
import torch
from torchvision import datasets, tran... |
import os
from typing import Iterator, Tuple
from .._util import iterate_csv_file
# The data directory containing the hardware definitions
ROOT = os.path.split(__file__)[0]
def iterate_hardware() -> Iterator[Tuple[str, str, str]]:
"""
Iterates over the known hardware.
:return: An iterator over the g... |
# -*- coding: utf-8 -*-
def test_django_app(django_app):
resp = django_app.get('/')
assert resp.status_int == 200
def test_django_app_post(django_app_factory):
app = django_app_factory(csrf_checks=False)
resp = app.post('/')
assert resp.status_int == 200
|
#calculadora basica
a = 10
b = 5
suma = a+b
resta = a-b
multiplicacion = a*b
division = a/b
print (suma)
print (resta)
print (multiplicacion)
print (division)
|
def digit_to_text(digit):
if digit == 1:
return "one"
elif digit == 2:
return "two"
elif digit == 3:
return "three"
elif digit == 4:
return "four"
elif digit == 5:
return "five"
elif digit == 6:
return "six"
elif digit == 7:
return "sev... |
import inspect, os
hiclibfolder = os.path.dirname(os.path.abspath(
os.path.join(inspect.getfile(inspect.currentframe()),
'../../')))
|
from converter.qiskit import Gate
from converter.qiskit import QuantumCircuit
from converter.qiskit._instructionset import InstructionSet
from converter.qiskit._quantumregister import QuantumRegister
class U0Gate(Gate):
pass
def __init__(self, m, qubit, circ=None):
pass
def inverse(self):
... |
import os
PORT = 8080
|
#TO RUN: joey2 project_create_tests.py
# OR TO RUN SPECIFIC METHODS:
# joey2 -m unittest project_tests.TestProjectCreate.test_create_project_via_package_xml_file
# joey2 -m unittest project_tests.TestProjectCreate.test_create_project_via_package_dict
import sys
import os
import unittest
import shutil
import requests
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.