text stringlengths 8 6.05M |
|---|
from math import *
import esn
import imp
# Check if we can use matplotlib
try :
imp.find_module( "matplotlib" )
from matplotlib import pyplot
from matplotlib import animation
USE_MATPLOTLIB = True
except ImportError :
USE_MATPLOTLIB = False
NEURON_COUNT = 10
CONNECTIVITY = 0.1
SINE_FREQ = 50.0
SIN... |
my_tuple = ("box", "blue", "victor")
print(my_tuple)
print(len(my_tuple))
tuple1 = (0, 1, 2, 3)
tuple2 = ('victor', 'ronaldo')
tuple3 = (tuple1, tuple2)
print(tuple3)
print(tuple('python')) |
"""empty message
Revision ID: 21808a470526
Revises: bf8a1557b052
Create Date: 2016-08-02 16:54:50.782946
"""
# revision identifiers, used by Alembic.
revision = '21808a470526'
down_revision = 'bf8a1557b052'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
#!/usr/bin/python
#Online linear regression using Gaussian RBF.
from gaussian_rbf import Sq, Vec, FeaturesG, FeaturesNG, ConstructRBF
import numpy as np
import numpy.linalg as la
import math
import random
#Features= FeaturesG
Features= FeaturesNG
def Func(x):
return x[0]*math.sin(3.0*x[1])
#return 3.0-(x[0]*x[0]... |
class HttpClientInterface:
def GET(self):
raise NotImplementedError
def POST(self):
raise NotImplementedError
class GatewayLive(HttpClientInterface):
def GET(self):
# zaciagnij informacje o userze
return ...
def POST(self):
# zapytaj po sieci
pass
cl... |
import csv
import os.path
import subprocess
import tempfile
from onegov.core.csv import CSVFile
class DigirezDB:
""" Offers access to a Digirez Room Booking Software Database
(see http://www.digiappz.com).
Expects that mdbtools are installed (http://mdbtools.sourceforge.net).
"""
def __init__(... |
from django.db import models
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template import RequestContext
from django.template.loader import render_to_string
class BaseFkeyContent(models.Model):
""" Returns a generic fkey Feincontent type for the simple ... |
def solve():
n = int(input())
grid = []
for i in range(n):
row = list(str(input()))
grid.append(row)
optimal_cost = 10000000
cost_tracker = dict()
# row passes
for r in range(n):
cost = 0
placements = ""
possible = True
for c in range(n):
... |
# Generated by Django 2.1.5 on 2019-03-31 20:01
import datetime
from django.db import migrations, models
import tasks.models
class Migration(migrations.Migration):
dependencies = [
('tasks', '0010_auto_20190331_1950'),
]
operations = [
migrations.AlterField(
model_name='week... |
import pymongo
import scrape_mars
def mongo_store():
# Import all of the data from the scrape_mars import.
news_title, news_p = scrape_mars.marsNasaNewsScrape()
mars_weather = scrape_mars.marsWeatherScrape()
featured_image_url = scrape_mars.marsImageScrape()
hemisphere_image_urls = scrape_mars.ma... |
#spark-submit --num-executors 10 --master yarn-client --executor-memory 8g --driver-memory 4g Nutrition_Data.py
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext,HiveContext
import os
import sys
import datetime
import pandas as pd
from time import gmtime, strftime
import subprocess
import ... |
__version__ = '1.1.8' |
#!/usr/bin/python
import rospy
import tf
import math
import sys
import time
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
class Bug(object):
# ctor
def __init__(self, forward_speed, rotation_speed, min_scan_angle, max_scan_angle, min_dist_from_obstacle, goal_x,
g... |
from html.parser import HTMLParser
class ContentsTableParser(HTMLParser):
def __init__(self):
super().__init__()
self.collect_data = False
self.links = []
self.collect_link_data = False
def error(self, message):
pass
def handle_endtag(self, tag):
if tag ==... |
# Generated by Django 2.1.7 on 2019-05-21 21:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('curriculo', '0006_curso_descricao'),
]
operations = [
migrations.AlterField(
model_name='curso',
name='descricao',
... |
# A/B testing
# Subset the DataFrame
email = marketing[marketing['marketing_channel']== 'Email']
# Group the email DataFrame by variant
alloc = email.groupby(['variant'])['user_id'].nunique()
# Plot a bar chart of the test allocation
alloc.plot(kind='bar')
plt.title('Personalization test allocation')
plt.ylabel('# ... |
from kubeflow.kubeflow.crud_backend import status
from werkzeug.exceptions import BadRequest
def parse_tensorboard(tensorboard):
"""
Process the Tensorboard object and format it as the UI expects it.
"""
if tensorboard.get("status", {}).get("readyReplicas", 0) == 1:
phase = status.STATUS_PHASE... |
##monitoring for the certificate transpirincy by www.crt.sh
#we are using the unoficial crtsh api and the elastic search
#elastic search databse stores the data and when the program runs after every 12 hrs
#it checks if there is new certificate has been generated it will prompt new certificate found or else it will ... |
#Class brain for - acrobat
import keras
from keras.layers import Dense, Dropout, Conv1D, MaxPooling1D, Flatten, concatenate
from keras.optimizers import Adam
from keras.models import Sequential, load_model
class Brain():
def __init__(self, IS = (6, 4), lr = 0.0001):
self.InputShape = IS
se... |
import pyautogui
import time
import pygame
input('explore')
explorex, explorey = pyautogui.position()
# im = pyautogui.screenshot()
# explore = im.getpixel((explorex,explorey))
input('skip')
skipx, skipy = pyautogui.position()
# im = pyautogui.screenshot()
# skip = im.getpixel((skipx, skipy))
#
# input('battle')
# bat... |
import roman1
import unittest, re
class KnownValues(unittest.TestCase):
known_values = ( (1, 'I'),
(2, 'II'),
(3, 'III'),
(4, 'IV'),
(5, 'V'),
(6, 'VI'),
(7, 'VII'),
(... |
# -*- coding: utf-8 -*-
# flake8: noqa
# Generated by Django 1.11 on 2017-05-06 15:43
from __future__ import unicode_literals
import ckeditor_uploader.fields
from django.db import migrations, models
import django.db.models.deletion
import image_cropping.fields
class Migration(migrations.Migration):
initial = Tr... |
import os
from setuptools import setup, find_packages
setup(
name = 'dropchat',
version = '0.3.0',
description = 'DropChat',
long_description = 'Drop Chat - Secure Disposable Chat',
url = '',
license = 'MIT',
author = 'Alejandro Caceres',
author_email = 'contact@hyperiongray.com',
p... |
# uses light sensor as a proximity sensor
# darkness (lower than trigger) = surprised face
from microbit import *
import tcs3472
tcs3472 = tcs3472.tcs3472()
# change the trigger - a lower number means you need
# to get closer to trigger the surprised face
trigger = 400
while True:
light_level = tcs3472.light()
... |
import os
from typing import Tuple
import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.callbacks import ReduceLROnPlateau
from tensorflow.keras.callbacks import TensorBoard
from tenso... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
... |
from xmc.multiCriterion import MultiCriterion
interpretationStructure = MultiCriterion.flagStructure
def interpretAsStoppingFlag(flag):
"""
This is the trivial interpreter for an input which is a boolean answering
the question `Must I stop the algorithm now'?
"""
interpretation = interpretationStr... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 21 15:21:33 2017
@author: Yam
"""
import numpy as np
from fdata import fgrid
np.set_printoptions(threshold=np.nan)
inner_X = 5E3 #inner span
inner_Y = 7E3
outer_X = 13E3 #outer allowance
outer_Y = 15E3
#div_X_inner = 14
#div_Y_inner = 15
#div_X_outer... |
import os
import sys
from distutils.sysconfig import get_python_lib
from setuptools import setup
CURRENT_PYTHON = sys.version_info[:2]
REQUIRED_PYTHON = (3, 6)
setup()
|
import pickle
# i = 10
# b = True
# f = 3.5
# l = [1,2,3,4]
# t = (6,7,8,9)
# d = dict(a=1, b=2, c=3)
# o = [i, b, f, l, t, d]
# fw = open("testpickle.bin", "wb")
# pickle.dump(o, fw)
fr = open("testpickle.bin", "rb")
o = pickle.load(fr)
print("Object read")
print(o) |
"""在我们捕获视频,并对每一帧都进行加工之后我们想要保存这个视频"""
"""这次我们要创建一个 VideoWriter 的对象。我们应该确定一个输出文件的名字。接下来指定 FourCC 编码(下面会介绍)。
播放频率和帧的大小也都需要确定。
最后一个是 isColor 标签。如果是 True,每一帧就是彩色图,否则就是灰度图。"""
"""FourCC 就是一个 4 字节码,用来确定视频的编码格式。可用的编码列表可以从fourcc.org查到。
这是平台依赖的。下面这些编码器对我来说是有用个。
• In Fedora: DIVX, XVID, MJPG, X264, WMV1, WMV2. (XVID is more pr... |
'''for c in range(1, 10):
print(c)
print('Fim')'''
'''c = 1
while c < 10:
print(c)
c +=1
print('Fim')'''
'''for c in range(1, 10):
n = int(input('Valor: '))
print('Fim')'''
'''n = 1
while n != 0:
n = int(input('Valor: '))
print('Fim')'''
n = 1
par = impar = 0
while n != 0:
n = int(input('Val... |
import unittest
import chainer
import chainer.functions as cf
import chainer.testing
import cupy as cp
import imageio
import numpy as np
import neural_renderer_chainer
class Parameter(chainer.Link):
def __init__(self, x):
super(Parameter, self).__init__()
with self.init_scope():
self... |
import math
def whoIsNext(names, r):
n = len(names)
k = 2 ** int(math.log(1 + (r - 1) // n, 2))
s = 1 + (k - 1) * n
return names[(r - s) // k]
names = ["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"]
r = 20
print(whoIsNext(names, 7230702951))
|
import functools
from flask import *
from werkzeug.security import *
from flaskr.db import get_db
bp = Blueprint('auth', __name__, url_prefix='/auth') |
import sys
class DataCounter:
movie_rating = []
movie_rating_data = []
def movieRatedByUser(self):
pass
def dataReader(self, data_file_path):
with open(data_file_path) as data_file:
count = 0
for line in data_file:
line = line.strip().split("::")
record = [int(line[0]),int(line[1]),float(line... |
numbers = list(range(1, 21, 2)) # 第三个参数是步长,默认为1
for number in numbers:
print(number) |
#https://realpython.com/linear-regression-in-python/#beyond-linear-regression
#Polynomial Regression With scikit-learn (two column input)
#𝑓(𝑥₁, 𝑥₂) = 𝑏₀ + 𝑏₁𝑥₁ + 𝑏₂𝑥₂ + 𝑏₃𝑥₁² + 𝑏₄𝑥₁𝑥₂ + 𝑏₅𝑥₂². polynominal for two inputs
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model ... |
import bcrypt
from flask_login import login_user, current_user, logout_user
from src.app import db
from src.create_db import add_default_settings
from common.models.user import User
from src.services.errors import LoginError, FieldExistsError, check_form
required_fields = ['username', 'password']
def login(form):
... |
import pandas as pd
from matplotlib import pylab as plt
train = pd.read_csv('E:/FAKULTET/MASTER/ISTRAZIVANJA/training/sales_train_v2.csv')
print ('number of shops: ', train['shop_id'].max())
print ('number of items: ', train['item_id'].max())
num_month = train['date_block_num'].max()
print ('number of month: ', num_mo... |
out = ""
for string in range(1, 101):
if string % 3 == 0 and string % 5 == 0:
out += "PlanitTesting "
continue
elif string % 3 == 0:
out += "Planit "
continue
elif string % 5 == 0:
out += "Testing "
continue
out += str(string) + " "
print(out.strip())
|
# -*- coding: utf-8 -*-
__author__ = 'Brandon Ogle'
from pandas import DataFrame
import pandas as pd
import networkx as nx
import numpy as np
from numpy import sin, cos, pi, arcsin, sqrt
import string
import collections
def prep_data(network, metrics, loc_tol=.5):
"""
This block of code performs fuzzy matchin... |
i=int(input(""))
if i<0:
print("Enter a Positive Number")
else:
sum=0
while(i>0):
sum+=i
num-=1
print("The Sum is",sum)
|
import discord
from mcstatus import MinecraftServer
from decouple import config
server = MinecraftServer.lookup(config('ADDRESS'))
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author... |
from ClassLoader import ClassLoader
from Input import Input
from Output import Output
from Console import Console
|
import pygame
from Pong.components.score import Score
from Pong.constants import ECRAN
class Balle(pygame.sprite.Sprite):
speed = 10
dirx = 2
diry = 0
mort = 0
ressuciter = 90
def __init__(self,score1,score2):
self.score1 = score1
self.score2 = score2
pygame.sprite.Spri... |
from itertools import product, chain
from interfaces.game_state import GameState
class HexesNotInLineException(Exception):
pass
class IllegalMoveException(Exception):
pass
class HtmfBoard(object):
def __init__(self, length, hexes=None, penguins=None, scores=None):
assert (hexes is None and penguin... |
import argparse
import os
import torchvision.models as models
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.nn.parallel
import torch.utils.data
import time
import copy
from sklearn.decomposition im... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.dashboard, name='dashboard'),
# Courses
#url(r'^courses/$', views.course_list, name='course_list'),
# url(r'^courses/detail/(?P<id>\d+)/$', views.course_detail, name='course_detail'),
# Trainers
#url(r'... |
from django.urls import path
from . import views
app_name = 'accounts'
urlpatterns = [
path('login/', views.user_login, name='login'),
path('logout/', views.user_logout, name='logout'),
path('register/', views.user_register, name='register'),
path('active/<uidb64>/<token>/', views.RegisterEmail.as_vie... |
import pymysql.cursors
import sys
MYSQL = '192.168.0.124'
def mysql_select_attr(db, sql, attribute):
'''
通过sql中的某个字段取值
:param db:
:param sql:
:param attribute:
:return:
'''
try:
# 连接mysql数据库
connection = pymysql.connect(host='MYSQL', port=3306, user='root', password='Pa... |
from .MoveCommand import MoveCommand
class MovePlayerCommand(MoveCommand):
def __init__(self, state, player):
super().__init__(state, player)
def run(self):
super().run()
player = self.unit
# зона игрока
if player.position.x <= self.state.border_left:
playe... |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class BaseModel(models.Model):
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
class Meta:
abstr... |
import geokerr_interface
import numpy as np
from scipy.optimize import minimize
g = geokerr_interface.geokerr()
def cartesian(u,mu,phi):
x = 1./u*np.sqrt(1.-mu**2.)*np.cos(phi)
y = 1./u*np.sqrt(1.-mu**2.)*np.sin(phi)
z = 1./u*mu
return x,y,z
def calc_orbit(ab,args):
a=args[0]; mu0=args[1]; uf=arg... |
# coding: utf-8
# In[18]:
import math
def mean_function(slist):
sum = 0
for a in slist:
sum += a
mean = sum / len(slist)
nsum = 0
for b in slist:
nsum += (b - mean) * (b - mean)
var = nsum / (len(slist) - 1)
dev = math.sqrt(var)
result = {"mean":m... |
import requests
from pprint import pprint
import json
import os
import sys
sys.path.append("..")
from server import app
from model import Hospital, db, connect_to_db
#Request response object with results
def load_hospitals(url):
#Replace URL with string variable to use with other requests in the future
#ur... |
#!/usr/bin/env python3
"""
https://github.com/dev0ps221/wordgen/tree/dev?fbclid=IwAR1jRpl6r-9FJAoRhFzCm1NpDuNF0Dv0rS933q2HD_NwE3pzFxjSZ9vCZAs
"""
__author__ = "kharris"
__version__ = "0.1.0"
__license__ = "MIT"
import sys
#global list of lists
lists = []
####################
###
def main():
p... |
import argparse, time, logging, os, math, random
os.environ["MXNET_USE_OPERATOR_TUNING"] = "0"
import numpy as np
from scipy import stats
import mxnet as mx
from mxnet import gluon, nd
from mxnet import autograd as ag
from mxnet.gluon import nn
from mxnet.gluon.data.vision import transforms
from gluoncv.model_zoo im... |
"""
@File: re_use_func.py
@CreateTime: 2020/2/27 上午10:29
@Desc: python中正则表达式的使用 脚本文件,修改链接为接口数据,
"""
import re
import requests
from setting import HEADERS
class ChangeUrlToApi(object):
def __init__(self):
self.url = "https://author.baidu.com/home/1611994554344933"
self.cookies = {
'BAI... |
import rhinoscriptsyntax as rs
import math
from random import choice
def getArea():
return rs.GetObject("Select area", filter=4)
def createTheater(area):
option = rs.GetInteger("Enter '1' for square, enter '2' for custom", 2)
if option == 1:
sqSides = math.sqrt(area)
rec = rs.... |
from flask import Blueprint, render_template, abort, jsonify, request
import app_setting
blueprint = Blueprint('Home', __name__,template_folder='BlueprintArchitech/Home')
@blueprint.route('/', methods=['GET'])
def welcome():
respond = {'status' : 200,'msj' : 'POST CALLED'}
return jsonify(respond)
@blueprint.route(... |
from uuid import uuid4
from sqlalchemy import Column, ForeignKey, Boolean, Table, Text
from onegov.core.orm import Base
from onegov.core.orm.types import UUID
table_name = 'fsi_reservations'
subscription_table = Table(
table_name,
Base.metadata,
Column('id', UUID, primary_key=True, default=uuid4),
Colu... |
'''
author: juzicode
address: www.juzicode.com
公众号: 桔子code/juzicode
date: 2020.10.30
'''
import time,threading,sys
from threading import Thread
from threading import Lock
def thread_1(lock):
print('进入线程: thread_1')
loop_cout = 100
while True:
time.sleep(0.5)
lock.acquire(... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('injector', '0004_auto_20150718_1136'),
]
operations = [
migrations.RemoveField(
model_name='technology',
... |
from bibliopixel.receiver_anim import BaseReceiver
import bibliopixel.drivers.network_receiver as net
from bibliopixel import log
class GenericNetworkReceiver(BaseReceiver):
def __init__(self, led, port=3142, interface='0.0.0.0'):
super(GenericNetworkReceiver, self).__init__(led)
self.address = (i... |
import sympy as sp
import numpy as np
from kaa.bundle import Bundle
from kaa.model import Model
class Phosphorelay(Model):
def __init__(self):
dim_sys = 7
x1, x2, x3, x4, x5, x6, x7 = sp.Symbol("x1"), sp.Symbol("x2"), sp.Symbol("x3"), sp.Symbol("x4"), sp.Symbol("x5"), sp.Symbol("x6"), sp.Symbol... |
# price a deep out of the money call option using importance sampling
# look at E[ exp(-rT) (S(T)-K)_+ exp(mu^2/2 - mu Z) ]
# where Z ~ N( mu, 1)
# below we write "mu + Z" instead of Z ... and plot the answer and the
# error for different values of mu
import numpy as np
from numpy import random as rn
import matplotlib... |
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from dailymirror.items import DailymirrorArticle
XPATH_TITLE = '//*[self::h1 or self::h2 or self::h3 or self::h4]//text()[normalize-space()]'
XPATH_DATE = '//div[contains(@class, "well")]//text()[normalize-space()]'
XPATH_COM... |
from itertools import repeat
from pprint import pprint
from nn import find_best_weights, neuron, show_correct, ratio_of_letters
def filedata(filename):
sentences = [s.strip().decode('utf8') for s in open(filename).read().split('\r\n') if s.strip()]
return sentences
data = (zip(filedata('spanish.txt'), repeat... |
# function to read the WYKO interferometer
# Marcos van Dam
# November 2005
# Elena Manjavacas, April 2020
import numpy as np
import os.path
import matplotlib.pyplot as plt
def readph(filename):
cdph = '/kroot/rel/ao/qfix/data/'
phase = np.zeros(349)
tmp0 = filename
tmp = os.path.isfile(tmp0)
... |
# Making a df file
# Version 1
# Vikram Anantha
# Feb 1 2021
"""
ID | Timestamp | Name | Email | Pemail | Grade | Town | State | Found out about HELM | Prev Classes | Next 3 classes
22 | 2020-09-07 | Tom | tom@gmail.com | tomsmom@gmail.com | 6 | Lex | MA | Whatsapp Group | [1, 4, 2, ... |
#!/usr/bin/env python
'''
Learning 2 x 3 bar and stripe using Born Machine.
'''
import numpy as np
import pytest
from qcbm.testsuit import load_barstripe
import mkl
mkl.set_num_threads(1)
np.random.seed(2)
# the testcase used in this program.
@pytest.mark.parametrize('nbit', range(4, 16))
def test_X(benchmark, nbit... |
# -*- coding: utf-8 -*-
import utils
from basehandler import BaseHandler
class Rot13(BaseHandler):
def get(self):
self.render('/templates/rot13.html')
def post(self):
t = self.request.get('text')
self.render('/templates/rot13.html',
texts=utils.rot1... |
'''
a = [
(5-8-5+9)**2 +
(9-8-11+9)**2 +
(10-8-11+9)**2 +
(5-10-5+9)**2 +
(13-10-11+9)**2 +
(12-10-11+9)**2]
'''
import pandas as pd
import seaborn as sns
import numpy as np
import math
import matplotlib.pyplot as plt
from random import randint
import scipy.stats as ss
#from scipy.stats import norm, kurtosis, skew
impo... |
import json
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('posts')
user_table = dynamodb.Table('gusers')
def get_user_subscriptions(user_id):
response = user_table.get_item(Key={
'id': int(user_id)
})
if 'Item' in response:
return response['Item']['subscription... |
from rest_framework.response import Response
from rest_framework import status
from rest_framework import serializers
from django.http import HttpResponse
from django.template.loader import get_template
from django.template.loader import render_to_string
import datetime
import os
import math
import os.path
import tempf... |
"""
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
示例 4:
输入: s = ""
输出: 0
提示:
0 <= s.length ... |
###############################################################################################
# Librería que alberga funciones de cálculos matemáticos controlados y utilidades matemáticas #
###############################################################################################
# Método controla el valor ... |
from CSS3.completions import types as t
import sublime
# This dict maps function names to their completions. It includes pseudo-class
# and pseudo-element functions like :nth-child() and ::attr().
func_name_to_completions = {
"attr": [
("angle",), # A tuple with only one string means the label is the same... |
"""
Assignment 2 - New Repository with Hello World
By : Fushan Leong
Date : Jan 20, 2021
"""
if __name__ == '__main__':
print('Hello World for Assignment 2')
|
"""
Listen to the DynamoDB stream for partition events and dispatch them as CloudWatch custom events
"""
import os
import json
import logging
from datetime import datetime
import backoff
import botocore
from aws_xray_sdk.core import patch_all, xray_recorder
from lib.decorators import KinesisRecord, kinesis_handler
fro... |
from django.contrib import admin
from django.urls import path, include
from . import views
from django.conf.urls.static import static
from django.conf import settings
# from django.contrib.auth.views import login
# from django.contrib import admin
admin.site.site_header = 'CMS administration' # d... |
import os
def get_config(key, default=None):
return os.getenv(key, default)
DB_URI = get_config("DB_URI", 'sqlite:///../kuaidi.db')
API_KEY = get_config("API_KEY")
SECRET_KEY = get_config("SECRET_KEY")
TOKEN_SECRET_KEY = get_config("TOKEN_SECRET_KEY")
INTERNAL_CODE = get_config("INTERNAL_CODE")
|
"""
File: hailstone.py
-----------------------
This function should implement a console program that simulates
the execution of the Hailstone sequence, as defined by Douglas
Hofstadter.
"""
def main():
"""
Using the hailstone process:
take any integer and multiply
by 3 and add 1 if its odd and
divi... |
from time import sleep
velocidade = float(input('Qual a velocidade(km/h) atual do carro: ' ))
multa = float(velocidade-80)*7
print('Processando...')
sleep(2)
if velocidade > 80:
print(f'MULTADO! você excedeu o limite de 80km/h!\ne sua multa será de R${multa:.2f}')
else:
print('Você não excedeu o limite de 80km/... |
import asyncio
import collections
import logging
import random
import time
import typing
from collector_app.configs import collector as config
from rzd_client import client
from rzd_client import models
logger = logging.getLogger(__name__)
class WorkerQueue:
_client: client.RZDClient
def __init__(self):
... |
#a = 2**
a = input("enter some:")
if len(str(a))<50:
print("good")
else:
print(a)
|
# Source Forge Docs
# http://sourceforge.net/p/forge/documentation/File%20Management/
# https://sourceforge.net/p/forge/documentation/SCP/
# Pycrypto: pycrypto-2.6.win32-py2.7
# Download link: http://www.voidspace.org.uk/python/modules.shtml#pycrypto
import paramiko # pip install paramiko
import scp #... |
import numpy as np
from keras.preprocessing import sequence
import io
from gensim.corpora import Dictionary
import torch
class Preprocessing():
def __init__(self, corpus, nmax=10000, maxlen=12):
self.dct = self.construct_dict(corpus, prune_at=nmax)
self.depth = len(self.dct)
se... |
import collections
from functools import partial
from rdflib import Graph, ConjunctiveGraph, Dataset
class Statement(collections.namedtuple("StatementBase", "s p o c")):
"""
Statement wrapper class. A convenient class to mask the graph <- > dataset question somewhat
This class is based on a namedtuple (s ... |
''''
This is a script to extract & save sample points from multiple rasters.
inputs (in form of a parameter file):
-rasterPath (of raster with clipped extent)
-bandNum
-numSamples (for each bin)
-bins (ex.0-10,11-20,20-30) INCLUSIVE
-searchPath (to find addition rasters, extent doesnt matter)
-bandNum_rest
... |
# Copyright (c) 2010 - 2014, AllSeen Alliance. All rights reserved.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PR... |
import asyncio
import pytest
import logging
from okws.client import create_client
from okws.server import run
import ccxt.async_support as ccxt
from tests.test_okex_app import get_okex_params
pytestmark = pytest.mark.asyncio
logger = logging.getLogger(__name__)
async def position(okex, api):
ret = await okex.sub... |
#!/usr/bin/env python
"""
@date november 2015, malmo
@author m. lund
"""
import matplotlib.pyplot as plt
import numpy as np
import warnings
import os
from math import sqrt, log, pi, exp, fabs, sinh
from scipy.optimize import curve_fit, OptimizeWarning
from scipy.constants import N_A
from sys import exit
class Radi... |
class Player:
def __init__(self, name, team):
self.name = name
self.team = team
self.link = None
self.stats_2019 = {}
self.stats_2020 = {}
def update2020(self):
pass
def getLink(self):
pass
|
num1 = int(input("Digite o primeiro número: "))
num2 = int(input("Digite o segundo número: "))
num3 = int(input("Digite o terceiro número: "))
if (num1 > num2) and (num1 > num3):
if (num2 > num3):
print (num1)
print (num2)
print (num3)
else:
print (num1)
print... |
"""
Python build script for setuptools
Raises:
RuntimeError: Raised if __version__ information is not found
"""
import codecs
import os
from setuptools import find_packages, setup
def get_version(filepath):
"""
Extracts the version string from a file
Args:
filepath (str): Path to the file ... |
from itertools import combinations, permutations
from collections import namedtuple
class Suggestion(object):
'''
Object that takes in input and number k,
provides suggestion
'''
def __init__(self, actual, target, data = {}):
assert len(data) != 0, "No data provided"
assert actual ... |
class Mediator:
i = 0
all_game_entities = []
to_be_removed = []
all_game_tiles = []
all_boundry_tiles = []
all_game_bullets = []
player = None |
# -*- coding: utf-8 -*-
from rest_framework import serializers
from .models import CustomerProfile,SellerProfile,User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('first_name','last_name','email','password')
extra_kwargs = {'password':{'write_only':... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.