content stringlengths 5 1.05M |
|---|
# Generated by Django 2.0.5 on 2018-05-31 08:06
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_ethereum_events', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Monitored... |
#Server dependencies
import json
import requests
import urllib
from uuid import uuid4
from bottle import Bottle, route, run, template, request
class Coursera:
def __init__(self,access_token):
self.enrollments_url = "https://api.coursera.org/api/users/v1/me/enrollments"
self.auth_headers = {'Author... |
#===========================================================================================
# pretvorbe temperature (najprej v osnovno enoto kelvin, nato iz osnovne v iskano enoto)
def osnovna_temperatura(stevilo, enota):
if enota == 'kelvin' :
return stevilo
elif enota == 'fahrenheit':
retu... |
from design_bench.disk_resource import DiskResource
import numpy as np
import abc
def default_uniform_distribution(ranks):
"""Accepts the rank of a set of designs as input and returns an
un-normalized uniform probability distribution
Arguments:
ranks: np.ndarray
a numpy array representing th... |
from cuser.admin import UserAdmin
from django.contrib import admin
# from hijack_admin.admin import HijackUserAdminMixin
from backend.auth.models import User
# TODO: fully install the hijacking functionality
# see here: https://django-hijack.readthedocs.io/en/stable/#after-installing
# class CustomUserAdmin(UserA... |
import discord
from discord.ext import commands
import DiscordUtils
music = DiscordUtils.Music()
class Music(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def join(self, ctx):
if ctx.guild.voice_client is None:
await ctx.author... |
even_squares = [x**2 for x in range(1,11) if x%2 == 0 ]
print even_squares
|
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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... |
def Main():
"""
:return:
"""
a = 1
b = True
c = True
if a and c and b:
return 8
return 3
|
def validate_full_term_is_acronym(data):
""" Validate full term exists if is_acronym and is_acronym is not False """
full_term = data.data.full_term
is_acronym = data.data.is_acronym
if full_term and not is_acronym:
return ('Please set is_acronym to true'
' or full_term to null'... |
from isharp.datahub.broker_client.remote_proxy import BrokerConnectionPool
from flask import Flask, render_template
import os
import socket
import json
hostname=socket.gethostname()
from flask import request
templates_dir = os.getenv('isharp_web_templates', 'templates')
static_dir = os.getenv('isharp_web_static', '... |
from ._only import only
from ._skip import skip
from ._skipper import Skipper
__all__ = ("Skipper", "only", "skip",)
|
import time
from lib.client import Client, get_api_path
client = Client(access_key='w1xbUls4U3siMljMx6RLjQTvFNTJ4C3BY0Hw8f5D', secret_key='aDJy2NWOIyj5UiDlxXxXpcmxlW9xXQnGzT9IKfhH')
#demo of GET APIs
#get member info
print(client.get(get_api_path('members')))
#get markets
markets = client.get(get_api_path('markets... |
n1 = float(input("Quanto dinheiro você tem na carteira: R$"))
print("Com R${:.2f} você pode comprar US${:.2f} Dolares." .format(n1,n1 / 5.07)) |
'''
__author__ = "Rodrigo Sobral"
__copyright__ = "Copyright 2021, Rodrigo Sobral"
__credits__ = ["Rodrigo Sobral"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Rodrigo Sobral"
__email__ = "rodrigosobral@sapo.pt"
__status__ = "Beta"
'''
import discord, datetime
from doten... |
#!/usr/bin/env python
#
# See top-level LICENSE file for Copyright information
#
# -*- coding: utf-8 -*-
"""
This script runs PypeIt on a set of MultiSlit images
"""
def parse_args(options=None, return_parser=False):
import argparse
parser = argparse.ArgumentParser(description='Script to run PypeIt in QuickLo... |
from django.conf.urls import include, url
from bev_reverse_geocoder_api.views import index, reverse_geocode
# from django.contrib import admin
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^reverse-geocode/(?P<format>\w+)$', reverse_geocode, name='reverse_geocode'),
]
|
blackjack_pays = 3/2
hands_played = 5 #to know when to shuffle
#Blackjack game logic
import classes
from functions import display_players_cards
from functions import get_players_bet
from functions import clear
if __name__ == "__main__":
#Define player and dealer
player_name = input("Welcome to Blackjack... |
from app import db
class Stats(db.Model):
"""An Anki statistics object
"""
__tablename__ = 'stats'
# s_id : unique row id
s_id = db.Column(db.Integer, primary_key=True)
# timestamp : UNIX Epoch
timestamp = db.Column(db.Integer)
# vocab : number of vocabulary notes
vocab = db.Colum... |
# flake8: noqa
from . import _pybullet as pybullet
from ._pybullet import PybulletRobotInterface
try:
from .ros import PandaROSRobotInterface
except ImportError:
pass
try:
from .ros import PR2ROSRobotInterface
except ImportError:
pass
|
num1 = 11
num4 = 44
num2 = 22
num3 = 33
num5 = 555
|
import pickle
from datetime import datetime
import numpy as np
import pandas as pd
import xarray as xr
import yaml
from vmodel.util.util import clean_attrs
def generate_filename(args):
# Construct output file name
time_str = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
fnamedict = {
'agents': a... |
'''OpenGL extension NV.vertex_program4
This module customises the behaviour of the
OpenGL.raw.GL.NV.vertex_program4 to provide a more
Python-friendly API
Overview (from the spec)
This extension builds on the common assembly instruction set
infrastructure provided by NV_gpu_program4, adding vertex program-specif... |
import x16rt_hash
from binascii import hexlify, unhexlify
# Block 5000 (ce9e64ee2f9832f9ff6a8b042d0aa66f2e0aca6e8a5958051c141f27b5e68a3b)
blockheader_str = '0000002049963e9e46701e28e2dd44f61dea241ba3a457979fa3b378822c6cc24457bc2500a0da644814e2a43cc163f3f37590982e1e2f5ac45d1de2f8222750fea1c844f8d2315c824d111b120979e300... |
# Solution of;
# Project Euler Problem 666: Polymorphic Bacteria
# https://projecteuler.net/problem=666
#
# Members of a species of bacteria occur in two different types: $\alpha$ and
# $\beta$. Individual bacteria are capable of multiplying and mutating between
# the types according to the following rules:Every min... |
"""
[2017-08-7] Challenge #326 [Easy] Nearest Prime Numbers
https://www.reddit.com/r/dailyprogrammer/comments/6s70oh/2017087_challenge_326_easy_nearest_prime_numbers/
# Description
A prime number is any integer greater than 1 which can only be evenly divided by 1 or itself. For this challenge, you
will output two num... |
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.urls import path, reverse
from django.utils.translation import gettext_lazy as _
fro... |
import asyncio
import json
import logging
import os
import socket
from datetime import datetime
from tkinter import messagebox
import anyio
import async_timeout
from dotenv import load_dotenv
import gui
from config import HISTORY_FILE, HOST, READ_PORT, WRITE_PORT
from connection import open_asyncio_connection
from he... |
"""
WSGI config for foobar project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
# If a 'settings_local' file is present, use it
try:
from dpaste.settings import loc... |
import time
from unittest import TestCase
import numpy as np
from algorithms.utils.algo_utils import EPS
from utils.decay import LinearDecay
from utils.tensorboard import image_summary
from utils.timing import Timing
from utils.utils import numpy_all_the_way, numpy_flatten, max_with_idx, min_with_idx
class TestDeca... |
import sys
n, m = sys.stdin.readline().split(' ')
n = int(n)
m = int(m)
print(6 * (n * m) \
- 2 * (m - 1) * n \
- 1 * (n - 1) * m)
|
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
import pandas as pd
from process_data import DataLabels
def plot_features_vs_target(file_name, features, target, save_tag='features_vs_target'):
data = pd.read_csv(file_name)
fig = plt.figure(figsize=(7.0, 7.0))
for i in range(len(featur... |
# Copyright (c) 2014 Johan Burke
# Distributed under the MIT software license. See http://www.opensource.org/licenses/mit-license.php.
from threading import *
import socket
from ..constants import *
from .threadutils import *
from ..config import *
from struct import pack, unpack
class SenderThread(Thread):
def ... |
import dataclasses
from typing import TYPE_CHECKING
import valohai_yaml
from papi import YAMLContext
from papi.base import PapiObject
from papi.contexts import APIContext
if TYPE_CHECKING:
from papi.nodes import Node
@dataclasses.dataclass(frozen=True)
class Edge(PapiObject):
source_node: str
source_ty... |
"""Implementation of basic binay tree"""
from node import Node
def main():
"""Main function of BasicBinary Tree Modual"""
root = Node(1)
root.left = Node(2)
root.right = Node(3)
print(root.data)
print(root.left.data)
print(root.right.data)
if __name__ == '__main__':
main()
|
import pandas as pd
from pandas import DataFrame as df
import numpy as np
import os
inputfile_dir='./inputfile'
outputfile='all2.csv'
for inputfile in os.listdir(inputfile_dir):
inputfile1=os.path.join("./inputfile",inputfile)
df = pd.read_csv(inputfile1)
df.to_csv(outputfile,index=False, heade... |
from visionpy.abi import vs_abi
def test_abi_encode():
assert (
vs_abi.encode_single("address", "VYKDHeQfG38C62Xo8tHLrGWiw5o9hL3QEK").hex()
== '000000000000000000000000ed89ea86dcc4ab17e7b803de95571e259a935774'
)
assert vs_abi.encode_single("(address,uint256)", ["VYKDHeQfG38C62Xo8tHLrGWiw5... |
from flask import request, jsonify
from helper import as_dict
from helper.user_helper import UserCrudHandler
from models.user import User
handler = UserCrudHandler(User)
class UserApiExtension:
def __init__(self, app):
if app is not None:
self.init_app(app)
@staticmethod
def init_ap... |
# By Mostapha Sadeghipour Roudsari
# Sadeghipour@gmail.com
# Honeybee started by Mostapha Sadeghipour Roudsari is licensed
# under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
"""
False Color
-
Provided by Honeybee 0.0.55
Args:
_HDRFilePath: Path to an HDR image file
legendU... |
#python 3.7
"""
Stores all file config information and some configuration info about input files (which prevents hard coding in code).
"""
import pathlib
import ruamel.yaml
data_folder = pathlib.Path(".").absolute().parent / 'data'
data_clean_folder = data_folder / 'gps_data_clean'
time_dist_folder = data_folder / 't... |
import datetime
import numpy as np
import os
import scipy.stats
import sklearn.decomposition
import xml.etree.ElementTree as ET
class StatCollector():
def __init__(self, bip_instance, generated_indices, observed_indices):
self.generated_indices = generated_indices
self.observed_indices = observed_i... |
import json
from waldur_core.core.features import FEATURES
from waldur_core.core.models import Feature
from waldur_core.core.utils import DryRunCommand
class Command(DryRunCommand):
help = "Import features in JSON format"
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
... |
from PRISMRenderingShaders.CustomShader import CustomShader
"""PlaneIntersectingShader Class containing the code for the Plane intersecting shader.
:param CustomShader: Parent class containing the function to access the parameters of the shader.
:type CustomShader: class.
"""
class PlaneIntersectingShader(CustomSh... |
# DO NOT EDIT THIS FILE!
#
# This code is generated off of PyCDP modules. If you need to make
# changes, edit the generator and regenerate all of the modules.
from __future__ import annotations
import typing
from ..context import get_connection_context, get_session_context
import cdp.emulation
from cdp.emulation imp... |
# Copyright 2016 Open Source Robotics Foundation, 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... |
# encoding=utf8
import logging
from math import ceil
import numpy as np
from niapy.algorithms.algorithm import Algorithm, Individual, default_individual_init, default_numpy_init
logging.basicConfig()
logger = logging.getLogger('niapy.algorithms.basic')
logger.setLevel('INFO')
__all__ = ['MonkeyKingEvolutionV1', 'Mo... |
__version__ = "0.9.2"
__author__ = "Oliver Lindemann"
"""
launch the GUI force from your Python program:
``
from forceDAQ import gui
gui.run_with_options(remote_control=False,
ask_filename=True,
calibration_file="FT_sensor1.cal")
``
import relevant stuff to program your own forc... |
"""
Implements a solution to the post-order tree traversal Hackerrank problem.
https://www.hackerrank.com/challenges/tree-postorder-traversal/problem
"""
__author__ = "Jacob Richardson"
def post_order(root):
""" Preforms a post order tree traversal and prints the order on a single line space separated. "... |
# Generated by Django 3.1.5 on 2021-01-21 10:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("evan", "0025_auto_20210120_1654"),
]
operations = [
migrations.DeleteModel(
name="Paper",
),
]
|
# Setup Keras
from scipy import ndimage
import csv
import numpy as np
import pandas as pd
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Lambda, Cropping2D
from keras.layers.core import Dense, A... |
"""
An example training a XGBClassifier, performing
randomized search using TuneSearchCV.
"""
from tune_sklearn import TuneSearchCV
from sklearn import datasets
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
digits = datasets.load_digits()
x = digits.data
y = digits.target
x_tr... |
#
# =======================================================================
#
# Copyright (C) 2018, Hisilicon Technologies 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 Redistr... |
import re
import setuptools
def read_version():
with open('threatresponse/version.py', 'r') as fin:
return re.search(
r"^__version__ = '(?P<version>.+)'$",
fin.read().strip(),
).group('version')
def read_readme():
with open('README.md', 'r') as fin:
return fin... |
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
LOG = logging.getLogger(__name__)
def __virtual__():
return 'heatv1'
def _heat_call(fname, *args, **kwargs):
return __salt__['heatv1.{}'.format(fname)](*args, **kwargs)
def _poll_for_c... |
import codecs
import glob
import json
import os
import re
import serial
import sys
from pathlib import Path
# Terminology:
# IM = Insteon PLM
# Insteon service exceptions
class InsteonException(Exception):
def __init__(self, msg):
self.data = msg
class InsteonPLMConfigError(InsteonException): pass
clas... |
name = "John"
age = 17
print(name == "John" or not age > 17)
print(name == "John" and not age == 17)
print((name == "John" or name == "Jane") and 25 > age >= 16)
|
import os
import sys
import datetime
import pdfkit
now = datetime.datetime.now()
def main():
print("BY GAWD")
print(sys.argv)
print(now)
# usage: python pageDL.py url save_format
# folder needs to be within cwd
args = sys.argv
url = args[1]
save_format = args[2]
pdfkit.from_url(... |
# -*- coding: utf-8 -*-
import os
from setuptools import setup
from setuptools import find_packages
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(
name='lemapp',
version='0.6.dev0',
description='lemonodor Google-alike app framework.',
long_descri... |
#!/usr/bin/python
import argparse
import json
import wave
import os, sys
from collections import Counter
BPS = 2 * 8000
WAV_DIR = '.'
def open_wav(fn):
w = wave.open(fn, 'w')
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(8000)
return w
def concat_snippets(src, dest, times):
#src is a... |
import logging
import abc
import datetime
import traceback
import urllib.parse
import sqlalchemy.exc
import common.database as db
import WebMirror.TimedTriggers.UrlTriggers
import WebMirror.TimedTriggers.RollingRewalkTriggers
def exposed_rss_trigger():
'''
Execute normal RSS triggers.
'''
run = WebMirror.Tim... |
"""
Reads and parse system configutation and properties from an ini config file.
The config file name can be provided through the PROOF_CFG environment variable
or it can be specified on creating the configuration object.
"""
import os
from os import path
import configparser
import logging
import logging.config
logg... |
import asyncio
from confluent_kafka import Consumer
BROKER_URL = 'PLAINTEXT://localhost:9092'
async def consume(topic_name):
consumer = Consumer(
{
"bootstrap.servers": BROKER_URL,
"group.id": "0"
}
)
consumer.subscribe([topic_name])
while True:
... |
#!/usr/bin/env python
#
import sys, cpp, kernel, glob, os, re, getopt, clean_header, subprocess
from defaults import *
from utils import *
def usage():
print """\
usage: %(progname)s [kernel-original-path] [kernel-modified-path]
this program is used to update all the auto-generated clean headers
used by... |
import os
import re
from contextlib import contextmanager
def create_temporary_shell_file(cell_id, contents, temp_dir='tmp'):
"""Create a temporary shell file in the runtime to execute bash scripts
Parameters
----------
cell_id: str
The id of the cell
contents: str
The content of... |
from dependency_injector import providers
# Test 1: to check the return type
provider1 = providers.Object(int(3))
var1: int = provider1()
# Test 2: to check the provided instance interface
provider2 = providers.Object(int)
provided2: providers.ProvidedInstance = provider2.provided
attr_getter2: providers.AttributeGe... |
from django.apps import AppConfig
class ActivitystreamConfig(AppConfig):
name = 'activitystream'
|
from scidb.core import DataSet, Metadata, Properties
from typing import Union, List, Callable, Any
def empty_dicts(key: str, value: Any, current_path: List[str]) -> bool:
if isinstance(value, dict) or isinstance(value, Metadata) or isinstance(value, Properties):
return bool(value)
def iter_node_dict(nod... |
# Copyright 2021 D-Wave Systems 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... |
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Set
from tinytag import TinyTag
logger = logging.getLogger(__name__)
AUDIO_EXTENSIONS = [".mp3", ".m4a", ".wma"]
@dataclass
class AudioTag:
album: str
artist: str
title: str
track: int
disc: int
def au... |
from psycopg2.sql import SQL
from .expression import Expression
class Count(Expression):
def __init__(self, expression=None):
self.expression = expression
def to_sql(self):
return SQL('COUNT(*)'), ()
|
# Generated by Django 2.2 on 2019-04-26 15:52
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
def _build_usd(apps, schema_editor):
""" Create the base USD object """
Currency = apps.get_model("currency", "Currency")
db_alias = schema_editor.connec... |
# Generated by Django 2.2.10 on 2020-05-20 10:48
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import wazimap_ng.datasets.models.upload
class Migration(migrations.Migration):
dependencies = [
('datasets', '0091_auto_20200520_0449'),
]
op... |
import unicodedata
import requests
from matilda import config
import pandas as pd
import os
import urllib
from bs4 import BeautifulSoup
from datetime import datetime
def store_to_csv(file_path, tickers):
current_date = datetime.now().strftime('%Y-%m-%d')
if not os.path.exists(file_path):
df = pd.DataF... |
# (c) Copyright IBM Corp. 2021
# (c) Copyright Instana Inc. 2019
from __future__ import absolute_import
import wrapt
import opentracing as ot
import opentracing.ext.tags as tags
from ..log import logger
from ..singletons import agent, tracer
from ..util.secrets import strip_secrets_from_query
try:
import webap... |
from sympy import Symbol
from sympy import integrate
from decimal import *
"""
Estos seran los datos de entrada de nuestro programa.
f(x) representa la funcion que queremos integrar
[a,b] es el intervalo donde queremos obtener el valor de la integral
n+1 son los nodos que utilizaremos.
"""
x... |
# Lint as: python3
# Copyright 2020 The TensorFlow 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 ... |
from torch.utils.data import Dataset
import numpy as np
import torch
class EEGDataset(Dataset):
# EEG dataset class
def __init__(self, X, y):
"""
:param X: data
:param y: label
"""
self.X = X
self.y = y
def __len__(self):
return len(self.y)
def... |
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from django.template.loader import render_to_string
from django.conf import settings
from optparse import make_option
from datetime import datetime
import commands
import os
import sys
from . import GenericCommand
from ...model... |
import functools
import math
from pathlib import Path
from experiments.celeba_experiments.celeba_metadata_providers import \
CELEBA_BASE_METADATA_OPT_EXP_PROVIDER, CELEBA_BASE_METADATA_HYPERPARAMETER_SEARCH_PROVIDER
from sources.datasets.celeba.celeba_client_dataset_factory import CelebaClientDatasetFactory
from s... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operati... |
from typing import Optional
import torch
from torch import Tensor
from torch.nn import MultiheadAttention, Linear, Dropout, LayerNorm, Module
from torch.nn.modules.transformer import _get_activation_fn, TransformerEncoderLayer
import torch.nn.functional as F
class MYTransformerEncoderLayer(Module):
r"""Transform... |
import pandas as pd
import numpy as np
def MA(df, n):
ma = pd.Series.rolling(df['close'], n).mean()
return ma
def MA_2(df, n):
df = df.copy(deep = True)
MA = df['close'].rolling(n).mean()
MA = pd.Series(MA, name='MA')
df = df.join(MA)
return df
def MA_series(series, n):
ma = pd.Ser... |
from .cryptocompare import *
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = 'x'
__author__ = 'JieYuan'
__mtime__ = '18-12-14'
"""
import functools
class xx:
"""I am very like a linux pipe"""
def __init__(self, function):
self.function = function
functools.update_wrapper(self, function)
def __ror__(sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import importlib
from argparse import ArgumentTypeError
def quantity_float(value):
quantity = float(value)
if quantity <= 0:
raise ArgumentTypeError("invalid quantity: {}, and quantity must be greater than 0!".format(quantity))
return quantity
def pr... |
# -*- coding: utf-8 -*-
import hypothesis.strategies as st
from hypothesis import given
from pyramid.httpexceptions import HTTPFound
from dbas.strings.fuzzy_modes import FuzzyMode
from dbas.tests.utils import TestCaseWithConfig, construct_dummy_request
from dbas.validators.common import valid_lang_cookie_fallback, va... |
#!/usr/bin/env python
import os
import serial
import sys
import optparse
import time
import re
def main():
parser = optparse.OptionParser(
usage='\n'
' %prog [opts] /dev/ttyUSB1')
parser.add_option('-d', '--delay', type='float', default=0.1,
help='Interval between comman... |
import sys
import time
import struct
import bteve as eve
from spidriver import SPIDriver
class Gameduino(eve.Gameduino):
def __init__(self):
self.buf = b''
def cc(self, s):
assert (len(s) % 4) == 0
self.buf += s
def pack(self):
print(len(self.buf), "bytes used")
wh... |
import sys
from typing import Callable, Optional, Union
from tonberry.exceptions import FigureItOutLaterException
from tonberry.models import Methods, RouteMapping
class _Expose:
_registrar = Methods()
@classmethod
def _new_registrar(cls) -> None:
cls._registrar = Methods()
@classmethod
... |
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... |
while True:
print("options:")
print("'add' adds two numbers")
print("'subtract' subtracts two numbers")
print("'multiply' multiplies 2 numbers")
print("'divide' divides two numbers")
print("quit")
user_input = input(": ")
if user_input == "quit":
break
elif ... |
# Exercise 3.9
# Author: Noah Waterfield Price
def area(vert):
A = 0.5 * abs(vert[1][0] * vert[2][1] - vert[2][0] * vert[1][1] -
vert[0][0] * vert[2][1] + vert[2][0] * vert[0][1] +
vert[0][0] * vert[1][1] - vert[1][0] * vert[0][1])
return A
v1 = (0, 0)
v2 = (1, 0)
v3 = (0, ... |
# -*- coding=utf-8 -*-
import json
import os
from Crypto.Cipher import AES
import base64
modulus = \
'00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b... |
# vim: expandtab:ts=4:sw=4
import tensorflow as tf
# import tensorflow
# import tensorflow.compat.v1 as tf
# tf.disable_eager_execution()
# tf.disable_v2_behavior()
# import tf_slim as slim
import tensorflow.contrib.slim as slim
def _pdist(a, b=None):
sq_sum_a = tf.reduce_sum(tf.square(a), reduction_indices=... |
#coding:utf8
from gale.web import router, app_run
from gale.server import HTTPServer
from gale.ipc import IPCDict
import os
@router(url='/')
def index(self):
ipc_dict = IPCDict('counter')
access_counter = ipc_dict.incr('access_counter')
self.push("pid: %s counter:%s" % (os.getpid(), access_counter))
app_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""segnet package
Helper tensorflow functions for the package.
We implement useful functions to deal with tensorboard,
weight initialization function (glorot) and specific layers.
"""
from itertools import compress
import tensorflow as tf
def add_activation_summary(va... |
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'suxx'
__mtime__ = '2019/1/15'
"""
import unittest, sys
sys.path.append("../")
import read_conf
from function.func import *
from function.ela_log import MyLog
log = MyLog.get_log()
logger = log.get_logger()
b = read_conf.ReadData()
normal_response_code = b.ge... |
from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
Base = declarative_base()
class Knowledge(Base):
__tablename__ = 'knowledge'
wiki_id = Column(String, primary_key... |
#!/usr/local/bin/python3
import os
import shutil
while not os.getcwd().lower().endswith("stasbar-app"):
os.chdir("..")
os.chdir("frontend")
subprocess.call(['npm', 'run', 'build'])
os.chdir("..")
shutil.rmtree("backend/src/main/resources/assets/static/js")
os.system("cp -rf frontend/build/ backend/src/main/resourc... |
import xlrd
import numpy as np
import matplotlib.pyplot as plt
# Import seaborn
import seaborn as sns
# Set dark grid
sns.set()
book = xlrd.open_workbook("hos_salaries\\data.xls")
sheet = book.sheet_by_name("All")
N = sheet.nrows
states = [sheet.cell_value(r, 0) for r in range(1, N)]
hos_salaries = [... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.