index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
986,500 | 1af0fde6387b66ff70eaf67e283c4508fdfe28c2 | from flask import Blueprint, redirect, url_for, request, flash, jsonify
from flask_login import login_user, logout_user, login_required
from werkzeug.security import generate_password_hash, check_password_hash
from api.book.models import User
from . import db
auth = Blueprint('auth', __name__)
@auth.route('/login', methods=['POST'])
def login_post():
data = request.get_json()
email = data['email']
password = data['password']
remember = data['remember']
user = User.query.filter_by(email=email).first()
if not user or not check_password_hash(user.password, password):
return jsonify({"error": 'Wrong username or password'}), 400
login_user(user, remember=remember)
return jsonify({"result": 'OK'}), 200
@auth.route('/signup', methods=['POST'])
def signup_post():
data = request.get_json()
email = data['email']
name = data['name']
password = data['password']
user = User.query.filter_by(email=email).first()
if user:
return jsonify({"error": 'Email address already exists'}), 400
new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256'))
db.session.add(new_user)
db.session.commit()
return jsonify({"result": 'OK'}), 200
@auth.route('/logout')
@login_required
def logout():
logout_user()
return jsonify({"result": 'OK'}), 200
|
986,501 | 21e1d62ac37a49e090d3c4546df5d3fa2bde0c00 | # -*- coding: utf-8 -*-
from app import logging
from app.remote.redis import Redis as redis
from app.telegram.app import get_client as telegram_get_client
from app.vk.app import start_polling as vk_start_polling
from threading import Thread
from time import sleep
import logging
import asyncio
if __name__ == "__main__":
try:
asyncio.get_event_loop().run_until_complete(redis.connection())
client = telegram_get_client()
Thread(target=client.start, name="telegram_client").start()
# Telegram клиенту нужно немного времени, чтобы запуститься
sleep(1)
Thread(target=vk_start_polling, args=(client,), name="vk_polling").start()
except Exception as e:
logging.critical("Произошла ошибка в работе приложения.", exc_info=True)
|
986,502 | 529e4fee5a3bfdf483c526c4b3313e0e16744853 | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^edx2canvas/', include('edx2canvas.urls', namespace="edx2canvas")),
url(r'^auth_error/', 'edx_in_canvas.views.lti_auth_error', name='lti_auth_error'),
)
|
986,503 | 5916f3ac2abaa8c6fb04a469c71590a6a9055240 | from compiler.ast import *
from HelperClasses import *
from compiler.ast import *
import varAnalysis, astpp
#Combines the func list and ast into a list of tuples (funcname, ModLambda)
#all code not in a lambda will be put into main
def standardize(ast, l):
ast.nodes.append(Return(Const(0)))
return l + [("main", Lambda([], [], 0, ast))]
#Helper to recursive call closure on each elm
#and to reduce the list of tuples into one large tuple
def iterList(list, gen, lambdaGen):
listTup = [closure(n, gen, lambdaGen) for n in list]
return reduce(lambda (acc_a, acc_l), (a, l) : (acc_a + [a], acc_l + l), listTup, ([],[]))
def closureModule(ast, gen, lambdaGen):
ast, l = closure(ast.node, gen, lambdaGen)
return standardize(ast, l)
def closureStmt(ast, gen, lambdaGen):
a, l = iterList(ast.nodes, gen, lambdaGen)
return Stmt(a), l
def closurePrintnl(ast, gen, lambdaGen):
ast, l = closure(ast.nodes[0], gen, lambdaGen)
return Printnl([ast], None), l
def closureConst(ast, gen, lambdaGen):
return ast, []
def closureUnarySub(ast, gen, lambdaGen):
ast, l = closure(ast.expr, gen, lambdaGen)
return UnarySub(ast), l
def closureAdd(ast, gen, lambdaGen):
ast_left, l_left = closure(ast.left, gen, lambdaGen)
ast_right, l_right = closure(ast.right, gen, lambdaGen)
return Add([ast_left, ast_right]), l_left + l_right
def closureDiscard(ast, gen, lambdaGen):
ast, l = closure(ast.expr, gen, lambdaGen)
return Discard(ast), l
def closureAssign(ast, gen, lambdaGen):
astN, l = closure(ast.expr, gen, lambdaGen)
return Assign([ast.nodes[0]], astN), l
def closureName(ast, gen, lambdaGen):
return ast, []
def closureAssName(ast, gen, lambdaGen):
return ast, []
def closureCallFunc(ast, gen, lambdaGen):
cl = Name(gen.inc().name())
funcRef, l1 = closure(ast.node, gen, lambdaGen)
a, l2 = iterList(ast.args, gen, lambdaGen)
args = [CallRuntime(Name("get_free_vars"), [cl])] + a
return Let(cl, funcRef,
CallFunc(CallRuntime(Name("get_fun_ptr"), [cl]), args)), l1 + l2
def closureCallRuntime(ast, gen, lambdaGen):
a, l = iterList(ast.args, gen, lambdaGen)
return CallRuntime(ast.node, a), l
def closureCompare(ast, gen, lambdaGen):
ast_left, l_left = closure(ast.expr, gen, lambdaGen)
ast_right, l_right = closure(ast.ops[0][1], gen, lambdaGen)
return Compare(ast_left, [(ast.ops[0][0], ast_right)]), l_left + l_right
def closureOr(ast, gen, lambdaGen):
ast_left, l_left = closure(ast.nodes[0], gen, lambdaGen)
ast_right, l_right = closure(ast.nodes[1], gen, lambdaGen)
return Or([ast_left,ast_right]), l_left + l_right
def closureAnd(ast, gen, lambdaGen):
ast_left, l_left = closure(ast.nodes[0], gen, lambdaGen)
ast_right, l_right = closure(ast.nodes[1], gen, lambdaGen)
return And([ast_left,ast_right]), l_left + l_right
def closureNot(ast, gen, lambdaGen):
ast, l = closure(ast.expr, gen, lambdaGen)
return Not(ast), l
def closureList(ast, gen, lambdaGen):
a, l = iterList(ast.nodes, gen, lambdaGen)
return List(a), l
def closureDict(ast, gen, lambdaGen):
l = []
new_items = []
for (k, v) in ast.items:
ast_v, l_v = closure(v, gen, lambdaGen)
l = l + l_v
new_items = new_items + [(k, ast_v)]
return Dict(new_items), l
def closureSubscript(ast, gen, lambdaGen):
astN, l = closure(ast.expr, gen, lambdaGen)
return Subscript(astN, ast.flags, ast.subs), l
def closureIfExp(ast, gen, lambdaGen):
ast_test, l_test = closure(ast.test, gen, lambdaGen)
ast_then, l_then = closure(ast.then, gen, lambdaGen)
ast_else_, l_else_ = closure(ast.else_, gen, lambdaGen)
return IfExp(ast_test, ast_then, ast_else_), l_test+l_then+l_else_
def closureLambda(ast, gen, lambdaGen):
#First recurse into the body
new_body, l_body = closure(ast.code, gen, lambdaGen)
lambdaName = lambdaGen.inc().name()
write, read = varAnalysis.getVars(new_body)
free_vars = list((read - write) - set(ast.argnames))
free_vars_param = '$free_vars_' + lambdaName
#Add the free_var assignments to the start of the body
#i.e x = free_vars_X[0]; y = free_vars_X[1]
for i, var in enumerate(free_vars):
n_assign = Assign([AssName(var, 'OP_ASSIGN')], Subscript(Name(free_vars_param), 'OP_APPLY', [Const(i)]))
new_body.nodes = [n_assign] + new_body.nodes
#Create the function definition for the top level scope
newParams = [free_vars_param] + ast.argnames
funcDef = Lambda(newParams, ast.defaults, ast.flags, new_body)
#Create the local, closure conversion'd reference to the function
closedLambda = InjectFrom("big", CallRuntime(Name('create_closure'),[Const(lambdaName), List([Name(fvar) for fvar in free_vars])]))
return closedLambda, l_body + [(lambdaName, funcDef)]
def closureReturn(ast, gen, lambdaGen):
ast, l = closure(ast.value, gen, lambdaGen)
return Return(ast), l
def closureWhile(ast, gen, lambdaGen):
ast_test, l_test = closure(ast.test, gen, lambdaGen)
ast_body, l_body = closure(ast.body, gen, lambdaGen)
return While(ast_test, ast_body, None), l_test + l_body
def closureAssAttr(ast, gen, lambdaGen):
return ast, []
def closureGetattr(ast, gen, lambdaGen):
return ast, []
def closureGetTag(ast, gen, lambdaGen):
ast, l = closure(ast.arg, gen, lambdaGen)
return GetTag(ast), l
def closureInjectFrom(ast, gen, lambdaGen):
astN, l = closure(ast.arg, gen, lambdaGen)
return InjectFrom(ast.typ, astN), l
def closureProjectTo(ast, gen, lambdaGen):
astN, l = closure(ast.arg, gen, lambdaGen)
return ProjectTo(ast.typ, astN), l
def closureLet(ast, gen, lambdaGen):
ast_rhs, l_rhs = closure(ast.rhs, gen, lambdaGen)
ast_body, l_body = closure(ast.body, gen, lambdaGen)
return Let(ast.var, ast_rhs, ast_body), l_rhs + l_body
def closureIsType(ast, gen, lambdaGen):
astN, l = closure(ast.arg, gen, lambdaGen)
return IsType(ast.typ, astN), l
def closureThrowError(ast, gen, lambdaGen):
return ast, []
#The function list is given as a tuple of (FuncName, Lambda)
#Where FuncName is the name that the Lambda is assigned to
def closure(ast, gen, lambdaGen):
return {
Module: closureModule,
Stmt: closureStmt,
Printnl: closurePrintnl,
Const: closureConst,
UnarySub: closureUnarySub,
Add: closureAdd,
Discard: closureDiscard,
Assign: closureAssign,
Name: closureName,
AssName: closureAssName,
CallFunc: closureCallFunc,
CallRuntime: closureCallRuntime,
Compare: closureCompare,
Or: closureOr,
And: closureAnd,
Not: closureNot,
List: closureList,
Dict: closureDict,
Subscript: closureSubscript,
IfExp: closureIfExp,
Lambda: closureLambda,
Return: closureReturn,
While: closureWhile,
#AssAttr: closureAssAttr,
#Getattr: closureGetattr,
GetTag: closureGetTag,
InjectFrom: closureInjectFrom,
ProjectTo: closureProjectTo,
Let: closureLet,
IsType: closureIsType,
ThrowError: closureThrowError
}[ast.__class__](ast, gen, lambdaGen)
|
986,504 | e913c79e74f8e212378e2aeecf867a66221eee3f | import dao.JWTUserImplementation as JWTDao
async def isUserPresentByEmail(email: str) -> bool:
res = await JWTDao.isUserPresentByEmail(email)
return True if res is not None else False
async def getUserByEmail(user: JWTDao) -> dict:
res = await JWTDao.getUserByEmail(user)
if res is None:
return {}
return dict(res)
|
986,505 | 661c98b729343cfd53b800627117162f9910568d | """Unit-tests for ``sfini``."""
|
986,506 | 360d4ae3668369408b933c3db5e987799a63227b | from django.conf.urls.defaults import *
from twitter.tcal.views import main
#from django.contrib.comments.models import FreeComment
urlpatterns = patterns('',
url(r'^$', main.main, name='tcal'),
url(r'^week/$', main.week, name='anonymous_week'),
url(r'^week/(?P<username>\w+)/$', main.week, name='this_week'),
url(r'^week/(?P<username>\w+)/(?P<day>\d\d?)/(?P<month>\w+)/(?P<year>\d{4})/$', main.week, name='week'),
url(r'^ajax_week/$', main.ajax_week, name='ajax_this_week'),
url(r'^ajax_week/(?P<username>\w+)/$', main.ajax_week, name='ajax_username'),
url(r'^about/$', main.about, name='tcal_about'),
url(r'^blog/$', main.blog, name='anonymous_blog'),
url(r'^blog/(?P<username>\w+)/$', main.blog, name='blog'),
)
|
986,507 | 6bc975e59e4c1e291ccc1ef58cc7e9b23113d87c | import ccxt
from tabulate import tabulate
"""
Show exchanges list.
"""
def run(ctx):
table = [[exchange] for exchange in ccxt.exchanges]
print(tabulate(table, ['Exchanges'], tablefmt="grid"))
|
986,508 | f1fc1209589bd6b771fdb155ab30db9cc2569dc5 | import pygame
pygame.init() #초기화 (반드시 필요)
#화면 크기 설정
screen_width = 480 #가로크기
screen_height = 640 #세로크기
screen = pygame.display.set_mode((screen_width, screen_height))
# 화면 타이틀 설정
pygame.display.set_caption("Nado Game") #게임이름
#배경 이미지 불러오기
background = pygame.image.load("C:\\Users\\ljs74\\OneDrive\\바탕 화면\\임정석\\PythonWorkspace\\pygame_basic\\background.png")
#캐릭터(스프라이트) 불러오기
character = pygame.image.load("C:\\Users\\ljs74\\OneDrive\\바탕 화면\\임정석\\PythonWorkspace\\pygame_basic\\character.png")
character_size = character.get_rect().size #이미지의 크기를 구해옴
character_width = character_size[0] #캐릭터의 가로 크기
character_height = character_size[1] #캐릭터의 세로 크기
character_x_pos = (screen_width / 2) - (character_width / 2) #화면 가로의 절반 크기에 해당하는 곳에 위치(가로위치)
character_y_pos = screen_height - character_height #화면 세로 크기 가장 아래에 해당하는 곳에 위치(세로위치)
#이동할 좌표
to_x = 0
to_y = 0
#이벤트 루프(위에 코드까지 작성후 실행하면 아무것도 없기땜에 실행하고 바로 꺼져서)
running = True #게임이 진행중인가?(True면 계속 돌고있다는것)
while running: #게임이 진행되는동안
for event in pygame.event.get(): #어떤 이벤트가 발생하였는가?
if event.type == pygame.QUIT: #창이 닫히는 이벤트가 발생하였는가?
running = False #게임이 진행중이 아님
if event.type == pygame.KEYDOWN: #키가 눌러졌는지 확인
if event.key == pygame.K_LEFT: #캐릭터를 왼쪽으로
to_x -= 5 #to_x = to_x - 5
elif event.key == pygame.K_RIGHT: #캐릭터를 오른쪽으로
to_x += 5
elif event.key == pygame.K_UP: #캐릭터를 위로
to_y -= 5
elif event.key == pygame.K_DOWN: #캐릭터를 아래로
to_y += 5
if event.type == pygame.KEYUP: #방향키를 때면 멈춤
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
to_x = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
to_y = 0
character_x_pos += to_x
character_y_pos += to_y
#가로 경계값 처리
if character_x_pos < 0: #화면이 왼쪽으로 나갔을때
character_x_pos = 0
elif character_x_pos > screen_width - character_width:
character_x_pos = screen_width - character_width
#세로 경계값 처리
if character_y_pos < 0:
character_y_pos = 0
elif character_y_pos > screen_height - character_height:
character_y_pos = screen_height - character_height
screen.blit(background, (0, 0)) #배경그리기[맨왼쪽 맨위(0, 0)]
screen.blit(character, (character_x_pos, character_y_pos)) #캐릭터 그리기
pygame.display.update() #게임화면을 다시 그리기!![업데이트 해줌으로서 while문을 돌면서 계속 그려주는거(필수)]
#pygame 종료
pygame.quit() |
986,509 | aaac55b122718d888273841d0750c32247fe18fb | # 근우의 다이어리 꾸미기
# 그리디 또한 규칙을 찾는 것이 중요함
n = input()
check = '1' * len(n)
if len(n) == 1:
print(1)
elif int(n) >= int(check):
print(len(n))
else:
print(len(n)-1) |
986,510 | 0ac11e6af41f5e76addccf7053b61afb5a1bf6d7 | from Entity.SystemFunction import SystemFunction
p= SystemFunction("01002")
result=p.get_section_function_json()
print result
|
986,511 | 4a1649b0803fdc009e23c132a9cc42c0febc84ac | #!/usr/bin/env python
PACKAGE="micvision"
from dynamic_reconfigure.parameter_generator_catkin import *
gen = ParameterGenerator()
gen.add("inflation_radius", double_t, 0, "The inflation radius(m)", 0.3, 0, 1)
gen.add("robot_radius", double_t, 0, "The robot radius(m)", 0.2, 0, 0.5)
gen.add("laserscan_circle_step", int_t, 0, "Laser scan sampled every circle", 1, 1, 10)
gen.add("range_step", int_t, 0, "Robot location sample step(pixel)", 3, 1, 10)
gen.add("laserscan_anglar_step", int_t, 0, "At each location, we sampled the anglar(degree)", 6, 1, 10)
gen.add("min_valid_range", double_t, 0, "The minimum valid range(m)", 0.0, 0.0, 1)
gen.add("max_valid_range", double_t, 0, "The maximum valid range(m)", 10.0, 0.0, 40.0)
gen.add("quick_score", bool_t, 0, "Using quick score", True)
gen.add("quick_score_num", int_t, 0, "The quick score number", 8, 4, 20)
exit(gen.generate(PACKAGE, "micvision", "Localization"))
|
986,512 | 2eb79af4023726526799ac8c88b637bf34349d98 | # -*- coding: utf-8 -*-
from . import helpers
from . import models
import numpy as np
class WymSim:
#default init values
__dparms = np.array([3.,2.,0.1,100.])
__drtot = np.array([0.001,0.0025,0.005,0.01,0.025,0.05])
__dlrange = np.array([0.001,100.,2.])
__drp = 3
__dst = 3333
__dns = 0.05
__dmodfunc = models.wymfunc
def __init__(self,modfunc=__dmodfunc,parms=__dparms,rtot=__drtot,ligrange=__dlrange,reps=__drp,sets=__dst,noise=__dns):
'''Returns a Wyman model object'''
self.sets = sets
self.reps = reps
self.modfunc = modfunc
self.parms = parms
self.rtot = rtot
self.noise = noise
self.ligs = np.array([helpers.dilser(ligrange[0],ligrange[1],ligrange[2]) for i in range(len(self.rtot))])
self.bfrac = np.array([self.modfunc(self.parms,self.ligs[i],self.rtot[i]) for i in range(len(self.rtot))])
self.noised = np.array([[np.random.normal(self.bfrac,(self.noise*self.bfrac)) for i in range(self.reps)] for i in range(self.sets)])
self.meanset = np.array([self.noised[i].mean(axis=0) for i in range(len(self.noised))])
self.stdset = np.array([self.noised[i].std(axis=0) for i in range(len(self.noised))])
class WymSimTest:
#default init values
__dparms = np.array([3.,2.,0.1,100.])
__drtot = np.array([0.001,0.0025,0.005,0.01,0.025,0.05])
__dlrange = np.array([0.001,100.,2.])
__drp = 3
__dst = 3333
__dns = 0.05
__dmodfunc = models.wymfunc
def __init__(self,modfunc=__dmodfunc,parms=__dparms,rtot=__drtot,ligrange=__dlrange,reps=__drp,sets=__dst,noise=__dns):
'''Returns a Wyman model object'''
self.sets = sets
self.reps = reps
self.modfunc = modfunc
self.parms = parms
self.rtot = rtot
self.noise = noise
self.ligs = np.array([helpers.dilser(ligrange[0],ligrange[1],ligrange[2]) for i in range(len(self.rtot))])
self.bfrac = np.array([self.modfunc(self.parms,self.ligs[i],self.rtot[i]) for i in range(len(self.rtot))])
self.noised = np.array([[np.random.normal(self.bfrac,(self.noise*self.bfrac)) for i in range(self.reps)] for i in range(self.sets)])
self.meanset = np.array([self.noised[i].mean(axis=0) for i in range(len(self.noised))])
def subset(self,lo,hi):
self.meanset = np.array([[j[lo:hi] for j in i] for i in self.meanset])
self.ligs = np.array([j[lo:hi] for j in self.ligs])
self.bfrac = np.array([j[lo:hi] for j in self.ligs])
class WymSim_Hardlig:
#default init values
__dparms = np.array([3.,2.,0.1,100.])
__drtot = np.array([0.001,0.0025,0.005,0.01,0.025,0.05])
__drp = 3
__dst = 3333
__dns = 0.05
__dmodfunc = models.wymfunc
def __init__(self,ligs,modfunc=__dmodfunc,parms=__dparms,rtot=__drtot,reps=__drp,sets=__dst,noise=__dns):
'''Returns a Wyman model object'''
self.sets = sets
self.reps = reps
self.modfunc = modfunc
self.parms = parms
self.rtot = rtot
self.noise = noise
self.ligs = ligs
self.bfrac = np.array([self.modfunc(self.parms,self.ligs[i],self.rtot[i]) for i in range(len(self.rtot))])
self.noised = np.array([[np.random.normal(self.bfrac,(self.noise*self.bfrac)) for i in range(self.reps)] for i in range(self.sets)])
self.meanset = np.array([self.noised[i].mean(axis=0) for i in range(len(self.noised))])
self.stdset = np.array([self.noised[i].std(axis=0) for i in range(len(self.noised))])
class WymFit:
__dguess = np.array([10.,10.,10.,100.])
__dbounds = ((0.,0.,0.,0.,),(100.,100.,100.,10000.))
def __init__(self, model, guess=__dguess, bounds=__dbounds, weight=0, **kwargs):
'''Takes Wyman model object and performs nls fitting with optional weighting (1 = weight by s.d, 2 = weight by Y)'''
self.model = model
self.guess = guess
self.bounds = bounds
self.fits = helpers.fitwrap(self,weight=weight,**kwargs)
self.ests = np.array([self.fits[i].x for i in range(len(self.fits))])
self.k11 = self.ests[:,0]
self.k21 = self.ests[:,1]
self.k22 = self.ests[:,2]
self.l20 = self.ests[:,3]
|
986,513 | 4cd87dc9bc1c5ce52ae70764efb34aa790e87104 | from __future__ import print_function
import keras
from keras.models import load_model
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
import time
from PIL import ImageGrab
import cv2
import numpy as np
from press_keys import PressKey,ReleaseKey, Up
from make_data import take_part
num_classes= 2
modelx = Sequential()
modelx.add(Conv2D(32, (3, 3), padding='same',
input_shape=(100,75,1)))
modelx.add(Activation('relu'))
modelx.add(Conv2D(32, (3, 3)))
modelx.add(Activation('relu'))
modelx.add(MaxPooling2D(pool_size=(2, 2)))
#modelx.add(Dropout(0.25))
modelx.add(Conv2D(64, (3, 3), padding='same'))
modelx.add(Activation('relu'))
modelx.add(Conv2D(64, (3, 3)))
modelx.add(Activation('relu'))
modelx.add(MaxPooling2D(pool_size=(2, 2)))
#modelx.add(Dropout(0.25))
modelx.add(Flatten())
modelx.add(Dense(512))
modelx.add(Activation('relu'))
#modelx.add(Dropout(0.5))
modelx.add(Dense(num_classes))
modelx.add(Activation('softmax'))
modelx.load_weights('my_model_weights_4.h5')
'''
WIDTH = 80
HEIGHT = 60
train_data = np.load('training_data_v3.npy')
test = train_data[:600]
x_test = np.array([i[0] for i in test]).reshape(-1,WIDTH,HEIGHT,1)
y_test = np.array([i[1] for i in test])
y_test = keras.utils.to_categorical(y_test, num_classes)
res = modelx.predict(x_test)
res2 = []
for x in res:
res2.append(np.argmax(x))
print(res2)
'''
def Jump():
PressKey(Up)
def main():
last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
while(True):
screen = np.array(ImageGrab.grab(bbox=(300,350,650,540)))
print('fps: {} '.format(1./(time.time()-last_time)))
last_time = time.time()
screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
vertices = np.array([[0,160],[0,125], [200,125], [200,160]], np.int32)
screen = take_part(screen, [vertices])
screen = cv2.resize(screen, (100,75))
cv2.imshow('',screen)
moves = list(np.around(modelx.predict([screen.reshape(1,100,75,1)])[0]))
moves= moves[0]
print(moves)
if moves == [0.0]:
Jump()
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
main()
|
986,514 | 9ae9bf029f8c64e54e1c750174a9598a9126ae8f | import csv
from datetime import datetime
class CsvSaveAndRetrievePlastic(object):
# TODO make the file name and path coded here, not in the tests
file_name = 'NEXI/01a.plastic_setup/plastic_output.txt'
def write_plastic_to_file(self, test_case, plastic, date, embossing_file):
# this method writes a new plastic to a text file, plastic will be retrieved and verified after NB
# TODO: format the real date to remove fractions of seconds
# TODO make a new file with date every time unless one exists
with open(self.file_name, mode='a+') as output_file:
output_writer = csv.writer(output_file, delimiter=',')
output_writer.writerow([datetime.now(), test_case, plastic, date, embossing_file])
def retrieve_plastic_from_file(self, test_case, environment_date):
new_plastic_data = {}
my_file_content = []
with open(self.file_name, mode='r') as customer_file:
for row in csv.reader(customer_file):
if row:
# csv reader makes blank lines when reading the file, so this has to be here to get rid of them
my_file_content.append(row)
for row in reversed(my_file_content):
# reversed, so we check the latest plastics first
# looking for the first row with the right test case, environment date lower than given
if row[1] == test_case \
and datetime.strptime(row[3], '%d.%m.%Y') < datetime.strptime(environment_date, '%d.%m.%Y'):
new_plastic_data = {'plastic number': row[2], 'embossing file': row[4]}
break
return new_plastic_data
def retrieve_multiple_plastics_from_file(self, test_case, environment_date):
# this method looks for created plastics in the file with the correct test case name
# it looks for the first date that is lower than environment date
# then it returns a list of plastics with the same date
# in dictionaries with plastic number: and embossing file:
new_plastics = []
my_file_content = []
my_date = ''
with open(self.file_name, mode='r') as customer_file:
for row in csv.reader(customer_file):
if row:
# csv reader makes blank lines when reading the file, so this has to be here to get rid of them
my_file_content.append(row)
for row in reversed(my_file_content):
# reversed, so we check the latest plastics first
# looking for the first row with the right test case, environment date lower than given
if row[1] == test_case \
and datetime.strptime(row[3], '%d.%m.%Y') < datetime.strptime(environment_date, '%d.%m.%Y'):
my_date = datetime.strptime(row[3], '%d.%m.%Y')
break
for row in reversed(my_file_content):
if row[1] == test_case and datetime.strptime(row[3], '%d.%m.%Y') < my_date:
break
if row[1] == test_case and datetime.strptime(row[3], '%d.%m.%Y') == my_date:
new_plastics.append({'plastic number': row[2], 'embossing file': row[4]})
return new_plastics
|
986,515 | b0e7bad386015aa3283a6d5c44677fe99a328308 | from EC.EC import *
ec = EC(7,11,593899)
x = 12345
x *= 10
messagelist = [i for i in xrange(x, x+10)]
for m in messagelist:
p1,p2 = ec.at(m)
if ec.is_valid(p1):
print p1
elif ec.is_valid(p2):
print p2
pass
|
986,516 | 4d04c95db4c50577622ebd892fb6f7c3044cefeb | from venue_objects.helper import add_attr_db, convert_params
class PhrasesSample:
def __init__(self, db, db_result=None, **query):
attr_db = {
"id": "_id",
"text": "text",
"indices_start": "indices_start"
}
if db_result is None:
db_result = db.find("phrases_samples", convert_params(attr_db, query))
add_attr_db(self, db_result, attr_db)
|
986,517 | 7ea286d5c9e7e3f3106a43dd0025c52764e7b4be | print("Entrez une note.")
nn = input()
print("Entrez la note maximale à attribuer.")
pp = input()
note = int(nn)
lim = int(pp)
ratio = note/lim
if ratio == 1:
print("SS")
elif 1 > ratio >= 0.95:
print("S")
elif 0.95 > ratio >= 0.80:
print("A")
elif 0.80 > ratio >= 0.60:
print("B")
elif 0.60 > ratio >= 0.50:
print("C")
elif 0.50 > ratio >= 0.40:
print("D")
elif 0.40 > ratio >= 0.20:
print("E")
elif ratio < 0.20:
print("F")
else:
print("Entrée non valide")
|
986,518 | 5d856960daa8582e074ba87d398315e793712508 |
N = [[0.1, 0.5, 1, 0.5, 0.1],
[0.05, 0.7, 1, 0.7, 0.05],
[0.05, 0.2, 1, 0.2, 0.05],
[0.05, 0.05, 0.05, 0.05, 0.05],
[0.05, 0.05, 0.05, 0.05, 0.05]]
S = [[0.05, 0.05, 0.05, 0.05, 0.05],
[0.05, 0.05, 0.05, 0.05, 0.05],
[0.05, 0.2, 1, 0.2, 0.05],
[0.05, 0.7, 1, 0.7, 0.05],
[0.1, 0.5, 1, 0.5, 0.1]]
W = [[0.1, 0.05, 0.5, 0.05, 0.05],
[0.5, 0.7, 0.2, 0.05, 0.05],
[1, 1, 1, 0.05, 0.05],
[0.5, 0.7, 0.2, 0.05, 0.05],
[0.1, 0.05, 0.05, 0.05, 0.05]]
E = [[0.05, 0.05, 0.5, 0.05, 0.1],
[0.05, 0.05, 0.2, 0.7, 0.5],
[0.05, 0.05, 1, 1, 1],
[0.05, 0.05, 0.2, 0.7, 0.5],
[0.05, 0.05, 0.5, 0.05, 0.1]]
O = [[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]]
STOVE_SMOG_PRODUCTION = 2
STOVE_PRODUCTION_PERCENTAGE = 0.03
MAX_CONTAMINATION_VALUE = 256
SPREAD_COEFFICIENT = 0.5
HUMIDITY=1
WIND=1
RAIN=2
WIND_DIR=W
FLOW_RESISTANCE=0.8
|
986,519 | 72d41a5f77de2873b1e463452345ca0cf575222e | import pymysql
from common import database
# 글 정보를 저장아는 함수
def add_board_content(board_subject, board_content, board_writer_idx, board_info_idx, board_image) :
conn = database.get_connection()
sql = '''
insert into board_table(board_subject, board_writer_idx, board_date, board_content, board_image, board_info_idx)
values (%s, %s, sysdate(), %s, %s, %s)
'''
cursor = conn.cursor()
cursor.execute(sql, (board_subject, board_writer_idx, board_content, board_image, board_info_idx))
print(board_subject, board_writer_idx, board_content, board_image, board_info_idx)
conn.commit()
# 방금 작성한 글의 번호(글의 번호가 가장 큰 것)을 가져온다.
sql = '''
select max(board_idx) from board_table
where board_info_idx = %s
'''
cursor.execute(sql, (board_info_idx))
result = cursor.fetchone()
conn.close()
return result[0]
# 주어진 글 번호를 통해 게시글 정보를 가져와 반환하는 함수
def get_board_content(board_idx):
conn = database.get_connection()
sql = '''
select a1.board_subject, a2.user_name, a1.board_content, a1.board_image, a3.board_info_name
from board_table a1, user_table a2, board_info_table a3
where a1.board_writer_idx = a2.user_idx and a1.board_info_idx = a3.board_info_idx and a1.board_idx = %s
'''
cursor = conn.cursor()
print(board_idx)
cursor.execute(sql,(board_idx))
result = cursor.fetchone()
conn.close()
return result
# 게시판 이름 가져오는 함수
def get_board_info_name(board_info_idx):
conn = database.get_connection()
sql = '''
select board_info_name
from board_info_table
where board_info_idx = %s
'''
cusror = conn.cursor()
cusror.execute(sql, (board_info_idx))
result = cusror.fetchone()
conn.close()
return result[0]
# 게시글 목록을 가져오는 함수
def get_board_list(board_info_idx, page):
conn = database.get_connection()
# 현재 페이지의 글 목록의 시작 글의 인덱스
start_idx = (int(page) -1 ) * 10
sql = '''
select a1.board_idx, a1.board_subject, a2.user_name, date_format(a1.board_date, '%%Y-%%m-%%d')
from board_table a1, user_table a2
where a1.board_writer_idx = a2.user_idx and a1.board_info_idx = %s
order by a1.board_idx desc
limit %s, 10
'''
cursor = conn.cursor()
cursor.execute(sql, (board_info_idx, start_idx))
result = cursor.fetchall()
conn.close()
return result
# 전체 글의 개수를 반환한다.
def get_total_board_cnt(board_info_idx):
conn = database.get_connection()
sql = '''
select count(*)
from board_table
where board_info_idx = %s
'''
cursor = conn.cursor()
cursor.execute(sql,(board_info_idx))
result = cursor.fetchone()
conn.close()
return result[0]
|
986,520 | dce54d2d43eac03e9870a12774a1715fe49b0583 | #!/usr/bin/python
import json
import os
import urllib.request
import requests
# 下载歌曲并且设置参数
from base import set_mp3_info, xstr, init_folder, check_base_path
base_url = "http://39.98.194.220:3300"
def download_item(count, song_url, name, pic, artist, album, savePath):
if song_url is None or name is None:
print(name, '该资源不存在')
return
# 歌曲名 包含路径符号
name = name.replace('\\', '\')
file_name, ext = os.path.splitext(str(song_url).split("?")[0])
# 保存的文件地址
file_path = os.path.join(savePath, name + ext)
if os.path.exists(file_path):
print(name + " 已存在 -- " + count)
return
# 下载mp3
urllib.request.urlretrieve(song_url, file_path)
# 图片流文件
info = {'pic': requests.get(pic).content,
'title': name,
'artist': artist,
'album': album}
set_mp3_info(count, file_path, info)
# 获取歌曲信息
def build_song_info(song, count, save_path, cookie):
# 专辑封面
album_cover = "https://y.gtimg.cn/music/photo_new/T002R300x300M000{}.jpg".format(song["albummid"])
# 获取下载连接
url = "{}/song/url?id={}&mediaId={}&type={}&ownCookie=1".format(base_url, song["songmid"], song["strMediaMid"],
"320")
json = requests.get(url, cookies=cookie).json()
mp3_url = json.get("data")
download_item(str(count), mp3_url, song["songname"], album_cover, song["singer"][0]["name"],
song["albumname"], save_path)
# 获取歌单信息
def songlist_info(song_id, save_path, cookie):
url = "{}/songlist?id={}&ownCookie=1".format(base_url, song_id)
r = requests.get(url, cookies=cookie)
json = r.json()
data = json.get("data")
dissname = data["dissname"]
print("歌单名称:" + dissname)
print("歌单描述:" + xstr(data["desc"]))
print("歌单封面:" + data["logo"])
print("歌曲数量:" + str(data["songnum"]))
songlist = data["songlist"]
count = 0
save_path = os.path.join(save_path, dissname)
# 创建文件夹
init_folder(save_path)
for song in songlist:
count = count + 1
try:
build_song_info(song, count, save_path, cookie)
except Exception as e:
print(e)
print("歌曲id:{},歌曲名称:{},发生异常,联系管理员q:872019874".format(song_id, song["songname"]))
continue
def get_config():
with open('qq_music_config.json', 'r') as f:
data = json.load(f)
return data.get("base_path"), data.get("playId"), data.get("cookie")
if __name__ == '__main__':
(save_path, song_id, cookie_str) = get_config()
for param in (save_path, song_id, cookie_str):
assert '<' not in param, '请设置参数:' + param
cookie = {"cookie": cookie_str}
# 最后需要加上 '/'
save_path = check_base_path(save_path)
init_folder(save_path)
# 开始程序
print("歌单id:{} ---开始下载---".format(song_id))
songlist_info(song_id, save_path, cookie)
print("歌单id:{} ---结束下载---".format(song_id))
|
986,521 | 3818ba960f299f48fc406a6f2107ac24216f4f61 | # -*- coding: utf-8 -*-
"""
dynamic_learn.testsuite
~~~~~~~~~~~~~~~~~~~~~~~
:license: BSD, see LICENSE for more details.
"""
import unittest
import versus.tools.dataIO as dio
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
class LocalTestCase(unittest.TestCase):
"""
Setup relevant test context in this class
"""
def setUp(self):
# TODO - add setup for MySQLIO related testing
unittest.TestCase.setUp(self)
class TestMySQLConnect(LocalTestCase):
""" Test cases for Redis read/writes """
def test_simple(self):
raise NotImplementedError()
class TestMySQLCreateTable(LocalTestCase):
""" Test cases for Redis read/writes """
def test_simple(self):
mysql_inst = dio.DataIOMySQL()
mysql_inst.connect_lite()
self.assertTrue(mysql_inst.create_table('User'))
class TestMySQLInsert(LocalTestCase):
""" Test cases for Redis read/writes """
def test_simple(self):
mysql_inst = dio.DataIOMySQL()
mysql_inst.connect_lite()
mysql_inst.create_table('User')
self.assertTrue(mysql_inst.insert('User',
id=1,
name='me',
fullname='me',
password='pass',
date_join=0))
class TestMySQLFetchRows(LocalTestCase):
""" Test cases for Redis read/writes """
def test_simple(self):
mysql_inst = dio.DataIOMySQL()
mysql_inst.connect_lite()
mysql_inst.create_table('User')
mysql_inst.insert('User', id=1, name='me', fullname='me',
password='pass', date_join=0)
self.assertTrue(len(mysql_inst.fetch_all_rows('User')) > 0)
class TestMySQLDelete(LocalTestCase):
""" Test cases for Redis read/writes """
def test_simple(self):
mysql_inst = dio.DataIOMySQL()
mysql_inst.connect_lite()
mysql_inst.create_table('User')
for row in mysql_inst.fetch_all_rows('User'):
mysql_inst.delete(row)
|
986,522 | 35df0c11ddff67d1fe4f67d8fa2e1970529c1833 | #!D:\Py_projects\mjunitfw3_testsuite_nose\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'unittest-parallel==1.0.5','console_scripts','unittest-parallel'
__requires__ = 'unittest-parallel==1.0.5'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('unittest-parallel==1.0.5', 'console_scripts', 'unittest-parallel')()
)
|
986,523 | 7d7f03abb3d8d442544e629a1b0c286cd7eef1cf | from package import *
class twisted(EasyInstallPackage):
pass
|
986,524 | 277a169653e10ad26c1f361676bd611569d55cfd | """
source: https://leetcode.com/problems/palindrome-number/
"""
x = -121
def isPalindrome(x):
if x < 0:
return False
else:
return x == int(str(x)[::-1])
print(isPalindrome(x)) |
986,525 | abcbedad86bdc9505bcbb07cb743d0b8707b8bc1 | # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
from . import res_partner
from . import res_company
from . import account_invoice
from . import sale_export
from . import res_country
from . import product
from . import stock_picking
|
986,526 | df8cd9d587ce9a2302905f5c38fdc9b1a2ff34ca | import requests
import calendar;
import time;
from collections import Counter
from utils import utils
starting_time = calendar.timegm(time.gmtime())
########################################getting movie list#####################################################
movie_id_list = utils.get_total_media_ids(["primary_release_date.gte","primary_release_date.lte"],"movie")
movie_id_list = list(movie_id_list)
print(len(movie_id_list))
#############################getting cast for movies##############################################
cast_id_list = utils.get_total_cast_ids("movie",movie_id_list)
cast_id_list = list(cast_id_list)
print(len(cast_id_list))
####################################################getting tv show list######################################
tv_id_list = utils.get_total_media_ids(["air_date.gte","air_date.lte"],"tv")
tv_id_list = list(tv_id_list)
print(len(tv_id_list))
######################################################getting tv cast######################################
cast_id_list_tv = utils.get_total_cast_ids("tv",tv_id_list)
cast_id_list_tv = list(cast_id_list_tv)
###########################################showing results!!#################################################3
print('------------------------------ count is -----------------------------------')
print(len(set(cast_id_list_tv).intersection(set(cast_id_list))))
print('--------------------------execution time is-----------------------------')
print((calendar.timegm(time.gmtime())-starting_time)/60,":Mins")
|
986,527 | b048fe974882d8f2a4f6ee5ebc7fee70eee93e2a | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import time
import re
import os
import tempfile
import shutil
import subprocess
from automation import Automation
from devicemanager import NetworkTools, DMError
# signatures for logcat messages that we don't care about much
fennecLogcatFilters = [ "The character encoding of the HTML document was not declared",
"Use of Mutation Events is deprecated. Use MutationObserver instead." ]
class RemoteAutomation(Automation):
_devicemanager = None
def __init__(self, deviceManager, appName = '', remoteLog = None):
self._devicemanager = deviceManager
self._appName = appName
self._remoteProfile = None
self._remoteLog = remoteLog
# Default our product to fennec
self._product = "fennec"
self.lastTestSeen = "remoteautomation.py"
Automation.__init__(self)
def setDeviceManager(self, deviceManager):
self._devicemanager = deviceManager
def setAppName(self, appName):
self._appName = appName
def setRemoteProfile(self, remoteProfile):
self._remoteProfile = remoteProfile
def setProduct(self, product):
self._product = product
def setRemoteLog(self, logfile):
self._remoteLog = logfile
# Set up what we need for the remote environment
def environment(self, env = None, xrePath = None):
# Because we are running remote, we don't want to mimic the local env
# so no copying of os.environ
if env is None:
env = {}
# Except for the mochitest results table hiding option, which isn't
# passed to runtestsremote.py as an actual option.
if 'MOZ_HIDE_RESULTS_TABLE' in os.environ:
env['MOZ_HIDE_RESULTS_TABLE'] = os.environ['MOZ_HIDE_RESULTS_TABLE']
return env
def waitForFinish(self, proc, utilityPath, timeout, maxTime, startTime, debuggerInfo, symbolsPath):
""" Wait for tests to finish (as evidenced by the process exiting),
or for maxTime elapse, in which case kill the process regardless.
"""
# maxTime is used to override the default timeout, we should honor that
status = proc.wait(timeout = maxTime)
self.lastTestSeen = proc.getLastTestSeen
if (status == 1 and self._devicemanager.getTopActivity() == proc.procName):
# Then we timed out, make sure Fennec is dead
if maxTime:
print "TEST-UNEXPECTED-FAIL | %s | application ran for longer than " \
"allowed maximum time of %s seconds" % (self.lastTestSeen, maxTime)
else:
print "TEST-UNEXPECTED-FAIL | %s | application ran for longer than " \
"allowed maximum time" % (self.lastTestSeen)
proc.kill()
return status
def checkForJavaException(self, logcat):
found_exception = False
for i, line in enumerate(logcat):
if "REPORTING UNCAUGHT EXCEPTION" in line or "FATAL EXCEPTION" in line:
# Strip away the date, time, logcat tag and pid from the next two lines and
# concatenate the remainder to form a concise summary of the exception.
#
# For example:
#
# 01-30 20:15:41.937 E/GoannaAppShell( 1703): >>> REPORTING UNCAUGHT EXCEPTION FROM THREAD 9 ("GoannaBackgroundThread")
# 01-30 20:15:41.937 E/GoannaAppShell( 1703): java.lang.NullPointerException
# 01-30 20:15:41.937 E/GoannaAppShell( 1703): at org.mozilla.goanna.GoannaApp$21.run(GoannaApp.java:1833)
# 01-30 20:15:41.937 E/GoannaAppShell( 1703): at android.os.Handler.handleCallback(Handler.java:587)
# 01-30 20:15:41.937 E/GoannaAppShell( 1703): at android.os.Handler.dispatchMessage(Handler.java:92)
# 01-30 20:15:41.937 E/GoannaAppShell( 1703): at android.os.Looper.loop(Looper.java:123)
# 01-30 20:15:41.937 E/GoannaAppShell( 1703): at org.mozilla.goanna.util.GoannaBackgroundThread.run(GoannaBackgroundThread.java:31)
#
# -> java.lang.NullPointerException at org.mozilla.goanna.GoannaApp$21.run(GoannaApp.java:1833)
found_exception = True
logre = re.compile(r".*\): \t?(.*)")
m = logre.search(logcat[i+1])
if m and m.group(1):
top_frame = m.group(1)
m = logre.search(logcat[i+2])
if m and m.group(1):
top_frame = top_frame + m.group(1)
print "PROCESS-CRASH | java-exception | %s" % top_frame
break
return found_exception
def deleteANRs(self):
# delete ANR traces.txt file; usually need root permissions
traces = "/data/anr/traces.txt"
try:
self._devicemanager.shellCheckOutput(['rm', traces], root=True)
except DMError:
print "Error deleting %s" % traces
pass
def checkForANRs(self):
traces = "/data/anr/traces.txt"
if self._devicemanager.fileExists(traces):
try:
t = self._devicemanager.pullFile(traces)
print "Contents of %s:" % traces
print t
# Once reported, delete traces
self.deleteANRs()
except DMError:
print "Error pulling %s" % traces
pass
else:
print "%s not found" % traces
def checkForCrashes(self, directory, symbolsPath):
self.checkForANRs()
logcat = self._devicemanager.getLogcat(filterOutRegexps=fennecLogcatFilters)
javaException = self.checkForJavaException(logcat)
if javaException:
return True
# No crash reporting
return False
def buildCommandLine(self, app, debuggerInfo, profileDir, testURL, extraArgs):
# If remote profile is specified, use that instead
if (self._remoteProfile):
profileDir = self._remoteProfile
# Hack for robocop, if app & testURL == None and extraArgs contains the rest of the stuff, lets
# assume extraArgs is all we need
if app == "am" and extraArgs[0] == "instrument":
return app, extraArgs
cmd, args = Automation.buildCommandLine(self, app, debuggerInfo, profileDir, testURL, extraArgs)
# Remove -foreground if it exists, if it doesn't this just returns
try:
args.remove('-foreground')
except:
pass
#TODO: figure out which platform require NO_EM_RESTART
# return app, ['--environ:NO_EM_RESTART=1'] + args
return app, args
def getLanIp(self):
nettools = NetworkTools()
return nettools.getLanIp()
def Process(self, cmd, stdout = None, stderr = None, env = None, cwd = None):
if stdout == None or stdout == -1 or stdout == subprocess.PIPE:
stdout = self._remoteLog
return self.RProcess(self._devicemanager, cmd, stdout, stderr, env, cwd)
# be careful here as this inner class doesn't have access to outer class members
class RProcess(object):
# device manager process
dm = None
def __init__(self, dm, cmd, stdout = None, stderr = None, env = None, cwd = None):
self.dm = dm
self.stdoutlen = 0
self.lastTestSeen = "remoteautomation.py"
self.proc = dm.launchProcess(cmd, stdout, cwd, env, True)
if (self.proc is None):
if cmd[0] == 'am':
self.proc = stdout
else:
raise Exception("unable to launch process")
exepath = cmd[0]
name = exepath.split('/')[-1]
self.procName = name
# Hack for Robocop: Derive the actual process name from the command line.
# We expect something like:
# ['am', 'instrument', '-w', '-e', 'class', 'org.mozilla.fennec.tests.testBookmark', 'org.mozilla.roboexample.test/android.test.InstrumentationTestRunner']
# and want to derive 'org.mozilla.fennec'.
if cmd[0] == 'am' and cmd[1] == "instrument":
try:
i = cmd.index("class")
except ValueError:
# no "class" argument -- maybe this isn't robocop?
i = -1
if (i > 0):
classname = cmd[i+1]
parts = classname.split('.')
try:
i = parts.index("tests")
except ValueError:
# no "tests" component -- maybe this isn't robocop?
i = -1
if (i > 0):
self.procName = '.'.join(parts[0:i])
print "Robocop derived process name: "+self.procName
# Setting timeout at 1 hour since on a remote device this takes much longer
self.timeout = 3600
# The benefit of the following sleep is unclear; it was formerly 15 seconds
time.sleep(1)
@property
def pid(self):
pid = self.dm.processExist(self.procName)
# HACK: we should probably be more sophisticated about monitoring
# running processes for the remote case, but for now we'll assume
# that this method can be called when nothing exists and it is not
# an error
if pid is None:
return 0
return pid
@property
def stdout(self):
""" Fetch the full remote log file using devicemanager and return just
the new log entries since the last call (as a multi-line string).
"""
if self.dm.fileExists(self.proc):
try:
t = self.dm.pullFile(self.proc)
except DMError:
# we currently don't retry properly in the pullFile
# function in dmSUT, so an error here is not necessarily
# the end of the world
return ''
newLogContent = t[self.stdoutlen:]
self.stdoutlen = len(t)
# Match the test filepath from the last TEST-START line found in the new
# log content. These lines are in the form:
# 1234 INFO TEST-START | /filepath/we/wish/to/capture.html\n
testStartFilenames = re.findall(r"TEST-START \| ([^\s]*)", newLogContent)
if testStartFilenames:
self.lastTestSeen = testStartFilenames[-1]
return newLogContent.strip('\n').strip()
else:
return ''
@property
def getLastTestSeen(self):
return self.lastTestSeen
def wait(self, timeout = None):
timer = 0
interval = 5
if timeout == None:
timeout = self.timeout
while (self.dm.getTopActivity() == self.procName):
t = self.stdout
if t != '': print t
time.sleep(interval)
timer += interval
if (timer > timeout):
break
# Flush anything added to stdout during the sleep
print self.stdout
if (timer >= timeout):
return 1
return 0
def kill(self):
self.dm.killProcess(self.procName)
|
986,528 | 46e31575b33ee71a79fa77c194b6b2ad276bd8fb | """
Homework #06
CSCI-UA.003-001 Fall 2020
Edmund Cheng
ec3219
2020-11-01
"""
import random
def generate_word(syllables):
available_words = [
['age', 'roof', 'plain', 'slime', 'floor', 'fig', 'rode', 'oomph', 'flab', 'chit', 'creek', "we'll", 'brail', 'bay', 'big', 'salve', 'yaws', 'heal', 'bring', 'stir', 'bah', 'con', 'rone', 'team', 'nought', 'gill', 'rare', 'plains', 'bowls', 'wee', 'queue', 'gun', 'etch', 'set', 'mode', 'miss', 'ate', 'darn', 'rusk', 'mast', 'box', 'their', 'duds', 'depth', 'lien', 'rob', 'deek', 'word', 'quell', 'hark', 'home', 'pledge', 'brown', 'rune', 'pike', 'sprout', 'trace', 'cot', 'nob', 'nonce', 'dear', 'sense', 'sleek', 'poke', 'hut'],
['stunner', 'sucrose', 'begone', 'scorecard', 'humble', 'crouton', 'trimming', 'pudding', 'henchman', 'cackle', 'coffee', 'coma', 'aces', 'prudence', 'rematch', 'hipper', 'chopper', 'imprint', 'purple', 'second', 'lowbrow', 'faucet', 'bureau', 'commune', 'endive', 'stakeout', 'sourpuss', 'cave-in', 'shipyard', 'honors', 'kowtow', 'okra', 'haler', 'rattan'],
['echoless', 'fluidly', 'catchier', 'cathartic', 'lawnmower', 'physicist', 'huntedly', 'unzipping', 'centigrade', 'cheekily', 'tectonics', 'clearheaded', 'seditious', 'anodized', 'vehicle', 'sprightliest', 'prevention', 'vehement', 'mnemonics', 'steamroller', 'spikiest', 'persuasive', 'randomly', 'forensics', 'uneasy', 'dizziness', 'nonhuman', 'ethanol', 'connection', 'shrewishly', 'fingerprint'],
['nongalactic', 'lacerating', 'optometer', 'troglodytic', 'regradated', 'uniformize', 'chlorination', 'retotaling', 'acceptable', 'culmination', 'forbiddingness', 'immoveable', 'disconcerted', 'prosperity', 'vapourizing', 'profitably', 'envelopment', 'unsealable', 'librarian', 'transmissiveness', 'willowpattern', 'nationalise', 'devotedness', 'clangorously', 'likeableness', 'troubleshooting', 'weakheartedly', 'obsoleteness'],
['unsublimated', 'hyperanarchy', 'cylindrically', 'irrationally', 'quasipractical', 'sulfurization', 'undermeasuring', 'victoriously', 'disquietingly', 'metaphysical', 'quasihistoric', 'undesirably', 'soporiferous', 'underrespected', 'unsymmetrical', 'reliberating', 'curability', 'nonrevolution', 'nonscientific', 'marbleization', 'wearability', 'supervexation', 'misconjugating', 'inattentiveness', 'unruinable', 'incorporeal', 'stereoscopic', 'overpolicing', 'noncombustible', 'communicable', 'janitorial', 'etymologist', 'unconnectedness', 'personality', 'unmaintainable', 'geodesical', 'sociologist', 'fortitudinous', 'elimination'],
['disaffiliated', 'redeemability', 'misauthorization', 'renegotiated', 'zootomically', 'microbacteria', 'malleability', 'intermediaries', 'supportability', 'eliminatory', 'nonhierarchical', 'quasiadvantageous', 'palaeontology', 'typographically', 'radioactively', 'hyperpotassemic', 'collapsibility', 'selfdramatization', 'hallucinatory', 'megalomania', 'communicativeness', 'quasisatirical', 'nontechnological', 'electrosensitive', 'overintensity', 'excommunicating', 'fundamentality', 'photoelectrical', 'visualization', 'incommensurable', 'noncontinuity', 'etymological', 'overemotional'],
['electrometallurgist', 'discreditability', 'nonperfectibility', 'etherealization', 'inexhaustibility', 'unautomatically', 'overdeliberated', 'nonuniversality', 'encyclopaedically', 'paradoxicality', 'hieroglyphically', 'hypercivilization', 'biogenetically', 'incompatibility', 'unconstitutionalism', 'unutilitarian', 'overidealizing', 'transcendentalization']
]
if syllables not in range(1,8):
return None
else:
word = available_words[syllables-1][random.randint(1, len(available_words[syllables-1])-1)]
return word
def generate_line(syllables_in_line):
syllables = 0
string = ''
while syllables < syllables_in_line:
new_num = syllables_in_line - syllables
random_num = random.randint(1, new_num)
string += generate_word(random_num)
syllables += random_num
string += ' '
return string
def generate_lines(all_lines):
poem = ''
for i in range(len(all_lines)):
poem += generate_line(all_lines[i])
poem += '\n'
return poem
# Generate a poem
choice = input('I would like to write some poetry for you. Would you like a... \n * (h)aiku \n * (t)anka \n * (r)andom '
'5 line poem, or do you want to \n * (s)pecify lines and syllables for each line?\n> ')
if choice == 'h':
print('Here is your poem (5-7-5) \n=====')
print(generate_lines([5,7,5]))
elif choice == 't':
print('Here is your poem (5-7-5-7-7) \n=====')
print(generate_lines([5,7,5,7,7]))
elif choice == 'r':
line1 = random.randint(1,7)
line2 = random.randint(1,7)
line3 = random.randint(1,7)
line4 = random.randint(1,7)
line5 = random.randint(1,7)
print(f'Here is your poem ({line1}-{line2}-{line3}-{line4}-{line5}) \n=====')
print(generate_lines([line1, line2, line3, line4, line5]))
elif choice == 's':
count = 1
specified_poem = ''
while True:
num_syllables = int(input(f'How many syllables for line(s) {count}?\n> '))
yes_or_nah = input(f'There are currently {count} line(s). Add another line (y/n)?\n> ')
specified_poem += generate_line(num_syllables)
specified_poem += '\n'
if yes_or_nah == 'y':
count += 1
# num_syllables = int(input(f'How many syllables for lines {count}?\n> '))
else:
break
print(specified_poem)
else:
print('ERROR')
print('A crash reduces \nYour expensive computer \nTo a simple stone.')
|
986,529 | 8066267a7a74fcc9d7a995b197aa4e347024da23 | class Schema:
BODY = 'body'
QUERY_PARAMETER = 'query_parameter'
URL_PARAMETER = 'url_parameter'
@staticmethod
def validate_body(schema):
return {Schema.BODY: schema()}
@staticmethod
def validate_query_parameter(schema):
return {Schema.QUERY_PARAMETER: schema()}
@staticmethod
def validate_url_parameter(schema):
return {Schema.URL_PARAMETER: schema()}
|
986,530 | dd345b87f74ed09a249069c74eaaf6a17cf34a72 | from ..classes import Message
from ..helpers import SendMessage, UpdateConfig, print_bridge_network, print_LAN_network
import math
def implement_protocol(bridge_network, LAN_network):
"""
Implements the Spanning Tree Protocol algorithm after
the construction of the network topology.
"""
spawned = [] # stores messages that have been sent in each iteration
received = [] # stores received messages in each iteration
curr_time = 0
# initial message spawned by each bridge.
for bridge in bridge_network:
msg = Message(bridge.bridge_id, 0, bridge, -1, None)
spawned.append(msg)
# first iteration.
"""
Pops each message in the spawned list(could've been implemented
as a queue) and simulates the sending using the SendMessage() function
(defined in helpers.py).
"""
while spawned:
m = spawned.pop(0)
received_by_set = SendMessage(m, bridge_network, LAN_network)
for message in received_by_set:
received.append(message)
curr_time += 1
# subsequent iterations
while True:
# clear out spawned
spawned = []
while received:
# TODO: add received trace.
m = received.pop(0)
to_be_published = UpdateConfig(m, bridge_network)
if to_be_published.root != -1:
spawned.append(to_be_published)
if not spawned:
break
while spawned:
m = spawned.pop(0)
received_by_set = SendMessage(m, bridge_network, LAN_network)
for message in received_by_set:
received.append(message)
curr_time += 1
def print_bridge_root_ports(bridge_network):
print()
print('Root ports for bridges: ')
print()
for bridge in bridge_network:
print(f'{bridge.bridge_id} {bridge.root_port[0]}')
print()
def print_port_statuses(bridge_network, LAN_network):
for i in range(len(LAN_network)):
temp = math.inf
for adj_bridge in LAN_network[i].adj_bridges:
if adj_bridge < temp:
temp = adj_bridge
LAN_network[i].desig_port = temp
print()
# print("Designated ports for lans: ")
print()
# print_LAN_network(LAN_network)
print()
for bridge in bridge_network:
# print(f'B{bridge.bridge_id}:')
for j in range(len(bridge.adj_LANs)):
try:
LAN = bridge.adj_LANs[j]
except IndexError:
break
flag = 0
c = LAN
print(f' {c}-', end = '')
if c == bridge.root_port[0]:
print('RP', end = '')
flag = 1
for LAN in LAN_network:
if (c == LAN.lan_id) and (bridge.bridge_id == LAN.desig_port) and (flag == 0):
print('DP', end = '')
flag = 1
break
if flag == 0:
print('NP', end='')
list(filter((c).__ne__, bridge.adj_LANs))
j -= 1
print() |
986,531 | b05c85d66e3b6d649c60f10601cc4423028eb0c2 | #!/usr/bin/python
import irctestframework.irctest
m = irctestframework.irctest.IrcTest()
c1a = m.new('c1a')
m.connect()
m.send(c1a, "FAKEREPUTATION 127.0.0.1 500")
m.expect(c1a, "Confirm setting reputation", "Reputation for.*127.0.0.1.*500");
m.clearlog()
print
|
986,532 | ce2df328194842d586b1abc3b16311b74faf4027 | from tkinter import *
SQUARE_SIZE = 100
SQUARE_DST = 10
SQUARE_COLOUR = "#ffffff"
BG_COLOUR = "#e05e00"
FIELD_BG_COLOUR = "#000000"
WIN_FONT = "consolas 9"
WIDGET_PADDING = 5
PLAYER_TYPES = ["Human", "Random Bot", "Easy Bot", "Medium Bot", "Hard Bot", "Extreme Bot", "Impossible Bot", "Greedy Bot"]
HUMAN, RANDOM, EASY, MEDIUM, HARD, EXTREME, IMPOSSIBLE, GREEDY = 0, 1, 2, 3, 4, 5, 6, 7
STATES = ["Settings", "Game"]
SETTINGS, GAME = 0, 1
# Requirements:
# The widget must have an assigned parent;
# The widget can only be a label;
# The widget must also be assigned in a grid environment.
def create_label(widget, text, row=0, column=0, columnspan=1, padx=WIDGET_PADDING, sticky="nsew"):
widget.configure(text=text, bg=BG_COLOUR)
widget.grid(row=row, column=column, columnspan=columnspan, padx=padx, sticky=sticky)
return widget
# Requirements:
# The widget must have an assigned parent and command;
# The widget can only be a button;
# The widget must also be assigned in a grid environment.
def create_button(widget, text, row, column, columnspan=1, padx=WIDGET_PADDING, pady=WIDGET_PADDING):
widget.configure(text=text)
widget.grid(row=row, column=column, columnspan=columnspan, padx=padx, pady=pady)
return widget
# Requirements:
# The widget must have an assigned parent;
# The widget can only be an entry;
# The widget must also be assigned in a grid environment.
def create_entry(widget, row=0, column=1, columnspan=1):
widget.grid(row=row, column=column, columnspan=columnspan)
return widget
# Requirements:
# The widget must have an assigned parent, variable and options;
# The widget can only be an OptionMenu;
# The widget must also be assigned in a grid environment.
def create_dropdown(widget, row=0, column=1, columnspan=1):
widget.grid(row=row, column=column, columnspan=columnspan)
return
# Creates the requested state, if it doesn't exist it throws an exception
# Requirements:
# state must be given as a string
def state_factory(state, root, player_names=None):
if state == STATES[SETTINGS]:
return Settings(root)
elif state == STATES[GAME]:
return Game(root, player_names)
else:
raise Exception("Wrong name")
class State:
def __init__(self, root, state):
self.states = {}
self.players = []
self.current_state = STATES[SETTINGS]
self.root = root
settings_state = state_factory(state, root)
self.states[STATES[SETTINGS]] = settings_state
# Puts the correct frame on top.
# Requirements:
# frame_key must be a key of frames
def show_frame(self, frame_key):
self.states[frame_key].main_frame.tkraise()
return
# Makes sure that the names are stored and that the game starts.
def start_game(self):
current_state = self.states[STATES[SETTINGS]]
player1_entry = current_state.player1_name_entry.get()
player2_entry = current_state.player2_name_entry.get()
player1_name = "Player 1" if not player1_entry else player1_entry
player2_name = "Player 2" if not player2_entry else player2_entry
self.players = [{"name": player1_name, "player_type": current_state.player1},
{"name": player2_name, "player_type": current_state.player2}]
self.update_state(STATES[GAME])
# Makes sure that the requested stated will be the new one.
# If the requested state already exists it will update to that one.
# Requirements:
# state_name must be in state_factory
def update_state(self, state_name):
if not self.states.keys().__contains__(state_name):
new_state = state_factory(state_name, self.root, self.players)
self.states[state_name] = new_state
if state_name == STATES[GAME]:
new_state.update_button.configure(command=lambda: self.update_state(STATES[SETTINGS]))
self.current_state = state_name
self.show_frame(state_name)
# Inputs:
# player_id: x or o, depending on who's playing
# Updates the label that says who's turn it is to the requested player's name
def update_turnlabel(self, player_name, player_id):
self.states[STATES[GAME]].turnlabel.configure(text=("It's " + player_name + "'s turn. (" + player_id + ")"))
class Game:
# Creates the main frame of the game state with all widgets
def __init__(self, root, player_names):
game_frame = Frame(root, bg=BG_COLOUR)
game_frame.grid(row=0, column=0, sticky="nsew")
instruction_frame = Frame(game_frame, bg=BG_COLOUR)
self.reset_button = create_button(Button(game_frame), "Reset Game", 0, 0)
self.update_button = create_button(Button(game_frame), "Update Players", 0, 1)
player_name = "[PLAYER]"
self.turnlabel = create_label(Label(game_frame), "It's " + player_name + "'s turn", row=2, columnspan=2)
self.result_labels = []
result_frame = Frame(game_frame, bg=BG_COLOUR)
create_label(Label(result_frame), player_names[0]["name"])
create_label(Label(result_frame), "Tie", column=1)
create_label(Label(result_frame), player_names[1]["name"], column=2)
self.result_labels.append(create_label(Label(result_frame), "-", row=1))
self.result_labels.append(create_label(Label(result_frame), "-", row=1, column=1))
self.result_labels.append(create_label(Label(result_frame), "-", row=1, column=2))
result_frame.grid(row=1, column=0, columnspan=3)
field_frame = Frame(game_frame, bg=FIELD_BG_COLOUR)
self.field_labels = [[], [], []]
self.field = [[], [], []]
for i in range(len(self.field)):
for j in range(len(self.field)):
self.create_square(field_frame, i, j)
field_frame.grid(row=3, column=0, columnspan=3)
win_frame = Frame(game_frame, bg=BG_COLOUR)
win_frame.option_add("*font", WIN_FONT)
win_text = ""
info_text = "Press r to reset the game"
self.win_label = create_label(Label(win_frame), win_text, row=0, columnspan=3)
create_label(Label(win_frame), info_text, row=1, columnspan=3)
self.win_frame = win_frame
self.field_frame = field_frame
self.main_frame = game_frame
# Creates one square of the field
# Inputs:
# parent = master widget of the requested square
def create_square(self, parent, row, column):
# Inspired by Tom in thread https://stackoverflow.com/questions/16363292/label-width-in-tkinter
new_frame = Frame(parent, width=SQUARE_SIZE, height=SQUARE_SIZE)
new_frame.pack_propagate(0)
new_label = Label(new_frame, text=" ", bg=SQUARE_COLOUR)
self.field_labels[row].append(new_label)
self.field[row].append(None)
new_label.pack(fill=BOTH, expand=1)
new_frame.grid(row=row, column=column, padx=SQUARE_DST / 2, pady=SQUARE_DST / 2)
# Sets all field elements to -1, and empties all field labels and makes them white
def clear_field(self):
for i in range(len(self.field_labels)):
for j in range(len(self.field_labels[i])):
self.field_labels[i][j].configure(text=" ", bg=SQUARE_COLOUR)
self.field[i][j] = None
# Increases the counter for the wins, if it's a tie you can leave out the player_id
def add_win(self, result_id=2):
if result_id != 0:
result_id = 1 if result_id == 2 else 2
result_label = self.result_labels[result_id]
result_label_text = str(1) if result_label['text'] == "-" else str(int(result_label['text']) + 1)
result_label.configure(text=result_label_text)
def reset_results(self):
for label in self.result_labels:
label.configure(text="-")
class Settings:
# Creates the main frame of the settings state with all widgets
def __init__(self, root):
settings_frame = Frame(root, bg=BG_COLOUR)
settings_frame.grid(row=0, column=0, sticky="nsew")
player1_dropdown_frame = Frame(settings_frame, bg=BG_COLOUR)
player1_entry_frame = Frame(settings_frame, bg=BG_COLOUR)
player2_dropdown_frame = Frame(settings_frame, bg=BG_COLOUR)
player2_entry_frame = Frame(settings_frame, bg=BG_COLOUR)
create_label(Label(settings_frame), "Enter the info for the players", columnspan=2)
create_label(Label(player1_dropdown_frame), "Player 1", padx=WIDGET_PADDING * 4)
create_label(Label(player1_entry_frame), "Name player 1:")
create_label(Label(player2_dropdown_frame), "Player 2", padx=WIDGET_PADDING * 4)
create_label(Label(player2_entry_frame), "Name player 2:")
player1 = StringVar()
player1.set(PLAYER_TYPES[0])
create_dropdown(OptionMenu(player1_dropdown_frame, player1, *PLAYER_TYPES))
self.player1 = player1
player2 = StringVar()
player2.set(PLAYER_TYPES[0])
create_dropdown(OptionMenu(player2_dropdown_frame, player2, *PLAYER_TYPES))
self.player2 = player2
self.player1_name_entry = create_entry(Entry(player1_entry_frame))
self.player2_name_entry = create_entry(Entry(player2_entry_frame))
self.start_button = create_button(Button(settings_frame), "Go!",
5, 0, 2, pady=WIDGET_PADDING * 2)
# Putting the frames in the main_frame
player1_dropdown_frame.grid(row=1, pady=(WIDGET_PADDING * 4, WIDGET_PADDING))
player1_entry_frame.grid(row=2)
player2_dropdown_frame.grid(row=3, pady=(WIDGET_PADDING * 4, WIDGET_PADDING))
player2_entry_frame.grid(row=4)
self.main_frame = settings_frame
|
986,533 | 45a4eb5333215f148ce6faaf92ffff9adce82860 | #%%
import xarray as xr
if __name__ == '__main__':
data_dir = '/home/zzhzhao/data/CMFD_Prec'
with xr.open_mfdataset(f'{data_dir}/*.nc', concat_dim='time', parallel=True) as ds:
### 青藏高原范围
lat_min, lat_max = 27, 40
lon_min, lon_max = 73, 105
### 提取该范围
ds_TP = ds.sel(lat=slice(lat_min, lat_max), lon=slice(lon_min, lon_max))
### 输出成新文件
output_dir = '/home/zzhzhao/data/CMFD_Prec_TP'
print('>> 正在输出netcdf <<')
ds_TP.to_netcdf(f'{output_dir}/CMFD_Prec_TP_1979-2018.nc', mode='w', format='NETCDF4') |
986,534 | 5931d8e991e05144fc912a4cb6a6fbb77a77c263 | import _plotly_utils.basevalidators
class PatternValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="pattern", parent_name="bar.marker", **kwargs):
super(PatternValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Pattern"),
data_docs=kwargs.pop(
"data_docs",
"""
bgcolor
Sets the background color of the pattern fill.
Defaults to a transparent background.
bgcolorsrc
Sets the source reference on Chart Studio Cloud
for bgcolor .
shape
Sets the shape of the pattern fill. By default,
no pattern is used for filling the area.
shapesrc
Sets the source reference on Chart Studio Cloud
for shape .
size
Sets the size of unit squares of the pattern
fill in pixels, which corresponds to the
interval of repetition of the pattern.
sizesrc
Sets the source reference on Chart Studio Cloud
for size .
solidity
Sets the solidity of the pattern fill. Solidity
is roughly the fraction of the area filled by
the pattern. Solidity of 0 shows only the
background color without pattern and solidty of
1 shows only the foreground color without
pattern.
soliditysrc
Sets the source reference on Chart Studio Cloud
for solidity .
""",
),
**kwargs
)
|
986,535 | 9fdffd5c9b329a511604680cf075c85387ac2a62 | from abc import abstractmethod
from enum import Enum
from typing import TYPE_CHECKING
from galaxy_crawler.models import utils
if TYPE_CHECKING:
from typing import List, Optional
from sqlalchemy.orm.session import Session
class ModelInterfaceMixin(object):
@classmethod
@abstractmethod
def from_json(cls, json_obj: 'dict', session: 'Session') -> 'ModelInterfaceMixin':
raise NotImplementedError
def exists(self, session: 'Session') -> 'bool':
pk = getattr(self, self._pk, None)
if pk is None:
raise NotImplementedError('_pk is not imeplemented yet.')
return session.query(self.__class__).get(pk)
@classmethod
def get_by_pk(cls, primary_key, session: 'Session') -> 'ModelInterfaceMixin':
return session.query(cls).filter_by(**{cls._pk: primary_key}).one_or_none()
def update_or_create(self, session: 'Session') -> 'ModelInterfaceMixin':
if self.exists(session):
pk = getattr(self, self._pk, None)
if pk is None:
raise NotImplementedError('_pk is not imeplemented yet.')
exists_obj = self.get_by_pk(pk, session)
return utils.update_params(exists_obj, self)
return self
class RoleTypeEnum(Enum):
ANS = "Ansible"
CON = "Container Enabled"
APP = "Container App"
def description(self) -> str:
return self.value
class LicenseType(Enum):
MIT = 'MIT License'
GPL = 'GNU General Public License'
GPLv2 = 'GNU General Public License v2'
GPLv3 = 'GNU General Public License v3'
LGPL = 'GNU Lesser General Public License'
LGPLv2 = 'GNU Lesser General Public License v2'
LGPLv21 = 'GNU Lesser General Public License v2.1'
LGPLv3 = 'GNU Lesser General Public License v3'
AGPL = 'GNU Affero General Public License'
AGPLv2 = 'GNU Affero General Public License v2'
AGPLv3 = 'GNU Affero General Public License v3'
APACHE = 'Apache License'
APACHEv1 = 'Apache Software License 1.0'
APACHEv11 = 'Apache Software License 1.1'
APACHEv2 = 'Apache License 2.0'
CC_BY = 'Creative Commons Attribution 4.0 license'
CC_BY_SA = 'Creative Commons Attribution (Share Alike) 4.0 license'
CC_BY_ND = 'Creative Commons Attribution (No Derivative Works) 4.0 license'
CC_BY_NC = 'Creative Commons Attribution (Noncommercial) 4.0 license'
CC_BY_NC_SA = 'Creative Commons Attribution (Noncommercial, Share Alike) 4.0 license'
CC_BY_NC_ND = 'Creative Commons Attribution (Noncommercial, No Derivative Works) 4.0 license'
CC0 = 'Creative Commons Zero'
BSD = 'BSD License'
BSD2 = 'BSD 2 Clause License'
BSD3 = 'BSD 3 Clause License'
APLv2 = 'Apple Public Source License v2'
MPLv2 = 'Mozilla Public License v2'
EPL = 'Eclipse Public License'
CISCO = 'CISCO SAMPLE CODE LICENSE'
@classmethod
def normalize(cls, license_str: str) -> 'List[LicenseType]':
splitted = license_str.split(',')
licenses = []
for string in splitted:
licenses.append(parse_mit(string))
licenses.append(parse_apache(string))
licenses.append(parse_bsd(string))
licenses.append(parse_cc(string))
licenses.append(parse_gpl(string))
licenses.append(parse_apl(string))
licenses.append(parse_epl(string))
licenses.append(parse_cisco(string))
return list(set([l for l in licenses if l is not None]))
@property
def description(self) -> 'str':
return self.value
def parse_mit(license_str: str) -> 'Optional[LicenseType]':
if 'MIT' in license_str:
return LicenseType.MIT
return None
def parse_agpl(license_str: str) -> 'LicenseType':
if '2' in license_str:
return LicenseType.AGPLv2
elif '3' in license_str:
return LicenseType.AGPLv3
else:
return LicenseType.AGPL
def parse_lgpl(license_str: str) -> 'LicenseType':
if '2.1' in license_str:
return LicenseType.LGPLv21
elif '2' in license_str:
return LicenseType.LGPLv2
elif '3' in license_str:
return LicenseType.LGPLv3
else:
return LicenseType.LGPL
def parse_gpl(license_str: str) -> 'Optional[LicenseType]':
license_type = None
license_str = license_str.lower()
if 'gnu' in license_str or 'gpl' in license_str:
if 'agpl' in license_str or 'affelo' in license_str:
license_type = parse_agpl(license_str)
elif 'lgpl' in license_str or 'lesser' in license_str:
license_type = parse_lgpl(license_str)
elif '2' in license_str:
license_type = LicenseType.GPLv2
elif '3' in license_str:
license_type = LicenseType.GPLv3
else:
license_type = LicenseType.GPL
return license_type
def parse_cc(license_str: str) -> 'Optional[LicenseType]':
license_type = None
sa = False
nc = False
nd = False
license_str = license_str.lower()
if 'cc' in license_str or 'creative' in license_str:
if 'sa' in license_str or 'share' in license_str:
sa = True
if 'nd' in license_str or 'derivative' in license_str:
nd = True
if 'nc' in license_str or 'commercial' in license_str:
nc = True
if nc:
if sa:
license_type = LicenseType.CC_BY_NC_SA
elif nd:
license_type = LicenseType.CC_BY_NC_ND
else:
license_type = LicenseType.CC_BY_NC
elif sa:
license_type = LicenseType.CC_BY_SA
elif nd:
license_type = LicenseType.CC_BY_ND
elif 'zero' in license_str or '0' in license_str:
license_type = LicenseType.CC0
else:
license_type = LicenseType.CC_BY
return license_type
def parse_bsd(license_str: str) -> 'Optional[LicenseType]':
license_type = None
license_str = license_str.lower()
if 'bsd' in license_str:
if '2' in license_str:
return LicenseType.BSD2
elif '3' in license_str:
return LicenseType.BSD3
else:
return LicenseType.BSD
return license_type
def parse_apl(license_str: str) -> 'Optional[LicenseType]':
if 'apple' in license_str.lower() or 'apl' in license_str.lower():
return LicenseType.APLv2
return None
def parse_apache(license_str: str) -> 'Optional[LicenseType]':
if 'apache' in license_str.lower():
if '2.0' in license_str or '2' in license_str:
return LicenseType.APACHEv2
elif '1.1' in license_str:
return LicenseType.APACHEv11
elif '1.0' in license_str or '1' in license_str:
return LicenseType.APACHEv1
else:
return LicenseType.APACHE
return None
def parse_cisco(license_str: str) -> 'Optional[LicenseType]':
if 'cisco' in license_str.lower():
return LicenseType.CISCO
return None
def parse_epl(license_str: str) -> 'Optional[LicenseType]':
license_str = license_str.lower()
if 'epl' in license_str or 'eclipse' in license_str:
return LicenseType.EPL
return None
|
986,536 | 9066899e0801e4888f658bbf29755728529a26d6 | from Parser import differentiate
import argparse
from Function_Parser import parse_function
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--var', default='x', type=str)
parser.add_argument('expression')
return parser
if __name__ == '__main__':
arg_parser = parse_args().parse_args()
var = arg_parser.var
derivative = differentiate(var, arg_parser.expression).derivative()
parsed_derivative = parse_function(derivative)
print(parsed_derivative)
|
986,537 | fe194e9bf3b85115c4a6daab15a815a0b989ff7f | import logging
import logging.config
import os
from time_delta import DatetimeDelta
class TimezoneFormatter(logging.Formatter):
def __init__(self, fmt, datefmt,timezone=None):
#self.timezone = timezone or pytz.timezone('Asia/ShangHai')
super(TimezoneFormatter, self).__init__(fmt, datefmt)
def formatTime(self, record, datefmt=None):
if datefmt:
dt = DatetimeDelta.now()
return dt.strftime(datefmt)
else:
return super(TimezoneFormatter, self).formatTime(record, datefmt)
file_path = os.path.dirname(os.path.abspath(__file__))
ubcconfig_file = os.path.join(file_path,'logger.conf')
logging.config.fileConfig(ubcconfig_file)
logger = logging.getLogger('guest')
for handler in logger.handlers:
handler.setFormatter(TimezoneFormatter(handler.formatter._fmt, handler.formatter.datefmt,)) |
986,538 | 1f48478d02433c65490b17aceee7652112e4c457 | """@package docstring
District class contains district information.
This class is a parameter to all the metric fucntions,
either individually or a part of the district plans.
"""
class District:
def __init__(self, id=None, population=None, votes=None, party_votes=None, geometry=None):
"""
:param id: the unique identifier for this district
:param population: population of this district
:param votes: all votes in this district for the election
:param party_votes: dictionary whose keys are strings (party) and values (votes)
:param geometry: spatial geometry of this district
"""
self.id = id
self.population = population
self.votes = votes
self.party_votes = party_votes
self.geometry = geometry
|
986,539 | c42e3426c2c9ce8c395af6c3d1affe8188daffb0 |
__author__="Harshit.Kashiv"
import MySQLdb
if __name__ == '__main__':
print 'Hi'
host="localhost"
user="root"
password="Km7Iv80l"
database="cja_test_anand"
unix_socket="/tmp/mysql.sock"
db = MySQLdb.connect(host = host, user = user, passwd=password, db = database, unix_socket = unix_socket)
cur = cursor = db.cursor(MySQLdb.cursors.DictCursor)
#cmd = '''select * from check2 limit 1'''
#cmd = '''insert into check2 values (1,2)'''
cmd = '''delete from jobrec'''
cur.execute(cmd)
#for i in xrange(24, 40):
# cmd = '''insert into jobrec values (''' + str(i) + ''', '1,2,3')'''
params = []
for i in [2,2,2]:
#cmd = '''INSERT INTO jobrec (resid, jobs2bsent) VALUES (%s, %s) on duplicate key update resid = %s, jobs2bsent = %s, (resid, jobs2bsent)'''
resid = i
jobs2bsent = '1,2,3'
params.append((resid, jobs2bsent))
print params
print cmd
print resid
try:
cmd = '''INSERT IGNORE INTO jobrec (resid, jobs2bsent) VALUES (%s, %s)'''
cur.executemany(cmd, params)
except:
db.rollback()
else:
db.commit()
|
986,540 | 48c8512184c00e2da80d704cb4bd778b6a67ffde | import asyncio
import os
from . import toolbox, mask, fs
from aiohttp_session import get_session
@asyncio.coroutine
def route(request):
session = yield from get_session(request)
if 'uid' in session:
uid = session['uid']
else:
return toolbox.javaify(403,"forbidden")
query_parameters = request.rel_url.query
path = query_parameters["path"] if "path" in query_parameters else ''
if not path:
return toolbox.javaify(400,"miss parameter")
(directory,name) = os.path.split(path)
with (yield from request.app['pool']) as connect:
cursor = yield from connect.cursor()
directory_id = yield from fs.directory_exists(cursor,uid,directory)
if not directory_id:
yield from cursor.close()
connect.close()
return toolbox.javaify(404,"no directory")
file_meta = yield from fs.file_query(cursor,directory_id,[name])
if not file_meta or file_meta[0]['type'] == 'directory':
yield from cursor.close()
connect.close()
return toolbox.javaify(404,"no file")
yield from cursor.execute('''
SELECT name, modify, size, md5 FROM history WHERE id = %s ORDER BY version DESC
''',(file_meta[0]['id']))
out = yield from cursor.fetchall()
yield from cursor.close()
connect.close()
data = []
for line in out:
if line[0] == "":
continue
data.append({
"name": line[0],
"extension": os.path.splitext(line[0])[-1][1:],
"modify": toolbox.time_utc(line[1]),
"size": line[2],
"source": mask.generate(uid,line[3],os.path.splitext(line[0])[-1][1:])
})
return toolbox.javaify(200,"ok",data)
|
986,541 | 650a08368e607d487fabe65690a479b3d0c5bfd4 | locations_dict = {
'PT': [
[[-6.90628, 40.726315], [['1543314339', 'https://live.staticflickr.com/2070/1543314339_2d965ddb0a_s.jpg']]],
[[-8.408253, 40.196675], [['7718394114', 'https://live.staticflickr.com/8284/7718394114_eb94cd238a_s.jpg']]],
[[-8.712349, 39.459728], [['4637039854', 'https://live.staticflickr.com/4028/4637039854_cfde8a6462_s.jpg']]],
[[-7.38008, 38.441978], [['7693643290', 'https://live.staticflickr.com/8028/7693643290_922738c691_s.jpg'], ['1543318893', 'https://live.staticflickr.com/2342/1543318893_e3552440d7_s.jpg']]],
[[-8.512945, 38.37201], [['32784744384', 'https://live.staticflickr.com/2811/32784744384_7a56efdc6c_s.jpg']]],
[[-7.428817, 39.28909], [['33518561171', 'https://live.staticflickr.com/3931/33518561171_b05f0b819e_s.jpg']]],
[[-16.97735, 32.650089], [['3430166156', 'https://live.staticflickr.com/3549/3430166156_8a17eb4a5a_s.jpg']]]
],
'ID': [
[[115.249671, -8.51957], [['31133092402', 'https://live.staticflickr.com/5690/31133092402_2d95b43ebc_s.jpg']]]
],
'IS': [
[[-20.9729, 64.318491], [['6898398863', 'https://live.staticflickr.com/7180/6898398863_c51baa827d_s.jpg']]],
[[-19.02116, 64.963943], [['7678964046', 'https://live.staticflickr.com/8010/7678964046_5275f967f2_s.jpg']]],
[[-20.21759, 64.30599], [['6888268643', 'https://live.staticflickr.com/7200/6888268643_78468a993a_s.jpg']]],
[[-18.987808, 63.415653], [['6888751427', 'https://live.staticflickr.com/7208/6888751427_bf5c824d7a_s.jpg']]]
],
'RO': [
[[24.497237, 47.133597], [['44306995244', 'https://live.staticflickr.com/1976/44306995244_bf49b81c6f_s.jpg']]],
[[25.538234, 47.695009], [['45037883151', 'https://live.staticflickr.com/1945/45037883151_10a3a2c823_s.jpg']]],
[[24.495434, 47.132149], [['43214976520', 'https://live.staticflickr.com/1950/43214976520_e6aae7d182_s.jpg']]],
[[25.590248, 45.656431], [['44318566174', 'https://live.staticflickr.com/1934/44318566174_55215baed5_s.jpg']]],
[[24.98291, 47.536488], [['30135695657', 'https://live.staticflickr.com/1964/30135695657_9d2618314f_s.jpg']]]
],
'AR': [
[[-60.029689, -37.14822], [['9455564322', 'https://live.staticflickr.com/5494/9455564322_48eaeda6ae_s.jpg']]]
],
'CZ': [
[[14.413933, 50.086108], [['3383646950', 'https://live.staticflickr.com/3574/3383646950_a684c9522a_s.jpg']]],
[[14.41595, 50.081351], [['8603205261', 'https://live.staticflickr.com/8540/8603205261_3ac99f8124_s.jpg']]]
],
'BT': [
[[90.725097, 27.581329], [['15243425804', 'https://live.staticflickr.com/7473/15243425804_f1ec6188fd_s.jpg']]],
[[90.455932, 27.532629], [['15706590888', 'https://live.staticflickr.com/7566/15706590888_ef3299f778_s.jpg'], ['15883040845', 'https://live.staticflickr.com/8677/15883040845_31355a21d1_s.jpg'], ['15263439313', 'https://live.staticflickr.com/8618/15263439313_08a46f68b6_s.jpg'], ['15697060299', 'https://live.staticflickr.com/7581/15697060299_e096b59c3b_s.jpg']]],
[[90.076904, 27.532629], [['15881074991', 'https://live.staticflickr.com/8627/15881074991_562557734e_s.jpg'], ['15697185509', 'https://live.staticflickr.com/8561/15697185509_c424aff8f1_s.jpg']]],
[[89.895629, 27.518015], [['15857314746', 'https://live.staticflickr.com/7475/15857314746_5dd23b3d0b_s.jpg'], ['15839853516', 'https://live.staticflickr.com/7520/15839853516_5b53644295_s.jpg']]]
],
'NL': [
[[4.893189, 52.373119], [['3331725776', 'https://live.staticflickr.com/3391/3331725776_d4bfc1cc33_s.jpg']]]
],
'TR': [
[[35.266113, 38.477244], [['16745738743', 'https://live.staticflickr.com/8788/16745738743_f899b27ed9_s.jpg']]]
],
'EE': [
[[24.744987, 59.442086], [['9339116474', 'https://live.staticflickr.com/7307/9339116474_355f7818a5_s.jpg']]]
],
'PL': [
[[19.938361, 50.055458], [['7637424088', 'https://live.staticflickr.com/8160/7637424088_e620b8433c_s.jpg']]],
[[19.937739, 50.055526], [['7630620574', 'https://live.staticflickr.com/8014/7630620574_a97df9c4bd_s.jpg']]],
[[19.93628, 50.055265], [['7630151282', 'https://live.staticflickr.com/7246/7630151282_76de4b3736_s.jpg']]],
[[19.935164, 50.054631], [['7632357784', 'https://live.staticflickr.com/8292/7632357784_c25c49aef9_s.jpg']]]
],
'AT': [
[[16.367568, 48.199506], [['6163847705', 'https://live.staticflickr.com/6171/6163847705_ec6e101ec6_s.jpg']]]
],
'BE': [
[[3.225034, 51.202019], [['5054884097', 'https://live.staticflickr.com/4089/5054884097_e5281f9c86_s.jpg']]],
[[3.223221, 51.200853], [['5075558591', 'https://live.staticflickr.com/4071/5075558591_c60fcbed62_s.jpg']]],
[[3.220667, 51.2115], [['5059647846', 'https://live.staticflickr.com/4083/5059647846_06d61a9f1d_s.jpg']]],
[[3.224015, 51.204893], [['5059696130', 'https://live.staticflickr.com/4150/5059696130_c3631bd31b_s.jpg']]],
[[3.222491, 51.209168], [['5057377701', 'https://live.staticflickr.com/4083/5057377701_e9138f91c6_s.jpg']]],
[[3.225474, 51.204712], [['5058851727', 'https://live.staticflickr.com/4085/5058851727_b528f6c84f_s.jpg']]],
[[3.229186, 51.208872], [['17160634965', 'https://live.staticflickr.com/7689/17160634965_a0be910da1_s.jpg']]],
[[3.226869, 51.207017], [['5059515892', 'https://live.staticflickr.com/4088/5059515892_31f156b318_s.jpg']]],
[[3.223006, 51.206285], [['3224177559', 'https://live.staticflickr.com/3418/3224177559_b236d3776b_s.jpg']]],
[[3.225474, 51.204725], [['5058966741', 'https://live.staticflickr.com/4144/5058966741_b3140ced96_s.jpg']]]
],
'IN': [
[[75.822143, 26.923294], [['8284506169', 'https://live.staticflickr.com/8075/8284506169_f7b144c9ac_s.jpg']]],
[[80.198822, 12.716707], [['11851155045', 'https://live.staticflickr.com/5545/11851155045_035f74659e_s.jpg']]],
[[77.044715, 10.116583], [['11809285475', 'https://live.staticflickr.com/3811/11809285475_9dbb6a6770_s.jpg']]],
[[74.003097, 26.15003], [['8298961679', 'https://live.staticflickr.com/8500/8298961679_a1d8d4e54a_s.jpg'], ['8294938452', 'https://live.staticflickr.com/8351/8294938452_427d6e1dc3_s.jpg'], ['8289404876', 'https://live.staticflickr.com/8482/8289404876_cc103026c5_s.jpg']]],
[[72.584609, 23.019076], [['8288144337', 'https://live.staticflickr.com/8481/8288144337_94ce1ff9c7_s.jpg']]],
[[76.980171, 8.382374], [['11800438973', 'https://live.staticflickr.com/3721/11800438973_1c02c9c901_s.jpg']]],
[[78.036575, 27.180744], [['8285482646', 'https://live.staticflickr.com/8494/8285482646_e3979e62bb_s.jpg']]],
[[77.94754, 27.21441], [['8293971811', 'https://live.staticflickr.com/8363/8293971811_f6974e3c2d_s.jpg']]],
[[78.021383, 27.17937], [['8364541572', 'https://live.staticflickr.com/8326/8364541572_ab206454cc_s.jpg']]],
[[78.021812, 27.179981], [['8357168261', 'https://live.staticflickr.com/8517/8357168261_cebe3e314c_s.jpg']]],
[[75.453887, 11.86468], [['11809179176', 'https://live.staticflickr.com/2808/11809179176_eea1827790_s.jpg']]],
[[72.585468, 23.01955], [['8358399506', 'https://live.staticflickr.com/8194/8358399506_5c81aaec65_s.jpg']]],
[[77.95113, 27.217731], [['8293678617', 'https://live.staticflickr.com/8497/8293678617_c1a65d5e3b_s.jpg']]],
[[79.484367, 10.39361], [['11381161453', 'https://live.staticflickr.com/5515/11381161453_45f58671c5_s.jpg']]],
[[80.23693, 12.996194], [['11383804785', 'https://live.staticflickr.com/2864/11383804785_65e5622f9f_s.jpg']]],
[[79.797561, 11.929329], [['11422656134', 'https://live.staticflickr.com/5545/11422656134_a97d72afa5_s.jpg'], ['11409038206', 'https://live.staticflickr.com/3798/11409038206_7848255f9c_s.jpg'], ['11382031684', 'https://live.staticflickr.com/3721/11382031684_9a93477dd6_s.jpg']]],
[[78.027648, 27.166695], [['8315345631', 'https://live.staticflickr.com/8351/8315345631_a3396b5bbf_s.jpg'], ['8290825913', 'https://live.staticflickr.com/8356/8290825913_71e07e22d1_s.jpg']]],
[[77.994453, 27.183799], [['8300679613', 'https://live.staticflickr.com/8499/8300679613_bf8c50f84f_s.jpg']]],
[[76.258636, 9.953749], [['11875578095', 'https://live.staticflickr.com/2844/11875578095_0d11f27a0e_s.jpg'], ['11802690276', 'https://live.staticflickr.com/5493/11802690276_766b60a763_s.jpg']]],
[[76.068443, 10.586059], [['11381591886', 'https://live.staticflickr.com/7376/11381591886_6d9cd4a33e_s.jpg'], ['11381476725', 'https://live.staticflickr.com/5528/11381476725_c4acd487c7_s.jpg']]],
[[79.824428, 11.927989], [['11383134944', 'https://live.staticflickr.com/7304/11383134944_ae7f2aea45_s.jpg']]],
[[78.034172, 27.182271], [['8310845663', 'https://live.staticflickr.com/8079/8310845663_43de04be16_s.jpg']]],
[[72.588043, 23.017812], [['8287189840', 'https://live.staticflickr.com/8211/8287189840_aca32ff2f6_s.jpg']]],
[[78.029022, 27.166084], [['8285890010', 'https://live.staticflickr.com/8496/8285890010_f2b766f29c_s.jpg']]],
[[77.950658, 27.218532], [['8300801997', 'https://live.staticflickr.com/8492/8300801997_b01a8aebd0_s.jpg']]],
[[76.589469, 27.024629], [['8305441686', 'https://live.staticflickr.com/8353/8305441686_852214fef9_s.jpg']]],
[[72.569869, 23.030199], [['8294662650', 'https://live.staticflickr.com/8076/8294662650_9d41dbb2bf_s.jpg'], ['8288285541', 'https://live.staticflickr.com/8345/8288285541_91330c440d_s.jpg'], ['8285169166', 'https://live.staticflickr.com/8072/8285169166_15780ae926_s.jpg']]],
[[76.242713, 9.943489], [['11383568633', 'https://live.staticflickr.com/7441/11383568633_78707383d2_s.jpg']]],
[[74.012145, 26.14311], [['8291759754', 'https://live.staticflickr.com/8492/8291759754_32e19da2d0_s.jpg']]],
[[73.029876, 26.26843], [['8294996420', 'https://live.staticflickr.com/8221/8294996420_b8c286d922_s.jpg'], ['8293797543', 'https://live.staticflickr.com/8357/8293797543_98bd061572_s.jpg'], ['8294783996', 'https://live.staticflickr.com/8220/8294783996_5f0f3c7dc6_s.jpg'], ['8291709939', 'https://live.staticflickr.com/8081/8291709939_f128672c03_s.jpg']]],
[[73.047323, 26.280871], [['8284673281', 'https://live.staticflickr.com/8339/8284673281_d1b6e578ba_s.jpg']]],
[[72.56607, 23.041193], [['8284703627', 'https://live.staticflickr.com/8350/8284703627_d54dc9fc70_s.jpg']]]
],
'GR': [
[[23.727121, 37.972975], [['2604070348', 'https://live.staticflickr.com/3148/2604070348_b2b4be1d62_s.jpg']]],
[[25.374727, 36.461192], [['5965049820', 'https://live.staticflickr.com/6026/5965049820_ddf0cda2a2_s.jpg']]],
[[23.16163, 39.378108], [['5961370746', 'https://live.staticflickr.com/6006/5961370746_e50c036bc8_s.jpg']]],
[[25.377388, 36.461606], [['5911756168', 'https://live.staticflickr.com/5080/5911756168_93b1b8fb3b_s.jpg']]],
[[25.379319, 36.462037], [['5963865910', 'https://live.staticflickr.com/6142/5963865910_139b3eb5c8_s.jpg']]],
[[23.726649, 37.97303], [['5964557615', 'https://live.staticflickr.com/6002/5964557615_2b52ae06e4_s.jpg']]]
],
'NZ': [
[[170.175476, -43.667871], [['4742397607', 'https://live.staticflickr.com/4114/4742397607_78af9cccf5_s.jpg']]]
],
'FR': [
[[1.609153, 44.936248], [['6071142792', 'https://live.staticflickr.com/6182/6071142792_9fbf2b7cdb_s.jpg']]],
[[1.217079, 44.889809], [['6063109852', 'https://live.staticflickr.com/6080/6063109852_b0c95f5666_s.jpg']]],
[[0.58588, 45.322702], [['6051519570', 'https://live.staticflickr.com/6209/6051519570_579f54ae70_s.jpg']]],
[[0.885772, 46.693018], [['3827888816', 'https://live.staticflickr.com/2586/3827888816_53de65cb81_s.jpg']]],
[[5.493893, 47.091309], [['2831591914', 'https://live.staticflickr.com/2279/2831591914_59a561f587_s.jpg']]],
[[0.374769, 46.650489], [['3827889052', 'https://live.staticflickr.com/2563/3827889052_8f55f86b37_s.jpg']]],
[[0.585365, 45.323306], [['6062044518', 'https://live.staticflickr.com/6061/6062044518_a091b096d4_s.jpg']]],
[[0.233105, 49.420298], [['25351955371', 'https://live.staticflickr.com/1469/25351955371_cd9db999f3_s.jpg']]],
[[1.718189, 46.71067], [['2831591192', 'https://live.staticflickr.com/3127/2831591192_181508838e_s.jpg']]],
[[0.586051, 45.322823], [['6063059350', 'https://live.staticflickr.com/6194/6063059350_f40c6283da_s.jpg']]],
[[1.558869, 44.583198], [['6057059917', 'https://live.staticflickr.com/6090/6057059917_3d6a75404d_s.jpg']]],
[[0.585386, 45.323454], [['50807215016', 'https://live.staticflickr.com/65535/50807215016_05dcc9ca93_s.jpg']]],
[[-149.482727, -17.709444], [['1523573550', 'https://live.staticflickr.com/2075/1523573550_de6817602c_s.jpg']]],
[[5.19783, 43.912788], [['8582268923', 'https://live.staticflickr.com/8519/8582268923_ac8665a751_s.jpg']]],
[[2.341209, 48.856918], [['2830757365', 'https://live.staticflickr.com/3148/2830757365_e67d303e85_s.jpg']]],
[[2.34867, 48.854663], [['4581649451', 'https://live.staticflickr.com/4039/4581649451_cf1674eae8_s.jpg']]],
[[0.585021, 45.323064], [['6056559357', 'https://live.staticflickr.com/6201/6056559357_2f4cf69150_s.jpg']]],
[[1.731789, 44.917289], [['5936497474', 'https://live.staticflickr.com/6002/5936497474_edbb684087_s.jpg'], ['5935116760', 'https://live.staticflickr.com/6124/5935116760_f307dd720b_s.jpg']]],
[[1.142578, 44.249133], [['2831591412', 'https://live.staticflickr.com/3120/2831591412_e404a30b81_s.jpg']]],
[[-149.521179, -17.679353], [['8584133108', 'https://live.staticflickr.com/8237/8584133108_7fd33c2f4a_s.jpg']]],
[[1.236969, 45.908679], [['6056894749', 'https://live.staticflickr.com/6067/6056894749_0b2c43e3cf_s.jpg']]],
[[0.650253, 46.564997], [['20740310306', 'https://live.staticflickr.com/698/20740310306_21b666b8bf_s.jpg'], ['3827090659', 'https://live.staticflickr.com/2675/3827090659_43e6aefb26_s.jpg']]],
[[0.585708, 45.323306], [['6077733980', 'https://live.staticflickr.com/6199/6077733980_0c8138b7be_s.jpg']]],
[[0.23285, 49.419441], [['5916804508', 'https://live.staticflickr.com/6015/5916804508_2cc0108d6c_s.jpg']]],
[[0.539703, 46.819797], [['5953760940', 'https://live.staticflickr.com/6144/5953760940_0188930d52_s.jpg']]],
[[2.399729, 44.59933], [['6015070503', 'https://live.staticflickr.com/6018/6015070503_996bf03099_s.jpg'], ['6012363787', 'https://live.staticflickr.com/6016/6012363787_fa35c239c0_s.jpg']]],
[[1.005509, 44.776309], [['6070737348', 'https://live.staticflickr.com/6197/6070737348_d37c8d2b4a_s.jpg']]],
[[5.200009, 43.91128], [['4596425728', 'https://live.staticflickr.com/4064/4596425728_ba9741fd3b_s.jpg']]],
[[1.382904, 44.7371], [['6056756265', 'https://live.staticflickr.com/6191/6056756265_b73f59bc01_s.jpg']]],
[[0.5855, 45.324279], [['6050794775', 'https://live.staticflickr.com/6084/6050794775_579066c25c_s.jpg']]],
[[2.744189, 43.354301], [['5952322662', 'https://live.staticflickr.com/6016/5952322662_8021962ebb_s.jpg']]],
[[2.40242, 43.269298], [['2830757149', 'https://live.staticflickr.com/3198/2830757149_c710dcf983_s.jpg']]],
[[0.885086, 46.691841], [['20119662524', 'https://live.staticflickr.com/774/20119662524_1fde32c7d8_s.jpg'], ['5041365980', 'https://live.staticflickr.com/4092/5041365980_ccbeb26f6b_s.jpg'], ['3827091151', 'https://live.staticflickr.com/3440/3827091151_3babd50802_s.jpg']]],
[[0.587768, 45.321737], [['6077964918', 'https://live.staticflickr.com/6193/6077964918_b7539d1dd1_s.jpg']]],
[[0.82283, 43.794818], [['6056728360', 'https://live.staticflickr.com/6196/6056728360_08cdec0d51_s.jpg']]]
],
'CN': [
[[109.451293, 24.332081], [['34498931486', 'https://live.staticflickr.com/4171/34498931486_b5b92e0983_s.jpg'], ['34273409782', 'https://live.staticflickr.com/4167/34273409782_216316dd8c_s.jpg'], ['34112601872', 'https://live.staticflickr.com/65535/34112601872_12e7dd74fa_s.jpg']]],
[[112.678527, 23.352342], [['33885994450', 'https://live.staticflickr.com/2880/33885994450_925e2e83fd_s.jpg'], ['33886053330', 'https://live.staticflickr.com/2810/33886053330_bdc904f580_s.jpg'], ['34223557896', 'https://live.staticflickr.com/2855/34223557896_e206e91412_s.jpg'], ['34080872161', 'https://live.staticflickr.com/2864/34080872161_6f176c7da2_s.jpg'], ['34211611965', 'https://live.staticflickr.com/2821/34211611965_a56a8a07d8_s.jpg'], ['34211650505', 'https://live.staticflickr.com/2858/34211650505_b227336bc4_s.jpg'], ['33827549070', 'https://live.staticflickr.com/2860/33827549070_03449544dc_s.jpg']]],
[[107.418823, 24.620053], [['33354716504', 'https://live.staticflickr.com/2818/33354716504_ddac93a3a0_s.jpg']]]
],
'IL': [
[[34.49295, 31.836732], [['32887180531', 'https://live.staticflickr.com/3953/32887180531_f620a8e5bc_s.jpg']]]
],
'HR': [
[[18.107786, 42.640399], [['5964778923', 'https://live.staticflickr.com/6027/5964778923_3a19514285_s.jpg']]],
[[13.629698, 45.082642], [['20637285439', 'https://live.staticflickr.com/706/20637285439_7f65f2b2e6_s.jpg']]]
],
'MG': [
[[47.541618, -18.91931], [['28593736845', 'https://live.staticflickr.com/8389/28593736845_f5b8784bd6_s.jpg']]],
[[45.900878, -19.808054], [['28844065625', 'https://live.staticflickr.com/8811/28844065625_300f46cb6a_s.jpg'], ['28756504611', 'https://live.staticflickr.com/8690/28756504611_3ffd19ddc6_s.jpg']]],
[[44.539604, -20.114293], [['28600827211', 'https://live.staticflickr.com/8207/28600827211_2b23cfb40c_s.jpg'], ['28012678313', 'https://live.staticflickr.com/8535/28012678313_394306896e_s.jpg'], ['28519718822', 'https://live.staticflickr.com/8607/28519718822_dbbc796de2_s.jpg']]],
[[48.957824, -19.059521], [['28599243586', 'https://live.staticflickr.com/8250/28599243586_9b1dfd535e_s.jpg']]],
[[43.59375, -23.049407], [['28582872086', 'https://live.staticflickr.com/8588/28582872086_49b9854e50_s.jpg']]],
[[47.5284, -18.910184], [['28013807453', 'https://live.staticflickr.com/8715/28013807453_41c10a91aa_s.jpg'], ['28590616815', 'https://live.staticflickr.com/8609/28590616815_a27b7efcb8_s.jpg'], ['28501570101', 'https://live.staticflickr.com/8713/28501570101_cd6416e56a_s.jpg'], ['28289313690', 'https://live.staticflickr.com/8388/28289313690_4bb25b736c_s.jpg']]],
[[47.504882, -19.746024], [['28587807036', 'https://live.staticflickr.com/8583/28587807036_367d7538d9_s.jpg']]]
],
'ES': [
[[-3.967094, 36.845147], [['26303799922', 'https://live.staticflickr.com/1617/26303799922_7d6cdbb2b0_s.jpg']]],
[[-3.951473, 36.844598], [['26288293171', 'https://live.staticflickr.com/1566/26288293171_0675e463a5_s.jpg']]],
[[-3.990955, 36.83924], [['1525767845', 'https://live.staticflickr.com/2301/1525767845_d413fa30b2_s.jpg']]],
[[-3.973177, 36.834921], [['26316173996', 'https://live.staticflickr.com/1601/26316173996_bbb7b914f9_s.jpg']]],
[[-5.986862, 37.379433], [['1525768245', 'https://live.staticflickr.com/2210/1525768245_b92264bb43_s.jpg']]],
[[-4.118156, 40.949695], [['5913515054', 'https://live.staticflickr.com/5074/5913515054_0081ea52c6_s.jpg']]],
[[-4.115924, 40.945092], [['1572932316', 'https://live.staticflickr.com/2183/1572932316_58f7ba9cc0_s.jpg']]],
[[-6.00181, 37.387691], [['5931191397', 'https://live.staticflickr.com/6138/5931191397_c55cb4fb7f_s.jpg'], ['1525769245', 'https://live.staticflickr.com/2120/1525769245_1854069c63_s.jpg']]],
[[-5.166279, 36.74179], [['1572043529', 'https://live.staticflickr.com/2394/1572043529_38f493a48a_s.jpg']]],
[[2.170049, 41.385719], [['8030888769', 'https://live.staticflickr.com/8032/8030888769_145520e273_s.jpg']]],
[[-4.420183, 36.721076], [['25730818443', 'https://live.staticflickr.com/1680/25730818443_a74848f6bf_s.jpg']]],
[[-4.11636, 40.948211], [['5913669196', 'https://live.staticflickr.com/5036/5913669196_8c2a82ede9_s.jpg'], ['5912843027', 'https://live.staticflickr.com/5078/5912843027_6e8b441f2e_s.jpg']]],
[[-5.996217, 37.391709], [['1525768055', 'https://live.staticflickr.com/2291/1525768055_174f3cf81f_s.jpg']]],
[[-4.415012, 36.720551], [['26466895515', 'https://live.staticflickr.com/1675/26466895515_5f813413d3_s.jpg']]],
[[-3.974475, 36.838965], [['25739921463', 'https://live.staticflickr.com/1683/25739921463_f06d6ab43f_s.jpg']]]
],
'MM': [
[[94.746093, 21.248422], [['14880741958', 'https://live.staticflickr.com/5596/14880741958_d093265a92_s.jpg'], ['14707921730', 'https://live.staticflickr.com/5593/14707921730_cc6944dfe9_s.jpg'], ['14884922361', 'https://live.staticflickr.com/3870/14884922361_ab14492966_s.jpg'], ['14876944545', 'https://live.staticflickr.com/3835/14876944545_13865788b5_s.jpg']]],
[[97.492675, 23.382598], [['14858948681', 'https://live.staticflickr.com/5581/14858948681_f4945c20df_s.jpg']]],
[[96.092605, 22.032183], [['15067149662', 'https://live.staticflickr.com/3924/15067149662_43d91fb58d_s.jpg']]],
[[95.119628, 21.186972], [['15069671830', 'https://live.staticflickr.com/3847/15069671830_21e10e0591_s.jpg'], ['14675153190', 'https://live.staticflickr.com/3916/14675153190_7663d59e72_s.jpg']]],
[[96.119384, 21.993988], [['14894674743', 'https://live.staticflickr.com/5592/14894674743_7252535a3c_s.jpg']]],
[[94.907283, 21.202337], [['15878084804', 'https://live.staticflickr.com/7447/15878084804_9056c004e0_s.jpg'], ['14702451330', 'https://live.staticflickr.com/3842/14702451330_cd6ec78d7e_s.jpg'], ['14678332249', 'https://live.staticflickr.com/3915/14678332249_a0b3a76bab_s.jpg']]],
[[96.904907, 20.591652], [['14723660730', 'https://live.staticflickr.com/3863/14723660730_512c0038c1_s.jpg'], ['14899992063', 'https://live.staticflickr.com/5575/14899992063_2ba1c3b0fe_s.jpg'], ['14878586292', 'https://live.staticflickr.com/5587/14878586292_56a05c2ea0_s.jpg']]],
[[94.912261, 21.203617], [['14852814036', 'https://live.staticflickr.com/3844/14852814036_53cdfabfb2_s.jpg']]]
],
'NP': [
[[85.319137, 27.698728], [['15260843194', 'https://live.staticflickr.com/7498/15260843194_af5c2f8b0e_s.jpg'], ['15881127451', 'https://live.staticflickr.com/7484/15881127451_f8f87c2f37_s.jpg'], ['15260851204', 'https://live.staticflickr.com/7537/15260851204_f4ac7fde4c_s.jpg'], ['15260856084', 'https://live.staticflickr.com/7553/15260856084_eaea952eda_s.jpg']]]
],
'GB': [
[[-0.851612, 50.828384], [['8561006780', 'https://live.staticflickr.com/8522/8561006780_9e7107d156_s.jpg']]],
[[1.682689, 52.327046], [['5923314685', 'https://live.staticflickr.com/6018/5923314685_2f298e4f56_s.jpg']]],
[[-1.99213, 55.760494], [['8593779350', 'https://live.staticflickr.com/8515/8593779350_22a789455c_s.jpg']]],
[[-1.009798, 51.644974], [['32999094945', 'https://live.staticflickr.com/2069/32999094945_a386c2eccd_s.jpg']]],
[[-1.254158, 51.751835], [['1652030353', 'https://live.staticflickr.com/2356/1652030353_60935cf32c_s.jpg']]],
[[0.594978, 50.857922], [['9731771382', 'https://live.staticflickr.com/7460/9731771382_8c58830bdd_s.jpg']]],
[[0.240797, 52.024191], [['27119221354', 'https://live.staticflickr.com/7301/27119221354_9737b465e8_s.jpg']]],
[[0.916221, 52.059553], [['50144021603', 'https://live.staticflickr.com/65535/50144021603_d9ba559e50_s.jpg'], ['50143862331', 'https://live.staticflickr.com/65535/50143862331_d4786ef4c4_s.jpg']]],
[[-1.263953, 51.751556], [['6556293213', 'https://live.staticflickr.com/7016/6556293213_473662e981_s.jpg']]],
[[-2.830706, 52.430138], [['43465257781', 'https://live.staticflickr.com/924/43465257781_e7f738e5dd_s.jpg']]],
[[0.596694, 50.855809], [['3586246333', 'https://live.staticflickr.com/3408/3586246333_cc69c328bb_s.jpg']]],
[[-2.106113, 53.982692], [['5910369756', 'https://live.staticflickr.com/6004/5910369756_2326857715_s.jpg']]],
[[-2.33541, 52.082222], [['5834104278', 'https://live.staticflickr.com/5032/5834104278_71ae95abd3_s.jpg']]],
[[-1.065673, 51.761502], [['51214701950', 'https://live.staticflickr.com/65535/51214701950_306c4df3f0_s.jpg']]],
[[1.513195, 52.762995], [['5926264924', 'https://live.staticflickr.com/65535/5926264924_afcbea57aa_s.jpg']]],
[[0.181134, 51.338192], [['7183701576', 'https://live.staticflickr.com/8144/7183701576_0777fa0f7d_s.jpg']]],
[[-1.345202, 52.179124], [['51016907295', 'https://live.staticflickr.com/65535/51016907295_f8e2ddaa02_s.jpg']]],
[[-2.770442, 54.283626], [['36052811174', 'https://live.staticflickr.com/4434/36052811174_5f337edae1_s.jpg']]],
[[-1.253954, 51.754439], [['5707780435', 'https://live.staticflickr.com/2453/5707780435_cc211dc5eb_s.jpg'], ['5707701259', 'https://live.staticflickr.com/3564/5707701259_85e33b20f7_s.jpg']]],
[[1.279099, 52.687858], [['8570556981', 'https://live.staticflickr.com/8239/8570556981_4e464097f2_s.jpg']]],
[[-1.255531, 51.752367], [['6556291111', 'https://live.staticflickr.com/7165/6556291111_18145b8469_s.jpg']]],
[[-0.148873, 52.785913], [['4577880400', 'https://live.staticflickr.com/4065/4577880400_d1396e071c_s.jpg']]],
[[0.916543, 52.059367], [['50144382466', 'https://live.staticflickr.com/65535/50144382466_6acbaa9422_s.jpg']]],
[[-0.979049, 51.74802], [['49810818857', 'https://live.staticflickr.com/65535/49810818857_0d30272f7f_s.jpg']]],
[[1.499762, 52.666246], [['4684592439', 'https://live.staticflickr.com/4041/4684592439_e28ebb4f7f_s.jpg']]],
[[0.596694, 50.854942], [['26946420416', 'https://live.staticflickr.com/7265/26946420416_3ccd981490_s.jpg'], ['3586245609', 'https://live.staticflickr.com/3402/3586245609_70c5a27f12_s.jpg']]],
[[-2.323608, 54.521081], [['9621517902', 'https://live.staticflickr.com/7430/9621517902_42d930c9de_s.jpg']]],
[[-1.780128, 51.908696], [['5091142428', 'https://live.staticflickr.com/4089/5091142428_57b729cea3_s.jpg']]],
[[1.304132, 52.931303], [['7157600483', 'https://live.staticflickr.com/7073/7157600483_b75b8332eb_s.jpg']]],
[[-0.572597, 51.234281], [['51174692953', 'https://live.staticflickr.com/65535/51174692953_b1f12ee464_s.jpg'], ['51153180733', 'https://live.staticflickr.com/65535/51153180733_45c4bcb5f7_s.jpg']]],
[[-1.253557, 51.754738], [['5707977457', 'https://live.staticflickr.com/3130/5707977457_9c652be30d_s.jpg']]],
[[-0.3424, 51.751118], [['8091732482', 'https://live.staticflickr.com/8326/8091732482_8d8c6f3e72_s.jpg']]],
[[-2.018909, 53.959115], [['5906917704', 'https://live.staticflickr.com/6058/5906917704_1bcb5eb4cb_s.jpg']]],
[[-1.564429, 50.668121], [['5995052953', 'https://live.staticflickr.com/6018/5995052953_9bdb72e1aa_s.jpg']]],
[[0.241935, 52.025413], [['51139522407', 'https://live.staticflickr.com/65535/51139522407_36070898d1_s.jpg']]],
[[-0.555388, 50.855098], [['29458928431', 'https://live.staticflickr.com/8487/29458928431_24c6b35772_s.jpg']]],
[[-3.939628, 52.970508], [['1517024468', 'https://live.staticflickr.com/2412/1517024468_0654ca2b68_s.jpg']]],
[[0.87566, 52.89756], [['4659579445', 'https://live.staticflickr.com/4063/4659579445_441d7327d0_s.jpg'], ['3347299990', 'https://live.staticflickr.com/3615/3347299990_290c1d6172_s.jpg'], ['3347065574', 'https://live.staticflickr.com/3662/3347065574_d6da7d868e_s.jpg']]],
[[-2.364807, 52.112725], [['5835855476', 'https://live.staticflickr.com/3112/5835855476_f54a6724b9_s.jpg']]],
[[0.50139, 51.389237], [['12309671294', 'https://live.staticflickr.com/7345/12309671294_cc3a803736_s.jpg']]],
[[-4.124679, 51.2114], [['5093865709', 'https://live.staticflickr.com/4089/5093865709_4d5480455e_s.jpg']]],
[[-0.08053, 51.795173], [['33873452610', 'https://live.staticflickr.com/2945/33873452610_c97e2a57a9_s.jpg']]],
[[-2.14508, 54.304906], [['9632242332', 'https://live.staticflickr.com/7433/9632242332_7ce5390a00_s.jpg']]],
[[-1.811542, 52.058253], [['49899876653', 'https://live.staticflickr.com/65535/49899876653_8d005302b6_s.jpg']]],
[[-2.229012, 51.493191], [['50365285263', 'https://live.staticflickr.com/65535/50365285263_ed7d6daf08_s.jpg'], ['50366137987', 'https://live.staticflickr.com/65535/50366137987_3a0e852d8d_s.jpg'], ['50365286823', 'https://live.staticflickr.com/65535/50365286823_21f2b95044_s.jpg']]],
[[-0.112953, 51.896198], [['12570595405', 'https://live.staticflickr.com/2848/12570595405_05f9612505_s.jpg']]],
[[-1.845703, 52.055256], [['49900487366', 'https://live.staticflickr.com/65535/49900487366_9c3c612612_s.jpg']]],
[[-1.165215, 51.613654], [['50939518478', 'https://live.staticflickr.com/65535/50939518478_d63eac1ac2_s.jpg']]],
[[-1.247634, 51.751676], [['2616188515', 'https://live.staticflickr.com/2274/2616188515_214e5b56c8_s.jpg']]],
[[-1.935138, 53.449317], [['6096930022', 'https://live.staticflickr.com/6185/6096930022_30651382a7_s.jpg']]],
[[0.181413, 51.333494], [['7191407934', 'https://live.staticflickr.com/8015/7191407934_99af6b8b44_s.jpg']]],
[[0.394885, 52.751451], [['4570149905', 'https://live.staticflickr.com/3535/4570149905_9ce78f7515_s.jpg']]],
[[-1.03648, 51.485074], [['51227684334', 'https://live.staticflickr.com/65535/51227684334_742956b416_s.jpg']]],
[[-3.937225, 52.960634], [['1517027578', 'https://live.staticflickr.com/2227/1517027578_9d758ffac2_s.jpg']]],
[[-2.154436, 54.046413], [['1508551143', 'https://live.staticflickr.com/65535/1508551143_fd1e88e6eb_s.jpg']]],
[[-0.573284, 51.233453], [['5750615676', 'https://live.staticflickr.com/65535/5750615676_5eff506a11_s.jpg']]],
[[1.445388, 51.358061], [['4695804726', 'https://live.staticflickr.com/4027/4695804726_e26ec19a44_s.jpg'], ['2626164552', 'https://live.staticflickr.com/3129/2626164552_d052e580b8_s.jpg']]],
[[-0.606609, 51.452419], [['51179985362', 'https://live.staticflickr.com/65535/51179985362_332afd6733_s.jpg']]],
[[-0.151598, 51.538184], [['7269510292', 'https://live.staticflickr.com/7224/7269510292_e0529346b9_s.jpg']]],
[[-3.938126, 52.963348], [['27729062119', 'https://live.staticflickr.com/4645/27729062119_279fdf2697_s.jpg'], ['1517025808', 'https://live.staticflickr.com/2050/1517025808_e9f2e62b1c_s.jpg']]],
[[-1.254458, 51.74967], [['1652893868', 'https://live.staticflickr.com/2130/1652893868_a85b370717_s.jpg']]],
[[0.118317, 52.208645], [['8064805476', 'https://live.staticflickr.com/8462/8064805476_680d417ea6_s.jpg']]],
[[0.059094, 51.823771], [['51165209128', 'https://live.staticflickr.com/65535/51165209128_6c85ece6e0_s.jpg']]],
[[1.444702, 51.35506], [['8590301122', 'https://live.staticflickr.com/8090/8590301122_ff9e8666ff_s.jpg']]],
[[-1.228365, 51.751556], [['8335203192', 'https://live.staticflickr.com/8500/8335203192_648326059c_s.jpg']]],
[[-1.249759, 51.751649], [['8094710964', 'https://live.staticflickr.com/8476/8094710964_8f8aa0817b_s.jpg']]],
[[0.874443, 51.971323], [['49875286193', 'https://live.staticflickr.com/65535/49875286193_1044eae9a1_s.jpg']]],
[[-1.806564, 54.284155], [['28654494483', 'https://live.staticflickr.com/8529/28654494483_b6fa791570_s.jpg']]],
[[-0.57234, 51.234353], [['8510034884', 'https://live.staticflickr.com/65535/8510034884_953a39b2c8_s.jpg']]],
[[-0.961689, 51.261345], [['50178001662', 'https://live.staticflickr.com/65535/50178001662_2114a594a2_s.jpg']]],
[[-2.527198, 54.323932], [['14987946771', 'https://live.staticflickr.com/3903/14987946771_7e1a5d6e1f_s.jpg']]],
[[-0.182905, 51.521161], [['5934208330', 'https://live.staticflickr.com/6010/5934208330_462a36eba8_s.jpg']]],
[[0.691065, 52.70332], [['51185299748', 'https://live.staticflickr.com/65535/51185299748_0294b13246_s.jpg']]],
[[0.010557, 51.806067], [['8176767214', 'https://live.staticflickr.com/8481/8176767214_f54d331438_s.jpg']]],
[[-0.338076, 51.50016], [['5863093194', 'https://live.staticflickr.com/3200/5863093194_82d4c8c1f4_s.jpg']]],
[[-1.294841, 51.781727], [['1652023941', 'https://live.staticflickr.com/2213/1652023941_27ef106f94_s.jpg']]],
[[1.096439, 52.904941], [['7342713966', 'https://live.staticflickr.com/7080/7342713966_032a63e98f_s.jpg']]],
[[-1.674569, 53.212219], [['6100054312', 'https://live.staticflickr.com/6192/6100054312_5fcc6f2c52_s.jpg']]],
[[-0.47297, 51.527291], [['50192636471', 'https://live.staticflickr.com/65535/50192636471_da2a5cc197_s.jpg']]],
[[0.875911, 52.894602], [['48052062247', 'https://live.staticflickr.com/65535/48052062247_ff1931c540_s.jpg']]],
[[-1.345374, 52.17936], [['51082637373', 'https://live.staticflickr.com/65535/51082637373_5fc6bc9abf_s.jpg']]],
[[-1.571429, 53.083881], [['6097005328', 'https://live.staticflickr.com/6195/6097005328_134a3d151d_s.jpg']]],
[[-1.816349, 51.749064], [['49917464727', 'https://live.staticflickr.com/65535/49917464727_21aa463b0e_s.jpg']]],
[[-1.763606, 51.901317], [['50009391401', 'https://live.staticflickr.com/65535/50009391401_8360bf8dce_s.jpg']]],
[[-4.51744, 50.334066], [['9921961205', 'https://live.staticflickr.com/7342/9921961205_5343fa2e2f_s.jpg']]],
[[-1.261711, 51.752327], [['14555126644', 'https://live.staticflickr.com/65535/14555126644_6655608fd1_s.jpg']]],
[[-2.016742, 53.963268], [['3329427266', 'https://live.staticflickr.com/3593/3329427266_cd13c9ece0_s.jpg']]],
[[-1.531348, 51.799799], [['50574132441', 'https://live.staticflickr.com/65535/50574132441_4071965ebf_s.jpg']]],
[[1.660189, 52.58715], [['1514285296', 'https://live.staticflickr.com/2308/1514285296_48c8471abd_s.jpg']]],
[[0.075531, 51.857295], [['51165753989', 'https://live.staticflickr.com/65535/51165753989_b6278bb7db_s.jpg']]],
[[-0.753185, 52.26593], [['51329657270', 'https://live.staticflickr.com/65535/51329657270_f1a83a2df3_s.jpg']]],
[[0.77666, 51.971488], [['49875064237', 'https://live.staticflickr.com/65535/49875064237_1db6031cf9_s.jpg']]],
[[1.343958, 52.222252], [['18206645315', 'https://live.staticflickr.com/7732/18206645315_d88d9f28a2_s.jpg']]],
[[-1.254222, 51.753403], [['1652028957', 'https://live.staticflickr.com/2102/1652028957_3333d88579_s.jpg']]],
[[-1.63457, 51.809494], [['50009651757', 'https://live.staticflickr.com/65535/50009651757_c18c662ee2_s.jpg']]],
[[-0.023174, 52.974332], [['5988072711', 'https://live.staticflickr.com/65535/5988072711_b072da24eb_s.jpg']]],
[[-1.26523, 51.753572], [['6559340309', 'https://live.staticflickr.com/7144/6559340309_98fa0b7cd7_s.jpg']]],
[[-1.253793, 51.753642], [['5717026374', 'https://live.staticflickr.com/3528/5717026374_b0ac14a596_s.jpg']]],
[[-0.980755, 51.748917], [['49811681712', 'https://live.staticflickr.com/65535/49811681712_f0a0360f2b_s.jpg']]],
[[0.592639, 50.85627], [['34691375810', 'https://live.staticflickr.com/4269/34691375810_85043cb6d6_s.jpg']]],
[[-1.964524, 51.953268], [['50962619532', 'https://live.staticflickr.com/65535/50962619532_4078e0f918_s.jpg']]],
[[0.593476, 50.856215], [['9611093664', 'https://live.staticflickr.com/5512/9611093664_35a860e913_s.jpg']]],
[[0.393018, 52.755905], [['5915982485', 'https://live.staticflickr.com/6002/5915982485_0f3b51a772_s.jpg']]],
[[-0.268017, 51.886676], [['15626357274', 'https://live.staticflickr.com/7578/15626357274_35bd9d5622_s.jpg'], ['15628174133', 'https://live.staticflickr.com/7569/15628174133_32ec9bb512_s.jpg']]],
[[-1.103096, 51.087539], [['6801441936', 'https://live.staticflickr.com/7193/6801441936_273e387d76_s.jpg'], ['3380599480', 'https://live.staticflickr.com/3443/3380599480_1a3464b457_s.jpg']]],
[[1.614475, 52.578071], [['5780124149', 'https://live.staticflickr.com/2056/5780124149_c0fbb96d81_s.jpg']]],
[[-1.256411, 51.753881], [['6307168579', 'https://live.staticflickr.com/6092/6307168579_f00a6c7831_s.jpg']]],
[[-0.831699, 51.669893], [['13360176785', 'https://live.staticflickr.com/2810/13360176785_3c3656fb7d_s.jpg']]],
[[-1.272718, 51.750347], [['32077146372', 'https://live.staticflickr.com/280/32077146372_e777733e85_s.jpg']]],
[[-2.64467, 51.208751], [['6017079655', 'https://live.staticflickr.com/6136/6017079655_dee1181a9f_s.jpg']]],
[[-0.707416, 51.561312], [['51117403777', 'https://live.staticflickr.com/65535/51117403777_6ff0d7d57a_s.jpg']]],
[[-2.016205, 53.962745], [['1509418542', 'https://live.staticflickr.com/2199/1509418542_0aafb1811f_s.jpg']]],
[[-0.492668, 51.229113], [['1533356001', 'https://live.staticflickr.com/2012/1533356001_28d8d254cb_s.jpg']]],
[[-4.514729, 50.334491], [['9899336654', 'https://live.staticflickr.com/7349/9899336654_d1433e9eaa_s.jpg']]],
[[-0.295257, 51.446384], [['5077807571', 'https://live.staticflickr.com/65535/5077807571_22029652ae_s.jpg']]],
[[-2.55681, 54.336144], [['8044211633', 'https://live.staticflickr.com/8453/8044211633_5d3a18acd5_s.jpg']]],
[[1.090242, 52.906197], [['8580579556', 'https://live.staticflickr.com/8509/8580579556_4b2031e8fd_s.jpg']]],
[[-1.282482, 51.667365], [['8335734356', 'https://live.staticflickr.com/8354/8335734356_124cb97131_s.jpg']]],
[[-2.470893, 52.632802], [['14996729612', 'https://live.staticflickr.com/3844/14996729612_760ed82048_s.jpg']]],
[[1.536712, 52.095538], [['14289880325', 'https://live.staticflickr.com/2930/14289880325_9a4a87f8b8_s.jpg']]],
[[-3.894653, 52.762476], [['8581284722', 'https://live.staticflickr.com/8252/8581284722_ca70093c2d_s.jpg']]],
[[-0.307048, 51.511183], [['33595258158', 'https://live.staticflickr.com/7903/33595258158_287ff8d09f_s.jpg']]],
[[-2.320261, 54.522118], [['36054086254', 'https://live.staticflickr.com/4393/36054086254_b81736f5e2_s.jpg']]],
[[0.581953, 52.076902], [['49955421953', 'https://live.staticflickr.com/65535/49955421953_cd6aeab6b4_s.jpg']]],
[[-1.297159, 51.779046], [['8576362367', 'https://live.staticflickr.com/8093/8576362367_d7b4cc1490_s.jpg']]],
[[-0.273027, 51.448096], [['7198054632', 'https://live.staticflickr.com/7219/7198054632_4b6369c7d2_s.jpg']]],
[[0.238265, 50.734716], [['3248669420', 'https://live.staticflickr.com/3382/3248669420_ab0f8eedfa_s.jpg']]],
[[-1.83669, 51.828961], [['5078353036', 'https://live.staticflickr.com/4016/5078353036_49bcc681c8_s.jpg']]],
[[-2.160755, 51.991299], [['50043694922', 'https://live.staticflickr.com/65535/50043694922_18e8a95f28_s.jpg']]],
[[0.875344, 52.890936], [['7342835978', 'https://live.staticflickr.com/7103/7342835978_42fc810423_s.jpg']]],
[[0.692825, 52.643896], [['8571586844', 'https://live.staticflickr.com/8245/8571586844_358919f2ee_s.jpg']]],
[[1.44659, 52.447117], [['1513432563', 'https://live.staticflickr.com/2371/1513432563_8edc8baa3c_s.jpg']]],
[[-3.82513, 53.279943], [['5839712535', 'https://live.staticflickr.com/3518/5839712535_349c2c5da0_s.jpg']]],
[[-0.230197, 51.488331], [['7961066662', 'https://live.staticflickr.com/8438/7961066662_9b080f010d_s.jpg']]],
[[-0.162563, 52.671333], [['5900333563', 'https://live.staticflickr.com/6029/5900333563_d9f5efe35d_s.jpg']]],
[[-4.034729, 52.719658], [['5958862156', 'https://live.staticflickr.com/6010/5958862156_fb39a60e6b_s.jpg']]],
[[-2.336053, 52.078833], [['3626042875', 'https://live.staticflickr.com/3594/3626042875_513d16a8e1_s.jpg']]],
[[-3.033149, 52.422015], [['51375752857', 'https://live.staticflickr.com/65535/51375752857_27aaa9bb83_s.jpg']]],
[[-0.45237, 51.637408], [['35815028843', 'https://live.staticflickr.com/4361/35815028843_1f8df2aa80_s.jpg']]],
[[-0.156018, 51.763129], [['50683866602', 'https://live.staticflickr.com/65535/50683866602_8d42c07b6a_s.jpg']]],
[[-3.878173, 52.788645], [['8596333804', 'https://live.staticflickr.com/8237/8596333804_f72efb469b_s.jpg']]],
[[1.300399, 52.631651], [['51219892397', 'https://live.staticflickr.com/65535/51219892397_b1580d48e9_s.jpg']]],
[[-3.982715, 52.655977], [['4178465919', 'https://live.staticflickr.com/2589/4178465919_80009c1de2_s.jpg']]],
[[-1.631469, 50.859277], [['6193022957', 'https://live.staticflickr.com/6160/6193022957_6ec1d60912_s.jpg']]],
[[0.650424, 51.539956], [['6053694719', 'https://live.staticflickr.com/6199/6053694719_7715010bf0_s.jpg']]],
[[-2.489089, 54.580543], [['5100587656', 'https://live.staticflickr.com/1092/5100587656_aec8c7f1b8_s.jpg']]],
[[-1.258471, 51.753562], [['6307520634', 'https://live.staticflickr.com/6212/6307520634_4b4e8ceeb0_s.jpg']]],
[[-0.929719, 51.77283], [['8165382079', 'https://live.staticflickr.com/7258/8165382079_cbe277d1a6_s.jpg'], ['8165332849', 'https://live.staticflickr.com/7255/8165332849_52abb16b72_s.jpg']]],
[[-2.311935, 54.528254], [['5906250699', 'https://live.staticflickr.com/5280/5906250699_afaa2bec9f_s.jpg']]],
[[-1.265487, 51.754512], [['1652031943', 'https://live.staticflickr.com/2039/1652031943_49128fb995_s.jpg']]],
[[-1.255059, 50.633416], [['4795971574', 'https://live.staticflickr.com/4120/4795971574_92bb9d7c13_s.jpg']]],
[[1.047821, 52.95598], [['5787654936', 'https://live.staticflickr.com/3368/5787654936_6607a4c442_s.jpg']]],
[[-4.008421, 50.730903], [['4590417276', 'https://live.staticflickr.com/4060/4590417276_c23a1ed7c1_s.jpg']]],
[[0.274647, 51.197012], [['36360421625', 'https://live.staticflickr.com/4371/36360421625_c130c70ae5_s.jpg']]],
[[-0.538362, 53.232319], [['5940518259', 'https://live.staticflickr.com/6021/5940518259_74f8e774df_s.jpg']]],
[[-1.25508, 51.75238], [['5708542970', 'https://live.staticflickr.com/2801/5708542970_db1de66d19_s.jpg']]],
[[0.082579, 51.780105], [['26268542887', 'https://live.staticflickr.com/789/26268542887_a149546900_s.jpg']]],
[[-2.228926, 51.493011], [['50365983626', 'https://live.staticflickr.com/65535/50365983626_2b626e2f2a_s.jpg']]],
[[-2.222886, 52.191092], [['50112147383', 'https://live.staticflickr.com/65535/50112147383_1507666651_s.jpg']]],
[[-2.336182, 52.078793], [['5823398635', 'https://live.staticflickr.com/2328/5823398635_80186fba1a_s.jpg']]],
[[-1.442964, 51.167444], [['50178000427', 'https://live.staticflickr.com/65535/50178000427_3313cb0b1b_s.jpg']]],
[[-0.343623, 51.750905], [['6934783026', 'https://live.staticflickr.com/7213/6934783026_68a9787426_s.jpg']]],
[[-2.15435, 54.055256], [['7859060118', 'https://live.staticflickr.com/8444/7859060118_dc30790677_s.jpg']]],
[[-0.308662, 51.511025], [['50810472203', 'https://live.staticflickr.com/65535/50810472203_71894753b6_s.jpg']]],
[[-1.060931, 54.245763], [['3226876214', 'https://live.staticflickr.com/3420/3226876214_37996c9022_s.jpg']]],
[[-0.009194, 51.8007], [['13226926833', 'https://live.staticflickr.com/3787/13226926833_89ccbf4dd7_s.jpg']]],
[[-0.322465, 51.531493], [['5754502809', 'https://live.staticflickr.com/3140/5754502809_5736204c5e_s.jpg']]],
[[-3.272724, 54.558775], [['5985111819', 'https://live.staticflickr.com/6006/5985111819_81a4c27ac4_s.jpg']]],
[[-1.265959, 51.85881], [['50628835848', 'https://live.staticflickr.com/65535/50628835848_5dbbe87a7f_s.jpg']]],
[[-4.516067, 50.331984], [['5982714986', 'https://live.staticflickr.com/6008/5982714986_2285039897_s.jpg']]],
[[-0.570259, 51.220222], [['51247076984', 'https://live.staticflickr.com/65535/51247076984_a76e2c08f7_s.jpg']]],
[[0.0848, 51.957114], [['51023092878', 'https://live.staticflickr.com/65535/51023092878_8852306a4d_s.jpg']]],
[[-3.934478, 52.961875], [['1516170049', 'https://live.staticflickr.com/2168/1516170049_604c2f3a55_s.jpg']]],
[[-1.257033, 51.746548], [['1652896176', 'https://live.staticflickr.com/2186/1652896176_e28436003d_s.jpg']]],
[[-0.533039, 51.673583], [['50123019236', 'https://live.staticflickr.com/65535/50123019236_1eff59b270_s.jpg']]],
[[-2.727012, 54.652583], [['5913567110', 'https://live.staticflickr.com/6022/5913567110_1e48f07757_s.jpg']]],
[[-0.518245, 51.236556], [['1534220020', 'https://live.staticflickr.com/2285/1534220020_501a585426_s.jpg']]],
[[-0.147714, 52.785485], [['4570149493', 'https://live.staticflickr.com/3475/4570149493_ef8c03ef45_s.jpg']]],
[[1.444959, 51.358972], [['5992919327', 'https://live.staticflickr.com/6142/5992919327_869595ec5a_s.jpg']]],
[[-2.699117, 51.144301], [['2830757903', 'https://live.staticflickr.com/3184/2830757903_8ecd3cbdc2_s.jpg']]],
[[-2.337813, 52.078292], [['5462656469', 'https://live.staticflickr.com/5015/5462656469_905d29b7ac_s.jpg']]],
[[-0.813069, 51.815231], [['7760962476', 'https://live.staticflickr.com/8304/7760962476_eb60f89699_s.jpg']]],
[[-5.321502, 55.699646], [['4591881989', 'https://live.staticflickr.com/65535/4591881989_63b1e0699e_s.jpg']]],
[[0.145354, 50.760486], [['26461211306', 'https://live.staticflickr.com/1650/26461211306_27364ec7e8_s.jpg']]],
[[0.132737, 51.947513], [['51025352307', 'https://live.staticflickr.com/65535/51025352307_69106c23dd_s.jpg']]],
[[-1.265037, 51.761824], [['5708333512', 'https://live.staticflickr.com/3576/5708333512_5011fff621_s.jpg']]],
[[-4.277114, 53.141931], [['5916889252', 'https://live.staticflickr.com/6004/5916889252_7314dd2cae_s.jpg']]],
[[-0.538823, 53.234406], [['5938599960', 'https://live.staticflickr.com/6016/5938599960_fb85c2b68d_s.jpg']]],
[[0.146985, 50.757757], [['14728683283', 'https://live.staticflickr.com/2934/14728683283_552f488e54_s.jpg'], ['14674877541', 'https://live.staticflickr.com/3891/14674877541_c7cfbb4538_s.jpg']]],
[[-1.572418, 53.081961], [['6097328574', 'https://live.staticflickr.com/6090/6097328574_981b9a1320_s.jpg']]],
[[-0.668996, 51.681878], [['51349691982', 'https://live.staticflickr.com/65535/51349691982_e37559db5c_s.jpg']]],
[[-0.600814, 51.409244], [['34387050481', 'https://live.staticflickr.com/4169/34387050481_78d5aed831_s.jpg']]],
[[-2.136497, 54.008273], [['8638906165', 'https://live.staticflickr.com/8256/8638906165_1733011711_s.jpg']]],
[[-1.279606, 51.762474], [['8149009779', 'https://live.staticflickr.com/8469/8149009779_e19f7f7cb4_s.jpg']]],
[[-1.558599, 50.675847], [['5995224471', 'https://live.staticflickr.com/6143/5995224471_299f9c2b1f_s.jpg']]],
[[1.081134, 51.27844], [['19761471192', 'https://live.staticflickr.com/489/19761471192_baa7cdb041_s.jpg']]],
[[0.901908, 52.851821], [['4627366637', 'https://live.staticflickr.com/4062/4627366637_1a760442ba_s.jpg']]],
[[-1.299819, 51.720222], [['6710885823', 'https://live.staticflickr.com/7028/6710885823_003780e7dd_s.jpg']]],
[[-1.442878, 51.167525], [['50185722292', 'https://live.staticflickr.com/65535/50185722292_d4a468d26e_s.jpg']]],
[[-1.584177, 52.279832], [['36826595460', 'https://live.staticflickr.com/4423/36826595460_0861541fc1_s.jpg']]],
[[-3.939113, 52.963606], [['8114071640', 'https://live.staticflickr.com/8189/8114071640_6a95132e00_s.jpg']]],
[[-2.418751, 52.532148], [['9662887367', 'https://live.staticflickr.com/2833/9662887367_728cd9c553_s.jpg']]],
[[-4.018936, 52.732133], [['50276981563', 'https://live.staticflickr.com/65535/50276981563_23af658c22_s.jpg'], ['5960587570', 'https://live.staticflickr.com/6130/5960587570_3dc15e7e7f_s.jpg'], ['1517284737', 'https://live.staticflickr.com/65535/1517284737_43d34c7a9b_s.jpg']]],
[[1.444551, 51.359146], [['4695169797', 'https://live.staticflickr.com/4021/4695169797_b2763210c2_s.jpg']]],
[[1.300549, 52.932499], [['7157549403', 'https://live.staticflickr.com/7232/7157549403_241cc81a06_s.jpg']]],
[[0.13911, 51.965017], [['51023129838', 'https://live.staticflickr.com/65535/51023129838_24d737421d_s.jpg']]],
[[-1.266517, 51.755515], [['1652028339', 'https://live.staticflickr.com/2418/1652028339_fb68688ee7_s.jpg']]],
[[-1.32677, 52.2085], [['31061102290', 'https://live.staticflickr.com/5551/31061102290_ece55e17d0_s.jpg']]],
[[0.592671, 50.856337], [['34335293393', 'https://live.staticflickr.com/4287/34335293393_c22598b331_s.jpg']]],
[[0.176467, 50.755463], [['9702901192', 'https://live.staticflickr.com/3743/9702901192_c6d20e71ee_s.jpg']]],
[[0.597381, 50.855809], [['3598446357', 'https://live.staticflickr.com/3388/3598446357_ef8d9a2eef_s.jpg']]],
[[-0.396194, 54.289078], [['2890313277', 'https://live.staticflickr.com/3153/2890313277_0963854ab9_s.jpg']]],
[[-4.698715, 51.674684], [['3331725796', 'https://live.staticflickr.com/3555/3331725796_f728550d36_s.jpg'], ['3331725792', 'https://live.staticflickr.com/3663/3331725792_643a569bbb_s.jpg']]],
[[-0.572576, 51.234213], [['51078281877', 'https://live.staticflickr.com/65535/51078281877_5e6554451f_s.jpg']]],
[[0.406494, 51.092418], [['26923077401', 'https://live.staticflickr.com/7278/26923077401_9417bde209_s.jpg'], ['26381724713', 'https://live.staticflickr.com/7192/26381724713_b7aba6757e_s.jpg']]],
[[-5.517196, 57.2783], [['3226876172', 'https://live.staticflickr.com/3517/3226876172_7e754a0e92_s.jpg']]],
[[-0.98363, 51.750212], [['49810518861', 'https://live.staticflickr.com/65535/49810518861_9924a6d00b_s.jpg']]],
[[-0.34049, 51.751251], [['10008285044', 'https://live.staticflickr.com/7342/10008285044_4c8ef3a651_s.jpg'], ['3331725786', 'https://live.staticflickr.com/3620/3331725786_efa8e8a063_s.jpg']]],
[[-0.129175, 51.504094], [['11889149245', 'https://live.staticflickr.com/2843/11889149245_f3da2ab48d_s.jpg']]],
[[-1.818237, 55.681842], [['5984830167', 'https://live.staticflickr.com/6143/5984830167_f27e3c891b_s.jpg']]],
[[0.069115, 51.845707], [['21585264371', 'https://live.staticflickr.com/5752/21585264371_def7306bbc_s.jpg']]],
[[-2.11667, 54.070998], [['1509415886', 'https://live.staticflickr.com/2120/1509415886_8f93f05d10_s.jpg']]],
[[-0.148315, 52.787645], [['4570785236', 'https://live.staticflickr.com/3469/4570785236_fcb6711064_s.jpg']]],
[[-2.008116, 53.553559], [['45529375972', 'https://live.staticflickr.com/1934/45529375972_2d9ffb17de_s.jpg']]],
[[0.590772, 50.857055], [['9615222718', 'https://live.staticflickr.com/5550/9615222718_9422757867_s.jpg']]],
[[-2.056953, 50.637026], [['4724255314', 'https://live.staticflickr.com/1262/4724255314_1a1c74af6f_s.jpg']]],
[[-1.270508, 51.757773], [['1652022059', 'https://live.staticflickr.com/65535/1652022059_7c8c19bcc3_s.jpg']]],
[[1.323208, 51.128565], [['44703003621', 'https://live.staticflickr.com/1875/44703003621_28002d0fd1_s.jpg']]],
[[0.153379, 50.775387], [['1533354513', 'https://live.staticflickr.com/2051/1533354513_4a3bbde73d_s.jpg']]],
[[-0.800628, 51.668083], [['16796176451', 'https://live.staticflickr.com/8616/16796176451_558e7d4a5e_s.jpg']]],
[[-0.850859, 50.829868], [['5919628827', 'https://live.staticflickr.com/6010/5919628827_d093e1f858_s.jpg']]],
[[-1.246304, 51.751284], [['2604037528', 'https://live.staticflickr.com/3101/2604037528_e9a81487f9_s.jpg']]],
[[1.050224, 52.955877], [['5780670576', 'https://live.staticflickr.com/65535/5780670576_66dd31ec81_s.jpg']]],
[[-0.49241, 51.682755], [['50740720838', 'https://live.staticflickr.com/65535/50740720838_2332a31890_s.jpg']]],
[[-2.272624, 54.102363], [['28776599914', 'https://live.staticflickr.com/8104/28776599914_1eff28b4f6_s.jpg']]],
[[-1.264489, 51.749747], [['50762833082', 'https://live.staticflickr.com/65535/50762833082_5d57234fca_s.jpg']]],
[[-2.195849, 54.303685], [['1508560169', 'https://live.staticflickr.com/2213/1508560169_b42f448c99_s.jpg']]],
[[-2.140445, 54.018057], [['1508563727', 'https://live.staticflickr.com/2160/1508563727_5458c3d02c_s.jpg']]],
[[-4.51538, 50.336257], [['9901222626', 'https://live.staticflickr.com/7382/9901222626_b6147d90cc_s.jpg']]],
[[-0.983394, 51.749926], [['49810819222', 'https://live.staticflickr.com/65535/49810819222_95ebc21dea_s.jpg']]],
[[-0.598583, 51.429397], [['7227949562', 'https://live.staticflickr.com/8013/7227949562_c4e9a30b49_s.jpg']]],
[[-1.91574, 54.007768], [['1509408142', 'https://live.staticflickr.com/2038/1509408142_d8d922e388_s.jpg']]],
[[-1.160516, 51.643951], [['49849869212', 'https://live.staticflickr.com/65535/49849869212_0ab37f85fe_s.jpg']]],
[[-4.518041, 50.331217], [['9904803113', 'https://live.staticflickr.com/2857/9904803113_39a0d6f66e_s.jpg']]],
[[-0.8008, 51.644794], [['3629968424', 'https://live.staticflickr.com/3408/3629968424_0cfb264ff0_s.jpg']]],
[[-0.605192, 51.483333], [['8036990202', 'https://live.staticflickr.com/8037/8036990202_07b41952e7_s.jpg']]],
[[-0.478913, 51.489032], [['29588287873', 'https://live.staticflickr.com/8128/29588287873_ee7dda7a56_s.jpg']]],
[[0.733165, 50.950316], [['27079760986', 'https://live.staticflickr.com/7627/27079760986_a077ffd1b3_s.jpg'], ['26490369753', 'https://live.staticflickr.com/7278/26490369753_8bfa90135d_s.jpg'], ['4771713397', 'https://live.staticflickr.com/4099/4771713397_c1852736ba_s.jpg']]],
[[0.437511, 51.948679], [['51126343611', 'https://live.staticflickr.com/65535/51126343611_844647ce00_s.jpg']]],
[[-4.83334, 50.593562], [['15215842391', 'https://live.staticflickr.com/3912/15215842391_684d57faa6_s.jpg']]],
[[-1.267268, 51.747037], [['46423386731', 'https://live.staticflickr.com/4888/46423386731_b056c47f2e_s.jpg']]],
[[-1.08342, 53.95333], [['5927076024', 'https://live.staticflickr.com/6131/5927076024_ba64aa49a8_s.jpg']]],
[[0.272297, 51.196655], [['35963646520', 'https://live.staticflickr.com/4440/35963646520_670d5618bb_s.jpg']]],
[[0.235776, 50.735987], [['51320303988', 'https://live.staticflickr.com/65535/51320303988_43df1f333c_s.jpg']]],
[[-2.143707, 54.514704], [['37163257411', 'https://live.staticflickr.com/4338/37163257411_bbb3b2c2c5_s.jpg']]],
[[-2.124599, 53.26151], [['10733164236', 'https://live.staticflickr.com/2855/10733164236_aea0d1bd86_s.jpg']]],
[[-1.571388, 53.083095], [['6096838579', 'https://live.staticflickr.com/6069/6096838579_4915a602be_s.jpg']]],
[[-2.194862, 51.785279], [['50044624983', 'https://live.staticflickr.com/65535/50044624983_b4782e03b1_s.jpg']]],
[[-2.039852, 54.104401], [['1509420988', 'https://live.staticflickr.com/2161/1509420988_75b6128ba8_s.jpg']]],
[[-0.738294, 52.224505], [['51328734656', 'https://live.staticflickr.com/65535/51328734656_fb4d507329_s.jpg']]],
[[-0.573799, 51.234044], [['7980505439', 'https://live.staticflickr.com/8442/7980505439_e3a453ac7e_s.jpg']]],
[[-1.256411, 51.753642], [['6307117799', 'https://live.staticflickr.com/6094/6307117799_41524d6141_s.jpg']]],
[[0.250625, 50.734282], [['9694001939', 'https://live.staticflickr.com/7433/9694001939_97f64597bb_s.jpg']]],
[[0.601372, 51.992565], [['51143059400', 'https://live.staticflickr.com/65535/51143059400_3223218c50_s.jpg']]],
[[-0.287897, 51.486588], [['50874700253', 'https://live.staticflickr.com/65535/50874700253_9ef647a4d0_s.jpg']]],
[[1.047413, 52.946447], [['51221388183', 'https://live.staticflickr.com/65535/51221388183_71087f5b00_s.jpg']]],
[[-0.573306, 51.233446], [['5658799607', 'https://live.staticflickr.com/5070/5658799607_2cc9ee8567_s.jpg']]],
[[-0.476982, 51.367073], [['51121294478', 'https://live.staticflickr.com/65535/51121294478_5a8c903a61_s.jpg']]],
[[-4.512634, 50.336695], [['9903931615', 'https://live.staticflickr.com/3707/9903931615_010b0ae520_s.jpg']]],
[[-2.155809, 54.071728], [['1508568171', 'https://live.staticflickr.com/2369/1508568171_b685875fa2_s.jpg']]],
[[-0.542149, 50.880786], [['51245393047', 'https://live.staticflickr.com/65535/51245393047_7345c706a3_s.jpg']]],
[[-0.507345, 51.676137], [['50780008062', 'https://live.staticflickr.com/65535/50780008062_cb96f814a4_s.jpg']]],
[[-2.278976, 54.07339], [['6175942095', 'https://live.staticflickr.com/6160/6175942095_19ef9c5fee_s.jpg']]],
[[-1.514772, 51.416663], [['30169057428', 'https://live.staticflickr.com/1836/30169057428_5b4d66b59a_s.jpg']]],
[[-1.263127, 51.752189], [['50733402028', 'https://live.staticflickr.com/65535/50733402028_a7a81dea53_s.jpg']]],
[[-1.275701, 51.758942], [['4727779253', 'https://live.staticflickr.com/1386/4727779253_42fa6303f6_s.jpg']]],
[[-2.955601, 54.432536], [['6182317027', 'https://live.staticflickr.com/6158/6182317027_4351ffd987_s.jpg']]],
[[-1.539931, 51.798366], [['50573514436', 'https://live.staticflickr.com/65535/50573514436_5d655608e3_s.jpg']]],
[[0.5033, 51.388608], [['12277197396', 'https://live.staticflickr.com/3671/12277197396_fb93434437_s.jpg']]],
[[-0.148615, 52.785829], [['4570149671', 'https://live.staticflickr.com/3469/4570149671_9057e73dce_s.jpg']]],
[[1.301107, 52.932661], [['7342900296', 'https://live.staticflickr.com/7085/7342900296_05cc56b8e0_s.jpg']]],
[[-1.256582, 51.75402], [['6314135915', 'https://live.staticflickr.com/6108/6314135915_7b31ac8fa1_s.jpg']]],
[[-1.184409, 54.18851], [['3226876330', 'https://live.staticflickr.com/3407/3226876330_cb2e90e390_s.jpg']]],
[[-1.067476, 53.784008], [['5101468047', 'https://live.staticflickr.com/4110/5101468047_49eff2dda6_s.jpg']]],
[[-0.383749, 51.760163], [['6938855942', 'https://live.staticflickr.com/5275/6938855942_f8a14ffa71_s.jpg']]],
[[0.169258, 50.751879], [['6012276271', 'https://live.staticflickr.com/6021/6012276271_72b348e52e_s.jpg']]],
[[-1.311621, 52.20192], [['51082370878', 'https://live.staticflickr.com/65535/51082370878_a366406c71_s.jpg']]],
[[-1.164915, 51.643632], [['51239825468', 'https://live.staticflickr.com/65535/51239825468_181d030027_s.jpg']]],
[[0.138745, 51.964479], [['51025372432', 'https://live.staticflickr.com/65535/51025372432_645399e752_s.jpg']]],
[[-0.814661, 51.816905], [['7768770392', 'https://live.staticflickr.com/8439/7768770392_820c7555eb_s.jpg']]],
[[0.594205, 50.855701], [['7876325116', 'https://live.staticflickr.com/8283/7876325116_bdd123aa2b_s.jpg']]],
[[0.198054, 50.761789], [['9764168172', 'https://live.staticflickr.com/7295/9764168172_c639f4564c_s.jpg']]],
[[-1.76367, 51.901608], [['50008879518', 'https://live.staticflickr.com/65535/50008879518_bda125d601_s.jpg']]],
[[-3.03317, 52.42191], [['51400588963', 'https://live.staticflickr.com/65535/51400588963_504998619d_s.jpg']]],
[[0.821743, 51.967707], [['49868853582', 'https://live.staticflickr.com/65535/49868853582_384310f2c8_s.jpg']]],
[[-1.255102, 51.750347], [['1652893134', 'https://live.staticflickr.com/2389/1652893134_e0da53af87_s.jpg']]],
[[0.012069, 51.689485], [['13334060515', 'https://live.staticflickr.com/3740/13334060515_a2e60b173b_s.jpg']]],
[[-1.27083, 51.762372], [['4685226074', 'https://live.staticflickr.com/65535/4685226074_6c6f0319a7_s.jpg']]],
[[-0.081067, 51.946639], [['16568906408', 'https://live.staticflickr.com/7646/16568906408_5f260f3da2_s.jpg']]],
[[-0.067205, 51.951935], [['16744618421', 'https://live.staticflickr.com/7636/16744618421_1fa1c531f3_s.jpg']]],
[[-3.126082, 52.073663], [['16166760944', 'https://live.staticflickr.com/8676/16166760944_027ebf7d7d_s.jpg']]],
[[-1.253793, 51.752699], [['1652029567', 'https://live.staticflickr.com/2014/1652029567_3359721625_s.jpg']]],
[[-3.037891, 54.433148], [['5878025319', 'https://live.staticflickr.com/6053/5878025319_7ce9e105e8_s.jpg']]],
[[-2.484884, 52.627293], [['7853615596', 'https://live.staticflickr.com/8292/7853615596_d65048607b_s.jpg']]],
[[-1.259822, 51.75764], [['31671010341', 'https://live.staticflickr.com/510/31671010341_ae56a2c70f_s.jpg']]],
[[-2.057361, 50.636397], [['14217537720', 'https://live.staticflickr.com/3858/14217537720_b7aa57c16c_s.jpg'], ['14421621273', 'https://live.staticflickr.com/3908/14421621273_72790f2341_s.jpg']]],
[[-0.308717, 51.510941], [['48583701131', 'https://live.staticflickr.com/65535/48583701131_09de7d956b_s.jpg']]],
[[-0.492721, 51.683818], [['16417745379', 'https://live.staticflickr.com/8673/16417745379_8de3d38669_s.jpg']]],
[[-0.306951, 51.458038], [['26353907878', 'https://live.staticflickr.com/4713/26353907878_f7f0bedf67_s.jpg']]],
[[-2.337341, 52.115149], [['5839354952', 'https://live.staticflickr.com/3085/5839354952_0506c4dba9_s.jpg']]],
[[-1.264007, 51.751729], [['5708131730', 'https://live.staticflickr.com/65535/5708131730_195cf5de3d_s.jpg']]],
[[-0.572597, 51.234294], [['50687569413', 'https://live.staticflickr.com/65535/50687569413_45b82915e9_s.jpg']]],
[[-1.253921, 51.754074], [['5735125158', 'https://live.staticflickr.com/2487/5735125158_5f830c3b7e_s.jpg']]],
[[1.301686, 52.631768], [['51222331176', 'https://live.staticflickr.com/65535/51222331176_4b311d0c40_s.jpg']]],
[[-2.516169, 50.946761], [['5870549683', 'https://live.staticflickr.com/5078/5870549683_2371dc05b3_s.jpg']]],
[[-0.915234, 52.142517], [['49808504671', 'https://live.staticflickr.com/65535/49808504671_06337f8554_s.jpg']]],
[[1.413679, 52.78207], [['4660305054', 'https://live.staticflickr.com/4022/4660305054_7b3fa299b7_s.jpg']]],
[[-1.76126, 51.90142], [['5988860420', 'https://live.staticflickr.com/6137/5988860420_c083ff3280_s.jpg'], ['1651247717', 'https://live.staticflickr.com/2142/1651247717_905fefcc9c_s.jpg']]]
],
'CH': [
[[6.148996, 46.201395], [['5574683043', 'https://live.staticflickr.com/5059/5574683043_3f53e32bea_s.jpg']]],
[[8.545067, 47.369815], [['7774209438', 'https://live.staticflickr.com/7266/7774209438_783af4621f_s.jpg']]],
[[8.545475, 47.370934], [['7774427078', 'https://live.staticflickr.com/8427/7774427078_b63695672d_s.jpg']]]
],
'SI': [
[[14.086532, 46.358775], [['2604037490', 'https://live.staticflickr.com/3191/2604037490_9a428f46cc_s.jpg']]],
[[15.22808, 45.927871], [['23612437149', 'https://live.staticflickr.com/5709/23612437149_30d37341f8_s.jpg'], ['5860328074', 'https://live.staticflickr.com/5311/5860328074_8aae257594_s.jpg']]],
[[14.089965, 46.360671], [['6157085630', 'https://live.staticflickr.com/6063/6157085630_bbc7704fb1_s.jpg'], ['2603208001', 'https://live.staticflickr.com/3285/2603208001_4131398c1b_s.jpg']]]
],
'IT': [
[[12.337646, 45.43243], [['5632650654', 'https://live.staticflickr.com/5028/5632650654_a92e2f7c07_s.jpg']]],
[[10.503079, 43.840996], [['8679148536', 'https://live.staticflickr.com/8403/8679148536_6d2b833a48_s.jpg']]],
[[11.035144, 43.465192], [['4609707967', 'https://live.staticflickr.com/65535/4609707967_f94ed82b08_s.jpg']]],
[[10.504796, 43.839402], [['8679537274', 'https://live.staticflickr.com/8391/8679537274_14c3d61de5_s.jpg']]],
[[10.546489, 43.995811], [['5951612577', 'https://live.staticflickr.com/6134/5951612577_6f0a3cb759_s.jpg']]],
[[12.334889, 45.433872], [['2610890025', 'https://live.staticflickr.com/3249/2610890025_6c58b34070_s.jpg']]],
[[10.501213, 43.842513], [['8679305168', 'https://live.staticflickr.com/8117/8679305168_c14e842ab9_s.jpg']]],
[[10.960235, 43.609233], [['4610849387', 'https://live.staticflickr.com/1262/4610849387_8f93781a7c_s.jpg']]],
[[12.329106, 45.431813], [['5622942204', 'https://live.staticflickr.com/5030/5622942204_f5be09ef4a_s.jpg']]],
[[12.336101, 45.432069], [['1535164760', 'https://live.staticflickr.com/2236/1535164760_69458ca115_s.jpg']]],
[[11.041946, 43.468369], [['4611458758', 'https://live.staticflickr.com/4055/4611458758_a4ffc554d0_s.jpg']]],
[[12.344405, 45.433989], [['2604037252', 'https://live.staticflickr.com/3265/2604037252_3a4e7a2814_s.jpg']]],
[[10.502307, 43.843596], [['8678365807', 'https://live.staticflickr.com/8379/8678365807_5a07aa7c03_s.jpg']]],
[[12.337388, 45.43237], [['5622355487', 'https://live.staticflickr.com/5302/5622355487_5303caae38_s.jpg']]],
[[14.613929, 40.651149], [['4521330321', 'https://live.staticflickr.com/2722/4521330321_5ea12857d4_s.jpg']]],
[[11.021003, 43.404174], [['4612393610', 'https://live.staticflickr.com/4031/4612393610_58ed122636_s.jpg']]],
[[16.86985, 41.128633], [['5964610581', 'https://live.staticflickr.com/6135/5964610581_dbc3a07dc1_s.jpg']]],
[[17.23537, 40.785659], [['4671329632', 'https://live.staticflickr.com/4034/4671329632_4d9a062cec_s.jpg'], ['4523739675', 'https://live.staticflickr.com/2755/4523739675_7f5cafc82e_s.jpg']]],
[[12.333526, 45.441555], [['8752444285', 'https://live.staticflickr.com/2869/8752444285_7195f3dd3a_s.jpg']]],
[[12.495759, 41.90311], [['8580325737', 'https://live.staticflickr.com/8511/8580325737_e22fbbe4bc_s.jpg']]],
[[12.323055, 45.440862], [['5629513022', 'https://live.staticflickr.com/5301/5629513022_b77f27b36c_s.jpg']]],
[[12.333451, 45.433138], [['6170180201', 'https://live.staticflickr.com/6153/6170180201_dbb5e560a1_s.jpg']]],
[[8.502484, 40.296482], [['3242291946', 'https://live.staticflickr.com/3418/3242291946_b0f2cbd88a_s.jpg']]],
[[17.325439, 40.746216], [['4525616856', 'https://live.staticflickr.com/4020/4525616856_9508f18285_s.jpg']]],
[[12.322797, 45.441028], [['5628866191', 'https://live.staticflickr.com/5145/5628866191_beebe5f1ab_s.jpg']]],
[[12.339019, 45.434343], [['5625815342', 'https://live.staticflickr.com/5068/5625815342_17842578d8_s.jpg']]],
[[12.335715, 45.434026], [['5622442117', 'https://live.staticflickr.com/5061/5622442117_d6a424ce09_s.jpg']]],
[[11.04034, 43.467029], [['2891149900', 'https://live.staticflickr.com/3050/2891149900_897a0df305_s.jpg']]]
],
'US': [
[[-73.981246, 40.768094], [['5926952921', 'https://live.staticflickr.com/6005/5926952921_cccd285f69_s.jpg']]],
[[-112.877826, 35.32787], [['22657338364', 'https://live.staticflickr.com/5668/22657338364_29ab4f042d_s.jpg']]],
[[-113.041076, 37.306829], [['23323716671', 'https://live.staticflickr.com/624/23323716671_d193ebb17c_s.jpg'], ['23346034465', 'https://live.staticflickr.com/619/23346034465_0312786e92_s.jpg'], ['23013331380', 'https://live.staticflickr.com/5836/23013331380_df742a4058_s.jpg'], ['22652728893', 'https://live.staticflickr.com/635/22652728893_ba30b449aa_s.jpg']]]
],
'VN': [
[[107.082538, 20.950859], [['22189356644', 'https://live.staticflickr.com/730/22189356644_d9c9551564_s.jpg'], ['20469705801', 'https://live.staticflickr.com/337/20469705801_50e324a46a_s.jpg'], ['20208911359', 'https://live.staticflickr.com/379/20208911359_3104e58de3_s.jpg'], ['20190417369', 'https://live.staticflickr.com/379/20190417369_a4b303595a_s.jpg']]],
[[106.412887, 10.229788], [['20667419032', 'https://live.staticflickr.com/619/20667419032_53aa303458_s.jpg'], ['20187371480', 'https://live.staticflickr.com/269/20187371480_9009000707_s.jpg']]],
[[107.087688, 20.939797], [['20354232886', 'https://live.staticflickr.com/468/20354232886_593a1a0263_s.jpg']]]
],
'CR': [
[[-84.816703, 10.3], [['5940832209', 'https://live.staticflickr.com/6135/5940832209_82b5865ba1_s.jpg']]],
[[-84.858398, 10.526294], [['5940924085', 'https://live.staticflickr.com/6124/5940924085_429070a5d2_s.jpg']]]
],
'MY': [
[[115.433349, 4.319023], [['7430617910', 'https://live.staticflickr.com/8021/7430617910_98b473c244_s.jpg']]],
[[109.665527, 2.067727], [['7430779268', 'https://live.staticflickr.com/8003/7430779268_6acb8766e6_s.jpg']]],
[[115.3125, 4.083452], [['7430815724', 'https://live.staticflickr.com/7122/7430815724_f60e4423e5_s.jpg']]],
[[116.087036, 5.993752], [['24817697345', 'https://live.staticflickr.com/1450/24817697345_3a999675e8_s.jpg'], ['7439836192', 'https://live.staticflickr.com/8027/7439836192_1d37a0b266_s.jpg']]],
[[115.664062, 4.45595], [['7430894464', 'https://live.staticflickr.com/7140/7430894464_dac846d941_s.jpg']]]
],
'MA': [
[[-4.978265, 34.061284], [['50409037956', 'https://live.staticflickr.com/65535/50409037956_cdca3ebda6_s.jpg'], ['27845215698', 'https://live.staticflickr.com/965/27845215698_0764b02665_s.jpg']]],
[[-4.975776, 34.066539], [['40814745385', 'https://live.staticflickr.com/829/40814745385_7ed4286d22_s.jpg']]],
[[-5.261163, 35.169644], [['27845442298', 'https://live.staticflickr.com/963/27845442298_de18d2b612_s.jpg']]],
[[-4.972429, 34.063041], [['39906716970', 'https://live.staticflickr.com/982/39906716970_43342d54c6_s.jpg']]],
[[-4.975991, 34.063432], [['26846300157', 'https://live.staticflickr.com/906/26846300157_4ee39522e6_s.jpg']]]
],
'HU': [
[[19.078016, 47.514852], [['5689733269', 'https://live.staticflickr.com/5147/5689733269_6b41ecaccc_s.jpg']]],
[[19.046301, 47.48789], [['5690367270', 'https://live.staticflickr.com/5030/5690367270_dc7d8dc625_s.jpg']]],
[[19.055185, 47.485656], [['5691112233', 'https://live.staticflickr.com/5028/5691112233_3c73ac7ff8_s.jpg']]],
[[19.045915, 47.487368], [['5691387820', 'https://live.staticflickr.com/5185/5691387820_56cb7e084e_s.jpg']]],
[[19.048061, 47.487542], [['5690733687', 'https://live.staticflickr.com/5221/5690733687_ee950b3172_s.jpg']]],
[[19.048061, 47.486584], [['5690872140', 'https://live.staticflickr.com/5147/5690872140_69b7230f20_s.jpg']]]
]
}
|
986,542 | dc9e9f0dd44013f1911e9eb89abb8134dca98761 | import sys
import os
import django
sys.path.append('../../../platform_manage')
os.environ['DJANGO_SETTINGS_MODULE'] = 'platform_manage.settings'
django.setup()
|
986,543 | d022cbb75ae80cd18919091478f224a40ed648f4 | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
hashtable = {}
HT = {}
result = []
for i in nums1:
if i in hashtable.keys():
hashtable[i] += 1
else:
hashtable[i] = 1
for i in nums2:
if i in HT.keys():
HT[i] += 1
else:
HT[i] = 1
for key,values in hashtable.items():
if key in HT.keys():
for i in range(min(HT[key],values)):
result.append(key)
return result
|
986,544 | 7d343ef75f50eefa9616dc4f51866183f02dc47b | # coding=utf-8
#
# @lc app=leetcode id=860 lang=python
#
# [860] Lemonade Change
#
# https://leetcode.com/problems/lemonade-change/description/
#
# algorithms
# Easy (50.28%)
# Likes: 318
# Dislikes: 60
# Total Accepted: 31.3K
# Total Submissions: 61.7K
# Testcase Example: '[5,5,5,10,20]'
#
# At a lemonade stand, each lemonade costs $5.
#
# Customers are standing in a queue to buy from you, and order one at a time
# (in the order specified by bills).
#
# Each customer will only buy one lemonade and pay with either a $5, $10, or
# $20 bill. You must provide the correct change to each customer, so that the
# net transaction is that the customer pays $5.
#
# Note that you don't have any change in hand at first.
#
# Return true if and only if you can provide every customer with correct
# change.
#
#
#
#
# Example 1:
#
#
# Input: [5,5,5,10,20]
# Output: true
# Explanation:
# From the first 3 customers, we collect three $5 bills in order.
# From the fourth customer, we collect a $10 bill and give back a $5.
# From the fifth customer, we give a $10 bill and a $5 bill.
# Since all customers got correct change, we output true.
#
#
#
# Example 2:
#
#
# Input: [5,5,10]
# Output: true
#
#
#
# Example 3:
#
#
# Input: [10,10]
# Output: false
#
#
#
# Example 4:
#
#
# Input: [5,5,10,10,20]
# Output: false
# Explanation:
# From the first two customers in order, we collect two $5 bills.
# For the next two customers in order, we collect a $10 bill and give back a $5
# bill.
# For the last customer, we can't give change of $15 back because we only have
# two $10 bills.
# Since not every customer received correct change, the answer is false.
#
#
#
#
# Note:
#
#
# 0 <= bills.length <= 10000
# bills[i] will be either 5, 10, or 20.
#
#
#
#
#
#
#
class Solution(object):
def lemonadeChange(self, bills):
"""
:type bills: List[int]
:rtype: bool
"""
# pay back with the transaction and carry with the minimal
carry = {5: 0, 10: 0, 20: 0}
amount = 5
for bill in bills:
if bill > amount:
pay_back = bill - amount
if pay_back == 5:
if carry[5] > 0:
carry[5] -= 1
else:
return False
elif pay_back == 15:
if carry[5] > 0 and carry[10] > 0:
carry[5] -= 1
carry[10] -= 1
elif carry[5] > 2:
carry[5] -= 3
else:
return False
else:
return False
carry[bill] += 1
return True
# if __name__ == '__main__':
# s = Solution()
# print s.lemonadeChange([5, 5, 10])
# print s.lemonadeChange([10, 10])
# print s.lemonadeChange([5, 5, 10, 10, 20])
# print s.lemonadeChange([5, 5, 5, 10, 20])
|
986,545 | 380d9a9d09586b1fc3a30ce4a4169c5e8d422bd8 | # -*- coding: utf-8 -*-
"""
Created on Mon May 3 16:51:24 2021
@author: Will
"""
#exception to force user to input an integer
while True:
try:
n = input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("Input not an integer; try again")
print("Correct input of an integer!")
#example: control input
data = []
file_name = input("Provide a name of a file of data")
try:
fh = open(file_name, 'r')
except IOError:
print("Cannot open ", file_name)
else:
for new in fh:
if new != '\n':
addIt = new[:-1].split(',')
data.append(addIt)
finally:
fh.close()
#example: file is a list of names and grades - want to add an empty list to students that do not have a grade
#name could be 1 element, or 2 elements, or 3 elements... grade is always the last element of the list
gradesData = []
if data:
for x in data:
try:
name = x[0:-1]
grades = int(x[-1])
gradesData.append([name, [grades]])
except ValueError: #if student does not havea grade, this will throw a value error
gradesData.append([x[:],[]])
#exceptions as control flow
def get_ratios(L1, L2):
"""Assumes L1 and L2 are lists of equal length of numbers. Returns a
List containing L1[i] / L2[i] """
ratios = []
for index in range(len(L1)):
try:
ratios.append(L1[index]/float(L2[index]))
except ZeroDivisionError:
ratios.append(float('NaN')) #NaN = not a number
except:
raise ValueError('get_ratios called with bad arg')
return ratios
#giving a return to an exception
def avg(grades):
try:
return sum(grades)/len(grades)
except ZeroDivisionError:
print('no grades data')#flags the error
return 0.0 #returns an output that is more in line with the data structure we want
#helper function for fancy divide (shown below)
#do not raise exception if there is a divide by zero error
#when dividing by 0, this should returna list with all 0 elements
def simple_divide(item, denom):
try:
return item / denom
except ZeroDivisionError:
return 0
def fancy_divide(list_of_numbers, index):
denom = list_of_numbers[index]
return[simple_divide(item, denom) for item in list_of_numbers]
#function to normalize a list of numbers
def normalize(numbers):
max_number = max(numbers)
assert(max_number != 0), "Cannot divide by 0" #asserts that max_number is not equal to 0
for i in range(len(numbers)):
numbers[i] /= float(max_number)
assert(0.0 <= numbers[i] <= 1.0), "output not between 0 and 1"
return numbers
|
986,546 | 253a18f54bc420d883e70df5c03dcc01057f055c | from arms import arms
import os
import pygame
import sys
import time
import math
import random
from bullet import bullet
from pygame.locals import *
class explosion(arms):
def __init__(self, x, y,radius=-1):
pygame.sprite.Sprite.__init__(self, self.containers)
sheet = pygame.image.load('Sprites/enemy_explode.png')
self.images = []
for i in range(0, 768, 48):
rect = pygame.Rect((i, 0, 48, 48))
image = pygame.Surface(rect.size)
image = image.convert()
colorkey = -1
colorkey = image.get_at((10, 10))
image.set_colorkey(colorkey, RLEACCEL)
image.blit(sheet, (0, 0), rect)
if radius != -1:
image = pygame.transform.scale(image,(radius,radius))
self.images.append(image)
self.image = self.images[0]
self.index = 0
self.rect = self.image.get_rect()
self.rect.center = (x, y)
def update(self):
self.image = self.images[self.index]
self.index += 1
if self.index >= len(self.images):
self.kill()
|
986,547 | 82a4fda86c56ff115ce3fed28d4a84efd1c6477c | from {{cookiecutter.project_slug}}.analytics.{{cookiecutter.feature_name}}.parse_cli_args import parse_cli_args
from {{cookiecutter.project_slug}}.analytics.{{cookiecutter.feature_name}}.common.setup_logging.setup_logging import initialise_logging
def main(command_line, environment):
args = parse_cli_args(command_line, environment)
if args is None:
return 1
initialise_logging(args.debug) |
986,548 | e5625738220b3525759c0c2476074e0270f61934 | # -*- coding: utf-8 -*-
# @Author : Lee
# @Time : 2021/7/13 10:46
# @Function: 示例3 : Mauna Loa CO2 数据中的 GRR
#
import numpy as np
from matplotlib import pyplot as plt
from sklearn.datasets import fetch_openml
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, WhiteKernel, RationalQuadratic, ExpSineSquared
def load_mauna_loa_atmospheric_co2():
ml_data = fetch_openml(data_id=41187, as_frame=False)
months = []
ppmv_sums = []
counts = []
y = ml_data.data[:, 0]
m = ml_data.data[:, 1]
month_float = y + (m - 1) / 12
ppmvs = ml_data.target
for month, ppmv in zip(month_float, ppmvs):
if not months or month != months[-1]:
months.append(month)
ppmv_sums.append(ppmv)
counts.append(1)
else:
# aggregate monthly sum to produce average
ppmv_sums[-1] += ppmv
counts[-1] += 1
months = np.asarray(months).reshape(-1, 1)
avg_ppmvs = np.asarray(ppmv_sums) / counts
return months, avg_ppmvs
X, y = load_mauna_loa_atmospheric_co2()
#
# Kernel with parameters given in GPML book
k1 = 66.0**2 * RBF(length_scale=67.0) # long term smooth rising trend
k2 = 2.4**2 * RBF(length_scale=90.0) * ExpSineSquared(length_scale=1.3, periodicity=1.0) # seasonal component
# medium term irregularity
k3 = 0.66**2 * RationalQuadratic(length_scale=1.2, alpha=0.78)
k4 = 0.18**2 * RBF(length_scale=0.134) + WhiteKernel(noise_level=0.19**2) # noise terms
kernel_gpml = k1 + k2 + k3 + k4
gp = GaussianProcessRegressor(kernel=kernel_gpml, alpha=0, optimizer=None, normalize_y=True)
gp.fit(X, y)
print("GPML kernel: %s" % gp.kernel_)
print("Log-marginal-likelihood: %.3f" % gp.log_marginal_likelihood(gp.kernel_.theta))
#
# Kernel with optimized parameters
k1 = 50.0**2 * RBF(length_scale=50.0) # RBF解释一个长期平稳的上升趋势
k2 = 2.0**2 * RBF(length_scale=100.0) \
* ExpSineSquared(length_scale=1.0, periodicity=1.0, periodicity_bounds="fixed") # 季节性因素。固定周期为1年
# RationalQuadratic解释较小的中期不规则性
k3 = 0.5**2 * RationalQuadratic(length_scale=1.0, alpha=1.0)
# WhiteKernel处理噪声
k4 = 0.1**2 * RBF(length_scale=0.1) \
+ WhiteKernel(noise_level=0.1**2, noise_level_bounds=(1e-5, np.inf)) # noise terms
kernel = k1 + k2 + k3 + k4
# kernel = k1 + k3 + k4 # 可以多测试几种
gp = GaussianProcessRegressor(kernel=kernel, alpha=0, normalize_y=True)
gp.fit(X, y)
print("\nLearned kernel: %s" % gp.kernel_)
print("Log-marginal-likelihood: %.3f" % gp.log_marginal_likelihood(gp.kernel_.theta))
X_ = np.linspace(X.min(), X.max() + 30, 1000)[:, np.newaxis]
y_pred, y_std = gp.predict(X_, return_std=True)
plt.scatter(X, y, c='k')
plt.plot(X_, y_pred)
plt.fill_between(X_[:, 0], y_pred - y_std, y_pred + y_std, alpha=0.5, color='k')
plt.xlim(X_.min(), X_.max())
plt.xlabel("Year")
plt.ylabel(r"CO$_2$ in ppm")
plt.title(r"Atmospheric CO$_2$ concentration at Mauna Loa")
plt.tight_layout()
plt.show()
"""
Learned kernel:
2.62**2 * RBF(length_scale=51.6) +
0.155**2 * RBF(length_scale=91.4) * ExpSineSquared(length_scale=1.48, periodicity=1) +
0.0315**2 * RationalQuadratic(alpha=2.88, length_scale=0.968) +
0.011**2 * RBF(length_scale=0.122) + WhiteKernel(noise_level=0.000126)
GPML kernel:
66**2 * RBF(length_scale=67) +
2.4**2 * RBF(length_scale=90) * ExpSineSquared(length_scale=1.3, periodicity=1) +
0.66**2 * RationalQuadratic(alpha=0.78, length_scale=1.2) +
0.18**2 * RBF(length_scale=0.134) + WhiteKernel(noise_level=0.0361)
"""
|
986,549 | 0889fad3c96ec00078bea2092b9bd62fe03dc671 | from django.db import models
import uuid
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from userena.models import UserenaBaseProfile
from django.core.validators import URLValidator
from django.contrib import admin
import tagulous.models
#from phonenumber_field.modelfields import PhoneNumberField
class Team(models.Model):
"""docstring for Team"""
uuid = models.AutoField(primary_key=True)
name = models.CharField(max_length=100, unique=True, blank=False, null=False)
description = models.TextField(blank=True, null=True)
mentor = models.OneToOneField(User,unique=True,verbose_name=_('mentor'),related_name='mentor')
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
verbose_name = _('team')
verbose_name_plural = _('teams')
# Custom manager lets us do things like Item.completed_tasks.all()
objects = models.Manager()
def get_default_team():
return Team.objects.first()
class MyProfile(UserenaBaseProfile):
user = models.OneToOneField(User,unique=True,verbose_name=_('user'),related_name='profile')
# team = models.OneToOneField(Team,unique=True,verbose_name=_('team'),related_name='team')
team = models.ForeignKey(Team,blank=False, null=False, default=get_default_team)
birth_date = models.DateField(blank=True, null=True)
address = models.TextField(blank=True, null=True)
#telephone = models.PhoneNumberField(blank=True)
about = models.TextField(blank=True, null=True)
city = models.CharField(max_length=100,blank=True, null=True)
GENDER_CHOICES = (('M', 'Male'),('F', 'Female'))
gender = models.CharField(max_length=1, choices=GENDER_CHOICES,blank=True, null=True)
github = models.CharField(max_length=100,validators=[URLValidator()],blank=True, null=True)
facebook = models.CharField(max_length=100,validators=[URLValidator()],blank=True, null=True)
twitter = models.CharField(max_length=100,validators=[URLValidator()],blank=True, null=True)
googleplus = models.CharField(max_length=100,validators=[URLValidator()],blank=True, null=True)
website = models.CharField(max_length=100,validators=[URLValidator()],blank=True, null=True)
skills = tagulous.models.TagField(autocomplete_initial=True,blank=True, null=True)
def __unicode__(self):
return '%s' % (self.user)
# objects = models.Manager()
class TeamAdmin(admin.ModelAdmin):
search_fields = ["name"]
list_display = ["name"]
|
986,550 | d5027cf75ea452c38b4ef41e768b5edcfea79ba0 | from PIL import ImageGrab
from PIL import Image
import requests
import io
import time
def screen_shot():
img = ImageGrab.grab()
roiImg = img.crop()
imgByteArr = io.BytesIO()
roiImg.save(imgByteArr, format='JPEG')
imgByteArr = imgByteArr.getbuffer()
return imgByteArr
def image_to_byte_array():
image = Image.open('im.jpeg')
imgByteArr = io.BytesIO()
image.save(imgByteArr, format='JPEG')
imgByteArr = imgByteArr
print(imgByteArr)
print(open('im.jpeg', 'rb'))
return imgByteArr
image_to_byte_array()
def to_byte(s):
num = []
for i in s:
num.append(ord(i))
num = bytes(num)
print(num)
to_byte('denis')
|
986,551 | 1479bbba636268707d7e2f05d2f10506504cb36b | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-25 11:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userapi', '0009_remove_location_status'),
]
operations = [
migrations.AddField(
model_name='location',
name='status',
field=models.IntegerField(default=None, null=True),
),
migrations.AlterField(
model_name='location',
name='lat',
field=models.FloatField(blank=True, null=True),
),
migrations.AlterField(
model_name='location',
name='lng',
field=models.FloatField(blank=True, null=True),
),
]
|
986,552 | 5308f9fd194feae515e3d20cc2309d4709751887 | import builtins
import logging
from types import SimpleNamespace
from lumigo_tracer import lumigo_utils
from lumigo_tracer.spans_container import SpansContainer
import mock
import pytest
from lumigo_tracer.lumigo_utils import Configuration, get_omitting_regex, get_logger
from lumigo_tracer.wrappers.http.http_data_classes import HttpState
@pytest.fixture(autouse=True)
def reporter_mock(monkeypatch):
lumigo_utils.Configuration.should_report = False
reporter_mock = mock.Mock(lumigo_utils.report_json)
reporter_mock.return_value = 123
monkeypatch.setattr(lumigo_utils, "report_json", reporter_mock)
return reporter_mock
@pytest.fixture(autouse=True)
def cancel_timeout_mechanism(monkeypatch):
monkeypatch.setattr(Configuration, "timeout_timer", False)
@pytest.fixture(autouse=True)
def remove_caches(monkeypatch):
get_omitting_regex.cache_clear()
@pytest.yield_fixture(autouse=True)
def restart_global_span():
"""
This fixture initialize the span to be empty.
"""
yield
SpansContainer._span = None
HttpState.clear()
@pytest.yield_fixture(autouse=True)
def reset_print():
"""
Resets print
"""
local_print = print
yield
builtins.print = local_print
@pytest.fixture(autouse=True)
def verbose_logger():
"""
This fixture make sure that we will see all the log in the tests.
"""
lumigo_utils.get_logger().setLevel(logging.DEBUG)
lumigo_utils.config(should_report=False, verbose=True)
def pytest_addoption(parser):
parser.addoption("--all", action="store_true", default=False, help="run components tests")
def pytest_collection_modifyitems(config, items):
if config.getoption("--all"):
return # don't skip!
skip_slow = pytest.mark.skip(reason="need --all option to run")
for item in items:
if "slow" in item.keywords:
item.add_marker(skip_slow)
@pytest.fixture(autouse=True)
def capture_all_logs(caplog):
caplog.set_level(logging.DEBUG, logger="lumigo")
get_logger().propagate = True
@pytest.fixture
def context():
return SimpleNamespace(aws_request_id="1234", get_remaining_time_in_millis=lambda: 1000 * 2)
|
986,553 | 4b4ae0e9049372bc2adea7c1d3fbff12ec157000 | import shlex
import varchs.i386 as e_i386
def eflags(vdb, line):
"""
Shows or flips the status of the eflags register bits.
Usage: eflags [flag short name]
"""
trace = vdb.getTrace()
argv = shlex.split(line)
if len(argv) not in (0, 1):
return vdb.do_help('eflags')
if len(argv) > 0:
flag = argv[0].upper()
valid_flags = list(trace.getStatusFlags().keys())
if flag not in valid_flags:
raise Exception('invalid flag: %s, valid flags %s' % (flag, valid_flags))
value = trace.getRegisterByName(flag)
trace.setRegisterByName(flag, not bool(value))
# TODO: this is not plumbed through to flags gui due to new gui
# eventing coming soon.
vdb.vdbUIEvent('vdb:setflags')
return
ef = trace.getRegisterByName('eflags')
vdb.vprint('%16s: %s' % ('Carry', bool(ef & e_i386.EFLAGS_CF)))
vdb.vprint('%16s: %s' % ('Parity', bool(ef & e_i386.EFLAGS_PF)))
vdb.vprint('%16s: %s' % ('Adjust', bool(ef & e_i386.EFLAGS_AF)))
vdb.vprint('%16s: %s' % ('Zero', bool(ef & e_i386.EFLAGS_ZF)))
vdb.vprint('%16s: %s' % ('Sign', bool(ef & e_i386.EFLAGS_SF)))
vdb.vprint('%16s: %s' % ('Trap', bool(ef & e_i386.EFLAGS_TF)))
vdb.vprint('%16s: %s' % ('Interrupt', bool(ef & e_i386.EFLAGS_IF)))
vdb.vprint('%16s: %s' % ('Direction', bool(ef & e_i386.EFLAGS_DF)))
vdb.vprint('%16s: %s' % ('Overflow', bool(ef & e_i386.EFLAGS_OF)))
def vdbExtension(vdb, trace):
vdb.addCmdAlias('db', 'mem -F bytes')
vdb.addCmdAlias('dw', 'mem -F u_int_16')
vdb.addCmdAlias('dd', 'mem -F u_int_32')
vdb.addCmdAlias('dq', 'mem -F u_int_64')
vdb.addCmdAlias('dr', 'mem -F "Deref View"')
vdb.addCmdAlias('ds', 'mem -F "Symbols View"')
vdb.registerCmdExtension(eflags)
|
986,554 | 0c92663f229aa12ba3e4d06c0bcffa81057d1eec | from rest_framework import serializers
from apps.warehouse.models import HashTag, Tweet, TweetUser, TweetMedia
class TweetMediaSerializer(serializers.ModelSerializer):
class Meta:
model = TweetMedia
fields = ('url',)
class TweetUserSerializer(serializers.ModelSerializer):
class Meta:
model = TweetUser
fields = ('screen_name',)
class TweetSerializer(serializers.ModelSerializer):
user_mentions = TweetUserSerializer(read_only=True, many=True)
tweet_media = TweetMediaSerializer(read_only=True, many=True)
class Meta:
model = Tweet
fields = ('id', 'tweet_id', 'tip', 'favorite_count', 'retweet_count', 'timestamp', 'user_mentions', 'tweet_media')
class TweetSerializerSearch(serializers.ModelSerializer):
tweet_media = TweetMediaSerializer(read_only=True, many=True)
class Meta:
model = Tweet
fields = ('id', 'tweet_id', 'tip', 'timestamp', 'tweet_media')
class HashTagSerializer(serializers.ModelSerializer):
tweets = TweetSerializer(read_only=True, many=True)
class Meta:
model = HashTag
fields = ('id', 'tag', 'tweets')
|
986,555 | 10ec818e13f6b00528ed73890e36e79d98a9e12c | x, y, z, k = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))
A.sort()
B.sort()
C.sort()
A = A[::-1]
B = B[::-1]
C = C[::-1]
a = 0
b = 0
c = 0
visited = [[0 for i in range(max(x, y, z))] for i in range(3)]
myA = 0
myB = 0
myC = 0
for i in range(k):
visited[0][a] += 1
visited[1][b] += 1
visited[2][c] += 1
print(a, b, c)
print(A[a] + B[b] + C[c])
if a == len(A) - 1:
thisA = 10 ** 20
else:
thisA = A[myA] - A[a + 1]
if b == len(B) - 1:
thisB = 10 ** 20
else:
thisB = B[myB] - B[b + 1]
if c == len(C) - 1:
thisC = 10 ** 20
else:
thisC = C[myC] - C[c + 1]
this = [thisA, thisB, thisC]
if min(this) == thisA:
a += 1
for j in range((max(x, y, z))):
if visited[1][j] < x * z:
b = j
myB = b
break
for j in range((max(x, y, z))):
if visited[2][j] < x * y:
c = j
byC = c
break
elif min(this) == thisB:
b += 1
for j in range((max(x, y, z))):
if visited[0][j] < x * z:
a = j
myA = a
break
for j in range((max(x, y, z))):
if visited[2][j] < x * y:
c = j
myC = c
break
else:
c += 1
for j in range((max(x, y, z))):
if visited[0][j] < x * z:
a = j
myA = a
break
for j in range((max(x, y, z))):
if visited[1][j] < x * y:
b = j
myB = b
break |
986,556 | 0fbd9d06737277c55c085ba33f022fd608b9ed89 | '''OPGAVE
Schrijf een functie groep waaraan een reeks (een lijst of een tuple) van strings moet doorgegeven worden die een groep stenen voorstelt.
De functie moet een dictionary teruggeven die de gegeven groep stenen voorstelt.
Schrijf een functie uitleggen waaraan twee dictionaries moeten doorgegeven worden. De eerste stelt een rijtje stenen voor die een speler wil uitleggen.
De tweede stelt de stenen voor die de speler op zijn rekje heeft staan.
De functie moet een Booleaanse waarde teruggeven die aangeeft of de speler het gegeven rijtje stenen kan uitleggen.
Dat is het geval als alle stenen van het rijtje wel degelijk op het gegeven rekje staan, rekening houdend met het aantal keer dat de stenen voorkomen in het rijtje en op het rekje.
Indien de speler het gegeven rijtje kan uitleggen, dan moet de functie er ook voor zorgen dat die stenen weggehaald worden uit de dictionary die de stenen op het rekje voorstelt.
Indien de speler het gegeven rijtje niet kan uitleggen, dan mag de functie de gegeven dictionary die de stenen op het rekje voorstelt niet wijzigen.'''
def groep(stenen):
stenen_dictionary = {}
for steen in stenen:
if steen in stenen_dictionary:
stenen_dictionary[steen] += 1
else:
stenen_dictionary[steen] = 1
return stenen_dictionary
#print(groep(['1G', '7G', '8G', '12G', '12B', '13B', '13B', '13Z', '13G', '2Z', '3Z', '4Z', '11Z', '11Z', '4R', '5R']))
#print(groep(['9G', '7R', '9G', '7R', '9G', '7R', '9G']))
def uitleggen(uitleggen, rekje):
if set(uitleggen).issubset(set(rekje)):
i = 0
mes = True
while i < len(uitleggen) and mes is True:
if groep(uitleggen).get(uitleggen[i]) <= groep(rekje).get(uitleggen[i]):
rekje.remove(uitleggen[i])
i += 1
else:
mes = False
else:
mes = False
return mes, rekje
#print(uitleggen(['13B', '13Z', '13G'],['1G', '7G', '8G', '12G', '12B', '13B', '13B', '13Z', '13G', '2Z', '3Z', '4Z', '11Z', '11Z', '4R', '5R']))
#print(uitleggen(['12B', '12Z', '12G'],['1G', '7G', '8G', '12G', '12B', '13B', '13B', '13Z', '13G', '2Z', '3Z', '4Z', '11Z', '11Z', '4R', '5R'])) |
986,557 | d4660f0ff279ccec93ace2f6f781cd33ea8d1ea5 |
SUMPAR = 0
SUMIMP = 0
CUEPAR = 0
for I in range(0,271,1):
NUM = int(input("Ingresa un numero entero positivo: "))
if NUM != 0:
if ((-1) ** NUM) > 0:
SUMPAR += NUM
CUEPAR += 1
else:
SUMIMP += NUM
else:
I += 1
PROPAR = SUMPAR / CUEPAR
print(f"El promedio de los numeros pares ingresados es {PROPAR} y la suma de los impares es de {CUEPAR}.")
print("Fin del programa.")
|
986,558 | a475a2f47a1f4f084b72e5c7d5ff0c7276abd470 | #!/usr/bin/env python
from twisted.internet import reactor
from settings import settings
from webserver.site import site
def main():
print 'Start listening on http://localhost:8080/'
reactor.listenTCP(8080, site)
reactor.run()
if __name__ == '__main__':
from utils import autoreload
autoreload.main(main,
root=settings.PROJECT_ROOT,
extensions=['.py', '.jinja2', '.jstmpl']
)
|
986,559 | dbd5997fa3dd925790d0a6115bbd2bf470ca9620 | import numpy as np
import cv2
cap = cv2.VideoCapture('forward_6sec.mp4')
cap_rev = cv2.VideoCapture('reverse_6sec.mp4')
fgbg = cv2.createBackgroundSubtractorMOG2()
fgbg.setShadowValue(0)
kernel5 = np.ones((5,5), np.uint8)
kernel7 = np.ones((7,7), np.uint8)
kernel3 = np.ones((3,3), np.uint8)
i=1
while(1):
ret, frame = cap.read()
ret, frame_rev = cap_rev.read()
fgmask = fgbg.apply(frame)
fgmask_rev = fgbg.apply(frame_rev)
if i==182:
break;
elif i<=9:
vid_erode = cv2.erode(fgmask, kernel3, iterations=1)
vid_dilate = cv2.dilate(vid_erode, kernel3, iterations=1)
vid_erode_rev = cv2.erode(fgmask_rev, kernel7, iterations=1)
vid_dilate_rev = cv2.dilate(vid_erode_rev, kernel7, iterations=1)
#cv2.imshow('frame',fgmask)
#vid_dilate = cv2.dilate(fgmask, kernel3, iterations=1)
#vid_dilate_rev = cv2.dilate(fgmask_rev, kernel7, iterations=1)
cv2.imwrite('forward/f'+str(i)+'.bmp',vid_dilate);
cv2.imwrite('reverse/r'+str(182-i)+'.bmp',vid_dilate_rev);
cv2.imshow('Eroded and dilated',vid_dilate)
cv2.imshow('Eroded and dilated reverse',vid_dilate_rev)
elif i>=172:
vid_erode = cv2.erode(fgmask, kernel7, iterations=1)
vid_dilate = cv2.dilate(vid_erode, kernel7, iterations=1)
vid_erode_rev = cv2.erode(fgmask_rev, kernel3, iterations=1)
vid_dilate_rev = cv2.dilate(vid_erode_rev, kernel3, iterations=1)
#cv2.imshow('frame',fgmask)
#vid_dilate = cv2.dilate(fgmask, kernel7, iterations=1)
#vid_dilate_rev = cv2.dilate(fgmask_rev, kernel3, iterations=1)
cv2.imwrite('forward/f'+str(i)+'.bmp',vid_dilate);
cv2.imwrite('reverse/r'+str(182-i)+'.bmp',vid_dilate_rev);
cv2.imshow('Eroded and dilated',vid_dilate)
cv2.imshow('Eroded and dilated reverse',vid_dilate_rev)
else:
vid_erode = cv2.erode(fgmask, kernel5, iterations=1)
vid_dilate = cv2.dilate(vid_erode, kernel5, iterations=1)
vid_erode_rev = cv2.erode(fgmask_rev, kernel5, iterations=1)
vid_dilate_rev = cv2.dilate(vid_erode_rev, kernel5, iterations=1)
#cv2.imshow('frame',fgmask)
#vid_dilate = cv2.dilate(fgmask, kernel5, iterations=1)
#vid_dilate_rev = cv2.dilate(fgmask_rev, kernel5, iterations=1)
cv2.imwrite('forward/f'+str(i)+'.bmp',vid_dilate);
cv2.imwrite('reverse/r'+str(182-i)+'.bmp',vid_dilate_rev);
cv2.imshow('Eroded and dilated',vid_dilate)
cv2.imshow('Eroded and dilated reverse',vid_dilate_rev)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
i+=1
cap.release()
cv2.destroyAllWindows()
i=1
while i<=181:
img_f = cv2.imread('forward/f'+str(i)+'.bmp')
img_r = cv2.imread('reverse/r'+str(i)+'.bmp')
img_final = cv2.bitwise_or(img_f,img_r)
#img_final_eroded = cv2.erode(img_final,kernel7,iterations=1)
cv2.imwrite('Final/fin'+str(i)+'.bmp',img_final)
i+=1
|
986,560 | f72fd2f37f7f077344325d4fa23d52c7d214d9bf | import sys
import os
path = os.getcwd()
sys.path.append(os.path.join(*[path, "bin"]))
from source.component import Slot, Car
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
raise Exception("Can not initiate %s multiple times" % cls._instance.__class__)
class Parking(object):
"""
Main logic written in this class
This store the slot data and allocate / deallocate the space
"""
def __init__(self):
self.slots = {}
def create_parking_lot(self, allow_slots):
"""
Helps to create a parking lot
input:
allow_slots - int
"""
allow_slots = int(allow_slots)
if len(self.slots) > 0:
print("Parking Lot is already created")
return
if allow_slots < 1:
print("Number of slot: %s provided is incorrect." % allow_slots)
return
for i in range(1, allow_slots + 1):
self.slots[i] = Slot(slot_no=i, available=True)
print("Created a parking lot with %s slots" % allow_slots)
def _get_nearest_slot(self):
"""
Method to find nearest available slot to the entry point
"""
available_slots = [pslot for pslot in self.slots.values() if pslot.available]
if not available_slots:
return None
return sorted(available_slots, key=lambda x: x.slot_no)[0]
def park(self, reg_no, colour):
"""
Helping to park car with recording reg number and colour
input:
reg_no - String
colour - String
"""
if not self._is_valid():
return False, None
available_slot = self._get_nearest_slot()
if available_slot:
# create car object and save in the available slot
available_slot.car = Car.create(reg_no, colour)
available_slot.available = False
print("Allocated slot number: %s" % (available_slot.slot_no))
return True, reg_no
else:
print("Sorry, parking lot is full")
return False, None
def leave(self, slot_no):
"""
deallocate the slot once car left
input:
slot_no - Integer Type
"""
slot_no = int(slot_no)
if not self._is_valid():
return
if slot_no in self.slots:
pslot = self.slots[slot_no]
if not pslot.available and pslot.car:
pslot.car = None
pslot.available = True
print("Slot number %s is free" % slot_no)
else:
print("No car is present at slot number %s" % slot_no)
else:
print("Sorry, slot number does not exist in parking lot.")
def status(self):
"""
Show the current situation of partking lot
"""
if not self._is_valid():
return
print("Slot No\tRegistration No\tColour")
parked_car = []
for i in self.slots.values():
if not i.available and i.car:
parked_car.append(i.car.reg_no)
print("%s\t%s\t%s" % (i.slot_no, i.car.reg_no, i.car.colour))
return parked_car
def _is_valid(self):
"""
Validation before doing any change in parking
"""
if len(self.slots) == 0:
print("Parking Lot not created")
return False
return True
def registration_numbers_for_cars_with_colour(self, colour):
"""
Find registration numbers of car with given colour in parking
input:
colour - String
"""
if not self._is_valid():
return
colour = colour.lower()
reg_nos = []
for pslot in self.slots.values():
if not pslot.available and pslot.car and pslot.car.colour.lower() == colour:
reg_nos.append(pslot.car.reg_no)
if reg_nos:
print(", ".join(reg_nos))
else:
print("Not found")
return reg_nos
def slot_numbers_for_cars_with_colour(self, colour):
"""
Find slot numbers for cars with given colour in parking.
input:
colour - String
"""
if not self._is_valid():
return
colour = colour.lower()
slot_nos = []
for pslot in self.slots.values():
if not pslot.available and pslot.car and pslot.car.colour.lower() == colour:
slot_nos.append(str(pslot.slot_no))
if slot_nos:
print(", ".join(slot_nos))
else:
print("Not found")
return slot_nos
def slot_number_for_registration_number(self, reg_no):
"""
Find slot numbers in parking against registration number.
input:
reg_no - String
"""
if not self._is_valid():
return
slot_no = ""
for pslot in self.slots.values():
if not pslot.available and pslot.car and pslot.car.reg_no == reg_no:
slot_no = pslot.slot_no
break
if slot_no:
print(slot_no)
else:
print("Not found")
return
return slot_no
|
986,561 | 2736716763d80400edf1e35163103d6a269c062b | import numpy
import skimage.io
import sys
fnames = sys.argv[1:]
for fname in fnames:
im = skimage.io.imread(fname)
if numpy.count_nonzero(im[0:2, :, :]) == 0:
continue
print(fname)
im2 = numpy.zeros((im.shape[0]+4, im.shape[1]+4, 3), dtype='uint8')
im2[2:-2, 2:-2, :] = im
im2[0:2, :, :] = 0
im2[-2:, :, :] = 0
im2[:, 0:2, :] = 0
im2[:, -2:, :] = 0
skimage.io.imsave(fname, im2)
|
986,562 | ff8164af9bf7e1c0344478d001fdd014a681dfcc | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# auth: wallace.wang
import imp
import json
from tornado import web
from com.utils.MyLog import MyLog
from utils.handlerData import handler_data
from utils.auth import AuthToken
class AuthHandler(web.RequestHandler):
def initialize(self):
"""
identity_data:是请求时的用户信息
response_data:用于返回给请求端的数据
identity_action:标识的是认证的结果,成功则为True默认为False
:return:
"""
self.identity_data = dict()
self.response_data = {'status': None, 'access_token': None, 'msg': None}
self.identity_action = False
self.log = MyLog(path='../log/', name='login')
# 数据处理和认证
def prepare(self):
self.identity_data = handler_data(self.request.body)
if len(self.identity_data) == 0:
self.write('Please carried valid data ')
self._identity_auth()
self._generate_response_data()
# 认证逻辑
def _identity_auth(self):
# 这里的密码保存在数据的密码进行匹配/需要连接数据库
# info = self._get_info()
info = {'appID': '123456', 'authKey': 'qwe123'}
if self.identity_data.get('appID') == info['appID'] and \
self.identity_data.get('authKey') == info['authKey']:
self.identity_action = True
log_msg = '%s login successful' % self.identity_data.get('appID')
self.log.info(log_msg)
else:
if self.identity_data.get('appID') is None or self.identity_data.get('authKey') is None:
log_msg = 'Request parameter errors'
self.log.warning(log_msg)
self.write('Request parameter errors, please provide the correct request parameters')
log_msg = 'login fails, UserID or authKey is error '
self.response_data['msg'] = 'appID or authKey is error'
self.log.warning(log_msg)
def _generate_response_data(self):
if self.identity_action is True:
token = AuthToken(self.identity_data.get('appID')).generate_token()
self.response_data['status'] = 8000
self.response_data['access_token'] = token
self.response_data['msg'] = 'Identity success'
else:
self.response_data['status'] = 8004
# 返回数据
def post(self, *args, **kwargs):
print '数据返回'
self.write(json.dumps(self.response_data))
class BaseHandler(web.RequestHandler):
def initialize(self):
self.request_data = dict()
self.response_data = {'status': None, 'data': None, 'msg': None}
self.auth_status = None
def prepare(self):
# 认证token信息
token = self.request.headers.get('Token')
self.app_id = self.request.headers.get('appID')
if not token or not self.app_id:
self.write('Request parameter errors, please provide the correct request parameters')
self.request_data = handler_data(self.request.body)
self.log = MyLog(path='../log/', name='server')
# self.auth_status = AuthToken(self.app_id).verify_auth_token(token)
self.auth_status=True # 测试获取数据使用
if self.auth_status is not True:
self.response_data['status'] = 9004
self.response_data['msg'] = self.auth_status
log_msg = '%s authentication failure' % self.app_id
self.log.warning(log_msg)
self.write(json.dumps(self.response_data))
else:
pass
class ServerHandler(BaseHandler):
def post(self, *args, **kwargs):
try:
api_module, method = tuple(self.request_data.pop('api').split('.'))
parameters = self.request_data
except KeyError, e:
msg = 'Request parameter errors, please provide the correct request parameters!'
self.response_data['msg'] = msg
self.response_data['status']=7004
self.log.error(msg)
self.write(self.response_data)
self._specific_operate(api_module, method, **parameters)
self.write(json.dumps(self.response_data))
def _specific_operate(self, api_module, method, **kwargs):
"""
这里是根据提供的数据进行动态的导入模块,注意这里导入模块是要根据文件路径来导入
导入后根据提供的method来操纵数据并得到返回值
:param data:
:return:
"""
import os
try:
# 根据提供的api_name动态导入模块
# path = os.sep.join([os.path.dirname(os.path.dirname(os.path.abspath(__name__))),api_module+'.py'])
module_li = imp.load_source('mymode', r'G:\project_code\tbs-dc-dss-new\test\test1.py')
obj = module_li.fun(**kwargs)
data_result = getattr(obj, method)
operate_data = data_result()
self.response_data['data'] = operate_data
self.response_data['status'] = 7000
self.response_data['msg'] = 'operate success'
log_msg = '%s %s operation is successful, object is %s' % (self.app_id, method, api_module)
self.log.info(log_msg)
except (TypeError, AttributeError, ImportError, KeyError), e:
if isinstance(e, KeyError):
e = 'Params is Invalid'
self.response_data['msg'] = str(e)
self.response_data['status'] = 7004
log_msg = '%s %s operation is fails,by operated object is %s, the reason is %s' %\
(self.app_id, method, api_module, e)
self.log.error(log_msg) |
986,563 | 54d6533af09dda94939ef42cafd2f9ce333e9638 | import time
from django.test import TestCase
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from django.conf import settings
class TestLogin(TestCase):
def setUp(self):
chrome_options = Options()
chrome_options.add_argument("--headless")
self.driver = webdriver.Chrome(ChromeDriverManager().install(),options=chrome_options )
super(TestLogin, self).setUp()
def test_login_success(self):
self.driver.get(settings.BASE_URL+"/actionbot")
uname = self.driver.find_element_by_name("username")
passd = self.driver.find_element_by_name("password")
uname.clear()
passd.clear()
uname.send_keys("system")
passd.send_keys("system123")
submit = self.driver.find_elements_by_xpath("//*[contains(text(), 'Proceed')]")
submit[0].click()
print(self.driver.current_url)
self.assertEqual( settings.BASE_URL+"/actionbot/index/" , self.driver.current_url)
self.driver.close()
print("login successful")
def test_login_failure(self):
self.driver.get(settings.BASE_URL+"/actionbot")
uname = self.driver.find_element_by_name("username")
passd = self.driver.find_element_by_name("password")
uname.clear()
passd.clear()
uname.send_keys("invalid user")
passd.send_keys("invalid pass")
submit = self.driver.find_elements_by_xpath("//*[contains(text(), 'Proceed')]")
submit[0].click()
print(self.driver.current_url)
self.assertNotEqual(settings.BASE_URL+"/actionbot/index/" , self.driver.current_url)
self.assertEqual(settings.BASE_URL+"/actionbot/login/" , self.driver.current_url)
self.driver.close()
print("login failure")
def tearDown(self):
self.driver.quit() |
986,564 | a09bd54b3b5682dd6889885afeaa005924c8e573 | import urllib.request
import json
from group import Group
from member import Member
class Jsonstream:
def get_json_object(self):
url = "https://toonhq.org/api/v1/group/"
headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0"}
request = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(request)
json_object = json.loads(response.read().decode('utf8'))
return json_object
def get_members_list(self, member_list):
members = []
for toon in member_list:
toon_id = toon["id"]
toon_name = toon["toon_name"]
irc_nick = toon["irc_nick"]
owner = toon["owner"]
num_players = toon["num_players"]
joined = toon["joined"]
species = toon["species"]
color = toon["color"]
m = Member(toon_id, toon_name, irc_nick, owner, num_players, joined, species, color)
members.append(m)
return members
def get_group_dict(self):
json_object = self.get_json_object()
group_dict = {}
for grp in json_object:
group_id = grp["id"]
options = grp["options"]
member_list = grp["members"]
members = self.get_members_list(member_list)
expiration = grp["expiration"]
num_messages = grp["num_messages"]
special = grp["special"]
created = grp["created"]
updated = grp["updated"]
last_keep_alive = grp["last_keep_alive"]
keep_alives = grp["keep_alives"]
group_type = grp["type"]
district = grp["district"]
location = grp["location"]
g = Group(
group_id, options, members, expiration, num_messages,
special, created, updated, last_keep_alive, keep_alives,
group_type, district, location
)
group_dict[group_id] = g
return group_dict |
986,565 | 32a0f77d4e0b7a5d62079edb89bbfa5411f7553f | from django.db import models
class ChatObjManager(models.Manager):
def save_via_form(self,*args,**kwargs):
#{'mesenge': 'asdas', 'status': 'O', 'change_user': <SimpleLazyObject: <CustomUser: fdsd dfg>>, 'task_id': 1}
cls = {}
cls['mesenge'] = kwargs['mesenge']
cls['change_user'] =kwargs['change_user']
cls['task_id'] = kwargs['task_id']
self.create_messenge(**cls)
def create_messenge(self, **kwargs):
book = self.create(**kwargs)
# do something with the book
return book
def get_chat(self,task):
return self.filters(task=task).order_by('-created_at')
|
986,566 | d49239ccbd22233e659ae98896896722f5af09db | import pprint
from gdax_client import get_balance as get_gdax_balance
from binance_client import get_balance as get_binance_balance
INVESTED = 11000
def merge_balances(b1, b2):
balances = {}
for k, v in b1.iteritems():
if k not in balances:
balances[k] = v
else:
balances[k] += v
for k, v in b2.iteritems():
if k not in balances:
balances[k] = v
else:
balances[k] += v
return balances
def pretty_numbers(b):
for k, v in b.iteritems():
b[k] = '${:,.2f}'.format(b[k])
return b
if __name__=='__main__':
gdax = get_gdax_balance()
binance = get_binance_balance()
b = merge_balances(gdax, binance)
total_balance = sum(b.values())
profit = total_balance - INVESTED
pp = pprint.PrettyPrinter()
pp.pprint(pretty_numbers(b))
print "\nTotal: {}".format('${:,.2f}'.format(total_balance))
print "Profit: {}".format('${:,.2f}'.format(profit))
|
986,567 | 334321d46112aec057616ee504108f75c5a33dce |
"""
Testing module for httpimport
"""
__version__ = '0.3.4'
__name__ = 'searcher'
__author__ = 'AK'
|
986,568 | 30a84e0ee12f6ebae9c35051698cc79468fc9b77 | r_HBx = 11.5 # HB vertical radius
r_HBfym = -4.13 # HB entrance -y
r_HBfyp = 11.75 # HB entrance +y
r_HBmenym = -5.45 # HB mag entrance -y
# (4.13 + (20.06/115.22) * (11.71 - 4.13))
r_HBmenyp = 11.74 # HB mag entrance +y
r_HBmexym = -10.25 # HB mag exit -y
# (4.13 + (95.19/115.22) * (11.71 - 4.13))
r_HBmexyp = 11.71 # HB mag exit +y
r_HBbym = -11.71 # HB exit -y
r_HBbyp = 11.70 # HB exit +y
r_Q1 = 20.00 # 20.00 cm radius
r_Q2 = 30.00 # 30.00 cm radius
r_Q3 = 30.00 # 30.00 cm radius
r_D1 = 30.00 # 30 cm radius
r_BP = 50 # 50 cm radius for flare
off_bp = -19.441 # measured in ?
ang_bp_in = 9.20 # degrees
ang_bp_out = -9.20 # degrees
off_d1 = -11.365 # measured in ?
ang_d1_in = 9.049 # degrees
ang_d1_out = -9.049 # degrees
off_mid = 7.00 # measured in ?
ang_mid = 0 # degrees
x_d1 = 31.5
x_d2 = 28.5
x_d3 = 13.97
x_d4 = 1.956
x_d5 = 28.5
y_d5 = 28.5
r_d5 = 6.35
a_d6 = -0.114
b_d6 = 20.54
|
986,569 | 1626b8c11fd1aeb1ed9d15aecd651c203d472546 | import os
import sys
import warnings
from pathlib import Path
import pandas as pd
from classifiers.basic import BasicClf
from classifiers.personal import PersonalClf
from utils.csv_generator import CSVGenerator
from utils import ctmtocsv
def warn(*args, **kwargs):
# Used to remove warnings to print
pass
warnings.warn = warn
def csv_exist(trans, file):
if trans == 'manu':
path = Path("../release1/trans-" + trans + "/" + file + ".csv")
if path.exists():
return pd.read_csv(path, sep='\t', header=None, names=['id', 'content', 'label'], quoting=3,
keep_default_na=False)
else:
txt_exist(trans, file)
csvg = CSVGenerator("trans-" + trans + "/" + file)
csvg.generate()
return pd.read_csv(path, sep='\t', header=None, names=['id', 'content', 'label'], quoting=3,
keep_default_na=False)
elif trans == 'auto':
path = Path("../release2/" + file + ".csv")
if path.exists():
return pd.read_csv(path, sep='\t', header=None, names=['id', 'content', 'label'], quoting=3,
keep_default_na=False)
else:
# generate files using ctmtocsv.py
pass
def txt_exist(trans, file):
file_path = "../release1/trans-" + trans + "/" + file + "/txt/"
path = Path(file_path)
if not path.exists() or os.listdir(file_path) == []:
os.popen("sh utils/trs2txt-utf8.sh trans-" +
trans + "/" + file, "r").read()
def main(argv):
if argv[1] == "manu":
train_corpus = csv_exist(argv[1], "train")
dev_corpus = csv_exist(argv[1], "dev")
test_corpus = csv_exist(argv[1], "test")
if argv[1] == "auto":
train_corpus = csv_exist(argv[1], "train")
dev_corpus = csv_exist(argv[1], "dev")
test_corpus = csv_exist(argv[1], "test")
print("Run 1")
basic = BasicClf(train_corpus)
print("Baseline:")
basic.evaluate(test_corpus, full=True)
perso = PersonalClf(train_corpus)
print("Perso:")
perso.evaluate(test_corpus, full=True)
print("Run 2")
basic = BasicClf(train_corpus, corpus_add=dev_corpus)
print("Baseline:")
basic.evaluate(test_corpus, full=True)
perso = PersonalClf(train_corpus, corpus_add=dev_corpus)
print("Perso:")
perso.evaluate(test_corpus, full=True)
if __name__ == "__main__":
main(sys.argv)
|
986,570 | d071a7bc85dba350e646659bb532442163d4f364 | import cv2
import numpy as np
def rotate(ImageName):
img = cv2.imread(ImageName, 1)
# 0 means Black and white image and 1 means coloured
shape = img.shape
rotate = np.zeros((shape[0], shape[1]), dtype=object)
for i in range(len(img)):
for j in range(len(img[i])):
x = len(img) - 1 - i
k = len(img[i]) - 1 - j
rotate[x][k] = img[i][j]
# print("[", i, "][", j, "] -------> [", x, "][", i, "]")
fi = []
for i in range(len(rotate)):
for j in range(len(rotate[i])):
fi.append(rotate[i][j])
final = np.array(fi).reshape(shape[0], shape[1], 3)
cv2.imshow("Image", final)
cv2.imwrite("ImageRotate180.jpg", (final))
cv2.waitKey(0)
|
986,571 | aa99a49fe2a4738c221bc6fe53511af0c0e933ba | #
# Sharded Library
# Authors: Tomas, Nick, Tianyu
#
# This library allows you to configure one computer to run a python program with
# the power of multiple computers.
#
# On each of the Workers (auxilary computers), run run_worker.py, please ensure
# the computer is configured with any libraries code that needs to run on it
# will require. The Nexus (main computer that runs the major file), will dispatch
# work to the Workers periodically.
#
# Each Worker will start a server and print the address and port of the
# server, along with a Key that is needed to access the server.
#
# Upon running an async computation (computation), the computation will be added to a
# Queue. When a Worker becomes available, the computation will be converted to a
# runnable, serialized, sent to the worker, and then we will wait for a returned
# from the worker.
#
# The nexus periodically pings workers for a heartbeat, should a worker fail to
# provide one for N cycles, the nexus will assume the worker has died and
# dispatch its work to another worker.
import json
from flask import Flask
import threading
import time
import requests
import Resources
import threading
import functools
import Resources
WORKER_SLEEP_TIME = 1 # in seconds
STATE_READY = 1
STATE_RUNNING = 2
STATE_COMPLETE = 3
STATE_DEAD = 4
STATE_STRINGS = {
STATE_READY: "State ready",
STATE_RUNNING: "State running",
STATE_COMPLETE: "State complete"
}
class Nexus(object):
"""
The main machine running computations, this object allows the user to
queue computations for workers.
"""
"""
Function:
Initialize a Nexus object
Args:
None
Returns:
None
"""
def __init__(self, dead_callback=None):
self._workers = []
self._queued_computations = []
self._dead_callback = dead_callback
"""
Function:
Registers a worker to this nexus
Args:
addr (string) : IP address of the worker
password (string) : password for the worker
Returns:
None
addr should be ip_address:port (i.e. 10.10.0.1:1234)
"""
def register_worker(self, addr, password, sleep_time=WORKER_SLEEP_TIME):
new_worker = RemoteWorker(self, addr, password, sleep_time=sleep_time)
self._workers.append(new_worker)
"""
Function:
Loads a Computation object into the queue
Args:
computation (instance) : a Computation object
Returns:
None
"""
def load_work(self, computation):
self._queued_computations.append(computation)
self.unload_work()
"""
Function:
Unloads queued Computation objects to remote worker(s)
Args:
None
Returns:
None
"""
def unload_work(self):
self.all_dead_check()
for worker in self._workers:
if worker._state == STATE_READY:
self.assign_work_to(worker)
"""
Function:
Checks if all the workers are dead
Args:
None
Returns:
None
"""
def all_dead_check(self):
for worker in self._workers:
if worker._state != STATE_DEAD:
return
print "[ALL WORKERS DEAD]"
"""
Function:
Assigns a Computation object to a specific worker. Does nothing
if no queued Computation objects.
Args:
remote_worker (instance) : remote worker to send computation object to
Returns:
None
"""
def assign_work_to(self, remote_worker):
if len(self._queued_computations) == 0:
return
# nexus sends Computation objects to workers
computation = self._queued_computations.pop(0)
remote_worker.assign_work(computation)
"""
Function:
Checks if there is still work being done by a worker.
Args:
None
Returns:
boolean
"""
def all_done(self):
# check if anything left
if len(self._queued_computations) > 0:
return False
# check if workers still going
for worker in self._workers:
if worker._state == STATE_RUNNING:
return False
return True
"""
Function:
Do nothing until all workers are done working.
Args:
None
Returns:
None
"""
def wait(self):
while not self.all_done():
time.sleep(WORKER_SLEEP_TIME)
"""
Function:
Decorator that turns the wrapped function into a promise, begins
begins execution and returns the promise.
Args:
f (function) : The function to wrap
Returns:
(promise) : The promise that completes when the worker returns
"""
def shard(self, f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
runnable = Resources.Runnable(f, args, kwargs)
computation = Resources.Computation(runnable)
self.load_work(computation)
return computation
return wrapped
class RemoteWorker(object):
"""The Nexus' interal representation of Workers."""
"""
Function:
Initialize a RemoteWorker object
Args:
nexus (instance) : nexus object this worker will "belong" to
addr (string) : web address of the worker
password (string) : password for the worker
Returns:
None
"""
def __init__(self, nexus, addr, password, sleep_time=WORKER_SLEEP_TIME):
self._state = STATE_READY
self._running = None
self._addr = addr
self._password = password
self._nexus = nexus
self._sleep_time = sleep_time
# Set up self.ping to run every few seconds in a different thread
self._thread = threading.Thread(target=self.ping)
self._thread.daemon = True
self._thread.start()
"""
Function:
Assign work to a remote worker. Currently serializes object using JSON
Args:
computation (instance) : Computation object
Returns:
int if an exception occurred, otherwise None
"""
def assign_work(self, computation):
assert(self._state == STATE_READY)
self._state = STATE_RUNNING
self._running = computation
print "func. assign_work log | About to assign runnable to worker"
try:
# send get request with data
print "func. assign_work log | computation._runnable.serialize(): ", computation._runnable.serialize()
res = requests.get(self._addr + "computation", params={"password": self._password},
data=computation._runnable.serialize())
except requests.exceptions.ConnectionError as e:
# Encountered issue connecting to worker, log error message and
# invalidate this worker
print e
self._state = STATE_DEAD
return 1
"""
Function:
Pings workers to see if they're alive - marks them as dead if they're not.
If a worker fails, add computation back to the Nexus' queue. If worker has
computed a result, gets the result and handles it appropriately.
Args:
None
Returns:
None
"""
def ping(self):
while True:
try:
# Hard coded to ping every 3 seconds
res = requests.get(self._addr + "heartbeat", params={"password": self._password}, timeout=0.5)
except requests.exceptions.ConnectionError as e:
# Encountered issue connecting to worker, log error message,
# kill heartbeat thread and invalidate this worker
print e
# NOTE: It is a design decision not to remove the nexus' worker
# list. It is up to the nexus to reap zombies
# appropriately, we do this in case the nexus would like
# to run any manual cleanup (e.g. spin up another AWS
# box).
self._state = STATE_DEAD
# Return computation back to nexus' queue
if self._running is not None:
self._nexus.load_work(self._running)
# have user handle death
self._nexus.all_dead_check()
if self._nexus._dead_callback is not None:
self._nexus._dead_callback()
# end the thread
return 1
if (res.text == "Invalid auth."):
raise Exception('Invalid password')
# return 1
# If worker is ready or running, heartbeat is okay
worker_response = json.loads(res.text)
if worker_response['status_code'] == STATE_READY or worker_response['status_code'] == STATE_RUNNING:
print "heartbeat alive"
self.state = worker_response['status_code']
elif worker_response['status_code'] == STATE_COMPLETE:
# Otherwise, the worker should be retuning a result from computatoin.
# Try to deserialize data
print "func. ping log | worker returned a result"
returned = Resources.Returned.unserialize(worker_response['result'])
self._running.done(returned)
self._running = None
self._state = STATE_READY
self._nexus.assign_work_to(self)
# continue so we can start work immediately
continue
else:
assert(False, "State code unrecognized")
# sleep before we query again
time.sleep(self._sleep_time)
|
986,572 | 04f0d4a252e43e482942d569493767aa0ac3843a | from collections import deque
def recursive(list, result):
if len(list) == 1 :return result
if len(list) == 2: return result +1
if list[2] == 0: return recursive(list[2:], result +1)
return recursive(list[1:], result +1)
def jumpingOnClouds(c):
return recursive(c, 0)
print(jumpingOnClouds([0, 0,1, 0, 0 ,0 , 0 ,1 , 0,0]))
print(jumpingOnClouds([0 ,0 ,1 ,0 ,0 ,1 ,0]))
# 0 ,0 ,1 ,0 ,0 ,1 ,0 0
#
# 0 ,1 ,0 ,0 ,1 ,0 1 |
986,573 | e917961af8fc85336f601a46c1a9baffbaf726b9 | '''
Created on Sep 26, 2015
@author: sumit
'''
import logging
from cookielib import logger
class GetStaticFile(object):
'''
classdocs
'''
def __init__(self, params):
logger = logging.getLogger(__name__)
'''
Constructor
'''
@staticmethod
def get_static_file_data(path):
css=None
fh=None
try:
fh=open(path,'r')
css=fh.read()
except IOError:
logger.error("File not Found")
else:
fh.close()
return css;
|
986,574 | 870906025ad463dc1d91b278fa904b1d6eac33c2 | """
Plot the energy spectra for the Hamiltonian of two coupled SSH chains
system defined in the article:
Li, C., Lin, S., Zhang, G., & Song, Z. (2017). Topological nodal
points in two coupled Su-Schrieffer-Heeger chains. Physical Review B,
96(12), 125418.
as a function of the hoppings v/t on a 2xN ladder with open boundary
condition. The script is able to reproduce FIG.3. from Li, et al.
(2017)
Author: Carla Borja Espinosa
Date: October 2019
Example command line in terminal to run the program:
$ python3 ZeroPoints.py 10 1 figure.png
"""
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
from numpy import linalg as la
from sympy.printing.str import StrPrinter
from sys import argv
from sympy.abc import v, w
class Hamiltonian(object):
"""Diagonalization of the system hamiltonian"""
def __init__(self):
"""Variables"""
self.N = 2*int(argv[1]) # Number of ladders
self.t = float(argv[2]) # Value of the interchain hopping
self.filePNG = argv[3] # Name of the file to store the plot
"""Functions"""
self.HamiltonianMatrix()
self.EigenvalsPlot()
def HamiltonianMatrix(self):
"""Construct the matrix representation of the system
hamiltonian up to N ladders"""
self.Inter = sp.Matrix([[0,self.t],[self.t,0]])
self.Intra1 = sp.Matrix([[0,v],[w,0]])
self.Intra2 = sp.Matrix([[0,w],[v,0]])
H = sp.Matrix([])
for i in range(1, self.N+1):
fila = sp.Matrix([])
for j in range(1, self.N+1):
if j==i:
fila = fila.row_join(self.Inter)
elif j==i+1:
fila = fila.row_join(self.Intra1)
elif j==i-1:
fila = fila.row_join(self.Intra2)
else:
fila = fila.row_join(sp.Matrix([[0,0],[0,0]]))
H = H.col_join(fila)
H.simplify()
#printer = StrPrinter()
#print(H.table(printer,align='center'))
self.H = H
def EigenvalsPlot(self):
"""Plot the eigenvalues as a function of v/t for different
relations of the hopping parameters
(uncomment the desired case)"""
Hfv = sp.lambdify(('v','w'), self.H)
v_vals = np.arange(-1.5, 1.5+0.03 ,0.03)
w_vals = self.t + v_vals # case a
#w_vals = v_vals # case b
#w_vals = 2*self.t - v_vals # case c
#w_vals = -v_vals # case d
size_v = np.size(v_vals)
size_aut = self.H.shape[1]
graph = np.empty([size_v,size_aut])
for i in range(0,size_v):
energies,vectors = la.eig(Hfv(v_vals[i],w_vals[i]))
energies = np.sort(np.real(energies))
graph[i] = energies
graph = np.insert(graph, [0], v_vals.reshape(-1,1), axis = 1)
graph = np.matrix(graph)
#with open(self.filetxt, "w+") as f:
# for line in graph:
# np.savetxt(f,line)
for i in range(0, size_aut):
plt.plot(v_vals,graph[:,i+1],'g')
plt.xlim(-1.5,0.5)
plt.ylim(-3,3)
plt.savefig(self.filePNG)
#plt.savefig(self.filePNG, format='eps', dpi=1200)
#plt.show()
Hamiltonian()
|
986,575 | 3d4c67ca7e70470c590db1e467607f5f0b74852e | add_two_numbers = 2 + 2
print(add_two_numbers) |
986,576 | a1b402311f6b89be2ab44ac61ee284044135aed7 | import argparse
parser = argparse.ArgumentParser(description="""Preprocess data, creating the subtokens.txt file from
subtokens, train_nodes from python100k_train.json, or test_nodes from python50k_eval.json
""")
parser.add_argument('--generate-subtokens', action="store_true", help="Generate subtokens file from infile-train")
parser.add_argument('--generate-node-data', action="store_true", help="Generate preprocessed data")
parser.add_argument('--infile-train', help="The input file for training such as python100k_train.json")
parser.add_argument('--infile-test', help="The input file for testing such as python50k_eval.json (not "
"needed for generating subtokens.txt)")
parser.add_argument('--subtokens-file', '-s', help="The file for the subtoken vocabulary")
parser.add_argument('--vocab-size', '-v', help="The number of subtokens to keep for the vocabulary size", type=int, default=50000)
parser.add_argument('--nodes-out', '-nout', help="The output file for the pickled nodes. Will be suffixed with _train,"
"_val, and _test")
parser.add_argument('--chunk-size', '-c', help="The size of the chunks for parsing the nodes", type=int, default=5000)
parser.add_argument('--max-fn-size', '-max', help="The maximum size (in number of nodes) to keep. Functions/Classes "
"with more nodes will be discarded", type=int, default=1000)
parser.add_argument('--train-val-split', type=float, help="The fraction of infile-train that should go into train"
" rather than val", default=0.8)
if __name__ == "__main__":
args = parser.parse_args()
if args.generate_subtokens:
from load_python_trees.tokenize_identifiers import get_subtoken_vocab, save_ind2token
print("Getting subtokens from dataset...")
ind2token = get_subtoken_vocab(args.infile, vocab_size=args.vocab_size, file_num_lines=args.num_lines)
save_ind2token(args.subtokens_file, ind2token)
if args.generate_node_data:
from load_python_trees.node import preprocess
if args.infile_train is not None:
print("Saving pickled nodes... (train)")
num_train, num_val = preprocess(args.infile_train, args.nodes_out + '.train.pkl', args.subtokens_file, 100000,
args.max_fn_size, args.chunk_size, validation=(args.nodes_out + '.val.pkl', args.train_val_split))
print("Num train examples", num_train)
print("Num val examples", num_val)
if args.infile_test is not None:
print("Saving pickled nodes... (test)")
num_test, _ = preprocess(args.infile_test, args.nodes_out + '.test.pkl', args.subtokens_file, 50000,
args.max_fn_size, args.chunk_size)
assert _ == 0
print("Num test examples", num_test)
|
986,577 | a66860390243e59db957d1f9bdb78fe226314762 | from scrapy.cmdline import execute
# execute("scrapy crawl cyb_link".split(" "))
# execute("scrapy crawl sh_link".split(" "))
# execute("scrapy crawl sz_link".split(" "))
# execute("scrapy crawl company_info".split(" "))
# execute("scrapy crawl info_lrb".split(" "))
# execute("scrapy crawl info_zcfzb".split(" "))
execute("scrapy crawl info_xjllb".split(" ")) |
986,578 | ba64020cfbb8057edfd63432a65463631d63820c | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 15 18:49:08 2019
@author: Tara
"""
p = [-4, 6, 2, 0]
#my polynomial is 2x^2 + 6x - 4
j = []
h = []
def polynomial(x):
for ii in range(len(p)):
k = x**i
j.append(p[ii]*l)
return sum(j)
print(sum(p(-4)))
def p_derivative(n):
for ii in range(len(p)):
n = p[ii]*ii
h.append(n)
return h
for l in range(len(h)):
f = x**i
h.append(m[l]*f)
return h[1:]
print(p_derivative(-4)) |
986,579 | 5468b67652e0d906310b1a80c62400283c4652fc | """
We want to make a row of bricks that is goal inches long.
We have a number of small bricks (1 inch each) and big bricks (5 inches each).
Return True if it is possible to make the goal by choosing from the given bricks.
This is a little harder than it looks and can be done without any loops.
make_bricks(3, 1, 8) → True
make_bricks(3, 1, 9) → False
make_bricks(3, 2, 10) → True
"""
def make_bricks(small, big, goal):
while(goal >= 5) and (big > 0):
goal = goal - 5
big = big - 1
while(goal > 0) and (small > 0):
goal = goal - 1
small = small - 1
if (goal == 0):
return True
else:
return False
|
986,580 | 7074ebd54fd41881f5876af1388fc750ae94a6c7 | from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title=models.CharField(verbose_name="Ad",max_length=123,default="Başlık")
image1=models.ImageField(verbose_name="Profil",blank=True,null=True)
who=models.TextField(max_length=500,verbose_name="Hakkımda",blank=True,default="Kim")
what_to_do=models.TextField(max_length=500,verbose_name="Ne Yaparım ?",blank=True,default="Ne yapar")
interested_1=models.TextField(max_length=500,verbose_name="İlgi Alanlarım 1",blank=True,default="İlgi Alanı")
img1=models.ImageField(verbose_name="İmg 1",blank=True)
interested_2=models.TextField(max_length=500,verbose_name="İlgi Alanlarım 2",blank=True,default="İlgi Alanı")
img2 = models.ImageField(verbose_name="İmg 2",blank=True)
interested_3=models.TextField(max_length=500,verbose_name="İlgi Alanlarım 3",blank=True,default="İlgi Alanı")
img3 = models.ImageField(verbose_name="İmg 3",blank=True)
def __str__(self):
return "{} - {} ".format(self.title,self.id)
|
986,581 | de5ec303648ca6044478ee2ac4d9e36d03365ab0 | """
This module contains template tags for instance for a unified pagination
look and feel.
"""
from django.conf import settings
from django.utils.dateformat import format
from django import template
register = template.Library()
@register.filter('datetime')
def datetime(value):
return format(value, settings.DATETIME_FORMAT)
|
986,582 | 9403376a20ce6e58aa165c9abce3b07fa45c5945 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas_datareader import data, wb
if __name__ == '__main__':
# collect time series for S&P 500
sp500 = data.DataReader('^GSPC', data_source='yahoo', start='1/1/2000')
# estimate two-month and one-year trends
sp500['42d'] = np.round(sp500['Close'].rolling(window=42).mean(), 2)
sp500['252d'] = np.round(sp500['Close'].rolling(window=252).mean(), 2)
# trading singals
sp500['42-252'] = sp500['42d'] - sp500['252d']
SD = 50 # signal threshold
sp500['Regime'] = np.where(sp500['42-252'] > SD, 1, 0)
sp500['Regime'] = np.where(sp500['42-252'] < -SD, -1, sp500['Regime'])
sp500['Market'] = np.log(sp500['Close'] / sp500['Close'].shift(1))
sp500['Strategy'] = sp500['Regime'].shift(1) * sp500['Market']
# plot trends over close quotes; strategy vs. market
sp500[['Close', '42d', '252d']].plot(grid=True, figsize=(8,6))
sp500[['Market', 'Strategy']].cumsum().apply(np.exp).plot(grid=True, figsize=(8,6))
plt.show(block=True)
|
986,583 | 622c58529bf02615e838445cce8cfe79caf2c791 | # llia.synths.orgn.orgn_pp
from __future__ import print_function
import llia.util.lmath as math
from llia.performance_edit import performance_pp
def amp_to_db(amp):
return int(math.amp_to_db(amp))
def pp_rdrum(program, slot=127):
def db (key):
amp = program[key]
rs = int(amp_to_db(program[key]))
#print("DEBUG key '%s' amp = %s db = %s" % (key, amp, rs))
return rs
def fval(key):
return float(program[key])
pad = ' '*5
pad2 = pad + ' '* 3
acc = 'rdrum(%3d, "%s", amp=%d,\n' % (slot, program.name, db('amp'))
acc += '%sa = {"ratio" : %6.4f,\n' % (pad2, fval("aRatio"))
acc += '%s "attack" : %5.3f,\n' % (pad2, fval("aAttack"))
acc += '%s "decay" : %5.3f,\n' % (pad2, fval("aDecay"))
acc += '%s "bend" : %-6.3f,\n' % (pad2, fval("aBend"))
acc += '%s "tone" : %5.3f,\n' % (pad2, fval("aTone"))
acc += '%s "velocity" : %5.3f,\n' % (pad2, fval("aVelocity"))
acc += '%s "amp" : %d},\n' % (pad2, db("aAmp"))
acc += '%sb = {"ratio" : %6.4f,\n' % (pad2, fval("bRatio"))
acc += '%s "attack" : %5.3f,\n' % (pad2, fval("bAttack"))
acc += '%s "decay" : %5.3f,\n' % (pad2, fval("bDecay"))
acc += '%s "bend" : %-6.3f,\n' % (pad2, fval("bBend"))
acc += '%s "tune" : %6.4f,\n' % (pad2, fval("bTune"))
acc += '%s "velocity" : %5.3f,\n' % (pad2, fval("bVelocity"))
acc += '%s "amp" : %d},\n' % (pad2, db("bAmp"))
acc += '%snoise = {"ratio" : %6.4f,\n' % (pad2, fval("noiseRatio"))
acc += '%s "attack" : %5.3f,\n' % (pad2, fval("noiseAttack"))
acc += '%s "decay" : %5.3f,\n' % (pad2, fval("noiseDecay"))
acc += '%s "bend" : %-6.3f,\n' % (pad2, fval("noiseBend"))
acc += '%s "res" : %6.4f,\n' % (pad2, fval("noiseRes"))
acc += '%s "velocity" : %5.3f,\n' % (pad2, fval("noiseVelocity"))
acc += '%s "amp" : %d})\n' % (pad2, db("noiseAmp"))
return acc
|
986,584 | 82b3c000ed38b079b554c0927cd4c2e86e9f2484 | from collections import namedtuple
from typing import List
class Stack:
def __init__(self, id: int, timestamp: int, clazz: str, frames: List[str]):
self.id = id
self.ts = timestamp
self.clazz = clazz
self.frames = frames
def eq_content(self, stack: 'Stack'):
return self.clazz == stack.clazz and self.frames == stack.frames
|
986,585 | 1dbf3730eb617813320194d54b2c429e615c742f | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy import Field
class InformationItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
table_name='weibo_users_information'
screen_name = Field()
id = Field()
cover_image_phone=Field()
close_blue_v=Field()
desc1=Field()
desc2=Field()
description=Field()
follow_count=Field()
followers_count=Field()
gender=Field()
profile_url=Field()
verified_reason=Field()
spider_time=Field()
url=Field()
verified=Field()
class TweetsItem(scrapy.Item):
table_name='weibo_tweets'
mblog_id = Field()
screen_name=Field()
id=Field()
created_at = Field()
text = Field()
attitudes_count = Field()
comments_count=Field()
source=Field()
isLongText=Field()
is_paid=Field()
spider_time=Field()
is_top=Field()
retweeted_status=Field()
ve=Field()
class TestItem(scrapy.Item):
table_name='test_id'
id=Field()
|
986,586 | 95c033185c3884dce7d5ab1f94afa4bb6f171b94 | from .api import MediaCloud
from .storage import *
__version__ = '2.53.0'
|
986,587 | a049ff67818b26540379811581401cdf50b0efe6 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
"name": "Odoo Logs",
"version": "0.0.1",
"category": "Tools",
"installable": True,
"application": True,
"depends": ["ihub"],
"data": [
],
}
|
986,588 | d096dffe20a6b1ebc702b0a02d0a388f2bb1a52f | from rlsa import rlsa
import cv2
import pandas as pd
import copy
def get_block_stats(stats, centroids):
"""
Get block stats in a pandas DataFrams
Parameters:
stats ():
centroids ():
Returns:
block_stats ():
"""
stats_columns = ["left", "top", "width", "height", "area"]
block_stats = pd.DataFrame(stats, columns=stats_columns)
block_stats["centroid_x"], block_stats["centroid_y"] = centroids[:,
0], centroids[:, 1]
# Ignore the label 0 since it is the background
block_stats.drop(0, inplace=True)
return block_stats
def getCropped(process_dict):
image = process_dict['page_rlsa']
rlsa_vertical=rlsa(cv2.bitwise_not(image),False,True,process_dict["image_height"]/80)
cv2.imwrite(f"rlsa_vertical/{process_dict['count']}.png",rlsa_vertical)
_, _, stats, centroids = cv2.connectedComponentsWithStats(cv2.bitwise_not(rlsa_vertical))
block_stats = get_block_stats(stats, centroids)
block_stats["right"] = block_stats.left + block_stats.width
block_stats["bottom"] = block_stats.top + block_stats.height
box=copy.deepcopy(rlsa_vertical)
max_area=0
cropped_top,cropped_bottom,cropped_left,cropped_right = 0,0,0,0
for i in range(len(block_stats)):
top = block_stats["top"].iloc[i]
bottom=block_stats["top"].iloc[i]+block_stats["height"].iloc[i]
left=block_stats["left"].iloc[i]
right=block_stats["left"].iloc[i]+block_stats["width"].iloc[i]
if(int(block_stats["height"].iloc[i])*int(block_stats["width"].iloc[i]) > max_area and\
block_stats["width"].iloc[i] < process_dict['image_width']-10):
cropped_top=top
cropped_bottom=bottom
cropped_left=left
cropped_right=right
max_area=int(block_stats["height"].iloc[i])*int(block_stats["width"].iloc[i])
# box=cv2.rectangle(box,(left,top,right,bottom),(0, 0, 255),thickness=2)
box=cv2.rectangle(box,(cropped_left,cropped_top),(cropped_right,cropped_bottom),(0, 0, 0),thickness=4)
cv2.imwrite(f"rlsa_rect/{process_dict['count']}.png",box)
return process_dict["binary"][cropped_top:cropped_bottom,cropped_left:cropped_right] |
986,589 | 76130618b1f826d77103b3521c9c40a3f70ea811 | import os
from os.path import join
from sets import Set
import tempfile
from kjbuckets import kjGraph
from useless.base import Error
from useless.base.util import ujoin, RefDict, strfile, filecopy
from useless.sqlgen.clause import one_many, Eq, In
from useless.db.midlevel import Environment
from paella.base.objects import TextFileManager
from base import TraitRelation
from parent import TraitParent
from paella import deprecated
class TraitPackage(TraitRelation):
def __init__(self, conn, suite):
table = ujoin(suite, 'trait', 'package')
TraitRelation.__init__(self, conn, suite, table, name='TraitPackage')
self.cmd.set_fields(['package', 'action'])
self.traitparent = TraitParent(conn, suite)
def packages(self, traits=None):
if traits is None:
traits = [self.current_trait]
#self.cmd.set_clause([('trait', trait) for trait in traits], join='or')
clause = In('trait', traits)
rows = self.cmd.select(clause=clause, order='package')
self.reset_clause()
return rows
def all_packages(self, traits, traitparent=None):
if not traitparent:
traitparent = self.traitparent
return list(self.packages(traitparent.get_traitset(traits)))
def set_action(self, action, packages, trait=None):
if trait is None:
trait = self.current_trait
clause = Eq('trait', trait) & In('package', packages)
if action == 'drop':
self.cmd.delete(clause=clause)
elif action in ['remove', 'install', 'purge']:
self.cmd.set_data({'action' : action})
self.cmd.update(clause=clause)
else:
raise Error, 'bad action in TraitPackage -%s-' % action
def insert_package(self, package, action='install'):
idata = {'trait' : self.current_trait,
'action' : action,
'package' : package}
self.cmd.insert(data=idata)
def delete_package(self, package, action):
clause = Eq('package', package) & Eq('trait', self.current_trait)
if action is not None:
clause = clause & Eq('action', action)
self.cmd.delete(clause=clause)
def insert_packages(self, packages):
diff = self.diff('package', packages)
for package in packages:
if package in diff:
self.insert_package(package)
def set_trait(self, trait):
TraitRelation.set_trait(self, trait)
self.traitparent.set_trait(trait)
if __name__ == '__main__':
#f = file('tmp/trait.xml')
#tx = TraitXml(f)
import sys
|
986,590 | 1832fc677724dd34120d85b9a296731ed67c65c3 | '''
environments
tundra, space, rainforest
desert, grassland, jungle, ocean, rainforest, space, tundra
'''
INSTANT_DEATH = -100
DEATH = -50
POOR = -20
NEUTRAL = 0
FAIR = 20
EXCEPTIONAL = 50
ENVIRONMENTS = ['desert', 'grassland', 'jungle', 'ocean', 'forest', 'tundra', 'arctic']
SKIN = {'fur': {'arctic': EXCEPTIONAL, 'desert': NEUTRAL, 'grassland': NEUTRAL, 'jungle': NEUTRAL, 'ocean': NEUTRAL, 'forest': NEUTRAL,'tundra':EXCEPTIONAL},
'feathers': {'arctic': FAIR,'desert':NEUTRAL, 'grassland': NEUTRAL, 'jungle': NEUTRAL , 'ocean': NEUTRAL, 'forest': NEUTRAL,'tundra': NEUTRAL},
'dry skin': {'arctic': DEATH,'desert': POOR, 'grassland':FAIR, 'jungle':POOR, 'ocean':POOR, 'forest':POOR,'tundra':DEATH},
'amphibious': {'arctic': DEATH,'desert':DEATH, 'grassland':DEATH, 'jungle': EXCEPTIONAL, 'ocean': FAIR, 'forest': POOR,'tundra':DEATH},
'dry scales': {'arctic':DEATH,'desert': EXCEPTIONAL, 'grassland':FAIR, 'jungle':FAIR, 'ocean': DEATH, 'forest': POOR,'tundra':DEATH},
'wet scales': {'arctic':DEATH,'desert': DEATH, 'grassland':DEATH, 'jungle':FAIR, 'ocean': EXCEPTIONAL, 'forest':POOR,'tundra': DEATH}
}
DIET = {'carnivore':{'arctic':FAIR,'desert':NEUTRAL, 'grassland':NEUTRAL, 'jungle':FAIR, 'ocean':NEUTRAL, 'forest':NEUTRAL,'tundra':NEUTRAL},
'herbivore':{'arctic':POOR,'desert':NEUTRAL, 'grassland':FAIR, 'jungle':FAIR, 'ocean':NEUTRAL, 'forest':FAIR,'tundra':NEUTRAL},
'omnivore':{'arctic':FAIR,'desert': NEUTRAL, 'grassland':FAIR, 'jungle':FAIR, 'ocean':NEUTRAL, 'forest':EXCEPTIONAL,'tundra':NEUTRAL}
}
MOVE = {'two legs': {'arctic': POOR,'desert': NEUTRAL, 'grassland': EXCEPTIONAL, 'jungle': POOR, 'ocean': DEATH, 'forest': FAIR, 'tundra': NEUTRAL},
'four legs':{'arctic': NEUTRAL,'desert': NEUTRAL, 'grassland': EXCEPTIONAL, 'jungle': NEUTRAL, 'ocean': POOR, 'forest': EXCEPTIONAL,'tundra': FAIR},
'climbing':{'arctic': NEUTRAL,'desert': POOR, 'grassland': POOR, 'jungle': EXCEPTIONAL, 'ocean': DEATH, 'forest': FAIR, 'tundra': DEATH},
'wings':{'arctic': NEUTRAL,'desert': FAIR, 'grassland': FAIR, 'jungle': EXCEPTIONAL, 'ocean': POOR, 'forest': EXCEPTIONAL,'tundra': NEUTRAL},
'flippers':{'arctic': FAIR,'desert': DEATH , 'grassland': DEATH, 'jungle': POOR, 'ocean': EXCEPTIONAL, 'forest': DEATH,'tundra':DEATH}
}
BREATH = {'lungs':{'arctic':NEUTRAL,'desert':NEUTRAL , 'grassland':NEUTRAL, 'jungle':NEUTRAL, 'ocean': DEATH, 'forest':NEUTRAL,'tundra':NEUTRAL},
'external gills':{'arctic': DEATH,'desert': DEATH, 'grassland':DEATH, 'jungle':EXCEPTIONAL, 'ocean':FAIR, 'forest':DEATH,'tundra':DEATH}, #amphibian
'internal gills':{'arctic':DEATH,'desert':DEATH, 'grassland':DEATH, 'jungle':DEATH, 'ocean':EXCEPTIONAL, 'forest':DEATH,'tundra':DEATH}, #fish/aquatic
'tracheae': {'arctic': NEUTRAL,'desert':NEUTRAL, 'grassland':NEUTRAL, 'jungle':NEUTRAL, 'ocean': DEATH, 'forest':NEUTRAL,'tundra':NEUTRAL} #bugs
}
COLOR = {'black':{'arctic': POOR,'desert':NEUTRAL,'grassland':NEUTRAL,'jungle':NEUTRAL,'ocean':NEUTRAL,'forest':NEUTRAL,'tundra':POOR},
'brown': {'arctic':POOR,'desert':FAIR,'grassland':FAIR,'jungle':FAIR,'ocean':NEUTRAL,'forest':FAIR,'tundra':FAIR},
'white': {'arctic': EXCEPTIONAL,'desert':POOR,'grassland':POOR,'jungle':POOR,'ocean':POOR,'forest':POOR,'tundra':EXCEPTIONAL},
'colorful': {'arctic':DEATH,'desert':POOR,'grassland':POOR,'jungle':NEUTRAL,'ocean':NEUTRAL,'forest':POOR,'tundra':DEATH},
'stripes': {'arctic':POOR,'desert':FAIR,'grassland':NEUTRAL,'jungle':FAIR,'ocean':FAIR,'forest':NEUTRAL,'tundra':NEUTRAL},
}
|
986,591 | 0b4c92cfd92691dd2abbf47ca394fa84de19b2cb | from sqlalchemy import inspect
from jet_bridge_base.serializers.model_serializer import ModelSerializer
def get_model_serializer(Model):
mapper = inspect(Model)
class CustomModelSerializer(ModelSerializer):
class Meta:
model = Model
model_fields = list(map(lambda x: x.key, mapper.columns))
return CustomModelSerializer
|
986,592 | 96ea1c2014f4b0c2fb0e78c6721bc5f7564e3fd7 | #//
#//----------------------------------------------------------------------
#// Copyright 2010-2011 Synopsys, Inc.
#// Copyright 2010 Mentor Graphics Corporation
#// Copyright 2010-2011 Cadence Design Systems, Inc.
#// Copyright 2019-2020 Tuomas Poikela (tpoikela)
#// All Rights Reserved Worldwide
#//
#// 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, software distributed under the License is
#// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
#// CONDITIONS OF ANY KIND, either express or implied. See
#// the License for the specific language governing
#// permissions and limitations under the License.
#//----------------------------------------------------------------------
#
from uvm.comps.uvm_test import UVMTest
from uvm.macros import *
from blk_seqlib import *
from uvm.base.sv import sv
from uvm.base.uvm_root import uvm_top
from blk_env import blk_env
from blk_seqlib import *
class blk_R_test(UVMTest):
def __init__(self, name="blk_R_test", parent=None):
super().__init__(name, parent)
self.env = None # blk_env
def build_phase(self, phase):
if self.env is None:
arr = []
if (sv.cast(arr, uvm_top.find("env$"), blk_env)):
self.env = arr[0]
else:
uvm_fatal("NO_ENV_ERR", "test_top unable to find 'env'")
async def run_phase(self, phase):
phase.raise_objection(self)
rst_seq = dut_reset_seq.type_id.create("rst_seq", self)
rst_seq.vif = self.env.apb.vif
await rst_seq.start(None)
self.env.model.reset()
seq = blk_R_test_seq.type_id.create("blk_R_test_seq",self)
seq.model = self.env.model
await seq.start(None)
phase.drop_objection(self)
uvm_component_utils(blk_R_test)
|
986,593 | 484f4ac67c624021605f23807470cf4e00cd30e9 | from tornado import gen, web, tcpserver, iostream
import struct, socket
import logging, ujson
from bridge import message_factory
logger = logging.getLogger(__name__)
# connection from BOT to SCRAPER
class ScraperTCPConnection(object):
def __init__(self, stream, server):
self.stream = stream
self.server = server
self.stream.socket.setsockopt(
socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.stream.socket.setsockopt(
socket.IPPROTO_TCP, socket.SO_KEEPALIVE, 1)
self.stream.set_close_callback(self.on_disconnect)
@gen.coroutine
def on_disconnect(self):
logger.debug('scraper tcp client disconnected')
@gen.coroutine
def on_connect(self):
yield self.dispatch_client()
@gen.coroutine
def dispatch_client(self):
try:
while True:
data = yield self.stream.read_bytes(4)
logger.debug('RECEIVING DATA: {} bytes'.format(len(data)))
msg_len = struct.unpack('I', data)[0]
data = yield self.stream.read_bytes(msg_len)
logger.debug('RECEIVING DATA: {} bytes'.format(len(data)))
yield self.server.handle_request(self, data)
except iostream.StreamClosedError,e:
logger.error(e)
class ScraperTCPServer(tcpserver.TCPServer):
def __init__(self,*args, **kwargs):
super(ScraperTCPServer, self).__init__(*args, **kwargs)
self.scrapers = {}
self.msg_factory = message_factory.MessageFactory()
def add_scraper(self, scraper):
self.scrapers[scraper.name] = scraper
def remove_scraper(self, name):
try:
del self.scrapers[name]
except KeyError, e:
logger.error(e)
def get_scraper(self, name):
try:
return self.scrapers[name]
except KeyError, e:
raise
# on connection with bot, hand off to connection.on_connect()
@gen.coroutine
def handle_stream(self, stream, address):
connection = ScraperTCPConnection(stream, self)
yield connection.on_connect()
@gen.coroutine
def handle_request(self, conn, data):
input_msg = self.msg_factory.decode_input(data)
bot_hid = input_msg.bot_hid
scraper_name = input_msg.scraper_name
source_name = input_msg.source_name
fetch_kwargs = ujson.loads(input_msg.fetch_kwargs)
query_kwargs = ujson.loads(input_msg.query_kwargs)
output_msg = 'bot cannot understand request'
try:
scraper = self.scrapers[scraper_name]
source = scraper.get_source(source_name)
response = yield source.fetch(**fetch_kwargs)
obj = source.parse(response.body)
out = source.query(obj, **query_kwargs)
# add metadata
out = {
'content': out,
'scraper': scraper_name,
'source': source_name
}
# dumps to string output_msg
output_msg = ujson.dumps(out)
except AttributeError, e:
output_msg = 'unable to fetch data, please try again. Error {}'.format(e)
except Exception, e:
output_msg = str(e)
output_msg = self.msg_factory.encode_output(bot_hid, output_msg)
yield conn.stream.write(output_msg)
|
986,594 | e376735aa4c71287878058e0a0a3b6832b2b448a | import pylab
import sklearn
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
from sklearn.cross_validation import cross_val_score
import numpy as np
from sklearn.cross_validation import StratifiedKFold
from random import shuffle
import gzip
import sys
# ### Ingest data:
# #### Round 1 data
#data = pd.read_csv(gzip.open('thrombin.gz'),',',header=None)
data = pd.read_pickle(sys.argv[1])
X = data[range(1,len(data.columns))]
Y = data['I']
mix_rates = np.array([2./3, 1./6, 1./6])
df = RandomForestClassifier(n_estimators=12, criterion='gini',
bootstrap=True, oob_score=False, n_jobs=4,
random_state=0, verbose=0, class_weight='auto')
def entropy(p):
return sum([-p_val*np.log2(p_val+1e-10) for p_val in p])
def max_prob(p):
return p[0]
def select_preds(all_preds, mix_rates, n_preds):
n_picks = [round(p*n_preds) for p in mix_rates]
if n_preds - sum(n_picks) != 0:
n_picks[np.argmax(mix_rates)] += n_preds - sum(n_picks)
preds = set()
for i,n_curr in enumerate(n_picks):
len_init = len(preds); j = 0;
while len(preds) < (len_init + n_curr):
preds.add(all_preds[i][j]); j+=1
return preds
def test_active_learner(argtuple):
X,Y,strategy_list,mix_rates,batches = argtuple
if mix_rates is None:
mix_rates = np.array([1./len(strategy_list) for n in range(len(strategy_list))])
elif sum(mix_rates) != 1:
mix_rates = np.array(mix_rates)/float(sum(mix_rates))
skf = StratifiedKFold(Y,n_folds=batches,shuffle=True,random_state=0)
for test_inds, train_inds in skf: break
train_inds = set(train_inds); test_inds = set(test_inds);
curr_hits = [sum(Y.loc[train_inds]=='A')]; mcc = [0]; auc = [0]
iter_cnt = 0; strategy_ind = 0;
while len(test_inds) > 0:
train_X = X.loc[train_inds]; train_Y = Y.loc[train_inds];
test_X = X.loc[test_inds] ; test_Y = Y.loc[test_inds];
print 'Iter:',iter_cnt, '#TrainSet:', len(train_inds), '#TestSet:', len(test_inds), '#Hits:', curr_hits[-1]
print train_X.isnull().sum().sum()
df.fit(train_X.astype(int).values, train_Y)
fpr, tpr, thresholds = sklearn.metrics.roc_curve(Y, df.predict_proba(X)[:,0], pos_label='A')
auc.append(sklearn.metrics.auc(fpr,tpr))
mcc.append(sklearn.metrics.matthews_corrcoef(df.predict(test_X),test_Y))
n_preds = min(len(test_Y), int(round(len(Y)*(1./batches))))
all_preds = []
probs = df.predict_proba(test_X)
for strategy in strategy_list:
scores = [strategy(p) for p in probs]
sort_idx = np.argsort(scores)
data_idx = test_X.index[sort_idx]
all_preds.append(data_idx[-n_preds:])
preds = select_preds(all_preds, mix_rates, n_preds)
train_inds = train_inds.union(set(preds))
test_inds.difference_update(preds)
curr_hits.append(sum(Y.loc[train_inds]=='A'))
iter_cnt+=1
return curr_hits, mcc, auc
def get_baseline(Y,batches=20):
num_hits = sum(Y=='A')
hits_optimal = np.array([1]*num_hits + [0]*(len(Y)-num_hits))
hits_random = hits_optimal.copy()
shuffle(hits_random)
curr_hits_optimal = []; curr_hits_random = [];
skf = sklearn.cross_validation.KFold(len(Y),shuffle=False,n_folds=batches)
for tr,ts in skf:
curr_hits_optimal.append(sum(hits_optimal[ts]))
curr_hits_random.append(sum(hits_random[ts]))
curr_hits_optimal = np.cumsum(curr_hits_optimal)
curr_hits_random = np.cumsum(curr_hits_random)
return curr_hits_optimal, curr_hits_random, num_hits
curr_hits_optimal, curr_hits_random, num_hits = get_baseline(Y)
curr_hits_entropy, mcc_entropy, auc_entropy = test_active_learner((X,Y,[entropy],[1],20))
curr_hits_maxprob, mcc_maxprob, auc_maxprob = test_active_learner((X,Y,[max_prob],[1],20))
curr_hits_hybrid, mcc_hybrid, auc_hybrid = test_active_learner((X,Y,[entropy,max_prob],[0.5,0.5],20))
pylab.figure(figsize=(11,8))
pylab.plot(np.array(range(len(curr_hits_entropy)))*100./float(len(curr_hits_entropy)-1),
np.array(curr_hits_entropy)/float(num_hits)*100, 'ko-',label='Max Entropy')
pylab.plot(np.array(range(len(curr_hits_maxprob)))*100./float(len(curr_hits_maxprob)-1),
np.array(curr_hits_maxprob)/float(num_hits)*100, 'bo-',label='Max Probability')
pylab.plot(np.array(range(len(curr_hits_optimal)))*100./float(len(curr_hits_optimal)-1),
np.array(curr_hits_optimal)/float(num_hits)*100, 'g--',label='Optimal')
pylab.plot(np.array(range(len(curr_hits_random)))*100./float(len(curr_hits_random)-1),
np.array(curr_hits_random) /float(num_hits)*100, 'y--',label='Random')
pylab.plot(np.array(range(len(curr_hits_hybrid)))*100./float(len(curr_hits_hybrid)-1),
np.array(curr_hits_hybrid) /float(num_hits)*100, 'r--',label='Hybrid')
pylab.xlabel('Tested Chemical Space (%)')
pylab.ylabel('Discovered Hits (%)')
pylab.legend(loc=0)
pylab.rc('font', size=20)
pylab.savefig('active_hits.png',dpi=100)
|
986,595 | 2d7d7e78ebbdd09f0867dcba881bc5d7f38952fc | import unittest
from unittest.mock import patch
from app.utils.handlers.notification_handler import NotificationHandler
class TestNotificationHandler(unittest.TestCase):
def test_init(self):
notification_handler = NotificationHandler('title', 'subtitle', 'description')
self.assertEqual(notification_handler.title, 'title')
self.assertEqual(notification_handler.subtitle, 'subtitle')
self.assertEqual(notification_handler.description, 'description')
@patch('app.utils.handlers.notification_handler.platform')
def test_send_push_notification_unknown_platform(self, patched_platform):
patched_platform.system.return_value = 'Fake'
self.assertRaises(NotImplementedError)
@patch('app.utils.handlers.notification_handler.platform')
@patch('app.utils.handlers.notification_handler.NotificationHandler._send_notification_mac_os')
def test_send_push_notification_max_os_was_called(self, patched_send_notification_mac_os, patched_platform):
patched_platform.system.return_value = 'Darwin'
patched_send_notification_mac_os.asserd_called()
@patch('app.utils.handlers.notification_handler.platform')
def test_send_push_notification_linux_was_called(self, patched_platform):
patched_platform.system.return_value = 'Linux'
self.assertRaises(NotImplementedError)
@patch('app.utils.handlers.notification_handler.platform')
def test_send_push_notification_max_windows_called(self, patched_platform):
patched_platform.system.return_value = 'Windows'
self.assertRaises(NotImplementedError)
if __name__ == '__main__':
unittest.main()
|
986,596 | 2d4575135be019ca30d7702e234bf95c0d3a1f1f | """empty message
Revision ID: 540209e25f1d
Revises: f69a6dfd554a
Create Date: 2021-09-27 15:59:32.223483
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '540209e25f1d'
down_revision = 'f69a6dfd554a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('favs', 'timestamp')
op.add_column('recipes', sa.Column('timestamp', sa.DateTime(), nullable=False))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('recipes', 'timestamp')
op.add_column('favs', sa.Column('timestamp', postgresql.TIMESTAMP(), autoincrement=False, nullable=False))
# ### end Alembic commands ###
|
986,597 | cc9ec17de3b552cf5865a92c3fcdf5d8ab62e875 | import scrapy
from scrapy import Selector
from scrapy.shell import inspect_response
from scrapy_splash import SplashRequest
#This function can extract all the singaopre hotel url on the current page, press the next button, and continue until end of hotel
MAIN_URL = 'https://www.tripadvisor.com.sg'
class TravelSpider (scrapy.Spider):
name = "tripadvisor"
start_urls = [
'https://www.tripadvisor.com.sg/Hotels-g294265-oa30-Singapore-Hotels.html',
]
def parse(self, response):
#enter hotel page
hotels = response.css('div.listing_title a.property_title.prominent::attr("href")')
for hotel in hotels:
yield response.follow(hotel.extract(), self.parse_hotel_reviews)
next_page = response.css('div.unified.ui_pagination a.primary::attr("href")').extract_first()
if next_page is not None:
yield response.follow(next_page, self.parse)
else:
inspect_response(response, self)
def parse_hotel_reviews(self, response):
print("Checking hotel ", response.url)
|
986,598 | f68920abc036f470bd919e98f467f74468cbb3a4 | from . import views
from . import api
from django.conf.urls import url
from django.contrib import admin # We can remove this later on.
from django.urls import include, path # Do we need to import path..?
from django.views.decorators.csrf import csrf_exempt
from rest_framework import routers
from rest_framework.authtoken import views as auth_views
# Imports the class DefaultRouter from routers.
router = routers.DefaultRouter()
# Register the all CRUD operations with the router
router.register(r'users', api.UserViewSet)
# router.register(r'groups', api.GroupViewSet)
router.register(r'practitioner', api.PractitionerViewSet, 'practitioner')
router.register(r'diabetic', api.DiabeticViewSet, 'diabetic')
router.register(r'meal', api.MealViewSet, 'meal')
router.register(r'recipe', api.RecipeViewSet, 'recipe')
router.register(r'log', api.LogViewSet, 'log')
urlpatterns = [
# ... the rest of the urlpatterns ...
# must be catch-all for pushState to work
path('admin/', admin.site.urls),
path('api/', include(router.urls)),
path('api/it/', csrf_exempt(views.ApiView.as_view())),
url(r'^api-token-auth/', auth_views.obtain_auth_token, name='api-token-auth'),
path('api/calculate_dosages/', views.calculate_dosages),
path('api/food_search/', views.food_search),
path('api/search_recipes/', views.search_recipes),
# url(r'^rest-auth/', include('rest_auth.urls')),
# path('login/', views.api_login),
# path('logout/', views.api_logout),
# path('api/register/', views.api_register),
# url(r'^login/$', views.api_login),
url(r'^', views.FrontendAppView.as_view()) # This is a catch-all for React.
]
|
986,599 | 971af3e0b1ed7ae92e6e2fe93d7828d7e0736722 | from marshmallow import Schema, fields, validate
class UserSchema(Schema):
name = fields.Str(required=True, allow_none=False, )
username = fields.Str(required=True, allow_none=False, )
twitter_username = fields.Str(required=True, allow_none=True)
github_username = fields.Str(required=True, allow_none=True)
website_url = fields.URL(required=True, allow_none=True)
profile_image = fields.URL(required=True, allow_none=True)
profile_image_90 = fields.URL(required=True, allow_none=True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.