text stringlengths 38 1.54M |
|---|
import gensim
import gensim.downloader as api
import numpy as np
import argparse
import tensorflow as tf
from util import DataManager
import os
from sys import argv
from keras.models import load_model
from keras.backend import set_session
gpu_options = tf.GPUOptions(allow_growth=True)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
set_session(sess)
parser = argparse.ArgumentParser(description='Natural Language Matching')
parser.add_argument('modelname')
parser.add_argument('datapath')
parser.add_argument('--subtask', choices=['A', 'B', 'C'])
args = parser.parse_args()
def outputA(qidlist, result, modelname):
"""
The function which writes prediction file of subtaskA
Arguments:
qidlist: A list of RELC_ID
result: 2D numpy array, the output of the model
modelname: String, modelname
Outputs:
subtaskA/result/[modelname]/res.pred
"""
outdir = os.path.join("subtaskA","result", modelname)
if not os.path.isdir(outdir):
os.makedirs(outdir)
with open(os.path.join(outdir, "res.pred"), "w") as f:
for idx, r in enumerate(result):
print(r)
label = np.argmax(r)
relq_id = qidlist[idx].split('_')[0] + '_' + qidlist[idx].split('_')[1]
f.write(relq_id)
f.write(' ')
f.write(qidlist[idx])
f.write(' 0 ')
f.write(str(r[1]))
f.write(' ')
if label == 1:
f.write('true')
elif label == 0:
f.write('false')
f.write('\n')
def outputB(qidlist, result, modelname):
"""
The function which writes prediction file of subtaskB
Arguments:
qidlist: A list of RELC_ID
result: 2D numpy array, the output of the model
modelname: String, modelname
Outputs:
subtaskB/result/[modelname]/res.pred
"""
outdir = os.path.join("subtaskB","result", modelname)
if not os.path.isdir(outdir):
os.makedirs(outdir)
with open(os.path.join(outdir, "res.pred"), "w") as f:
for idx, r in enumerate(result):
print(r)
label = np.argmax(r)
relq_id = qidlist[idx].split('_')[0]
f.write(relq_id)
f.write(' ')
f.write(qidlist[idx])
f.write(' 0 ')
f.write(str(r[1]))
f.write(' ')
if label == 1:
f.write('true')
elif label == 0:
f.write('false')
f.write('\n')
def outputC(qidlist, result, modelname):
"""
The function which writes prediction file of subtaskB
Arguments:
qidlist: A list of RELC_ID
result: 2D numpy array, the output of the model
modelname: String, modelname
Outputs:
subtaskC/result/[modelname]/res.pred
"""
outdir = os.path.join("subtaskC", "result", modelname)
if not os.path.isdir(outdir):
os.makedirs(outdir)
with open(os.path.join(outdir, "res.pred"), "w") as f:
for idx, r in enumerate(result):
print(r)
label = np.argmax(r)
orgq_id = qidlist[idx].split('_')[0]
f.write(orgq_id)
f.write(' ')
f.write(qidlist[idx])
f.write(' 0 ')
f.write(str(r[1]))
f.write(' ')
if label == 1:
f.write('true')
elif label == 0:
f.write('false')
f.write('\n')
def main():
"""
Main function of test.py
Arguments:
modelname: String, name of the model
datapath: The testing file
subtask: String, "A" or "B" or "C"
Outputs:
subtask + [subtask]/result/[modelname]/res.pred
"""
modelname = args.modelname
datapath = args.datapath
subtask = args.subtask
dm = DataManager(subtask)
dm.load_tokenizer(os.path.join("subtask" + subtask, "models", modelname, "word2idx.pkl"), os.path.join("subtask" + subtask, "models", modelname, "idx2word.pkl"))
dm.add_data("test", datapath)
dm.to_sequence(40, 40)
(test_Q, test_C), qidlist = dm.get_data("test")
print("test_Q", test_Q[0:2])
print("test_C", test_C[0:2])
print("qidlist", qidlist[0:2])
model = load_model(os.path.join("subtask" + subtask, "models", modelname, "model.h5"))
result = model.predict([test_Q, test_C], batch_size = 128, verbose=1)
print("result", result[0:2])
if subtask == "A":
outputA(qidlist, result, modelname)
elif subtask == "B":
outputB(qidlist, result, modelname)
elif subtask == "C":
outputC(qidlist, result, modelname)
if __name__ == "__main__":
main()
|
# -*- coding:utf-8 -*-
# Author:D.Gray
import pymysql
conn = pymysql.connect(host = 'localhost',port = 3306,user = 'root',password = 'admin1988',db = 'oldboy')
cursor = conn.cursor()
recount = cursor.execute('select * from student')
print(cursor.fetchall()) |
import math
def side(x1,y1,x2,y2):
x=math.sqrt(((x1-x2)**2+(y1-y2)**2))
return x
x1=eval(input("x1="))
y1=eval(input("y1="))
x2=eval(input("x2="))
y2=eval(input("y2="))
x3=eval(input("x3="))
y3=eval(input("y3="))
side1=side(x1,y1,x2,y2)
side2=side(x1,y1,x3,y3)
side3=side(x2,y2,x3,y3)
s=(side1+side2+side3)/2
area=math.sqrt(s*(s-side1)*(s-side2)*(s-side3))
print("{:<7.2f}".format(area)) |
i=1
s=0
dec=int(input("Enter the number\n"))
while(dec>0):
rem=int(dec%2)
s=s+(i*rem)
dec=int(dec/2)
i=i*10
print(s)
input("Press 'Enter' Key to exit")
|
from Lesson_8_Dataclass.base_page import BaseTransport
from Lesson_8_Dataclass.transport.air import Air
if __name__ == "__main__": # тест для самолета
fuel = 26025
speed = 220
elevation = 5
echelon = 10600
landing_height = 400
permissible_speed = 300
print(Air.get_transport({}))
BaseTransport.fuel_test()
Air.test_takeoff()
Air.test_landing()
|
import slack
import logging
import os
#import time
#import uuid
#import cloudwatch_metric
#from decimal import Decimal
#logger = logging.getLogger()
#logger.setLevel(logging.INFO)
def coffee_ready_handler(event, context):
coffee_ready(event, context)
return
def coffee_ready(event, context):
## Environment
#
# Required
slack_token = os.environ['SLACK_TOKEN']
aws_region = os.environ['AWS_REGION']
#
# Optional
slack_channel = os.environ.get('SLACK_CHANNEL', 'general')
#
## End Environment
#session = boto3.Session(region_name=aws_region)
slack_post = '@here Coffee is ready!'
# Post to slack
slack.post_text_message(slack_token, slack_channel, slack_post)
return
|
# Assignes Behtsa to variable name
name = "Behtsa"
# Assignes 23 t age
age = 23
# Assignes 59 inches to variable height
height = 59 # inches
# Assignes 110 lbs to variable weight
weight = 110 # lbs
# Assignes dark brown to variable eyes color
eyes = 'Dark brown'
# Assignes white to variable teeth color
teeth = 'White'
# Assignes dark brown to variable hair color
hair = 'Dark brown'
# Converts height given in cm
height_in_cm = height * 2.54
# Converts weight given in kg
weight_in_kg = weight * .4535
# Concatenates the variable name in the string
print "Let' talk about {}." .format (name)
# Concatenates more than just 1 variable ( height, heigh_in_cm) with the string // this with the new format
# as it can be done %d % height // %f is a float value
print "She's %d inches tall, in centimeters is %f." % (height, height_in_cm)
# Concatenates variable weight and weight_in_cm to the string
print "She's %d pounds heavy, in kilos is %f." % (weight, weight_in_kg)
# Concatenates the variables eyes and hair to the string
print "She's got %r eyes and %s hair." % (eyes, hair)
# Concatenates the variable teeth to the string below.
print "Her teeth are usually %s." % teeth
#Concatenates with .format (new way) all the variables below to the string., as a sum up
print "If I add {}, {}, and {} I get {}." .format(age, height, weight, age + height + weight)
|
s=[]
b=int(input())
for k in range(0,b):
n=input()
s.append(n)
st=""
count=0
t=[]
for l in s:
t.append(len(l))
t.sort()
m=t[0]
z=0
for j in range(0,m):
count=0
for i in range(1,b):
if s[i-1][j]==s[i][j]:
count+=1
else:
z=1
break
if count==b-1:
st=st+(s[i][j])
if z==1:
break
print(st)
|
#coding: utf-8
import math
import heapq
MOD = 10**9+7
a,b,x = map(int, input().split())
V = (a**2)*b
if x>=(V/2):
h = 2*b-2*x/(a*a)
htan = h/a
else:
h = 2*x/(a*b)
htan = b/h
ans = math.atan(htan)*180/(math.atan(1.0)*4)
print(ans) |
# coding=utf8
from flask import Flask, render_template, redirect, url_for,request,jsonify,current_app,make_response
from datetime import timedelta
from flask_cors import CORS,cross_origin
from flask import make_response
# import statements
import wikipedia
import random
import re
from summa import summarizer
import operator
from rake_nltk import Rake
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk import pos_tag
from allennlp.predictors.predictor import Predictor
from functools import update_wrapper
import nltk
import spacy
import numpy as np
import pandas as pd
import argparse
from pytorch_pretrained_bert.tokenization import (BasicTokenizer,
BertTokenizer, whitespace_tokenize)
import collections
import torch
from torch.utils.data import TensorDataset
from pytorch_pretrained_bert.modeling import BertForQuestionAnswering, BertConfig
import math
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
TensorDataset)
from tqdm import tqdm
from termcolor import colored, cprint
class SquadExample(object):
"""
A single training/test example for the Squad dataset.
For examples without an answer, the start and end position are -1.
"""
def __init__(self,
example_id,
para_text,
qas_id,
question_text,
doc_tokens,
unique_id):
self.qas_id = qas_id
self.question_text = question_text
self.doc_tokens = doc_tokens
self.example_id = example_id
self.para_text = para_text
self.unique_id = unique_id
def __str__(self):
return self.__repr__()
def __repr__(self):
s = ""
s += "qas_id: %s" % (self.qas_id)
s += ", question_text: %s" % (
self.question_text)
s += ", doc_tokens: [%s]" % (" ".join(self.doc_tokens))
return s
### Convert paragraph to tokens and returns question_text
def read_squad_examples(input_data):
"""Read a SQuAD json file into a list of SquadExample."""
def is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
i = 0
examples = []
for entry in input_data:
example_id = entry['id']
paragraph_text = entry['text']
doc_tokens = []
prev_is_whitespace = True
for c in paragraph_text:
if is_whitespace(c):
prev_is_whitespace = True
else:
if prev_is_whitespace:
doc_tokens.append(c)
else:
doc_tokens[-1] += c
prev_is_whitespace = False
for qa in entry['ques']:
qas_id = i
question_text = qa
example = SquadExample(example_id=example_id,
qas_id=qas_id,
para_text=paragraph_text,
question_text=question_text,
doc_tokens=doc_tokens,
unique_id=i)
i += 1
examples.append(example)
return examples
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span.start + doc_span.length - 1
if position < doc_span.start:
continue
if position > end:
continue
num_left_context = position - doc_span.start
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
unique_id,
example_index,
doc_span_index,
tokens,
token_is_max_context,
token_to_orig_map,
input_ids,
input_mask,
segment_ids):
self.doc_span_index = doc_span_index
self.unique_id = unique_id
self.example_index = example_index
self.tokens = tokens
self.token_is_max_context = token_is_max_context
self.token_to_orig_map = token_to_orig_map
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
def convert_examples_to_features(examples, tokenizer, max_seq_length,
doc_stride, max_query_length):
"""Loads a data file into a list of `InputBatch`s."""
features = []
unique_id = 1
for (example_index, example) in enumerate(examples):
query_tokens = tokenizer.tokenize(example.question_text)
### Truncate the query if query length > max_query_length..
if len(query_tokens) > max_query_length:
query_tokens = query_tokens[0:max_query_length]
tok_to_orig_index = []
orig_to_tok_index = []
all_doc_tokens = []
for (i, token) in enumerate(example.doc_tokens):
orig_to_tok_index.append(len(all_doc_tokens))
sub_tokens = tokenizer.tokenize(token)
for sub_token in sub_tokens:
tok_to_orig_index.append(i)
all_doc_tokens.append(sub_token)
tok_start_position = None
tok_end_position = None
max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
# We can have documents that are longer than the maximum sequence length.
# To deal with this we do a sliding window approach, where we take chunks
# of the up to our max length with a stride of `doc_stride`.
_DocSpan = collections.namedtuple( # pylint: disable=invalid-name
"DocSpan", ["start", "length"])
doc_spans = []
start_offset = 0
while start_offset < len(all_doc_tokens):
length = len(all_doc_tokens) - start_offset
if length > max_tokens_for_doc:
length = max_tokens_for_doc
doc_spans.append(_DocSpan(start=start_offset, length=length))
if start_offset + length == len(all_doc_tokens):
break
start_offset += min(length, doc_stride)
for (doc_span_index, doc_span) in enumerate(doc_spans):
tokens = []
token_to_orig_map = {}
token_is_max_context = {}
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
for i in range(doc_span.length):
split_token_index = doc_span.start + i
token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]
is_max_context = _check_is_max_context(doc_spans, doc_span_index,
split_token_index)
token_is_max_context[len(tokens)] = is_max_context
tokens.append(all_doc_tokens[split_token_index])
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
features.append(InputFeatures(unique_id=unique_id,
example_index=example_index,
doc_span_index=doc_span_index,
tokens=tokens,
token_is_max_context=token_is_max_context,
token_to_orig_map=token_to_orig_map,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids))
unique_id += 1
return features
def _get_best_indexes(logits, n_best_size):
"""Get the n-best logits from a list."""
index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
best_indexes = []
for i in range(len(index_and_score)):
if i >= n_best_size:
break
best_indexes.append(index_and_score[i][0])
return best_indexes
def get_final_text(pred_text, orig_text, do_lower_case, verbose_logging=False):
"""Project the tokenized prediction back to the original text."""
def _strip_spaces(text):
ns_chars = []
ns_to_s_map = collections.OrderedDict()
for (i, c) in enumerate(text):
if c == " ":
continue
ns_to_s_map[len(ns_chars)] = i
ns_chars.append(c)
ns_text = "".join(ns_chars)
return (ns_text, ns_to_s_map)
tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
tok_text = " ".join(tokenizer.tokenize(orig_text))
start_position = tok_text.find(pred_text)
if start_position == -1:
if verbose_logging:
logger.info(
"Unable to find text: '%s' in '%s'" % (pred_text, orig_text))
return orig_text
end_position = start_position + len(pred_text) - 1
(orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)
(tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)
if len(orig_ns_text) != len(tok_ns_text):
if verbose_logging:
logger.info("Length not equal after stripping spaces: '%s' vs '%s'",
orig_ns_text, tok_ns_text)
return orig_text
# We then project the characters in `pred_text` back to `orig_text` using
# the character-to-character alignment.
tok_s_to_ns_map = {}
for (i, tok_index) in tok_ns_to_s_map.items():
tok_s_to_ns_map[tok_index] = i
orig_start_position = None
if start_position in tok_s_to_ns_map:
ns_start_position = tok_s_to_ns_map[start_position]
if ns_start_position in orig_ns_to_s_map:
orig_start_position = orig_ns_to_s_map[ns_start_position]
if orig_start_position is None:
if verbose_logging:
logger.info("Couldn't map start position")
return orig_text
orig_end_position = None
if end_position in tok_s_to_ns_map:
ns_end_position = tok_s_to_ns_map[end_position]
if ns_end_position in orig_ns_to_s_map:
orig_end_position = orig_ns_to_s_map[ns_end_position]
if orig_end_position is None:
if verbose_logging:
logger.info("Couldn't map end position")
return orig_text
output_text = orig_text[orig_start_position:(orig_end_position + 1)]
return output_text
_PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
"PrelimPrediction",
["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
def _compute_softmax(scores):
"""Compute softmax probability over raw logits."""
if not scores:
return []
max_score = None
for score in scores:
if max_score is None or score > max_score:
max_score = score
exp_scores = []
total_sum = 0.0
for score in scores:
x = math.exp(score - max_score)
exp_scores.append(x)
total_sum += x
probs = []
for score in exp_scores:
probs.append(score / total_sum)
return probs
_NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
"NbestPrediction", ["text", "start_logit", "end_logit"])
def predict(examples, all_features, all_results, max_answer_length):
n_best_size = 10
### Adding index to feature ###
example_index_to_features = collections.defaultdict(list)
for feature in all_features:
example_index_to_features[feature.example_index].append(feature)
unique_id_to_result = {}
for result in all_results:
unique_id_to_result[result.unique_id] = result
all_predictions = collections.OrderedDict()
for example in examples:
index = 0
features = example_index_to_features[example.unique_id]
prelim_predictions = []
for (feature_index, feature) in enumerate(features):
result = unique_id_to_result[feature.unique_id]
start_indexes = _get_best_indexes(result.start_logits, n_best_size)
end_indexes = _get_best_indexes(result.end_logits, n_best_size)
for start_index in start_indexes:
for end_index in end_indexes:
#### we remove the indexes which are invalid @
if start_index >= len(feature.tokens):
continue
if end_index >= len(feature.tokens):
continue
if start_index not in feature.token_to_orig_map:
continue
if end_index not in feature.token_to_orig_map:
continue
if not feature.token_is_max_context.get(start_index, False):
continue
if end_index < start_index:
continue
length = end_index - start_index + 1
if length > max_answer_length:
continue
prelim_predictions.append(
_PrelimPrediction(
feature_index=feature_index,
start_index=start_index,
end_index=end_index,
start_logit=result.start_logits[start_index],
end_logit=result.end_logits[end_index]))
prelim_predictions = sorted(
prelim_predictions,
key=lambda x: (x.start_logit + x.end_logit),
reverse=True)
seen_predictions = {}
nbest = []
for pred in prelim_predictions:
if len(nbest) >= n_best_size:
break
feature = features[pred.feature_index]
if pred.start_index > 0: # this is a non-null prediction
tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]
orig_doc_start = feature.token_to_orig_map[pred.start_index]
orig_doc_end = feature.token_to_orig_map[pred.end_index]
orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]
tok_text = " ".join(tok_tokens)
# De-tokenize WordPieces that have been split off.
tok_text = tok_text.replace(" ##", "")
tok_text = tok_text.replace("##", "")
# Clean whitespace
tok_text = tok_text.strip()
tok_text = " ".join(tok_text.split())
orig_text = " ".join(orig_tokens)
final_text = get_final_text(tok_text, orig_text, True)
if final_text in seen_predictions:
continue
seen_predictions[final_text] = True
else:
final_text = ""
seen_predictions[final_text] = True
nbest.append(
_NbestPrediction(
text=final_text,
start_logit=pred.start_logit,
end_logit=pred.end_logit))
if not nbest:
nbest.append(
_NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
assert len(nbest) >= 1
total_scores = []
best_non_null_entry = None
for entry in nbest:
total_scores.append(entry.start_logit + entry.end_logit)
if not best_non_null_entry:
if entry.text:
best_non_null_entry = entry
probs = _compute_softmax(total_scores)
nbest_json = []
for (i, entry) in enumerate(nbest):
output = collections.OrderedDict()
output["text"] = entry.text
output["probability"] = probs[i]
output["start_logit"] = entry.start_logit
output["end_logit"] = entry.end_logit
nbest_json.append(output)
assert len(nbest_json) >= 1
all_predictions[example] = nbest_json[0]["text"]
index = +1
return all_predictions
RawResult = collections.namedtuple("RawResult",
["unique_id", "start_logits", "end_logits"])
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model_path = 'BERT/bert_model.bin'
config_file = 'BERT/bert_config.json'
config = BertConfig(config_file)
model = BertForQuestionAnswering(config)
model.load_state_dict(torch.load(model_path, map_location='cpu'))
model.to(device)
def bert_predict(context, q):
parser = argparse.ArgumentParser()
parser.add_argument("--paragraph", default=None, type=str)
parser.add_argument("--model", default=None, type=str)
parser.add_argument("--max_seq_length", default=384, type=int)
parser.add_argument("--doc_stride", default=128, type=int)
parser.add_argument("--max_query_length", default=64, type=int)
parser.add_argument("--config_file", default=None, type=str)
parser.add_argument("--max_answer_length", default=30, type=int)
# args = parser.parse_args()
# para_file = args.paragraph
# model_path = args.model
model_path = 'BERT/bert_model.bin'
config_file = 'BERT/bert_config.json'
max_answer_length = 30
max_query_length = 64
doc_stride = 128
max_seq_length = 384
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
n_gpu = torch.cuda.device_count()
'''
### Raeding paragraph
f = open(para_file, 'r',encoding="utf8")
para = f.read()
f.close()
## Reading question
# f = open(ques_file, 'r')
# ques = f.read()
# f.close()
para_list = para.split('\n\n')
input_data = []
i = 1
for para in para_list :
paragraphs = {}
splits = para.split('\nQuestions:')
paragraphs['id'] = i
paragraphs['text'] = splits[0].replace('Paragraph:', '').strip('\n')
paragraphs['ques']=splits[1].lstrip('\n').split('\n')
input_data.append(paragraphs)
i+=1
'''
input_data = [{'id': 1, 'text': context, 'ques': [q]}]
## input_data is a list of dictionary which has a paragraph and questions
examples = read_squad_examples(input_data)
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
eval_features = convert_examples_to_features(
examples=examples,
tokenizer=tokenizer,
max_seq_length=max_seq_length,
doc_stride=doc_stride,
max_query_length=max_query_length)
all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
### Loading Pretrained model for QnA
'''
config = BertConfig(config_file)
model = BertForQuestionAnswering(config)
model.load_state_dict(torch.load(model_path, map_location='cpu'))
model.to(device)
'''
pred_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_example_index)
# Run prediction for full data
pred_sampler = SequentialSampler(pred_data)
pred_dataloader = DataLoader(pred_data, sampler=pred_sampler, batch_size=9)
predictions = []
for input_ids, input_mask, segment_ids, example_indices in tqdm(pred_dataloader):
input_ids = input_ids.to(device)
input_mask = input_mask.to(device)
segment_ids = segment_ids.to(device)
with torch.no_grad():
batch_start_logits, batch_end_logits = model(input_ids, segment_ids, input_mask)
features = []
example = []
all_results = []
for i, example_index in enumerate(example_indices):
start_logits = batch_start_logits[i].detach().cpu().tolist()
end_logits = batch_end_logits[i].detach().cpu().tolist()
feature = eval_features[example_index.item()]
unique_id = int(feature.unique_id)
features.append(feature)
all_results.append(RawResult(unique_id=unique_id,
start_logits=start_logits,
end_logits=end_logits))
output = predict(examples, features, all_results, max_answer_length)
predictions.append(output)
return list(predictions[0].values())[0]
basestring = (str,bytes)
def preprocess(text):
tokenized_text = nltk.word_tokenize(text)
tagged_text = nltk.tag.pos_tag(tokenized_text)
simple_tagged_text = [(word, nltk.tag.map_tag('en-ptb', 'universal', tag)) for word, tag in tagged_text]
return simple_tagged_text
priorities = {
"PERSON":1,
"EVENT":2,
"ORG":3,
"PRODUCT":4,
"LOC":5,
"GPE":6,
"NORP":7,
"LANGUAGE":8,
"DATE":9,
"OTHER":10
}
nlp = spacy.load("en_core_web_md")
def spacy_ner(TEXT):
# Much worse but faster NER with "en_core_web_sm"
doc = nlp(TEXT)
# tagged_text = preprocess(TEXT)
tagged_text = []
for token in doc:
tagged_text.append((token.text, token.tag_))
prev = ""
ents_label_list = []
for X in doc.ents:
if X.label_ not in priorities.keys():
ents_label_list.append((X.text, "OTHER"))
else:
if prev == "DATE" and X.label_ == "EVENT":
old_ent = ents_label_list.pop()
new_ent = (old_ent[0] + " " + X.text, "EVENT")
ents_label_list.append(new_ent)
else:
ents_label_list.append((X.text, X.label_))
prev = X.label_
ents_label_list = sorted(ents_label_list, key=lambda x: priorities[x[1]])
print("Entities and their labels")
return ents_label_list
def add_cors_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*'
if request.method == 'OPTIONS':
response.headers['Access-Control-Allow-Methods'] = 'DELETE, GET, POST, PUT'
headers = request.headers.get('Access-Control-Request-Headers')
if headers:
response.headers['Access-Control-Allow-Headers'] = headers
return response
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
st = StanfordNERTagger('stanford-ner/classifiers/english.all.3class.distsim.crf.ser.gz',
'stanford-ner/stanford-ner.jar',
encoding='utf-8')
NLTKSTOPWORDS = ["i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself",
"yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself",
"they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that",
"these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had",
"having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because",
"as", "until", "while", "of", "at", "by", "for", "with", "about", "against",
"between", "into", "through", "during", "before", "after", "above", "below", "to", "from",
"up", "down", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here",
"there", "when", "where", "why", "how", "all", "any",
"both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own",
"same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now"]
PUNCIGN = "()"
LOCALINFO = {"you":'Data/About_Self',"yourself":'Data/About_Self',"You":'Data/About_Self',"Yourself":'Data/About_Self',
"PESU":'Data/About_PESU',"PES University":'Data/About_PESU'}
DATAKEYS = LOCALINFO.keys()
r = Rake(stopwords=NLTKSTOPWORDS, punctuations=PUNCIGN)
#predictor = Predictor.from_path("QAModels/allen_bidaf")
def replace_pronouns(text, noun):
rep_pronouns = ["She", "she", "He", "he", "They", "they", "It", "it"]
try:
for rep in rep_pronouns:
if text[0:len(rep)] == rep:
text = noun + text[len(rep):]
break
except IndexError:
pass
return text
class Context:
def __init__(self, topic, match):
if match:
try:
self.page = wikipedia.page(topic)
except wikipedia.exceptions.DisambiguationError as err:
self.page = wikipedia.page(err.options[0])
else:
try:
results = wikipedia.search(topic, results=100)
self.page = wikipedia.page(results[random.randint(0, 100)])
except wikipedia.exceptions.DisambiguationError as err:
self.page = wikipedia.page(err.options[0])
self.sections = self.page.sections
self.summary = ""
self.keywords = ""
self.keywords_full = []
self.sentences = []
self.questions = []
self.ktotal = []
def get_section(self):
print("Selected article:", self.page.title)
print("Available sections:")
print("0 : All")
i = 1
for section in self.sections:
print(i, ":", section)
i += 1
print()
choice = int(input("Selected section:"))
if choice == 0:
self.summary = summarizer.summarize(self.page.content, words=300)
r.extract_keywords_from_text(self.page.content)
self.ktotal = r.get_ranked_phrases_with_scores()
else:
self.summary = summarizer.summarize(self.page.section(self.sections[choice-1]), words=300)
r.extract_keywords_from_text(self.page.section(self.sections[choice-1]))
self.ktotal = r.get_ranked_phrases_with_scores()
def gen_questions(self):
r.extract_keywords_from_text(self.summary)
self.keywords_full = r.get_ranked_phrases_with_scores()
self.sentences = self.summary.split(".")
# print("All keywords:",self.keywords_full)
for s in self.sentences:
r.extract_keywords_from_text(s)
only_sentence_keywords = r.get_ranked_phrases_with_scores()
# print("Only Sentence:", only_sentence_keywords)
s.rstrip("\n")
sentence_keywords = []
for tup in self.keywords_full:
i = list(tup)
if ")" in i[1]:
split_string = i[1].split(")")
repstring = ""
for k in split_string:
repstring += k + "\)"
i[1] = repstring
if "(" in i[1]:
split_string = i[1].split("(")
repstring = ""
for k in split_string:
repstring += "\(" + k
i[1] = repstring
if re.search(i[1], s, flags=re.IGNORECASE):
sentence_keywords.append(i)
for tup in only_sentence_keywords:
sentence_keywords.append(list(tup))
sentence_keywords.sort(key=operator.itemgetter(0), reverse=True)
if len(sentence_keywords) != 0:
if ")" in sentence_keywords[0][1]:
split_string = sentence_keywords[0][1].split(")")
repstring = ""
for k in split_string:
repstring += k+"\)"
sentence_keywords[0][1] = repstring
if "(" in sentence_keywords[0][1]:
split_string = sentence_keywords[0][1].split("(")
repstring = ""
for k in split_string:
repstring += "\("+k
sentence_keywords[0][1] = repstring
qtext = re.sub(sentence_keywords[0][1],
"_"*len(sentence_keywords[0][1]), s, flags=re.IGNORECASE)
self.questions.append([qtext, sentence_keywords[0]])
print("Generated Questions:")
for q in self.questions:
print(q[0])
print(q[1])
def gen_questions_df(self):
r.extract_keywords_from_text(self.summary)
self.keywords_full = r.get_ranked_phrases_with_scores()
self.sentences = self.summary.split(".")
# print("All keywords:",self.keywords_full)
for s in self.sentences:
r.extract_keywords_from_text(s)
only_sentence_keywords = r.get_ranked_phrases_with_scores()
# print("Only Sentence:", only_sentence_keywords)
s.rstrip("\n")
sentence_keywords=[]
for tup in self.keywords_full:
i = list(tup)
if ")" in i[1]:
split_string = i[1].split(")")
repstring = ""
for k in split_string:
repstring += k+"\)"
i[1] = repstring
if "(" in i[1]:
split_string = i[1].split("(")
repstring = ""
for k in split_string:
repstring += "\("+k
i[1] = repstring
if re.search(i[1], s, flags=re.IGNORECASE):
sentence_keywords.append(i)
for tup in only_sentence_keywords:
sentence_keywords.append(list(tup))
sentence_keywords.sort(key=operator.itemgetter(0), reverse=True)
if len(sentence_keywords) != 0:
qtext = re.sub(sentence_keywords[0][1],"_"*len(sentence_keywords[0][1]), s, flags=re.IGNORECASE)
self.questions.append([qtext, sentence_keywords[0]])
self.questions.append(["USING FKF", "****"])
self.keywords_full.sort(key=operator.itemgetter(0), reverse=True)
for s in self.sentences:
for kf in self.keywords_full:
if kf[1] in s:
qtext = re.sub(kf[1],"_"*len(kf[1]),s,flags=re.IGNORECASE)
self.questions.append([qtext, kf[1]])
self.keywords_full.remove(kf)
print("Generated Questions:")
for q in self.questions:
print(q[0])
print(q[1])
def highvolume(self):
print("500 word summary:")
print(self.summary)
print("Fulltext keywords:")
for key in self.ktotal:
if key[0]>4:
print(key)
class QInput:
def __init__(self,ip_txt):
self.questext = ip_txt
if self.questext[len(self.questext)-1]!="?":
self.questext+="?"
self.inbotdata = False
self.dkey = ""
for k in DATAKEYS:
if k in self.questext:
self.inbotdata = True
self.dkey = k
self.tokenized_text = word_tokenize(ip_txt)
self.classified_text = st.tag(self.tokenized_text)
self.people_names = []
self.locations = []
self.orgs = []
self.others = []
self.qkey = r.extract_keywords_from_text(ip_txt)
prev_tag = ""
current = ""
for i in self.classified_text:
if i[1] !=0:
if i[1] == "PERSON":
if prev_tag != "PERSON":
prev_tag = "PERSON"
current = i[0]
else:
current += " "+i[0]
else:
if prev_tag == "PERSON":
self.people_names.append(current)
current = ""
prev_tag = i[1]
prev_tag = ""
current = ""
for i in self.classified_text:
if i[1] != 0:
if i[1] == "LOCATION":
if prev_tag != "LOCATION":
prev_tag = "LOCATION"
current = i[0]
else:
current += " "+i[0]
else:
if prev_tag == "LOCATION":
self.locations.append(current)
current = ""
prev_tag = i[1]
prev_tag = ""
current = ""
for i in self.classified_text:
if i[1] != 0:
if i[1] == "ORGANIZATION":
if prev_tag != "ORGANIZATION":
prev_tag = "ORGANIZATION"
current = i[0]
else:
current += " "+i[0]
else:
if prev_tag == "ORGANIZATION":
self.orgs.append(current)
current = ""
prev_tag = i[1]
self.pos_text = pos_tag(self.tokenized_text)
self.backup_keys = []
for i in self.pos_text:
if i[1][:2] == "NN":
self.backup_keys.append(i[0])
def showner(self):
print(self.pos_text)
print("People found :", self.people_names)
print("Locations found :", self.locations)
print("Organizations found :", self.orgs)
print("Backup keys :", self.backup_keys)
def gen_searchstring(self):
self.search = []
self.search.extend(self.people_names)
self.search.extend(self.orgs)
for i in self.backup_keys:
if i not in self.search and i not in self.locations:
self.search.append(i)
self.search.extend(self.locations)
if self.inbotdata==True:
f = open(LOCALINFO[self.dkey],"r")
self.con_final = f.read()
self.context = self.con_final
self.spacy_res = []
else:
self.spacy_res = spacy_ner(self.questext)
other_nn = []
if len(self.spacy_res)==0:
#print("Looking for NN")
doc = nlp(self.questext)
for token in doc:
#print(token.tag_,end=",")
if 'NN' in token.tag_:
other_nn.append(token.lemma_)
self.spacy_res = [other_nn]
self.context = Context(self.spacy_res[0][0],1)
print("Page used:",self.context.page.title)
self.con_final = self.context.page.summary
self.con_summary = self.context.page.summary
def reduced_context(self):
if self.inbotdata==True:
text = self.context
self.con_final = text
else:
text = self.context.page.content
q = self.questext
doc = nlp(q)
rdc = ""
doc_roots = []
for chunk in doc.noun_chunks:
doc_roots.append(chunk.root.text)
for nkey in self.spacy_res:
if nkey[0] in doc_roots:
doc_roots.remove(nkey[0])
text = text.split('\n')
if "== See also ==" in text:
text = text[:text.index("== See also ==")]
if "== Notes ==" in text:
text = text[:text.index("== Notes ==")]
if "== References ==" in text:
text = text[:text.index("== References ==")]
for line in text:
for root in doc_roots:
if root in line:
sen = line.split(".")
for s in sen:
if root in s:
rdc += s + "."
self.con_final = self.con_summary + rdc
def guessans(self):
#return(predictor.predict(passage=self.con_final, question=self.questext)['best_span_str'])
self.reduced_context()
#print(lultxt)
return bert_predict(self.con_final,self.questext)
def qanswer(q_text):
qobj = QInput(q_text)
qobj.gen_searchstring()
return qobj.guessans()
app = Flask(__name__)
CORS(app)
app.after_request(add_cors_headers)
@app.route("/")
def home():
return render_template("ChatUI/index.html")
@app.route('/chat', methods=['GET'])
@crossdomain(origin='*')
def chat():
message = "This the chat app"
if request.method == 'GET':
q_text = request.args.get('question')
try:
ans_text = qanswer(q_text)
print(ans_text)
except IndexError:
ans_text = "Sorry! I am unable to answer that question!"
return ans_text
if __name__ == "__main__":
app.run(host='0.0.0.0', debug = True)
|
#!/usr/bin/env python3
# coding: utf-8
#
import re
import os
import time
import argparse
import yaml
import bunch
import uiautomator2 as u2
from logzero import logger
CLICK = "click"
# swipe
SWIPE_UP = "swipe_up"
SWIPE_RIGHT = "swipe_right"
SWIPE_LEFT = "swipe_left"
SWIPE_DOWN = "swipe_down"
SCREENSHOT = "screenshot"
EXIST = "assert_exist"
WAIT = "wait"
def split_step(text: str):
__alias = {
"点击": CLICK,
"上滑": SWIPE_UP,
"右滑": SWIPE_RIGHT,
"左滑": SWIPE_LEFT,
"下滑": SWIPE_DOWN,
"截图": SCREENSHOT,
"存在": EXIST,
"等待": WAIT,
}
for keyword in __alias.keys():
if text.startswith(keyword):
body = text[len(keyword):].strip()
return __alias.get(keyword, keyword), body
else:
raise RuntimeError("Step unable to parse", text)
def read_file_content(path: str, mode:str = "r") -> str:
with open(path, mode) as f:
return f.read()
def run_step(cf: bunch.Bunch, app: u2.Session, step: str):
logger.info("Step: %s", step)
oper, body = split_step(step)
logger.debug("parse as: %s %s", oper, body)
if oper == CLICK:
app.xpath(body).click()
elif oper == SWIPE_RIGHT:
app.xpath(body).swipe("right")
elif oper == SWIPE_UP:
app.xpath(body).swipe("up")
elif oper == SWIPE_LEFT:
app.xpath(body).swipe("left")
elif oper == SWIPE_DOWN:
app.xpath(body).swipe("down")
elif oper == SCREENSHOT:
output_dir = "./output"
filename = "screen-%d.jpg" % int(time.time()*1000)
if body:
filename = body
name_noext, ext = os.path.splitext(filename)
if ext.lower() not in ['.jpg', '.jpeg', '.png']:
ext = ".jpg"
os.makedirs(cf.output_directory, exist_ok=True)
filename = os.path.join(cf.output_directory, name_noext + ext)
logger.debug("Save screenshot: %s", filename)
app.screenshot().save(filename)
elif oper == EXIST:
assert app.xpath(body).wait(), body
elif oper == WAIT:
#if re.match("^[\d\.]+$")
if body.isdigit():
seconds = int(body)
logger.info("Sleep %d seconds", seconds)
time.sleep(seconds)
else:
app.xpath(body).wait()
else:
raise RuntimeError("Unhandled operation", oper)
def run_conf(d, conf_filename: str):
d.healthcheck()
d.xpath.when("允许").click()
d.xpath.watch_background(2.0)
cf = yaml.load(read_file_content(conf_filename), Loader=yaml.SafeLoader)
default = {
"output_directory": "output",
"action_before_delay": 0,
"action_after_delay": 0,
"skip_cleanup": False,
}
for k, v in default.items():
cf.setdefault(k, v)
cf = bunch.Bunch(cf)
print("Author:", cf.author)
print("Description:", cf.description)
print("Package:", cf.package)
logger.debug("action_delay: %.1f / %.1f", cf.action_before_delay, cf.action_after_delay)
app = d.session(cf.package)
for step in cf.steps:
time.sleep(cf.action_before_delay)
run_step(cf, app, step)
time.sleep(cf.action_after_delay)
if not cf.skip_cleanup:
app.close()
device = None
conf_filename = None
def test_entry():
pass
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--command", help="run single step command")
parser.add_argument("-s", "--serial", help="run single step command")
parser.add_argument("conf_filename", default="test.yml", nargs="?", help="config filename")
args = parser.parse_args()
d = u2.connect(args.serial)
if args.command:
cf = bunch.Bunch({"output_directory": "output"})
app = d.session()
run_step(cf, app, args.command)
else:
run_conf(d, args.conf_filename)
|
import re
import sys
import collections
import json
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
if __name__ == '__main__':
sizes_list = []
sizes = []
sizes_repo = collections.defaultdict(lambda: collections.defaultdict(lambda: []))
csv_file = sys.argv[1]
f = open(csv_file, 'r')
for line in f: # currently there is only one line
data = re.findall("[^,]+", line)
for elem in data:
if elem.startswith('\r'): # newline
sizes_list.append(sizes)
sizes = []
currSize = float(elem.lstrip('\r'))
elif is_number(elem):
currSize = float(elem)
else:
sizes.append(elem + "," + str(currSize))
for sizes in sizes_list:
for size1 in sizes:
for size2 in sizes:
if size2 != size1:
size2 = size2.split(',')
sizes_repo[size1][size2[0]].append(size2[1])
print json.dumps(sizes_repo) |
from dagster_examples.intro_tutorial.custom_types import burger_time
from dagster import execute_pipeline_with_preset
def test_custom_types_example():
assert execute_pipeline_with_preset(burger_time, 'test').success
|
from classes.piece import Piece
from functions.pieces import Pieces
class Queen(Piece):
def __init__(self):
super().__init__('Q')
self.player = ''
self.id = ''
self.position = ''
def move(self, Queen):
self.moves = Pieces.moves(Queen)
return self.moves
|
import bottle
import wp
import json
import os
collection = wp.WikipediaCollection("./data/wp.db")
index = wp.Index("./data/indexWithTimes.db", collection)
analyse = wp.AnalyseQuery()
gameEnd = False
wordsState = []
@bottle.route('/action')
def action():
global wordsState, gameEnd
query = bottle.request.query.q
bottle.response.content_type = 'application/json'
if gameEnd:
if query == 'はい':
gameEnd = False
return json.dumps({
'textToSpeech': '新しいゲームを始めるよ。単語を言ってください'
}, indent=2, separators=(',', ': '), ensure_ascii=False)
else:
return json.dumps({
'textToSpeech': '聞こえないよ?もう一度遊びますか?'
#'textToSpeech': 'にゃ' #上書きされちゃう
}, indent=2, separators=(',', ': '), ensure_ascii=False)
terms = analyse.extractWords(query)
wordsState += terms
titles = index.search(wordsState)
if len(titles) == 0:
wordsState = []
gameEnd = True
return json.dumps({
#しんばる
#爆発音
'textToSpeech': '<speak><audio src="https://actionproxy-e83f8.firebaseapp.com/ranking.mp3">ドラムロール</audio><audio src="https://actionproxy-e83f8.firebaseapp.com/pop_explosion.mp3">どっかーん</audio>記事が見つかりませんでした。あなたのまけー!もう一度遊びますか</speak>'
}, indent=2, separators=(',', ': '), ensure_ascii=False)
if len(titles) < 5:
return json.dumps({
'textToSpeech': '<speak><audio src="https://actionproxy-e83f8.firebaseapp.com/ranking.mp3">ドラムロール</audio>記事が{}件見つかりました。今まで言われた単語は{}です。もう爆発寸前ですね。気をつけて!</speak>'.format(len(titles), 'と'.join(wordsState))
}, indent=2, separators=(',', ': '), ensure_ascii=False)
if len(titles) < 10:
return json.dumps({
'textToSpeech': '<speak><audio src="https://actionproxy-e83f8.firebaseapp.com/ranking.mp3">ドラムロール</audio>記事が{}件見つかりました。今まで言われた単語は{}です。そろそろ爆発しそうですね。どきどきします。</speak>'.format(len(titles), 'と'.join(wordsState))
}, indent=2, separators=(',', ': '), ensure_ascii=False)
if len(titles) < 100:
return json.dumps({
'textToSpeech': '<speak><audio src="https://actionproxy-e83f8.firebaseapp.com/ranking.mp3">ドラムロール</audio>記事が{}件見つかりました。今まで言われた単語は{}です。もうちょっと攻めてください。</speak>'.format(len(titles), 'と'.join(wordsState))
}, indent=2, separators=(',', ': '), ensure_ascii=False)
if len(titles) < 500:
return json.dumps({
'textToSpeech': '<speak><audio src="https://actionproxy-e83f8.firebaseapp.com/ranking.mp3">ドラムロール</audio>記事が{}件見つかりました。今まで言われた単語は{}です。もっといけますよ。</speak>'.format(len(titles), 'と'.join(wordsState))
}, indent=2, separators=(',', ': '), ensure_ascii=False)
return json.dumps({
'textToSpeech': '<speak><audio src="https://actionproxy-e83f8.firebaseapp.com/ranking.mp3">ドラムロール</audio>記事が{}件見つかりました。今まで言われた単語は{}です。まだまだですね。</speak>'.format(len(titles), 'と'.join(wordsState))
}, indent=2, separators=(',', ': '), ensure_ascii=False)
@bottle.route('/article/<title>')
def article(title):
article = collection.get_document_by_id(title)
bottle.response.content_type = 'application/json'
if article is None:
bottle.abort(404, "Not found")
return json.dumps({
'title': article.title,
'text': "<<<Omitted>>>",
'opening_text': article.opening_text,
'auxiliary_text': article.auxiliary_text,
'categories': article.categories,
'headings': article.headings,
'wiki_text': "<<<Omitted>>>",
'popularity_score': article.popularity_score,
'num_incoming_links': article.num_incoming_links,
}, indent=2, separators=(',', ': '), ensure_ascii=False)
@bottle.route('/article/wiki_text/<title>')
def article_wiki_text(title):
article = collection.get_document_by_id(title)
if article is None:
bottle.abort(404, "Not found")
bottle.response.content_type = 'text/plain;charset=utf-8'
return article.wiki_text
@bottle.route('/article/text/<title>')
def article_text(title):
article = collection.get_document_by_id(title)
if article is None:
bottle.abort(404, "Not found")
bottle.response.content_type = 'text/plain;charset=utf-8'
return article.text()
port = 8081
if 'WPSEARCH_PORT' in os.environ:
port = int(os.environ['WPSEARCH_PORT'])
bottle.run(host='0.0.0.0', port=port, reloader=False)
|
import pprint
import redis
import os
import datetime
import time
from multiprocessing import Pool
from elasticsearch import Elasticsearch
from redisearch import Client, TextField, NumericField, Query
from expbase import Experiment
from utils.utils import QueryPool
from pyreuse import helpers
from .Clients import *
from . import rs_bench_go
INDEX_NAME = "wik{0}"
def worker_wrapper(args):
worker(*args)
def worker(query_pool, query_count, engine):
client = create_client(engine)
for i in range(query_count):
query = query_pool.next_query()
ret = client.search(query)
if i % 5000 == 0:
print os.getpid(), "{}/{}".format(i, query_count)
def create_client(engine):
if engine == "elastic":
return ElasticSearchClient(INDEX_NAME)
elif engine == "redis":
# return RediSearchClient(INDEX_NAME)
return RedisClient(INDEX_NAME)
class ExperimentEsRs(Experiment):
def __init__(self):
self._exp_name = "redis-pybench-1shard-014"
self.wiki_abstract_path = "/mnt/ssd/downloads/enwiki-20171020-abstract.xml"
parameters = {
'worker_count': [1, 16, 32, 64, 128],
'query': ['hello', 'barack obama', 'wiki-query-log'],
# 'query': ['wiki-query-log'],
'engine': ['elastic'],
'line_doc_path': ["/mnt/ssd/downloads/enwiki-abstract.linedoc.withurl"],
'n_shards': [1],
'n_hosts': [1],
'rebuild_index': [False],
'index_builder': ['RediSearchBenchmark'] # or PyBench
}
self.paras = helpers.parameter_combinations(parameters)
self._n_treatments = len(self.paras)
assert len(parameters['engine']) == 1, \
"Allow only 1 engine because we only build index for one engine at an experiment"
def conf(self, i):
para = self.paras[i]
conf = {
'doc_count': 10**8,
'query_count': int(50000 / para['worker_count']),
'query': para['query'],
'engine': para['engine'],
"benchmark": "PyBench",
"line_doc_path": para['line_doc_path'],
'n_clients': para['worker_count'],
'rebuild_index': para['rebuild_index'],
'index_builder': para['index_builder'],
'n_hosts': para['n_hosts']
}
if para['query'] == 'wiki-query-log':
conf['query_source'] = "/mnt/ssd/downloads/wiki_QueryLog"
else:
conf['query_source'] = [para['query']]
if conf['engine'] == 'elastic':
client = create_client(conf['engine'])
conf['n_shards'] = client.get_number_of_shards(),
elif conf['engine'] == 'redis':
conf['n_shards'] = para['n_shards']
if conf['engine'] == 'redis':
assert conf['n_shards'] == 1, "pybench only supports one redis shard at this time"
return conf
def before(self):
conf = self.conf(0)
# build index
if conf['rebuild_index'] is True:
if conf['index_builder'] == "PyBench":
client = create_client(conf['engine'])
client.build_index(conf['line_doc_path'], conf['doc_count'])
elif conf['index_builder'] == "RediSearchBenchmark":
rs_bench_go.update_address(conf)
rs_bench_go.build_index(n_shards=conf['n_shards'],
n_hosts=conf['n_hosts'],
engine=conf['engine'],
start_port=conf['start_port'],
host=conf['host'])
else:
raise NotImplementedError
def beforeEach(self, conf):
print "Query Source", conf['query_source']
self.query_pool = QueryPool(conf['query_source'], conf['query_count'])
self.starttime = datetime.datetime.now()
def treatment(self, conf):
p = Pool(conf['n_clients'])
p.map(worker_wrapper, [
(self.query_pool, conf['query_count'], conf['engine']) for _ in range(conf['n_clients'])
])
def afterEach(self, conf):
self.endtime = datetime.datetime.now()
duration = (self.endtime - self.starttime).total_seconds()
print "Duration:", duration
query_per_sec = conf['n_clients'] * conf['query_count'] / duration
print "Query per second:", query_per_sec
d = {
"duration": duration,
"query_per_sec": query_per_sec,
}
d.update(conf)
perf_path = os.path.join(self._subexpdir, "perf.txt")
print 'writing to', perf_path
helpers.table_to_file([d], perf_path, width=0)
config_path = os.path.join(self._subexpdir, "config.json")
helpers.dump_json(conf, config_path)
def main():
exp = ExperimentEsRs()
exp.main()
if __name__ == '__main__':
main()
|
def count_inversion(A, low, high):
inv_count = 0
if high > low:
mid = (low + high) / 2
inv_count = count_inversion(A, low, mid)
inv_count += count_inversion(A, mid + 1, high)
inv_count += merge_inversion(A, low, mid, high)
return inv_count
def merge_inversion(A, low, mid, high):
n1 = mid - low + 1
n2 = high - mid
# initialise temp list
left = [0] * n1
right = [0] * n2
# copy value from original list
for i in range(0, n1):
left[i] = A[low + i]
for i in range(0, n2):
right[i] = A[mid + 1 + i]
i = 0 # index of left list
j = 0 # index of right list
k = low # index of original list
count = 0
while i < n1 and j < n2:
if left[i] < right[j]:
A[k] = left[i]
i += 1
else:
A[k] = right[j]
j += 1
count += (n1 - i)
k += 1
while i < n1:
A[k] = left[i]
i += 1
k += 1
while j < n2:
A[k] = right[j]
j += 1
k += 1
return count
def main():
A = [5, 1, 2, 3, 7, 8, 6, 4]
n = len(A)
print "Original Array"
for i in range(n):
print("%d " % A[i]),
print '\n'
inversion = count_inversion(A, 0, n - 1)
print inversion
if __name__ == "__main__":
main()
|
__author__ = 'Marie Hoffmann ozymandiaz147@googlemail.com'
import timeit
import numpy as np
# idea 1: sort [(a_i, p_i), key=p], runtime: O(nlogn), space: O(n)
# A array of elements to permute, P index mapping
def permuteArray(A, P):
AP = zip(A, P)
AP.sort(key=lambda ap: ap[1])
return [ap[0] for ap in AP]
# idea 2: apply mapping and store in new array: runtime O(n), space: O(n)
def permuteArray2(A, P):
A_new = [None for _ in range(len(A))]
for i in range(len(A)):
A_new[P[i]] = A[i]
return A_new
# idea 3: apply permutation iteratively in-place, i.e. copy A[i] to A[P[i]] together with P[i] to P[P[i]],
# save former A[P[i]] and P[P[i]] and apply moving in next round, since P is permutation each address i is used once
# runtime: O(n), space: O(1)
def permuteArray3(A, P):
a = A[0]
p = P[0]
j = 0
for i in range(len(A)):
while p == P[p] and j < len(A)-1:
j += 1
p = P[j]
a = A[j]
a_next = A[p]
p_next = P[p]
A[p] = a
P[p] = p
a = a_next
p = p_next
#return A
A = [chr(i) for i in range(97,97+26)]
P = np.random.permutation(len(A))
start = timeit.default_timer()
B = permuteArray(A, P)
stop = timeit.default_timer()
print "permute array with sorting: ", stop - start
print B
start = timeit.default_timer()
B = permuteArray2(A, P)
stop = timeit.default_timer()
print "permute array with copying to 2nd array: ", stop - start
print B
start = timeit.default_timer()
permuteArray3(A, P)
stop = timeit.default_timer()
print "permute array with cycling copying: ", stop - start
print A
|
import pytest
from lightbus import commands
pytestmark = pytest.mark.unit
def test_commands_run():
"""make sure the arg parser is vaguely happy"""
args = commands.parse_args(args=['run'])
commands.command_run(args, dry_run=True)
|
def readInput():
n, p = [int(i) for i in input().split()]
arr = [None] * n
for i in range(n):
arr[i] = ([int(x) for x in input().split()])
arr[i].append(i + 1)
return n, arr
def getSol(n, arr):
count, h = 0, 0
sol = []
lastColor = -1
for x in arr:
if lastColor == -1:
lastColor = x[1]
count += 1
h += x[0]
sol.append(x)
else:
if lastColor != x[1]:
count += 1
h += x[0]
sol.append(x)
lastColor = x[1]
return count, h, sol
def driveCode():
n, arr = readInput()
arr = sorted(arr, key = lambda x: x[0], reverse = True)
count, h, sol = getSol(n, arr)
print(count, end=' ')
print(h)
for x in sol:
print(x[2], end=' ')
driveCode()
|
menu_name = "File browser"
from ui import PathPicker, Printer
import os
callback = None
i = None
o = None
def init_app(input, output):
global callback, i, o
i = input; o = output
callback = browse
def print_path(path):
if os.path.isdir(path):
Printer("Dir: {}".format(path), i, o, 5)
elif os.path.isfile(path):
Printer("File: {}".format(path), i, o, 5)
else:
Printer("WTF: {}".format(path), i, o, 5) # ;-P
def browse():
#"File options" menu yet to be added
path_picker = PathPicker("/", i, o, callback=print_path)
path_picker.activate()
|
from unittest import TestCase
from unittest.mock import patch
import app
class AppTest(TestCase):
def test_print_header(self):
expected = '----------------------\n Password Validation \n----------------------\n'
with patch('builtins.print') as mocked_print:
app.print_header()
mocked_print.assert_called_with(expected)
def test_get_password(self):
expected_input = 'What is the password? '
expected_password = '12345'
with patch('builtins.input') as mocked_input:
mocked_input.side_effect = ('','12345')
password = app.get_password()
mocked_input.assert_called_with(expected_input)
self.assertEqual(password, expected_password)
def test_check_password(self):
# unit test
invalid_password = '12345'
valid_password = 'abc$123'
is_valid = app.get_is_password_valid(invalid_password)
self.assertEqual(False, is_valid)
is_valid = app.get_is_password_valid(valid_password)
self.assertEqual(True, is_valid)
def test_print_message(self):
expected_invalid = 'I dont\'t know you'
expected_valid = 'Welcome!'
with patch('builtins.print') as mocked_print:
app.print_message('12345')
mocked_print.assert_called_with(expected_invalid)
app.print_message('abc$123')
mocked_print.assert_called_with(expected_valid) |
from flask import Flask, session, redirect, url_for, escape, request, render_template, jsonify, json
from flaskext.mysql import MySQL
from yahoo_finance import Share
from lxml import html
import requests
from exceptions import ValueError
import json
from collections import OrderedDict
mysql = MySQL()
app = Flask(__name__)
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = '24singh96'
app.config['MYSQL_DATABASE_DB'] = 'login'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
app = Flask(__name__)
company_symbol = ['AAPL', 'GOOGL', 'MSFT', 'CSCO', 'INTC', 'AMZN', 'VOD', 'QCOM', 'EBAY', 'INFY', 'DVMT', 'FB', 'CBS',
'BBRY', 'AGNC', 'NVDA', 'TXN', 'SBUX', 'NFLX', 'ADBE', 'TSLA', 'CERN', 'EA', 'WDC', 'HPQ', 'ATVI',
'TMUS', 'MAT', 'FOXA', 'CTSH', 'DISCA', 'PYPL', 'GPRO', 'CTXS']
company_name = ['Apple Inc.', 'Google Inc.', 'Microsoft Corporation', 'Cisco Systems', 'Intel Corporation',
'Amazon.com Inc', 'Vodafone Group Plc', 'Qualcomm, Inc.', 'eBay Inc.', 'Infosys Technologies Limited',
'Dell Inc.', 'Facebook, Inc.', 'CBSAdvisor, Inc.', 'BlackBerry Limited', 'American Capital Agency',
'NVIDIA Corporation', 'Texas Instruments Incorporated', 'Starbucks Corporation', 'Netflix, Inc.',
'Adobe Systems Incorporated', 'Tesla, Inc.', 'Marriott International', 'Electronic Arts Inc.',
'Western Digital Corporation', 'Hewlett-Packard Co.', 'Activision Blizzard Inc.', 'T-Mobile US',
'Mattel Inc', '21st Century Fox Class A', 'Cognizant Technology', 'Discovery Communications Inc.',
'Paypal Holdings Inc', 'GoPro, Inc.', 'Citrix Systems, Inc.']
google_links = ['https://www.google.com/finance?q=NASDAQ%3AAAPL&ei=LKiZWejREcOvuATThbuACQ',
'https://www.google.com/finance?q=NASDAQ%3AGOOGL&ei=hqiZWfGDONGkuASQ7oUg',
'https://www.google.com/finance?q=NASDAQ%3AMSFT&ei=nKiZWdipLtG8uQSv6IUQ',
'https://www.google.com/finance?q=NASDAQ%3ACSCO&ei=waiZWaiZD9KqugSFtKLICg',
'https://www.google.com/finance?q=NASDAQ%3AINTC&ei=5KiZWbHFN9GkuASQ7oUg',
'https://www.google.com/finance?q=NASDAQ%3AAMZN&ei=DKmZWbHYB4rBugSfhozIDg',
'https://www.google.com/finance?q=NASDAQ%3AVOD&ei=KKmZWfnOLI67ugS8vYeQBw',
'https://www.google.com/finance?q=NASDAQ%3AQCOM&ei=SKmZWYm1JYyKuwSZ7azoCAV',
'https://www.google.com/finance?q=NASDAQ%3AEBAY&ei=WamZWfDmF4fCuASxrJawBQ',
'https://www.google.com/finance?q=NYSE%3AINFY&ei=j6mZWbjvNtOouAS4h7_QAw',
'https://www.google.com/finance?q=NYSE%3ADVMT&ei=p6mZWcCuL4GtuAScnZT4CQ',
'https://www.google.com/finance?q=NASDAQ%3AFB&ei=wamZWdCMAYWtugSnu42QCA',
'https://www.google.com/finance?q=NASDAQ%3ACBS&ei=3amZWaGHCN2-uwSkyKB4',
'https://www.google.com/finance?q=NASDAQ%3ABBRY&ei=_KmZWYCXIsOvuATThbuACQ',
'https://finance.google.com/finance?q=NYSE:AGNC',
'https://www.google.com/finance?q=NASDAQ%3ANVDA&ei=HqqZWaDoO9G8uQSv6IUQ',
'https://www.google.com/finance?q=NASDAQ%3ATXN&ei=M6qZWZn3KcjRuATVkbaYDA',
'https://www.google.com/finance?q=NASDAQ%3ASBUX&ei=TKqZWaDlPNGkuASQ7oUg',
'https://www.google.com/finance?q=NASDAQ%3ANFLX&ei=XKqZWYi-IoGtuAScnZT4CQ',
'https://www.google.com/finance?q=NASDAQ%3AADBE&ei=caqZWcmXGszMuATmi4SwBA',
'https://www.google.com/finance?q=NASDAQ%3ATSLA&ei=gaqZWaiVOs6ruAS6yYTADg',
'https://www.google.com/finance?q=NASDAQ%3ACERN&ei=kKqZWcDqG4i6uQSOvrqYDA',
'https://www.google.com/finance?q=NASDAQ%3AEA&ei=o6qZWbjeEt2-uwSkyKB4',
'https://www.google.com/finance?q=NASDAQ%3AWDC&ei=uqqZWfGYMYrBugSfhozIDg',
'https://finance.google.com/finance?q=NYSE:HPQ',
'https://www.google.com/finance?q=NASDAQ%3AATVI&ei=66qZWdiAEsejugTW54WoCg',
'https://www.google.com/finance?q=NASDAQ%3ATMUS&ei=C6uZWZCPFYbOuATGs5DQDA',
'https://www.google.com/finance?q=NASDAQ%3AMAT&ei=HKuZWYnoFJKQuQS13q-QAw',
'https://www.google.com/finance?q=NASDAQ%3AFOXA&ei=LKuZWYnKHsejugTW54WoCg',
'https://www.google.com/finance?q=NASDAQ%3ACTSH&ei=QquZWeCVGIfCuASxrJawBQ',
'https://www.google.com/finance?q=NASDAQ%3ADISCA&ei=T6uZWYmkAdOouAS4h7_QAw',
'https://www.google.com/finance?q=NASDAQ%3APYPL&ei=c6uZWfrSAYbguQTQsrP4Dw',
'https://www.google.com/finance?q=NASDAQ%3AGPRO&ei=gKuZWfmiEYi6uQSOvrqYDA',
'https://www.google.com/finance?q=NASDAQ%3ACTXS&ei=j6uZWcDzGMvSuASc2b7ICw']
def load_portfolio():
conn = mysql.connect()
cur = conn.cursor()
if 'username' in session:
username = session['username']
cur.execute("SELECT * FROM user WHERE username = %s", username)
userdetails = [dict(
id=row[0],
username=row[5],
password=row[6],
stock=row[7],
purse=row[8],
playervalue=row[9]
) for row in cur.fetchall()]
return userdetails
@app.route('/login', methods=['GET', 'POST'])
def login():
print "login"
error = ""
if request.method == 'POST':
username_form = request.form['username']
password_form = request.form['password']
conn = mysql.connect()
cur = conn.cursor()
cur.execute("SELECT COUNT(1) FROM user WHERE username = %s;", [username_form]) # CHECKS IF USERNAME EXSIST
if cur.fetchone()[0]:
cur.execute("SELECT password FROM user WHERE username = %s;", [username_form])
for row in cur.fetchall():
if password_form == row[0]:
cur.execute("SELECT * FROM user WHERE username = %s", [username_form])
userdetails = [dict(
id=row[0],
username=row[5],
password=row[6],
stock=row[7],
purse=row[8],
playervalue=row[9]
) for row in cur.fetchall()]
session['username'] = request.form['username']
currentownership = getcurrentstock()
print session['username']
print userdetails,currentownership
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
else:
error = "Invalid credential"
else:
error = "Invalid Credential"
conn.commit()
return render_template('index.html', error=error)
@app.route('/', methods=['GET', 'POST'])
def hello_world():
print "index"
error = ""
if 'username' in session:
username_form = session['username']
print "username is "+username_form
conn = mysql.connect()
cur = conn.cursor()
cur.execute("SELECT * FROM user WHERE username = %s", [username_form])
userdetails = [dict(
id=row[0],
username=row[5],
password=row[6],
stock=row[7],
purse=row[8],
playervalue=row[9]
) for row in cur.fetchall()]
currentownership = getcurrentstock()
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
if request.method == 'POST':
username_form = request.form['username']
password_form = request.form['password']
conn = mysql.connect()
cur = conn.cursor()
cur.execute("SELECT COUNT(1) FROM user WHERE username = %s;", [username_form]) # CHECKS IF USERNAME EXSIST
if cur.fetchone()[0]:
cur.execute("SELECT password FROM user WHERE username = %s;", [username_form])
for row in cur.fetchall():
if password_form == row[0]:
cur.execute("SELECT * FROM user WHERE username = %s", [username_form])
userdetails = [dict(
id=row[0],
username=row[5],
password=row[6],
stock=row[7],
purse=row[8],
playervalue=row[9]
) for row in cur.fetchall()]
session['username'] = request.form['username']
currentownership = getcurrentstock()
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
else:
error = "Invalid credential"
else:
error = "Invalid Credential"
conn.commit()
return render_template('index.html', error=error)
def getcurrentstock():
conn = mysql.connect()
cur = conn.cursor()
if 'username' in session:
username = session['username']
print "username is "+username
cur.execute("SELECT * FROM user WHERE username = %s", [username])
for row in cur.fetchall():
print row
newarray = row[7].split(',')
stocks = []
j = 0
k=0
for i in newarray:
if i != '0' :
stocks.append([])
stocks[k].append(i)
stocks[k].append(j)
k = k+1
j = j + 1
currentownership = [dict(
stock=row[0],
name=company_name[row[1]],
symbol=company_symbol[row[1]]
) for row in stocks]
updateleaderboard()
return currentownership
@app.route('/signup', methods=['GET', 'POST'])
def sign_up():
print "sign up"
error = ""
if 'username' in session:
return "User already exists with username "+session['username']
if request.method == 'POST':
print "sign up post"
Signupuser = request.form['signupusername']
Signuppass = request.form['signuppassword']
Signupname = request.form['signupname']
Signupreg = request.form['signupreg']
Signupmob = request.form['signupmob']
Signupcol = request.form['signupcol']
conn = mysql.connect()
cur = conn.cursor()
cur.execute("SELECT COUNT(1) FROM user WHERE username = %s;", [Signupuser]) # CHECKS IF USERNAME EXSIST
if cur.fetchone()[0]:
error = "Incorrect Credentials"
return render_template('signup.html', error=error)
#cur.execute("SELECT password FROM user WHERE username = %s;", [Signupuser])
#for row in cur.fetchall():
# for lol in row:
# if Signuppass == lol:
temp = "insert into user(name,regno,college,mobileno,username,password,stock,purse,playervalue) values (\""+Signupname+"\",\""+Signupreg+"\",\""+Signupmob+"\",\""+Signupcol+"\",\""+Signupuser+"\",\""+Signuppass+"\",\"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\",100000,10000);"
print temp
conn = mysql.connect()
cur = conn.cursor()
cur.execute(temp)
conn.commit()
cur.execute("SELECT * FROM user WHERE username = %s", [Signupuser])
userdetails = [dict(
id=row[0],
username=row[5],
password=row[6],
stock=row[7],
purse=row[8],
playervalue=row[9]
) for row in cur.fetchall()]
session['username'] = request.form['signupusername']
currentownership = getcurrentstock()
if currentownership == "" :
print "currentownership"
return render_template('portfolio.html', userdetails=userdetails)
return render_template('portfolio.html',userdetails=userdetails, currentownership=currentownership)
return render_template('signup.html',error=error)
@app.route('/NYSE', methods=['GET', 'POST'])
def NYSE():
companystock = [dict(
name = company_name[k],
symbol = company_symbol[k]
) for k in range(0,33)]
return render_template('NYSE.html', companystock=companystock)
def updateleaderboard():
conn = mysql.connect()
cur = conn.cursor()
cur.execute("SELECT username FROM user ORDER BY purse DESC")
names = []
player = []
for row in cur.fetchall():
for i in row:
temp = "SELECT stock FROM user WHERE username = \"" + str(i) + "\";"
cur.execute("SELECT stock FROM user WHERE username = %s;", [i])
print temp
for row in cur.fetchall():
for lol in row:
userstock = lol.split(',')
cur.execute("SELECT stock from stock");
userstockprice = []
for row in cur.fetchall():
for lol in row:
userstockprice.append(lol)
playerval = 0
cur.execute("SELECT purse FROM user WHERE username = %s;", [i])
for row in cur.fetchall():
for lol in row:
playerval += float(lol)
for j in range(0, 33):
playerval += float(userstock[j]) * float(userstockprice[j])
cur.execute("update user set playervalue = \"" + str(playerval) + "\"WHERE username = %s;", [i])
conn.commit()
@app.route('/leaderboard', methods=['GET', 'POST'])
def leaderboard():
conn = mysql.connect()
cur = conn.cursor()
cur.execute("SELECT username FROM user ORDER BY purse DESC")
names=[]
player=[]
for row in cur.fetchall():
for i in row:
temp="SELECT stock FROM user WHERE username = \""+str(i)+"\";"
cur.execute("SELECT stock FROM user WHERE username = %s;", [i])
print temp
for row in cur.fetchall():
for lol in row:
userstock = lol.split(',')
cur.execute("SELECT stock from stock");
userstockprice = []
for row in cur.fetchall():
for lol in row:
userstockprice.append(lol)
playerval = 0
cur.execute("SELECT purse FROM user WHERE username = %s;", [i])
for row in cur.fetchall():
for lol in row:
playerval+=float(lol)
for j in range(0,33):
playerval+=float(userstock[j])*float(userstockprice[j])
cur.execute("update user set playervalue = \""+str(playerval)+"\"WHERE username = %s;", [i])
conn.commit()
i=0
cur.execute("SELECT playervalue FROM user ORDER BY playervalue DESC limit 10")
for row in cur.fetchall():
for lol in row:
player.append(lol)
i=i+1
cur.execute("SELECT username FROM user ORDER BY playervalue DESC limit 10")
for row in cur.fetchall():
for lol in row:
names.append(lol)
print player
userstock = [dict(
name=names[j],
playerval=player[j],
)for j in range(0,i)]
return render_template('leaderboard.html',userstock=userstock)
@app.route('/AAPL', methods=['GET', 'POST'])
def AAPL():
companystock,stock,purse,currentstock = getStock2('AAPL')
error = ""
if request.method == 'POST':
error=makechanges('AAPL',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/GOOGL', methods=['GET', 'POST'])
def GOOGL():
companystock,stock,purse,currentstock = getStock2('GOOGL')
error = ""
if request.method == 'POST':
error=makechanges('GOOGL',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/MSFT', methods=['GET', 'POST'])
def MSFT():
companystock,stock,purse,currentstock = getStock2('MSFT')
error = ""
if request.method == 'POST':
error=makechanges('MSFT',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/CSCO', methods=['GET', 'POST'])
def CSCO():
companystock,stock,purse,currentstock = getStock2('CSCO')
error = ""
if request.method == 'POST':
error=makechanges('CSCO',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/INTC', methods=['GET', 'POST'])
def INTC():
companystock,stock,purse,currentstock = getStock2('INTC')
error = ""
if request.method == 'POST':
error=makechanges('INTC',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/AMZN', methods=['GET', 'POST'])
def AMZN():
companystock,stock,purse,currentstock = getStock2('AMZN')
error = ""
if request.method == 'POST':
error=makechanges('AMZN',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/VOD', methods=['GET', 'POST'])
def VOD():
companystock,stock,purse,currentstock = getStock2('VOD')
error = ""
if request.method == 'POST':
#print "hello"
error=makechanges('VOD',stock)
#print "whatff"
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/QCOM', methods=['GET', 'POST'])
def QCOM():
companystock,stock,purse,currentstock = getStock2('QCOM')
error = ""
if request.method == 'POST':
error=makechanges('QCOM',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/INFY', methods=['GET', 'POST'])
def INFY():
companystock,stock,purse,currentstock = getStock2('INFY')
error = ""
if request.method == 'POST':
error=makechanges('INFY',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/DVMT', methods=['GET', 'POST'])
def DVMT():
companystock,stock,purse,currentstock = getStock2('DVMT')
error = ""
if request.method == 'POST':
error=makechanges('DVMT',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/FB', methods=['GET', 'POST'])
def FB():
companystock,stock,purse,currentstock = getStock2('FB')
error = ""
if request.method == 'POST':
error=makechanges('FB',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/CBS', methods=['GET', 'POST'])
def CBS():
companystock,stock,purse,currentstock = getStock2('CBS')
error = ""
if request.method == 'POST':
error=makechanges('CBS',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/BBRY', methods=['GET', 'POST'])
def BBRY():
companystock,stock,purse,currentstock = getStock2('BBRY')
error = ""
if request.method == 'POST':
error=makechanges('BBRY',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/AGNC', methods=['GET', 'POST'])
def PBYI():
companystock,stock,purse,currentstock = getStock2('AGNC')
error = ""
if request.method == 'POST':
error=makechanges('AGNC',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/NVDA', methods=['GET', 'POST'])
def NVDA():
companystock,stock,purse,currentstock = getStock2('NVDA')
error = ""
if request.method == 'POST':
error=makechanges('NVDA',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/TXN', methods=['GET', 'POST'])
def TXN():
companystock,stock,purse,currentstock = getStock2('TXN')
error = ""
if request.method == 'POST':
error=makechanges('TXN',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/SBUX', methods=['GET', 'POST'])
def SBUX():
companystock,stock,purse,currentstock = getStock2('SBUX')
error = ""
if request.method == 'POST':
error=makechanges('SBUX',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/NFLX', methods=['GET', 'POST'])
def NFLX():
companystock,stock,purse,currentstock = getStock2('NFLX')
error = ""
if request.method == 'POST':
error=makechanges('NFLX',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/EBAY', methods=['GET', 'POST'])
def EBAY():
companystock,stock,purse,currentstock = getStock2('EBAY')
error = ""
if request.method == 'POST':
error=makechanges('EBAY',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/ADBE', methods=['GET', 'POST'])
def ADBE():
companystock,stock,purse,currentstock = getStock2('ADBE')
error = ""
if request.method == 'POST':
error=makechanges('ADBE',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/TSLA', methods=['GET', 'POST'])
def TSLA():
companystock,stock,purse,currentstock = getStock2('TSLA')
error = ""
if request.method == 'POST':
error=makechanges('TSLA',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/CERN', methods=['GET', 'POST'])
def CERN():
companystock,stock,purse,currentstock = getStock2('CERN')
error = ""
if request.method == 'POST':
error=makechanges('CERN',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/EA', methods=['GET', 'POST'])
def EA():
companystock,stock,purse,currentstock = getStock2('EA')
error = ""
if request.method == 'POST':
error=makechanges('EA',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/WDC', methods=['GET', 'POST'])
def WDC():
companystock,stock,purse,currentstock = getStock2('WDC')
error = ""
if request.method == 'POST':
error=makechanges('WDC',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/HPQ', methods=['GET', 'POST'])
def ADSK():
companystock,stock,purse,currentstock = getStock2('HPQ')
error = ""
if request.method == 'POST':
error=makechanges('ADSK',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/ATVI', methods=['GET', 'POST'])
def ATVI():
companystock,stock,purse,currentstock = getStock2('ATVI')
error = ""
if request.method == 'POST':
error=makechanges('ATVI',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/TMUS', methods=['GET', 'POST'])
def TMUS():
companystock,stock,purse,currentstock = getStock2('TMUS')
error = ""
if request.method == 'POST':
error=makechanges('TMUS',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/MAT', methods=['GET', 'POST'])
def MAT():
companystock,stock,purse,currentstock = getStock2('MAT')
error = ""
if request.method == 'POST':
error=makechanges('MAT',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/FOXA', methods=['GET', 'POST'])
def FOXA():
companystock,stock,purse,currentstock = getStock2('FOXA')
error = ""
if request.method == 'POST':
error=makechanges('FOXA',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/CTSH', methods=['GET', 'POST'])
def CTSH():
companystock,stock,purse,currentstock = getStock2('CTSH')
error = ""
if request.method == 'POST':
error=makechanges('CTSH',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/DISCA', methods=['GET', 'POST'])
def DISCA():
companystock,stock,purse,currentstock = getStock2('DISCA')
error = ""
if request.method == 'POST':
error=makechanges('DISCA',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/PYPL', methods=['GET', 'POST'])
def PYPL():
companystock,stock,purse,currentstock = getStock2('PYPL')
error = ""
if request.method == 'POST':
error=makechanges('PYPL',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/GPRO', methods=['GET', 'POST'])
def GPRO():
companystock,stock,purse,currentstock = getStock2('GPRO')
error = ""
if request.method == 'POST':
error=makechanges('GPRO',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
@app.route('/CTXS', methods=['GET', 'POST'])
def CTXS():
companystock,stock,purse,currentstock = getStock2('CTXS')
error = ""
if request.method == 'POST':
error=makechanges('CTXS',stock)
userdetails = load_portfolio()
currentownership=getcurrentstock()
if error != "":
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
return render_template('portfolio.html', userdetails=userdetails, currentownership=currentownership)
print companystock
return render_template('company.html', companystock=companystock , purse=purse, currentstock=currentstock,error=error)
def getStock(name_of_company):
global company_name,company_symbol
stock = []
k=0
stock.append([])
stock.append("NA")
stock.append("NA")
stock.append("NA")
stock.append("NA")
stock.append("NA")
stock.append("NA")
stock.append("NA")
j=0
for i in company_symbol:
if i == name_of_company:
break
j=j+1
print "j is "+str(j)+"link is "
stock[0]=company_name[j]
yahoo = Share(name_of_company)
stock[1] = yahoo.get_open()
stock[2] = yahoo.get_price()
stock[3] = yahoo.get_trade_datetime()
stock[4] = company_symbol[j]
stock[5] = yahoo.get_volume()
stock[6] = yahoo.get_dividend_yield()
stock[7] = google_links[j]
print stock
conn = mysql.connect()
cur = conn.cursor()
if 'username' in session:
username = session['username']
cur.execute("SELECT purse FROM user WHERE username = %s;", [username])
print username
for row in cur.fetchall():
for lol in row:
purse=lol
companystock = [dict(
name=stock[0],
open=stock[1],
lasttradeprice=stock[2],
lasttradetime=stock[3],
stocksymbol=stock[4],
MarketCapital=stock[5],
dividend=stock[6],
link=stock[7]
)]
cur.execute("SELECT stock FROM user WHERE username = %s;", [username])
print username
for row in cur.fetchall():
for lol in row:
newarray = lol.split(',')
currentstock = newarray[j]
print purse
return companystock,stock,purse,currentstock
def parse(ticker):
url = "http://finance.yahoo.com/quote/%s?p=%s" % (ticker, ticker)
response = requests.get(url)
print "Parsing %s" % (url)
parser = html.fromstring(response.text)
summary_table = parser.xpath('//div[contains(@data-test,"summary-table")]//tr')
summary_data = OrderedDict()
other_details_json_link = "https://query2.finance.yahoo.com/v10/finance/quoteSummary/{0}?formatted=true&lang=en-US®ion=US&modules=summaryProfile%2CfinancialData%2CrecommendationTrend%2CupgradeDowngradeHistory%2Cearnings%2CdefaultKeyStatistics%2CcalendarEvents&corsDomain=finance.yahoo.com".format(
ticker)
summary_json_response = requests.get(other_details_json_link)
financialData =[]
financialData.append([])
financialData.append("NA")
financialData.append("NA")
financialData.append("NA")
financialData.append("NA")
financialData.append("NA")
financialData.append("NA")
try:
json_loaded_summary = json.loads(summary_json_response.text)
financialData[0] = json_loaded_summary["quoteSummary"]["result"][0]["financialData"]["targetMeanPrice"]['raw']
financialData[1] = json_loaded_summary["quoteSummary"]["result"][0]["financialData"]["currentPrice"]['raw']
financialData[2] =json_loaded_summary["quoteSummary"]["result"][0]["financialData"]["totalRevenue"]['fmt']
financialData[3] = ticker
financialData[4] = url
earnings_list = json_loaded_summary["quoteSummary"]["result"][0]["calendarEvents"]['earnings']
eps = json_loaded_summary["quoteSummary"]["result"][0]["defaultKeyStatistics"]["trailingEps"]['raw']
financialData[5] = eps
return financialData
except ValueError:
print "Failed to parse json response"
return {"error": "Failed to parse json response"}
def getStock2(ticker):
financial_data=parse(ticker)
j = 0
for i in company_symbol:
if i == ticker:
break
j = j + 1
conn = mysql.connect()
cur = conn.cursor()
temp = "update stock set stock = \"" + str(financial_data[1]) + "\" where name = \"" + str(j) + "\";"
cur.execute(temp)
print temp
conn.commit()
print "j is " + str(j) + "link is "
stock = []
stock.append([])
stock.append("NA")
stock.append("NA")
stock.append("NA")
stock.append("NA")
stock.append("NA")
stock.append("NA")
stock.append("NA")
stock.append("NA")
stock[0] = company_name[j]
stock[1] = financial_data[0]
stock[2] = financial_data[1]
stock[3] = financial_data[2]
stock[4] = financial_data[3]
stock[5] = financial_data[4]
stock[6] = financial_data[5]
stock[7] = google_links[j]
conn = mysql.connect()
cur = conn.cursor()
if 'username' in session:
username = session['username']
cur.execute("SELECT purse FROM user WHERE username = %s;", [username])
#print username
for row in cur.fetchall():
for lol in row:
purse = lol
companystock = [dict(
name=stock[0],
targetest=stock[1],
currentprice=stock[2],
totalrevenue=stock[3],
stocksymbol=stock[4],
url=stock[5],
eps=stock[6],
link=stock[7]
)]
cur.execute("SELECT stock FROM user WHERE username = %s;", [username])
#print username
for row in cur.fetchall():
for lol in row:
newarray = lol.split(',')
currentstock = newarray[j]
return companystock, stock, purse, currentstock
def makechanges(name_of_company,company2):
error = ""
stock = request.form['stockbuy']
stocksell = request.form['stocksell']
conn = mysql.connect()
cur = conn.cursor()
if 'username' in session:
username = session['username']
cur.execute("SELECT stock FROM user WHERE username = %s;", [username])
for row in cur.fetchall():
for lol in row:
newarray=lol.split(',')
print newarray
j=0
for i in company_symbol:
if i == name_of_company:
break
j=j+1
print j
if stocksell != "":
currentownership = int(newarray[j])
stocksell = convertnum(stocksell)
currentownership = currentownership - int(stocksell)
if currentownership >=0 :
currentownership = str(currentownership)
newarray[j] = currentownership
temp2 = ""
for i in newarray:
temp2 += i + ","
temp2 = temp2[:-1]
temp = "update user set stock = \"" + temp2 + "\" where username = \"" + username + "\";"
cur.execute(temp)
conn.commit()
cur.execute("SELECT purse FROM user WHERE username = %s;", [username])
for row in cur.fetchall():
for temp in row:
currency = float(temp)
print currency
#company = convertnum(company[2])
print company2[2]
company = float(company2[2])
currency = currency + float(stocksell) * company
currency = str(currency)
temp = "update user set purse = \"" + currency + "\" where username = \"" + username + "\";"
print temp
cur.execute(temp)
conn.commit()
else :
error = "Not Enough Stocks To Sell !"
if stock != "":
cur.execute("SELECT purse FROM user WHERE username = %s;", [username])
for row in cur.fetchall():
for temp in row:
currency = float(temp)
print currency
#company = convertnum(company[2])
#print company[2]
company = float(company2[2])
currency = currency - float(stock) * company
if currency > 0:
currency = str(currency)
temp = "update user set purse = \"" + currency + "\" where username = \"" + username + "\";"
print temp
cur.execute(temp)
conn.commit()
currentownership = int(newarray[j])
#stock = convertnum(stock)
currentownership = currentownership + int(stock)
currentownership = str(currentownership)
newarray[j] = currentownership
temp2 = ""
for i in newarray:
temp2 += i + ","
temp2 = temp2[:-1]
temp = "update user set stock = \"" + temp2 + "\" where username = \"" + username + "\";"
cur.execute(temp)
conn.commit()
j = 0
else :
error = "You don't have enough money !"
updateleaderboard()
return error
def updatestocks():
for j in range(0,33):
financial_data = parse(company_symbol[j])
conn = mysql.connect()
cur = conn.cursor()
temp = "update stock set stock = \""+str(financial_data[1])+"\" where name = \""+str(j)+"\";"
cur.execute(temp)
print temp
conn.commit()
def convertnum(stockvalue):
temp = ""
for num in stockvalue:
if(num != ','):
temp+=num
return temp
if __name__ == '__main__':
app.config['SESSION_TYPE'] = 'memcached'
app.config['SECRET_KEY'] = 'super secret key'
app.run()
|
from django import forms
from django.forms import ModelForm
from django.core.exceptions import ValidationError
from campaigns.models import *
from django.forms.extras.widgets import SelectDateWidget
class CreateForm(ModelForm):
start= forms.DateField(initial=datetime.date.today,widget=SelectDateWidget)
end = forms.DateField(initial=datetime.date.today,widget=SelectDateWidget)
time = forms.TimeField(widget=forms.TimeInput(format='%H:%M'))
choices = forms.ChoiceField(choices = ([('monthly','monthly'), ('yearly','yearly'), ]))
class Meta:
model = FixedEmail
fields = ['subject','content','option','start','end','time','choices']
def __init__(self, *args, **kwargs):
super(CreateForm, self).__init__(*args, **kwargs)
class RelativeStartForm(ModelForm):
confirm_email = forms.EmailField(
label="Confirm email",
required=True,
)
class Meta:
model = Subscriber
fields = ['name','email_address','confirm_email']
def __init__(self, *args, **kwargs):
if kwargs.get('instance'):
email = kwargs['instance'].email
kwargs.setdefault('initial', {})['confirm_email'] = email
return super(RelativeStartForm, self).__init__(*args, **kwargs)
def clean(self):
cleaned_data = super(RelativeStartForm,self).clean()
if (cleaned_data.get('email_address') !=
cleaned_data.get('confirm_email')):
raise ValidationError("Email addresses must match.")
return cleaned_data
class DeadlineForm(ModelForm):
confirm_email = forms.EmailField(
label = "Confirm email",
required = True,
)
def __init__(self, *args, **kwargs):
campaign = kwargs.pop('campaign',None)
super(DeadlineForm, self).__init__(*args, **kwargs)
self.fields['options']= forms.ModelMultipleChoiceField(
required=False,
queryset = DeadlineOption.objects.filter(required=False,campaign=campaign),
widget=OptionsWidget(
fields=('description',),
)
)
self.fields['deadline'].required = True
self.fields['deadline'].widget = SelectDateWidget()
self.fields['name'].widget.attrs['autofocus'] = u'autofcous'
class Meta:
model = Subscriber
fields = ['name','email_address','confirm_email','deadline']
def clean(self):
cleaned_data = super(DeadlineForm,self).clean()
if (cleaned_data.get('email_address') !=
cleaned_data.get('confirm_email')):
raise ValidationError("Email addresses must match.")
return cleaned_data
class FixedForm(ModelForm):
confirm_email = forms.EmailField(
label = "Confirm email",
required = True,
)
def __init__(self, *args, **kwargs):
campaign = kwargs.pop('campaign',None)
super(FixedForm, self).__init__(*args, **kwargs)
self.fields['options']= forms.ModelMultipleChoiceField(
queryset = FixedOption.objects.filter(campaign=campaign),
widget=OptionsWidget(
fields=('description',),
)
)
self.fields['name'].widget.attrs['autofocus'] = u'autofcous'
class Meta:
model = Subscriber
fields = ['name','email_address','confirm_email']
def clean(self):
cleaned_data = super(FixedForm,self).clean()
if (cleaned_data.get('email_address') !=
cleaned_data.get('confirm_email')):
raise ValidationError("Email addresses must match.")
return cleaned_data
class OptionsWidget(forms.widgets.SelectMultiple):
def __init__(self, *a, **kw):
self.fields = kw.pop('fields', []) # list of attrs
self.rns = kw.pop('related_null_string', 'Null')
super(OptionsWidget, self).__init__(*a, **kw)
def render(self, name, value, attrs=None, choices=()):
from itertools import chain
from django.forms.widgets import CheckboxInput
from django.utils.encoding import force_unicode
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
if value is None: value = []
has_id = attrs and 'id' in attrs
final_attrs = self.build_attrs(attrs, name=name)
output = []
id_number = 0
# Normalize to strings
str_values = set([force_unicode(v) for v in value])
for i, (option_value, option_label) in enumerate(chain(self.choices,
choices)):
# If an ID attribute was given, add a numeric index as a suffix,
# so that the checkboxes don't all have the same ID attribute.
if has_id:
final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
label_for = u' for="%s"' % final_attrs['id']
else:
label_for = ''
cb = CheckboxInput(
final_attrs, check_test=lambda value: value in str_values)
option_value = force_unicode(option_value)
rendered_cb = cb.render(name, option_value)
option_label = conditional_escape(force_unicode(option_label))
instance = self.choices.queryset.model.objects.get(id=option_value)
rendered_fields = []
for f in self.fields:
try:
v = getattr(instance, f)
if hasattr(v, 'all'):
v = list(getattr(v, 'all')())
if v:
v = ', '.join([unicode(s) for s in v])
else:
v = self.rns # set to related_null_string
elif isinstance(v, datetime.datetime):
v = v.strftime('%b %d, %Y')
if isinstance(v, bool):
rendered_fields.append(
'<td class="%s"><label><span class="%s">%s</span></label></td>' % (
f, str(v).lower(), str(v).lower() )
)
else:
rendered_fields.append(
'<td class="%s"><label for="id_options_%s">%s</label></td>' % (f, id_number,v))
id_number = id_number + 1
except AttributeError:
rendered_fields.append(
'<td class="%s">None</td>' % f)
output.append('<tr><td class="checkbox">%s</td>%s</tr>'
% (rendered_cb, ''.join(rendered_fields)))
#output.append(u'</table>')
return mark_safe(u'\n'.join(output))
def id_for_label(self, id_):
# See the comment for RadioSelect.id_for_label()
if id_:
id_ += '_0'
return id_
id_for_label = classmethod(id_for_label)
|
from pymongo import MongoClient
import os
import time
import datetime
class AtlasDB:
def __init__(self, season):
self.client = MongoClient(os.environ["PREDICTIZ_CREDENTIALS"])
dblist = self.client.list_database_names()
if "season_" + season in dblist:
#raise IOError("Cette base de donnée existe déjà.")
print("attention, cette base de donnée existe déja, vous avez 5 secondes pour annuler l'opération")
time.sleep(5)
db = self.client["season_" + season]
self.table_team = db["team"]
self.table_player = db["player"]
self.table_game = db["game"]
self.table_player_stats = db["playerStats"]
self.table_history = db["prediction_history"]
print("Atlas MongoDB connected")
def add_team(self, team):
exist = self.table_team.find_one({"nick": team['nick']})
if(exist == None):
self.table_team.insert_one(team)
def add_game(self, game):
visitor = self.table_team.find_one({"nick": game["visitor_nick"]})
home = self.table_team.find_one({"nick": game["home_nick"]})
existing_game = self.table_game.find_one({"csk": game["csk"]})
# Insert in Games
if(existing_game is not None):
stats = self.table_history.find_one({"ide":"games_2021"})
try:
game["home_odd"] = existing_game["home_odd"]
game["visitor_odd"] = existing_game["visitor_odd"]
print("")
except Exception:
print("no odd for this game")
game["home_odd"] = 1
game["visitor_odd"] = 1
try:
home_win = existing_game['home_win_bet']
no_bet = existing_game['no_bet']
visitor_win = existing_game['visitor_win_bet']
game['home_win_bet'] = home_win
game['no_bet'] = no_bet
game['visitor_win_bet'] = visitor_win
balance = 0
games_predicted = 0
games_misspredicted = 0
if(stats != None):
balance = stats["balance"]
games_predicted = stats["games_predicted"]
games_misspredicted = stats["games_misspredicted"]
if(home_win > visitor_win) & (home_win > no_bet):
game['earned'] = -10.0
if(game['winner'] == 1):
balance += 10.0 * game["home_odd"]
games_predicted += 1
game['earned'] += 10.0 * game["home_odd"]
else:
games_misspredicted += 1
balance += -10.0
game['betted'] = 1
elif(visitor_win > home_win) & (visitor_win > no_bet):
game['earned'] = -10.0
if(game['winner'] == 0):
balance += 10.0 * game["visitor_odd"]
games_predicted += 1
game['earned'] += 10.0 * game["visitor_odd"]
else:
games_misspredicted +=1
balance += -10.0
game['betted'] = 0
else:
game['betted'] = -1
game['earned'] = 0
game['earned'] = round(game['earned'],2)
balance = round(balance, 2)
if(stats == None):
self.table_history.insert_one({
"balance":balance,
"games_predicted":games_predicted,
"games_misspredicted":games_misspredicted,
"ide":"games_2021"
})
else:
self.table_history.update_one({"ide":"games_2021"},
{
"$set":{
"balance":balance,
"games_predicted":games_predicted,
"games_misspredicted":games_misspredicted,
}
})
except Exception:
print(Exception, "this game was not predicted")
self.table_game.delete_one({"csk": game["csk"]})
if(visitor is not None) & (home is not None):
game["visitor_id"] = visitor["_id"]
game["home_id"] = home["_id"]
game["home_name"] = home["name"]
game["visitor_name"] = visitor["name"]
retour = self.table_game.insert_one(game)
# Update GamesIds in team
self.table_team.update_one({"nick": game["visitor_nick"]}, {"$push": {"gameIds": retour.inserted_id}})
self.table_team.update_one({"nick": game["home_nick"]}, {"$push": {"gameIds": retour.inserted_id}})
def add_player(self, name):
exist = self.table_player.find_one({"name": name})
if exist is None:
retour = self.table_player.insert_one({"name": name})
return retour.inserted_id
else:
return exist['_id']
def add_player_stats(self, game_csk, player_name, team_name, stats):
team = self.table_team.find_one({"nick": team_name})
game = self.table_game.find_one({"csk": game_csk})
player = self.table_player.find_one({"name": player_name})
if player is None:
player_id = self.add_player(player_name)
# print("PLAYER IS NONE, ADD PLAYER : "+str(player_id))
else:
player_id = player["_id"]
# print("PLAYER IS NOT NONE, get id : "+str(player_id))
if (team is not None) & (game is not None):
# Insert in Player Stats
self.table_player_stats.insert_one(
{"player_id": player_id, "game_id": game["_id"], "team_id": team["_id"], "stats": stats})
# print("stat added To the db")
# Update rosterIds from the team if necessary
roster_ids = team["rosterIds"]
if player_id not in roster_ids:
self.table_team.update_one({"nick": team_name}, {"$push": {"rosterIds": player_id}})
|
# 버스 정류장 고유ID 검색법
'''
how to get stID + 저상버스
1. https://www.data.go.kr/subMain.jsp#/L3B1YnIvcG90L215cC9Jcm9zTXlQYWdlL29wZW5EZXZEZXRhaWxQYWdlJEBeMDgyTTAwMDAxMzBeTTAwMDAxMzUkQF5wdWJsaWNEYXRhRGV0YWlsUGs9dWRkaTozMjA1NjhiNS1jZDBmLTQyODAtOGI5Ny1iZjUxMmYxNWZlNDkkQF5wcmN1c2VSZXFzdFNlcU5vPTg5Njk3ODkkQF5yZXFzdFN0ZXBDb2RlPVNUQ0QwMQ==
getLowStationByNameList에서 정류장이름(한글) 검색
https://www.data.go.kr/subMain.jsp#/L3B1YnIvcG90L215cC9Jcm9zTXlQYWdlL29wZW5EZXZEZXRhaWxQYWdlJEBeMDgyTTAwMDAxMzBeTTAwMDAxMzUkQF5wdWJsaWNEYXRhRGV0YWlsUGs9dWRkaTo5OWQ5OGM3YS1jNWNiLTQ2YjktYWZiZS1hMTBhODA0OTc2ZGEkQF5wcmN1c2VSZXFzdFNlcU5vPTg5MjIzNDIkQF5yZXFzdFN0ZXBDb2RlPVNUQ0QwMQ==
getLowArrInfoByStIdList에 정류소ID 입력(9자리)
'''
'''
arsIS + 모든 버스
1. xls 파일 검색 혹 앞의 #1에서 받아오기
2. https://www.data.go.kr/subMain.jsp#/L3B1YnIvcG90L215cC9Jcm9zTXlQYWdlL29wZW5EZXZEZXRhaWxQYWdlJEBeMDgyTTAwMDAxMzBeTTAwMDAxMzUkQF5wdWJsaWNEYXRhRGV0YWlsUGs9dWRkaTozMjA1NjhiNS1jZDBmLTQyODAtOGI5Ny1iZjUxMmYxNWZlNDkkQF5wcmN1c2VSZXFzdFNlcU5vPTg5Njk3ODkkQF5yZXFzdFN0ZXBDb2RlPVNUQ0QwMQ==
getStationByUidItem에 정류소ID 입력(5자리)
'''
import requests
from bs4 import BeautifulSoup
key = 'Uvejg0Q58CP9PVj1Pzd1wEbLNJTJ9dvBcK7OixMGJjk96hrRbKjCaBMtDC1UomYOJiis1lROIqHO4aoFwXkj3g%3D%3D'
stID = '103000121'
arsID = '04222'
url = f"http://ws.bus.go.kr/api/rest/stationinfo/getStationByUid?serviceKey={key}&arsId={arsID}"
data = requests.get(url).text
soup = BeautifulSoup(data, 'html.parser')
buses = soup.find_all('rtnm')
bus = []
for single_bus in buses:
bus.append(single_bus.text)
# 이후에 올 1대
times = soup.find_all('arrmsg1')
time = []
for single_time in times:
time.append(single_time.text)
print(bus)
print(time)
|
from gi.repository import Gtk, GObject
# http://python-gtk-3-tutorial.readthedocs.org/en/latest/dialogs.html
class AddAccountWindow (Gtk.Dialog):
__gsignals__ = {
'sign-in': (GObject.SIGNAL_RUN_FIRST, None, ()),
'token-entered': (GObject.SIGNAL_RUN_FIRST, None, (str,)),
}
def __init__ (self, controller, parent):
Gtk.Dialog.__init__ (self, "Add Account", parent, 0)
self.set_default_size (400, 300)
label = Gtk.Label ("First, you have to login to the UP app and get an auth code. Once you have a code, enter it in the box below.")
label.set_line_wrap (True)
box = self.get_content_area()
box.add (label)
b1 = Gtk.Button ("Sign in to UP!")
b1.connect ("clicked", self.on_sign_in)
# if we don't make a "Box" to put the button in then it makes
# the button HUGE and it looks dumb
b1_box = Gtk.Box()
b1_box.add (b1)
self.code_entry = Gtk.TextView()
# removed for easier debugging
#self.code_entry.set_editable (False)
self.code_entry.set_size_request (200, 200)
self.code_entry.set_wrap_mode (Gtk.WrapMode.CHAR)
self.code_entry.get_buffer().connect ("modified-changed", self.on_text_changed)
# Gtk puts things one after the other in the order that you add them.
# Each container has an "orientation", so adding 3 things to a
# horizontal container will put them like this:
# a b c
#
# and adding 3 things to a vertical container will put them
# like this:
# a
# b
# c
#
# The default container for a "Dialog" appears to be horizontal,
# but we want our text input to be below the button, so we should
# make a new vertical box to organize them
button_box = Gtk.Box (orientation=Gtk.Orientation.VERTICAL)
button_box.pack_start (b1_box, False, False, 2)
button_box.add (self.code_entry)
box.pack_start (button_box, True, True, 2)
self.show_all()
def on_response (self, arg1, response):
self.destroy()
def on_sign_in (self, button):
self.code_entry.set_editable (True)
self.emit ("sign-in")
def on_text_changed (self, buffer):
bounds = buffer.get_bounds()
text = buffer.get_text (bounds[0], bounds[1], False)
self.emit ("token-entered", text)
def set_complete (self):
self.destroy()
|
"""Unit tests for the Discord integration."""
import json
from urllib.request import urlopen
from django.contrib.auth.models import User
from djblets.conditions import ConditionSet, Condition
from djblets.testing.decorators import add_fixtures
from reviewboard.accounts.trophies import TrophyType, trophies_registry
from reviewboard.reviews.conditions import ReviewRequestRepositoriesChoice
from reviewboard.reviews.models import ReviewRequestDraft
from rbintegrations.discord.integration import DiscordIntegration
from rbintegrations.testing.testcases import IntegrationTestCase
class DiscordIntegrationTests(IntegrationTestCase):
"""Tests Review Board integration with Discord."""
integration_cls = DiscordIntegration
fixtures = ['test_scmtools', 'test_users']
def setUp(self):
super(DiscordIntegrationTests, self).setUp()
self.user = User.objects.create(username='test',
first_name='Test',
last_name='User')
def test_notify_new_review_request(self):
"""Testing DiscordIntegration notifies on new review request"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
target_people=[self.user],
publish=False)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.publish(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New review request from Test User: '
'http://example.com/r/1/'
),
'fields': [
{
'short': False,
'title': 'Description',
'value': 'My description.',
},
{
'short': True,
'title': 'Repository',
'value': 'Test Repo',
},
{
'short': True,
'title': 'Branch',
'value': 'my-branch',
},
],
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/',
'text': None,
'pretext': None,
}],
'text': (
'New review request from '
'<http://example.com/users/test/|Test User>'
),
})
@add_fixtures(['test_site'])
def test_notify_new_review_request_with_local_site(self):
"""Testing DiscordIntegration notifies on new review request with
local site
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
with_local_site=True,
local_id=1,
target_people=[self.user],
publish=False)
review_request.local_site.users.add(self.user)
self._create_config(with_local_site=True)
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.publish(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New review request from Test User: '
'http://example.com/s/local-site-1/r/1/'
),
'fields': [
{
'short': False,
'title': 'Description',
'value': 'My description.',
},
{
'short': True,
'title': 'Repository',
'value': 'Test Repo',
},
{
'short': True,
'title': 'Branch',
'value': 'my-branch',
},
],
'title': '#1: Test Review Request',
'title_link': 'http://example.com/s/local-site-1/r/1/',
'text': None,
'pretext': None,
}],
'text': (
'New review request from '
'<http://example.com/s/local-site-1/users/test/'
'|Test User>'
),
})
def test_notify_new_review_request_with_diff(self):
"""Testing DiscordIntegration notifies on new review request with
diff
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
publish=False)
self.create_diffset(review_request)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.publish(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New review request from Test User: '
'http://example.com/r/1/'
),
'fields': [
{
'short': False,
'title': 'Description',
'value': 'My description.',
},
{
'short': True,
'title': 'Diff',
'value': (
'<http://example.com/r/1/diff/1/|Revision 1>'
),
},
{
'short': True,
'title': 'Repository',
'value': 'Test Repo',
},
{
'short': True,
'title': 'Branch',
'value': 'my-branch',
},
],
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/',
'text': None,
'pretext': None,
}],
'text': (
'New review request from '
'<http://example.com/users/test/|Test User>'
),
})
@add_fixtures(['test_site'])
def test_notify_new_review_request_with_local_site_and_diff(self):
"""Testing DiscordIntegration notifies on new review request with local
site and diff
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
with_local_site=True,
local_id=1,
publish=False)
self.create_diffset(review_request)
review_request.local_site.users.add(self.user)
self._create_config(with_local_site=True)
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.publish(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New review request from Test User: '
'http://example.com/s/local-site-1/r/1/'
),
'fields': [
{
'short': False,
'title': 'Description',
'value': 'My description.',
},
{
'short': True,
'title': 'Diff',
'value': (
'<http://example.com/s/local-site-1/r/1/'
'diff/1/|Revision 1>'
),
},
{
'short': True,
'title': 'Repository',
'value': 'Test Repo',
},
{
'short': True,
'title': 'Branch',
'value': 'my-branch',
},
],
'title': '#1: Test Review Request',
'title_link': 'http://example.com/s/local-site-1/r/1/',
'text': None,
'pretext': None,
}],
'text': (
'New review request from '
'<http://example.com/s/local-site-1/users/test/'
'|Test User>'
),
})
def test_notify_new_review_request_with_image_file_attachment(self):
"""Testing DiscordIntegration notifies on new review request with
image file attachment
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
target_people=[self.user],
publish=False)
attachment = self.create_file_attachment(review_request)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.publish(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New review request from Test User: '
'http://example.com/r/1/'
),
'fields': [
{
'short': False,
'title': 'Description',
'value': 'My description.',
},
{
'short': True,
'title': 'Repository',
'value': 'Test Repo',
},
{
'short': True,
'title': 'Branch',
'value': 'my-branch',
},
],
'image_url': attachment.get_absolute_url(),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/',
'text': None,
'pretext': None,
}],
'text': (
'New review request from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_new_review_request_with_fish_trophy(self):
"""Testing DiscordIntegration notifies on new review request with
fish trophy
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
target_people=[self.user],
publish=False,
id=12321)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.publish(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#12321: New review request from Test User: '
'http://example.com/r/12321/'
),
'fields': [
{
'short': False,
'title': 'Description',
'value': 'My description.',
},
{
'short': True,
'title': 'Repository',
'value': 'Test Repo',
},
{
'short': True,
'title': 'Branch',
'value': 'my-branch',
},
],
'thumb_url': self.integration.TROPHY_URLS['fish'],
'title': '#12321: Test Review Request',
'title_link': 'http://example.com/r/12321/',
'text': None,
'pretext': None,
}],
'text': (
'New review request from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_new_review_request_with_milestone_trophy(self):
"""Testing DiscordIntegration notifies on new review request with
milestone trophy
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
target_people=[self.user],
publish=False,
id=10000)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.publish(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#10000: New review request from Test User: '
'http://example.com/r/10000/'
),
'fields': [
{
'short': False,
'title': 'Description',
'value': 'My description.',
},
{
'short': True,
'title': 'Repository',
'value': 'Test Repo',
},
{
'short': True,
'title': 'Branch',
'value': 'my-branch',
},
],
'thumb_url': self.integration.TROPHY_URLS['milestone'],
'title': '#10000: Test Review Request',
'title_link': 'http://example.com/r/10000/',
'text': None,
'pretext': None,
}],
'text': (
'New review request from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_new_review_request_with_custom_trophy(self):
"""Testing DiscordIntegration notifies on new review request with
ignored custom trophy
"""
class MyTrophy(TrophyType):
category = 'test'
def __init__(self):
super(MyTrophy, self).__init__(title='My Trophy',
image_url='blahblah')
def qualifies(self, review_request):
return True
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
target_people=[self.user],
publish=False)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
trophies_registry.register(MyTrophy)
try:
review_request.publish(self.user)
finally:
trophies_registry.unregister(MyTrophy)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New review request from Test User: '
'http://example.com/r/1/'
),
'fields': [
{
'short': False,
'title': 'Description',
'value': 'My description.',
},
{
'short': True,
'title': 'Repository',
'value': 'Test Repo',
},
{
'short': True,
'title': 'Branch',
'value': 'my-branch',
},
],
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/',
'text': None,
'pretext': None,
}],
'text': (
'New review request from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_updated_review_request(self):
"""Testing DiscordIntegration notifies on updated review request"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
target_people=[self.user],
publish=True)
draft = ReviewRequestDraft.create(review_request)
draft.summary = 'My new summary'
draft.description = 'My new description'
draft.save()
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.publish(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New update from Test User: '
'http://example.com/r/1/'
),
'fields': [
{
'short': True,
'title': 'Repository',
'value': 'Test Repo',
},
{
'short': True,
'title': 'Branch',
'value': 'my-branch',
},
],
'title': '#1: My new summary',
'title_link': 'http://example.com/r/1/',
'text': '',
'pretext': None,
}],
'text': (
'New update from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_updated_review_request_with_change_description(self):
"""Testing DiscordIntegration notifies on updated review request
with change description
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
target_people=[self.user],
publish=True)
draft = ReviewRequestDraft.create(review_request)
draft.summary = 'My new summary'
draft.description = 'My new description'
draft.save()
changedesc = draft.changedesc
changedesc.text = 'These are my changes.'
changedesc.save()
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.publish(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New update from Test User: '
'http://example.com/r/1/'
),
'fields': [
{
'short': True,
'title': 'Repository',
'value': 'Test Repo',
},
{
'short': True,
'title': 'Branch',
'value': 'my-branch',
},
],
'title': '#1: My new summary',
'title_link': 'http://example.com/r/1/',
'text': 'These are my changes.',
'pretext': None,
}],
'text': (
'New update from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_updated_review_request_with_new_image_attachments(self):
"""Testing DiscordIntegration notifies on updated review request with
new image attachments
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
target_people=[self.user],
publish=False)
self.create_file_attachment(review_request)
review_request.publish(self.user)
attachment = self.create_file_attachment(review_request,
caption='My new attachment',
draft=True)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.publish(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New update from Test User: '
'http://example.com/r/1/'
),
'fields': [
{
'short': True,
'title': 'Repository',
'value': 'Test Repo',
},
{
'short': True,
'title': 'Branch',
'value': 'my-branch',
},
],
'image_url': attachment.get_absolute_url(),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/',
'text': '',
'pretext': None,
}],
'text': (
'New update from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_closed_review_request_as_submitted(self):
"""Testing DiscordIntegration notifies on closing review request as
submitted
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
publish=True)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.close(review_request.SUBMITTED)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: Closed as completed by Test User: '
'http://example.com/r/1/'
),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/',
'text': None,
'pretext': None,
}],
'text': (
'Closed as completed by '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_closed_review_request_as_discarded(self):
"""Testing DiscordIntegration notifies on closing review request as
discarded
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
publish=True)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.close(review_request.DISCARDED)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: Discarded by Test User: '
'http://example.com/r/1/'
),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/',
'text': None,
'pretext': None,
}],
'text': (
'Discarded by '
'<http://example.com/users/test/|Test User>'
),
})
@add_fixtures(['test_site'])
def test_notify_closed_review_request_with_local_site(self):
"""Testing DiscordIntegration notifies on closing review request with
local site
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
with_local_site=True,
local_id=1,
publish=True)
review_request.local_site.users.add(self.user)
self._create_config(with_local_site=True)
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.close(review_request.SUBMITTED)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: Closed as completed by Test User: '
'http://example.com/s/local-site-1/r/1/'
),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/s/local-site-1/r/1/',
'text': None,
'pretext': None,
}],
'text': (
'Closed as completed by '
'<http://example.com/s/local-site-1/users/test/'
'|Test User>'
),
})
def test_notify_reopened_review_request(self):
"""Testing DiscordIntegration notifies on reopened review request"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
publish=True)
review_request.close(review_request.SUBMITTED)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.reopen(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: Reopened by Test User: '
'http://example.com/r/1/'
),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/',
'text': 'My description.',
'pretext': None
}],
'text': (
'Reopened by '
'<http://example.com/users/test/|Test User>'
),
})
@add_fixtures(['test_site'])
def test_notify_reopened_review_request_with_local_site(self):
"""Testing DiscordIntegration notifies on reopened review request with
local site
"""
review_request = self.create_review_request(
create_repository=True,
submitter=self.user,
summary='Test Review Request',
description='My description.',
with_local_site=True,
local_id=1,
publish=True)
review_request.close(review_request.SUBMITTED)
review_request.local_site.users.add(self.user)
self._create_config(with_local_site=True)
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review_request.reopen(self.user)
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: Reopened by Test User: '
'http://example.com/s/local-site-1/r/1/'
),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/s/local-site-1/r/1/',
'text': 'My description.',
'pretext': None,
}],
'text': (
'Reopened by '
'<http://example.com/s/local-site-1/users/test/'
'|Test User>'
),
})
def test_notify_new_review_with_body_top(self):
"""Testing DiscordIntegration notifies on new review with body_top"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
publish=True)
review = self.create_review(review_request,
user=self.user,
body_top='This is my review.')
self.create_general_comment(review)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New review from Test User: '
'http://example.com/r/1/#review1'
),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review1',
'text': 'This is my review.',
'pretext': None,
}],
'text': (
'New review from '
'<http://example.com/users/test/|Test User>'
),
})
@add_fixtures(['test_site'])
def test_notify_new_review_with_local_site(self):
"""Testing DiscordIntegration notifies on new review with local site"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
with_local_site=True,
local_id=1,
publish=True)
review_request.local_site.users.add(self.user)
review = self.create_review(review_request,
user=self.user,
body_top='This is my review.')
self.create_general_comment(review)
self._create_config(with_local_site=True)
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New review from Test User: '
'http://example.com/s/local-site-1/r/1/#review1'
),
'title': '#1: Test Review Request',
'title_link': (
'http://example.com/s/local-site-1/r/1/#review1'
),
'text': 'This is my review.',
'pretext': None,
}],
'text': (
'New review from '
'<http://example.com/s/local-site-1/users/test/'
'|Test User>'
),
})
def test_notify_new_review_with_comments(self):
"""Testing DiscordIntegration notifies on new review with only comments
"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
publish=True)
review = self.create_review(review_request, user=self.user,
body_top='')
self.create_general_comment(review, text='My general comment.')
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New review from Test User: '
'http://example.com/r/1/#review1'
),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review1',
'text': 'My general comment.',
'pretext': None,
}],
'text': (
'New review from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_new_review_with_one_open_issue(self):
"""Testing DiscordIntegration notifies on new review with 1 open
issue
"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
publish=True)
review = self.create_review(review_request, user=self.user,
body_top='')
self.create_general_comment(review, text='My general comment.',
issue_opened=True)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': 'warning',
'fallback': (
'#1: New review from Test User (1 issue): '
'http://example.com/r/1/#review1'
),
'fields': [{
'title': 'Open Issues',
'value': ':warning: 1 issue',
'short': True,
}],
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review1',
'text': 'My general comment.',
'pretext': None,
}],
'text': (
'New review from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_new_review_with_open_issues(self):
"""Testing DiscordIntegration notifies on new review with > 1 open
issue
"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
publish=True)
review = self.create_review(review_request, user=self.user,
body_top='')
self.create_general_comment(review, text='My general comment.',
issue_opened=True)
self.create_general_comment(review, text='My general comment 2.',
issue_opened=True)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': 'warning',
'fallback': (
'#1: New review from Test User (2 issues): '
'http://example.com/r/1/#review1'
),
'fields': [{
'title': 'Open Issues',
'value': ':warning: 2 issues',
'short': True,
}],
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review1',
'text': 'My general comment.',
'pretext': None,
}],
'text': (
'New review from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_new_review_with_ship_it(self):
"""Testing DiscordIntegration notifies on new review with Ship It!"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
publish=True)
review = self.create_review(review_request,
user=self.user,
ship_it=True,
body_top='Ship It!')
self.create_general_comment(review,
text='My comment')
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': 'good',
'fallback': (
'#1: New review from Test User (Ship it!): '
'http://example.com/r/1/#review1'
),
'fields': [{
'title': 'Ship it!',
'value': ':white_check_mark:',
'short': True,
}],
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review1',
'text': 'My comment',
'pretext': None,
}],
'text': (
'New review from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_new_review_with_ship_it_and_custom_body_top(self):
"""Testing DiscordIntegration notifies on new review with Ship It
and custom body_top
"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
target_people=[self.user],
publish=True)
review = self.create_review(review_request,
user=self.user,
ship_it=True,
body_top='This is body_top.')
self.create_general_comment(review)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': 'good',
'fallback': (
'#1: New review from Test User (Ship it!): '
'http://example.com/r/1/#review1'
),
'fields': [{
'title': 'Ship it!',
'value': ':white_check_mark:',
'short': True,
}],
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review1',
'text': 'This is body_top.',
'pretext': None,
}],
'text': (
'New review from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_new_review_with_ship_it_and_one_open_issue(self):
"""Testing DiscordIntegration notifies on new review with Ship It!
and 1 open issue
"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
target_people=[self.user],
publish=True)
review = self.create_review(review_request,
user=self.user,
ship_it=True,
body_top='Ship It!')
self.create_general_comment(review,
text='My comment',
issue_opened=True)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': 'warning',
'fallback': (
'#1: New review from Test User '
'(Fix it, then Ship it!): '
'http://example.com/r/1/#review1'
),
'fields': [{
'title': 'Fix it, then Ship it!',
'value': ':warning: 1 issue',
'short': True,
}],
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review1',
'text': 'My comment',
'pretext': None,
}],
'text': (
'New review from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_new_review_with_ship_it_and_open_issues(self):
"""Testing DiscordIntegration notifies on new review with Ship It!
and > 1 open issues
"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
target_people=[self.user],
publish=True)
review = self.create_review(review_request,
user=self.user,
ship_it=True,
body_top='Ship It!')
self.create_general_comment(review,
text='My comment 1',
issue_opened=True)
self.create_general_comment(review,
text='My comment 2',
issue_opened=True)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': 'warning',
'fallback': (
'#1: New review from Test User '
'(Fix it, then Ship it!): '
'http://example.com/r/1/#review1'
),
'fields': [{
'title': 'Fix it, then Ship it!',
'value': ':warning: 2 issues',
'short': True,
}],
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review1',
'text': 'My comment 1',
'pretext': None,
}],
'text': (
'New review from '
'<http://example.com/users/test/|Test User>'
),
})
def test_notify_with_body_bottom(self):
"""Testing DiscordIntegration notifies on new review with body_bottom
"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
publish=True)
review = self.create_review(review_request,
user=self.user,
body_top='',
body_bottom='Test')
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review.publish()
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'attachments': [{
'color': '#efcc96',
'fallback': (
'#1: New review from Test User: '
'http://example.com/r/1/#review1'
),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review1',
'text': 'Test',
'pretext': None,
}],
'icon_url': self.integration.LOGO_URL,
'text': (
'New review from '
'<http://example.com/users/test/|Test User>'
),
'username': 'RB User',
})
def test_notify_with_empty_review(self):
"""Testing DiscordIntegration does not notify on empty review"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
publish=True)
review = self.create_review(review_request,
user=self.user,
body_top='',
body_bottom='')
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
review.publish()
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'attachments': [{
'color': '#efcc96',
'fallback': (
'#1: New review from Test User: '
'http://example.com/r/1/#review1'
),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review1',
'text': '',
'pretext': None,
}],
'icon_url': self.integration.LOGO_URL,
'text': (
'New review from '
'<http://example.com/users/test/|Test User>'
),
'username': 'RB User',
})
def test_notify_new_reply_with_body_top(self):
"""Testing DiscordIntegration notifies on new reply with body_top"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
target_people=[self.user],
publish=True)
review = self.create_review(review_request,
user=self.user,
publish=True)
comment = self.create_general_comment(review, issue_opened=True)
reply = self.create_reply(review,
user=self.user,
body_top='This is body_top.')
self.create_general_comment(reply,
text='This is a comment.',
reply_to=comment)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
reply.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New reply from Test User: '
'http://example.com/r/1/#review2'
),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review2',
'text': 'This is body_top.',
'pretext': None,
}],
'text': (
'New reply from '
'<http://example.com/users/test/|Test User>'
),
})
@add_fixtures(['test_site'])
def test_notify_new_reply_with_local_site(self):
"""Testing DiscordIntegration notifies on new reply with local
site
"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
with_local_site=True,
local_id=1,
target_people=[self.user],
publish=True)
review_request.local_site.users.add(self.user)
review = self.create_review(review_request,
user=self.user,
publish=True)
comment = self.create_general_comment(review, issue_opened=True)
reply = self.create_reply(review,
user=self.user,
body_top='This is body_top.')
self.create_general_comment(reply,
text='This is a comment.',
reply_to=comment)
self._create_config(with_local_site=True)
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
reply.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New reply from Test User: '
'http://example.com/s/local-site-1/r/1/#review2'
),
'title': '#1: Test Review Request',
'title_link': (
'http://example.com/s/local-site-1/r/1/#review2'
),
'text': 'This is body_top.',
'pretext': None,
}],
'text': (
'New reply from '
'<http://example.com/s/local-site-1/users/test/'
'|Test User>'
),
})
def test_notify_new_reply_with_comment(self):
"""Testing DiscordIntegration notifies on new reply with comment"""
review_request = self.create_review_request(
create_repository=True,
summary='Test Review Request',
target_people=[self.user],
publish=True)
review = self.create_review(review_request,
user=self.user,
publish=True)
comment = self.create_general_comment(review, issue_opened=True)
reply = self.create_reply(review, user=self.user, body_top='')
self.create_general_comment(reply,
text='This is a comment.',
reply_to=comment)
self._create_config()
self.integration.enable_integration()
self.spy_on(urlopen, call_original=False)
self.spy_on(self.integration.notify)
reply.publish()
self.assertEqual(len(self.integration.notify.calls), 1)
self.assertEqual(len(urlopen.spy.calls), 1)
self.assertEqual(
json.loads(urlopen.spy.calls[0].args[0].data),
{
'username': 'RB User',
'icon_url': self.integration.LOGO_URL,
'attachments': [{
'color': self.integration.DEFAULT_COLOR,
'fallback': (
'#1: New reply from Test User: '
'http://example.com/r/1/#review2'
),
'title': '#1: Test Review Request',
'title_link': 'http://example.com/r/1/#review2',
'text': 'This is a comment.',
'pretext': None,
}],
'text': (
'New reply from '
'<http://example.com/users/test/|Test User>'
),
})
def _create_config(self, with_local_site=False):
"""Set configuration values for DiscordIntegration"""
choice = ReviewRequestRepositoriesChoice()
condition_set = ConditionSet(conditions=[
Condition(choice=choice,
operator=choice.get_operator('any')),
])
if with_local_site:
local_site = self.get_local_site(name=self.local_site_name)
else:
local_site = None
config = self.integration.create_config(name='Config 1',
enabled=True,
local_site=local_site)
config.set('notify_username', 'RB User')
config.set('webhook_url', 'http://example.com/discord-url/')
config.set('conditions', condition_set.serialize())
config.save()
return config
|
# -*- coding: utf-8 -*-
from ldapApi import LdapApi
import config
class Student:
"""Represent a Student of University"""
def __init__(self, uid=None, name=None, email=None):
self.name = name
self.uid = int(uid)
self.email = email
def getStudent(cn):
ldap = LdapApi(config.LDAP_URI)
studentList = ldap.search(config.LDAP_DN, cn, config.LDAP_FIELDS)
if len(studentList) == 1:
name = studentList[0][1].get('cn')[0]
student = Student(studentList[0][1].get('uid')[0], name.title(), studentList[0][1].get('uc3mCorreoAlias')[0])
return [student]
elif len(studentList) >1:
students = []
for studentValue in studentList:
name = studentValue[1].get('cn')[0]
student = Student(studentValue[1].get('uid')[0], name.title(), studentValue[1].get('uc3mCorreoAlias')[0])
students.append(student)
return students
|
import sys
human_list=[]
class human:
def __init__(self,name,phone,sex):
self.name = name
self.phone = phone
self.sex = sex
def print_infow(self):
print("이름은",self.name, "전화번호는",self.phone, "성별은",self.sex, "입니다")
def set_contact():
name =input("이름을 입력하세요: ")
if(name == "그만"):
return "그만"
phone =input("전화번호를 입력하세요:")
sex = input("성별을 입력하세요: ")
if ((sex != "male") and (sex != "female")):
sex = "unknown"
contact = human(name,phone,sex)
return contact
while(1):
contact = set_contact()
human_list.append(contact)
for i in human_list:
i.print_infow()
if(i.name == "그만"):
sys.exit() |
import json
import logging
import urllib
import urllib2
from secrets import TOKEN, WEBHOOK_URL, MAIN_ANDROID_ID
# standard app engine imports
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
import webapp2
BASE_URL = 'http://api.tofusms.com/devices/send/' + MAIN_ANDROID_ID
JSON_HEADER = {'Content-Type': 'application/json;charset=utf-8',
"Authorization": "Token " + TOKEN}
# ================================
class User(ndb.Model):
contact = ndb.StringProperty()
currentMode = ndb.StringProperty(default="new")
rating = ndb.IntegerProperty(default=0)
# ================================
def make_payload(message, contact):
payload = json.dumps({
'message': message,
'contact': contact
})
return payload
def send_message(data):
urlfetch.fetch(url=BASE_URL, payload = data, method = urlfetch.POST,
headers = JSON_HEADER)
def get_user_by_contact(contact):
q = User.query(User.contact == str(contact)).fetch()
if len(q) != 0:
user = q[0]
return user
else:
newuser = User(contact = contact)
newuser.put()
return newuser
# ================================
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.write("LULULULULUL")
class ReceiveHandler(webapp2.RequestHandler):
def get(self):
self.response.write("Receive page")
def post(self):
data = json.loads(self.request.body) #deserializing json in POST request body
logging.debug(self.request.body) # prints debug message
msg = data["message"]
contact = data["contact"]
user = get_user_by_contact(contact)
new_msg = ""
# if (msg == "start"):
# user.currentMode = "new"
if (msg == "new"):
user.currentMode = "new"
if (user.currentMode == "new"):
if (msg == "start"):
new_msg = "You are about to start a new demo. At any point if you feel like restarting the " + \
"demo, type in 'new'!"
send_message(make_payload(new_msg, contact))
new_msg = "Hi! I am De-Bot.\nYour package #059123754 has arrived in Singapore! " + \
"It will be be delivered to you @ 6 College Avenue East, University Town " + \
"on 24th September 2017, 1:00PM - 3:00PM. \n \n" + \
"Please reply '0' if you are not able to collect at the stated time. " + \
"No action is required if you are okay with this arrangement."
user.currentMode = "start"
user.put()
if (user.rating > 0):
new_msg += "\n\nAlso... You seem familiar... you were the human who " + \
"rated me " + str(user.rating) + " right? Bots like me have good memory!"
else:
new_msg = "Hello! It seems like you are a new user. I am De-Bot, nice to meet you! \n \n" + \
"Please enter 'start' to begin trying me out!"
if (user.rating >= 0):
new_msg += "\n\n Also... You seem familiar... you were the human who " + \
"rated me " + str(user.rating) + " right? Bots like me have good memory!" + \
" I'll see if I can do better this time!"
send_message(make_payload(new_msg, contact))
elif (user.currentMode == "start"):
if (msg == "next"):
new_msg = "Hi! I am De-Bot.\n" + \
"Your package will be be delivered to you TOMORROW at 1:00PM - 3:00PM. \n \n " + \
"Please reply '0' if you are not able to collect at the stated time. " + \
"No action is required if you are okay with this arrangement."
user.currentMode = "demo1"
user.put()
elif (msg == "0"):
new_msg = "Hi! I have noticed that you are not able to collect " + \
"your package today. \n " + \
"Thank you for informing us!\n\n " + \
"Your package will not be delivered today and is being " + \
"rescheduled for delivery on another day."
user.currentMode = "new"
user.put()
else:
new_msg += "Sorry, I did not understand what you just said.\n"
new_msg += "[DEMO MODE]\n"
new_msg += "You are currently in start mode\n"
new_msg += "Type 'next' to go to the next step of the demo."
send_message(make_payload(new_msg, contact))
elif (user.currentMode == "demo1"):
if (msg == "next"):
new_msg = "Hi! I am De-Bot.\n" + \
"Your package will be be delivered to you TODAY at 1:00PM - 3:00PM. \n \n " + \
"Please reply '0' if you are not able to collect at the stated time. " + \
"No action is required if you are okay with this arrangement."
user.currentMode = "demo2"
user.put()
elif (msg == "0"):
new_msg = "Hi! I have noticed that you are not able to collect " + \
"your package today. \n " + \
"Thank you for informing us!\n\n " + \
"Your package will not be delivered today and is being " + \
"rescheduled for delivery on another day."
user.currentMode = "new"
user.put()
else:
new_msg += "Sorry, I did not understand what you just said.\n"
new_msg += "[DEMO MODE]\n"
new_msg += "You are currently in demo1 mode\n"
new_msg += "Type 'next' to go to the next step of the demo."
send_message(make_payload(new_msg, contact))
elif (user.currentMode == "demo2"):
if (msg == "next"):
new_msg = "Your package has successfully been delivered! \n\n" + \
"Thank you for using De-Bot! \n " + \
"If you want to, give me a rating from '1' to '5' just by typing " + \
"the number in! \n\n" + \
"Also, you can find my source code and leave a feedback for a " + \
"friendly bot like me to my developers Sharan, De Long " + \
"and Dominic at https://github.com/bannified !"
send_message(make_payload(new_msg,contact))
new_msg = "--- END OF DEMO --- \n" + \
"Type in 'new' to try again"
elif (msg == "0"):
new_msg = "Hi! I have noticed that you are not able to collect " + \
"your package today. \n" + \
"Thank you for informing us!\n\n " + \
"Your package will not be delivered today and is being " + \
"rescheduled for delivery on another day."
user.currentMode = "new"
user.put()
elif (msg == "1"):
new_msg = "That means that I still have much to improve on! \n" + \
"Thank you for the feedback, kind human!"
user.rating = 1
user.currentMode = "new"
user.put()
elif (msg == "2"):
new_msg = "I'll try harder the next time we meet! \n" + \
"Thank you for the feedback, kind human!"
user.rating = 2
user.currentMode = "new"
user.put()
elif (msg == "3"):
new_msg = "Nice! That's kind of you. I'll become better in the future! \n" + \
"Thank you for the feedback, kind human!"
user.rating = 3
user.currentMode = "new"
user.put()
elif (msg == "4"):
new_msg = "Wow! I've never been praised so highly before. \n" + \
"Thank you for the feedback, kind human!"
user.rating = 4
user.currentMode = "new"
user.put()
elif (msg == "5"):
new_msg = "Does this make me the best bot in the world? \n" + \
"Thank you for the feedback, kind human!"
user.rating = 5
user.currentMode = "new"
user.put()
else:
new_msg = "Sorry, I did not understand what you just said.\n"
new_msg += "[DEMO MODE]\n"
new_msg += "You are currently in demo2 mode\n"
new_msg += "Type 'next' to go to the next step of the demo."
send_message(make_payload(new_msg, contact))
self.response.write(self.request)
app = webapp2.WSGIApplication([
('/', MainHandler),
('/receive', ReceiveHandler),
], debug=True)
|
import numpy as np
import lasagne
def iterator(inputs, batchsize, eta_d_shared, eta_g_shared, epoch):
if (epoch >= 500) and (epoch % 500 == 0):
eta_d_shared.set_value(lasagne.utils.floatX(0.5 * eta_d_shared.get_value()))
eta_g_shared.set_value(lasagne.utils.floatX(0.5 * eta_g_shared.get_value()))
indices = np.arange(len(inputs))
np.random.shuffle(indices)
for start_idx in range(0, len(inputs) - batchsize + 1, batchsize):
excerpt = indices[start_idx:start_idx + batchsize]
yield inputs[excerpt] |
# -*- coding: utf-8 -*-
"""
飞行时间方法建模
@author: luowei
"""
import math
import numpy as np
import pandas as pd
from scipy import constants as scipy_cons
import matplotlib.pyplot as plt
###################################################################################
# 物理常数
neutron_m = scipy_cons.physical_constants['neutron mass'][0]
light_c = scipy_cons.physical_constants['natural unit of velocity'][0]
unit_e = scipy_cons.physical_constants['elementary charge']
###################################################################################
# 飞行时间测量方法
def flight_t(en,flight_length = 76.6):
# 单位 : en / MeV flight_length/m t / ns
return 72.3*flight_length/np.sqrt(en)
def relative_t(en,flight_length = 76.6):
# en -- > t
junk = 1-(939.552/(en+939.552))**2
return flight_length/light_c/np.sqrt(junk)*10**9
def t_to_e(t,flight_length = 76.6):
# t -- > en(MeV)
return (72.3*flight_length/t)**2
def relative_resol_e(resol_t,en,flight_length=76.6):
# 不考虑飞行距离的不确定度
junk1 = (en+939.552)/en
tt = relative_t(en,flight_length=flight_length) # ns
beta = flight_length/light_c/tt*10**9
junk2 = beta**2/(1-beta**2)
return resol_t*junk1*junk2
def relative_resol_t(resol_e,en,flight_length=76.6):
# 不考虑飞行距离的不确定度,
# 由分析知扩大delta_T统计区间,对应的ET平面覆盖面积可以通过扩大delta_E来完成。
# 故可以反用该关系,通过指定delta_E来推算统计的delta_T区间
junk1 = (en+939.552)/en
tt = relative_t(en,flight_length=flight_length) # ns
beta = flight_length/light_c/tt*10**9
junk2 = beta**2/(1-beta**2)
return resol_e/junk1/junk2
def nonrelative_resol_e(resol_t):
return resol_t*2
def distance_diff(en,time_diff):
junk = 1-(939.552/(en+939.552))**2
return light_c*np.sqrt(junk)*time_diff/10**9
###################################################################################
# 白光中子源描述
class Neutron_source():
def __init__(self,power=25,flux_file = r'D:\en.txt'):
# 输入:
# 加速器功率/每发质子打靶数/每发中子总注量:
# 1. 给出这三者转换关系
# ES和束斑尺寸选择
# 参数存储
# 1. 不同ES和束斑尺寸之间的相对比例,尺寸距离信息等
# 2. 不同ES的归一化中子能谱(flux_area的和为1)
# 3. 加速器频率
# 输出:
# 当前束流参数下的中子能谱
self.Freq = 25
self.filename = flux_file
self.power = power
self.read_flux_option()
self.read_raw_da()
def set_power(self,power):
self.power = power
self.read_flux_option()
self.read_raw_da()
def read_flux_option(self):
# CSNS白光源的各种构型信息
df = pd.DataFrame(columns = ['spot','spot_area','distance','flux'])
spot = [u'$\phi$ 20mm',u'$\phi$ 30mm',u'$\phi$ 60mm',u'90*90mm']
diameter = [1,1.5,3]
area = [x**2*math.pi for x in diameter]+[81]
distance = [56,77.6]
flux = [6.3e+4,2.3e+4,1.1e+6,3.9e+5,2.2e+7,6.8e+6,3.0e+7,1.1e+7]
for i in range(len(spot)):
for j in range(len(distance)):
data = [spot[i],area[i],distance[j],flux[i*2+j]]
se = pd.Series(data,index =['spot','spot_area','distance','flux'] )
df = df.append(se,ignore_index = True)
# flux和ix[5]数据的相对比值,假设不同构型下能谱不变
df['unit_ref'] = df['flux']/df.iloc[5]['flux']
df['unit_area'] = df['spot_area']/df.iloc[5]['spot_area']
df['flux'] = df['flux']*self.power/100.0
self.flux_option = df.copy()
def read_raw_da(self):
# 读取原始能谱数据 : 60mm 76.6m 100KW 双束团
filename = r'D:\en.txt'
da = pd.read_table(filename,names = ['en_start','en_end','flux'])
# 原始数据为双发模式,实际实验为单发模式,所以flux除以2
da['flux'] = da['flux']/2
# 加速器功率引起的flux变化
da['flux'] = da['flux']*self.power/100.00
self.raw_data = da.copy()
def flux_pluse(self,numb):
# 将能谱转为单个脉冲的飞行时间谱
flux_profile = self.flux_option.iloc[numb]
da = self.raw_data.copy()
distance = float(flux_profile['distance'])
## da['distance'] = flux_profile['distance'],# /s 变为 /pulse
# /MeV/cm2/pulse
da['flux'] = da['flux']*flux_profile['unit_ref']/self.Freq
# /cm2/pulse 一个能量切片里的flux
da['flux_area'] = (da['en_end'] - da['en_start'])*da['flux']
da['time_start'] = da['en_start'].map(lambda x: flight_t(x,flight_length = distance))
da['time_end'] = da['en_end'].map(lambda x: flight_t(x,flight_length = distance))
da['time_section'] = da['time_start']-da['time_end']
# 该pluse产生的中子,飞到distance时的flux
# /cm2/ns,时间切片和能量切片对应,总的flux_area不变,即time_start到time_end期间,该值不变
da['flux_time'] = da['flux_area']/da['time_section']
# 能通量
da['en_flux'] = da['en_start']*da['flux']
da['energy_flux'] = (da['en_start']+da['en_end'])*da['flux_time']/2
flux_profile['data'] = da.copy()
return flux_profile
# 选择特定能量中子对应的注量
def select_flux_from_en(en,flux_numb):
# select single energy data
da = CSNS_source.flux_pluse(flux_numb)['data'].copy()
junk = da.loc[en <= da['en_end']]
return junk.iloc[0]
# 源信息全局变量
CSNS_source = Neutron_source(power=25)
###################################################################################
###################################################################################
# 飞行时间谱可视化
def plot_section_spectrum(da,index,ax,plot_option='plot',fill = True,color='b',alpha=0.3):
# 通用多道谱可视化
# plot, semilogx, semilogy, loglog
# index : start_x, end_x, height
plot_command = 'ax.'+plot_option+'(x,y,color = color,alpha=alpha)'
da = da.reset_index()
for i in range(len(da)):
x = da.iloc[i][index[0]],da.iloc[i][index[1]]
y = da.iloc[i][index[2]],da.iloc[i][index[2]]
eval(plot_command)
if fill is True:
ax.fill_between(x,y,facecolor=color,alpha=alpha)
for i in range(len(da)-1):
x = da.iloc[i][index[1]],da.iloc[i][index[1]]
y = da.iloc[i][index[2]],da.iloc[i+1][index[2]]
eval(plot_command)
def select_energy(en,da):
# select single energy data
junk = da.loc[en <= da['en_end']]
return junk.iloc[0]
def neutron_spectrum(nn):
# 能谱
flux_profile = CSNS_source.flux_pluse(nn)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid(True)
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
da = flux_profile['data']
plot_section_spectrum(da,['en_start','en_end','flux'],ax,plot_option='loglog')
#ax.set_ylabel(u'Neutron flux (/MeV/$cm^2$/pluse)',fontsize=12)
ax.set_ylabel(u'中子注量 (/MeV/$cm^2$/pluse)',fontsize=12)
ax.set_xlabel(u'中子能量 (MeV)',fontsize=12)
ax.text(0.5,0.9,str(CSNS_source.power)+u"KW 加速器能量",transform = ax.transAxes,fontsize=12)
text = u'@'+str(flux_profile['distance'])+' @'+flux_profile['spot']
ax.text(0.5,0.85,text,transform = ax.transAxes,fontsize=12)
plt.legend(fontsize=12)
plt.show()
def time_spectrum(nn):
# 飞行时间谱
flux_profile = CSNS_source.flux_pluse(nn)
distance = flux_profile['distance']
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid(axis='y')
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
da = flux_profile['data']
plot_section_spectrum(da,['time_start','time_end','flux_time'],ax,plot_option='semilogx')
ax.set_ylabel(u'中子注量率 (/ns/$cm^2$)',fontsize = 12)
ax.set_xlabel(u'飞行时间 (ns)',fontsize = 12)
# neutron energy label
energy_label = [0.001,0.01,0.1,1,10,100]
x_start = 0.6
label_control = 1
height_limit = max(da['flux_time'])*1.1
for x in energy_label:
xx = [relative_t(x,flight_length=distance),relative_t(x,flight_length=distance)]
yy =[select_energy(x,da)['flux_time'],height_limit]
if label_control == 1:
ax.semilogx(xx,yy,'--',color='g',label = u'中子能量(MeV)',linewidth = 2)
else:
ax.semilogx(xx,yy,'--',color='g',linewidth = 2)
ax.text(x_start,1.05,str(x),transform = ax.transAxes)
x_start = x_start - 0.1
label_control = label_control*0
# flux info
ax.text(0.65,0.25,str(CSNS_source.power)+u"KW 加速器能量",transform = ax.transAxes,fontsize=12)
text = u'飞行距离: '+str(flux_profile['distance'])+'m'
ax.text(0.65,0.20,text,transform = ax.transAxes,fontsize=12)
text = u'束斑尺寸: '+flux_profile['spot']
ax.text(0.65,0.15,text,transform = ax.transAxes,fontsize=12)
# gamma
t_gamma = distance*10**9/light_c
ax.semilogx([t_gamma,t_gamma],[0,height_limit],'-',color='y',label = '$\gamma$ ('+ '%.2f' % t_gamma +'ns)',linewidth=3)
ax.text(0.04,1.05,u"$\gamma$",transform = ax.transAxes)
plt.legend(fontsize=12,frameon=True,facecolor='grey',framealpha = 0.5)
plt.show() |
from balance_item import BalanceItem
from collections import Counter
from helpers import DISPLAY_WIDTH, format_money
from enum import Enum
from typing import List
class Category(Enum):
VEGGIES = "Veggies"
DAIRY = "Dairy"
SNACKS = "Snacks"
FRUITS = "Fruits"
DRINKS = "Drinks"
KITCHEN = "Kitchen"
HEALTH = "Health"
COUPON = "Coupon"
OTHER = "Other"
class Balance:
"""
A Balance is a running total for a transaction. It tracks all the additions and deductions that were
made (through BalanceItems) and allows for filtering based on category.
"""
def __init__(self) -> None:
self.cached_amount = 0
self.balance_items = []
self.five_for_five_used = 0
self.dirty = False
def add_balance(self, amount: int, category: Category = Category.OTHER, description: str = "Add money") -> None:
self.balance_items += [BalanceItem(amount, category, description)]
self.dirty = True
def subtract_balance(self, amount: int, category: Category = Category.OTHER, description: str = "Subtract money") -> None:
self.balance_items += [BalanceItem(-amount, category, description)]
self.dirty = True
def clear_balance(self) -> None:
self.balance_items = []
self.dirty = True
def balance_items_with_category(self, category: Category) -> List[BalanceItem]:
return list(filter(lambda item: item.category == category, self.balance_items))
def amount(self) -> int:
if self.dirty:
total = sum([item.amount for item in self.balance_items])
self.dirty = False
self.cached_amount = total
return self.cached_amount
def group_balance_items(self) -> None:
"""
Groups items so that they look nicer in the final purchase list.
For example, 3 separate BalanceItems for apples will turn into a single item that says 'Apple (x3 @ 199 each)'.
This permanently changes the items belonging to this balance!!
"""
"""
BUG:
The bug was caused by the Counter() implementation, which would return a count of 1 for each balance item.
This is because each balance item has a unique identifier as the object
FIX:
To fix this, I created a Counter object called item_counts that would show the number of times an item description was in balance_items.
I grouped the items by their descriptions since their descriptions are unique to the items.
I then iterated through the balance items and added items to balance and mapped the appropriate grouping.
I separated single items and grouped items so repetitions would not occur.
"""
all_balance_items = self.balance_items
item_counts = Counter(list(map(lambda item: item.description, all_balance_items)))
used_group_items = []
self.clear_balance()
for item in all_balance_items:
if item_counts[item.description] > 1 and item.description not in used_group_items:
quantity_str = f" (x{item_counts[item.description]} @ {format_money(item.amount)} each)"
used_group_items += [item.description]
self.add_balance(item.amount * item_counts[item.description], category=item.category, description=f"{item.description}{quantity_str}")
elif item_counts[item.description] == 1:
self.add_balance(item.amount * item_counts[item.description], category=item.category, description=f"{item.description}")
self.dirty = False # No need to recalculate; total is the same
def __str__(self) -> str:
result = ""
for item in self.balance_items:
result += f"{item}\n"
result += "=" * DISPLAY_WIDTH + "\n"
result += f"{'TOTAL:'.ljust(DISPLAY_WIDTH - 9)} {format_money(self.amount())}\n"
result += "=" * DISPLAY_WIDTH
return result
|
# -*- coding: utf-8 -*-
__author__ = 'Sun Fang'
import pickle
my_file = open('newNote.txt', 'r')
lines = my_file.readlines()
print(lines)
my_file.seek(0)
# 一次只读一行
first_line = my_file.readline()
second_line = my_file.readline()
print(first_line)
print(second_line)
# 回到起始位置
my_file.seek(0)
first_line_again = my_file.readline()
print(first_line_again)
# 使用完文件 记得关闭它
my_file.close()
# 追加到文件
todo_list = open('newNote.txt', 'a')
todo_list.write('\nStudy day by day')
todo_list.close()
todo_list = open('newNote.txt', 'r')
lines_after_append = todo_list.readlines()
print(lines_after_append)
todo_list.close()
# 写文件 (对一个新文件写,即当前目录中还没有这个文件)
new_file = open("my_new_file.txt", 'w')
new_file.write("Study\n")
new_file.write("Play soccer\n")
new_file.write("Go to bed")
new_file.close()
# 写文件 (对一个已有文件写,会覆盖该文件之前的内容)
the_file = open("my_new_file", "w")
the_file.write("Wake up\n")
the_file.write("Watch cartoons\n")
the_file.close()
# 在文件中保存内容:pickle
# 要pickle某个东西,比如列表,需要使用dump()函数
my_list = ['Fred', 73, 'Hello there', 81.9876e-13]
pickle_file = open('my_pickle_list.pkl', 'wb+')
pickle.dump(my_list, pickle_file)
pickle_file.close()
# 去除pickle前的数据
# 使用load()还原
pickle_file1 = open('my_pickle_list.pkl', 'rb')
recovered_list = pickle.load(pickle_file1)
pickle_file.close()
print(recovered_list)
|
#!/bin/python
# -*- coding: utf-8 -*-
# extract_basic.py
# extract the basic patterns using brute-force
# 1 extract n-gram frequent set
#
# Author: Xing Shi
# contact: xingshi@usc.edu
from rcpe import settings
from multiprocessing import Process,Queue
from loader import Loader
import os
import operator
from collections import defaultdict
from functools import partial
import cPickle
import math
def main():
data = Loader.load()
min_n_gram = 2
max_n_gram = 6
dir_path = os.path.join(settings.TEMP_DIR,'n_gram/')
#---- frequent# n_gram ----
# processes = []
# for i in xrange(min_n_gram,max_n_gram+1):
# p = Process(target = n_gram_group , args = (dir_path,data,i))
# processes.append(p)
# p.start()
# for p in processes:
# p.join()
#---- frequent parse_gram ----
# parse_gram_group(dir_path,data,min_n_gram,max_n_gram)
#---- frequent parse_gram ----
matrix_group(dir_path,data,min_n_gram,max_n_gram)
#------------------------------ extract frequent n-gram from stem words--------------
def n_gram_group(dir_path,data,n_gram):
result_map = {}
processes = []
n_process = settings.N_CORES
q = Queue()
for i in xrange(n_process):
p = Process(target=n_gram_worker, args = (data,n_gram,i,n_process,q))
processes.append(p)
p.start()
for i in xrange(n_process):
d = q.get()
for key in d:
if key in result_map:
result_map[key]+=d[key]
else:
result_map[key] = d[key]
for p in processes:
p.join()
result_map = sorted(result_map.iteritems(), key=operator.itemgetter(1),reverse=True)
f = open(os.path.join(dir_path,'r_%d.txt' % (n_gram,)),'w')
for key,rank in result_map:
f.write('%s %d\n' % (key.encode('utf8'),rank))
f.close()
def n_gram_worker(data,n_gram,r,b,queue):
n_gram_map = {}
for i in xrange(len(data)):
if i%b ==r:
sent = data[i]
stems = sent.stems
for i in xrange(len(stems)-n_gram+1):
s = '_'.join(stems[i:i+n_gram])
if s not in n_gram_map:
n_gram_map[s] = 1
else:
n_gram_map[s] += 1
queue.put(n_gram_map)
#------------------------------/ extract frequent n-gram from stem words--------------
#------------------------------ extract frequent parse_gram from stem words--------------
def parse_gram_group(dir_path,data,min_n_gram,max_n_gram):
result_map = {}
processes = []
n_process = settings.N_CORES
q = Queue()
for i in xrange(n_process):
p = Process(target=parse_gram_worker, args = (data,i,n_process,q,min_n_gram,max_n_gram))
processes.append(p)
p.start()
for i in xrange(n_process):
d = q.get()
for key in d:
if key in result_map:
result_map[key]+=d[key]
else:
result_map[key] = d[key]
for p in processes:
p.join()
result_map = sorted(result_map.iteritems(), key=operator.itemgetter(1),reverse=True)
f = open(os.path.join(dir_path,'parse_gram.txt'),'w')
for key,rank in result_map:
f.write('%s %d\n' % (key.encode('utf8'),rank))
f.close()
def parse_gram_worker(data,r,b,queue,min_n_gram,max_n_gram):
parse_gram_map = {}
for i in xrange(len(data)):
if i%b ==r:
sent = data[i]
leaves,substring = sent.tree.getSubstring()
stems = sent.stems
for sb in substring:
if sb.size<=max_n_gram and sb.size>=min_n_gram:
sbstr = sb.toString(stems)
if sbstr in parse_gram_map:
parse_gram_map[sbstr]+=1
else:
parse_gram_map[sbstr] = 1
queue.put(parse_gram_map)
#------------------------------/ extract frequent parse_gram from stem words--------------
#------------------------------calculate matrix --------------
def calculate_npmi(dir_path,matrix,rdict,cdict,n):
'''
npmi(x,y) = pmi(x,y) / -log(p(x,y))
pmi(x,y) = log( p(x,y) / ( p(x)*p(y) )
npmi(x,y) = ( log(n(x)*n(y)) - 2 logN ) / ( log( n(x,y) ) - log N) - 1
'''
pmi = defaultdict(partial(defaultdict,float))
pmi_tuple = []
for rs in matrix:
for cs in matrix[rs]:
npmi_top = math.log( rdict[rs] * cdict[cs] ) - 2*math.log(n)
npmi_bot = math.log( matrix[rs][cs] ) - math.log(n)
npmi = npmi_top / npmi_bot - 1.0
#print matrix[rs][cs],rdict[rs],cdict[cs],npmi_top,npmi_bot
pmi[rs][cs] = npmi
if npmi > 1:
print rs,cs,matrix[rs][cs], rdict[rs],cdict[cs]
pmi_tuple.append( (rs,cs,npmi) )
pmi_tuple=sorted(pmi_tuple, key=operator.itemgetter(2),reverse=True)
f = open(os.path.join(dir_path,'pmi.pickle'),'w')
cPickle.dump(pmi,f)
f.close()
f = open(os.path.join(dir_path,'pmi.txt'),'w')
for rs,cs,npmi in pmi_tuple:
f.write('\t'.join([rs.encode('utf8'),cs.encode('utf8'),str(npmi),str(matrix[rs][cs]),str(rdict[rs]),str(cdict[cs])])+'\n')
f.close()
def matrix_group(dir_path,data,min_n_gram,max_n_gram):
data_tuple = Loader.sent2pair(data)
result_matrix = defaultdict(partial(defaultdict,int))
rdict = defaultdict(int)
cdict = defaultdict(int)
processes = []
n_process = settings.N_CORES
q = Queue()
for i in xrange(n_process):
p = Process(target=matrix_worker, args = (data_tuple,i,n_process,q,min_n_gram,max_n_gram))
processes.append(p)
p.start()
for i in xrange(n_process):
(d,rd,cd) = q.get()
for k1 in d:
for k2 in d[k1]:
result_matrix[k1][k2] += d[k1][k2]
for rk in rd:
rdict[rk]+=rd[rk]
for ck in cd:
cdict[ck]+=cd[ck]
for p in processes:
p.join()
print 'writing data into pickle ...'
f = open(os.path.join(dir_path,'parse_matrix.pickle'),'w')
cPickle.dump(result_matrix,f)
f.close()
f = open(os.path.join(dir_path,'parse_rdict.pickle'),'w')
cPickle.dump(rdict,f)
f.close()
f = open(os.path.join(dir_path,'parse_cdict.pickle'),'w')
cPickle.dump(cdict,f)
f.close()
print 'calculating npmi ...'
calculate_npmi(dir_path,result_matrix,rdict,cdict,len(data_tuple))
def matrix_worker(data_tuple,r,b,queue,min_n_gram,max_n_gram):
matrix = defaultdict(partial(defaultdict,int))
rdict = defaultdict(int)
cdict = defaultdict(int)
for i in xrange(len(data_tuple)):
if i%b ==r:
pair = data_tuple[i]
rsubs = set()
csubs = set()
for sent in pair:
leaves,subs = sent.tree.getSubstring()
stems = sent.stems
substrs = [s.toString(stems) for s in subs if s.size<=max_n_gram and s.size>=min_n_gram]
if sent.rc == 'R':
rsubs.update(substrs)
elif sent.rc == 'C':
csubs.update(substrs)
for rsub in rsubs:
for csub in csubs:
matrix[rsub][csub]+=1
for rsub in rsubs:
rdict[rsub]+=1
for csub in csubs:
cdict[csub]+=1
queue.put((matrix,rdict,cdict))
#------------------------------/ calculate matrix --------------
if __name__ == "__main__":
main()
|
def drought_stage(month):
return {
1 : [40, 30, 25],
2 : [50, 35, 25],
3 : [65, 45, 30],
4 : [85, 60, 35],
5 : [75, 55, 35],
6 : [65, 45, 30],
7 : [55, 45, 25],
8 : [50, 40, 25],
9 : [45, 35, 25],
10: [40, 30, 25],
11: [35, 30, 25],
12: [35, 30, 25],
}[month]
def recission(month):
return {
1 : [60, 50, 45],
2 : [70, 55, 45],
3 : [85, 65, 50],
4 : [100, 80, 55],
5 : [95, 75, 55],
6 : [85, 65, 50],
7 : [75, 65, 45],
8 : [70, 60, 45],
9 : [65, 55, 45],
10: [60, 50, 45],
11: [55, 50, 45],
12: [55, 50, 45],
}
'''
stage1 = [False] * len(file_dict[filename])
stage2 = [False] * len(file_dict[filename])
stage3 = [False] * len(file_dict[filename])
for i in range(len(file_dict[filename])):
if storage[i] <= drought_stage(months[i])[0]:
stage1[i] = True
if storage[i] <= drought_stage(months[i])[1]:
stage2[i] = True
if storage[i] <= drought_stage(months[i])[2]:
stage3[i] = True
file_dict[filename]['stage1'] = stage1
file_dict[filename]['stage2'] = stage2
file_dict[filename]['stage3'] = stage3
print(file_dict[filename])
''' |
# File management
print("tony.txt is open. Write something to the file:")
content = str(input())
f = open('tony.txt', 'w')
f.write(content)
f.close()
f = open('tony.txt', 'r')
print(f.read())
f.close()
for i in range(10, 0, -1):
print(i)
|
def amountofds(x,d):
res = 0
for ch in str(x):
if ch == d:
res += 1
return res
def s(x):
sum = 0
amount = 0
in_i = 0
for i in range(0,100000000):
in_i += amountofds(i,x)
amount += in_i
#print str(i) + " " + str(in_i)
if i == in_i:
# print i
sum += i
return sum
def main():
print s("1")
if __name__ == "__main__":
main() |
from collections import deque
import sys
from itertools import permutations
from random import *
# n = int(input())
# a = sorted(map(int, input().strip().split()))
def solve(a):
d = deque()
test = 0
for i in a:
if test:
d.appendleft(i)
test = 0
else:
d.append(i)
test = 1
d = list(d)
# print(d)
if all(a < b + c for a, b, c in zip(d, d[1:] + [d[0]], [d[-1]] + d)):
# print("YES")
# print(*d)
return True
else:
# print("NO")
return False
def solve2(a):
n = len(a)
a = list(reversed(a))
if a[0] >= a[1] + a[2]:
return False
else:
return True
def brute(a):
for d in permutations(a):
if all(a < b + c for a, b, c in zip(d, d[1:] + (d[0],), (d[-1],) + d)):
# print(d)
return True
return False
# solve(a)
while True:
a = sorted([randint(2, 50) for _ in range(7)])
if solve2(a) != brute(a):
print(a)
sys.exit()
else:
print("ok")
|
#!/usr/bin/env python
# coding=utf-8
import numpy
import scipy
from numpy import *
import numpy as np
import scipy as sp
import pylab as pl |
import numpy as np
import h5py
import time
import os
from PIL import Image
from resizeimage import resizeimage
import matplotlib.pyplot as plt
RES = 100
NUM_PIX = RES * RES
RGB_LEN = NUM_PIX * 3
NUM_FLOWER_CLASSES = 4
THRESHOLD = 0.4 # Above this probabilty, declare True for that flower class
# Eventually, test different #layers for improvement to final solution (bias and variance)
# Also change number of hidden nodes / size of each hidden layer (use layer dims for both)
def load_data():
"""
Loads all the image files along with labels into training set
Classified and labeled based on directory name = flower name
Does the same for test set
Returns:
train_set_x -- training set x with R, G, B values in order (flattened)
train_set_y -- training set y with labels 0, 1, 2, 3, 4 (0000, 1000, 0100, 0010, 0001)
1 = agapanthus
2 = ca_poppy
3 = nasturtium
4 = alyssum
0 = not a flower, random picture
test_set_x
test_set_y
"""
n_x = RGB_LEN
n_y = NUM_FLOWER_CLASSES
for flower_class, current_dir in enumerate(["../Data/square_images/01_agapanthus", "../Data/square_images/02_california_poppy", "../Data/square_images/03_nasturtium", "../Data/square_images/04_alyssum", "../Data/square_images/not_flower_random"]):
m = len([filename for filename in os.listdir(current_dir) if filename.endswith("JPG") or filename.endswith("jpeg") or filename.endswith("jpg")])
print("Number of training examples in", current_dir, "is", m)
curr_training_set_x = np.zeros((n_x, m)) # Array training examples as columns
curr_training_set_y = np.zeros((n_y, m)) # n_y is the number of output classes
i=0 # Don't enumerate because some non JEPG files might be present, or test in the for statement for JPG
for filename in os.listdir(current_dir):
if filename.endswith("JPG") or filename.endswith("jpeg") or filename.endswith("jpg"):
im = Image.open(current_dir + "/" + filename)
small = resizeimage.resize_cover(im, [RES, RES])
pixels = list(small.getdata())
flatten = [rgb_val for p in pixels for rgb_val in p] # Extract R G B values from the tuples into a long list
curr_training_set_x[:, i] = flatten # Store 3 * RES * RES values per example
if flower_class < NUM_FLOWER_CLASSES: # Last class is not_flower_random pictures, should be left as 0, 0, 0, 0
curr_training_set_y[flower_class, i] = 1
i=i+1
if flower_class == 0:
train_set_x = curr_training_set_x
train_set_y = curr_training_set_y
else:
train_set_x = np.append(train_set_x, curr_training_set_x, axis = 1)
train_set_y = np.append(train_set_y, curr_training_set_y, axis = 1)
for flower_class, current_dir in enumerate(["../Data/test_square_images/01_agapanthus", "../Data/test_square_images/02_california_poppy\
", "../Data/test_square_images/03_nasturtium", "../Data/test_square_images/04_alyssum", "../Data/test_square_images/not_flower_random"]):
m = len([filename for filename in os.listdir(current_dir) if filename.endswith("JPG") or filename.endswith("jpeg") or filename.endswith("jpg")])
print("Number of TEST examples in", current_dir, "is", m)
curr_test_set_x = np.zeros((n_x, m)) # Array test examples as columns
curr_test_set_y = np.zeros((n_y, m)) # n_y is the number of output classes
i=0 # Don't enumerate because some non JEPG files might be present, or test in the for statement for JPG
for filename in os.listdir(current_dir):
if filename.endswith("JPG") or filename.endswith("jpeg") or filename.endswith("jpg"):
im = Image.open(current_dir + "/" + filename)
small = resizeimage.resize_cover(im, [RES, RES])
pixels = list(small.getdata())
flatten = [rgb_val for p in pixels for rgb_val in p] # Extract R G B values from the tuples into a long list
curr_test_set_x[:, i] = flatten # Store 3 * RES * RES values per example
if flower_class < NUM_FLOWER_CLASSES: # Last class is not_flower_random pictures, should be left as 0, 0, 0, 0
curr_test_set_y[flower_class, i] = 1
i=i+1
if flower_class == 0:
test_set_x = curr_test_set_x
test_set_y = curr_test_set_y
else:
test_set_x = np.append(test_set_x, curr_test_set_x, axis = 1)
test_set_y = np.append(test_set_y, curr_test_set_y, axis = 1)
return train_set_x, train_set_y, test_set_x, test_set_y
def initialize_parameters(n_x, n_h, n_y):
"""
Arguments:
n_x: size of the input layer
n_y: size of the output layer
n_h: size of the hidden layers (Choose 2 layers for now, with same #hidden nodes - later make L layers, vary nodes)
Returns:
parameters: Python dictionary of parameters for the whole network -
W1: Weight matrix of shape (n_h, n_x)
b1: bias matrix of shape (n_h, 1)
W2: Weight matrix of shape (n_y, n_h)
b2: bias matric of shape (n_h, 1)
"""
# Initialize bias vectors to zero, and Weight matrices to a standard normal distribution from -0.01 to +0.01
W1 = np.random.randn(n_h, n_x) * 0.01
b1 = np.zeros((n_h, 1))
W2 = np.random.randn(n_y, n_h) * 0.01
b2 = np.zeros((n_y, 1))
# Assert shapes of matrices later here
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
def initialize_parameters_deep(layer_dims):
"""
Argument:
layer_dims: Python array (list) containing the dimensions (# hidden nodes) of each layer in the network
Returns:
parameters: Python dictionary containing the parameters W1, b1, W2, b2, and so on until WL and bL
Wl: Weight matrix of dimensions layer_dims[l], layer_dims[l-1]
bl: bias vector of shape layer_dims[l], 1
"""
parameters = {}
L = len(layer_dims) # Number of layers in network including input and output layers
# Later L refers to the number of layers in the network not including the input layer
# In actuality below, we assign parameters to L-1 layers, as the first layer contains the input dim
for l in range(1, L):
# Weight and bias matrices are needed for L-1 layers, labeled W1, W2... Wl-1, not counting input layer
parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01
parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
return parameters
def linear_forward(A, W, b):
"""
Implement the linear step in forward prop (without activation)
Arguments:
A: activation from previous layer (or input data in the case of A0 = X), shape: (size of prev layer, #examples)
W: Weight matrix, numpy array of shape (size of current layer, size of previous layer)
b: bias vector, numpy array of shape (size of current layer, 1)
Returns:
Z: linear forward prop step without activation, forms the input to the activation
cache: Python tuple, containing A, W and b, in order to do back prop later on
"""
Z = np.dot(W, A) + b
cache = (A, W, b)
return Z, cache
def sigmoid(Z):
"""
Implements the sigmoid activation in numpy
Arguments:
Z: numpy array of any shape
Returns:
A: output of sigmoid(z), same shape as Z
cache: returns Z as well, useful during backprop
"""
A = 1/(1+np.exp(-Z))
cache = Z
return A, cache
def relu(Z):
"""
Implement the RELU function.
Arguments:
Z: Output of the linear layer, of any shape
Returns:
A: Post-activation parameter, of the same shape as Z
cache: a python dictionary containing "A" ; stored for back prop later
"""
A = np.maximum(0,Z)
cache = Z
return A, cache
def linear_activation_forward(A_prev, W, b, activation):
"""
Implement the linear forward prop as well as the Activation, ie LINEAR --> ACTIVATION both
Arguments:
A_prev: activations from previous layer (or input data): (size of previous layer, number of examples)
W: Weight matrix, numpy array of shape (size of current layer, size of previous layer)
b: bias vector, numpy array of shape (size of the current layer, 1)
activation: the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
Returns:
A -- the output of the linear Weights plus bias step, plus activation function
cache -- a python tuple containing "linear_cache" and "activation_cache";
stored for computing back prop later
"""
if activation == "sigmoid":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
Z, linear_cache = linear_forward(A_prev, W, b) # linear cache contains A_prev, W and b
A, activation_cache = sigmoid(Z) # the Cache contains Z
elif activation == "relu":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
Z, linear_cache = linear_forward(A_prev, W, b) # linear_cache contains A_prev, W and b
A, activation_cache = relu(Z) # the Cache contains Z
cache = (linear_cache, activation_cache)
return A, cache
def forward_prop(X, parameters):
"""
Implement forward propagation for the [LINEAR->RELU]*(L-1) for the first L-1 layers, then->LINEAR->SIGMOID for last layer
Assumes 4 output classes, but with 5 possible outcomes: 0000, 1000, 0100, 0010, 0001
This can be changed to add more output classes (more flowers recognized)
Arguments:
X: numpy array of shape (input features, number of examples)
parameters: output of initialize_parameters_deep()
Returns:
AL: final post-activation value of final output layer (NUM_FLOWER_CLASSES, # examples)
caches: list of caches containing:
every cache of linear_activation_forward() (there are L-1 of them, indexed from 1 to L-1, eg W1, W2)
each individual cache is a tuple containing the linear cache (A, W, b) and activation cache (Z)
"""
caches = []
A = X
L = len(parameters) // 2 # number of layers in the neural network
# Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list.
for l in range(1, L):
A_prev = A
A, cache = linear_activation_forward(A_prev, parameters['W'+str(l)], parameters['b' + str(l)], "relu")
caches = caches + [cache] # for back prop later
# Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list.
AL, cache = linear_activation_forward(A, parameters['W'+str(L)], parameters['b' + str(L)], "sigmoid")
caches = caches + [cache]
assert(AL.shape == (NUM_FLOWER_CLASSES, X.shape[1]))
return AL, caches
def compute_cost(AL, Y):
"""
Implement Cost function as a cross entropy (logistic regression style) loss over NUM_FLOWER_CLASSES
Arguments:
AL: Vector of probabilities outputs for each class, corresponding to predictions for that label,
shape(NUM_FLOWER_CLASSES, # examples)
Y: True label vector, same shape as AL, contains labels like 0100 for 2nd flower class
Returns:
cost: Cross entropy cost (can be changed if we want different metrics for measuring loss)
"""
m = Y.shape[1]
# Compute individual costs for each flower class in a binary cross entropy / logistic regression way and sum
cost = 0
for i in range(NUM_FLOWER_CLASSES):
cost += (-1/m) * (np.dot(Y[i, :], np.log(AL[i, :]).T) + np.dot(1-Y[i, :], np.log(1-AL[i, :]).T))
cost = np.squeeze(cost)
assert(cost.shape == ())
return cost
## BEGIN BACK PROP FUNCTIONS
def relu_backward(dA, cache):
"""
Implement the backward propagation for a single RELU unit.
Arguments:
dA: post-activation gradient, of any shape
cache: 'Z' where we store for computing backward propagation efficiently
Returns:
dZ: Gradient of the cost with respect to Z
"""
Z = cache
dZ = np.array(dA, copy=True)
# When z <= 0, you should set dz to 0 as well.
dZ[Z <= 0] = 0
assert (dZ.shape == Z.shape)
return dZ
def sigmoid_backward(dA, cache):
"""
Implement the backward propagation for a single SIGMOID unit.
Arguments:
dA: post-activation gradient, of any shape
cache: 'Z' where we store for computing backward propagation efficiently
Returns:
dZ: Gradient of the cost with respect to Z
"""
Z = cache
s = 1/(1+np.exp(-Z))
dZ = dA * s * (1-s) #formula for derivative of sigmoid function
assert (dZ.shape == Z.shape)
return dZ
def linear_backward(dZ, cache):
"""
Implement the linear portion of backward propagation for a single layer (layer l)
Arguments:
dZ: Gradient of the cost with respect to the linear output (of current layer l)
cache: tuple of values (A_prev, W, b) coming from the forward propagation in the current layer
Returns:
dA_prev: Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
dW: Gradient of the cost with respect to W (current layer l), same shape as W
db: Gradient of the cost with respect to b (current layer l), same shape as b
"""
A_prev, W, b = cache
m = A_prev.shape[1]
dW = (1/m) * np.dot(dZ, A_prev.T)
db = (1/m) * np.sum(dZ, axis = 1, keepdims = True)
dA_prev = np.dot(W.T, dZ)
assert (dA_prev.shape == A_prev.shape)
assert (dW.shape == W.shape)
assert (db.shape == b.shape)
return dA_prev, dW, db
def linear_activation_backward(dA, cache, activation):
"""
Implement the backward propagation for the LINEAR and ACTIVATION steps for a given layer.
Arguments:
dA: post-activation gradient for current layer l
cache: tuple of values (linear_cache, activation_cache) stored during fwd prop for computing back prop efficiently
activation: the activation that was used in this layer, stored as a text string: "sigmoid" or "relu"
Returns:
dA_prev: Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
dW: Gradient of the cost with respect to W (current layer l), same shape as W
db: Gradient of the cost with respect to b (current layer l), same shape as b
"""
linear_cache, activation_cache = cache
if activation == "relu":
dZ = relu_backward(dA, activation_cache)
elif activation == "sigmoid":
dZ = sigmoid_backward(dA, activation_cache)
dA_prev, dW, db = linear_backward(dZ, linear_cache)
return dA_prev, dW, db
def back_prop(AL, Y, caches):
"""
Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID whole L layer network
Arguments:
AL: probability vector, output of the forward propagation
Y: true "label" vector (containing 0 if a given flower class is not present and 1 if it is present in the image)
caches: list of caches containing:
every cache of linear_activation_forward() with "relu" (caches[l], for l in range(L-1) i.e l = 0...L-2)
the cache of linear_activation_forward() with "sigmoid" (caches[L-1])
Returns:
grads: A dictionary with the gradients
grads["dA" + str(l)] = ...
grads["dW" + str(l)] = ...
grads["db" + str(l)] = ...
"""
grads = {}
L = len(caches) # the number of layers
m = AL.shape[1]
Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL
# Initializing the backpropagation
dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # Derivative of cost in compute_cost wrt AL
# FINAL Lth layer (SIGMOID -> LINEAR) back prop gradients.
# Inputs: "dAL, current_cache". Outputs: "grads["dAL-1"], grads["dWL"], grads["dbL"]
current_cache = caches[L-1]
grads["dA" + str(L-1)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, "sigmoid")
# Loop from l=L-2 to l=0
for l in reversed(range(L-1)):
# lth layer: (RELU -> LINEAR) back prop gradients.
# Inputs: "grads["dA" + str(l + 1)], current_cache".
# Outputs: "grads["dA" + str(l)] , grads["dW" + str(l + 1)] , grads["db" + str(l + 1)]
current_cache = caches[l]
# In the first round grads[dAL-1]has been set above already (L-2+1)
dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l+1)], current_cache, "relu")
grads["dA" + str(l)] = dA_prev_temp
grads["dW" + str(l + 1)] = dW_temp
grads["db" + str(l + 1)] = db_temp
return grads
def update_parameters(parameters, grads, learning_rate):
"""
Update parameters using gradient descent
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients, output of L_model_backward
Returns:
parameters -- python dictionary containing your updated parameters
parameters["W" + str(l)] = ...
parameters["b" + str(l)] = ...
"""
L = len(parameters) // 2 # number of layers in the neural network
# Update rule for each parameter. Use a for loop.
for l in range(L):
parameters["W" + str(l+1)] -= learning_rate * grads["dW" + str(l + 1)]
parameters["b" + str(l+1)] -= learning_rate * grads["db" + str(l + 1)]
return parameters
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009
"""
Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID.
Arguments:
X: data, numpy array of shape (RES * RES * 3, number of examples)
Y: true "label" one-hot vector with number of flower classes (0000, 1000, 0100, etc) (NUM_FLOWER_CLASSES, #examples)
layers_dims -- list containing the input size and each layer size, of length (number of layers + 1).
learning_rate -- learning rate of the gradient descent update rule
num_iterations -- number of iterations of the optimization loop
print_cost -- if True, it prints the cost every 100 steps
Returns:
parameters -- parameters learnt by the model. They can then be used to predict.
"""
costs = [] # keep track of cost
parameters = initialize_parameters_deep(layers_dims)
# Gradient Descent
for i in range(0, num_iterations):
# Forward propagation: [LINEAR -> RELU]*(L-1) -> LINEAR -> SIGMOID.
AL, caches = forward_prop(X, parameters)
cost = compute_cost(AL, Y)
# Back prop
grads = back_prop(AL, Y, caches)
parameters = update_parameters(parameters, grads, learning_rate)
# Print the cost every 100 training example
if print_cost and i % 100 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
if print_cost and i % 100 == 0:
costs.append(cost)
print(costs)
# plot the cost
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters
def predict(X, y, parameters):
"""
This function is used to predict the results of a L-layer neural network.
Arguments:
X: test data set of examples you would like to label using the parameters in the trained L-layer model network
y: test data set ground truth labels to assess how well the model is doing
parameters: parameters of the trained model
Returns:
p -- predictions for the given dataset X
"""
m = X.shape[1]
n = len(parameters) // 2 # number of layers in the neural network, 2 arrays of parameters per layer
p = np.zeros((NUM_FLOWER_CLASSES,m))
# Forward propagation
probs, caches = forward_prop(X, parameters) # probs contains the predictions and is shape: NUM_FLOWER_CLASSES, m
# convert probs to 0/1 predictions
for i in range(0, probs.shape[1]):
for j in range(0, NUM_FLOWER_CLASSES):
if probs[j,i] > THRESHOLD:
p[j,i] = 1
# else:
# p[j,i] = 0 # this should not be necessary since the matrix is initialized to zeros
print ("predictions: " + str(p))
print ("true labels: " + str(y))
print("Accuracy for Flower Class 1 Agapanthus: " + str(np.sum((p[0, :] == y[0, :])/m)))
return p
def print_mislabeled_images(classes, X, y, p):
"""
Plots images where predictions and truth were different.
X -- dataset
y -- true labels
p -- predictions
"""
a = p + y
mislabeled_indices = np.asarray(np.where(a == 1))
plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots
num_images = len(mislabeled_indices[0])
for i in range(num_images):
index = mislabeled_indices[1][i]
plt.subplot(2, num_images, i + 1)
plt.imshow(X[:,index].reshape(64,64,3), interpolation='nearest')
plt.axis('off')
plt.title("Prediction: " + classes[int(p[0,index])].decode("utf-8") + " \n Class: " + classes[y[0,index]].decode("utf-8"))
## BEGIN MAIN
tsx, tsy, test_x, test_y = load_data()
print(tsx.shape)
print(tsy.shape)
print(tsx)
print(tsy)
print(test_x.shape)
print(test_y.shape)
tsx = tsx/255
test_x = test_x/255
#layers_dims = [RES*RES*3, 20, 7, 5, 4] # 4-layer model
#L_layer_model(tsx, tsy, layers_dims, num_iterations = 3000, print_cost=True)
layers_dims = [RES*RES*3, 10, 4] # 2-layer model
parameters = L_layer_model(tsx, tsy, layers_dims, num_iterations = 3000, print_cost=True)
# do some predicting based on test
predict(test_x,test_y, parameters)
# add test set
# notes for next steps:
# gradient checking
# simpler networks performance seems better, explore
# bias and variance - check with differing numbers of training data
# save the parameters for later,
# save .npy files for later for training and testing
# Nan issues
# 0/0 is not 1, so what to do about the sigmoid intial cost for backprop, and derivative calc
|
#!/bin/python
# Head ends here
class Node:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distTo(self, target):
return abs(target.x - self.x) + abs(target.y - self.y)
def nextMove(posx, posy, board):
# the input x and y were reversed in Hackerrank puzzles.
bot_node = Node(posy, posx)
# find the nearest dirty node.
nearest_node = None
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == "d":
dirty_node = Node(j, i)
dist = dirty_node.distTo(bot_node)
#bot at the dirty node.
if dist == 0:
print "CLEAN"
return
if nearest_node is None or dist < nearest_node.distTo(bot_node):
nearest_node = dirty_node
# path finding.
output = None
if nearest_node is not None:
delta_x = nearest_node.x - bot_node.x
if delta_x < 0:
output = "LEFT"
elif delta_x > 0:
output = "RIGHT"
if output is not None:
print output
return
delta_y = nearest_node.y - bot_node.y
if delta_y < 0:
output = "UP"
elif delta_y > 0:
output = "DOWN"
if output is not None:
print output
return
# Tail starts here
if __name__ == "__main__":
pos = [int(i) for i in raw_input().strip().split()]
board = [[j for j in raw_input().strip()] for i in range(5)]
nextMove(pos[0], pos[1], board) |
from newton_raphson import *
import newton_raphson_test_base as tb
import numpy.linalg as la
# Vecteur colonne de test
f=np.matrix([[tb.f0], [tb.f1], [tb.f2]])
# Jacobienne de f
J=np.matrix([[tb.g00, tb.g01, tb.g02],[tb.g10, tb.g11, tb.g12],[tb.g20, tb.g21, tb.g22]])
# Conditions de test
U0=np.matrix([10., 10., 10.]).T
IMAX=400
EPS=10**(-14)
dx=np.ones(f.shape) * 10**(-12)
def print_result(head, U):
print(head)
print(" > U :", U[0].T)
print(" > ||f(U)|| :", la.norm(calc(f, U[0])))
print(" > Itérations :", U[1])
print()
def print_item(head, I):
print(head)
print(I)
print()
#-------------------------------------------------#
print ("Début des tests des implémentation de l'algorithme de Newton-Raphson")
print()
#-------------------------------------------------#
print (" Conditions de test :")
print (" > Point de départ U0 :", U0.T)
print ()
print (" > Nombre maximal d'itérations :", IMAX)
print ()
print (" > Précision demandée : ", EPS)
print ()
print (" > Variation transmises : ", dx.T)
print ()
#-------------------------------------------------#
print (" > f(U0) =", calc(f, U0).T)
print ()
#-------------------------------------------------#
print_result(" Méthode sans retour arrière et Jacobienne requise",
Newton_Raphson(f,J, U0, dx, IMAX, EPS))
#-------------------------------------------------#
print_result(" Méthode sans retour arrière et Jacobienne non requise",
Newton_Raphson_Auto_Jacob(f, U0, dx, IMAX, EPS))
#-------------------------------------------------#
print_result(" Méthode avec retour arrière et Jacobienne requise",
Backtracking_Newton_Raphson(f, J, U0, dx, EPS))
#-------------------------------------------------#
print_result(" Méthode avec retour arrière et Jacobienne non requise",
Backtracking_Newton_Raphson_Auto_Jacob(f, U0, dx, EPS))
#-------------------------------------------------#
print ("Fin des tests des implémentation de l'algorithme de Newton-Raphson")
|
from manejoArchivos import *
from usuarioService import *
import mysql.connector
from datetime import *
class BaseDeDatosService:
def __init__(self, nombreBase, nombreTabla, host, user, password):
self.nombreBase = nombreBase
self.nombreTabla = nombreTabla
self.host = host
self.user = user
self.password = password
def armarEntorno(self):
if(not self.existeLaBase()):
self.crearBaseDeDatos()
if(not self.existeLaTabla()):
self.crearTablaArchivosDrive()
def existeLaBase(self):
conexion1 = mysql.connector.connect(host= self.host, user=self.user, passwd=self.password)
query = "show databases"
result = self.ejecutarQueryExist(query, self.nombreBase, conexion1)
conexion1.close()
return result
def existeLaTabla(self):
conexion1 = self.conexionSQL()
query = "show tables"
result = self.ejecutarQueryExist(query,self.nombreTabla,conexion1)
conexion1.close()
return result
def crearBaseDeDatos(self):
conexion1 = mysql.connector.connect(host= self.host, user=self.user, passwd=self.password)
cursor1 = conexion1.cursor()
cursor1.execute("CREATE DATABASE %s" % self.nombreBase)
conexion1.close()
def crearTablaArchivosDrive(self):
query = "CREATE TABLE %s (id INT AUTO_INCREMENT PRIMARY KEY, file_id VARCHAR(255), nombre VARCHAR(255), ext VARCHAR(255), owner VARCHAR(255), visibilidad VARCHAR(255), fecha_modificacion DATETIME)" % self.nombreTabla
self.ejecutarQuery(query)
def conexionSQL(self):
return mysql.connector.connect(host= self.host, user=self.user, passwd=self.password, database= self.nombreBase)
def guardarSiNoExiste(self, file):
if(not self.existeArchivoEnTabla(file) or self.seModifico(file)):
self.guardarArchivo(file)
def existeArchivoEnTabla(self, file):
query = "SELECT file_id FROM " + self.nombreTabla
archivos = self.ejecutarQueryFetchAll(query)
for archivo in archivos:
if(archivo[0] == file['id']):
return True
return False
def seModifico(self, file):
query = "SELECT fecha_modificacion FROM archivos_drive WHERE file_id = '%s'" % file['id']
fechasModificaciones = self.ejecutarQueryFetchAll(query)
modificacionReciente = fechasModificaciones[0][0]
for fecha in fechasModificaciones:
if(fecha[0] > modificacionReciente):
modificacionReciente = fecha[0]
return modificacionReciente < datetime.strptime(file['modifiedDate'][0:19],'%Y-%m-%dT%H:%M:%S')
#Formato RFC 3339 '%Y-%m-%dT%H:%M:%S.%fZ'
#Se le debe colocar el [0:19] dado que el file['modifiedDate'] trae consigo milesimas de segundos (.%f) que no son captados por archivo[1] por el tipo de datetime de la base de datos
def guardarArchivo(self, file):
conexion1 = self.conexionSQL()
cursor1 = conexion1.cursor()
query ="insert into archivos_drive(nombre, ext, owner, visibilidad, fecha_modificacion, file_id) values (%s,%s,%s,%s,%s,%s)"
datos = (file['title'], file['fileExtension'], ' '.join(file['ownerNames']), self.visibilidadDe(file), file['modifiedDate'], file['id'])
cursor1.execute(query, datos)
conexion1.commit()
conexion1.close()
def visibilidadDe(self, file):
if (file['shared']):
return 'Publico'
else:
return 'Privado'
def drop(self):
if(self.existeLaBase()):
conexion1 = mysql.connector.connect(host= self.host, user=self.user, passwd=self.password)
cursor1 = conexion1.cursor()
cursor1.execute("DROP DATABASE %s" % self.nombreBase)
conexion1.close()
def getArchivos(self):
return self.ejecutarQueryFetchAll("SELECT * FROM %s" % self.nombreTabla)
def ejecutarQueryFetchAll(self, query):
conexion1 = self.conexionSQL()
cursor1 = conexion1.cursor()
cursor1.execute(query)
result = cursor1.fetchall()
conexion1.close()
return result
def ejecutarQuery(self, query):
conexion1 = self.conexionSQL()
cursor1 = conexion1.cursor()
cursor1.execute(query)
conexion1.close()
def ejecutarQueryExist(self, query, value, conexion):
cursor1 = conexion.cursor()
cursor1.execute(query)
for registro in cursor1:
if (registro[0] == value):
return True
return False |
import unittest
import unittest.mock as mock
from imagemounter.exceptions import NoRootFoundError
from imagemounter.parser import ImageParser
from imagemounter.volume import Volume
class ReconstructionTest(unittest.TestCase):
def test_no_volumes(self):
parser = ImageParser()
parser.add_disk("...")
with self.assertRaises(NoRootFoundError):
parser.reconstruct()
def test_no_root(self):
parser = ImageParser()
disk = parser.add_disk("...")
v1 = Volume(disk)
v1.mountpoint = '...'
v1.info['lastmountpoint'] = '/etc/x'
v2 = Volume(disk)
v2.mountpoint = '....'
v2.info['lastmountpoint'] = '/etc'
disk.volumes.volumes = [v1, v2]
with self.assertRaises(NoRootFoundError):
parser.reconstruct()
def test_simple(self):
parser = ImageParser()
disk = parser.add_disk("...")
v1 = Volume(disk)
v1.mountpoint = '...'
v1.info['lastmountpoint'] = '/'
v2 = Volume(disk)
v2.mountpoint = '....'
v2.info['lastmountpoint'] = '/etc'
disk.volumes.volumes = [v1, v2]
with mock.patch.object(v2, "bindmount") as v2_bm:
parser.reconstruct()
v2_bm.assert_called_once_with(".../etc")
def test_multiple_roots(self):
parser = ImageParser()
disk = parser.add_disk("...")
v1 = Volume(disk)
v1.index = '1'
v1.mountpoint = '...'
v1.info['lastmountpoint'] = '/'
v2 = Volume(disk)
v2.index = '2'
v2.mountpoint = '....'
v2.info['lastmountpoint'] = '/'
v3 = Volume(disk)
v3.index = '3'
v3.mountpoint = '.....'
v3.info['lastmountpoint'] = '/etc'
disk.volumes.volumes = [v1, v2, v3]
with mock.patch.object(v1, "bindmount") as v1_bm, mock.patch.object(v2, "bindmount") as v2_bm, \
mock.patch.object(v3, "bindmount") as v3_bm:
parser.reconstruct()
v1_bm.assert_not_called()
v2_bm.assert_not_called()
v3_bm.assert_called_with('.../etc')
|
import ast
import pandas as pd
import requests
from io import BytesIO
from jinja2 import Template
from django.apps import apps
from . import code_templates
GDRIVE_BASE_URL = "https://docs.google.com/spreadsheet/ccc?key="
def model_fields_to_dict(sample):
"""
returns a list of dictionary fields from a given model
:param sample: a model class
"""
model_fields = []
for x in sample._meta.get_fields():
field_dict = {}
if 'reverse_related' in f"{type(x)}":
continue
else:
field_dict['field_name'] = x.name
field_dict['field_type'] = type(x).__name__
if x.verbose_name:
field_dict['field_verbose_name'] = x.verbose_name
else:
field_dict['field_verbose_name'] = x.name
if x.help_text:
field_dict['field_helptext'] = x.help_text
else:
field_dict['field_helptext'] = x.name
if field_dict['field_type'] in ['ForeignKey', 'ManyToManyField']:
field_dict['related_class'] = f"{x.related_model.__name__}"
field_dict['related_name'] = f"{x.related_query_name()}"
model_fields.append(field_dict)
return model_fields
def get_classdict_from_model(sample):
"""
returns a dict describing a model and its fields
:param sample: a model class
"""
class_dict = {}
class_dict['model_name'] = f"{sample.__name__}"
class_dict['model_verbose_name'] = f"{sample._meta.verbose_name}"
class_dict['model_helptext'] = f"{sample.__doc__.strip()}"
class_dict['model_representation'] = False
class_dict['model_order'] = False
class_dict['model_fields'] = model_fields_to_dict(sample)
return class_dict
def app_to_classdicts(app_name):
class_dicts = []
app_models = apps.get_app_config(app_name).get_models()
for x in app_models:
class_dicts.append(get_classdict_from_model(x))
return class_dicts
def gsheet_to_df(sheet_id):
url = f"{GDRIVE_BASE_URL}{sheet_id}&output=csv"
r = requests.get(url)
print(r.status_code)
data = r.content
df = pd.read_csv(BytesIO(data))
return df
def df_to_classdicts(df):
"""
parses an Excel sheet and yields dicts of model definitions
:param df: a dataframe
:return: yields dicts
"""
classes = df.groupby('class name technical')
for x in classes:
local_df = x[1]
class_dict = {}
class_dict['model_name'] = x[0]
class_dict['model_helptext'] = x[1]['class name helptext'].iloc[0].replace('\n', '')
class_dict['model_verbose_name'] = x[1]['class name verbose_name'].iloc[0].replace('\n', '')
try:
source_table = x[1]['source_table'].iloc[0]
except KeyError:
source_table = None
if source_table is not None and isinstance(source_table, str):
class_dict['source_table'] = source_table
else:
class_dict['source_table'] = None
try:
natural_primary_key = x[1]['natural primary key'].iloc[0]
except KeyError:
natural_primary_key = 'legacy_id'
if natural_primary_key is not None and isinstance(natural_primary_key, str):
class_dict['natural_primary_key'] = natural_primary_key
else:
class_dict['natural_primary_key'] = "legacy_id"
class_dict['model_representation'] = "{}".format(
x[1]['class self representation'].iloc[0]
).lower()
class_dict['model_order'] = "{}".format(
x[1]['class object order by field'].iloc[0]
).lower()
class_dict['model_fields'] = []
for i, row in local_df.iterrows():
org_field_name = row['field name technical'].lower().replace('/', '_').replace('|', '_')
org_field_name = org_field_name.replace('__', '_')
if org_field_name[0].isdigit():
org_field_name = f"xx_{org_field_name}"
field_name = org_field_name.replace('-', '_').replace('\n', '').replace(' ', '')
if isinstance(field_name, str) and isinstance(row['field type'], str):
field = {}
field['field_name'] = field_name
# public yes / no
try:
field_public = row['public (yes|no)']
except KeyError:
field_public = "yes"
if field_public is not None and isinstance(field_public, str):
if 'yes' in field_public:
field['field_public'] = True
elif 'no' in field_public:
field['field_public'] = False
else:
field['field_public'] = True
else:
field['field_public'] = True
# value from lookup
try:
value_from = row['value from']
except KeyError:
value_from = None
if value_from is not None and isinstance(value_from, str):
field['value_from'] = value_from.replace('\n', '').replace(' ', '').replace('\\', '/')
else:
field['value_from'] = False
# maps to arche
try:
arche_prop = row['maps to ARCHE']
except KeyError:
arche_prop = None
if arche_prop is not None and isinstance(arche_prop, str):
field['arche_prop'] = arche_prop.replace('\n', '').replace(' ', '')
else:
field['arche_prop'] = False
try:
arche_prop_str_template = row['Mapping extra app work']
except KeyError:
arche_prop_str_template = None
if arche_prop_str_template is not None and isinstance(arche_prop_str_template, str):
field['arche_prop_str_template'] = arche_prop_str_template.replace('\n', '')
else:
field['arche_prop_str_template'] = False
# field type
if ' ' in row['field type'].strip():
continue
if row['field type'].startswith('Bool'):
field['field_type'] = 'BooleanField'
elif '|' in row['field type']:
field_type = row['field type'].split('|')[0]
if field_type == 'FK':
field['field_type'] = 'ForeignKey'
else:
field['field_type'] = 'ManyToManyField'
# through param
if '#' in row['field type']:
rel_class = row['field type'].split('|')[1]
field['through'] = "".join(rel_class.split('#'))
field['related_class'] = rel_class.split('#')[0]
else:
field['related_class'] = row['field type'].split('|')[1].split(':')[0].strip()
temp_related_name = "rvn_{}_{}_{}".format(
x[0].lower(),
field_name,
field['related_class'].lower().strip()
).replace('__', '_')
field['related_name'] = temp_related_name
elif row['field type'] == "URI":
field['field_type'] = "CharField"
elif row['field type'].startswith('Integ'):
field['field_type'] = "IntegerField"
elif row['field type'].startswith('Float'):
field['field_type'] = "FloatField"
elif row['field type'].startswith('Point'):
field['field_type'] = "PointField"
elif row['field type'].startswith('TextF'):
field['field_type'] = "TextField"
elif row['field type'].startswith('DateR'):
field['field_type'] = "DateRangeField"
elif row['field type'].startswith('Date'):
field['field_type'] = "DateField"
elif row['field type'] == "CharField":
field['field_type'] = "CharField"
elif row['field type'] == "ChoiceField":
if isinstance(row['choices'], str):
field['choices'] = ast.literal_eval(row['choices'])
field['field_type'] = "CharField"
else:
continue
if isinstance(row['verbose field name'], str):
field['field_verbose_name'] = row['verbose field name'].replace('\n', '')
else:
field['field_verbose_name'] = field_name
if isinstance(row['helptext'], str):
field['field_helptext'] = row['helptext'].replace('\n', '')
else:
field['field_helptext'] = f"helptext for {field_name}"
class_dict['model_fields'].append(field)
yield class_dict
def class_dicst_to_df(app_name):
""" creates a DataFrame holding information about Models and Properties """
class_dicts = app_to_classdicts(app_name)
model_props = [
'model_name',
'model_verbose_name',
'model_helptext',
]
data = []
for x in class_dicts:
for key, value in x.items():
if isinstance(value, list):
for item in value:
row = {}
for mp in model_props:
row[mp] = x[mp]
for f_key, f_value in item.items():
row[f_key] = f_value
data.append(row)
df = pd.DataFrame(data)
return df
def serialize_data_model(dicts, app_name="my_app", file_name='models.py'):
t = Template(code_templates.MODELS_PY)
output = t.render(
data=dicts,
app_name=app_name
)
with open(file_name, "w") as text_file:
print(output, file=text_file)
return file_name
def serialize_admin(dicts, app_name="my_app", file_name='admin.py'):
t = Template(code_templates.ADMIN_PY)
output = t.render(
data=dicts,
app_name=app_name
)
with open(file_name, "w") as text_file:
print(output, file=text_file)
return file_name
def serialize_tables(dicts, app_name="my_app", file_name='tables.py'):
t = Template(code_templates.TABLES_PY)
output = t.render(
data=dicts,
app_name=app_name
)
with open(file_name, "w") as text_file:
print(output, file=text_file)
return file_name
def serialize_views(dicts, app_name="my_app", file_name='views.py'):
t = Template(code_templates.VIEWS_PY)
output = t.render(
data=dicts,
app_name=app_name
)
with open(file_name, "w") as text_file:
print(output, file=text_file)
return file_name
def serialize_forms(dicts, app_name="my_app", file_name='forms.py'):
t = Template(code_templates.FORMS_PY)
output = t.render(
data=dicts,
app_name=app_name
)
with open(file_name, "w") as text_file:
print(output, file=text_file)
return file_name
def serialize_filters(dicts, app_name="my_app", file_name='filters.py'):
t = Template(code_templates.FILTERS_PY)
output = t.render(
data=dicts,
app_name=app_name
)
with open(file_name, "w") as text_file:
print(output, file=text_file)
return file_name
def serialize_urls(dicts, app_name="my_app", file_name='urls.py'):
t = Template(code_templates.URLS_PY)
output = t.render(
data=dicts,
app_name=app_name
)
with open(file_name, "w") as text_file:
print(output, file=text_file)
return file_name
def serialize_dal_views(dicts, app_name="my_app", file_name='urls.py'):
t = Template(code_templates.DAL_VIEW_PY)
output = t.render(
data=dicts,
app_name=app_name
)
with open(file_name, "w") as text_file:
print(output, file=text_file)
return file_name
def serialize_dal_urls(dicts, app_name="my_app", file_name='urls.py'):
t = Template(code_templates.DAL_URLS_PY)
output = t.render(
data=dicts,
app_name=app_name
)
with open(file_name, "w") as text_file:
print(output, file=text_file)
return file_name
# code example on how to use it:
# from appcreator import creator
# classdict = creator.app_to_classdicts("my_app")
# for x in dir(creator):
# if x.startswith('seri'):
# func = getattr(creator, x)
# func(classdict, app_name="my_app")
|
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 17 12:36:19 2021
@author: gerry
"""
import random
def fleip_eller_fakta():
uttalelse = []
uttalelse.append(["Tigere har striper", "Fakta"])
uttalelse.append(["Jeg har 2 katter", "Fakta"])
uttalelse.append(["Jeg har 1 hund", "Fleip"])
uttalelse.append(["Kattene mine er oransj", "Fleip"])
return uttalelse
def spill_fleip_eller_fakta():
fef_uttalelse = fleip_eller_fakta()
random.shuffle(fef_uttalelse)
resultat = 0
for s in fef_uttalelse:
print("Fleip eller fakta: " + s[0])
svar = input("Fleip eller Fakta: ")
if svar == s[1]:
print("Riktig!")
resultat += 1
else:
print("Ikke riktig =(")
print("Ditt resultat ble: " + str(resultat))
spill_fleip_eller_fakta() |
from django import forms
from .models import sampledata
class formdata(forms.ModelForm):
class Meta:
model = sampledata
fields = '__all__' |
from arvore import Arvore
import sys
nome_arquivo = sys.argv[1]
with open(nome_arquivo, 'r') as arquivo:
genoma = ''
for linha in arquivo:
if not linha.startswith('>'):
genoma += linha.replace('\n', '')
arvore = Arvore(genoma)
arvore.maior_substring_repetida()
|
# get the number of marks
number_of_marks = int(input("Enter the number of marks: "))
# initialize total
total = 0
# compute the total of the marks
for i in range(number_of_marks):
# get a mark from the user and add to total
mark = float(input("Enter a mark: "))
total = total + mark
# compute average based on total
average = total/number_of_marks
print("The average of the " + str(number_of_marks) + " marks is " +str(average)) |
# Пользователь вводит время в секундах. Переведите время в часы,
# минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк.
seconds_input = int(input('Введите время в секундах: '))
day = seconds_input // 86400
hours = (seconds_input // 3600) % 24
minutes = (seconds_input // 60) % 60
seconds = seconds_input % 60
if day == 1:
day_text = 'днь'
elif 1 < day < 5:
day_text = 'дня'
else:
day_text = 'дней'
print(f'Результат перевода секунд в формат чч:мм:сс - {(seconds_input // 3600):02}:{minutes:02}:{seconds:02}')
print(f'Если нужно еще выводить и день то вот держите - {day} {day_text} {hours:02}:{minutes:02}:{seconds:02}')
|
from NTWebsite.improtFiles.processor_import_head import *
from NTWebsite.improtFiles.models_import_head import *
from NTWebsite.Config import AppConfig as AC
from NTWebsite.Config import DBConfig as DC
def indexView(request):
return HttpResponseRedirect("/Topic/List/0/LE/1")
def PaginatorInfoGet(objects, number, URLParams):
if objects:
ObjectsPaginator = Paginator(list(objects), number)
ObjectList = Paginator(list(objects), number).page(
int(URLParams['PageNumber']))
Paginator_num_pages = ObjectsPaginator.num_pages
Paginator_href = "/%s/%s/%s/%s/" % (
URLParams['Region'], URLParams['Part'], URLParams['FilterValue'], URLParams['Order'])
return {'ObjectList': ObjectList, 'ObjectsPaginator': ObjectsPaginator, 'Paginator_num_pages': Paginator_num_pages, 'Paginator_Href': Paginator_href}
else:
return {'ObjectList': [], 'ObjectsPaginator': '', 'Paginator_num_pages': 0, 'Paginator_Href': ''}
def GetNotificationCount(requestObject):
if requestObject.user.is_authenticated:
return str(QRC('Notification.objects.filter(TargetUser=%s).count()', None, requestObject.user))
else:
return '0'
def FetchTopic(request):
if request.method == 'POST':
if request.user.is_authenticated:
TopicObject = QRC('TopicInfo.objects.get(ObjectID=%s)',
0, request.POST.get('TopicID'))
TopicID = str(TopicObject.ObjectID)
Title = TopicObject.Title
Content = TopicObject.Content
Category = TopicObject.Category.Name
themes = []
for theme in TopicObject.Theme.all():
themes.append(theme.Name)
Themes = '&'.join(themes)
jsondata = json.dumps({'TopicID': TopicID, 'Title': Title, 'Content': Content,
'Category': Category, 'Themes': Themes}, ensure_ascii=False)
return HttpResponse(jsondata)
def PublishTopic(request):
if request.method == 'POST':
if request.user.is_authenticated:
InsertDataDict = {'Title': request.POST.get('Title'),
'Category': request.POST.get('Category'),
'Content': request.POST.get('Content'),
'Description': request.POST.get('Description'), }
TopicID = request.POST.get('TopicID')
Themes = request.POST.get('Themes')
InsertDataDict['Category'] = QRC(
'TopicCategoryInfo.objects.get(Name=%s)', None, InsertDataDict['Category'])
# 将主题按&分割后使用get_or_create有就返回,没有就创建了返回
ThemeObjects = []
for Theme in Themes.split('&'):
ThemeObjects.append(
QRC('TopicThemeInfo.objects.get_or_create(Name=%s)', None, Theme)[0])
try:
# 放在try里面执行,避免图片被移动后,检查出标题重复的问题
InsertDataDict['Content'] = mMs.MovePicToSavePath(
InsertDataDict['Content'])
# 如果Topic有值则为编辑文章
if TopicID:
mMs.RemovePicFromSavePath(
TopicID, InsertDataDict['Content'])
Topic = TopicInfo.objects.filter(
ObjectID=TopicID).update(**InsertDataDict)
Topic = TopicInfo.objects.get(ObjectID=TopicID)
else:
# 不用QRC的原因是ContentText文章中的引号容易出现问题!
Topic = TopicInfo.objects.create(Title=InsertDataDict['Title'],
Content=InsertDataDict[
'Content'],
Description=InsertDataDict[
'Description'],
Category=InsertDataDict[
'Category'],
Publisher=request.user)
Topic.Theme.clear()
Topic.Theme.add(*ThemeObjects)
Topic.save()
CounterOperate(QRC('User.objects.get(id=%s)', 0,
request.user.id), 'TCount', '+')
return HttpResponse('ok')
except Exception as e:
raise e
return HttpResponse(str(e))
else:
return HttpResponse('login')
def PublishRollCall(request):
if request.user.is_authenticated:
RollCallTitle = request.POST.get('RollCallTitle')
TargetUserNick = request.POST.get('TargetUserNick')
RollCallContent = request.POST.get('RollCallContent')
TargetUser = QRC('User.objects.get(Nick=%s)', None, TargetUserNick)
BlackListRecord = QRC(
'BlackList.objects.filter(Enforceder=%s,Handler=%s)', None, request.user, TargetUser)
if TargetUser:
if BlackListRecord:
return HttpResponse("用户:'" + TargetUserNick + "'" + '已经屏蔽您!')
else:
try:
NewRollCall = QRC('RollCallInfo.objects.create(Title=%s,Publisher=%s,Target=%s)', 0,
RollCallTitle, request.user, QRC('User.objects.get(Nick=%s)', None, TargetUserNick))
NewDialogue = QRC(
'RollCallDialogue.objects.create(RollCallID=%s,Publisher=%s,Content=%s)', 0, NewRollCall, request.user, RollCallContent)
CounterOperate(QRC('RollCallInfo.objects.get(ObjectID=%s)', 0,
NewRollCall.ObjectID), 'Comment', '+')
AddNotification('RollCall', NewRollCall.ObjectID, NewDialogue.ObjectID, QRC(
'User.objects.get(Nick=%s)', None, TargetUserNick), request.user)
return HttpResponse('publishok')
except Exception as e:
if 'UNIQUE' in str(e):
return HttpResponse('titleisexisted')
else:
raise e
else:
return HttpResponse("用户:'" + TargetUserNick + "'" + '不存在!')
else:
return HttpResponse('login')
def PermissionConfirm(type, Object, request, URLParams):
ReturnList = []
items = []
if isinstance(Object, Iterable):
items = Object
else:
if Object:
items.append(Object)
else:
return 0
for item in items:
Permission_Sizer = {}
if type != 'UserProfileInfo':
if request.user.is_authenticated:
if request.user == item.Publisher:
Permission_Sizer['VoteBtn'] = 'disabled'
Permission_Sizer['Vote1Status'] = ''
Permission_Sizer['Vote0Status'] = ''
Permission_Sizer['DonateBtn'] = 'hidden'
Permission_Sizer['TipOffBtn'], Permission_Sizer[
'TipOffStatus'] = ('hidden', '投诉')
Permission_Sizer['CloseBtn'] = 'Close' if URLParams[
'Region'] in 'SpecialTopic' else 'Delete'
Permission_Sizer['ShareBtn'] = ''
Permission_Sizer['CollectBtn'], Permission_Sizer[
'CollectStatus'] = ('hidden', '收藏')
Permission_Sizer['EditBtn'] = ''
# Comment特有
Permission_Sizer['ChatBtn'] = ''
Permission_Sizer['ReplayBtn'] = 'hidden'
# RollCall特有
Permission_Sizer['ReplayBlock'] = ''
Permission_Sizer['ReplayBlockSite'] = ''
else:
Permission_Sizer['VoteBtn'] = ''
Permission_Sizer['Vote1Status'] = 'is-active' if QRC(
'Attitude.objects.filter(ObjectID=%s,Point=1,Publisher=%s)', 0, item.ObjectID, request.user) else ''
Permission_Sizer['Vote0Status'] = 'is-active' if QRC(
'Attitude.objects.filter(ObjectID=%s,Point=0,Publisher=%s)', 0, item.ObjectID, request.user) else ''
Permission_Sizer['DonateBtn'] = ''
Permission_Sizer['TipOffBtn'], Permission_Sizer['TipOffStatus'] = ('', '已投诉') if QRC(
'TipOffBox.objects.filter(ObjectID=%s,Publisher=%s)', 0, item.ObjectID, request.user) else ('', '投诉')
Permission_Sizer['CloseBtn'] = 'Close'
Permission_Sizer['ShareBtn'] = ''
Permission_Sizer['CollectBtn'], Permission_Sizer['CollectStatus'] = ('', '取消收藏') if QRC(
'Collection.objects.filter(ObjectID=%s,Publisher=%s)', 0, item.RollCallID.ObjectID if hasattr(item, 'RollCallID') else item.ObjectID, request.user) else ('', '收藏')
Permission_Sizer['EditBtn'] = 'hidden'
# Comment特有
Permission_Sizer['ChatBtn'] = ''
Permission_Sizer['ReplayBtn'] = ''
# RollCall特有
Permission_Sizer['ReplayBlock'] = '' if request.user == (
item.RollCallID.Target if hasattr(item, 'RollCallID') else '') else 'hidden'
Permission_Sizer['ReplayBlockSite'] = 'right' if request.user == (
item.RollCallID.Target if hasattr(item, 'RollCallID') else '') else ''
else:
Permission_Sizer['VoteBtn'] = ''
Permission_Sizer['Vote1Status'] = ''
Permission_Sizer['Vote0Status'] = ''
Permission_Sizer['DonateBtn'] = ''
Permission_Sizer['TipOffBtn'], Permission_Sizer[
'TipOffStatus'] = ('', '投诉')
Permission_Sizer['CloseBtn'] = 'Close'
Permission_Sizer['ShareBtn'] = ''
Permission_Sizer['CollectBtn'], Permission_Sizer[
'CollectStatus'] = ('', '收藏')
Permission_Sizer['EditBtn'] = 'hidden'
# Comment特有
Permission_Sizer['ChatBtn'] = ''
Permission_Sizer['ReplayBtn'] = ''
# RollCall特有
Permission_Sizer['ReplayBlock'] = 'hidden'
Permission_Sizer['ReplayBlockSite'] = ''
else:
TargetUser = QRC('User.objects.get(id=%s)',
None, URLParams['FilterValue'])
if TargetUser == request.user:
Permission_Sizer['VisitorIdentity'] = 'Self'
Permission_Sizer['VisitorOAuth-Read'] = ''
Permission_Sizer['VisitorOAuth-Edit'] = ''
Permission_Sizer['VisitorOAuth-Link'] = ''
Permission_Sizer['VisitorOAuth-Block'] = ''
else:
Permission_Sizer['VisitorIdentity'] = 'Others'
Permission_Sizer['VisitorOAuth-Read'] = 'readonly'
Permission_Sizer['VisitorOAuth-Edit'] = 'hidden'
Permission_Sizer['VisitorOAuth-Link'] = 'Linked' if QRC(
'UserLink.objects.get(UserBeLinked=%s,UserLinking=%s)', 0, TargetUser, request.user) else 'Link'
Permission_Sizer['VisitorOAuth-Block'] = 'Blocked' if QRC(
'BlackList.objects.get(Enforceder=%s,Handler=%s)', 0, TargetUser, request.user) else 'Block'
ReturnList.append((item, Permission_Sizer))
return ReturnList
def ContextConfirm(request, **Params):
NotificationCount = GetNotificationCount(request)
# 文章分类信息获取
CategoryList = QRC('TopicCategoryInfo.objects.all()', None)
# 推荐发布者信息获取
PublisherList = QRC("PublisherList.objects.all()", None)
# 生成上下文字典
ContextDict = {"Layout_Sizer": Params['URLParams'],
"ExportItem_UserInfo": Params['User'] if 'User' in Params else '',
"ExportList_Topic": Params['Object'] if 'Object' in Params else '',
"ExportList_Cards": Params['PaginatorDict']['ObjectList'] if 'PaginatorDict' in Params else '',
"ExportList_Categorys": CategoryList,
"ExportList_Publishers": PublisherList,
"Paginator_num_pages": Params['PaginatorDict']['Paginator_num_pages'] if 'PaginatorDict' in Params else '',
"Current_Pagenumber": Params['URLParams']['PageNumber'] if 'URLParams' in Params else '',
"Paginator_Href": Params['PaginatorDict']['Paginator_Href'] if 'PaginatorDict' in Params else '',
"Search_Placeholder": Params['APPConf'].TopicHotKeyWord if 'APPConf' in Params else '',
"NotificationCount": NotificationCount}
return ContextDict
def CommentPackage(CommentObjects):
if CommentObjects:
CommentCards = []
for CommentObject in CommentObjects:
if CommentObject[0].Parent:
ParentCommentObject = QRC(
'CommentInfo.objects.get(CommentID=%s)', 0, CommentObject[0].Parent)
CommentCards.append(
('1', ParentCommentObject, CommentObject))
else:
CommentCards.append(('0', '', CommentObject))
return CommentCards
else:
return 0
def ReadIPRecord(IP, ID, type):
ReadsIP.objects.get_or_create(IP=IP, ObjectID=ID, Type=type)
def CounterOperate(object, field, method):
print("***************")
exec("object.%s = F('%s')%s1" % (field, field, method))
exec('object.save()')
return exec('object.refresh_from_db()')
def AttitudeOperate(request):
if request.method == 'POST':
Type = 'Topic' if request.POST.get(
'Type') in 'SpecialTopic' else request.POST.get('Type')
ObjectID = request.POST.get('ObjectID')
Title = QRC(Type + ('Info.objects.get(ObjectID=%s)' if Type != 'Comment' else 'Info.objects.get(CommentID=%s)'),
None, ObjectID).Content[0:10]
Point = request.POST.get('Point')
if request.user.is_authenticated:
attitude = QRC(
'Attitude.objects.filter(ObjectID=%s,Type=%s,Publisher=%s)', 0, ObjectID, Type, request.user)
if attitude:
if attitude[0].Point == int(Point):
attitude.delete()
CounterOperate(QRC(Type + ('Info.objects.get(ObjectID=%s)' if Type != 'Comment' else 'Info.objects.get(CommentID=%s)'), 0,
ObjectID), 'Like' if int(Point) == 1 else 'Dislike', '-')
return HttpResponse('Cancel')
else:
Attitude.objects.filter(
ObjectID=ObjectID, Type=Type, Publisher=request.user).update(Point=int(Point))
CounterOperate(QRC(Type + ('Info.objects.get(ObjectID=%s)' if Type != 'Comment' else 'Info.objects.get(CommentID=%s)'), 0,
ObjectID), 'Like' if int(Point) == 1 else 'Dislike', '+')
CounterOperate(QRC(Type + ('Info.objects.get(ObjectID=%s)' if Type != 'Comment' else 'Info.objects.get(CommentID=%s)'), 0, ObjectID),
'Like' if abs(int(Point) - 1) == 1 else 'Dislike', '-')
return HttpResponse('Become')
else:
Attitude.objects.create(
ObjectID=ObjectID, Type=Type, Point=int(Point), Publisher=request.user)
CounterOperate(QRC(Type + ('Info.objects.get(ObjectID=%s)' if Type != 'Comment' else 'Info.objects.get(CommentID=%s)'), 0,
ObjectID), 'Like' if int(Point) == 1 else 'Dislike', '+')
return HttpResponse('Confirm')
else:
return HttpResponse('login')
@csrf_exempt
def UploadImg(request):
if request.method == 'POST':
return HttpResponse(mMs.PicUploadOperate(request.FILES['upload']))
def TipOff(request):
if request.method == 'POST':
Type = request.POST.get('Type')
TopicID = request.POST.get('TopicID')
Content = request.POST.get('Content')
if request.user.is_authenticated:
userObject = QRC('User.objects.get(id=%s)', None, request.user.id)
TipOffObject = QRC(
'TipOffBox.objects.filter(ObjectID=%s,Publisher=%s)', 0, TopicID, userObject)
if TipOffObject:
return HttpResponse('cancel')
else:
QRC('TipOffBox.objects.create(ObjectID=%s, Publisher=%s, Type=%s, Content=%s)',
0, TopicID, userObject, Type, Content)
return HttpResponse('success')
else:
return HttpResponse('login')
def Replay(request):
if request.method == 'POST':
temp_Map = {'Topic': 'TRCount',
'SpecialTopic': 'SRCount', 'RollCall': 'RCount'}
Type = request.POST.get('Type')
ObjectID = request.POST.get('ObjectID')
Content = request.POST.get('Content')
ParentID = request.POST.get('ParentID')
if request.user.is_authenticated:
if Type in 'SpecialTopic':
ReplayObject = QRC('CommentInfo.objects.create(ObjectID=%s,Content=%s,Parent=%s,Type=%s,Publisher=%s)',
0, ObjectID, Content, ParentID, Type, request.user)
AddNotification(Type, ObjectID, ReplayObject.CommentID, QRC('CommentInfo.objects.get(CommentID=%s)', None,
ParentID).Publisher if ParentID else QRC(Type.replace('Special','') + 'Info.objects.get(ObjectID=%s)', None, ObjectID).Publisher, request.user)
else:
RollCall = QRC(
'RollCallInfo.objects.get(ObjectID=%s)', None, ObjectID)
ReplayObject = QRC('RollCallDialogue.objects.create(RollCallID=%s,Content=%s,Display=%s,Publisher=%s)',
0, RollCall, Content, '' if RollCall.Publisher == request.user else 'right', request.user)
if not RollCall.Publisher == request.user:
AddNotification(Type, ObjectID, ReplayObject.ObjectID, QRC('CommentInfo.objects.get(ObjectID=%s)', None,
ParentID).Publisher if ParentID else QRC(Type + 'Info.objects.get(ObjectID=%s)', None, ObjectID).Publisher, request.user)
CounterOperate(QRC('User.objects.get(id=%s)', 0,
request.user.id), temp_Map[Type], '+')
CounterOperate(
QRC(Type.replace('Special','') + 'Info.objects.get(ObjectID=%s)', 0, ObjectID), 'Comment', '+')
return HttpResponse('replayok')
else:
return HttpResponse('login')
def Collect(request):
if request.method == 'POST':
if request.user.is_authenticated:
ObjectID = request.POST.get('ObjectID')
Type = request.POST.get('Type')
result = QRC(
'Collection.objects.filter(Publisher=%s,Type=%s,ObjectID=%s)', 0, request.user, Type, ObjectID)
if not result:
QRC('Collection.objects.create(Publisher=%s,Type=%s,ObjectID=%s)',
0, request.user, Type, ObjectID)
CounterOperate(
QRC((Type if Type not in 'SpecialTopic' else 'Topic') + 'Info.objects.get(ObjectID=%s)', 0, ObjectID), 'Collect', '+')
return HttpResponse('collect')
else:
result[0].delete()
CounterOperate(
QRC((Type if Type not in 'SpecialTopic' else 'Topic') + 'Info.objects.get(ObjectID=%s)', 0, ObjectID), 'Collect', '-')
return HttpResponse('cancel')
else:
return HttpResponse('login')
def StatisticalDataUpdata(objectStr, methodDsc):
exec(objectStr + methodDsc)
exec(objectStr + '.save()')
def GetParam(request):
if request.method == "POST":
KeyWord = request.POST.get('KeyWord')
if KeyWord == 'SecretKey':
APPConf = AC()
jsondata = json.dumps(
[APPConf.SecretKey, APPConf.SecretVI], ensure_ascii=False)
return HttpResponse(jsondata)
else:
pass
def Login(request):
if request.method == 'POST':
# 注册信息获取
username = mMs.Decrypt(mMs.DecodeWithBase64(
request.POST.get('username')))
userpassword = mMs.Decrypt(
mMs.DecodeWithBase64(request.POST.get('password')))
user = auth.authenticate(username=username, password=userpassword)
if user:
login(request, user)
return HttpResponse(True)
else:
return HttpResponse("")
# 注册界面
def Regist(request):
APPConf = AC()
if request.method == 'POST':
username = mMs.Decrypt(mMs.DecodeWithBase64(
request.POST.get('username')))
usernickname = mMs.Decrypt(mMs.DecodeWithBase64(
request.POST.get('usernickname')))
password = mMs.Decrypt(mMs.DecodeWithBase64(
request.POST.get('password')))
email = mMs.Decrypt(mMs.DecodeWithBase64(request.POST.get('email')))
try:
# 这里通过前端注册账号一定要是要create_user 不然后期登录的时候
# auth.authenticate无法验证用户名和密码
newUser = User.objects.create_user(
username, Nick=usernickname, password=password, email=email)
newUser.Avatar = mMs.UserAvatarOperation(request.POST.get(
'userimagedata'), request.POST.get('userimageformat'),APPConf.DefaultAvatar.url.replace(settings.MEDIA_URL,''))['Path']
newUser.save()
return HttpResponse('ok')
except Exception as e:
return HttpResponse(str(e))
def Logout(request):
if request.method == 'GET':
if request.user.is_authenticated:
auth.logout(request)
return HttpResponse('Logout')
else:
return HttpResponse('logouted')
else:
return HttpResponse('not get')
def AddNotification(Region, ObjectID, AnchorID, TargetUser, SourceUser):
try:
QRC('Notification.objects.create(Region=%s, ObjectID=%s, AnchorID=%s, TargetUser=%s, SourceUser=%s)',
0, Region, ObjectID, AnchorID, TargetUser, SourceUser)
except Exception as e:
raise e
def GetNotificationInfo(request):
if request.method == 'GET':
if request.user.is_authenticated:
try:
NotificationObjects = QRC(
'Notification.objects.filter(TargetUser=%s)', 0, request.user)
if NotificationObjects:
dataList = []
for Object in NotificationObjects:
dataDict = {}
dataDict['ID'] = str(Object.ID)
dataDict['Region'] = Object.Region
dataDict['ObjectID'] = Object.ObjectID
dataDict['AnchorID'] = Object.AnchorID
dataDict['Title'] = QRC(dataDict['Region'].replace('Special', '') + 'Info.objects.get(ObjectID=%s)', None, dataDict[
'ObjectID']).Title[0:10] + '...'
dataDict['PageNumber'] = GetPageNumber(dataDict['Region'], dataDict[
'ObjectID'], dataDict['AnchorID'])
dataDict['TargetURL'] = '/' + dataDict['Region'] + '/Content/' + dataDict[
'ObjectID'] + '/LE/' + dataDict['PageNumber'] + '/' + dataDict['AnchorID']
dataDict['SourceUser'] = Object.SourceUser.Nick
dataList.append(dataDict)
jsondata = json.dumps(dataList, ensure_ascii=False)
return HttpResponse(jsondata)
else:
return HttpResponse('None')
except Exception as e:
raise e
else:
return HttpResponse('login')
@csrf_exempt
def RemoveNotificationInfo(request):
if request.method == 'POST':
if request.POST.get('IDs'):
IDs = request.POST.get('IDs').split(',')
if request.user.is_authenticated:
if len(IDs) == 1:
try:
QRC('Notification.objects.get(ID=%s)',
0, IDs[0]).delete()
return HttpResponse('OneDeleteOk')
except Exception as e:
raise e
else:
for ID in IDs:
QRC('Notification.objects.get(ID=%s)', 0, ID).delete()
return HttpResponse('AllDeleteOk')
else:
return HttpResponse('DeleteFail')
def GetPageNumber(Region, ObjectID, AnchorID):
APPConf = AC()
if Region in 'SpecialTopic':
CommentObjects = QRC(
"CommentInfo.objects.filter(ObjectID=%s).order_by('-EditDate')", 0, ObjectID)
Number = 0
for CommentObject in CommentObjects:
Number += 1
if str(CommentObject.ObjectID) == AnchorID:
break
PageNumber = Number // APPConf.CommentsPageLimit if Number % APPConf.CommentsPageLimit == 0 else Number // APPConf.CommentsPageLimit + 1
return str(PageNumber)
else:
return '1'
def BlackListOperation(request):
if request.method == 'POST':
UserID = request.POST.get('UserID')
Operation = request.POST.get('Operation')
UserObject = QRC('User.objects.get(id=%s)', None, UserID)
if request.user.is_authenticated and Operation == 'add':
try:
BlackList.objects.get_or_create(
Enforceder=UserObject, Handler=request.user)
return HttpResponse('add')
except Exception as e:
return HttpResponse(e)
elif request.user.is_authenticated and Operation == 'delete':
try:
QRC('BlackList.objects.get(Enforceder=%s,Handler=%s)',
0, UserObject, request.user).delete()
return HttpResponse('delete')
except Exception as e:
return HttpResponse(e)
else:
return HttpResponse('login')
def UserLink(request):
Operation = request.POST.get('Operation')
if request.method == 'POST':
if request.user.is_authenticated:
UserID = request.POST.get('UserID')
UserObject = QRC('User.objects.get(id=%s)', None, UserID)
try:
if Operation == 'add':
QRC('UserLink.objects.get_or_create(UserBeLinked=%s,UserLinking=%s)',
0, UserObject, request.user)
#UserLink.objects.get_or_create(UserBeLinked=UserObject, UserLinking=request.user)
CounterOperate(UserObject, 'FansCount', '+')
CounterOperate(request.user, 'FoucusCount', '+')
return HttpResponse('add')
elif Operation == 'delete':
QRC('UserLink.objects.get(UserBeLinked=%s,UserLinking=%s)',
0, UserObject, request.user).delete()
CounterOperate(UserObject, 'FansCount', '-')
CounterOperate(request.user, 'FoucusCount', '-')
return HttpResponse('delete')
except Exception as e:
return HttpResponse(e)
else:
return HttpResponse('login')
def UserProfileUpdate(request):
APPConf = AC()
if request.method == 'POST':
UserImageData = request.POST.get('UserImageData')
UserImageFormat = request.POST.get('UserImageFormat')
UserNickName = request.POST.get('UserNickName')
UserDescription = request.POST.get('UserDescription')
UserSex = request.POST.get('UserSex')
UserConstellation = request.POST.get('UserConstellation')
UserEmail = request.POST.get('UserEmail')
UserRegion = request.POST.get('UserRegion')
userObject = QRC('User.objects.get(Nick=%s)', 0, request.user.Nick)
print('UserImageFormat', UserImageFormat)
if QRC('User.objects.get(Nick=%s)', 0, UserNickName) and QRC('User.objects.get(Nick=%s)', 0, UserNickName) != request.user:
return HttpResponse('Nick')
else:
UploadImage_Operated = ''
UploadImage_Operated = mMs.UserAvatarOperation(
UserImageData, UserImageFormat, userObject.Avatar)
userObject.Avatar = UploadImage_Operated['Path']
userObject.Nick = UserNickName
userObject.Sex = UserSex
userObject.Region = UserRegion
userObject.email = UserEmail
userObject.Description = UserDescription
userObject.Constellation = UserConstellation
userObject.save()
return HttpResponse(UploadImage_Operated['Status'])
|
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
Builder.load_file('driver_vote.kv')
class DriverVoteWindow(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def refresh(self):
pass
def vote(self):
pass
class DriverVoteApp(App):
def build(self):
return DriverVoteWindow()
if __name__ == '__main__':
DriverVoteApp().run() |
import argparse
from pathlib import Path
from server import base_path, redis_client
from server.modules.file_manager.dto import CommandResult
from server.modules.file_manager.services.actions import BaseCommand
class FilesCopyCommand(BaseCommand):
"""Command for copying files in directory"""
def __init__(self, command: str):
self.command = command.replace('copy', '')
self.current_path = redis_client.get('current_path')
if not self.current_path:
self.current_path = base_path
self.command_args = self.command.split(' ')
def process(self) -> CommandResult:
folder_path = ""
try:
folder_path = self.command_args[self.command_args.index('-p') + 1]
except ValueError:
folder_path = str(self.current_path)
keys = set(redis_client.scan_iter())
file_keys = [
elem
for elem in keys
if str(folder_path) in str(elem)
]
file_ids = []
try:
ids_input = self.command_args[self.command_args.index('-p') + 2:].split(',')
file_ids = [
int(elem)
for elem in ids_input
]
filtered_paths = [
elem
for elem in file_keys
if self.redis_client.get(elem) is not None
and int(self.redis_client.get(elem)) in file_ids
]
for elem in filtered_paths:
src = Path(elem)
dest = Path(f'{self.command_args.path}') / Path(f'{src.name}.{src.stem}')
dest.write_bytes(src.read_bytes())
except:
return CommandResult(
is_success=False,
command=f'copy {self.command}',
path=folder_path,
message='File copy result',
attributes=[]
)
return CommandResult(
is_success=True,
command=f'copy {self.command}',
path=folder_path,
message='File copy result',
attributes=filtered_paths
)
|
# # Extending your Metadata using DocumentClassifiers at Index Time
#
# With DocumentClassifier it's possible to automatically enrich your documents
# with categories, sentiments, topics or whatever metadata you like.
# This metadata could be used for efficient filtering or further processing.
# Say you have some categories your users typically filter on.
# If the documents are tagged manually with these categories, you could automate
# this process by training a model. Or you can leverage the full power and flexibility
# of zero shot classification. All you need to do is pass your categories to the classifier,
# no labels required.
# This tutorial shows how to integrate it in your indexing pipeline.
# DocumentClassifier adds the classification result (label and score) to Document's meta property.
# Hence, we can use it to classify documents at index time. \
# The result can be accessed at query time: for example by applying a filter for "classification.label".
# This tutorial will show you how to integrate a classification model into your preprocessing steps and how you can filter for this additional metadata at query time. In the last section we show how to put it all together and create an indexing pipeline.
# Here are the imports we need
from haystack.document_stores.elasticsearch import ElasticsearchDocumentStore
from haystack.nodes import PreProcessor, TransformersDocumentClassifier, FARMReader, ElasticsearchRetriever
from haystack.schema import Document
from haystack.utils import convert_files_to_dicts, fetch_archive_from_http, print_answers, launch_es
def tutorial16_document_classifier_at_index_time():
# This fetches some sample files to work with
doc_dir = "data/preprocessing_tutorial"
s3_url = "https://s3.eu-central-1.amazonaws.com/deepset.ai-farm-qa/datasets/documents/preprocessing_tutorial.zip"
fetch_archive_from_http(url=s3_url, output_dir=doc_dir)
# ## Read and preprocess documents
# note that you can also use the document classifier before applying the PreProcessor, e.g. before splitting your documents
all_docs = convert_files_to_dicts(dir_path=doc_dir)
preprocessor_sliding_window = PreProcessor(
split_overlap=3,
split_length=10,
split_respect_sentence_boundary=False
)
docs_sliding_window = preprocessor_sliding_window.process(all_docs)
# ## Apply DocumentClassifier
# We can enrich the document metadata at index time using any transformers document classifier model.
# Here we use a zero shot model that is supposed to classify our documents in 'music', 'natural language processing' and 'history'.
# While traditional classification models are trained to predict one of a few "hard-coded" classes and required a dedicated training dataset,
# zero-shot classification is super flexible and you can easily switch the classes the model should predict on the fly.
# Just supply them via the labels param.
# Feel free to change them for whatever you like to classify.
# These classes can later on be accessed at query time.
doc_classifier = TransformersDocumentClassifier(model_name_or_path="cross-encoder/nli-distilroberta-base",
task="zero-shot-classification",
labels=["music", "natural language processing", "history"],
batch_size=16
)
# we can also use any other transformers model besides zero shot classification
# doc_classifier_model = 'bhadresh-savani/distilbert-base-uncased-emotion'
# doc_classifier = TransformersDocumentClassifier(model_name_or_path=doc_classifier_model, batch_size=16)
# we could also specifiy a different field we want to run the classification on
# doc_classifier = TransformersDocumentClassifier(model_name_or_path="cross-encoder/nli-distilroberta-base",
# task="zero-shot-classification",
# labels=["music", "natural language processing", "history"],
# batch_size=16,
# classification_field="description")
# convert to Document using a fieldmap for custom content fields the classification should run on
docs_to_classify = [Document.from_dict(d) for d in docs_sliding_window]
# classify using gpu, batch_size makes sure we do not run out of memory
classified_docs = doc_classifier.predict(docs_to_classify)
# let's see how it looks: there should be a classification result in the meta entry containing labels and scores.
print(classified_docs[0].to_dict())
# ## Indexing
launch_es()
# Connect to Elasticsearch
document_store = ElasticsearchDocumentStore(host="localhost", username="", password="", index="document")
# Now, let's write the docs to our DB.
document_store.delete_all_documents()
document_store.write_documents(classified_docs)
# check if indexed docs contain classification results
test_doc = document_store.get_all_documents()[0]
print(f'document {test_doc.id} with content \n\n{test_doc.content}\n\nhas label {test_doc.meta["classification"]["label"]}')
# ## Querying the data
# All we have to do to filter for one of our classes is to set a filter on "classification.label".
# Initialize QA-Pipeline
from haystack.pipelines import ExtractiveQAPipeline
retriever = ElasticsearchRetriever(document_store=document_store)
reader = FARMReader(model_name_or_path="deepset/roberta-base-squad2", use_gpu=True)
pipe = ExtractiveQAPipeline(reader, retriever)
## Voilà! Ask a question while filtering for "music"-only documents
prediction = pipe.run(
query="What is heavy metal?", params={"Retriever": {"top_k": 10, "filters": {"classification.label": ["music"]}}, "Reader": {"top_k": 5}}
)
print_answers(prediction, details="high")
# ## Wrapping it up in an indexing pipeline
from pathlib import Path
from haystack.pipelines import Pipeline
from haystack.nodes import TextConverter, FileTypeClassifier, PDFToTextConverter, DocxToTextConverter
file_type_classifier = FileTypeClassifier()
text_converter = TextConverter()
pdf_converter = PDFToTextConverter()
docx_converter = DocxToTextConverter()
indexing_pipeline_with_classification = Pipeline()
indexing_pipeline_with_classification.add_node(component=file_type_classifier, name="FileTypeClassifier", inputs=["File"])
indexing_pipeline_with_classification.add_node(component=text_converter, name="TextConverter", inputs=["FileTypeClassifier.output_1"])
indexing_pipeline_with_classification.add_node(component=pdf_converter, name="PdfConverter", inputs=["FileTypeClassifier.output_2"])
indexing_pipeline_with_classification.add_node(component=docx_converter, name="DocxConverter", inputs=["FileTypeClassifier.output_4"])
indexing_pipeline_with_classification.add_node(component=preprocessor_sliding_window, name="Preprocessor", inputs=["TextConverter", "PdfConverter", "DocxConverter"])
indexing_pipeline_with_classification.add_node(component=doc_classifier, name="DocumentClassifier", inputs=["Preprocessor"])
indexing_pipeline_with_classification.add_node(component=document_store, name="DocumentStore", inputs=["DocumentClassifier"])
indexing_pipeline_with_classification.draw("index_time_document_classifier.png")
document_store.delete_documents()
txt_files = [f for f in Path(doc_dir).iterdir() if f.suffix == '.txt']
pdf_files = [f for f in Path(doc_dir).iterdir() if f.suffix == '.pdf']
docx_files = [f for f in Path(doc_dir).iterdir() if f.suffix == '.docx']
indexing_pipeline_with_classification.run(file_paths=txt_files)
indexing_pipeline_with_classification.run(file_paths=pdf_files)
indexing_pipeline_with_classification.run(file_paths=docx_files)
document_store.get_all_documents()[0]
# we can store this pipeline and use it from the REST-API
indexing_pipeline_with_classification.save_to_yaml("indexing_pipeline_with_classification.yaml")
if __name__ == "__main__":
tutorial16_document_classifier_at_index_time()
# ## About us
#
# This [Haystack](https://github.com/deepset-ai/haystack/) notebook was made with love by [deepset](https://deepset.ai/) in Berlin, Germany
#
# We bring NLP to the industry via open source!
# Our focus: Industry specific language models & large scale QA systems.
#
# Some of our other work:
# - [German BERT](https://deepset.ai/german-bert)
# - [GermanQuAD and GermanDPR](https://deepset.ai/germanquad)
# - [FARM](https://github.com/deepset-ai/FARM)
#
# Get in touch:
# [Twitter](https://twitter.com/deepset_ai) | [LinkedIn](https://www.linkedin.com/company/deepset-ai/) | [Slack](https://haystack.deepset.ai/community/join) | [GitHub Discussions](https://github.com/deepset-ai/haystack/discussions) | [Website](https://deepset.ai)
#
# By the way: [we're hiring!](https://www.deepset.ai/jobs)
#
|
import os, sys
import arcpy
from TINcontours import tin_contours
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "TIN Processing Toolbox"
self.alias = ""
# List of tool classes associated with this toolbox
self.tools = [GetTINContours]
class GetTINContours(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "TIN Contours"
self.description = ""
self.canRunInBackground = True
def getParameterInfo(self):
in_points = arcpy.Parameter(
displayName="Input points feature layer",
name="in_points",
datatype="GPFeatureLayer",
parameterType="Required",
direction="Input")
in_points.filter.list = ["Point"]
in_field = arcpy.Parameter(
displayName="Z value field",
name="in_field",
datatype="GPString",
parameterType="Required",
direction="Input")
in_field.parameterDependencies = [in_points.name]
contour_interval = arcpy.Parameter(
displayName="Contour interval",
name="contour_interval",
datatype="GPDouble",
parameterType="Required",
direction="Input")
contour_interval.filter.type = "Range"
contour_interval.filter.list = [sys.float_info.min, sys.float_info.max]
base_contour = arcpy.Parameter(
displayName="Base contour level",
name="base_contour",
datatype="GPDouble",
parameterType="Required",
direction="Input")
base_contour.value = 0.0
index_step = arcpy.Parameter(
displayName="Index contour step (each)",
name="index_step",
datatype="GPLong",
parameterType="Required",
direction="Input")
base_contour.value = 5
clip_features = arcpy.Parameter(
displayName="Clipping polygons (optional)",
name="clip_features",
datatype="GPFeatureLayer",
parameterType="Optional",
direction="Input")
clip_features.filter.list = ["Polygon"]
out_contours = arcpy.Parameter(
displayName="Output contours feature class",
name="out_features",
datatype="DEFeatureClass",
parameterType="Required",
direction="Output")
out_bands = arcpy.Parameter(
displayName="Output isobands feature class (optional)",
name="out_bands",
datatype="DEFeatureClass",
parameterType="Optional",
direction="Output")
params = [in_points, in_field, contour_interval, base_contour, index_step, clip_features, out_contours, out_bands]
return params
def isLicensed(self):
return True
def updateParameters(self, parameters):
if parameters[0].altered:
fields = arcpy.ListFields(parameters[0].value)
num_fields = []
for field in fields:
if field.type == "Double":
num_fields.append(field.name)
parameters[1].filter.type = "ValueList"
parameters[1].filter.list = num_fields
return
def updateMessages(self, parameters):
return
def execute(self, parameters, messages):
in_points = parameters[0].valueAsText
in_field = parameters[1].valueAsText.split('.')[-1]
contour_interval = float(parameters[2].valueAsText)
base_contour = float(parameters[3].valueAsText)
index_step = int(parameters[4].valueAsText)
clip_features = parameters[5].valueAsText
out_contours = parameters[6].valueAsText
out_bands = parameters[7].valueAsText
# os.system('TINcontours.py "{0}" "{1}" "{2}" "{3}" "{4}" "{5}" "{6}"'.format(in_points, in_field, contour_interval, base_contour, clip_features, out_contours, out_bands))
tin_contours(in_points, in_field, contour_interval, base_contour, index_step, clip_features, out_contours, out_bands)
return |
import sys
import logging
if sys.version_info < (3, 0):
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append("../xmpp_bot")
logging.basicConfig(level=logging.DEBUG)
server = 'localhost'
port = 5222
from xmpp_bot.controllers.copernicus import DashboardController
if __name__ == '__main__':
if len(sys.argv) >= 4:
jid = sys.argv[1] # dashboard1@localhost
password = sys.argv[2] # 1234
pubsub_server = sys.argv[3] # pubsub.localhost
if len(sys.argv) >= 5:
server = sys.argv[4] # localhost
if len(sys.argv) >= 6:
port = sys.argv[5] # 5222
xmpp = DashboardController(jid, password, pubsub_server)
xmpp.connect(address = (server, port), use_tls=False)
xmpp.process(threaded=False)
else:
print("Invalid number of arguments.\n" +
"Usage: python %s " +
"<jid> <pass> <pubsub> [host] [port]" % sys.argv[0])
|
# %%
import pandas as pd
from util import con, cfg, db, file
cfg_fname = "./config/config.json"
DailyOHLCmin_TB = cfg.getConfigValue(cfg_fname, "tb_mins")
rddb_con = db.mySQLconn(DailyOHLCmin_TB.split(".")[0], "read")
mins5_OHLC = pd.read_sql(f"""SELECT * FROM {DailyOHLCmin_TB} WHERE TradeTime <= '09:05:00' AND TradeDate = (SELECT distinct max(TradeDate) from {DailyOHLCmin_TB})""" , con = rddb_con).groupby(["StockID", "TradeDate"], sort=True).agg({"Open": "first", "High": max, "Low": min, "Close": "last", "Volume": sum}).reset_index()
DailyOHLC_TB = cfg.getConfigValue(cfg_fname, "tb_daily")
filt = {"TradeDate": "20210827"}
Daily_OHLC = db.readDataFromDBtoDF(DailyOHLC_TB, filt).filter(items = ["StockID", "Close", "Volume"]).rename(columns = {"Volume": "DayVolume","Close": "DayClose"})
FinalDF = Daily_OHLC.merge(mins5_OHLC, on = ["StockID"], how = "left")
FinalDF.loc[(FinalDF.Close > FinalDF.Open) & (FinalDF.Close > FinalDF.High * (1 - 0.01)), "Buy"] = "X"
FinalDF.loc[(FinalDF.Close > FinalDF.Open) & (FinalDF.Close == FinalDF.High), "Buy"] = "XX"
FinalDF.loc[(FinalDF.Close > FinalDF.Open) & (FinalDF.Close > FinalDF.High * (1 - 0.01)) & (FinalDF.DayClose > FinalDF.Close), "Stasus"] = "+"
FinalDF.loc[(FinalDF.Close > FinalDF.Open) & (FinalDF.Close == FinalDF.High) & (FinalDF.DayClose > FinalDF.Close), "Stasus"] = "++"
file.genFiles(cfg_fname, FinalDF, "./data/analysis.xlsx", "xlsx")
# import os
# import requests as req
# import json
# import pandas as pd
# from datetime import date
# from bs4 import BeautifulSoup as bs
# def getConfigData(file_path, datatype):
# try:
# with open(file_path, encoding="UTF-8") as f:
# jfile = json.load(f)
# val = jfile[datatype]
# # val = ({True: "", False: jfile[datatype]}[jfile[datatype] == "" | jfile[datatype] == "None"])
# except:
# val = ""
# return val
# def getBSobj(YYYYMMDD, cfg):
# head_info = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"}
# url = f"https://www.twse.com.tw/fund/T86?response=html&date={YYYYMMDD}&selectType=ALL"
# # 處理網址
# urlwithhead = req.get(url, headers = head_info)
# urlwithhead.encoding = "utf-8"
# # 抓config檔決定是否要產生File
# genfile = getConfigData(cfg, "genhtml")
# # 判斷是否要產生File,不產生就直接把BS Obj傳出去
# if genfile != "":
# ## 寫網頁原始碼到檔案中cfg是config檔的路徑及檔名
# wpath = getConfigData(cfg, "webpath")
# # 產生出的檔案存下來
# ## 建立目錄,不存在才建...
# if os.path.exists(wpath) == False:
# os.makedirs(wpath)
# rootlxml = bs(urlwithhead.text, "lxml")
# with open(f"{wpath}/三大法人買賣超日報_{YYYYMMDD}.html", mode="w", encoding="UTF-8") as web_html:
# web_html.write(rootlxml.prettify())
# #傳出BeautifulSoup物件
# return bs(urlwithhead.text, "lxml")
# def getTBobj(bsobj, tbID, cfg):
# tb = bsobj.find_all("table")[tbID]
# # 抓config檔決定是否要產生File
# genfile = getConfigData(cfg, "genhtml")
# # 判斷是否要產生File,不產生就直接把BS Obj傳出去
# if genfile != "":
# ## 寫網頁原始碼到檔案中cfg是config檔的路徑及檔名
# wpath = getConfigData(cfg, "webpath")
# # 產生出的檔案存下來
# ## 建立目錄,不存在才建...
# if os.path.exists(wpath) == False:
# os.makedirs(wpath)
# with open(f"{wpath}/table.html", mode="w", encoding="UTF-8") as web_html:
# web_html.write(tb.prettify())
# return tb
# def getHeaderLine(tbObj):
# headtext = []
# for head in tbObj.select("table > thead > tr:nth-child(2) > td"):
# headtext.append(head.text)
# return headtext
# # %%
# cfg_fname = r"./config/config.json"
# ymd = date.today().strftime("%Y%m%d")
# TB_Obj = getTBobj(getBSobj(ymd, cfg_fname), 0, cfg_fname)
# Header = getHeaderLine(TB_Obj)
# ItemData = []
# for rows in TB_Obj.select("table > tbody > tr")[1:]:
# itemlist = []
# colnum = 0
# for col in rows.select("td"):
# colnum += 1
# if colnum in (1, 2):
# val = col.string.strip()
# else:
# val = int(col.text.replace(",", "").strip())
# itemlist.append(val)
# ItemData.append(itemlist)
# df_vol = pd.DataFrame(ItemData, columns = Header)
# fpath = getConfigData(cfg_fname, "filepath")
# volfile = f"{fpath}/" + getConfigData(cfg_fname, "volname") + f"_{ymd}.csv"
# if os.path.exists(fpath) == False:
# os.makedirs(fpath)
# df_vol.to_csv(volfile, index = False)
# # %%
# cfg_fname = r"./config/config.json"
# files = os.listdir(getConfigData(cfg_fname, "filepath"))
# matching = [s for s in files if getConfigData(cfg_fname, "volname") in s]
# # %%
# for file in matching:
# filename = file.split(sep = ".")[0]
# fmname = getConfigData(cfg_fname, "filepath") + f"/{file}"
# toname = getConfigData(cfg_fname, "bkpath") + f"/{filename}_bk.csv"
# os.replace(fmname, toname)
# # %%
# %%
|
from sklearn import tree
from sklearn.metrics import accuracy_score
from scipy.spatial import distance
import scipy
from pylab import *
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
def euc(a,b):
return distance.euclidean(a,b)
class MyKNN():
def fit(self, x_train, y_train):
self.x_train = x_train
self.y_train = y_train
def predict(self, x_test):
for row in x_test:
label = self.closest(row)
predictions = label
return predictions
def calcaccuracy(self,x_test):
caccuracy = []
for row in x_test:
label = self.closest(row)
caccuracy.append(label)
return caccuracy
def closest(self, row):
best_dist = euc(row, self.x_train[0])
best_index = 0
for i in range(1, len(self.x_train)):
dist = euc(row, self.x_train[i])
if dist < best_dist:
best_dist = dist
best_index = i
return self.y_train[best_index]
x = np.loadtxt("train2.csv",delimiter=",")
y =np.loadtxt("label.csv",delimiter=",")
clf = MyKNN()
from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = .1)
clf.fit(x_train,y_train)
cross_valid=clf.calcaccuracy(x_test)
clf.fit(x, y)
test = np.loadtxt("contacts.csv",delimiter=",")
test = test.reshape(1, -1)
predictions = clf.predict(test)
if (predictions == 0):
f1='0'
if (predictions == 1):
f1='1'
fd = file('result.csv','w')
fd.write(f1)
fd.close()
#print predictions
accuracy = accuracy_score(y_test, cross_valid)
accuracy = accuracy * 100
accuracy = str(accuracy)
fd1 = file('resultac.csv','w')
fd1.write(accuracy)
fd1.close()
#print cross_valid
#print accuracy
|
import pdb
class Solution:
def __init__(self):
self.factors = [1]
for i in range(9):
self.factors.append(self.factors[i] * (i+1))
def getPermutation(self, n, k):
left = k
pointer = n
chosen = []
result = []
for i in range(n):
chosen.append(str(i+1))
#pdb.set_trace()
while pointer > 0:
if left == 0:
index = len(chosen)
else:
if left <= self.factors[pointer-1]:
index = 1
else:
if left % self.factors[pointer-1] == 0:
index = left / self.factors[pointer-1]
left = 0
else:
index = left / self.factors[pointer-1] + 1
left = left - (index-1) * self.factors[pointer-1]
result.append(chosen[index-1])
del(chosen[index-1])
pointer = pointer - 1
return ''.join(result)
test = Solution()
for i in range(1, 25):
print (test.getPermutation(4, i))
print (test.getPermutation(1,1)) |
from Reporters.API.Reporter import Reporter
from Services.Logger.Implementation.Logging import Logging
from ResultData.ResultData import ResultData
class TextFileReporter(Reporter):
def __init__(self, path, file_service):
self.path = path
self.file_service = file_service
self.file = None
def report(self):
Logging.info("Attempting to open file for report writing: " + self.path)
self.file = self.file_service.open_file(self.path, "w")
for key, value in ResultData.names_and_links.items():
self.file_service.write_line(self.file, "{}: {}".format(key, value))
pass
|
import math
from typing import List
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
start = 0
end = len(nums)-1
middle = math.ceil(end/2)
#print(start, middle, end)
while not (middle == end or middle == start):
if nums[middle] != nums[middle+1] and nums[middle] != nums[middle-1]:
return nums[middle]
if middle%2 == 0:
if nums[middle] == nums[middle+1]:
start = middle
middle = middle + math.ceil((end-middle)/2)
else:
end = middle
middle = middle - math.ceil((middle-start)/2)
else:
if nums[middle] == nums[middle-1]:
start = middle
middle = middle + math.ceil((end-middle)/2)
else:
end = middle
middle = middle - math.ceil((middle-start)/2)
#print(start, middle, end)
return nums[middle]
s = Solution()
res = s.singleNonDuplicate([1,1,2,3,3,4,4,8,8])
print(res)
res = s.singleNonDuplicate([3,3,7,7,10,11,11])
print(res)
res = s.singleNonDuplicate([1,1,2])
print(res)
res = s.singleNonDuplicate([1,2,2])
print(res)
|
import tensorflow as tf
import os
import numpy as np
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
x = np.arange(0, 6000)
# print(x)
dataset = tf.data.Dataset.from_tensor_slices(x)
dataset = dataset.batch(32)
dataset = dataset.shuffle(buffer_size=10000)
dataset = dataset.repeat(5)
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()
with tf.Session() as sess:
value = sess.run(next_element)
print(value)
# while True:
# try:
# value = sess.run(next_element)
# # print(value)
# except:
# print('finish')
# break |
#######################################################################################################################
#
# caughtSpeeding
#
# You are driving a little too fast, and a police officer stops you. Write code to compute the
# result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket.
# If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1.
# If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day,
# your speed can be 5 higher in all cases.
#
#######################################################################################################################
#
# caughtSpeeding(60, false) → 0
# caughtSpeeding(65, false) → 1
# caughtSpeeding(65, true) → 0
# caughtSpeeding(80, false) → 1
# caughtSpeeding(85, false) → 2
# caughtSpeeding(85, true) → 1
# caughtSpeeding(70, false) → 1
# caughtSpeeding(75, false) → 1
# caughtSpeeding(75, true) → 1
# caughtSpeeding(40, false) → 0
# caughtSpeeding(40, true) → 0
# caughtSpeeding(90, false) → 2
#
#######################################################################################################################
|
# check if a book is existing in your collection
collectionOfBooks = ["The Alchemist", "How to win friends and influence people", "The seven habits of highly effective people"]
print("Enter the name of the book: ")
bookToBeChecked = input()
for book in collectionOfBooks:
if book == bookToBeChecked:
print("Yes I do have that book!")
break
else:
print("NO I do not have that book!") |
class UserGroup:
def __init__(self, id = -1, name = "", parent_groups = {}, protein_groups = []):
self.__id = id
self.__name = name
self.__parents = parent_groups
self.__proteins = protein_groups
def get_name(self):
return self.__name
def get_proteins(self):
proteins = dict()
for group in self.__parents:
parent_proteins = group.get_proteins()
for protein in parent_proteins:
perm = parent_proteins[protein]
if proteins.has_key(protein):
proteins[protein] |= perm
else:
proteins[protein] = perm
for (group, perm) in self.__proteins:
for protein in group.get_proteins():
if proteins.has_key(protein):
proteins[protein] |= perm
else:
proteins[protein] = perm
return proteins
|
'''
Copyrights 2021
Work Done By Mike Zinyoni https://github.com/mikietechie
mzinyoni7@gmail.com (Do not spam please)
(Open to work)
''' |
from django.shortcuts import render
from rest_framework import status,generics
from user_watchlist.serializers import WatchListSerializer,WatchListCreateSerializer
from user_watchlist.models import UserWatchList as WatchList
class MovieListView(generics.ListCreateAPIView):
pagination_class = None
def get_queryset(self):
return WatchList.objects.filter(user=self.request.user)
def perform_create(self,serializer):
try:
serializer.save(user=self.request.user)
except:
upd_movie = WatchList.objects.filter(user=self.request.user).filter(movie=self.request.data.get("movie")).first()
if upd_movie.watched != self.request.data.get('watched'):
upd_movie.watched = self.request.data.get('watched')
upd_movie.save()
def get_serializer_class(self):
if self.request.method == 'GET':
return WatchListSerializer
if self.request.method == 'POST':
return WatchListCreateSerializer
else:
return WatchListSerializer
class MovieListRemoveView(generics.RetrieveUpdateDestroyAPIView):
queryset = WatchList.objects.all()
serializer_class = WatchListCreateSerializer |
#!/usr/bin/env python
from sympy import symbols
import sympy.physics.mechanics as me
print("Defining the problem.")
# The conical pendulum will have three links and three bobs.
n = 3
# Each link's orientation is described by two spaced fixed angles: alpha and
# beta.
# Generalized coordinates
alpha = me.dynamicsymbols('alpha:{}'.format(n))
beta = me.dynamicsymbols('beta:{}'.format(n))
# Generalized speeds
omega = me.dynamicsymbols('omega:{}'.format(n))
delta = me.dynamicsymbols('delta:{}'.format(n))
# At each joint there are point masses (i.e. the bobs).
m_bob = symbols('m:{}'.format(n))
# Each link is modeled as a cylinder so it will have a length, mass, and a
# symmetric inertia tensor.
l = symbols('l:{}'.format(n))
m_link = symbols('M:{}'.format(n))
Ixx = symbols('Ixx:{}'.format(n))
Iyy = symbols('Iyy:{}'.format(n))
Izz = symbols('Izz:{}'.format(n))
# Acceleration due to gravity will be used when prescribing the forces
# acting on the links and bobs.
g = symbols('g')
# Now defining an inertial reference frame for the system to live in. The Y
# axis of the frame will be aligned with, but opposite to, the gravity
# vector.
I = me.ReferenceFrame('I')
# Three reference frames will track the orientation of the three links.
A = me.ReferenceFrame('A')
A.orient(I, 'Space', [alpha[0], beta[0], 0], 'ZXY')
B = me.ReferenceFrame('B')
B.orient(A, 'Space', [alpha[1], beta[1], 0], 'ZXY')
C = me.ReferenceFrame('C')
C.orient(B, 'Space', [alpha[2], beta[2], 0], 'ZXY')
# Define the kinematical differential equations such that the generalized
# speeds equal the time derivative of the generalized coordinates.
kinematic_differentials = []
for i in range(n):
kinematic_differentials.append(omega[i] - alpha[i].diff())
kinematic_differentials.append(delta[i] - beta[i].diff())
# The angular velocities of the three frames can then be set.
A.set_ang_vel(I, omega[0] * I.z + delta[0] * I.x)
B.set_ang_vel(I, omega[1] * I.z + delta[1] * I.x)
C.set_ang_vel(I, omega[2] * I.z + delta[2] * I.x)
# The base of the pendulum will be located at a point O which is stationary
# in the inertial reference frame.
O = me.Point('O')
O.set_vel(I, 0)
# The location of the bobs (at the joints between the links) are created by
# specifiying the vectors between the points.
P1 = O.locatenew('P1', -l[0] * A.y)
P2 = P1.locatenew('P2', -l[1] * B.y)
P3 = P2.locatenew('P3', -l[2] * C.y)
# The velocities of the points can be computed by taking advantage that
# pairs of points are fixed on the referene frames.
P1.v2pt_theory(O, I, A)
P2.v2pt_theory(P1, I, B)
P3.v2pt_theory(P2, I, C)
points = [P1, P2, P3]
# Now create a particle to represent each bob.
Pa1 = me.Particle('Pa1', points[0], m_bob[0])
Pa2 = me.Particle('Pa2', points[1], m_bob[1])
Pa3 = me.Particle('Pa3', points[2], m_bob[2])
particles = [Pa1, Pa2, Pa3]
# The mass centers of each link need to be specified and, assuming a
# constant density cylinder, it is equidistance from each joint.
P_link1 = O.locatenew('P_link1', -l[0] / 2 * A.y)
P_link2 = P1.locatenew('P_link2', -l[1] / 2 * B.y)
P_link3 = P2.locatenew('P_link3', -l[2] / 2 * C.y)
# The linear velocities can be specified the same way as the bob points.
P_link1.v2pt_theory(O, I, A)
P_link2.v2pt_theory(P1, I, B)
P_link3.v2pt_theory(P2, I, C)
points_rigid_body = [P_link1, P_link2, P_link3]
# The inertia tensors for the links are defined with respect to the mass
# center of the link and the link's reference frame.
inertia_link1 = (me.inertia(A, Ixx[0], Iyy[0], Izz[0]), P_link1)
inertia_link2 = (me.inertia(B, Ixx[1], Iyy[1], Izz[1]), P_link2)
inertia_link3 = (me.inertia(C, Ixx[2], Iyy[2], Izz[2]), P_link3)
# Now rigid bodies can be created for each link.
link1 = me.RigidBody('link1', P_link1, A, m_link[0], inertia_link1)
link2 = me.RigidBody('link2', P_link2, B, m_link[1], inertia_link2)
link3 = me.RigidBody('link3', P_link3, C, m_link[2], inertia_link3)
links = [link1, link2, link3]
# The only contributing forces to the system is the force due to gravity
# acting on each particle and body.
forces = []
for particle in particles:
mass = particle.get_mass()
point = particle.get_point()
forces.append((point, -mass * g * I.y))
for link in links:
mass = link.get_mass()
point = link.get_masscenter()
forces.append((point, -mass * g * I.y))
# Make a list of all the particles and bodies in the system.
total_system = links + particles
# Lists of all generalized coordinates and speeds.
q = alpha + beta
u = omega + delta
# Now the equations of motion of the system can be formed.
print("Generating equations of motion.")
kane = me.KanesMethod(I, q_ind=q, u_ind=u, kd_eqs=kinematic_differentials)
fr, frstar = kane.kanes_equations(forces, total_system)
print("Derivation complete.")
|
import tensorflow as tf
def enum_each(enum_sizes, name="repeat_each"):
""" creates an enumeration for each repeat
and concatenates the results because we can't have
a tensor with different row or column sizes
Example:
enum_each([1,2,4])
Returns
[0,0,1,0,1,2,3]
the enums are [0], [0,1], [0,1,2,3]
Args:
x: Tensor with the same shape as repeats
enum_sizes: Tensor with the same shape as x
name: name for this op
Returns:
"""
with tf.name_scope(name, values=[enum_sizes]):
enum_sizes = tf.convert_to_tensor(enum_sizes)
# get maximum repeat length in x
maxlen = tf.reduce_max(enum_sizes)
x = tf.range(maxlen)
# tile it to the maximum repeat length, it should be of shape [maxlen x maxlen] now
x_repeat = tf.stack([maxlen, 1], axis=0)
x_tiled = tf.tile(tf.expand_dims(x, 0), x_repeat)
# create a sequence mask using x
# this will create a boolean matrix of shape [xlen, maxlen]
# where result[i,j] is true if j < x[i].
mask = tf.sequence_mask(enum_sizes, maxlen)
# mask the elements based on the sequence mask
return tf.boolean_mask(x_tiled, mask)
tf.InteractiveSession()
counts = [0, 3, 1, 2]
print(enum_each(counts).eval())
|
#coding:utf-8
from time import sleep
class Client():
def __init__(self, nom, prenom, numero_id, mdp):
self.nom = nom
self.prenom = prenom
self.numero_id = numero_id
self.mdp = mdp
### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###
### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###
class Gestionnaire(Client):
def __init__(self, nom, prenom, numero_id, mdp):
Client.__init__(self, nom, prenom, numero_id, mdp)
self.numero_compte = 0
def ajout_client(self):
message = "Enregistrement du client"
print(message.upper())
print("\n\n******************************\n")
print("Veillez remplire ce formulaire (*) \n")
try:
self.nom = str(input("Nom: "))
self.prenom = str(input("Prénom: "))
self.numero_id = str(input("Numero ID: "))
self.mdp = (input("Mot de passe (04 chiffres): "))
except:
print("Veillez rentrer des bonnes informations.")
"""if (len(self.mdp) > 4):
print("Le nombre de chiffre dépasse 04, recommencer")
self.mdp = int(input("Mot de passe (04 chiffres): "))"""
self.numero_compte += 1
if ((self.nom is None or self.prenom is None) and (self.numero_id is None or self.mdp is None)):
print("Erreur d'enregistrement, manque d'information")
else:
sleep(1)
print("Votre numéro de compte est >> A{} << " .format(self.numero_compte))
sleep(2)
print("\nBienvenue {} {}, votre enregistrement à notre banque a réussit." .format(self.prenom, self.nom))
sleep(2)
print("\n========== Enregistrement terminé ==========")
def supression_compte(mdp):
message = "Supression de compte"
print(message.upper())
print("\n\n******************************\n")
print("Vérification d'informations:")
nom1 = str(input("Votre nom: "))
mot_de_passe = str(input("Votre mot de passe: "))
if (mot_de_passe == mdp):
print("Voulez-vous suprimmer votre compte ?? (1 = oui et 0 = nom)")
reponse = int(input(">> "))
if reponse == 1:
print("supression de compte en cours...")
sleep(5)
print(">> Compte suprimer <<")
elif reponse == 0:
print("Supression de compte annuler")
else:
print("Erreur... (pas de base de données pour vérification information)")
def modification_de_compte(self, nom, prenom, mdp, numero_id):
message = "Modification de compte"
print(message.upper())
print("\n\n******************************\n")
print("Modification de mot de passe: \n")
try:
ancien_psw = int(input("Entrer l'ancien mot de passe: "))
except:
print("Le mot de passe doit etre des chiffres")
if ancien_psw == mdp:
new_psw = int(input("Entrer un nouveau mot de passe: "))
if (len(new_psw) > 4):
print("Le nombre de chiffre dépasse 04, recommencer")
new_psw = int(input("Mot de passe (04 chiffres): "))
else:
print("Mot de passe incorrect (faute de base de données pour récupération d'information)")
print("\n========== Modification effectuer ==========")
def emprunt(self):
message = "Emprunt d'argent à partir d'un compte courant"
print(message.upper())
print("\n\n******************************\n")
nb_dette = 0
nouveau_solde = int(input("Votre salaire: "))
print("Votre salaire mensuel est de:'{}' fcfa" .format(nouveau_solde))
salaire = 100000
if nouveau_solde <= salaire:
print("Taux d'interet 15%")
print("Etes vous pret à emprunter ?? (1 = oui)")
reponse = int(input(">> "))
if reponse == 1:
interet = (nouveau_solde * 15) / 100
emprunter = int(input("Entrer la somme à emprunter: "))
nb_dette += 1
print("Vous avez emprunter {} fcfa, et la banque en coupe l'interet dans votre salaire apres un mois" .format(emprunter))
solde_apres_emp = nouveau_solde - interet
print("Vous avez empruntez déjà >>{} fois<< " .format(nb_dette))
if nb_dette > 1:
print("Vous pouvez plus empruntez, vous avez une dette")
else:
pass
elif nouveau_solde >= 100000:
print("Pour le moment nous ne pouvons pas vous faire d'emprunt.")
else:
print("Allez voir ailleur svp...")
### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###
### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###
class Guichetier(Gestionnaire):
def __init__(self, nom, prenom, numero_id, mdp):
Gestionnaire.__init__(self, nom, prenom, numero_id, mdp)
def versement_argent(self):
message = "Versement argent"
print(message.upper())
print("\n\n******************************\n")
print("Versement sur quel compte: ??")
print("1- Courant")
print("2- salaire")
#print("3- client")
#print("2- étranger")
reponse = int(input(">> "))
if reponse == 1:
print("Versement sur un compte courant. nom client: >> {} <<" .format(self.nom))
somme_a_verser = int(input("entrer la somme à verser. Somme minimale = 500 fcfa: "))
if somme_a_verser <= 500:
print("la somme doit pas etre inférieur à 500 fcfa")
else:
sleep(2)
nouveau_solde = somme_a_verser
print("La somme verser dans votre compte courant est de {} fcfa " .format(nouveau_solde))
###++++++++++ compte salarial +++++++++++###
elif reponse == 2:
print("Versement dans votre compte (salaire)")
somme_a_verser = int(input("Entrer la somme: "))
sleep(2)
print("La somme verser dans votre compte est {} " .format(somme_a_verser))
else:
print("Erreur de choix !!")
def retrait_argent(mdp):
message = "Retrait d'argent"
print(message.upper())
print("\n\n******************************\n")
print("Retrait pour quel compte: ??")
print("1. courant")
print("2. salaire")
#Controleur.verification_caisse()
reponse = int(input(">> "))
if reponse == 1:
somme_a_retirer = int(input("Entrer la somme à retirer pour votre compte courant: "))
mot_de_passe = int(input("Entrer votre mot de passe: "))
if mot_de_passe == mdp:
if(somme_a_retirer > nouveau_solde or somme_a_retirer <= 0):
print("La somme à retirer est inférieur ou supérieur à votre solde.")
else:
sleep(5)
print("Vous avez effectuer un retrait de < {} > fcfa" .format(somme_a_retirer))
sleep(2)
solde_restant = nouveau_solde - somme_a_retirer
print("Votre nouveau solde est de < {} > fcfa" .format(solde_restant))
else:
print("Erreur... (pas de base de données pour vérification information) ")
###-------------------- compte salaire --------------------###
elif reponse == 2:
somme_a_retirer = int(input("Entrer la somme à retirer pour votre compte (Salaire): "))
mot_de_passe = int(input("Entrer votre mot de passe: "))
if mot_de_passe == mdp:
if(somme_a_retirer > nouveau_solde or somme_a_retirer <= 0):
print("La somme à retirer est inférieur ou supérieur à votre solde.")
else:
sleep(3)
print("Vous avez effectuer un retrait de < {} > fcfa" .format(somme_a_retirer))
sleep(2)
solde_restant = nouveau_solde - somme_a_retirer
print("Votre nouveau solde est de < {} > fcfa" .format(solde_restant))
else:
print("Erreur de mot de passe")
else:
print("Erreur de choix !!")
print("\n=============== Retrait terminé ===============")
###*************** Virement ***************###
print("Voulez-vous faire des virements ?? (1 = oui / 0 = non)")
reponse = int(input(">> "))
if reponse == 1:
N_compte = int(input("Numero du compte: "))
nom_compte = str(input("Nom compte: "))
nom_compte_virer = str(input("Nom compte virer: "))
somme_a_virer = int(input("Somme à virer : "))
print("Virement à partir du compte {} pour compte << {} >> d'une somme de {} fcfa" .format(nom_compte_virer, nom_compte,somme_a_virer))
elif reponse == 0:
pass
else:
print("Erreur de choix...")
print("\n============== Virement effectué ===============")
### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###
### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###
"""class Controleur():
def verification_caisse():
if (nouveau_solde is not None) and (somme_a_verser is not None):
pass
else:
print("Il y a pas d'argent en caisse")"""
### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###
### +++++++++++++++++++++++++++++++++++ Programme principal ++++++++++++++++++++++++++++++++++++++++++++++++###
### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###
Gestio = Gestionnaire("Donald", "Aimerite", "698604247", "1234")
Guiche = Guichetier("Donald", "Aimerite", "698604247", "1234")
print("Que voulez vous faire: ")
print("1- Créer un compte")
print("2- Supression du compte")
print("3- Modification du compte")
reponse = int(input(">> "))
print("\n\n******************************\n")
if reponse == 1:
Gestio.ajout_client()
print("\n\n******************************\n")
sleep(3)
print("Apres enregistrement vous pouvez: ")
print("1- VERSEMENT D'ARGENT(Compte courant, salaire)")
print("2- RETRAIT D'ARGENT")
print("3- EMPRUNT D'ARGENT")
sleep(2)
print("Voulez-vous faire une opération ?? (1 = oui et 0 = non)")
reponsec = int(input(">> "))
if reponsec == 1:
print("Que voulez vous faire: [(1- versement), (2- retrait), (3- emprunt)]")
reponse_client = int(input(">> "))
print("\n\n******************************\n")
if reponse_client == 1:
Guiche.versement_argent()
elif reponse_client == 2:
Guiche.retrait_argent()
elif reponse_client == 3:
Gestio.emprunt()
else:
pass
elif reponsec == 0:
print("Merci d'utiliser notre service.")
else:
pass
elif reponse == 2:
Gestio.supression_compte()
elif reponse == 3:
Gestio.modification_de_compte("Donald", "Aimerite", "698604247", "1234")
else:
print("Auccun des choix n'a été fait.")
|
from script import send, send1, send2, send3, send4, send5
import schedule
import time
#Maths
schedule.every().monday.at("05:30").do(send)
schedule.every().tuesday.at("06:30").do(send)
schedule.every().wednesday.at("06:30").do(send)
schedule.every().friday.at("08:30").do(send)
#Formal Language & Automata theory
schedule.every().monday.at("08:30").do(send1)
schedule.every().tuesday.at("05:30").do(send1)
schedule.every().thursday.at("05:30").do(send1)
#Computer Architecture
schedule.every().tuesday.at("08:30").do(send2)
schedule.every().wednesday.at("08:30").do(send2)
schedule.every().thursday.at("08:30").do(send2)
#Design And Analysis of Algorithm
schedule.every().wednesday.at("04:30").do(send3)
schedule.every().thursday.at("06:30").do(send3)
schedule.every().friday.at("04:30").do(send3)
#Environmental Science
schedule.every().monday.at("10:30").do(send4)
schedule.every().tuesday.at("09:30").do(send4)
schedule.every().thursday.at("09:30").do(send4)
#Biology
schedule.every().tuesday.at("10:30").do(send5)
schedule.every().wednesday.at("09:30").do(send5)
schedule.every().thursday.at("10:30").do(send5)
while True:
schedule.run_pending()
time.sleep(1) |
from django.db import models
'''
By default, the django users model doesn't give the user the ability
to upload profile pictures, so we need to modify that by creating our own class and extending the default class
1. Extend the user model
2. create a new profile model, that has a one-to-one relationship with the user
i.e A profile can have only one picture, a picture can belong to only one profile
'''
# Create your models here.
from django.contrib.auth.models import User
from PIL import Image #for profile resizing
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
#CASCADE, if the user is deleted then delete the profile
#we want a one to one relationship with the user model
image = models.ImageField(default='default.png', upload_to='profile_pics')
#NOTE: you need pillow lib for storing images
'''
Now, we create a dunder str method so that when we print this out
it will display how we want it to be displayed
basically if we dont have this its just gonna print out the profile object
and we want it to be more descriptive
'''
def __str__(self): #self is the instance
return f'{self.user.username} Profile'
# since we have created a model we need those migrations
# so run py manage.py makemigrations
# and then py manage.py migrate
# Since we need to view these profiles in the admin side we need to register this
# model with the admin side
def save(self, *args, **kwargs):
#this method already exists we're just over writing it
super().save() #we're gonna run the save method of the parent class by super()
#now we're gonna resize the profile picture
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300,300)
img.thumbnail(output_size)
img.save(self.image.path) |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import requests
import time
from flask import Flask
from flask import request
driver = webdriver.Firefox(executable_path = '/usr/local/bin/geckodriver')
driver.get("https://www.instagram.com/")
#login
time.sleep(5)
username = driver.find_element_by_css_selector("input[name='username']")
password = driver.find_element_by_css_selector("input[name='password']")
username.clear()
password.clear()
username.send_keys("xx")
password.send_keys("Password81")
login = driver.find_element_by_css_selector("button[type='submit']").click()
#save your login info?
time.sleep(10)
notnow = driver.find_element_by_xpath("//button[contains(text(), 'Not Now')]").click()
#turn on notif
time.sleep(10)
notnow2 = driver.find_element_by_xpath("//button[contains(text(), 'Not Now')]").click()
#searchbox
time.sleep(5)
searchbox = driver.find_element_by_css_selector("input[placeholder='Search']")
searchbox.clear()
searchbox.send_keys("host.py")
time.sleep(5)
searchbox.send_keys(Keys.ENTER)
time.sleep(5)
searchbox.send_keys(Keys.ENTER)
app = Flask(__name__)
@app.route("/")
def hello():
handle = request.args.get('handle')
driver.get("https://www.instagram.com/" + handle + "/?__a=1")
html = driver.page_source
return html
if __name__ == "__main__":
app.run()
|
# Generated by Django 2.1.1 on 2018-09-16 03:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lw2', '0015_profile_karma'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='display_name',
field=models.CharField(max_length=40, null=True),
),
]
|
from django.conf.urls import patterns, url
from albums import views
#Notes to self $ and ^ are regular expression characters that have special meaning
#The caret means that the pattern must match the start of the string eg rango/hisabout would still load the about page without it
#The dollar means that the pattern must match the end of the string eg rango/aboutblahblah would still load the about page without it
#The 'r' in front of each regular expression string is optional but recommended.
#It tells Python that a string is "raw" - that nothing in the string should be escaped.
#For the 4th entry in the list
#the second parameter comes from the parenthesis inserted in urls.py (?P<category_name_slug>[\w\-]+)
#Parenthesis around anything will create new arguments that are passed to views.py
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^new/$', views.new, name='new'),
url(r'^signup/$', views.register, name='signup'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^upload/$', views.upload_photo, name='upload'),
url(r'^comment/$', views.post_comment, name='comment'),
url(r'^share/$', views.add_collaborator, name='share'),
url(r'^remove/(?P<album_id>[\w\-]+)/$', views.remove, name='remove'),
url(r'^suggest_users/$', views.suggest_users, name='suggest_users'),
url(r'^(?P<album_name_slug>[\w\-]+)/$', views.memory, name='memory'),
)
|
import math
def num(s):
try:
return int(s)
except ValueError:
return float(s)
def get_divisor(n):
# max_try = int(math.floor(math.sqrt(n)))
max_try = 10
for k in range(2, max_try + 1):
if n % k == 0:
return k
return None
def num_of_base_x(n, x):
if len(n) > 0:
return num_of_base_x(n[:len(n) - 1], x) * x + num(n[-1:])
else:
return 0
def to_base_2(n):
if n == 1:
return '1'
else:
return to_base_2(n / 2) + str(n % 2)
# print to_base_2(17)
# print num_to_base_x('1010', 9)
f = open('qc.test')
count = num(f.readline())
for i in range(1, count + 1):
print 'Case #{}:'.format(i)
pair = f.readline()
nj = pair.split(' ')
n, j = int(nj[0]), int(nj[1])
num_in_test = '1' + '0' * (n - 2) + '1'
while j > 0:
results = []
for base in range(2, 11):
divisor = get_divisor(num_of_base_x(num_in_test, base))
if divisor is not None:
results.append(str(divisor))
else:
break
if len(results) == 9:
j -= 1
print '{} {}'.format(num_in_test, ' '.join(results))
num_in_test = to_base_2(num_of_base_x(num_in_test, 2) + 2)
|
from collections import defaultdict, Counter
from functools import reduce
class Solution:
def largestComponentSize(self, A: List[int]) -> int:
def find(i):
if uf.get(i, i) != i:
uf[i] = find(uf[i])
return uf.get(i, i)
def union(i, j):
uf[find(i)] = find(j)
facs = []
for i, x in enumerate(A):
j = 2
curr = []
while j * j <= x:
if x % j == 0:
while x % j == 0:
x //= j
curr.append(j)
j += 1
if x > 1 or not curr:
curr.append(x)
facs.append(curr)
# primes = list({p for f in facs for p in f})
# fac2idx = {p: i for i, p in enumerate(primes)}
fac2idx = {x:i for (i, x) in enumerate(list({p for f in facs for p in f}))}
uf = {i:i for i in range(len(fac2idx))}
for f in facs:
for x in f:
union(fac2idx[x], fac2idx[f[0]])
clusters = Counter(find(fac2idx[f[0]]) for f in facs)
return max(clusters.values()) |
#
# DAPLink Interface Firmware
# Copyright (c) 2009-2016, ARM Limited, All Rights Reserved
# SPDX-License-Identifier: Apache-2.0
#
# 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 __future__ import absolute_import
from __future__ import print_function
import six
import sys
import time
class TestInfo(object):
# Higher number = more severe
SUBTEST = 0
INFO = 1
WARNING = 2
FAILURE = 3
_MSG_TYPES = set((INFO, WARNING, FAILURE))
_MSG_LEVEL_TO_FMT_STR = {
INFO: "Info: %s",
WARNING: "Warning: %s",
FAILURE: "Failure: %s",
}
def __init__(self, name, init_print=True):
self._all = []
self.failures = 0
self.warnings = 0
self.infos = 0
self.name = name
if init_print:
self._print_msg("SubTest: " + name)
def failure(self, msg):
assert isinstance(msg, six.string_types)
self._add_entry(self.FAILURE, msg)
def warning(self, msg):
assert isinstance(msg, six.string_types)
self._add_entry(self.WARNING, msg)
def info(self, msg):
assert isinstance(msg, six.string_types)
self._add_entry(self.INFO, msg)
def print_msg(self, warning_level, max_recursion=0, spacing=2,
log_file=sys.stdout, _recursion_level=0):
"""
Print problems at the given level
By default only the top level passes and fails are printed.
Set max_recursion to the number of subtests to be printed, or
to None if all levels should be printed.
"""
assert warning_level in self._MSG_TYPES
assert max_recursion is None or max_recursion >= 0
if self.get_failed():
result_str = 'Failure'
test_level = self.FAILURE
elif self.get_warning():
result_str = 'Warning'
test_level = self.WARNING
else:
result_str = 'Pass'
test_level = self.INFO
prefix = ' ' * (_recursion_level * spacing)
# Check if test should be printed - the waning level
# is enabled, or this is the top level test
if test_level < warning_level and _recursion_level != 0:
return
# Print test header
print(prefix + "Test: %s: %s" % (self.name, result_str),
file=log_file)
# Check for recursion termination
if max_recursion is not None and _recursion_level > max_recursion:
return
_recursion_level += 1
# Print messages
prefix = ' ' * (_recursion_level * spacing)
for msg_level, msg in self._all:
if msg_level == self.SUBTEST:
test_info = msg
test_info.print_msg(warning_level, max_recursion,
spacing, log_file, _recursion_level)
else:
fmt = prefix + self._MSG_LEVEL_TO_FMT_STR[msg_level]
if msg_level >= warning_level:
print(fmt % msg, file=log_file)
def get_failed(self):
self._update_counts()
return self.failures != 0
def get_warning(self):
self._update_counts()
return self.warnings != 0
def get_name(self):
return self.name
def create_subtest(self, name):
assert isinstance(name, six.string_types)
test_info = TestInfo(name)
self._add_entry(self.SUBTEST, test_info)
return test_info
def attach_subtest(self, subtest):
assert isinstance(subtest, TestInfo)
self._add_entry(self.SUBTEST, subtest)
def get_counts(self):
"""
Return the number of events that occured
Return the number of even messages as a
tuple containing (failure_count, warning_count, info_count).
"""
self._update_counts()
return self.failures, self.warnings, self.infos
def _update_counts(self):
self.failures, self.warnings, self.infos = 0, 0, 0
for msg_level, msg in self._all:
if msg_level == self.SUBTEST:
test_info = msg
failures, warnings, infos = test_info.get_counts()
self.failures += failures
self.warnings += warnings
self.infos += infos
else:
if msg_level == self.FAILURE:
self.failures += 1
elif msg_level == self.WARNING:
self.warnings += 1
elif msg_level == self.INFO:
self.infos += 1
else:
# Should never get here
assert False
def _add_entry(self, entry_type, msg):
if entry_type is self.SUBTEST:
assert isinstance(msg, TestInfo)
# Test name printed in constructor
else:
assert isinstance(msg, six.string_types)
self._print_msg(msg)
self._all.append((entry_type, msg))
@staticmethod
def _print_msg(msg):
print(get_timestamp_tag() + msg)
class TestInfoStub(TestInfo):
def __init__(self):
super(TestInfoStub, self).__init__('stub test', False)
def create_subtest(self, name):
assert isinstance(name, six.string_types)
return TestInfoStub()
@staticmethod
def _print_msg(msg):
print(get_timestamp_tag() + "%s"%(msg,))
def get_timestamp_tag():
return "[{:0<17f}] ".format(time.time())
|
from kaizen.api import ZenRequest
from parse_this import parse_class, create_parser, Self
from pprint import pprint
from yaml.error import YAMLError
import os
import yaml
class KaizenConfigError(Exception):
"""Used when a configuration error occurs."""
def get_config(config_path):
"""Returns the configuration dict.
Args:
config_path: full path to the yaml config file
"""
try:
with open(config_path, "r") as config_file:
return yaml.load(config_file)
except IOError:
raise KaizenConfigError("'%s' does not exist." % config_path)
except YAMLError:
raise KaizenConfigError("'%s' is not a well formatted yaml file."
% config_path)
@parse_class()
class ZenApi(object):
"""Simplify access to the AgileZen API."""
@create_parser(Self, str)
def __init__(self, config_path=None):
"""
Args:
config_path: full path to the config file, by default
'~/.kaizen.yaml' is used
"""
config_path = config_path or os.path.expanduser("~/.kaizen.yaml")
self._config = get_config(config_path)
self._zen_request = ZenRequest(self._config["api_key"])
@create_parser(Self)
def list_projects(self, phases=False, members=False, metrics=False):
"""List all Projects you have access to.
Args:
phase: add the phases to the Project object
members: add the members to the Project object
metrics: add the metrics to the Project object
"""
request = self._zen_request.projects()
enrichments = [name for name, value in
[("phases", phases), ("members", members),
("metrics", metrics)]
if value]
if enrichments:
request = request.with_enrichments(*enrichments)
return request.send()
@create_parser(Self, int, bool, bool, int, int)
def list_stories(self, project_id=None, tasks=False, tags=False, page=1,
size=100):
"""List stories in the Project specified by the given id.
Args:
project_id: id of the Project you want to list Stories
tasks: should the tasks be included in the stories
tags: should the tags be included in the stories
page: page number to display, defaults to the first page
size: max number of stories to return, defaults to 100
"""
project_id = project_id or self._config["project_id"]
request = self._zen_request.projects(project_id).stories()
enrichments = [name for name, value in
[("tasks", tasks), ("tags", tags)] if value]
if enrichments:
request = request.with_enrichments(*enrichments)
return request.paginate(page, size).send()
@create_parser(Self, int)
def list_phases(self, project_id=None, stories=False, page=1, size=100):
"""List phases in the Project specified by the given id.
Args:
project_id: id of the Project you want to list Stories
stories: should the stories be included in the phases
page: page number to display, defaults to the first page
size: max number of stories to return, defaults to 100
"""
project_id = project_id or self._config["project_id"]
request = self._zen_request.projects(project_id).phases()
if stories:
request = request.with_enrichments("stories")
return request.paginate(page, size).send()
@create_parser(Self, int, str, str, int, int)
def add_phase(self, name, description, project_id=None, index=None,
limit=None):
"""Add a Phase to the Project specified by the given id.
Args:
name: name of the newly created Phase
description: description of the newly created Phase
project_id: id of the Project to add the Phase to
index: the zero based index into the list of phases
limit: Work in progress limit for phase
"""
project_id = project_id or self._config["project_id"]
return self._zen_request.projects(project_id).phases()\
.add(name, description, index, limit).send()
def _get_next_phase_id(self, phase_name, project_id):
# We can assume we won't need to paginate and go over more than 100 Phases
phases = self.list_phases(project_id)["items"]
if phases[-1]["name"] == phase_name:
raise ValueError("Story is already in the last phase '%s'"
% phase_name)
for (idx, phase) in enumerate(phases):
if phase["name"] == phase_name:
return phases[idx + 1]["id"]
raise ValueError("Unknown phase '%s'" % phase_name)
@create_parser(Self, int, int, name="bump-phase")
def move_story_to_next_phase(self, story_id, project_id=None):
"""The Story will be moved to the next Phase.
Args:
story_id: id of the Story to move
project_id: id of the Project
"""
project_id = project_id or self._config["project_id"]
request = self._zen_request.projects(project_id)
story_request = request.stories(story_id)
story = story_request.send()
try:
phase_id = self._get_next_phase_id(story["phase"]["name"],
project_id)
except ValueError as error:
return error.message
return story_request.update(phase_id=phase_id).send()
# TODO: Possible methods to implement include:
# - pop_next: pop the top Story of the "todo" phase and move it to
# "working" assigning it to the user
# - stats: list # of Story per user - also grouped by status/phase
# - todo: list Story in the "todo" phase
# - done: move Story to the "done" phase
# For those methods the concept of configuration should be introduced. It
# would contain: the username, name of the "todo" and "working" phases,
# api key, etc...
def run_cli():
pprint(ZenApi.parser.call())
if __name__ == "__main__":
run_cli()
|
import django_rq
def inflate_exception(job, exc_type, exc_value, traceback):
job.meta['exception'] = exc_value
job.save_meta()
return True
def move_to_failed_queue(job, *exc_info):
worker = django_rq.get_worker()
worker.move_to_failed_queue(job, *exc_info)
return True
|
import numpy as np
import torch
import torch.nn.functional as F
def softmax(scores):
es = np.exp(scores - scores.max(axis=-1)[..., None])
return es / es.sum(axis=-1)[..., None]
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].reshape(-1).float().sum(0)
res.append(correct_k.mul_(100.0 / batch_size))
return res
def get_multi_hot(test_y, classes, assumes_starts_zero=True):
bs = test_y.shape[0]
label_cnt = 0
# TODO ranking labels: (-1,-1,4,5,3,7)->(4,4,2,1,0,3)
if not assumes_starts_zero:
for label_val in torch.unique(test_y):
if label_val >= 0:
test_y[test_y == label_val] = label_cnt
label_cnt += 1
gt = torch.zeros(bs, classes + 1) # TODO(yue) +1 for -1 in multi-label case
for i in range(test_y.shape[1]):
gt[torch.LongTensor(range(bs)), test_y[:, i]] = 1 # TODO(yue) see?
return gt[:, :classes]
def cal_map(output, old_test_y):
batch_size = output.size(0)
num_classes = output.size(1)
ap = torch.zeros(num_classes)
test_y = old_test_y.clone()
gt = get_multi_hot(test_y, num_classes, False)
probs = F.softmax(output, dim=1)
rg = torch.range(1, batch_size).float()
for k in range(num_classes):
scores = probs[:, k]
targets = gt[:, k]
_, sortind = torch.sort(scores, 0, True)
truth = targets[sortind]
tp = truth.float().cumsum(0)
precision = tp.div(rg)
ap[k] = precision[truth.byte()].sum() / max(float(truth.sum()), 1)
return ap.mean() * 100, ap * 100
|
from rest_framework import serializers
from tabelas.models import Publicacao
class PublicacaoSerializer(serializers.ModelSerializer):
class Meta:
model = Publicacao
fields = ['text', 'user', 'image'] |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-10-25 07:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('useraction', '0003_auto_20181025_1528'),
]
operations = [
migrations.AlterField(
model_name='commands',
name='rulename',
field=models.CharField(blank=True, max_length=400, null=True, verbose_name='规则名称'),
),
]
|
lst1 = [1, 2, 3, 4, 5]
lst2 = [10, 20, 30, 40, 50]
lst_zip = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50)]
print(lst_zip)
out = zip(lst1, lst2)
print(list(out))
tup1 = (1, 2, 3)
x, y, z = tup1
for x, y in zip(lst1, lst2):
print(x, y) |
def solution():
x=1
i=2
while numDivisors(x)<501:
x = x+i
i+=1
return x
def numDivisors(number):
i=2
divisors = [1,number] #array that will keep track of divisors
while i<((number**0.5)+1):
if number%i==0:
divisors += [i]
divisors += [number/i]
i+=1
else:
i+=1
return len(divisors)
print solution() |
# office
# CAMERA_IP = "172.22.173.47"
# RASPBERRY_PI_IP = "172.22.150.239"
# home
CAMERA_IP = "192.168.2.41"
RASPBERRY_PI_IP = "192.168.2.50"
# thesis
# CAMERA_IP = ""
# RASPBERRY_PI_IP = ""
# camera uid
LOCK_DEVICE_UID = "da:device:ZWave:FD72A41B%2F5"
CAMERA_DEVICE_UID = "da:device:ONVIF:Bosch-FLEXIDOME_IP_4000i_IR-094454407323822009"
# image
AUTH_USERNAME = "service"
AUTH_PASSWORD = "Admin!234"
IMAGE_FROM_CAMERA_URL = "http://" + CAMERA_IP + "/snap.jpg?JpegCam=1"
|
BOARD_SIZE = 8
def move_rules_rook():
coor_deltas = []
for change in range(-BOARD_SIZE + 1, BOARD_SIZE):
new_position_horizontal = (0, change)
new_position_vertical = (change, 0)
if new_position_horizontal != (0, 0) and coor_deltas.count(new_position_horizontal) == 0:
coor_deltas.append(new_position_horizontal)
if new_position_vertical != (0, 0) and coor_deltas.count(new_position_vertical) == 0:
coor_deltas.append(new_position_vertical)
return coor_deltas
def new_move_rules_bishop():
coor_deltas = [[], [], [], []]
for delta in range(1, BOARD_SIZE):
delta_right_up = [delta, delta]
delta_right_down = [delta, -delta]
delta_left_up = [-delta, delta]
delta_left_down = [-delta, -delta]
coor_deltas[0].append(delta_right_up)
coor_deltas[1].append(delta_right_down)
coor_deltas[2].append(delta_left_up)
coor_deltas[3].append(delta_left_down)
return coor_deltas
print(move_rules_rook())
a = new_move_rules_bishop()
for element in a:
print(element)
|
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == []:
return 0
result = len(nums)
new_len = 1
ptr = nums[0]
for i in range(1, len(nums)):
if ptr == nums[i]:
result = result - 1
else:
nums[new_len] = nums[i]
ptr = nums[i]
new_len = new_len + 1
#nums = list(set(nums))
return result |
import matplotlib
matplotlib.use("Agg")
import numpy as np
import matplotlib.pyplot as plt
import sys
n=500
mu=0
sigma=1
from scipy.stats import norm
d1=np.genfromtxt('sample_1.dat')
d2=np.genfromtxt('sample_2.dat')
d3=np.genfromtxt('sample_3.dat')
d4=np.genfromtxt('sample_4.dat')
x_axis = np.arange(-10, 10, 0.001)
plt.subplot(221)
plt.plot(x_axis, norm.pdf(x_axis,mu,sigma),label='sample 1')
plt.hist(d1,normed=1)
plt.legend()
plt.subplot(222)
plt.plot(x_axis, norm.pdf(x_axis,mu,sigma),label='sample 2')
plt.hist(d2,normed=1)
plt.legend()
plt.subplot(223)
plt.plot(x_axis, norm.pdf(x_axis,mu,sigma),label='sample 3')
plt.hist(d3,normed=1)
plt.legend()
plt.subplot(224)
plt.plot(x_axis, norm.pdf(x_axis,mu,sigma),label='sample 4')
plt.hist(d4,normed=1)
plt.legend()
plt.title('Sample vs Real')
plt.savefig('sample.pdf')
|
from django.shortcuts import render, get_object_or_404, redirect, HttpResponseRedirect, HttpResponse
from .models import *
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.views import View
from .models import Patron
from django.contrib.auth.hashers import make_password, check_password
from django.core.mail import send_mail
from math import ceil
from django.urls import reverse, reverse_lazy
from django.http import JsonResponse
import requests
from django.conf import settings
from django.db.models import Q
from django.core.paginator import Paginator
from homeapp.middleware_auth import simple_middleware, admin_middleware
from django.utils.decorators import method_decorator
from .utils import password_reset_token
class Index(View):
def post(self, request):
if request.session.get('user_id'):
pslug = request.POST.get('data')
return get_cart_items(request, pslug)
else:
return redirect('cart')
return HttpResponseRedirect(self.request.path_info)
def get(self, request):
onsale = Product.objects.filter(homefeatured=True).filter(on_sale=True)
newarrivals = Product.objects.filter(
homefeatured=True).filter(recent_arrival=True)
n = len(onsale)
r = len(newarrivals)
nSlides = n//5 + ceil((n/5)-(n//5))
rSlides = r//5 + ceil((r/5)-(r//5))
print('+++++++', n, nSlides)
advertise = Advertise.objects.order_by('created_at')
data = {'no_of_slides': nSlides, 'onsale_length': range(nSlides), 'newarrivals_length': range(
rSlides), 'onsale': onsale, 'newarrivals': newarrivals, 'advertise': advertise}
return render(request, 'homeapp/index.html', data)
class SignUp(View):
def get(self, request):
return render(request, 'homeapp/signup.html')
def post(self, request):
postDetail = request.POST
firstname = postDetail.get('firstname')
lastname = postDetail.get('lastname')
phone = postDetail.get('phone')
address = postDetail.get('address')
email = postDetail.get('email')
password = postDetail.get('password')
cpassword = postDetail.get('cpassword')
value = {
'firstname': firstname,
'lastname': lastname,
'phone': phone,
'email': email,
'address': address,
'password': password,
'cpassword': cpassword,
}
customer = Patron(firstname=firstname, lastname=lastname, phone=phone,
address=address, email=email, password=password, cpassword=cpassword)
error_message = self.validateUser(customer)
if not error_message:
customer.password = make_password(customer.password)
customer.cpassword = make_password(customer.cpassword)
message = ('Thank you. Mr/Mrs.'+firstname + ' ' + lastname +
' for being a user of Unicart . We will provide you quality product in cheap price.')
send_mail('Thank you', message,
'herohiralaal14@gmail.com', [email])
customer.save()
return redirect('login')
else:
context = {'error': error_message, 'values': value}
return render(request, 'homeapp/signup.html', context)
def validateUser(self, customer):
error_message = None
if len(customer.password) < 7:
error_message = 'Password must be of 8 letters'
elif customer.password != customer.cpassword:
error_message = "Password doesn't match"
elif len(customer.phone) != 10:
error_message = 'Phone number must be of 10 digits'
elif customer.isExists():
error_message = 'Phone number already taken !!'
elif Patron.objects.filter(email=customer.email).exists():
error_message = 'Email already exists !!'
return error_message
class Login(View):
def get(self, request):
return render(request, 'homeapp/login.html')
def post(self, request):
phone = request.POST.get('phone')
password = request.POST.get('password')
user = Patron.get_user_by_phone(phone)
error_message = None
if user:
result = check_password(password, user.password)
print(result)
if result == True:
request.session['user_id'] = user.id
request.session['username'] = user.firstname
request.session['contact'] = user.phone
request.session['address'] = user.address
request.session['email'] = user.email
customer = user.id
cartitems = Cart.objects.filter(customer=Patron(id=customer))
listi = list()
for i in cartitems:
a = i.product.pslug
listi.append(a)
sorted = bubble(listi)
request.session['cart'] = sorted
if sorted:
cart = sorted
else:
cart = []
request.session['cart'] = cart
return redirect('homepage')
else:
error_message = 'Password incorrect !!!'
else:
error_message = 'No user registered to this Phone number !!'
# print(phone,password)
# print(user)
return render(request, 'homeapp/login.html', {'error': error_message})
def logout(request):
request.session.clear()
return redirect('login')
class ForgetPassword(View):
def get(self, request):
return render(request, 'homeapp/forgetpassword.html')
def post(self, request):
useremail= request.POST.get('email')
if Patron.objects.filter(email=useremail).exists():
url = self.request.META['HTTP_HOST']
user=Patron.objects.get(email=useremail)
text='Click the link to reset your password. '
html_content= url + "/password-reset/" + useremail + \
"/" + password_reset_token.make_token(user) + "/"
send_mail(
'Password Reset Link | Unicart',
text + html_content,
settings.EMAIL_HOST_USER,
[useremail],
fail_silently=False,
)
return render(request, 'homeapp/linksent.html')
else:
error_message = 'Email does not exists !!'
return render(request, 'homeapp/forgetpassword.html', {'error':error_message})
class PasswordReset(View):
def get(self, request, *args, **kwargs ):
# email=self.kwargs.get('email')
# user= Patron.objects.get(email=email)
# token=self.kwargs.get('token')
return render (request, 'homeapp/passwordresetform.html')
def post(self, request, *args, **kwargs ):
email=self.kwargs.get('email')
user= Patron.objects.get(email=email)
token=self.kwargs.get('token')
if user and password_reset_token.check_token(user, token):
password=request.POST.get('password')
cpassword=request.POST.get('cpassword')
message = self.formValid(password, cpassword)
if not message:
user.password=make_password(password)
user.save()
return redirect('login')
else:
return render (request, 'homeapp/passwordresetform.html', {'error':message})
def formValid(self, password, cpassword):
error_message = None
if len(password) < 7:
error_message = 'Password must be of 8 letters'
elif password != cpassword:
error_message = "Password doesn't match !"
return error_message
def clothhome(request):
product = SubCat.objects.filter(category=1).order_by('sub_category')
context = {'products': product}
return render(request, 'homeapp/clothhome.html', context)
def electrohome(request):
product = SubCat.objects.filter(category=2).order_by('sub_category')
context = {'products': product}
return render(request, 'homeapp/electrohome.html', context)
class UserProfile(View):
def get(self, request):
userid = request.session.get('user_id')
customer = Patron.objects.get(id=userid)
orders = OrderItems.objects.filter(customer=userid).order_by('-id')
context={'user':customer, 'orders':orders}
return render(request, 'homeapp/userprofile.html', context)
class Producty(View):
def post(self, request, slug):
if request.session.get('user_id'):
pslug = request.POST.get('data')
return get_cart_items(request, pslug)
else:
return redirect('cart')
def get(self, request, slug):
dhakal = None
genders = Gen.objects.all()
gender_id = request.GET.get('cate')
cat= SubCat.get_cat(slug)
print('-----------------------',cat)
if gender_id:
products = Product.objects.filter(slug_id=slug, gender=gender_id)
subcat = SubCat.get_subcat(slug)
paginator= Paginator(products, 10)
page_number = request.GET.get('page')
dhakal= paginator.get_page(page_number)
else:
products = Product.objects.filter(slug_id=slug)
subcat = SubCat.get_subcat(slug)
paginator= Paginator(products, 10)
page_number = request.GET.get('page')
dhakal= paginator.get_page(page_number)
return render(request, 'homeapp/product.html', {'products': dhakal, 'genders': genders, 'subcat': subcat, 'cat': cat})
def prodetail(request, pslug):
if request.method == 'GET':
data = Product.objects.filter(pslug=pslug)
pro=Product.objects.get(pslug=pslug)
pro.viewcount += 1
pro.save()
cat= SubCat.get_cat(pro.slug.id)
return render(request, 'homeapp/pdetail.html', {'details': data, 'cat': cat})
else:
if request.session.get('user_id'):
pslug = request.POST.get('data')
return get_cart_items(request, pslug)
else:
return redirect('cart')
return HttpResponseRedirect(self.request.path_info)
def cart(request):
if request.method == "GET":
if request.session.get('user_id'):
customer = request.session.get('user_id')
cart2 = request.session.get('cart')
customer = Patron(id=customer)
product = Cart.objects.filter(customer=customer).order_by('-id')
paginator= Paginator(product, 15)
page_number = request.GET.get('page')
products= paginator.get_page(page_number)
return render(request, 'homeapp/cart.html', {'products': products})
else:
msg1 = 'You have not logged in yet! '
return render(request, 'homeapp/cart.html', {'msg1': msg1})
else:
return render(request, 'homeapp/index.html')
class CartManage(View):
def get(self, request, *args, **kwargs):
customer = request.session.get('user_id')
cart2 = request.session.get('cart')
cart_id=self.kwargs['product_id']
cart = Cart.objects.get(
id=cart_id)
product=cart.product
action=request.GET.get('action')
cart.totalprice = product.price
if action == 'plus':
cart.quantity += 1
cart.totalprice = product.price
cart.totalprice = product.price * cart.quantity
cart.save()
elif action == 'minus':
if cart.quantity == 1:
cart.quantity = 1
cart.totalprice = product.price * cart.quantity
cart.save()
else:
cart.quantity -= 1
cart.totalprice = product.price * cart.quantity
cart.save()
elif action == 'rem':
cart.delete()
cart2.remove(product.pslug)
request.session['cart'] = cart2
print('we all are done. ', cart_id, action)
return redirect('homeapp:cart')
class Search(View):
def post(self, request):
if request.session.get('user_id'):
pslug = request.POST.get('data')
return get_cart_items(request, pslug)
else:
return redirect('cart')
return HttpResponseRedirect(self.request.path_info)
def get(self, request):
query = request.GET['query']
if len(query) > 20:
messages.warning(
request, 'Query is too long to read, you know I am lazy.🥱')
search_products = Product.objects.none()
elif len(query) == 0 or len(query) < 2:
search_products = Product.objects.none()
messages.error(
request, 'Give a well keyword so that i can fetch matching data..')
else:
# searchbyName = Product.objects.filter(name__icontains=query)
# searchbyDesc = Product.objects.filter(descrption__icontains=query)
# searchbyPrice = Product.objects.filter(price__icontains=query)
# search_products = searchbyName.union(searchbyDesc, searchbyPrice)
products=Product.objects.filter(Q(name__icontains=query) | Q(descrption__icontains=query) | Q(price__icontains=query) )
paginator= Paginator(products, 10)
page_number = request.GET.get('page')
search_products= paginator.get_page(page_number)
sproducts = {'sproduct': search_products, 'query': query}
return render(request, 'homeapp/search.html', sproducts)
# class CheckOut(View):
# def post(self, request, pslug):
# address=request.POST.get('address')
# phone= request.POST.get('phone')
# urgent= request.POST.get('urgent')
# customer=request.session.get('user_id')
# cart= request.session.get('cart')
# # product= get_object_or_404(Product, pslug=pslug)
# product= Product.get_product_by_id(cart.key(pslug))
# # products=Product.get_products_by_id(list(cart.keys()))
# print(cart, products)
# # for product in products:
# # order= OrderItems(customer=Patron(id= customer),
# # product=product, price=product.price,urgent=urgent,
# # ship=address, phone=phone)
# # order.save()
# order= OrderItems(customer=Patron(id= customer),
# product=product.name, price=product.price,urgent=urgent,
# ship=address, phone=phone)
# order.save()
# return redirect('cart')
def order(request, pslug):
if request.method == 'POST':
address = request.POST.get('address')
phone = request.POST.get('phone')
urgent = request.POST.get('urgent')
paymentid = request.POST.get('payment')
payment = PMethod.objects.get(id=paymentid)
color = request.POST.get('color')
size = request.POST.get('size')
customer = request.session.get('user_id')
email = request.session.get('email')
cart_product = Cart.objects.get(id=pslug)
product=cart_product.product
orderitem=product.name
ostatus= OrderStatus.objects.get(id=1)
# product= Product.get_product_by_id(pslug=pslug)
# products=Product.get_products_by_id(list(cart.keys()))
# for product in products:
# order= OrderItems(customer=Patron(id= customer),
# product=product, price=product.price,urgent=urgent,
# ship=address, phone=phone)
# order.save()
if urgent:
final_price = cart_product.totalprice + 200
order = OrderItems(customer=Patron(id=customer),
product=product, price=final_price, urgentstatus=urgent,quantity=cart_product.quantity,
pmethod=payment, color=color, size=size ,ship=address, phone=phone, payment_completed=False, orderstatus=ostatus)
order.save()
else:
final_price = cart_product.totalprice + 50
order = OrderItems(customer=Patron(id=customer),
product=product, price=final_price, urgentstatus=urgent,quantity=cart_product.quantity,
pmethod=payment, color=color, size=size ,ship=address, phone=phone, payment_completed=False, orderstatus=ostatus)
order.save()
pm = request.POST.get('payment')
if urgent:
if pm == '2':
return redirect(reverse('homeapp:khaltirequest') + '?o_id=' + str(order.id))
message = ('Thank you for ordering ' + orderitem +
' from Unicart. Your product will be shipped within 2-3 hours.')
send_mail('Thank you', message,
'herohiralaal14@gmail.com', [email])
else:
if pm == '2':
return redirect(reverse('homeapp:khaltirequest') + '?o_id=' + str(order.id))
message = ('Thank you for ordering ' + orderitem +
' from Unicart. Your product will be shipped within 2-3 days.')
send_mail('Thank you', message,
'herohiralaal14@gmail.com', [email])
return redirect('orderlist')
else:
customer = request.session.get('user_id')
product = Cart.objects.get(id=pslug)
cat= SubCat.get_cat(product.product.slug.id)
# product = get_object_or_404(cart, product=pslug)
# product=Cart.objects.filter()
return render(request, 'homeapp/order.html', {'product': product, 'cat':cat})
class BuyNow(View):
def get(self, request, *args, **kwargs):
pslug= self.kwargs['pslug']
product= Product.objects.get(id=pslug)
cat= SubCat.get_cat(product.slug.id)
return render(request, 'homeapp/buynow.html', {'product': product,'cat':cat})
def post(self, request, *args, **kwargs):
pslug= self.kwargs['pslug']
product= Product.objects.get(id=pslug)
address = request.POST.get('address')
phone = request.POST.get('phone')
urgent = request.POST.get('urgent')
paymentid = request.POST.get('payment')
payment = PMethod.objects.get(id=paymentid)
ostatus= OrderStatus.objects.get(id=1)
color = request.POST.get('color')
size = request.POST.get('size')
customer = request.session.get('user_id')
email = request.session.get('email')
orderitem=product.name
# product= Product.get_product_by_id(pslug=pslug)
# products=Product.get_products_by_id(list(cart.keys()))
# for product in products:
# order= OrderItems(customer=Patron(id= customer),
# product=product, price=product.price,urgent=urgent,
# ship=address, phone=phone)
# order.save()
if urgent:
final_price = product.price + 200
order = OrderItems(customer=Patron(id=customer),
product=product, price=final_price, urgentstatus=urgent,quantity=1,
pmethod=payment, color=color, size=size ,ship=address, phone=phone, payment_completed=False, orderstatus=ostatus)
order.save()
else:
final_price = product.price + 50
order = OrderItems(customer=Patron(id=customer),
product=product, price=final_price, urgentstatus=urgent,quantity=1,
pmethod=payment, color=color, size=size ,ship=address, phone=phone, payment_completed=False, orderstatus=ostatus)
order.save()
pm = request.POST.get('payment')
if urgent:
if pm == '2':
return redirect(reverse('homeapp:khaltirequest') + '?o_id=' + str(order.id))
message = ('Thank you for ordering ' + orderitem +
' from Unicart. Your product will be shipped within 2-3 hours.')
send_mail('Thank you', message,
'herohiralaal14@gmail.com', [email])
else:
if pm == '2':
return redirect(reverse('homeapp:khaltirequest') + '?o_id=' + str(order.id))
message = ('Thank you for ordering ' + orderitem +
' from Unicart. Your product will be shipped within 2-3 days.')
send_mail('Thank you', message,
'herohiralaal14@gmail.com', [email])
return redirect('orderlist')
class KhaltiRequestView(View):
def get(self, request, *args, **kwargs):
o_id = request.GET.get("o_id")
order = OrderItems.objects.get(id=o_id)
data = {
"order": order
}
return render(request, 'homeapp/khaltirequest.html', data)
class KhaltiVerifyView(View):
def get(self, request, *args, **kwargs):
token = request.GET.get('token')
amount = request.GET.get('amount')
order = request.GET.get('order')
print(token, amount, order)
url = "https://khalti.com/api/v2/payment/verify/"
payload = {
"token": token,
"amount": amount
}
headers = {
"Authorization": "Key test_secret_key_e870cfff05194c559c7e89cab66ab904"
}
order_obj= OrderItems.objects.get(id=order)
response = requests.post(url, payload, headers=headers)
res_dict= response.json()
print(res_dict)
if res_dict.get('idx'):
success=True
order_obj.payment_completed = True
oi= order_obj.product
orderitem= oi.name
customer= order_obj.customer
email=customer.email
if order_obj.urgentstatus:
message = ('Thank you for ordering ' + orderitem +
' from Unicart. Your payment has been recieved via Khalti. Your product will be shipped within 2-3 hours.')
send_mail('Thank you', message,
'herohiralaal14@gmail.com', [email])
else:
message = ('Thank you for ordering ' + orderitem +
' from Unicart. Your payment has been recieved via Khalti. Your product will be shipped within 2-3 days.')
send_mail('Thank you', message,
'herohiralaal14@gmail.com', [email])
order_obj.save()
else:
success=False
data = {
'success': success
}
return JsonResponse(data)
class OrderList(View):
@method_decorator(simple_middleware)
def get(self, request):
customer = request.session.get('user_id')
orders = OrderItems.objects.filter(customer=customer).order_by('-id')
return render(request, 'homeapp/orderlist.html', {'orders': orders})
class AdminLogin(View):
# template_name= 'homeapp/admin/adminlogin.html'
# success_url = reverse_lazy('homeapp:adminhome')
def get(self, request):
return render (request, 'homeapp/admin/adminlogin.html')
def post(self, request):
username = request.POST.get('username')
password = request.POST.get('password')
usr=authenticate(username=username, password=password)
error_message = None
if usr is not None:
request.session['admin_id'] =usr.id
return redirect('homeapp:adminhome')
else:
error_message = 'Invalid Crediantials'
return render (request, 'homeapp/admin/adminlogin.html',{'error': error_message})
class AdminHome(View):
@method_decorator(admin_middleware)
def get(self, request):
orders= OrderItems.objects.filter(urgentstatus=None).order_by('-id')
urgents= OrderItems.objects.filter(urgentstatus=True).order_by('-id')
data={'orders':orders,'urgents':urgents}
return render (request, 'homeapp/admin/adminhome.html', data)
class AdminOrderView(View):
def get(self, request, *args, **kwargs):
okay=self.kwargs['id']
order= OrderItems.objects.get(id=okay)
data={'order':order}
return render (request, 'homeapp/admin/orderview.html', data)
def changeStatus(request, id):
if request.method == 'GET':
order= OrderItems.objects.get(id=id)
action= request.GET.get('action')
if action == "1":
oid= 2
orderid=OrderStatus.objects.get(id=oid)
order.orderstatus = orderid
order.save()
elif action == "2":
oid= 3
orderid=OrderStatus.objects.get(id=oid)
order.orderstatus = orderid
order.save()
elif action == "3":
oid= 4
orderid=OrderStatus.objects.get(id=oid)
order.orderstatus = orderid
order.save()
elif action == "4":
oid= 5
orderid=OrderStatus.objects.get(id=oid)
order.orderstatus = orderid
order.save()
elif action == "5":
oid= 1
orderid=OrderStatus.objects.get(id=oid)
order.orderstatus = orderid
order.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def cancelorder(request, id):
if request.method == 'GET':
order= OrderItems.objects.get(id=id)
action= request.GET.get('action')
if action == "1":
oid= 5
orderid=OrderStatus.objects.get(id=oid)
order.orderstatus = orderid
order.save()
elif action == "2":
oid= 5
orderid=OrderStatus.objects.get(id=oid)
order.orderstatus = orderid
order.save()
elif action == "3":
oid= 5
orderid=OrderStatus.objects.get(id=oid)
order.orderstatus = orderid
order.save()
elif action == "4":
oid= 5
orderid=OrderStatus.objects.get(id=oid)
order.orderstatus = orderid
order.save()
elif action == "5":
oid= 5
orderid=OrderStatus.objects.get(id=oid)
order.orderstatus = orderid
order.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def bubble(list):
swap = True
while swap:
swap = False
for i in range(len(list)-1):
if list[i] > list[i+1]:
list[i], list[i+1] = list[i+1], list[i]
swap = True
return (list)
def get_cart_items(request, pslug):
customer = request.session.get('user_id')
cart1 = request.session.get('cart')
product = get_object_or_404(Product, pslug=pslug)
pslugo = product.pslug
print('--------------------------------->', product)
allitems = Cart.objects.filter(customer=Patron(id=customer))
listi = list()
for i in allitems:
a = i.product.pslug
listi.append(a)
sorted = bubble(listi)
search = Cart.binary_search_iterative(sorted, pslugo)
print('==================>', search)
if search == -1:
cart = Cart(customer=Patron(id=customer), product=product, totalprice=product.price)
cart.save()
cart1.append(product.pslug)
request.session['cart'] = cart1
print(cart1)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
|
#!/usr/bin/env python
#
# -------------------------------------------------------------------------
# Copyright (c) 2015-2017 AT&T Intellectual Property
#
# 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.
#
# -------------------------------------------------------------------------
#
import operator
from oslo_log import log
from .constraint import Constraint # Python 3 import statement relative imports
LOG = log.getLogger(__name__)
class Zone(Constraint):
def __init__(self, _name, _type, _demand_list, _priority=0,
_qualifier=None, _category=None, _location=None):
Constraint.__init__(self, _name, _type, _demand_list, _priority)
self.qualifier = _qualifier # different or same
self.category = _category # disaster, region, or update
self.location = _location
self.comparison_operator = None
if self.qualifier == "same":
self.comparison_operator = operator.eq
elif self.qualifier == "different":
self.comparison_operator = operator.ne
def solve(self, _decision_path, _candidate_list, _request):
conflict_list = []
decision_list = list()
# find previously made decisions for the constraint's demand list
for demand in self.demand_list:
# decision made for demand
if demand in _decision_path.decisions:
decision_list.append(_decision_path.decisions[demand])
# temp copy to iterate
# temp_candidate_list = copy.deepcopy(_candidate_list)
# for candidate in temp_candidate_list:
for candidate in _candidate_list:
# check if candidate satisfies constraint
# for all relevant decisions thus far
is_candidate = True
cei = _request.cei
# TODO(larry): think of an other way to handle this special case
if self.location and self.category == 'country':
if not self.comparison_operator(
cei.get_candidate_zone(candidate, self.category),
self.location.country):
is_candidate = False
for filtered_candidate in decision_list:
if not self.comparison_operator(
cei.get_candidate_zone(candidate, self.category),
cei.get_candidate_zone(filtered_candidate,
self.category)):
is_candidate = False
if not is_candidate:
if candidate not in conflict_list:
conflict_list.append(candidate)
# _candidate_list.remove(candidate)
_candidate_list[:] =\
[c for c in _candidate_list if c not in conflict_list]
# msg = "final candidate list for demand {} is "
# LOG.debug(msg.format(_decision_path.current_demand.name))
# for c in _candidate_list:
# print " " + c.name
return _candidate_list
|
import numpy as np
def get_columns(i):
cates_map = {"blouse":0 ,"outwear":1,"trousers":2,"skirt":3,"dress":4 }
blouse_columns = np.array( [ 'neckline_left', 'neckline_right',\
'center_front', 'shoulder_left', 'shoulder_right', 'armpit_left',\
'armpit_right', 'cuff_left_in', 'cuff_left_out', 'cuff_right_in', 'cuff_right_out', 'top_hem_left',\
'top_hem_right'] )
outwear_columns = np.array( ['neckline_left', 'neckline_right',\
'shoulder_left', 'shoulder_right', 'armpit_left',\
'armpit_right', 'waistline_left', 'waistline_right', 'cuff_left_in',\
'cuff_left_out', 'cuff_right_in', 'cuff_right_out', 'top_hem_left',\
'top_hem_right'] )
trousers_columns = np.array( [ 'waistband_left', 'waistband_right', 'crotch', 'bottom_left_in', 'bottom_left_out',\
'bottom_right_in', 'bottom_right_out'] )
skirt_columns = np.array( [ 'waistband_left', 'waistband_right', 'hemline_left', 'hemline_right'] )
dress_columns = np.array( ['neckline_left', 'neckline_right',\
'center_front', 'shoulder_left', 'shoulder_right', 'armpit_left',\
'armpit_right', 'waistline_left', 'waistline_right', 'cuff_left_in',\
'cuff_left_out', 'cuff_right_in', 'cuff_right_out', 'hemline_left',\
'hemline_right'] )
cates = np.array([blouse_columns,outwear_columns,trousers_columns,skirt_columns,dress_columns])
assert (type(i) == str or type(i) ==int) , "wrong arguement type "
if type(i) == int:
return cates[i]
else:
return cates[cates_map[i]]
def get_cate_name(i):
assert (type(i) == str or type(i) ==int) , "wrong arguement type "
cates_map = ["blouse" ,"outwear","trousers","skirt","dress" ]
if type(i) == int:
return cates_map[i]
else:
assert (i in cates_map), "wrong spell"
return i
def get_cate_lm_cnts(i):
assert (type(i) == str) , "wrong arguement type "
cates_map = {"blouse":13 ,"outwear":14,"trousers":7,"skirt":4,"dress":15 }
return cates_map[i] |
import pytest
from applications.schema import BerthApplicationNode
from berth_reservations.tests.utils import (
assert_not_enough_permissions,
create_api_client,
)
from customers.schema import ProfileNode
from leases.schema import BerthLeaseNode
from resources.schema import BerthNode
from utils.relay import to_global_id
from ..models import BerthSwitchOffer
from ..schema.types import BerthSwitchOfferNode
from .factories import BerthSwitchOfferFactory
BERTH_SWITCH_OFFERS_QUERY = """
query BERTH_SWITCH_OFFERS_QUERY {
berthSwitchOffers {
edges {
node {
id
customer {
id
}
application {
id
}
lease {
id
}
berth {
id
}
}
}
}
}
"""
@pytest.mark.parametrize(
"api_client",
["berth_supervisor", "berth_handler", "berth_services"],
indirect=True,
)
def test_get_berth_switch_offers(berth_switch_offer, api_client):
executed = api_client.execute(BERTH_SWITCH_OFFERS_QUERY)
assert len(executed["data"]["berthSwitchOffers"]["edges"]) == 1
assert executed["data"]["berthSwitchOffers"]["edges"][0]["node"] == {
"id": to_global_id(BerthSwitchOfferNode, berth_switch_offer.id),
"customer": {"id": to_global_id(ProfileNode, berth_switch_offer.customer.id)},
"application": {
"id": to_global_id(BerthApplicationNode, berth_switch_offer.application.id)
},
"lease": {"id": to_global_id(BerthLeaseNode, berth_switch_offer.lease.id)},
"berth": {"id": to_global_id(BerthNode, berth_switch_offer.berth.id)},
}
@pytest.mark.parametrize(
"api_client",
["api_client", "user", "harbor_services"],
indirect=True,
)
def test_get_berth_switch_offers_not_enough_permissions(berth_switch_offer, api_client):
executed = api_client.execute(BERTH_SWITCH_OFFERS_QUERY)
assert_not_enough_permissions(executed)
def test_get_berth_switch_offers_by_owner(
berth_customer_api_client, berth_switch_offer, customer_profile
):
berth_switch_offer.customer.user = berth_customer_api_client.user
berth_switch_offer.customer.save()
executed = berth_customer_api_client.execute(BERTH_SWITCH_OFFERS_QUERY)
assert len(executed["data"]["berthSwitchOffers"]["edges"]) == 1
assert executed["data"]["berthSwitchOffers"]["edges"][0]["node"] == {
"id": to_global_id(BerthSwitchOfferNode, berth_switch_offer.id),
"customer": {"id": to_global_id(ProfileNode, berth_switch_offer.customer.id)},
"application": {
"id": to_global_id(BerthApplicationNode, berth_switch_offer.application.id)
},
"lease": {"id": to_global_id(BerthLeaseNode, berth_switch_offer.lease.id)},
"berth": {"id": to_global_id(BerthNode, berth_switch_offer.berth.id)},
}
BERTH_SWITCH_OFFER_QUERY = """
query BERTH_SWITCH_OFFER_QUERY {
berthSwitchOffer(id: "%s") {
id
customer {
id
}
application {
id
}
lease {
id
}
berth {
id
}
}
}
"""
@pytest.mark.parametrize(
"api_client",
["berth_supervisor", "berth_handler", "berth_services"],
indirect=True,
)
def test_get_berth_switch_offer(berth_switch_offer, api_client):
offer_id = to_global_id(BerthSwitchOfferNode, berth_switch_offer.id)
executed = api_client.execute(BERTH_SWITCH_OFFER_QUERY % offer_id)
assert executed["data"]["berthSwitchOffer"] == {
"id": offer_id,
"customer": {"id": to_global_id(ProfileNode, berth_switch_offer.customer.id)},
"application": {
"id": to_global_id(BerthApplicationNode, berth_switch_offer.application.id)
},
"lease": {"id": to_global_id(BerthLeaseNode, berth_switch_offer.lease.id)},
"berth": {"id": to_global_id(BerthNode, berth_switch_offer.berth.id)},
}
CUSTOMER_OWN_BERTH_SWITCH_OFFERS_QUERY = """
query ORDERS {
berthSwitchOffers {
edges {
node {
id
lease {
customer {
id
}
}
}
}
}
}
"""
def test_get_customer_own_orders(customer_profile):
customer_order = BerthSwitchOfferFactory(
customer=customer_profile,
lease__customer=customer_profile,
application__customer=customer_profile,
)
BerthSwitchOfferFactory()
api_client = create_api_client(user=customer_profile.user)
executed = api_client.execute(CUSTOMER_OWN_BERTH_SWITCH_OFFERS_QUERY)
assert BerthSwitchOffer.objects.count() == 2
assert len(executed["data"]["berthSwitchOffers"]["edges"]) == 1
assert executed["data"]["berthSwitchOffers"]["edges"][0]["node"] == {
"id": to_global_id(BerthSwitchOfferNode, customer_order.id),
"lease": {"customer": {"id": to_global_id(ProfileNode, customer_profile.id)}},
}
|
#
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
# Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>,
# Apoorv Vyas <avyas@idiap.ch>
#
"""The weight mapper module provides a utility to load transformer model
weights from other implementations to a fast_transformers model.
NOTE: This API is lkely to change in the future as we collect more information
regarding how people use it.
"""
import re
class MappingRule(object):
"""A mapping rule can be applied to a key and value and it returns new keys
and values to be added in the state dict."""
def matches(self, key):
"""Check whether this mapping rule should be applied to this key."""
raise NotImplementedError()
def apply(self, key, value):
"""Apply the rule and map the key to a new one."""
raise NotImplementedError()
class IdentityRule(MappingRule):
"""The identity rule matches all keys and returns them as is."""
def matches(self, key):
return True
def apply(self, key, value):
return [(key, value)]
class NotRule(MappingRule):
"""Decorate a MappingRule by using a logical not for the matches function
and identity for the apply."""
def __init__(self, rule):
self.rule = rule
def matches(self, key):
return not self.rule.matches(key)
def apply(self, key, value):
return [(key, value)]
class OrRule(MappingRule):
"""Decorate some MappingRules using the logical or to create a matches
function that returns True if any of the rules matches. In case of a match
apply all of the rules."""
def __init__(self, *rules):
self.rules = rules
def matches(self, key):
return any(r.matches(key) for r in self.rules)
def apply(self, key, value):
items = [(key, value)]
for r in self.rules:
items = [
r.apply(k, v)
for k, v in items
]
return items
class RegexRule(MappingRule):
"""Apply a regex search and replace on a key.
Arguments
---------
search: str, the regex pattern to search and replace
replace: str or callable, the replacement for every occurence of the
search pattern. If it is a callable it should follow the rules
of python re.sub().
"""
def __init__(self, search, replace):
self.pattern = re.compile(search)
self.replace = replace
def matches(self, key):
return self.pattern.search(key) is not None
def apply(self, key, value):
return [(self.pattern.sub(self.replace, key), value)]
class PytorchAttentionWeightsRule(MappingRule):
"""Map the merged MultiheadAttention weights to the corresponding keys and
values."""
def __init__(self):
self.weight_pattern = "self_attn.in_proj_weight"
self.bias_pattern = "self_attn.in_proj_bias"
def matches(self, key):
return (
self.weight_pattern in key or
self.bias_pattern in key
)
def apply(self, key, value):
N = value.shape[0]
if self.weight_pattern in key:
return [
(
key.replace(
self.weight_pattern,
"attention.query_projection.weight"
),
value[:N//3]
),
(
key.replace(
self.weight_pattern,
"attention.key_projection.weight"
),
value[N//3:2*N//3]
),
(
key.replace(
self.weight_pattern,
"attention.value_projection.weight"
),
value[2*N//3:]
)
]
if self.bias_pattern in key:
return [
(
key.replace(
self.bias_pattern,
"attention.query_projection.bias"
),
value[:N//3]
),
(
key.replace(
self.bias_pattern,
"attention.key_projection.bias"
),
value[N//3:2*N//3]
),
(
key.replace(
self.bias_pattern,
"attention.value_projection.bias"
),
value[2*N//3:]
)
]
class SimpleMapper(object):
"""Map keys of a state dict to other keys.
Arguments
---------
rules: A list of mapping rules to apply to the keys (default: []).
add_identity: bool, if set to True add a catch all identity rule as the
final rule (default: True).
"""
def __init__(self, rules=[], add_identity=True):
self._rules = rules
if add_identity:
self._rules.append(IdentityRule())
def map(self, state_dict):
new_state = {}
for k, v in state_dict.items():
for rule in self._rules:
if rule.matches(k):
for nk, nv in rule.apply(k, v):
new_state[nk] = nv
break
return new_state
@classmethod
def load_file(cls, filepath, model_root=None, map_location=None,
**other_args):
"""Load the file and apply the weight map.
The model root the key that contains the state dict to be mapped.
Arguments
---------
filepath: The file containing the saved state.
model_root: The key for the state dict to be mapped, if None assume
it is the top level dictionary (default: None).
map_location: The parameter is passed to torch.load .
other_args: The parameter dict is passed to torch.load because it
expects a similar dictionary of arguments to pass to
pickle.load.
"""
state = torch.load(filepath, map_location=map_location, **other_args)
if model_root is None:
state = cls().map(state)
else:
state[model_root] = cls().map(state[model_root])
return state
class PytorchMapper(SimpleMapper):
"""Map a Pytorch transformer encoder state dict to a fast transformers
one."""
def __init__(self):
super(PytorchMapper, self).__init__([
PytorchAttentionWeightsRule(),
RegexRule(
r"layers\.(\d+)\.self_attn\.([a-z]+)_proj(ection)?\.",
r"layers.\1.attention.\2_projection."
),
NotRule(OrRule(
RegexRule(
r"\.softmax_temp$",
r""
)
))
], add_identity=False)
class HugginfaceBertEncoderMapper(SimpleMapper):
"""Map the weights of a model that uses a BertEncoder to our fast
transformers."""
RULES = [
RegexRule(
r"layer\.(\d+)\.attention\.self\.(query|key|value)",
r"layers.\1.attention.\2_projection"
),
RegexRule(
r"layer\.(\d+)\.attention\.output\.dense",
r"layers.\1.attention.out_projection"
),
RegexRule(
r"layer\.(\d+)\.attention\.output\.LayerNorm",
r"layers.\1.norm1"
),
RegexRule(
r"layer\.(\d+)\.intermediate\.dense",
r"layers.\1.linear1"
),
RegexRule(
r"layer\.(\d+)\.output\.dense",
r"layers.\1.linear2"
),
RegexRule(
r"layer\.(\d+)\.output\.LayerNorm",
r"layers.\1.norm2"
)
]
def __init__(self):
super(HugginfaceBertEncoderMapper, self).__init__(self.RULES)
class LongformerMapper(SimpleMapper):
"""Map the longformer weights to our fast transformers.
NOTE: The projections for the global attention are ignored.
"""
def __init__(self):
super(LongformerMapper, self).__init__(
HugginfaceBertEncoderMapper.RULES + [
NotRule(RegexRule(
r"layer\.(\d+)\.attention\.self\.(query|key|value)_global",
""
))
],
add_identity=False
)
|
import boto3
sqs = boto3.client("sqs")
s3 = boto3.resource("s3")
dynamodb = boto3.client("dynamodb")
def check_event_messages(queue_url):
messages = sqs.receive_message(QueueUrl = queue_url, MessageAttributeNames = ['Body',"ReceiptHandle"],MaxNumberOfMessages=10,WaitTimeSeconds=20)
if "Messages" in messages:
for message in messages["Messages"]:
message_body = eval(message["Body"])
if "Records" in message_body:
for record in message_body["Records"]:
if record["eventName"] == "ObjectCreated:Put":
save_to_dynamo_db(record["s3"]["object"]["key"])
sqs.delete_message(QueueUrl = queue_url,ReceiptHandle= message["ReceiptHandle"])
if record["eventName"] == "ObjectRemoved:Delete":
delete_from_dynamo_db(record["s3"]["object"]["key"])
sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=message["ReceiptHandle"])
def save_to_dynamo_db(key):
s3.Bucket("sree-second-bucket-1").download_file(key, 'download_file')
with open("download_file", 'rb') as f:
file = f.read()
dynamodb.put_item(TableName = "table_1", Item = {"name":{"S":key},"file" :{'B':file}})
def delete_from_dynamo_db(key):
dynamodb.delete_item(TableName ="table_1",Key = {"name":{"S":key}})
while(True):
check_event_messages("https://sqs.ap-south-1.amazonaws.com/150761330509/save_or_delete_object") |
from django.shortcuts import render
def home(request):
return render(request, 'welcome/home.html', {'title':'HOME'})
def products(request):
return render(request, 'welcome/products.html', {'title':'PRODUCTS'})
def animals(request):
return render(request, 'welcome/animals.html', {'title':'ANIMALS'})
def culture(request):
return render(request, 'welcome/culture.html', {'title':'CULTURE'})
def bulls(request):
return render(request, 'welcome/bulls.html', {'title':'KANGEYAM BULLS'})
def trees(request):
return render(request, 'welcome/trees.html', {'title':'TREES'})
def plants(request):
return render(request, 'welcome/plants.html', {'title':'PLANTS'})
def flowers(request):
return render(request, 'welcome/flowers.html', {'title':'FLOWERS'})
def lectures(request):
return render(request, 'welcome/lectures.html', {'title':'LECTURES'})
def fertilizers(request):
return render(request, 'welcome/fertilizers.html', {'title':'ORGANIC FERTILIZERS'})
|
from django.contrib import admin
from django.urls import path,include
from django.conf.urls.static import static
from .views.index import index
from .views.mark import mark
from .views.login import Login
urlpatterns = [
path('',Login.as_view(), name='login'),
path('2',index,name='homepage'),
path('result',mark,name='mark')
] |
import random
import numpy as np
from collections import namedtuple
from envs.mdp import StochasticMDPEnv
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import Adam
def meta_controller():
meta = Sequential()
meta.add(Dense(6, init='lecun_uniform', input_shape=(6,)))
meta.add(Activation("relu"))
meta.add(Dense(6, init='lecun_uniform'))
meta.add(Activation("softmax"))
meta.compile(loss='mse', optimizer=Adam())
return meta
def actor():
actor = Sequential()
actor.add(Dense(6, init='lecun_uniform', input_shape=(12,)))
actor.add(Activation("relu"))
actor.add(Dense(2, init='lecun_uniform'))
actor.add(Activation("softmax"))
actor.compile(loss='mse', optimizer=Adam())
return actor
def critic():
critic = Sequential()
critic.add(Dense(6, init='lecun_uniform', input_shape=(19,)))
critic.add(Activation("relu"))
critic.add(Dense(1, init='lecun_uniform'))
critic.compile(loss='mse', optimizer=Adam())
return critic
class Agent:
def __init__(self):
self.meta_controller = meta_controller()
self.actor = actor()
self.critic = critic()
self.actor_epsilon = 0.1 # TODO: Epsilon decay and goal-specific epsilons
self.meta_epsilon = 0.1 # TODO: Epsilon decay
self.n_samples = 10
self.meta_n_samples = 10
self.gamma = 0.96
self.memory = []
self.meta_memory = []
def select_move(self, state, goal):
vector = np.concatenate([state, goal], axis=1)
if self.actor_epsilon < random.random():
return np.argmax(self.actor.predict(vector, verbose=0))
return random.choice([0,1])
def select_goal(self, state):
if self.meta_epsilon < random.random():
return np.argmax(self.meta_controller.predict(state, verbose=0))+1
return random.choice([1,2,3,4,5,6])
def criticize(self, state, goal, action, next_state):
vector = np.concatenate([state, goal, [[action]], next_state], axis=1)
return self.critic.predict(vector, verbose=0)
def store(self, experience, meta=False):
if meta:
self.meta_memory.append(experience)
else:
self.memory.append(experience)
def _update(self):
exps = [random.choice(self.memory) for _ in range(self.n_samples)]
for exp in exps:
critic_vector = np.concatenate([exp.state, exp.goal, [[exp.action]], exp.next_state], axis=1)
actor_vector = np.concatenate([exp.state, exp.goal], axis=1)
actor_reward = self.actor.predict(actor_vector, verbose=0)
actor_reward[0][exp.action] = exp.reward
self.critic.fit(critic_vector, exp.reward, verbose=0)
self.actor.fit(actor_vector, actor_reward, verbose=0)
def _update_meta(self):
if 0 < len(self.meta_memory):
exps = [random.choice(self.meta_memory) for _ in range(self.meta_n_samples)]
for exp in exps:
meta_reward = self.meta_controller.predict(exp.state, verbose=0)
meta_reward[0][np.argmax(exp.goal)] = exp.reward
self.meta_controller.fit(exp.state, meta_reward, verbose=0)
def update(self, meta=False):
if meta:
self._update_meta()
else:
self._update()
def one_hot(state):
vector = np.zeros(6)
vector[state-1] = 1.0
return np.expand_dims(vector, axis=0)
def main():
ActorExperience = namedtuple("ActorExperience", ["state", "goal", "action", "reward", "next_state"])
MetaExperience = namedtuple("MetaExperience", ["state", "goal", "reward", "next_state"])
env = StochasticMDPEnv()
agent = Agent()
for episode in range(100):
print("\n### EPISODE %d ###" % episode)
state = env.reset()
done = False
while not done:
goal = agent.select_goal(one_hot(state))
print("New Goal: %d" % goal)
total_external_reward = 0
goal_reached = False
while not done and not goal_reached:
print(state, end=",")
action = agent.select_move(one_hot(state), one_hot(goal))
next_state, external_reward, done = env.step(action)
intrinsic_reward = agent.criticize(one_hot(state), one_hot(goal), action, one_hot(next_state))
goal_reached = next_state == goal
if goal_reached:
print("Success!!")
exp = ActorExperience(one_hot(state), one_hot(goal), action, intrinsic_reward, one_hot(next_state))
agent.store(exp, meta=False)
agent.update(meta=False)
agent.update(meta=True)
total_external_reward += external_reward
state = next_state
exp = MetaExperience(one_hot(state), one_hot(goal), total_external_reward, one_hot(next_state))
agent.store(exp, meta=True)
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.