text stringlengths 2 999k |
|---|
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# mac 下操作MySQL: https://www.jianshu.com/p/b13f99cbdf55
# python mysql 操作: https://www.runoob.com/python/python-mysql.html
# 操作相关表: employeeTable
import mysql.connector
# 打开数据库连接 (根据自己的用户名、密码及数据库名称进行修改)
mysqlDB = mysql.connector.connect(user="root", passwd="12345678", databa... |
import asyncio
import os
import platform
import socket
import ssl
import tempfile
from dataclasses import dataclass
from operator import attrgetter
import aiohttp
import aiohttp.client_exceptions
import pytest
import trustme
import urllib3
import urllib3.exceptions
from OpenSSL.crypto import X509
import truststore
#... |
import warnings
import numpy as np
import pandas as pd
import pandas.util.testing as tm
import pytest
from pytest import param
import ibis
import ibis.expr.datatypes as dt
from ibis.backends.pandas.execution.temporal import day_name
from ibis.tests.backends import (
BigQuery,
Clickhouse,
Csv,
Impala,
... |
# coding: utf-8
from django.db import models
from django.utils import timezone
from chisch.common.models import BaseModel
from .cores import VerifyManager, VerifyStatisticManager
_verify_manager = VerifyManager()
_verify_statistic_manager = VerifyStatisticManager()
class VerifyCode(BaseModel, models.Model):
u... |
# Copyright 2016 The Gemmlowp Authors. 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
# Generated by Django 2.1.2 on 2018-11-14 11:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('countries', '0002_auto_20181106_0840'),
]
operations = [
migrations.AlterField(
model_name='country',
name='flag',
... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: model.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf ... |
'''
https://projecteuler.net/problem=601
'''
import functools
import logging
import math
import pathlib
import textwrap
logger = logging.getLogger(__spec__.name)
def main(argv):
setup_logging(argv)
description = textwrap.dedent(solve.__doc__)
print(description)
logger.info(description)
solution = solve()
s... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from functools import reduce
def add(x,y):
return x+y
class Perceptron(object):
'''
Desc:
感知器类
Args:
None
Returns:
None
'''
def __init__(self,input_num,activator):
'''
Desc:
... |
from bs4 import BeautifulSoup
from multiprocessing.dummy import Pool
import os
import shutil
import time
import requests
import re
import json
import glob
BASE_URL = 'http://www.winemag.com/?s=&drink_type=wine&page={0}'
session = requests.Session()
HEADERS = {
'user-agent': ('Mozilla/5.0 (Windows NT 6.1; WOW64) A... |
# 99
# Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar todos os valores e dizer qual deles é o maior.
from time import sleep
def linha():
print('-=' * 20)
print()
def maior(* num):
cont = maior = 0
print('An... |
# 1.单链表的插入、删除、查找操作;
# 2.链表中存储的数据类型是Int
#
# Author:Lee
class Node():
'''链表结构的Node节点'''
def __init__(self, data, next=None):
'''Node节点的初始化方法.
参数:
data:存储的数据
next:下一个Node节点的引用地址
'''
self.__data = data
self.__next = next
@property
def data(s... |
from django import forms
from .models import Comment
class EmailPostForm(forms.Form):
name = forms.CharField(max_length=25)
email = forms.EmailField()
to = forms.EmailField()
comments = forms.CharField(required=False, widget=forms.Textarea)
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fie... |
import tkinter as tk
win = tk.Tk()
win.title("C语言中文网")
win.geometry('400x350+200+200')
win.iconbitmap('C:/Users/Administrator/Desktop/C语言中文网logo.ico')
win.rowconfigure(1, weight=1)
win.columnconfigure(0, weight=1)
# 左侧的frame
frame_left = tk.LabelFrame(win, bg='red')
tk.Label(frame_left, text='左侧标签1', bg='green', widt... |
"""App services"""
|
"""
Overall representation of PWSCF calc
"""
import os
import sys
import shutil
from pymatflow.qe.base.control import QeControl
from pymatflow.qe.base.system import QeSystem
from pymatflow.qe.base.electrons import QeElectrons
from pymatflow.qe.base.ions import QeIons
from pymatflow.qe.base.cell import QeCel... |
# This file should be in ~/.ipython/profile_default/ipython_config.py
c = get_config()
# Auto reload modules when changed
# Ref: http://stackoverflow.com/questions/5364050
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Midokura Japan K.K.
# Copyright (C) 2013 Midokura PTE LTD
# 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. You may obtain
# a copy of th... |
"""
Implementation of a standard financial plot visualization using Chaco
renderers and scales.
"""
# Major library imports
from numpy import abs, arange, cumprod, random
# Enthought library imports
from enable.api import Component, ComponentEditor
from traits.api import HasTraits, Instance
from traitsui.api import I... |
# ------------------------------------------------------------------------
# Solve 1-D PDE
# -u'' = lambda*u
# on [0,1] subject to
# u(0)=0, u'(1)=u(1)*lambda*kappa/(kappa-lambda)
# ------------------------------------------------------------------------
import sys, slepc4py
slepc4py.init(sys... |
import math
from math import pi
import numpy as np
from gym.spaces import Box, Discrete
from ray.rllib.utils import merge_dicts
from ray.rllib.env.multi_agent_env import MultiAgentEnv
def direction_to_coord(direction):
"""takes x \in [0,1), returns 2d coords on unit circle"""
return tuple([math.cos(2*pi*direc... |
# -*- coding: utf-8 -*-
# Waveshare PN532 NFC Hat control library.
# Author: Yehui from Waveshare
#
# The MIT License (MIT)
#
# Copyright (c) 2015-2018 Adafruit Industries
# Copyright (c) 2019 Waveshare
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated do... |
#!/usr/bin/env python
import sys
import logging
from cryptography.hazmat import backends
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import constant_time
from cryptography import x509
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitive... |
# Generated by Django 3.2.3 on 2021-05-20 07:51
from django.db import migrations
import home.RichTextBleachField
class Migration(migrations.Migration):
dependencies = [
('home', '0018_add_tags_test_data'),
]
operations = [
migrations.AlterField(
model_name='question',
... |
# Generated by Django 2.2.1 on 2019-06-11 10:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("sepa", "0002_auto_20171013_1436")]
operations = [
migrations.AddField(
model_name="membersepa",
name="mandate_state",
... |
import os
from easydict import EasyDict
# architecture
from basicts.archs.Stat_arch import AutoRegressive, VectorAutoRegression
# runner
from basicts.runners.Stat_runner import StatRunner
from basicts.data.base_dataset import BaseDataset
from basicts.metrics.mae import masked_mae
from basicts.metrics.mape import maske... |
import os
import shutil
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import SingleLetterAlphabet
from installed_clients.DataFileUtilClient import DataFileUtil
class AssemblyToFasta:
def __init__(self, callback_url, scratch):
self.scratch = scratch
... |
# -*- coding: utf-8 -*-
import codecs
import os
import shutil
import sys
import time
from seleniumbase.config import settings
from seleniumbase.fixtures import constants
def log_screenshot(test_logpath, driver, screenshot=None, get=False):
screenshot_name = settings.SCREENSHOT_NAME
screenshot_path = "%s/%s" %... |
# -*- coding: utf-8 -*-
import unittest
import os # noqa: F401
import json # noqa: F401
import time
import requests
import shutil
from os import environ
try:
from ConfigParser import ConfigParser # py2
except:
from configparser import ConfigParser # py3
from pprint import pprint # noqa: F401
from biokba... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
if not preorder:
return None
root = TreeNode(pre... |
import os
import sys
import setuptools
from setuptools import Extension
from setuptools.command.build_py import build_py as _build_py
import distutils.dir_util
import distutils.log
class build_py(_build_py):
def run(self):
self.run_command("build_ext")
return super().run()
kaldi_root = os.getenv('... |
from typing import Optional
from .factory import AppFactory
from .pattern.matcher import Matcher
from .util import json
matchers = {p.__name__.lower(): m for p, m in Matcher.all().items()}
def detect_patterns(input_path: str, output_path: Optional[str] = None,
patterns: Optional[str] = None) -> ... |
animal = input()
if animal == "dog":
print("mammal")
elif animal == "crocodile" or animal == "tortoise" or animal == "snake":
print("reptile")
else:
print("unknown") |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010, 2013, 2degrees Limited.
# All Rights Reserved.
#
# This file is part of django-pastedeploy-settings
# <https://github.com/2degrees/django-pastedeploy-settings>, which is subject
# to the provis... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2018-12-20 20:00
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... |
from setuptools import setup, find_packages
import pySmartDL
extra = {}
release_posttag = ""
setup(
name='pySmartDL',
version=pySmartDL.__version__ + release_posttag,
url='http://pypi.python.org/pypi/pySmartDL/',
author='Itay Brandes',
author_email='brandes.itay+pysmartdl@gmail.com',
license='... |
from cerulean import PasswordCredential, PubKeyCredential
from cerulean import SshTerminal
def test_password() -> None:
cred = PasswordCredential('cerulean', 'kingfisher')
with SshTerminal('cerulean-test-ssh', 22, cred):
pass
def test_pubkey() -> None:
cred = PubKeyCredential('cerulean', '/home/... |
"""Provides functions useful for background services."""
"""Copyright and License.
Copyright 2012-2014 Gregory Holt
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/license... |
import gprpy.gprpy as gp
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import os
import matplotlib.image as im
from scipy import signal
def showSplash(a,dir_path,widfac,highfac,fontfac):
'''
Creates the... |
"""
Base class of the tabular explainer
"""
from abc import ABC, abstractmethod
import numpy as np
from sklearn.preprocessing import StandardScaler
from faster_lime.utils import dict_disc_to_bin
class BaseTabularExplainer(ABC):
def __init__(self, training_data, feature_names=None,
categorica... |
from opentrons import protocol_api
import json
import os
import math
# metadata
metadata = {
'protocolName': 'Version 1 S14 Station C Viasure P20 Multi',
'author': 'Nick <protocols@opentrons.com>',
'source': 'Custom Protocol Request',
'apiLevel': '2.3'
}
NUM_SAMPLES = 8 # start with 8 samples, slowly... |
# Copyright 2018 Changan Wang
# 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 writing, so... |
# -*- coding: utf-8 -*-
# Author : 怕你呀
# Time : 2021/4/24
# File : main_page
# IDE : PyCharm
from appium.webdriver.common.mobileby import MobileBy
from app_test.page.base_page import BasePage
from app_test.page.calendar_page import CalendarPage
class MainPage(BasePage):
__by_calendar_lo = (Mob... |
import cv2
import os
path_name = "inconspicuous_folder"
def CreateDirectory():
global path_name
try:
os.mkdir(path_name)
except FileExistsError:
print("Directory already exists")
except OSError:
print("Creation of the directory %s failed" % path_name)
else:
print("Successfully created the direct... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Launching of programs, folders, URLs, etc.."""
from __future__ import print_function, unicode_literals, absolute_import
import sys
import os
import subprocess
import copy
import re
from .lnp import lnp
from . import hacks, paths, log, terminal
def toggle_autoclose():
... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ..base import CommandLineDtitk
def test_CommandLineDtitk_inputs():
input_map = dict(
args=dict(
argstr="%s",
),
environ=dict(
nohash=True,
usedefault=True,
),
)
inputs = CommandLi... |
# Copyright 2021 AI Singapore
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
import Adafruit_DHT
import logging
logger = logging.getLogger("Temperature")
class Temperature(object):
def __init__(self, config):
self.config = config
self.pin = self.config.get("temp_sensor")
self.sensor = Adafruit_DHT.DHT11
def set_sensor(self):
logger.info(f"Temperature ... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.16
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
from diff_highlighter.constants import (
FORMAT_ADD,
FORMAT_INVERT,
FORMAT_REMOVE,
FORMAT_RESET,
FORMAT_RESET_INVERT,
)
from diff_highlighter.main import main
def check(input_lines, expected_lines):
input_lines = [
line.format(
add=FORMAT_ADD,
remove=FORMAT_REMO... |
#!/usr/bin/env python3
# Copyright (c) 2015-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test node responses to invalid transactions.
In this test we connect to one node over p2p, and test tx... |
# Copyright 2018 Capital One Services, LLC
#
# 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... |
import pyodbc
try:
connect = pyodbc.connect(r'Driver= {Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=C:\Users\HP\PycharmProjects\pythonProject5\Database2.accdb')
print("Connected to a Database")
user_id = 10
record = connect.cursor()
record.execute('DELETE from Table1 WHERE id = ?',(user_... |
# ===============================================================================
# Copyright 2013 Jake Ross
#
# 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/licens... |
from distutils.core import setup
setup(
name = 'pyPheWAS',
packages = ['pyPheWAS'], # this must be the same as the name above
version = '4.0.3',
description = 'MASI Lab Port of PheWAS into Python',
author = 'MASI Lab',
author_email = 'bennett.landman@vanderbilt.edu',
url = 'https://github.com/MASILab/pyP... |
import psycopg2
from psycopg2.extras import DictCursor, execute_values
import os
from dotenv import load_dotenv
import json
import pandas as pd
load_dotenv('../../.env')
DB_HOST = os.getenv("DB_HOST", default="Hey hey DB HOST pls")
DB_USER = os.getenv("DB_USER", default="Hey hey DB USER pls")
DB_NAME = os.getenv("DB... |
# Copyright (c) 2012-2013 Craig Barnes
# Copyright (c) 2012 roger
# Copyright (c) 2012, 2014 Tycho Andersen
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2014 Adi Sieker
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"... |
# Copyright (c) 2019 PaddlePaddle Authors. 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Implementation of Sven Jandura's swap mapper submission for the 2018 QISKit
Developer Challenge, adapted to integrate int... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Alert.status'
db.add_column('sentry_alert', 'status',
self.gf('django.... |
# PyAlgoTrade
#
# Copyright 2011-2018 Gabriel Martin Becedillas Ruiz
#
# 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 ap... |
#!/usr/bin/env python3
from __future__ import annotations
import unittest
import torch
from linear_operator.operators import (
AddedDiagLinearOperator,
DenseLinearOperator,
DiagLinearOperator,
RootLinearOperator,
)
from linear_operator.test.linear_operator_test_case import LinearOperatorTestCase
c... |
from transitions import Machine
class Bot_transition(object):
states = ['start', 'new', 'english', 'russian', 'method_english', 'method_russian']
def __init__(self):
self.machine = Machine(model=self, states=Bot_transition.states, initial='start')
self.machine.add_transition(trigger='english... |
import unittest2
import threading
import itertools
from nose.tools import *
from gutter.client.arguments import Container as BaseArgument
from gutter.client import arguments
from gutter.client.models import Switch, Manager, Condition
from durabledict import MemoryDict
from durabledict.base import DurableDict
from gutt... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 1 16:04:54 2019
@author: Purnendu Mishra
"""
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
##********************************************************
## For GPU
#
config = tf.ConfigProto()
config.gpu_options.al... |
from .. import utils
from . import fmt
from . import utils as det_utils
incorrect_light_1569_message = 'Object "{0}" has incorrect light format: ' \
'"Builds 1096-1558". Must be "Builds 1569-CoP"'
incorrect_light_1096_message = 'Object "{0}" has incorrect light format: ' \
'"Builds 1569-CoP". Must be "Builds... |
"""
This is for testing the pypesto.History.
"""
import numpy as np
import pytest
import unittest
import tempfile
from typing import Sequence
import pypesto
from pypesto.objective.util import sres_to_schi2, res_to_chi2
from pypesto import CsvHistory, HistoryOptions, MemoryHistory, ObjectiveBase
from pypesto.optimize.... |
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/LICENSE
"""
Astroid hook for the dataclasses library
"""
import astroid
from astroid import MANAGER
DATACLASSES_DECORATORS = frozenset(("dataclasses.dataclass", "dataclass"... |
from cattle.type_manager import register_type, LIFECYCLE
from .console_agent import ConsoleAgent
register_type(LIFECYCLE, ConsoleAgent())
|
import graphene
import pytest
from ....discount.models import Sale, Voucher
from ...tests.utils import get_graphql_content
@pytest.fixture
def sale_list():
sale_1 = Sale.objects.create(name="Sale 1", value=5)
sale_2 = Sale.objects.create(name="Sale 2", value=5)
sale_3 = Sale.objects.create(name="Sale 3",... |
from ptrlib import *
def send_data(size, data, i):
payload = p32(size)
payload += p32(i)
payload += data
sock.send(payload)
print(payload)
return sock.recv()
def send_login(username, password):
payload = bytes([len(username)])
payload += bytes([len(password)])
payload += username
... |
# Generated by Django 3.1.2 on 2020-10-15 22:50
from django.db import migrations, models
import employment_agent.helpers
class Migration(migrations.Migration):
dependencies = [
('employment_agent', '0005_auto_20201015_2249'),
]
operations = [
migrations.RemoveField(
model_na... |
from telethon.sync import events
from plugins.base import Telegram, PluginMount
class GetAllChats(Telegram, metaclass=PluginMount):
command_name = 'get_all_chats'
def __call__(self):
async def _get_all_chats(self):
async for dialog in self._client.iter_dialogs():
self._log... |
# Copyright (c) 2019 Uber Technologies, Inc.
#
# 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... |
RAWDATA_DIR = '/staging/as/skchoudh/re-ribo-datasets/TryBruApr2005chr11/'
OUT_DIR = '/staging/as/skchoudh/re-ribo-analysis/TryBruApr2005chr11/'
GENOME_FASTA = '/home/cmb-06/as/skchoudh/genomes/TryBru_Apr2005_chr11/fasta/Trypanosoma_brucei.TryBru_Apr2005_chr11.dna.toplevel.fa'
CHROM_SIZES = '/home/cmb-06/as/skchoudh/gen... |
# coding: utf-8
import collections
import onnx
from onnx import helper
from onnx import TensorProto
import chainer
from chainer import functions as F
import numpy as np
from chainer_compiler.ch2o import array_devices
from chainer_compiler.ch2o import utils
from chainer_compiler.ch2o.env import Env
from chainer_compi... |
# -*- coding: utf-8 -*-
# Created by restran on 2016/11/30
from __future__ import unicode_literals, absolute_import
|
#!/usr/bin/env python
# --coding:utf-8--
# Copyright (c) 2020 vesoft inc. All rights reserved.
#
# This source code is licensed under Apache 2.0 License,
# attached with Common Clause Condition 1.0, found in the LICENSES directory.
import socket
from nebula2_fork.Exception import InValidHostname
from nebula2_fork.s... |
from django.contrib import admin
from .models import *
class OperationInline(admin.TabularInline):
model = Operation
extra = 0
class AgentAdmin(admin.ModelAdmin):
inlines = [
OperationInline,
]
class RequestConditionInline(admin.TabularInline):
model = RequestCondition
extra = 0
... |
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# --------------------------------------------... |
#!/usr/bin/env python
# save office air quality data into a mysql database
#
# Xiaoke Yang (das.xiaoke@hotmail.com)
# IFFPC, Beihang University
# Last Modified: Mon 16 Jan 2017 16:26:49 CST
import pymysql
import paho.mqtt.client as mqtt
from datetime import date
import time
# mysql database information
MYSQL_HOST_A... |
import sys
TEMPLATE="""
#include <yql/udfs/common/python/python_udf/python_udf.h>
#include <yql/library/udf/udf_registrator.h>
using namespace NKikimr::NUdf;
#ifdef BUILD_UDF
extern "C" UDF_API void Register(IRegistrator& registrator, ui32 flags)
{
RegisterYqlPythonUdf(registrator, flags, STRINGBUF("@MODULE_NA... |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet."""
from decimal import Decimal
from itertools import product
from test_framework.test... |
symmetry = 6
angle = 360 / symmetry
x_off = 0
def setup():
size(600, 600)
background(51)
colorMode(HSB, 360, 100, 100, 100)
def draw():
global x_off
translate(width/2, height/2)
if mouseX > 0 and mouseX < width and mouseY > 0 and mouseY < height:
mx = mouseX - width ... |
bind = "0.0.0.0:8080"
workers = 4
threads = 4
logfile = "-"
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Tiantian
"""
from re import T
import pandas as pd
import torch
import torch.nn as nn
import math
from torch.autograd import Variable
from torch.nn import functional as F
import pdb
import logging
from torch.nn.modules import dropout
import itertools
class On... |
import numpy as np
import pytest
import pandas as pd
from pandas import DataFrame, Index, MultiIndex, Series
import pandas._testing as tm
from pandas.core.indexing import IndexingError
@pytest.fixture
def single_level_multiindex():
"""single level MultiIndex"""
return MultiIndex(
levels=[["foo", "bar... |
# Copyright BigchainDB GmbH and BigchainDB contributors
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0
from copy import deepcopy
import pytest
import pymongo
from bigchaindb.backend import connect, query
pytestmark = pytest.mark.bdb
def test_get_txids_filtered(s... |
from .scrapers import * |
#
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 26 19:22:20 2015
@author: marco musy
"""
def nameof(n):
a = n.name+str(n.octave)
if "-" in a:
b = a.replace("C-","B")
b = b.replace("D-","C#")
b = b.replace("E-","D#")
b = b.replace("F-","E")
b = b.replace("G-","F#")
... |
from math import prod
import pytest
from src.day09.day09 import Map, Point
DEMO_MAP = [
[2, 1, 9, 9, 9, 4, 3, 2, 1, 0],
[3, 9, 8, 7, 8, 9, 4, 9, 2, 1],
[9, 8, 5, 6, 7, 8, 9, 8, 9, 2],
[8, 7, 6, 7, 8, 9, 6, 7, 8, 9],
[9, 8, 9, 9, 9, 6, 5, 6, 7, 8],
]
RAW_MAP = """2199943210
3987894921
9856789892
... |
import numpy as np
class __TableQuery:
def __init__(self):
read_file = lambda file_name: np.genfromtxt(file_name, dtype=str, delimiter=',', skip_header=1)
self.character_capacity = read_file('./tables/CharacterCapacity.txt')
self.codeword_info = read_file('./tables/CodewordInfo.txt')
... |
#!/usr/bin/python
import sys
previous = None
suma = 0.0
num = 1
for line in sys.stdin:
key, value = line.split('\t')
if key != previous:
if previous is not None:
media = suma / num
num = 0
print(previous + "\t" + str(media))
previous = key
suma = 0.0
suma = suma + float(value)
num = num + 1
medi... |
#coding=utf-8
#author@shibin
#2016.04.21
import os
class Session(object):
"""Session is a connect for the http user"""
def __init__(self,user,host):
self._user = user
self._host = host
local_ssh_path =
local_ssh_file = 'id_rsa'
public_path = '/home/{}/.ssh/id_rsa.p... |
"""
HyperOne
HyperOne API # noqa: E501
The version of the OpenAPI document: 0.1.0
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import h1
from h1.model.networking_rule import NetworkingRule
class TestNetworkingRule(unittest.TestCase):
"""NetworkingRule unit test... |
import pandas as pd
import json
import re
import numpy as np
import pickle
from config import *
def count_datasets(date: str):
if date not in os.listdir(EXCEL_PATH):
raise("No folder " + date + " in the " + EXCEL_PATH + ". No eval results calculated.")
# get res json
f = None
for f in os.list... |
# -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE... |
from sim.link import Link
from sim.server import Server
from sim.task import Task,TaskPattern
# Base system
# Display info
DEBUG=True
# Name of the configuration
NAME="WiFi Bandwidth 25Mb/s"
# Cloud added latency
cd=7.5
#Links
d2dlink=Link("D2D",50000000., 1.75, 50000000., 1.75)
ltelink=Link("LTE",30000000., 9.95,... |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
# Copyright 2019-2020 Fortinet, Inc.
#
# This program 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 the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.