text stringlengths 8 6.05M |
|---|
import numpy as np
import pandas as pd
data = pd.read_csv("C:/Users/Chetan.Chougle/Downloads/sms-spam-collection-dataset/spam.csv" , encoding='latin-1' )
data = data.drop(["Unnamed: 2", "Unnamed: 3", "Unnamed: 4"], axis=1)
data = data.rename(columns={"v1":"label" , "v2":"text"})
data["label_num"] = data.label.map({"ham":0 , "spam": 1 })
#print(data.head())
#print(data.label.value_counts)
from sklearn.model_selection import train_test_split
X_train,y_train,X_test,y_test = train_test_split(data["text"] , data["label"] , test_size = 0.2 , random_state = 10)
negatives = {}
positives ={}
alpha = 1
pA = 1
pNotA = 1
positivesTotal = 0
negativesTotal = 0
# for index, row in data.iterrows():
# print("tell 11")
#
# print(row['text'])
# print(row['label'])
# print("end here")
#
def train():
total = 0
numSpam = 0
for index, row in data.iterrows():
if row['label'] == "spam":
numSpam+=1
total+=1
processEmail(row['text'],row['label'])
pA = numSpam/float(total)
pNotA = (total - numSpam)/float(total)
def processEmail(body,label):
global positivesTotal , negativesTotal
for word in body:
if label == "spam":
positives[word] = positives.get(word , 0 ) + 1
positivesTotal += 1
else:
negatives[word] = negatives.get(word , 0 ) + 1
negativesTotal += 1
# print("negativesTotal")
# print(negativesTotal)
# print("positivesTotal")
# print(positivesTotal)
def typeofWord(word , spam):
if spam:
return (positives.get(word,0)+alpha)/(float) (positivesTotal )
return (negatives.get(word,0)+alpha)/(float)(negativesTotal )
def typeofEmail(body,spam):
result =1.0
for word in body:
result *= typeofWord(word,spam)
return result
def classify(email):
isSpam = pA * typeofEmail(email , True)
isNotSpam = pNotA * typeofEmail(email , False)
return isSpam > isNotSpam
train()
print(classify("Profits Money Free"))
print(classify("Hi Hello , Pizza was delicious"))
|
# Generated from /Users/labtop/PyCharm/BioScript/grammar/grammar/BSLexer.g4 by ANTLR 4.8
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\u00b5")
buf.write("\u047d\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")
buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r")
buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23")
buf.write("\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30")
buf.write("\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36")
buf.write("\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%")
buf.write("\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t,\4-\t-\4.")
buf.write("\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64")
buf.write("\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\49\t9\4:\t:")
buf.write("\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA\4B\tB\4C\t")
buf.write("C\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\tJ\4K\tK\4L\t")
buf.write("L\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S\tS\4T\tT\4U\t")
buf.write("U\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\4[\t[\4\\\t\\\4]\t]\4")
buf.write("^\t^\4_\t_\4`\t`\4a\ta\4b\tb\4c\tc\4d\td\4e\te\4f\tf\4")
buf.write("g\tg\4h\th\4i\ti\4j\tj\4k\tk\4l\tl\4m\tm\4n\tn\4o\to\4")
buf.write("p\tp\4q\tq\4r\tr\4s\ts\4t\tt\4u\tu\4v\tv\4w\tw\4x\tx\4")
buf.write("y\ty\4z\tz\4{\t{\4|\t|\4}\t}\4~\t~\4\177\t\177\4\u0080")
buf.write("\t\u0080\4\u0081\t\u0081\4\u0082\t\u0082\4\u0083\t\u0083")
buf.write("\4\u0084\t\u0084\4\u0085\t\u0085\4\u0086\t\u0086\4\u0087")
buf.write("\t\u0087\4\u0088\t\u0088\4\u0089\t\u0089\4\u008a\t\u008a")
buf.write("\4\u008b\t\u008b\4\u008c\t\u008c\4\u008d\t\u008d\4\u008e")
buf.write("\t\u008e\4\u008f\t\u008f\4\u0090\t\u0090\4\u0091\t\u0091")
buf.write("\4\u0092\t\u0092\4\u0093\t\u0093\4\u0094\t\u0094\4\u0095")
buf.write("\t\u0095\4\u0096\t\u0096\4\u0097\t\u0097\4\u0098\t\u0098")
buf.write("\4\u0099\t\u0099\4\u009a\t\u009a\4\u009b\t\u009b\4\u009c")
buf.write("\t\u009c\4\u009d\t\u009d\4\u009e\t\u009e\4\u009f\t\u009f")
buf.write("\4\u00a0\t\u00a0\4\u00a1\t\u00a1\4\u00a2\t\u00a2\4\u00a3")
buf.write("\t\u00a3\4\u00a4\t\u00a4\4\u00a5\t\u00a5\4\u00a6\t\u00a6")
buf.write("\4\u00a7\t\u00a7\4\u00a8\t\u00a8\4\u00a9\t\u00a9\4\u00aa")
buf.write("\t\u00aa\4\u00ab\t\u00ab\4\u00ac\t\u00ac\4\u00ad\t\u00ad")
buf.write("\4\u00ae\t\u00ae\4\u00af\t\u00af\4\u00b0\t\u00b0\4\u00b1")
buf.write("\t\u00b1\4\u00b2\t\u00b2\4\u00b3\t\u00b3\4\u00b4\t\u00b4")
buf.write("\4\u00b5\t\u00b5\4\u00b6\t\u00b6\4\u00b7\t\u00b7\4\u00b8")
buf.write("\t\u00b8\4\u00b9\t\u00b9\4\u00ba\t\u00ba\4\u00bb\t\u00bb")
buf.write("\4\u00bc\t\u00bc\4\u00bd\t\u00bd\3\2\3\2\3\2\3\3\3\3\3")
buf.write("\3\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\5\3\5\3\5\3\5")
buf.write("\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3")
buf.write("\7\3\7\3\7\3\7\3\7\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b")
buf.write("\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3\n\3")
buf.write("\n\3\n\3\n\3\n\3\n\3\13\3\13\3\13\3\13\3\13\3\13\3\13")
buf.write("\3\13\3\13\3\13\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3")
buf.write("\f\3\f\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\16\3\16\3")
buf.write("\16\3\16\3\17\3\17\3\17\3\17\3\17\3\17\3\20\3\20\3\20")
buf.write("\3\20\3\20\3\21\3\21\3\21\3\21\3\21\3\21\3\22\3\22\3\22")
buf.write("\3\22\3\22\3\22\3\22\3\22\3\22\3\23\3\23\3\23\3\23\3\23")
buf.write("\3\23\3\23\3\23\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\24")
buf.write("\3\24\3\25\3\25\3\25\3\25\3\25\3\25\3\26\3\26\3\26\3\26")
buf.write("\3\26\3\26\3\27\3\27\3\27\3\30\3\30\3\30\3\30\3\30\3\31")
buf.write("\3\31\3\31\3\31\3\32\3\32\3\32\3\32\3\32\3\33\3\33\3\33")
buf.write("\3\33\3\33\3\33\3\34\3\34\3\34\3\35\3\35\3\35\3\36\3\36")
buf.write("\3\36\3\36\3\36\3\36\3\37\3\37\3\37\3\37\3\37\3\37\3 ")
buf.write("\3 \3 \3 \3 \3 \3 \3 \3 \3!\3!\3!\3!\3!\3!\3\"\3\"\3\"")
buf.write("\3\"\3\"\3\"\3\"\3\"\3\"\3#\3#\3#\3#\3#\3#\3#\3#\3#\3")
buf.write("#\3$\3$\3$\3$\3$\3$\3$\3%\3%\3%\3%\3%\3%\3%\3%\3%\3%\3")
buf.write("&\3&\3&\3&\3\'\3\'\3\'\3\'\3\'\3(\3(\3(\3(\3)\3)\3)\3")
buf.write(")\3)\3*\3*\7*\u0285\n*\f*\16*\u0288\13*\3+\3+\3+\7+\u028d")
buf.write("\n+\f+\16+\u0290\13+\3+\3+\3,\3,\3,\3,\3,\3,\3,\3,\3,")
buf.write("\5,\u029d\n,\3-\3-\3-\5-\u02a2\n-\3-\3-\5-\u02a6\n-\3")
buf.write(".\3.\7.\u02aa\n.\f.\16.\u02ad\13.\3/\3/\5/\u02b1\n/\3")
buf.write("/\3/\3\60\3\60\5\60\u02b7\n\60\3\60\3\60\3\61\3\61\5\61")
buf.write("\u02bd\n\61\3\61\3\61\3\62\3\62\3\63\3\63\3\64\3\64\3")
buf.write("\65\3\65\3\66\3\66\3\67\3\67\38\38\39\39\3:\3:\3;\3;\3")
buf.write("<\3<\3=\3=\3>\3>\3?\3?\3@\3@\3A\3A\3B\3B\3B\3C\3C\3C\3")
buf.write("D\3D\3D\3E\3E\3E\3F\3F\3F\3G\3G\3G\3H\3H\3H\3I\3I\3I\3")
buf.write("J\3J\3K\3K\3L\3L\3M\3M\3N\3N\3O\3O\3P\3P\3Q\3Q\3R\3R\3")
buf.write("S\3S\3T\3T\3T\3U\3U\3U\3V\3V\3V\3W\3W\3W\3X\3X\3X\3Y\3")
buf.write("Y\3Z\3Z\3[\3[\3\\\3\\\3]\3]\3^\3^\3^\3_\3_\3`\3`\3`\3")
buf.write("a\3a\3a\3b\3b\3b\3c\3c\3c\3d\3d\3d\3e\3e\3f\3f\3f\3f\3")
buf.write("g\3g\3h\3h\3i\3i\3j\3j\3k\3k\3l\3l\3m\3m\3n\3n\3o\3o\3")
buf.write("p\3p\3q\3q\3r\3r\3s\3s\3s\3t\3t\3t\3u\3u\3u\3v\3v\3v\3")
buf.write("w\3w\3w\3x\3x\3x\3y\3y\3y\3z\3z\3z\3{\3{\3{\3|\3|\3|\3")
buf.write("}\3}\3}\3~\3~\3~\3\177\3\177\3\177\3\u0080\3\u0080\3\u0080")
buf.write("\3\u0081\3\u0081\3\u0081\3\u0082\3\u0082\3\u0082\3\u0083")
buf.write("\3\u0083\3\u0083\3\u0084\3\u0084\3\u0084\3\u0085\3\u0085")
buf.write("\3\u0085\3\u0086\3\u0086\3\u0086\3\u0087\3\u0087\3\u0087")
buf.write("\3\u0088\3\u0088\3\u0088\3\u0089\3\u0089\3\u0089\3\u008a")
buf.write("\3\u008a\3\u008a\3\u008b\3\u008b\3\u008b\3\u008c\3\u008c")
buf.write("\3\u008c\3\u008d\3\u008d\3\u008d\3\u008e\3\u008e\3\u008e")
buf.write("\3\u008f\3\u008f\3\u008f\3\u0090\3\u0090\3\u0090\3\u0091")
buf.write("\3\u0091\3\u0091\3\u0092\3\u0092\3\u0092\3\u0093\3\u0093")
buf.write("\3\u0093\3\u0094\3\u0094\3\u0094\3\u0095\3\u0095\3\u0095")
buf.write("\3\u0096\3\u0096\3\u0096\3\u0097\3\u0097\3\u0097\3\u0098")
buf.write("\3\u0098\3\u0098\3\u0099\3\u0099\3\u0099\3\u009a\3\u009a")
buf.write("\3\u009a\3\u009b\3\u009b\3\u009b\3\u009c\3\u009c\3\u009c")
buf.write("\3\u009d\3\u009d\3\u009d\3\u009e\3\u009e\3\u009e\3\u009f")
buf.write("\3\u009f\3\u009f\3\u00a0\3\u00a0\3\u00a0\3\u00a1\3\u00a1")
buf.write("\3\u00a1\3\u00a2\3\u00a2\3\u00a2\3\u00a3\3\u00a3\3\u00a3")
buf.write("\3\u00a4\3\u00a4\3\u00a4\3\u00a5\3\u00a5\3\u00a5\3\u00a6")
buf.write("\3\u00a6\3\u00a6\3\u00a7\3\u00a7\3\u00a7\3\u00a8\3\u00a8")
buf.write("\3\u00a8\3\u00a9\3\u00a9\3\u00a9\3\u00aa\3\u00aa\3\u00aa")
buf.write("\3\u00ab\3\u00ab\3\u00ab\3\u00ac\3\u00ac\3\u00ac\3\u00ad")
buf.write("\3\u00ad\3\u00ad\3\u00ae\3\u00ae\3\u00ae\3\u00af\3\u00af")
buf.write("\3\u00af\3\u00af\3\u00b0\3\u00b0\3\u00b0\3\u00b0\3\u00b1")
buf.write("\3\u00b1\3\u00b1\3\u00b2\6\u00b2\u0418\n\u00b2\r\u00b2")
buf.write("\16\u00b2\u0419\3\u00b2\3\u00b2\3\u00b3\3\u00b3\3\u00b3")
buf.write("\3\u00b3\7\u00b3\u0422\n\u00b3\f\u00b3\16\u00b3\u0425")
buf.write("\13\u00b3\3\u00b3\3\u00b3\3\u00b3\3\u00b3\3\u00b3\3\u00b4")
buf.write("\3\u00b4\3\u00b4\3\u00b4\7\u00b4\u0430\n\u00b4\f\u00b4")
buf.write("\16\u00b4\u0433\13\u00b4\3\u00b4\3\u00b4\3\u00b5\3\u00b5")
buf.write("\3\u00b5\3\u00b5\3\u00b5\3\u00b5\3\u00b5\3\u00b5\3\u00b5")
buf.write("\3\u00b5\3\u00b5\3\u00b5\5\u00b5\u0443\n\u00b5\3\u00b6")
buf.write("\3\u00b6\3\u00b6\3\u00b6\3\u00b6\3\u00b6\5\u00b6\u044b")
buf.write("\n\u00b6\3\u00b7\3\u00b7\3\u00b7\5\u00b7\u0450\n\u00b7")
buf.write("\3\u00b8\3\u00b8\7\u00b8\u0454\n\u00b8\f\u00b8\16\u00b8")
buf.write("\u0457\13\u00b8\3\u00b8\5\u00b8\u045a\n\u00b8\3\u00b9")
buf.write("\3\u00b9\5\u00b9\u045e\n\u00b9\3\u00ba\3\u00ba\3\u00ba")
buf.write("\3\u00ba\5\u00ba\u0464\n\u00ba\3\u00bb\3\u00bb\3\u00bb")
buf.write("\3\u00bb\5\u00bb\u046a\n\u00bb\3\u00bb\5\u00bb\u046d\n")
buf.write("\u00bb\3\u00bb\5\u00bb\u0470\n\u00bb\3\u00bc\6\u00bc\u0473")
buf.write("\n\u00bc\r\u00bc\16\u00bc\u0474\3\u00bd\5\u00bd\u0478")
buf.write("\n\u00bd\3\u00bd\3\u00bd\5\u00bd\u047c\n\u00bd\3\u0423")
buf.write("\2\u00be\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f")
buf.write("\27\r\31\16\33\17\35\20\37\21!\22#\23%\24\'\25)\26+\27")
buf.write("-\30/\31\61\32\63\33\65\34\67\359\36;\37= ?!A\"C#E$G%")
buf.write("I&K\'M(O)Q*S+U,W-Y.[/]\60_\61a\62c\63e\64g\65i\66k\67")
buf.write("m8o9q:s;u<w=y>{?}@\177A\u0081B\u0083C\u0085D\u0087E\u0089")
buf.write("F\u008bG\u008dH\u008fI\u0091J\u0093K\u0095L\u0097M\u0099")
buf.write("N\u009bO\u009dP\u009fQ\u00a1R\u00a3S\u00a5T\u00a7U\u00a9")
buf.write("V\u00abW\u00adX\u00afY\u00b1Z\u00b3[\u00b5\\\u00b7]\u00b9")
buf.write("^\u00bb_\u00bd`\u00bfa\u00c1b\u00c3c\u00c5d\u00c7e\u00c9")
buf.write("f\u00cbg\u00cdh\u00cfi\u00d1j\u00d3k\u00d5l\u00d7m\u00d9")
buf.write("n\u00dbo\u00ddp\u00dfq\u00e1r\u00e3s\u00e5t\u00e7u\u00e9")
buf.write("v\u00ebw\u00edx\u00efy\u00f1z\u00f3{\u00f5|\u00f7}\u00f9")
buf.write("~\u00fb\177\u00fd\u0080\u00ff\u0081\u0101\u0082\u0103")
buf.write("\u0083\u0105\u0084\u0107\u0085\u0109\u0086\u010b\u0087")
buf.write("\u010d\u0088\u010f\u0089\u0111\u008a\u0113\u008b\u0115")
buf.write("\u008c\u0117\u008d\u0119\u008e\u011b\u008f\u011d\u0090")
buf.write("\u011f\u0091\u0121\u0092\u0123\u0093\u0125\u0094\u0127")
buf.write("\u0095\u0129\u0096\u012b\u0097\u012d\u0098\u012f\u0099")
buf.write("\u0131\u009a\u0133\u009b\u0135\u009c\u0137\u009d\u0139")
buf.write("\u009e\u013b\u009f\u013d\u00a0\u013f\u00a1\u0141\u00a2")
buf.write("\u0143\u00a3\u0145\u00a4\u0147\u00a5\u0149\u00a6\u014b")
buf.write("\u00a7\u014d\u00a8\u014f\u00a9\u0151\u00aa\u0153\u00ab")
buf.write("\u0155\u00ac\u0157\u00ad\u0159\u00ae\u015b\u00af\u015d")
buf.write("\u00b0\u015f\u00b1\u0161\u00b2\u0163\u00b3\u0165\u00b4")
buf.write("\u0167\u00b5\u0169\2\u016b\2\u016d\2\u016f\2\u0171\2\u0173")
buf.write("\2\u0175\2\u0177\2\u0179\2\3\2\17\6\2\f\f\17\17$$^^\5")
buf.write("\2\13\f\16\17\"\"\4\2\f\f\17\17\3\2\62;\4\2\62;aa\6\2")
buf.write("&&C\\aac|\4\2\2\u0081\ud802\udc01\3\2\ud802\udc01\3\2")
buf.write("\udc02\ue001\n\2$$))^^ddhhppttvv\3\2\62\65\3\2\629\4\2")
buf.write("\13\13\"\"\2\u049d\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2")
buf.write("\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21")
buf.write("\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3")
buf.write("\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2\2\2\2!\3\2\2")
buf.write("\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2")
buf.write("\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2")
buf.write("\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2")
buf.write("\2\2\2?\3\2\2\2\2A\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3")
buf.write("\2\2\2\2I\3\2\2\2\2K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2Q")
buf.write("\3\2\2\2\2S\3\2\2\2\2U\3\2\2\2\2W\3\2\2\2\2Y\3\2\2\2\2")
buf.write("[\3\2\2\2\2]\3\2\2\2\2_\3\2\2\2\2a\3\2\2\2\2c\3\2\2\2")
buf.write("\2e\3\2\2\2\2g\3\2\2\2\2i\3\2\2\2\2k\3\2\2\2\2m\3\2\2")
buf.write("\2\2o\3\2\2\2\2q\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2\2w\3\2")
buf.write("\2\2\2y\3\2\2\2\2{\3\2\2\2\2}\3\2\2\2\2\177\3\2\2\2\2")
buf.write("\u0081\3\2\2\2\2\u0083\3\2\2\2\2\u0085\3\2\2\2\2\u0087")
buf.write("\3\2\2\2\2\u0089\3\2\2\2\2\u008b\3\2\2\2\2\u008d\3\2\2")
buf.write("\2\2\u008f\3\2\2\2\2\u0091\3\2\2\2\2\u0093\3\2\2\2\2\u0095")
buf.write("\3\2\2\2\2\u0097\3\2\2\2\2\u0099\3\2\2\2\2\u009b\3\2\2")
buf.write("\2\2\u009d\3\2\2\2\2\u009f\3\2\2\2\2\u00a1\3\2\2\2\2\u00a3")
buf.write("\3\2\2\2\2\u00a5\3\2\2\2\2\u00a7\3\2\2\2\2\u00a9\3\2\2")
buf.write("\2\2\u00ab\3\2\2\2\2\u00ad\3\2\2\2\2\u00af\3\2\2\2\2\u00b1")
buf.write("\3\2\2\2\2\u00b3\3\2\2\2\2\u00b5\3\2\2\2\2\u00b7\3\2\2")
buf.write("\2\2\u00b9\3\2\2\2\2\u00bb\3\2\2\2\2\u00bd\3\2\2\2\2\u00bf")
buf.write("\3\2\2\2\2\u00c1\3\2\2\2\2\u00c3\3\2\2\2\2\u00c5\3\2\2")
buf.write("\2\2\u00c7\3\2\2\2\2\u00c9\3\2\2\2\2\u00cb\3\2\2\2\2\u00cd")
buf.write("\3\2\2\2\2\u00cf\3\2\2\2\2\u00d1\3\2\2\2\2\u00d3\3\2\2")
buf.write("\2\2\u00d5\3\2\2\2\2\u00d7\3\2\2\2\2\u00d9\3\2\2\2\2\u00db")
buf.write("\3\2\2\2\2\u00dd\3\2\2\2\2\u00df\3\2\2\2\2\u00e1\3\2\2")
buf.write("\2\2\u00e3\3\2\2\2\2\u00e5\3\2\2\2\2\u00e7\3\2\2\2\2\u00e9")
buf.write("\3\2\2\2\2\u00eb\3\2\2\2\2\u00ed\3\2\2\2\2\u00ef\3\2\2")
buf.write("\2\2\u00f1\3\2\2\2\2\u00f3\3\2\2\2\2\u00f5\3\2\2\2\2\u00f7")
buf.write("\3\2\2\2\2\u00f9\3\2\2\2\2\u00fb\3\2\2\2\2\u00fd\3\2\2")
buf.write("\2\2\u00ff\3\2\2\2\2\u0101\3\2\2\2\2\u0103\3\2\2\2\2\u0105")
buf.write("\3\2\2\2\2\u0107\3\2\2\2\2\u0109\3\2\2\2\2\u010b\3\2\2")
buf.write("\2\2\u010d\3\2\2\2\2\u010f\3\2\2\2\2\u0111\3\2\2\2\2\u0113")
buf.write("\3\2\2\2\2\u0115\3\2\2\2\2\u0117\3\2\2\2\2\u0119\3\2\2")
buf.write("\2\2\u011b\3\2\2\2\2\u011d\3\2\2\2\2\u011f\3\2\2\2\2\u0121")
buf.write("\3\2\2\2\2\u0123\3\2\2\2\2\u0125\3\2\2\2\2\u0127\3\2\2")
buf.write("\2\2\u0129\3\2\2\2\2\u012b\3\2\2\2\2\u012d\3\2\2\2\2\u012f")
buf.write("\3\2\2\2\2\u0131\3\2\2\2\2\u0133\3\2\2\2\2\u0135\3\2\2")
buf.write("\2\2\u0137\3\2\2\2\2\u0139\3\2\2\2\2\u013b\3\2\2\2\2\u013d")
buf.write("\3\2\2\2\2\u013f\3\2\2\2\2\u0141\3\2\2\2\2\u0143\3\2\2")
buf.write("\2\2\u0145\3\2\2\2\2\u0147\3\2\2\2\2\u0149\3\2\2\2\2\u014b")
buf.write("\3\2\2\2\2\u014d\3\2\2\2\2\u014f\3\2\2\2\2\u0151\3\2\2")
buf.write("\2\2\u0153\3\2\2\2\2\u0155\3\2\2\2\2\u0157\3\2\2\2\2\u0159")
buf.write("\3\2\2\2\2\u015b\3\2\2\2\2\u015d\3\2\2\2\2\u015f\3\2\2")
buf.write("\2\2\u0161\3\2\2\2\2\u0163\3\2\2\2\2\u0165\3\2\2\2\2\u0167")
buf.write("\3\2\2\2\3\u017b\3\2\2\2\5\u017e\3\2\2\2\7\u0183\3\2\2")
buf.write("\2\t\u018a\3\2\2\2\13\u0190\3\2\2\2\r\u0199\3\2\2\2\17")
buf.write("\u01a0\3\2\2\2\21\u01a9\3\2\2\2\23\u01b0\3\2\2\2\25\u01bb")
buf.write("\3\2\2\2\27\u01c5\3\2\2\2\31\u01d2\3\2\2\2\33\u01d9\3")
buf.write("\2\2\2\35\u01dd\3\2\2\2\37\u01e3\3\2\2\2!\u01e8\3\2\2")
buf.write("\2#\u01ee\3\2\2\2%\u01f7\3\2\2\2\'\u01ff\3\2\2\2)\u0208")
buf.write("\3\2\2\2+\u020e\3\2\2\2-\u0214\3\2\2\2/\u0217\3\2\2\2")
buf.write("\61\u021c\3\2\2\2\63\u0220\3\2\2\2\65\u0225\3\2\2\2\67")
buf.write("\u022b\3\2\2\29\u022e\3\2\2\2;\u0231\3\2\2\2=\u0237\3")
buf.write("\2\2\2?\u023d\3\2\2\2A\u0246\3\2\2\2C\u024c\3\2\2\2E\u0255")
buf.write("\3\2\2\2G\u025f\3\2\2\2I\u0266\3\2\2\2K\u0270\3\2\2\2")
buf.write("M\u0274\3\2\2\2O\u0279\3\2\2\2Q\u027d\3\2\2\2S\u0282\3")
buf.write("\2\2\2U\u0289\3\2\2\2W\u029c\3\2\2\2Y\u02a5\3\2\2\2[\u02a7")
buf.write("\3\2\2\2]\u02b0\3\2\2\2_\u02b6\3\2\2\2a\u02bc\3\2\2\2")
buf.write("c\u02c0\3\2\2\2e\u02c2\3\2\2\2g\u02c4\3\2\2\2i\u02c6\3")
buf.write("\2\2\2k\u02c8\3\2\2\2m\u02ca\3\2\2\2o\u02cc\3\2\2\2q\u02ce")
buf.write("\3\2\2\2s\u02d0\3\2\2\2u\u02d2\3\2\2\2w\u02d4\3\2\2\2")
buf.write("y\u02d6\3\2\2\2{\u02d8\3\2\2\2}\u02da\3\2\2\2\177\u02dc")
buf.write("\3\2\2\2\u0081\u02de\3\2\2\2\u0083\u02e0\3\2\2\2\u0085")
buf.write("\u02e3\3\2\2\2\u0087\u02e6\3\2\2\2\u0089\u02e9\3\2\2\2")
buf.write("\u008b\u02ec\3\2\2\2\u008d\u02ef\3\2\2\2\u008f\u02f2\3")
buf.write("\2\2\2\u0091\u02f5\3\2\2\2\u0093\u02f8\3\2\2\2\u0095\u02fa")
buf.write("\3\2\2\2\u0097\u02fc\3\2\2\2\u0099\u02fe\3\2\2\2\u009b")
buf.write("\u0300\3\2\2\2\u009d\u0302\3\2\2\2\u009f\u0304\3\2\2\2")
buf.write("\u00a1\u0306\3\2\2\2\u00a3\u0308\3\2\2\2\u00a5\u030a\3")
buf.write("\2\2\2\u00a7\u030c\3\2\2\2\u00a9\u030f\3\2\2\2\u00ab\u0312")
buf.write("\3\2\2\2\u00ad\u0315\3\2\2\2\u00af\u0318\3\2\2\2\u00b1")
buf.write("\u031b\3\2\2\2\u00b3\u031d\3\2\2\2\u00b5\u031f\3\2\2\2")
buf.write("\u00b7\u0321\3\2\2\2\u00b9\u0323\3\2\2\2\u00bb\u0325\3")
buf.write("\2\2\2\u00bd\u0328\3\2\2\2\u00bf\u032a\3\2\2\2\u00c1\u032d")
buf.write("\3\2\2\2\u00c3\u0330\3\2\2\2\u00c5\u0333\3\2\2\2\u00c7")
buf.write("\u0336\3\2\2\2\u00c9\u0339\3\2\2\2\u00cb\u033b\3\2\2\2")
buf.write("\u00cd\u033f\3\2\2\2\u00cf\u0341\3\2\2\2\u00d1\u0343\3")
buf.write("\2\2\2\u00d3\u0345\3\2\2\2\u00d5\u0347\3\2\2\2\u00d7\u0349")
buf.write("\3\2\2\2\u00d9\u034b\3\2\2\2\u00db\u034d\3\2\2\2\u00dd")
buf.write("\u034f\3\2\2\2\u00df\u0351\3\2\2\2\u00e1\u0353\3\2\2\2")
buf.write("\u00e3\u0355\3\2\2\2\u00e5\u0357\3\2\2\2\u00e7\u035a\3")
buf.write("\2\2\2\u00e9\u035d\3\2\2\2\u00eb\u0360\3\2\2\2\u00ed\u0363")
buf.write("\3\2\2\2\u00ef\u0366\3\2\2\2\u00f1\u0369\3\2\2\2\u00f3")
buf.write("\u036c\3\2\2\2\u00f5\u036f\3\2\2\2\u00f7\u0372\3\2\2\2")
buf.write("\u00f9\u0375\3\2\2\2\u00fb\u0378\3\2\2\2\u00fd\u037b\3")
buf.write("\2\2\2\u00ff\u037e\3\2\2\2\u0101\u0381\3\2\2\2\u0103\u0384")
buf.write("\3\2\2\2\u0105\u0387\3\2\2\2\u0107\u038a\3\2\2\2\u0109")
buf.write("\u038d\3\2\2\2\u010b\u0390\3\2\2\2\u010d\u0393\3\2\2\2")
buf.write("\u010f\u0396\3\2\2\2\u0111\u0399\3\2\2\2\u0113\u039c\3")
buf.write("\2\2\2\u0115\u039f\3\2\2\2\u0117\u03a2\3\2\2\2\u0119\u03a5")
buf.write("\3\2\2\2\u011b\u03a8\3\2\2\2\u011d\u03ab\3\2\2\2\u011f")
buf.write("\u03ae\3\2\2\2\u0121\u03b1\3\2\2\2\u0123\u03b4\3\2\2\2")
buf.write("\u0125\u03b7\3\2\2\2\u0127\u03ba\3\2\2\2\u0129\u03bd\3")
buf.write("\2\2\2\u012b\u03c0\3\2\2\2\u012d\u03c3\3\2\2\2\u012f\u03c6")
buf.write("\3\2\2\2\u0131\u03c9\3\2\2\2\u0133\u03cc\3\2\2\2\u0135")
buf.write("\u03cf\3\2\2\2\u0137\u03d2\3\2\2\2\u0139\u03d5\3\2\2\2")
buf.write("\u013b\u03d8\3\2\2\2\u013d\u03db\3\2\2\2\u013f\u03de\3")
buf.write("\2\2\2\u0141\u03e1\3\2\2\2\u0143\u03e4\3\2\2\2\u0145\u03e7")
buf.write("\3\2\2\2\u0147\u03ea\3\2\2\2\u0149\u03ed\3\2\2\2\u014b")
buf.write("\u03f0\3\2\2\2\u014d\u03f3\3\2\2\2\u014f\u03f6\3\2\2\2")
buf.write("\u0151\u03f9\3\2\2\2\u0153\u03fc\3\2\2\2\u0155\u03ff\3")
buf.write("\2\2\2\u0157\u0402\3\2\2\2\u0159\u0405\3\2\2\2\u015b\u0408")
buf.write("\3\2\2\2\u015d\u040b\3\2\2\2\u015f\u040f\3\2\2\2\u0161")
buf.write("\u0413\3\2\2\2\u0163\u0417\3\2\2\2\u0165\u041d\3\2\2\2")
buf.write("\u0167\u042b\3\2\2\2\u0169\u0442\3\2\2\2\u016b\u044a\3")
buf.write("\2\2\2\u016d\u044f\3\2\2\2\u016f\u0451\3\2\2\2\u0171\u045d")
buf.write("\3\2\2\2\u0173\u0463\3\2\2\2\u0175\u046f\3\2\2\2\u0177")
buf.write("\u0472\3\2\2\2\u0179\u047b\3\2\2\2\u017b\u017c\7k\2\2")
buf.write("\u017c\u017d\7h\2\2\u017d\4\3\2\2\2\u017e\u017f\7g\2\2")
buf.write("\u017f\u0180\7n\2\2\u0180\u0181\7u\2\2\u0181\u0182\7g")
buf.write("\2\2\u0182\6\3\2\2\2\u0183\u0184\7t\2\2\u0184\u0185\7")
buf.write("g\2\2\u0185\u0186\7r\2\2\u0186\u0187\7g\2\2\u0187\u0188")
buf.write("\7c\2\2\u0188\u0189\7v\2\2\u0189\b\3\2\2\2\u018a\u018b")
buf.write("\7y\2\2\u018b\u018c\7j\2\2\u018c\u018d\7k\2\2\u018d\u018e")
buf.write("\7n\2\2\u018e\u018f\7g\2\2\u018f\n\3\2\2\2\u0190\u0191")
buf.write("\7h\2\2\u0191\u0192\7w\2\2\u0192\u0193\7p\2\2\u0193\u0194")
buf.write("\7e\2\2\u0194\u0195\7v\2\2\u0195\u0196\7k\2\2\u0196\u0197")
buf.write("\7q\2\2\u0197\u0198\7p\2\2\u0198\f\3\2\2\2\u0199\u019a")
buf.write("\7t\2\2\u019a\u019b\7g\2\2\u019b\u019c\7v\2\2\u019c\u019d")
buf.write("\7w\2\2\u019d\u019e\7t\2\2\u019e\u019f\7p\2\2\u019f\16")
buf.write("\3\2\2\2\u01a0\u01a1\7o\2\2\u01a1\u01a2\7c\2\2\u01a2\u01a3")
buf.write("\7p\2\2\u01a3\u01a4\7k\2\2\u01a4\u01a5\7h\2\2\u01a5\u01a6")
buf.write("\7g\2\2\u01a6\u01a7\7u\2\2\u01a7\u01a8\7v\2\2\u01a8\20")
buf.write("\3\2\2\2\u01a9\u01aa\7o\2\2\u01aa\u01ab\7q\2\2\u01ab\u01ac")
buf.write("\7f\2\2\u01ac\u01ad\7w\2\2\u01ad\u01ae\7n\2\2\u01ae\u01af")
buf.write("\7g\2\2\u01af\22\3\2\2\2\u01b0\u01b1\7u\2\2\u01b1\u01b2")
buf.write("\7v\2\2\u01b2\u01b3\7c\2\2\u01b3\u01b4\7v\2\2\u01b4\u01b5")
buf.write("\7k\2\2\u01b5\u01b6\7q\2\2\u01b6\u01b7\7p\2\2\u01b7\u01b8")
buf.write("\7c\2\2\u01b8\u01b9\7t\2\2\u01b9\u01ba\7{\2\2\u01ba\24")
buf.write("\3\2\2\2\u01bb\u01bc\7h\2\2\u01bc\u01bd\7w\2\2\u01bd\u01be")
buf.write("\7p\2\2\u01be\u01bf\7e\2\2\u01bf\u01c0\7v\2\2\u01c0\u01c1")
buf.write("\7k\2\2\u01c1\u01c2\7q\2\2\u01c2\u01c3\7p\2\2\u01c3\u01c4")
buf.write("\7u\2\2\u01c4\26\3\2\2\2\u01c5\u01c6\7k\2\2\u01c6\u01c7")
buf.write("\7p\2\2\u01c7\u01c8\7u\2\2\u01c8\u01c9\7v\2\2\u01c9\u01ca")
buf.write("\7t\2\2\u01ca\u01cb\7w\2\2\u01cb\u01cc\7e\2\2\u01cc\u01cd")
buf.write("\7v\2\2\u01cd\u01ce\7k\2\2\u01ce\u01cf\7q\2\2\u01cf\u01d0")
buf.write("\7p\2\2\u01d0\u01d1\7u\2\2\u01d1\30\3\2\2\2\u01d2\u01d3")
buf.write("\7f\2\2\u01d3\u01d4\7g\2\2\u01d4\u01d5\7v\2\2\u01d5\u01d6")
buf.write("\7g\2\2\u01d6\u01d7\7e\2\2\u01d7\u01d8\7v\2\2\u01d8\32")
buf.write("\3\2\2\2\u01d9\u01da\7o\2\2\u01da\u01db\7k\2\2\u01db\u01dc")
buf.write("\7z\2\2\u01dc\34\3\2\2\2\u01dd\u01de\7u\2\2\u01de\u01df")
buf.write("\7r\2\2\u01df\u01e0\7n\2\2\u01e0\u01e1\7k\2\2\u01e1\u01e2")
buf.write("\7v\2\2\u01e2\36\3\2\2\2\u01e3\u01e4\7j\2\2\u01e4\u01e5")
buf.write("\7g\2\2\u01e5\u01e6\7c\2\2\u01e6\u01e7\7v\2\2\u01e7 \3")
buf.write("\2\2\2\u01e8\u01e9\7f\2\2\u01e9\u01ea\7t\2\2\u01ea\u01eb")
buf.write("\7c\2\2\u01eb\u01ec\7k\2\2\u01ec\u01ed\7p\2\2\u01ed\"")
buf.write("\3\2\2\2\u01ee\u01ef\7f\2\2\u01ef\u01f0\7k\2\2\u01f0\u01f1")
buf.write("\7u\2\2\u01f1\u01f2\7r\2\2\u01f2\u01f3\7g\2\2\u01f3\u01f4")
buf.write("\7p\2\2\u01f4\u01f5\7u\2\2\u01f5\u01f6\7g\2\2\u01f6$\3")
buf.write("\2\2\2\u01f7\u01f8\7f\2\2\u01f8\u01f9\7k\2\2\u01f9\u01fa")
buf.write("\7u\2\2\u01fa\u01fb\7r\2\2\u01fb\u01fc\7q\2\2\u01fc\u01fd")
buf.write("\7u\2\2\u01fd\u01fe\7g\2\2\u01fe&\3\2\2\2\u01ff\u0200")
buf.write("\7i\2\2\u0200\u0201\7t\2\2\u0201\u0202\7c\2\2\u0202\u0203")
buf.write("\7f\2\2\u0203\u0204\7k\2\2\u0204\u0205\7g\2\2\u0205\u0206")
buf.write("\7p\2\2\u0206\u0207\7v\2\2\u0207(\3\2\2\2\u0208\u0209")
buf.write("\7u\2\2\u0209\u020a\7v\2\2\u020a\u020b\7q\2\2\u020b\u020c")
buf.write("\7t\2\2\u020c\u020d\7g\2\2\u020d*\3\2\2\2\u020e\u020f")
buf.write("\7t\2\2\u020f\u0210\7c\2\2\u0210\u0211\7p\2\2\u0211\u0212")
buf.write("\7i\2\2\u0212\u0213\7g\2\2\u0213,\3\2\2\2\u0214\u0215")
buf.write("\7c\2\2\u0215\u0216\7v\2\2\u0216.\3\2\2\2\u0217\u0218")
buf.write("\7y\2\2\u0218\u0219\7k\2\2\u0219\u021a\7v\2\2\u021a\u021b")
buf.write("\7j\2\2\u021b\60\3\2\2\2\u021c\u021d\7h\2\2\u021d\u021e")
buf.write("\7q\2\2\u021e\u021f\7t\2\2\u021f\62\3\2\2\2\u0220\u0221")
buf.write("\7k\2\2\u0221\u0222\7p\2\2\u0222\u0223\7v\2\2\u0223\u0224")
buf.write("\7q\2\2\u0224\64\3\2\2\2\u0225\u0226\7v\2\2\u0226\u0227")
buf.write("\7k\2\2\u0227\u0228\7o\2\2\u0228\u0229\7g\2\2\u0229\u022a")
buf.write("\7u\2\2\u022a\66\3\2\2\2\u022b\u022c\7q\2\2\u022c\u022d")
buf.write("\7p\2\2\u022d8\3\2\2\2\u022e\u022f\7q\2\2\u022f\u0230")
buf.write("\7h\2\2\u0230:\3\2\2\2\u0231\u0232\7w\2\2\u0232\u0233")
buf.write("\7p\2\2\u0233\u0234\7k\2\2\u0234\u0235\7v\2\2\u0235\u0236")
buf.write("\7u\2\2\u0236<\3\2\2\2\u0237\u0238\7w\2\2\u0238\u0239")
buf.write("\7u\2\2\u0239\u023a\7g\2\2\u023a\u023b\7k\2\2\u023b\u023c")
buf.write("\7p\2\2\u023c>\3\2\2\2\u023d\u023e\7u\2\2\u023e\u023f")
buf.write("\7v\2\2\u023f\u0240\7c\2\2\u0240\u0241\7t\2\2\u0241\u0242")
buf.write("\7v\2\2\u0242\u0243\7\"\2\2\u0243\u0244\7>\2\2\u0244\u0245")
buf.write("\7?\2\2\u0245@\3\2\2\2\u0246\u0247\7u\2\2\u0247\u0248")
buf.write("\7v\2\2\u0248\u0249\7c\2\2\u0249\u024a\7t\2\2\u024a\u024b")
buf.write("\7v\2\2\u024bB\3\2\2\2\u024c\u024d\7u\2\2\u024d\u024e")
buf.write("\7v\2\2\u024e\u024f\7c\2\2\u024f\u0250\7t\2\2\u0250\u0251")
buf.write("\7v\2\2\u0251\u0252\7\"\2\2\u0252\u0253\7@\2\2\u0253\u0254")
buf.write("\7?\2\2\u0254D\3\2\2\2\u0255\u0256\7h\2\2\u0256\u0257")
buf.write("\7k\2\2\u0257\u0258\7p\2\2\u0258\u0259\7k\2\2\u0259\u025a")
buf.write("\7u\2\2\u025a\u025b\7j\2\2\u025b\u025c\7\"\2\2\u025c\u025d")
buf.write("\7>\2\2\u025d\u025e\7?\2\2\u025eF\3\2\2\2\u025f\u0260")
buf.write("\7h\2\2\u0260\u0261\7k\2\2\u0261\u0262\7p\2\2\u0262\u0263")
buf.write("\7k\2\2\u0263\u0264\7u\2\2\u0264\u0265\7j\2\2\u0265H\3")
buf.write("\2\2\2\u0266\u0267\7h\2\2\u0267\u0268\7k\2\2\u0268\u0269")
buf.write("\7p\2\2\u0269\u026a\7k\2\2\u026a\u026b\7u\2\2\u026b\u026c")
buf.write("\7j\2\2\u026c\u026d\7\"\2\2\u026d\u026e\7@\2\2\u026e\u026f")
buf.write("\7?\2\2\u026fJ\3\2\2\2\u0270\u0271\7p\2\2\u0271\u0272")
buf.write("\7c\2\2\u0272\u0273\7v\2\2\u0273L\3\2\2\2\u0274\u0275")
buf.write("\7t\2\2\u0275\u0276\7g\2\2\u0276\u0277\7c\2\2\u0277\u0278")
buf.write("\7n\2\2\u0278N\3\2\2\2\u0279\u027a\7o\2\2\u027a\u027b")
buf.write("\7c\2\2\u027b\u027c\7v\2\2\u027cP\3\2\2\2\u027d\u027e")
buf.write("\7d\2\2\u027e\u027f\7q\2\2\u027f\u0280\7q\2\2\u0280\u0281")
buf.write("\7n\2\2\u0281R\3\2\2\2\u0282\u0286\5\u0173\u00ba\2\u0283")
buf.write("\u0285\5\u0171\u00b9\2\u0284\u0283\3\2\2\2\u0285\u0288")
buf.write("\3\2\2\2\u0286\u0284\3\2\2\2\u0286\u0287\3\2\2\2\u0287")
buf.write("T\3\2\2\2\u0288\u0286\3\2\2\2\u0289\u028e\7$\2\2\u028a")
buf.write("\u028d\n\2\2\2\u028b\u028d\5\u0175\u00bb\2\u028c\u028a")
buf.write("\3\2\2\2\u028c\u028b\3\2\2\2\u028d\u0290\3\2\2\2\u028e")
buf.write("\u028c\3\2\2\2\u028e\u028f\3\2\2\2\u028f\u0291\3\2\2\2")
buf.write("\u0290\u028e\3\2\2\2\u0291\u0292\7$\2\2\u0292V\3\2\2\2")
buf.write("\u0293\u0294\7v\2\2\u0294\u0295\7t\2\2\u0295\u0296\7w")
buf.write("\2\2\u0296\u029d\7g\2\2\u0297\u0298\7h\2\2\u0298\u0299")
buf.write("\7c\2\2\u0299\u029a\7n\2\2\u029a\u029b\7u\2\2\u029b\u029d")
buf.write("\7g\2\2\u029c\u0293\3\2\2\2\u029c\u0297\3\2\2\2\u029d")
buf.write("X\3\2\2\2\u029e\u029f\5\u016f\u00b8\2\u029f\u02a1\7\60")
buf.write("\2\2\u02a0\u02a2\5\u016f\u00b8\2\u02a1\u02a0\3\2\2\2\u02a1")
buf.write("\u02a2\3\2\2\2\u02a2\u02a6\3\2\2\2\u02a3\u02a4\7\60\2")
buf.write("\2\u02a4\u02a6\5\u016f\u00b8\2\u02a5\u029e\3\2\2\2\u02a5")
buf.write("\u02a3\3\2\2\2\u02a6Z\3\2\2\2\u02a7\u02ab\5\u016f\u00b8")
buf.write("\2\u02a8\u02aa\5\u016f\u00b8\2\u02a9\u02a8\3\2\2\2\u02aa")
buf.write("\u02ad\3\2\2\2\u02ab\u02a9\3\2\2\2\u02ab\u02ac\3\2\2\2")
buf.write("\u02ac\\\3\2\2\2\u02ad\u02ab\3\2\2\2\u02ae\u02b1\5Y-\2")
buf.write("\u02af\u02b1\5[.\2\u02b0\u02ae\3\2\2\2\u02b0\u02af\3\2")
buf.write("\2\2\u02b1\u02b2\3\2\2\2\u02b2\u02b3\5\u0169\u00b5\2\u02b3")
buf.write("^\3\2\2\2\u02b4\u02b7\5Y-\2\u02b5\u02b7\5[.\2\u02b6\u02b4")
buf.write("\3\2\2\2\u02b6\u02b5\3\2\2\2\u02b7\u02b8\3\2\2\2\u02b8")
buf.write("\u02b9\5\u016b\u00b6\2\u02b9`\3\2\2\2\u02ba\u02bd\5Y-")
buf.write("\2\u02bb\u02bd\5[.\2\u02bc\u02ba\3\2\2\2\u02bc\u02bb\3")
buf.write("\2\2\2\u02bd\u02be\3\2\2\2\u02be\u02bf\5\u016d\u00b7\2")
buf.write("\u02bfb\3\2\2\2\u02c0\u02c1\7*\2\2\u02c1d\3\2\2\2\u02c2")
buf.write("\u02c3\7+\2\2\u02c3f\3\2\2\2\u02c4\u02c5\7}\2\2\u02c5")
buf.write("h\3\2\2\2\u02c6\u02c7\7\177\2\2\u02c7j\3\2\2\2\u02c8\u02c9")
buf.write("\7]\2\2\u02c9l\3\2\2\2\u02ca\u02cb\7_\2\2\u02cbn\3\2\2")
buf.write("\2\u02cc\u02cd\7=\2\2\u02cdp\3\2\2\2\u02ce\u02cf\7.\2")
buf.write("\2\u02cfr\3\2\2\2\u02d0\u02d1\7\60\2\2\u02d1t\3\2\2\2")
buf.write("\u02d2\u02d3\7?\2\2\u02d3v\3\2\2\2\u02d4\u02d5\7@\2\2")
buf.write("\u02d5x\3\2\2\2\u02d6\u02d7\7>\2\2\u02d7z\3\2\2\2\u02d8")
buf.write("\u02d9\7#\2\2\u02d9|\3\2\2\2\u02da\u02db\7\u0080\2\2\u02db")
buf.write("~\3\2\2\2\u02dc\u02dd\7A\2\2\u02dd\u0080\3\2\2\2\u02de")
buf.write("\u02df\7<\2\2\u02df\u0082\3\2\2\2\u02e0\u02e1\7?\2\2\u02e1")
buf.write("\u02e2\7?\2\2\u02e2\u0084\3\2\2\2\u02e3\u02e4\7>\2\2\u02e4")
buf.write("\u02e5\7?\2\2\u02e5\u0086\3\2\2\2\u02e6\u02e7\7@\2\2\u02e7")
buf.write("\u02e8\7?\2\2\u02e8\u0088\3\2\2\2\u02e9\u02ea\7#\2\2\u02ea")
buf.write("\u02eb\7?\2\2\u02eb\u008a\3\2\2\2\u02ec\u02ed\7(\2\2\u02ed")
buf.write("\u02ee\7(\2\2\u02ee\u008c\3\2\2\2\u02ef\u02f0\7~\2\2\u02f0")
buf.write("\u02f1\7~\2\2\u02f1\u008e\3\2\2\2\u02f2\u02f3\7-\2\2\u02f3")
buf.write("\u02f4\7-\2\2\u02f4\u0090\3\2\2\2\u02f5\u02f6\7/\2\2\u02f6")
buf.write("\u02f7\7/\2\2\u02f7\u0092\3\2\2\2\u02f8\u02f9\7-\2\2\u02f9")
buf.write("\u0094\3\2\2\2\u02fa\u02fb\7/\2\2\u02fb\u0096\3\2\2\2")
buf.write("\u02fc\u02fd\7,\2\2\u02fd\u0098\3\2\2\2\u02fe\u02ff\7")
buf.write("\61\2\2\u02ff\u009a\3\2\2\2\u0300\u0301\7(\2\2\u0301\u009c")
buf.write("\3\2\2\2\u0302\u0303\7~\2\2\u0303\u009e\3\2\2\2\u0304")
buf.write("\u0305\7`\2\2\u0305\u00a0\3\2\2\2\u0306\u0307\7\'\2\2")
buf.write("\u0307\u00a2\3\2\2\2\u0308\u0309\7a\2\2\u0309\u00a4\3")
buf.write("\2\2\2\u030a\u030b\7B\2\2\u030b\u00a6\3\2\2\2\u030c\u030d")
buf.write("\7p\2\2\u030d\u030e\7u\2\2\u030e\u00a8\3\2\2\2\u030f\u0310")
buf.write("\7w\2\2\u0310\u0311\7u\2\2\u0311\u00aa\3\2\2\2\u0312\u0313")
buf.write("\7o\2\2\u0313\u0314\7u\2\2\u0314\u00ac\3\2\2\2\u0315\u0316")
buf.write("\7e\2\2\u0316\u0317\7u\2\2\u0317\u00ae\3\2\2\2\u0318\u0319")
buf.write("\7f\2\2\u0319\u031a\7u\2\2\u031a\u00b0\3\2\2\2\u031b\u031c")
buf.write("\7u\2\2\u031c\u00b2\3\2\2\2\u031d\u031e\7o\2\2\u031e\u00b4")
buf.write("\3\2\2\2\u031f\u0320\7j\2\2\u0320\u00b6\3\2\2\2\u0321")
buf.write("\u0322\7f\2\2\u0322\u00b8\3\2\2\2\u0323\u0324\7y\2\2\u0324")
buf.write("\u00ba\3\2\2\2\u0325\u0326\7o\2\2\u0326\u0327\7q\2\2\u0327")
buf.write("\u00bc\3\2\2\2\u0328\u0329\7{\2\2\u0329\u00be\3\2\2\2")
buf.write("\u032a\u032b\7p\2\2\u032b\u032c\7N\2\2\u032c\u00c0\3\2")
buf.write("\2\2\u032d\u032e\7w\2\2\u032e\u032f\7N\2\2\u032f\u00c2")
buf.write("\3\2\2\2\u0330\u0331\7o\2\2\u0331\u0332\7N\2\2\u0332\u00c4")
buf.write("\3\2\2\2\u0333\u0334\7e\2\2\u0334\u0335\7N\2\2\u0335\u00c6")
buf.write("\3\2\2\2\u0336\u0337\7f\2\2\u0337\u0338\7N\2\2\u0338\u00c8")
buf.write("\3\2\2\2\u0339\u033a\7N\2\2\u033a\u00ca\3\2\2\2\u033b")
buf.write("\u033c\7f\2\2\u033c\u033d\7c\2\2\u033d\u033e\7N\2\2\u033e")
buf.write("\u00cc\3\2\2\2\u033f\u0340\7e\2\2\u0340\u00ce\3\2\2\2")
buf.write("\u0341\u0342\7h\2\2\u0342\u00d0\3\2\2\2\u0343\u0344\7")
buf.write("m\2\2\u0344\u00d2\3\2\2\2\u0345\u0346\7\63\2\2\u0346\u00d4")
buf.write("\3\2\2\2\u0347\u0348\7\64\2\2\u0348\u00d6\3\2\2\2\u0349")
buf.write("\u034a\7\65\2\2\u034a\u00d8\3\2\2\2\u034b\u034c\7\66\2")
buf.write("\2\u034c\u00da\3\2\2\2\u034d\u034e\7\67\2\2\u034e\u00dc")
buf.write("\3\2\2\2\u034f\u0350\78\2\2\u0350\u00de\3\2\2\2\u0351")
buf.write("\u0352\79\2\2\u0352\u00e0\3\2\2\2\u0353\u0354\7:\2\2\u0354")
buf.write("\u00e2\3\2\2\2\u0355\u0356\7;\2\2\u0356\u00e4\3\2\2\2")
buf.write("\u0357\u0358\7\63\2\2\u0358\u0359\7\62\2\2\u0359\u00e6")
buf.write("\3\2\2\2\u035a\u035b\7\63\2\2\u035b\u035c\7\63\2\2\u035c")
buf.write("\u00e8\3\2\2\2\u035d\u035e\7\63\2\2\u035e\u035f\7\64\2")
buf.write("\2\u035f\u00ea\3\2\2\2\u0360\u0361\7\63\2\2\u0361\u0362")
buf.write("\7\65\2\2\u0362\u00ec\3\2\2\2\u0363\u0364\7\63\2\2\u0364")
buf.write("\u0365\7\66\2\2\u0365\u00ee\3\2\2\2\u0366\u0367\7\63\2")
buf.write("\2\u0367\u0368\7\67\2\2\u0368\u00f0\3\2\2\2\u0369\u036a")
buf.write("\7\63\2\2\u036a\u036b\78\2\2\u036b\u00f2\3\2\2\2\u036c")
buf.write("\u036d\7\63\2\2\u036d\u036e\79\2\2\u036e\u00f4\3\2\2\2")
buf.write("\u036f\u0370\7\63\2\2\u0370\u0371\7:\2\2\u0371\u00f6\3")
buf.write("\2\2\2\u0372\u0373\7\63\2\2\u0373\u0374\7;\2\2\u0374\u00f8")
buf.write("\3\2\2\2\u0375\u0376\7\64\2\2\u0376\u0377\7\62\2\2\u0377")
buf.write("\u00fa\3\2\2\2\u0378\u0379\7\64\2\2\u0379\u037a\7\63\2")
buf.write("\2\u037a\u00fc\3\2\2\2\u037b\u037c\7\64\2\2\u037c\u037d")
buf.write("\7\64\2\2\u037d\u00fe\3\2\2\2\u037e\u037f\7\64\2\2\u037f")
buf.write("\u0380\7\65\2\2\u0380\u0100\3\2\2\2\u0381\u0382\7\64\2")
buf.write("\2\u0382\u0383\7\66\2\2\u0383\u0102\3\2\2\2\u0384\u0385")
buf.write("\7\64\2\2\u0385\u0386\7\67\2\2\u0386\u0104\3\2\2\2\u0387")
buf.write("\u0388\7\64\2\2\u0388\u0389\78\2\2\u0389\u0106\3\2\2\2")
buf.write("\u038a\u038b\7\64\2\2\u038b\u038c\79\2\2\u038c\u0108\3")
buf.write("\2\2\2\u038d\u038e\7\64\2\2\u038e\u038f\7:\2\2\u038f\u010a")
buf.write("\3\2\2\2\u0390\u0391\7\64\2\2\u0391\u0392\7;\2\2\u0392")
buf.write("\u010c\3\2\2\2\u0393\u0394\7\65\2\2\u0394\u0395\7\62\2")
buf.write("\2\u0395\u010e\3\2\2\2\u0396\u0397\7\65\2\2\u0397\u0398")
buf.write("\7\63\2\2\u0398\u0110\3\2\2\2\u0399\u039a\7\65\2\2\u039a")
buf.write("\u039b\7\64\2\2\u039b\u0112\3\2\2\2\u039c\u039d\7\65\2")
buf.write("\2\u039d\u039e\7\65\2\2\u039e\u0114\3\2\2\2\u039f\u03a0")
buf.write("\7\65\2\2\u03a0\u03a1\7\66\2\2\u03a1\u0116\3\2\2\2\u03a2")
buf.write("\u03a3\7\65\2\2\u03a3\u03a4\7\67\2\2\u03a4\u0118\3\2\2")
buf.write("\2\u03a5\u03a6\7\65\2\2\u03a6\u03a7\79\2\2\u03a7\u011a")
buf.write("\3\2\2\2\u03a8\u03a9\7\65\2\2\u03a9\u03aa\7:\2\2\u03aa")
buf.write("\u011c\3\2\2\2\u03ab\u03ac\7\65\2\2\u03ac\u03ad\7;\2\2")
buf.write("\u03ad\u011e\3\2\2\2\u03ae\u03af\7\66\2\2\u03af\u03b0")
buf.write("\7\62\2\2\u03b0\u0120\3\2\2\2\u03b1\u03b2\7\66\2\2\u03b2")
buf.write("\u03b3\7\64\2\2\u03b3\u0122\3\2\2\2\u03b4\u03b5\7\66\2")
buf.write("\2\u03b5\u03b6\7\66\2\2\u03b6\u0124\3\2\2\2\u03b7\u03b8")
buf.write("\7\66\2\2\u03b8\u03b9\7\67\2\2\u03b9\u0126\3\2\2\2\u03ba")
buf.write("\u03bb\7\66\2\2\u03bb\u03bc\78\2\2\u03bc\u0128\3\2\2\2")
buf.write("\u03bd\u03be\7\66\2\2\u03be\u03bf\79\2\2\u03bf\u012a\3")
buf.write("\2\2\2\u03c0\u03c1\7\66\2\2\u03c1\u03c2\7:\2\2\u03c2\u012c")
buf.write("\3\2\2\2\u03c3\u03c4\7\66\2\2\u03c4\u03c5\7;\2\2\u03c5")
buf.write("\u012e\3\2\2\2\u03c6\u03c7\7\67\2\2\u03c7\u03c8\7\62\2")
buf.write("\2\u03c8\u0130\3\2\2\2\u03c9\u03ca\7\67\2\2\u03ca\u03cb")
buf.write("\7\63\2\2\u03cb\u0132\3\2\2\2\u03cc\u03cd\7\67\2\2\u03cd")
buf.write("\u03ce\7\67\2\2\u03ce\u0134\3\2\2\2\u03cf\u03d0\7\67\2")
buf.write("\2\u03d0\u03d1\7:\2\2\u03d1\u0136\3\2\2\2\u03d2\u03d3")
buf.write("\7\67\2\2\u03d3\u03d4\7;\2\2\u03d4\u0138\3\2\2\2\u03d5")
buf.write("\u03d6\78\2\2\u03d6\u03d7\7\62\2\2\u03d7\u013a\3\2\2\2")
buf.write("\u03d8\u03d9\78\2\2\u03d9\u03da\7\63\2\2\u03da\u013c\3")
buf.write("\2\2\2\u03db\u03dc\78\2\2\u03dc\u03dd\7\64\2\2\u03dd\u013e")
buf.write("\3\2\2\2\u03de\u03df\78\2\2\u03df\u03e0\7\65\2\2\u03e0")
buf.write("\u0140\3\2\2\2\u03e1\u03e2\78\2\2\u03e2\u03e3\7\66\2\2")
buf.write("\u03e3\u0142\3\2\2\2\u03e4\u03e5\78\2\2\u03e5\u03e6\7")
buf.write("\67\2\2\u03e6\u0144\3\2\2\2\u03e7\u03e8\78\2\2\u03e8\u03e9")
buf.write("\78\2\2\u03e9\u0146\3\2\2\2\u03ea\u03eb\78\2\2\u03eb\u03ec")
buf.write("\7:\2\2\u03ec\u0148\3\2\2\2\u03ed\u03ee\78\2\2\u03ee\u03ef")
buf.write("\7;\2\2\u03ef\u014a\3\2\2\2\u03f0\u03f1\79\2\2\u03f1\u03f2")
buf.write("\7\62\2\2\u03f2\u014c\3\2\2\2\u03f3\u03f4\79\2\2\u03f4")
buf.write("\u03f5\7\63\2\2\u03f5\u014e\3\2\2\2\u03f6\u03f7\79\2\2")
buf.write("\u03f7\u03f8\7\64\2\2\u03f8\u0150\3\2\2\2\u03f9\u03fa")
buf.write("\79\2\2\u03fa\u03fb\7\65\2\2\u03fb\u0152\3\2\2\2\u03fc")
buf.write("\u03fd\79\2\2\u03fd\u03fe\7\66\2\2\u03fe\u0154\3\2\2\2")
buf.write("\u03ff\u0400\79\2\2\u0400\u0401\7\67\2\2\u0401\u0156\3")
buf.write("\2\2\2\u0402\u0403\79\2\2\u0403\u0404\78\2\2\u0404\u0158")
buf.write("\3\2\2\2\u0405\u0406\7;\2\2\u0406\u0407\7:\2\2\u0407\u015a")
buf.write("\3\2\2\2\u0408\u0409\7;\2\2\u0409\u040a\7;\2\2\u040a\u015c")
buf.write("\3\2\2\2\u040b\u040c\7\63\2\2\u040c\u040d\7\62\2\2\u040d")
buf.write("\u040e\7\62\2\2\u040e\u015e\3\2\2\2\u040f\u0410\7\63\2")
buf.write("\2\u0410\u0411\7\65\2\2\u0411\u0412\7\66\2\2\u0412\u0160")
buf.write("\3\2\2\2\u0413\u0414\7/\2\2\u0414\u0415\7\63\2\2\u0415")
buf.write("\u0162\3\2\2\2\u0416\u0418\t\3\2\2\u0417\u0416\3\2\2\2")
buf.write("\u0418\u0419\3\2\2\2\u0419\u0417\3\2\2\2\u0419\u041a\3")
buf.write("\2\2\2\u041a\u041b\3\2\2\2\u041b\u041c\b\u00b2\2\2\u041c")
buf.write("\u0164\3\2\2\2\u041d\u041e\7\61\2\2\u041e\u041f\7,\2\2")
buf.write("\u041f\u0423\3\2\2\2\u0420\u0422\13\2\2\2\u0421\u0420")
buf.write("\3\2\2\2\u0422\u0425\3\2\2\2\u0423\u0424\3\2\2\2\u0423")
buf.write("\u0421\3\2\2\2\u0424\u0426\3\2\2\2\u0425\u0423\3\2\2\2")
buf.write("\u0426\u0427\7,\2\2\u0427\u0428\7\61\2\2\u0428\u0429\3")
buf.write("\2\2\2\u0429\u042a\b\u00b3\2\2\u042a\u0166\3\2\2\2\u042b")
buf.write("\u042c\7\61\2\2\u042c\u042d\7\61\2\2\u042d\u0431\3\2\2")
buf.write("\2\u042e\u0430\n\4\2\2\u042f\u042e\3\2\2\2\u0430\u0433")
buf.write("\3\2\2\2\u0431\u042f\3\2\2\2\u0431\u0432\3\2\2\2\u0432")
buf.write("\u0434\3\2\2\2\u0433\u0431\3\2\2\2\u0434\u0435\b\u00b4")
buf.write("\2\2\u0435\u0168\3\2\2\2\u0436\u0443\5\u00a7T\2\u0437")
buf.write("\u0443\5\u00a9U\2\u0438\u0443\5\u00abV\2\u0439\u0443\5")
buf.write("\u00adW\2\u043a\u0443\5\u00afX\2\u043b\u0443\5\u00b1Y")
buf.write("\2\u043c\u0443\5\u00b3Z\2\u043d\u0443\5\u00b5[\2\u043e")
buf.write("\u0443\5\u00b7\\\2\u043f\u0443\5\u00b9]\2\u0440\u0443")
buf.write("\5\u00bb^\2\u0441\u0443\5\u00bd_\2\u0442\u0436\3\2\2\2")
buf.write("\u0442\u0437\3\2\2\2\u0442\u0438\3\2\2\2\u0442\u0439\3")
buf.write("\2\2\2\u0442\u043a\3\2\2\2\u0442\u043b\3\2\2\2\u0442\u043c")
buf.write("\3\2\2\2\u0442\u043d\3\2\2\2\u0442\u043e\3\2\2\2\u0442")
buf.write("\u043f\3\2\2\2\u0442\u0440\3\2\2\2\u0442\u0441\3\2\2\2")
buf.write("\u0443\u016a\3\2\2\2\u0444\u044b\5\u00bf`\2\u0445\u044b")
buf.write("\5\u00c1a\2\u0446\u044b\5\u00c3b\2\u0447\u044b\5\u00c5")
buf.write("c\2\u0448\u044b\5\u00c9e\2\u0449\u044b\5\u00cbf\2\u044a")
buf.write("\u0444\3\2\2\2\u044a\u0445\3\2\2\2\u044a\u0446\3\2\2\2")
buf.write("\u044a\u0447\3\2\2\2\u044a\u0448\3\2\2\2\u044a\u0449\3")
buf.write("\2\2\2\u044b\u016c\3\2\2\2\u044c\u0450\5\u00cfh\2\u044d")
buf.write("\u0450\5\u00cdg\2\u044e\u0450\5\u00d1i\2\u044f\u044c\3")
buf.write("\2\2\2\u044f\u044d\3\2\2\2\u044f\u044e\3\2\2\2\u0450\u016e")
buf.write("\3\2\2\2\u0451\u0459\t\5\2\2\u0452\u0454\t\6\2\2\u0453")
buf.write("\u0452\3\2\2\2\u0454\u0457\3\2\2\2\u0455\u0453\3\2\2\2")
buf.write("\u0455\u0456\3\2\2\2\u0456\u0458\3\2\2\2\u0457\u0455\3")
buf.write("\2\2\2\u0458\u045a\t\5\2\2\u0459\u0455\3\2\2\2\u0459\u045a")
buf.write("\3\2\2\2\u045a\u0170\3\2\2\2\u045b\u045e\5\u0173\u00ba")
buf.write("\2\u045c\u045e\t\5\2\2\u045d\u045b\3\2\2\2\u045d\u045c")
buf.write("\3\2\2\2\u045e\u0172\3\2\2\2\u045f\u0464\t\7\2\2\u0460")
buf.write("\u0464\n\b\2\2\u0461\u0462\t\t\2\2\u0462\u0464\t\n\2\2")
buf.write("\u0463\u045f\3\2\2\2\u0463\u0460\3\2\2\2\u0463\u0461\3")
buf.write("\2\2\2\u0464\u0174\3\2\2\2\u0465\u0466\7^\2\2\u0466\u0470")
buf.write("\t\13\2\2\u0467\u046c\7^\2\2\u0468\u046a\t\f\2\2\u0469")
buf.write("\u0468\3\2\2\2\u0469\u046a\3\2\2\2\u046a\u046b\3\2\2\2")
buf.write("\u046b\u046d\t\r\2\2\u046c\u0469\3\2\2\2\u046c\u046d\3")
buf.write("\2\2\2\u046d\u046e\3\2\2\2\u046e\u0470\t\r\2\2\u046f\u0465")
buf.write("\3\2\2\2\u046f\u0467\3\2\2\2\u0470\u0176\3\2\2\2\u0471")
buf.write("\u0473\t\16\2\2\u0472\u0471\3\2\2\2\u0473\u0474\3\2\2")
buf.write("\2\u0474\u0472\3\2\2\2\u0474\u0475\3\2\2\2\u0475\u0178")
buf.write("\3\2\2\2\u0476\u0478\7\17\2\2\u0477\u0476\3\2\2\2\u0477")
buf.write("\u0478\3\2\2\2\u0478\u0479\3\2\2\2\u0479\u047c\7\f\2\2")
buf.write("\u047a\u047c\4\16\17\2\u047b\u0477\3\2\2\2\u047b\u047a")
buf.write("\3\2\2\2\u047c\u017a\3\2\2\2\35\2\u0286\u028c\u028e\u029c")
buf.write("\u02a1\u02a5\u02ab\u02b0\u02b6\u02bc\u0419\u0423\u0431")
buf.write("\u0442\u044a\u044f\u0455\u0459\u045d\u0463\u0469\u046c")
buf.write("\u046f\u0474\u0477\u047b\3\2\3\2")
return buf.getvalue()
class BSLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
IF = 1
ELSE = 2
REPEAT = 3
WHILE = 4
FUNCTION = 5
RETURN = 6
MANIFEST = 7
MODULE = 8
STATIONARY = 9
FUNCTIONS = 10
INSTRUCTIONS = 11
DETECT = 12
MIX = 13
SPLIT = 14
HEAT = 15
DRAIN = 16
DISPENSE = 17
DISPOSE = 18
GRADIENT = 19
STORE = 20
RANGE = 21
AT = 22
WITH = 23
FOR = 24
INTO = 25
TIMES = 26
ON = 27
OF = 28
UNITS = 29
USEIN = 30
SLE = 31
SEQ = 32
SGE = 33
FLE = 34
FEQ = 35
FGE = 36
NAT = 37
REAL = 38
MAT = 39
BOOL = 40
IDENTIFIER = 41
STRING_LITERAL = 42
BOOL_LITERAL = 43
FLOAT_LITERAL = 44
INTEGER_LITERAL = 45
TIME_NUMBER = 46
VOLUME_NUMBER = 47
TEMP_NUMBER = 48
LPAREN = 49
RPAREN = 50
LBRACE = 51
RBRACE = 52
LBRACKET = 53
RBRACKET = 54
SEMICOLON = 55
COMMA = 56
DOT = 57
ASSIGN = 58
GT = 59
LT = 60
BANG = 61
TILDE = 62
QUESTION = 63
COLON = 64
EQUALITY = 65
LTE = 66
GTE = 67
NOTEQUAL = 68
AND = 69
OR = 70
INC = 71
DEC = 72
ADDITION = 73
SUBTRACT = 74
MULTIPLY = 75
DIVIDE = 76
BITAND = 77
BITOR = 78
CARET = 79
MOD = 80
UNDERSCORE = 81
ATSIGN = 82
NANOSECOND = 83
MICROSECOND = 84
MILLISECOND = 85
CENTISECOND = 86
DECISECOND = 87
SECOND = 88
MINUTE = 89
HOUR = 90
DAY = 91
WEEK = 92
MONTH = 93
YEAR = 94
NANOLITRE = 95
MICROLITRE = 96
MILLILITRE = 97
CENTILITRE = 98
DECILITRE = 99
LITRE = 100
DECALITRE = 101
CELSIUS = 102
FAHRENHEIT = 103
KELVIN = 104
ACIDS_STRONG_NON_OXIDIZING = 105
ACIDS_STRONG_OXIDIZING = 106
ACIDS_CARBOXYLIC = 107
ALCOHOLS_AND_POLYOLS = 108
ALDEHYDES = 109
AMIDES_AND_IMIDES = 110
AMINES_PHOSPHINES_AND_PYRIDINES = 111
AZO_DIAZO_AZIDO_HYDRAZINE_AND_AZIDE_COMPOUNDS = 112
CARBAMATES = 113
BASES_STRONG = 114
CYANIDES_INORGANIC = 115
THIOCARBAMATE_ESTERS_AND_SALTS_DITHIOCARBAMATE_ESTERS_AND_SALTS = 116
ESTERS_SULFATE_ESTERS_PHOSPHATE_ESTERS_THIOPHOSPHATE_ESTERS_AND_BORATE_ESTERS = 117
ETHERS = 118
FLUORIDES_INORGANIC = 119
HYDROCARBONS_AROMATIC = 120
HALOGENATED_ORGANIC_COMPOUNDS = 121
ISOCYANATES_AND_ISOTHIOCYANATES = 122
KETONES = 123
SULFIDES_ORGANIC = 124
METALS_ALKALI_VERY_ACTIVE = 125
METALS_ELEMENTAL_AND_POWDER_ACTIVE = 126
METALS_LESS_REACTIVE = 127
METALS_AND_METAL_COMPOUNDS_TOXIC = 128
DIAZONIUM_SALTS = 129
NITRILES = 130
NITRO_NITROSO_NITRATE_AND_NITRITE_COMPOUNDS_ORGANIC = 131
HYDROCARBONS_ALIPHATIC_UNSATURATED = 132
HYDROCARBONS_ALIPHATIC_SATURATED = 133
PEROXIDES_ORGANIC = 134
PHENOLS_AND_CRESOLS = 135
SULFONATES_PHOSPHONATES_AND_THIOPHOSPHONATES_ORGANIC = 136
SULFIDES_INORGANIC = 137
EPOXIDES = 138
METAL_HYDRIDES_METAL_ALKYLS_METAL_ARYLS_AND_SILANES = 139
ANHYDRIDES = 140
SALTS_ACIDIC = 141
SALTS_BASIC = 142
ACYL_HALIDES_SULFONYL_HALIDES_AND_CHLOROFORMATES = 143
ORGANOMETALLICS = 144
OXIDIZING_AGENTS_STRONG = 145
REDUCING_AGENTS_STRONG = 146
NON_REDOX_ACTIVE_INORGANIC_COMPOUNDS = 147
FLUORINATED_ORGANIC_COMPOUNDS = 148
FLUORIDE_SALTS_SOLUBLE = 149
OXIDIZING_AGENTS_WEAK = 150
REDUCING_AGENTS_WEAK = 151
NITRIDES_PHOSPHIDES_CARBIDES_AND_SILICIDES = 152
CHLOROSILANES = 153
SILOXANES = 154
HALOGENATING_AGENTS = 155
ACIDS_WEAK = 156
BASES_WEAK = 157
CARBONATE_SALTS = 158
ALKYNES_WITH_ACETYLENIC_HYDROGEN = 159
ALKYNES_WITH_NO_ACETYLENIC_HYDROGEN = 160
CONJUGATED_DIENES = 161
ARYL_HALIDES = 162
AMINES_AROMATIC = 163
NITRATE_AND_NITRITE_COMPOUNDS_INORGANIC = 164
ACETALS_KETALS_HEMIACETALS_AND_HEMIKETALS = 165
ACRYLATES_AND_ACRYLIC_ACIDS = 166
PHENOLIC_SALTS = 167
QUATERNARY_AMMONIUM_AND_PHOSPHONIUM_SALTS = 168
SULFITE_AND_THIOSULFATE_SALTS = 169
OXIMES = 170
POLYMERIZABLE_COMPOUNDS = 171
NOT_CHEMICALLY_REACTIVE = 172
INSUFFICIENT_INFORMATION_FOR_CLASSIFICATION = 173
WATER_AND_AQUEOUS_SOLUTIONS = 174
NULL = 175
UNKNOWN = 176
WS = 177
COMMENT = 178
LINE_COMMENT = 179
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ "DEFAULT_MODE" ]
literalNames = [ "<INVALID>",
"'if'", "'else'", "'repeat'", "'while'", "'function'", "'return'",
"'manifest'", "'module'", "'stationary'", "'functions'", "'instructions'",
"'detect'", "'mix'", "'split'", "'heat'", "'drain'", "'dispense'",
"'dispose'", "'gradient'", "'store'", "'range'", "'at'", "'with'",
"'for'", "'into'", "'times'", "'on'", "'of'", "'units'", "'usein'",
"'start <='", "'start'", "'start >='", "'finish <='", "'finish'",
"'finish >='", "'nat'", "'real'", "'mat'", "'bool'", "'('",
"')'", "'{'", "'}'", "'['", "']'", "';'", "','", "'.'", "'='",
"'>'", "'<'", "'!'", "'~'", "'?'", "':'", "'=='", "'<='", "'>='",
"'!='", "'&&'", "'||'", "'++'", "'--'", "'+'", "'-'", "'*'",
"'/'", "'&'", "'|'", "'^'", "'%'", "'_'", "'@'", "'ns'", "'us'",
"'ms'", "'cs'", "'ds'", "'s'", "'m'", "'h'", "'d'", "'w'", "'mo'",
"'y'", "'nL'", "'uL'", "'mL'", "'cL'", "'dL'", "'L'", "'daL'",
"'c'", "'f'", "'k'", "'1'", "'2'", "'3'", "'4'", "'5'", "'6'",
"'7'", "'8'", "'9'", "'10'", "'11'", "'12'", "'13'", "'14'",
"'15'", "'16'", "'17'", "'18'", "'19'", "'20'", "'21'", "'22'",
"'23'", "'24'", "'25'", "'26'", "'27'", "'28'", "'29'", "'30'",
"'31'", "'32'", "'33'", "'34'", "'35'", "'37'", "'38'", "'39'",
"'40'", "'42'", "'44'", "'45'", "'46'", "'47'", "'48'", "'49'",
"'50'", "'51'", "'55'", "'58'", "'59'", "'60'", "'61'", "'62'",
"'63'", "'64'", "'65'", "'66'", "'68'", "'69'", "'70'", "'71'",
"'72'", "'73'", "'74'", "'75'", "'76'", "'98'", "'99'", "'100'",
"'134'", "'-1'" ]
symbolicNames = [ "<INVALID>",
"IF", "ELSE", "REPEAT", "WHILE", "FUNCTION", "RETURN", "MANIFEST",
"MODULE", "STATIONARY", "FUNCTIONS", "INSTRUCTIONS", "DETECT",
"MIX", "SPLIT", "HEAT", "DRAIN", "DISPENSE", "DISPOSE", "GRADIENT",
"STORE", "RANGE", "AT", "WITH", "FOR", "INTO", "TIMES", "ON",
"OF", "UNITS", "USEIN", "SLE", "SEQ", "SGE", "FLE", "FEQ", "FGE",
"NAT", "REAL", "MAT", "BOOL", "IDENTIFIER", "STRING_LITERAL",
"BOOL_LITERAL", "FLOAT_LITERAL", "INTEGER_LITERAL", "TIME_NUMBER",
"VOLUME_NUMBER", "TEMP_NUMBER", "LPAREN", "RPAREN", "LBRACE",
"RBRACE", "LBRACKET", "RBRACKET", "SEMICOLON", "COMMA", "DOT",
"ASSIGN", "GT", "LT", "BANG", "TILDE", "QUESTION", "COLON",
"EQUALITY", "LTE", "GTE", "NOTEQUAL", "AND", "OR", "INC", "DEC",
"ADDITION", "SUBTRACT", "MULTIPLY", "DIVIDE", "BITAND", "BITOR",
"CARET", "MOD", "UNDERSCORE", "ATSIGN", "NANOSECOND", "MICROSECOND",
"MILLISECOND", "CENTISECOND", "DECISECOND", "SECOND", "MINUTE",
"HOUR", "DAY", "WEEK", "MONTH", "YEAR", "NANOLITRE", "MICROLITRE",
"MILLILITRE", "CENTILITRE", "DECILITRE", "LITRE", "DECALITRE",
"CELSIUS", "FAHRENHEIT", "KELVIN", "ACIDS_STRONG_NON_OXIDIZING",
"ACIDS_STRONG_OXIDIZING", "ACIDS_CARBOXYLIC", "ALCOHOLS_AND_POLYOLS",
"ALDEHYDES", "AMIDES_AND_IMIDES", "AMINES_PHOSPHINES_AND_PYRIDINES",
"AZO_DIAZO_AZIDO_HYDRAZINE_AND_AZIDE_COMPOUNDS", "CARBAMATES",
"BASES_STRONG", "CYANIDES_INORGANIC", "THIOCARBAMATE_ESTERS_AND_SALTS_DITHIOCARBAMATE_ESTERS_AND_SALTS",
"ESTERS_SULFATE_ESTERS_PHOSPHATE_ESTERS_THIOPHOSPHATE_ESTERS_AND_BORATE_ESTERS",
"ETHERS", "FLUORIDES_INORGANIC", "HYDROCARBONS_AROMATIC", "HALOGENATED_ORGANIC_COMPOUNDS",
"ISOCYANATES_AND_ISOTHIOCYANATES", "KETONES", "SULFIDES_ORGANIC",
"METALS_ALKALI_VERY_ACTIVE", "METALS_ELEMENTAL_AND_POWDER_ACTIVE",
"METALS_LESS_REACTIVE", "METALS_AND_METAL_COMPOUNDS_TOXIC",
"DIAZONIUM_SALTS", "NITRILES", "NITRO_NITROSO_NITRATE_AND_NITRITE_COMPOUNDS_ORGANIC",
"HYDROCARBONS_ALIPHATIC_UNSATURATED", "HYDROCARBONS_ALIPHATIC_SATURATED",
"PEROXIDES_ORGANIC", "PHENOLS_AND_CRESOLS", "SULFONATES_PHOSPHONATES_AND_THIOPHOSPHONATES_ORGANIC",
"SULFIDES_INORGANIC", "EPOXIDES", "METAL_HYDRIDES_METAL_ALKYLS_METAL_ARYLS_AND_SILANES",
"ANHYDRIDES", "SALTS_ACIDIC", "SALTS_BASIC", "ACYL_HALIDES_SULFONYL_HALIDES_AND_CHLOROFORMATES",
"ORGANOMETALLICS", "OXIDIZING_AGENTS_STRONG", "REDUCING_AGENTS_STRONG",
"NON_REDOX_ACTIVE_INORGANIC_COMPOUNDS", "FLUORINATED_ORGANIC_COMPOUNDS",
"FLUORIDE_SALTS_SOLUBLE", "OXIDIZING_AGENTS_WEAK", "REDUCING_AGENTS_WEAK",
"NITRIDES_PHOSPHIDES_CARBIDES_AND_SILICIDES", "CHLOROSILANES",
"SILOXANES", "HALOGENATING_AGENTS", "ACIDS_WEAK", "BASES_WEAK",
"CARBONATE_SALTS", "ALKYNES_WITH_ACETYLENIC_HYDROGEN", "ALKYNES_WITH_NO_ACETYLENIC_HYDROGEN",
"CONJUGATED_DIENES", "ARYL_HALIDES", "AMINES_AROMATIC", "NITRATE_AND_NITRITE_COMPOUNDS_INORGANIC",
"ACETALS_KETALS_HEMIACETALS_AND_HEMIKETALS", "ACRYLATES_AND_ACRYLIC_ACIDS",
"PHENOLIC_SALTS", "QUATERNARY_AMMONIUM_AND_PHOSPHONIUM_SALTS",
"SULFITE_AND_THIOSULFATE_SALTS", "OXIMES", "POLYMERIZABLE_COMPOUNDS",
"NOT_CHEMICALLY_REACTIVE", "INSUFFICIENT_INFORMATION_FOR_CLASSIFICATION",
"WATER_AND_AQUEOUS_SOLUTIONS", "NULL", "UNKNOWN", "WS", "COMMENT",
"LINE_COMMENT" ]
ruleNames = [ "IF", "ELSE", "REPEAT", "WHILE", "FUNCTION", "RETURN",
"MANIFEST", "MODULE", "STATIONARY", "FUNCTIONS", "INSTRUCTIONS",
"DETECT", "MIX", "SPLIT", "HEAT", "DRAIN", "DISPENSE",
"DISPOSE", "GRADIENT", "STORE", "RANGE", "AT", "WITH",
"FOR", "INTO", "TIMES", "ON", "OF", "UNITS", "USEIN",
"SLE", "SEQ", "SGE", "FLE", "FEQ", "FGE", "NAT", "REAL",
"MAT", "BOOL", "IDENTIFIER", "STRING_LITERAL", "BOOL_LITERAL",
"FLOAT_LITERAL", "INTEGER_LITERAL", "TIME_NUMBER", "VOLUME_NUMBER",
"TEMP_NUMBER", "LPAREN", "RPAREN", "LBRACE", "RBRACE",
"LBRACKET", "RBRACKET", "SEMICOLON", "COMMA", "DOT", "ASSIGN",
"GT", "LT", "BANG", "TILDE", "QUESTION", "COLON", "EQUALITY",
"LTE", "GTE", "NOTEQUAL", "AND", "OR", "INC", "DEC", "ADDITION",
"SUBTRACT", "MULTIPLY", "DIVIDE", "BITAND", "BITOR", "CARET",
"MOD", "UNDERSCORE", "ATSIGN", "NANOSECOND", "MICROSECOND",
"MILLISECOND", "CENTISECOND", "DECISECOND", "SECOND",
"MINUTE", "HOUR", "DAY", "WEEK", "MONTH", "YEAR", "NANOLITRE",
"MICROLITRE", "MILLILITRE", "CENTILITRE", "DECILITRE",
"LITRE", "DECALITRE", "CELSIUS", "FAHRENHEIT", "KELVIN",
"ACIDS_STRONG_NON_OXIDIZING", "ACIDS_STRONG_OXIDIZING",
"ACIDS_CARBOXYLIC", "ALCOHOLS_AND_POLYOLS", "ALDEHYDES",
"AMIDES_AND_IMIDES", "AMINES_PHOSPHINES_AND_PYRIDINES",
"AZO_DIAZO_AZIDO_HYDRAZINE_AND_AZIDE_COMPOUNDS", "CARBAMATES",
"BASES_STRONG", "CYANIDES_INORGANIC", "THIOCARBAMATE_ESTERS_AND_SALTS_DITHIOCARBAMATE_ESTERS_AND_SALTS",
"ESTERS_SULFATE_ESTERS_PHOSPHATE_ESTERS_THIOPHOSPHATE_ESTERS_AND_BORATE_ESTERS",
"ETHERS", "FLUORIDES_INORGANIC", "HYDROCARBONS_AROMATIC",
"HALOGENATED_ORGANIC_COMPOUNDS", "ISOCYANATES_AND_ISOTHIOCYANATES",
"KETONES", "SULFIDES_ORGANIC", "METALS_ALKALI_VERY_ACTIVE",
"METALS_ELEMENTAL_AND_POWDER_ACTIVE", "METALS_LESS_REACTIVE",
"METALS_AND_METAL_COMPOUNDS_TOXIC", "DIAZONIUM_SALTS",
"NITRILES", "NITRO_NITROSO_NITRATE_AND_NITRITE_COMPOUNDS_ORGANIC",
"HYDROCARBONS_ALIPHATIC_UNSATURATED", "HYDROCARBONS_ALIPHATIC_SATURATED",
"PEROXIDES_ORGANIC", "PHENOLS_AND_CRESOLS", "SULFONATES_PHOSPHONATES_AND_THIOPHOSPHONATES_ORGANIC",
"SULFIDES_INORGANIC", "EPOXIDES", "METAL_HYDRIDES_METAL_ALKYLS_METAL_ARYLS_AND_SILANES",
"ANHYDRIDES", "SALTS_ACIDIC", "SALTS_BASIC", "ACYL_HALIDES_SULFONYL_HALIDES_AND_CHLOROFORMATES",
"ORGANOMETALLICS", "OXIDIZING_AGENTS_STRONG", "REDUCING_AGENTS_STRONG",
"NON_REDOX_ACTIVE_INORGANIC_COMPOUNDS", "FLUORINATED_ORGANIC_COMPOUNDS",
"FLUORIDE_SALTS_SOLUBLE", "OXIDIZING_AGENTS_WEAK", "REDUCING_AGENTS_WEAK",
"NITRIDES_PHOSPHIDES_CARBIDES_AND_SILICIDES", "CHLOROSILANES",
"SILOXANES", "HALOGENATING_AGENTS", "ACIDS_WEAK", "BASES_WEAK",
"CARBONATE_SALTS", "ALKYNES_WITH_ACETYLENIC_HYDROGEN",
"ALKYNES_WITH_NO_ACETYLENIC_HYDROGEN", "CONJUGATED_DIENES",
"ARYL_HALIDES", "AMINES_AROMATIC", "NITRATE_AND_NITRITE_COMPOUNDS_INORGANIC",
"ACETALS_KETALS_HEMIACETALS_AND_HEMIKETALS", "ACRYLATES_AND_ACRYLIC_ACIDS",
"PHENOLIC_SALTS", "QUATERNARY_AMMONIUM_AND_PHOSPHONIUM_SALTS",
"SULFITE_AND_THIOSULFATE_SALTS", "OXIMES", "POLYMERIZABLE_COMPOUNDS",
"NOT_CHEMICALLY_REACTIVE", "INSUFFICIENT_INFORMATION_FOR_CLASSIFICATION",
"WATER_AND_AQUEOUS_SOLUTIONS", "NULL", "UNKNOWN", "WS",
"COMMENT", "LINE_COMMENT", "TimeUnits", "VolumeUnits",
"TempUnits", "Digits", "LetterOrDigit", "Letter", "EscapeSequence",
"SPACES", "NEWLINE" ]
grammarFileName = "BSLexer.g4"
def __init__(self, input=None, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.8")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
|
from base_client import BaseClient, IntegrityError
from crypto import CryptoError
import util
from math import log, ceil
from collections import deque
BLOCKSIZE = 256 #512 #1024
def getNumBlocks(value):
length = len(value)
numblocks = length // BLOCKSIZE
if numblocks * BLOCKSIZE < length:
numblocks += 1
return numblocks
# get binary blocks
def binaryBlocks(numblocks, value):
binaryblock = 2 ** ceil(log(numblocks, 2))
blocksize = ceil(len(value) / binaryblock)
return binaryblock, blocksize
def path_join(*strings):
return '/'.join(strings)
class Client(BaseClient):
def __init__(self, storage_server, public_key_server, crypto_object,
username):
super().__init__(storage_server, public_key_server, crypto_object,
username)
self.dirkey = None
self.directory = {}
def generate_keys(self):
# symmetric encrypt key
sym_ke = self.crypto.get_random_bytes(16)
# MAC key
sym_ka = self.crypto.get_random_bytes(16)
# sym name encrypt key
sym_kn = self.crypto.get_random_bytes(16)
keys = (sym_ke, sym_ka, sym_kn)
return keys
def dir_keys(self):
# sym encrypt key
sym_ke = self.crypto.get_random_bytes(16)
# sym mac key
sym_ka = self.crypto.get_random_bytes(16)
return (sym_ke, sym_ka)
def get_directory_keys(self):
dir_ID = path_join("information", self.username)
resp = self.storage_server.get(dir_ID)
if resp is None:
keys = self.dir_keys()
key_info = self.safe_encrypt(keys)
self.storage_server.put(dir_ID, util.to_json_string(key_info))
else:
keys = self.safe_decrypt(resp)
return keys
def encrypt_filepath(self, file_id, session_key, newkeys, name):
sym_ke, sym_ka = session_key
sym_Ke, sym_Ka, sym_Kn = newkeys
F = self.crypto.message_authentication_code(name, sym_Kn, "SHA256")
path = path_join(self.username, F)
file_info = {"keys": newkeys, "path": path}
self.encrypt_directory(file_id, file_info, sym_ke, sym_ka)
def safe_encrypt(self, keys):
pub_key = self.private_key.publickey()
key_str = util.to_json_string(keys)
encrypted_keys = self.crypto.asymmetric_encrypt(key_str, pub_key)
signed_keys = self.crypto.asymmetric_sign(encrypted_keys, self.private_key)
return {"encrypted_keys": encrypted_keys, "signed_keys": signed_keys}
def safe_decrypt(self, resp):
pub_key = self.private_key.publickey()
try:
key_info = util.from_json_string(resp)
encrypted_keys = key_info["encrypted_keys"]
signed_keys = key_info["signed_keys"]
except:
raise IntegrityError()
if not self.crypto.asymmetric_verify(encrypted_keys, signed_keys, pub_key):
raise IntegrityError()
decrypted_keys = self.crypto.asymmetric_decrypt(encrypted_keys, self.private_key)
return util.from_json_string(decrypted_keys)
def encrypt_directory(self, client_ID, directory, sym_ke, sym_ka):
directory = util.to_json_string(directory)
IV = self.crypto.get_random_bytes(16)
encrypted_dir = self.crypto.symmetric_encrypt(directory, sym_ke, 'AES', 'CBC', IV)
signed_dir = self.crypto.message_authentication_code(encrypted_dir, sym_ka, 'SHA256')
directory_info = {"IV": IV, "encrypted_keys": encrypted_dir, "signed_keys": signed_dir}
self.storage_server.put(client_ID, util.to_json_string(directory_info))
def decrypt_directory(self, resp, sym_ke, sym_ka):
try:
directory_info = util.from_json_string(resp)
IV = directory_info['IV']
encrypted_keys = directory_info["encrypted_keys"]
signed_keys = directory_info["signed_keys"]
except:
raise IntegrityError()
signed_dir = self.crypto.message_authentication_code(encrypted_keys, sym_ka, 'SHA256')
if signed_dir != signed_keys:
raise IntegrityError()
directory = self.crypto.symmetric_decrypt(encrypted_keys, sym_ke, 'AES', 'CBC', IV)
directory = util.from_json_string(directory)
return directory
def getRoot(self, ID, sym_ka):
meta = self.storage_server.get(path_join(ID, str(0)))
if meta is None:
return None
try:
meta = util.from_json_string(meta)
numblocks = meta['numblocks']
mac = meta['mac']
meta_mac = self.crypto.message_authentication_code(str(numblocks), sym_ka, 'SHA') #SHA
if meta_mac != mac:
raise IntegrityError()
except:
raise IntegrityError()
return numblocks
def metaInRoot(self, ID, numblocks, sym_ka):
mac = self.crypto.message_authentication_code(str(numblocks), sym_ka, 'SHA') #SHA
meta_info = {"numblocks": numblocks, "mac": mac}
self.storage_server.put(path_join(ID, str(0)), util.to_json_string(meta_info))
# ENCRYPT THE DATA NODE
def hashData(self, ID, message, sym_ke, sym_ka):
IV = self.crypto.get_random_bytes(16)
encrypted_message = self.crypto.symmetric_encrypt(message, sym_ke, 'AES', 'CBC', IV)
mac = self.crypto.message_authentication_code(encrypted_message + ID, sym_ka, 'SHA256')
message_info = {"IV": IV, "encrypted": encrypted_message, "mac": mac}
self.storage_server.put(ID, util.to_json_string(message_info))
# stores only the data blocks as leaves as well as corresponding hashes
def hashDataBlocks(self, ID, numblocks, blocksize, value, sym_ke, sym_ka):
d = {}
start_index = 2**ceil(log(numblocks, 2)) # 1024
self.metaInRoot(ID, numblocks, sym_ka)
for i in range(numblocks):
# store data
message = value[i*blocksize : (i+1) * blocksize]
path = path_join(ID, 'data', str(i))
self.hashData(path, message, sym_ke, sym_ka)
# hash leaves
cipher = self.crypto.cryptographic_hash(message, 'SHA') #SHA
path = path_join(ID, str(i+start_index))
mac = self.crypto.message_authentication_code(cipher, sym_ka, 'SHA') #SHA
cipher_info = {"hash": cipher, "mac":mac}
self.storage_server.put(path, util.to_json_string(cipher_info))
d[i+start_index] = cipher
return d
# stores the internal nodes of merkel tree as hashes
def hashTree(self, ID, d, sym_ke, sym_ka):
tree = {}
if len(d.keys()) == 1:
return d
for i in d.keys():
if i % 2 == 0:
# even binary tree
if i+1 in d:
cipher = self.crypto.cryptographic_hash(d[i] + d[i+1], 'SHA') #SHA
# odd binary tree
else:
cipher = self.crypto.cryptographic_hash(d[i], 'SHA') #SHA
path = path_join(ID, str(i//2))
mac = self.crypto.message_authentication_code(cipher, sym_ka, 'SHA') #SHA
cipher_info = {"hash": cipher, "mac": mac}
self.storage_server.put(path, util.to_json_string(cipher_info))
tree[i//2] = cipher
return self.hashTree(ID, tree, sym_ke, sym_ka)
# called by localTree
def bunch(self, total, hh):
level = {}
if len(hh.keys()) == 1:
return total
for i in hh.keys():
if i % 2 == 0:
if i+1 in hh:
cipher = self.crypto.cryptographic_hash(hh[i] + hh[i+1], 'SHA') #SHA
else:
cipher = self.crypto.cryptographic_hash(hh[i], 'SHA') #SHA
level[i//2] = cipher
total[i//2] = cipher
return self.bunch(total, level)
# get local tree hashes
def getlocalTree(self, numblocks, blocksize, value):
val = {}
hh = {}
start_index = 2**ceil(log(numblocks, 2))
for i in range(numblocks):
# message
message = value[i*blocksize : (i+1) * blocksize]
val[i] = message
# cipher
cipher = self.crypto.cryptographic_hash(message, 'SHA') #SHA
hh[i+start_index] = cipher
bunch = self.bunch(hh.copy(), hh)
return val, bunch, start_index
# retrieves stored hash
def checkTreeNode(self, path, sym_Ka):
resp = self.storage_server.get(path)
if resp is None:
return None
try:
resp = util.from_json_string(resp)
except:
raise IntegrityError()
stored_hash = resp['hash']
mac = resp['mac']
newmac = self.crypto.message_authentication_code(stored_hash, sym_Ka, 'SHA') #SHA
if mac != newmac:
raise IntegrityError()
return stored_hash
def upload(self, name, value):
newFile = False
ID = ""
# cache
if self.dirkey is None:
directory_keys = self.get_directory_keys()
sym_ke, sym_ka = directory_keys
self.dirkey = directory_keys
else:
sym_ke, sym_ka = self.dirkey
# cache
if name in self.directory:
if len(self.directory[name]["file_id"]) == 32:
#owner
keys = self.directory[name]["keys"][0]
else:
#sharee
session_key = self.directory[name]["keys"]
file_id = self.directory[name]["file_id"]
sym_fe, sym_fa = session_key
shared_file = self.storage_server.get(file_id)
if shared_file is None:
return None
shared_info = self.decrypt_directory(shared_file, sym_fe, sym_fa)
keys = shared_info["keys"]
ID = shared_info["path"]
# actual
else:
# CLIENT DIRECTORY
client_ID = path_join(self.username, "directory")
resp = self.storage_server.get(client_ID)
if resp is None:
newFile = True
keys = self.generate_keys()
session_key = self.dir_keys()
directory = {name: {"keys": (keys, session_key), "shared": [], "file_id": self.crypto.get_random_bytes(16)}}
self.encrypt_directory(client_ID, directory, sym_ke, sym_ka)
# can cache directory here
self.directory[name] = {"keys": (keys, session_key), "shared": [], "file_id": self.crypto.get_random_bytes(16)}
else:
directory = self.decrypt_directory(resp, sym_ke, sym_ka)
if name in directory:
if len(directory[name]["file_id"]) == 32:
#owner
keys = directory[name]["keys"][0]
else:
#sharee
session_key = directory[name]["keys"]
file_id = directory[name]["file_id"]
sym_fe, sym_fa = session_key
shared_file = self.storage_server.get(file_id)
if shared_file is None:
return None
shared_info = self.decrypt_directory(shared_file, sym_fe, sym_fa)
keys = shared_info["keys"]
ID = shared_info["path"]
# map exists but this filename isn't. Create new file. Default = owner
else:
newFile = True
keys = self.generate_keys()
session_key = self.dir_keys()
directory[name] = {"keys": (keys, session_key), "shared": [], "file_id": self.crypto.get_random_bytes(16)}
self.encrypt_directory(client_ID, directory, sym_ke, sym_ka)
# can cache directory here
self.directory[name] = {"keys": (keys, session_key), "shared": [], "file_id": self.crypto.get_random_bytes(16)}
sym_Ke, sym_Ka, sym_Kn = keys
# If owner
if ID == "":
F = self.crypto.message_authentication_code(name, sym_Kn, 'SHA256')
ID = path_join(self.username, F)
numblocks = getNumBlocks(value)
if numblocks < 1:
print("Must have at least 1 block of data")
return None
# if numblock == 1 just store the whole damn thing. no tree
elif numblocks == 1:
self.metaInRoot(ID, numblocks, sym_Ka)
# DATA NODE
path = path_join(ID, 'data', str(0))
IV = self.crypto.get_random_bytes(16)
encrypted_file = self.crypto.symmetric_encrypt(value, sym_Ke, 'AES','CBC', IV)
mac = self.crypto.message_authentication_code(encrypted_file + path, sym_Ka, 'SHA256')
data_info = {"IV": IV, "encrypted": encrypted_file, "mac": mac}
self.storage_server.put(path, util.to_json_string(data_info))
else:
blocksize = BLOCKSIZE
if log(numblocks, 2) != int(log(numblocks, 2)):
numblocks, blocksize = binaryBlocks(numblocks, value)
# upload tree into server only if newfile or file size changes
if newFile or (self.getRoot(ID, sym_Ka) != numblocks):
datadic = self.hashDataBlocks(ID, numblocks, blocksize, value, sym_Ke, sym_Ka)
root = self.hashTree(ID, datadic, sym_Ke, sym_Ka)
else:
val, bunch, start_index = self.getlocalTree(numblocks, blocksize, value)
mmin = min(val.keys()) + start_index
mmax = max(val.keys()) + start_index
# root
checkentries = deque([1])
leaves = []
my_hash = {}
while len(checkentries) != 0:
p = checkentries.popleft()
path = path_join(ID, str(p))
stored_hash = self.checkTreeNode(path, sym_Ka)
my_hash[p] = stored_hash
if stored_hash != bunch[p]:
if mmin <= 2*p <= mmax:
leaves.append(2*p)
else:
checkentries.append(2*p)
if mmin <= 2*p + 1 <= mmax:
leaves.append(2*p+1)
else:
checkentries.append(2*p + 1)
for i in leaves:
path = path_join(ID, str(i))
stored_hash = self.checkTreeNode(path, sym_Ka)
if stored_hash != bunch[i]:
path = path_join(ID, 'data', str(i-start_index))
compare = self.storage_server.get(path)
if compare is None:
return None
compare = util.from_json_string(compare)
civ = compare["IV"]
cen = compare["encrypted"]
cmac = compare["mac"]
newmac = self.crypto.message_authentication_code(cen + path, sym_Ka, 'SHA256')
if newmac != cmac:
raise IntegrityError()
msg = self.crypto.symmetric_decrypt(cen, sym_Ke, 'AES', 'CBC', civ)
# updates DATA NODE
self.hashData(path, val[i-start_index], sym_Ke, sym_Ka)
# update HASH of DATA NODE
path = path_join(ID, str(i))
mac = self.crypto.message_authentication_code(bunch[i], sym_Ka, 'SHA') #SHA
cipher_info = {"hash": bunch[i], "mac":mac}
self.storage_server.put(path, util.to_json_string(cipher_info))
# GET SISTER LEAF HASH
if i % 2 == 0:
sister = path_join(ID, str(i+1))
stored_hash = self.checkTreeNode(sister, sym_Ka)
cipher = self.crypto.cryptographic_hash(bunch[i] + stored_hash, 'SHA')
else:
sister = path_join(ID, str(i-1))
storage_server = self.checkTreeNode(sister, sym_Ka)
cipher = self.crypto.cryptographic_hash(stored_hash + bunch[i], 'SHA')
path = path_join(ID, str(i//2))
mac = self.crypto.message_authentication_code(cipher, sym_Ka, 'SHA') #SHA
cipher_info = {"hash": cipher, "mac": mac}
self.storage_server.put(path, util.to_json_string(cipher_info))
i = i // 2
# update rest of HASHES of tree
while i > 1:
if i %2 == 0:
# get right node
sister = path_join(ID, str(i+1))
stored_hash = my_hash[i+1]
cipher = self.crypto.cryptographic_hash(bunch[i] + stored_hash, 'SHA') #SHA
else:
# get left node
sister = path_join(ID, str(i-1))
stored_hash = my_hash[i-1]
cipher = self.crypto.cryptographic_hash(stored_hash + bunch[i], 'SHA') #SHA
path = path_join(ID, str(i//2))
mac = self.crypto.message_authentication_code(cipher, sym_Ka, 'SHA') #SHA
cipher_info = {"hash": cipher, "mac": mac}
self.storage_server.put(path, util.to_json_string(cipher_info))
i = i//2
def download(self, name):
# GET DIRECTORY KEYS
directory_keys = self.get_directory_keys()
sym_ke, sym_ka = directory_keys
# GET DIRECTORY
client_ID = path_join(self.username, "directory")
resp = self.storage_server.get(client_ID)
if resp is None:
return None
directory = self.decrypt_directory(resp, sym_ke, sym_ka)
if name not in directory:
return None
file = directory[name]
#owner
if len(file["file_id"]) == 32:
keys = file["keys"][0]
sym_Ke, sym_Ka, sym_Kn = keys
F = self.crypto.message_authentication_code(name, sym_Kn, "SHA256")
ID = path_join(self.username, F)
#sharee
else:
file_id = file["file_id"]
session_key = file["keys"]
sym_fe, sym_fa = session_key
shared_file = self.storage_server.get(file_id)
if shared_file is None:
return None
shared_info = self.decrypt_directory(shared_file, sym_fe, sym_fa)
keys = shared_info["keys"]
ID = shared_info["path"]
sym_Ke, sym_Ka, sym_Kn = keys
numblocks = self.getRoot(ID, sym_Ka)
if numblocks is None:
return None
value = ""
for i in range(numblocks):
path = path_join(ID, 'data', str(i))
block = self.storage_server.get(path)
if block is None:
return None
try:
block = util.from_json_string(block)
iv = block['IV']
encrypted = block["encrypted"]
mac = block['mac']
newmac = self.crypto.message_authentication_code(encrypted + path, sym_Ka, 'SHA256')
if newmac != mac:
raise IntegrityError()
decrypt = self.crypto.symmetric_decrypt(encrypted, sym_Ke, 'AES', 'CBC', iv)
value += decrypt
except:
raise IntegrityError()
return value
# m = a.share("b", n1)
# every user must be able to see any updates made to this file immediately
def share(self, user, name):
# GET DIRECTORY KEYS
directory_keys = self.get_directory_keys()
sym_ke, sym_ka = directory_keys
# GET DIRECTORY
client_ID = path_join(self.username, "directory")
resp = self.storage_server.get(client_ID)
if resp is None:
return None
directory = self.decrypt_directory(resp, sym_ke, sym_ka)
if name not in directory:
return None
file = directory[name]
# directory[name] = {"keys": (keys, session_key), "shared": [], "file_id": self.crypto.get_random_bytes(16)}}
# owner sharing w/ child
if len(file["file_id"]) == 32:
keys = file["keys"][0]
session_key = file["keys"][1]
file_id = path_join(user, self.username, file["file_id"])
self.encrypt_filepath(file_id, session_key, keys, name)
# directory[name] = {"keys": session_key, "shared": [], "file_id": B/A/random 16 bytes}
# child sharing w/ grandchild
else:
file_id = file["file_id"]
session_key = file["keys"]
directory[name]["shared"].append(user)
self.encrypt_directory(client_ID, directory, sym_ke, sym_ka)
# cache directory
self.directory[name]["shared"].append(user)
# ENCRYPT MESSAGE TO SEND
recipient_pub_key = self.pks.get_public_key(user)
share_info = {"session_key": session_key, "file_id": file_id}
share_info = util.to_json_string(share_info)
crypted = self.crypto.asymmetric_encrypt(share_info, recipient_pub_key)
sign = self.crypto.asymmetric_sign(crypted, self.private_key)
output = (crypted, sign)
output = util.to_json_string(output)
return output
# b.receive_share("a", n2, m)
# b must be able to read / modify / reshare this file
def receive_share(self, from_username, newname, message):
sender_pub_key = self.pks.get_public_key(from_username)
try:
output = util.from_json_string(message)
crypted, sign = output
except:
raise IntegrityError()
# DECRYPT RECEIVED MESSAGE
if self.crypto.asymmetric_verify(crypted, sign, sender_pub_key):
msg = self.crypto.asymmetric_decrypt(crypted, self.private_key)
msg = util.from_json_string(msg)
session_key = msg['session_key']
file_id = msg['file_id']
else:
raise IntegrityError()
# GET DIRECTORY KEYS
directory_keys = self.get_directory_keys()
sym_ke, sym_ka = directory_keys
# GET DIRECTORY
client_ID = path_join(self.username, "directory")
resp = self.storage_server.get(client_ID)
if resp is None:
directory = {newname: {"keys": session_key, "shared": [], "file_id": file_id}}
else:
directory = self.decrypt_directory(resp, sym_ke, sym_ka)
directory[newname] = {"keys": session_key, "shared": [], "file_id": file_id}
# can cache directory here
self.directory[newname] = {"keys": session_key, "shared": [], "file_id": file_id}
self.encrypt_directory(client_ID, directory, sym_ke, sym_ka)
def revoke(self, user, name):
# GET DIRECTORY KEYS
directory_keys = self.get_directory_keys()
sym_ke, sym_ka = directory_keys
# GET DIRECTORY
client_ID = path_join(self.username, "directory")
resp = self.storage_server.get(client_ID)
if resp is None:
return None
directory = self.decrypt_directory(resp, sym_ke, sym_ka)
if name not in directory:
return None
file = directory[name]
# only Owner can revoke
if len(file["file_id"]) == 32:
newkeys = self.generate_keys()
session_key = file["keys"][1]
if user not in file["shared"]:
return None
file["shared"].remove(user)
# store new keys in path
for people in file["shared"]:
file_id = path_join(people, self.username, file["file_id"])
self.encrypt_filepath(file_id, session_key, newkeys, name)
directory[name] = {"keys": (newkeys, session_key), "shared": file["shared"], "file_id": file["file_id"]}
self.encrypt_directory(client_ID, directory, sym_ke, sym_ka)
# can cache directory here
self.directory[name] = {"keys": (newkeys, session_key), "shared": file["shared"], "file_id": file["file_id"]}
else:
raise IntegrityError()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-08-28 06:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('spider', '0003_auto_20180827_1701'),
]
operations = [
migrations.AddField(
model_name='cctvworldinfo',
name='content_image_url',
field=models.CharField(blank=True, default='', max_length=500, null=True, verbose_name='内容图片地址'),
),
migrations.AlterField(
model_name='cctvworldinfo',
name='front_image_url',
field=models.CharField(blank=True, default='', max_length=500, null=True, verbose_name='列表图片地址'),
),
]
|
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 10:37:52 2020
@author: NARAYANA REDDY DATA SCIENTIST
"""
# RANDOM FOREST REGRESSION
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Importing the data set
dataset=pd.read_csv('position_salaries.csv')
# divide the data set into independent and depedent variable
x=dataset.iloc[:,1:2].values
y=dataset.iloc[:,2].values
# splitting the data set into train and test data
"""from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x_train,y_train,test_size=0.3,ramdom_size=0)"""
# Feature scaling
""" from sklearn.preprocessing import StandardScaler
Sc_x=StandardScaler()
x_train=Sc_x.fit_transform(x_train)
x_test=Sc_x.fit_transform(x_test) """
# Fitting the Random Forest Regression to the dataset
from sklearn.ensemble import RandomForestRegressor
Regressor=RandomForestRegressor(n_estimators=10,random_state=0)
Regressor.fit(x,y)
# predict the regressor
y_predict=Regressor.predict(x)
# basic graph
plt.scatter(x,y,color='red')
plt.plot(x,Regressor.predict(x), color='blue')
plt.show
# Visualising the RandomForest Regressor Results (Higher Resolution)
x_grid=np.arange(min(x),max(x),0.01)
x_grid=x_grid.reshape((len(x_grid),1))
plt.scatter(x,y, color='red')
plt.plot(x_grid,Regressor.predict(x_grid), color='blue')
plt.title('TRUTH OR BLUFF (RANDOM FOREST REGRESSOR)')
plt.xlabel('position level')
plt.ylabel('salaries')
plt.show
|
#!/usr/bin/env python
import config
import smtplib
import time
import urllib2
import traceback
from bs4 import BeautifulSoup
# Coinmarket Cap ETH
search_url = 'https://coinmarketcap.com/currencies/'
run = True
#returns price as float
def parse_price(index):
content = urllib2.urlopen(search_url + config.currency_array[index].name + '/').read()
soup = BeautifulSoup(content, "lxml")
#convert text from unicode to float with 2 degrees of precision
str_price = soup.find(id = 'quote_price').getText()
price = int(float(str_price[1:].encode('utf-8'))*100)/100.0
#print type(price)
print "Log: $%.2f" % (price)
soup.decompose()
return price
def compare_price(value, index):
evaluate = False
if value <= config.currency_array[index].low or value >= config.currency_array[index].high:
evaluate = True
return evaluate
#sends email from email in config file to same email
def send_email(address, password, price, index):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(address, password)
msg = "The price of " + str(config.currency_array[index].name) + " is outside your limit $" + str(price) + "."
server.sendmail(address, address, msg)
server.quit()
if __name__ == '__main__':
while run:
try:
count = 0
for element in config.currency_array:
print config.currency_array[count].name
current_price = parse_price(count)
if compare_price(current_price, count):
send_email(config.email_address, config.password, current_price, count)
print "email sent"
count += 1
count = 0
time.sleep(config.time_interval)
except:
print("Error. Script aborted.")
traceback.print_exc()
run = False |
"""tests/test_bca_analysis.py module."""
from pathlib import Path
import pandas as pd
from numpy.testing import assert_array_almost_equal
from pandas.testing import assert_frame_equal
from experiment_data_viz import bca_analyis
DATA_DIR = Path(__file__).resolve().parent.joinpath("data")
PLATE_FILE_KEY = DATA_DIR.joinpath("Gryder_P2_7Jul21.csv")
SAMPLE_FILE_KEY = DATA_DIR.joinpath("Sample 1.csv")
PROTEINS_EXPECTED = pd.read_csv(
DATA_DIR.joinpath("protein_Gryder_P2_7Jul21.csv"), header=None
)
SAMPLE_EXPECTED = pd.read_csv(DATA_DIR.joinpath("Sample 1.csv_C1_C12.csv"))
def test_end_to_end() -> None:
"""Test end to end."""
plate_data = bca_analyis.read_plate_file(plate_filename=PLATE_FILE_KEY)
sample_data = bca_analyis.read_sample_file(sample_filename=SAMPLE_FILE_KEY)
df_sample_actual, protein_arr_actual = bca_analyis.get_concentration_values(
plate_data=plate_data,
sample_data=sample_data,
number_of_replicates=1,
sample_start="C1",
sample_end="C12",
)
assert_frame_equal(df_sample_actual, SAMPLE_EXPECTED)
assert_array_almost_equal(protein_arr_actual, PROTEINS_EXPECTED)
|
def ifInteger(value):
if value.strip().isdigit(): return True
else: return False
def main():
val=input("What number are you thinking about:")
if ifInteger(val) :
if int(val) % 2==0:
(print("This number is even!"))
else:
(print("This number is odd!"))
else:
print("Not a integer :/")
loop=True
while(loop):
val=input("Have another? If no input 0:")
if ifInteger(val) :
if int(val) == 0:break
if int(val) % 2==0:
(print("This number is even!"))
else:
(print("This number is odd!"))
else:
print("Not a integer :/")
main()
|
# Author Hamid Raza Noori(noorihamid1994@gmail.com)
# Desc Sample OOPS program
# Date 07 Nov 2020
class Employee:
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
def fullName(self):
return self.firstName + " " + self.lastName
emp = Employee('Aroh','yadav') #memory allocation
print(emp.fullName())
emp1 = Employee('Ahad','siddiqui')
print(emp1.fullName())
# 10001 : emp {aroh , yada}
# 10002 : emp2 {ahad si...} |
from sys import stdin
N = int(stdin.readline().strip())
def factorial(n):
return 1 if (n==1 or n==0) else n * factorial(n - 1);
for i in range(0, N):
x = int(stdin.readline().strip())
fact = factorial(x)
print(fact%10) |
######################################################################
# Add the lineage information to the Kraken/Braken output file.
#
#
# Author - Kobie Kirven
# Date: 2 - 17 - 2021
#
######################################################################
#Imports
import os, sys, argparse, subprocess
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-i",
"--input",
dest="in_file",
help="Input Kraken/Braken report file",
)
parser.add_argument(
"-o",
"--output",
dest="out",
help="Output file with lineages added",
)
parser.add_argument(
"-db",
"--database",
dest="database",
help="Path to NCBI Lineage database",
)
parser.add_argument(
"-t", "--type", dest="type", help="Output type"
)
args = parser.parse_args()
classLevels = ["k", "p", "c", "o", "f", "g", "s"]
def extractNCBIids(fileName):
with open(fileName) as fn:
lines = fn.readlines()
lines = [line.split("\t")[1] for line in lines]
with open("ids.txt", "w") as fn:
for line in lines[1:]:
fn.write(line + "\n")
return lines[1:]
def getLineages():
os.system(
"taxonkit --data-dir "
+ str(args.database)
+ " lineage ids.txt > out1.txt"
)
os.system("taxonkit --data-dir "
+ str(args.database) + " reformat -P -F out1.txt > out.txt")
with open("out.txt") as fn:
lines = fn.readlines()
lineages = []
for i in range(len(lines)):
line = lines[i].strip('\n').split("\t")
lineages.append(line[2])
return lineages
# Remove intermediate files
os.system("rm out1.txt")
os.system("rm ids.txt")
def outputWithLineage(lineages):
with open(args.in_file) as fn:
lines = fn.readlines()
lines = [line.strip("\n").split("\t") for line in lines]
with open(args.out, "w") as fn:
fn.write("lineage\t" + "\t".join(lines[0][3:]) + "\n")
lines = lines[1:]
for i in range(len(lines)):
fn.write(
lineages[i]
+ "\t"
+ "\t".join(lines[i][3:])
+ "\n"
)
def outputForOTU(lineages):
with open(args.in_file) as fn:
lines = fn.readlines()
lines = [line.strip("\n").split("\t") for line in lines]
with open(args.out, "w") as fn:
fn.write(
"Kingdom\tPyhlum\tClass\tOrder\tFamily\tGenus\tSpecies\t"
+ "\t".join(lines[0][3:])
+ "\n"
)
lines = lines[1:]
for i in range(len(lines)):
linList = lineages[i].split(";")
if len(linList) < 8:
length = 8 - len(linList)
for t in range(length):
linList.append("N/A")
linList = linList[1:8]
fn.write(
"\t".join(linList)
+ "\t"
+ "\t".join(lines[i][3:])
+ "\n"
)
ids = extractNCBIids(args.in_file)
lineage = getLineages()
if args.type == "l":
outputWithLineage(lineage)
elif args.type == "otu":
outputForOTU(lineage)
else:
print("No output style specified: Default linear")
outputWithLineage(lineage)
if __name__ == "__main__":
main()
|
# %% imports
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.ion()
import sys
import time
import pathlib
import numpy as np
import pandas as pd
import dask.distributed
import dask.array as da
_code_git_version="07f588cb83174cbac2f134044004c5112935bc67"
_code_repository="https://github.com/plops/cl-py-generator/tree/master/example/28_dask_test/source/run_00_start.py"
_code_generation_time="21:56:23 of Sunday, 2020-11-01 (GMT+1)"
client=dask.distributed.Client(processes=False, threads_per_worker=2, n_workers=1, memory_limit="2GB")
x=da.random.random((10000,10000,), chunks=(1000,1000,))
y=((x)+(x.T))
z=y[::2,5000:].mean(axis=1) |
import Horcner as H
import numpy as np
def diff(x, y):
n = len(y)
delta = np.zeros((n, n))
delta[:, 0] = y
for i in range(1, n):
for j in range(0, n - i):
delta[j, i] = (delta[j+1, i-1] - delta[j, i-1])
return delta
def Bessel(x, y):
n = len(x)
P = np.zeros(n)
for i in range(1, n):
L = np.zeros(i)
for j in range(0, i):
if (i % 2 != 0):
L[j] = (1 - i)/2 + j
else:
L[j] = (2 - i) / 2 + j
#for j in range(n - 1, n - i - 2, -1):
|
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from unittest import expectedFailure
from pants_test.pants_run_integration_test import PantsRunIntegrationTest
class ChangedTargetGoalsIntegrationTest(PantsRunIntegrationTest):
def ref_for_greet_change(self):
# Unfortunately, as in being an integration test, it is difficult to mock the SCM used.
# Thus this will use the pants commit log, so we need a commit that changes greet example.
# Any comment/whitespace/etc change is enough though, as long as we know the SHA.
return '14cc5bc23561918dc7134427bfcb268506fcbcaa'
def greet_classfile(self, workdir, filename):
path = 'compile/jvm/java/classes/org/pantsbuild/example/hello/greet'.split('/')
return os.path.join(workdir, *(path + [filename]))
@expectedFailure
def test_compile_changed(self):
cmd = ['compile-changed', '--diffspec={}'.format(self.ref_for_greet_change())]
with self.temporary_workdir() as workdir:
# Nothing exists.
self.assertFalse(os.path.exists(self.greet_classfile(workdir, 'Greeting.class')))
self.assertFalse(os.path.exists(self.greet_classfile(workdir, 'GreetingTest.class')))
run = self.run_pants_with_workdir(cmd, workdir)
self.assert_success(run)
# The directly changed target's produced classfile exists.
self.assertTrue(os.path.exists(self.greet_classfile(workdir, 'Greeting.class')))
self.assertFalse(os.path.exists(self.greet_classfile(workdir, 'GreetingTest.class')))
with self.temporary_workdir() as workdir:
# Nothing exists.
self.assertFalse(os.path.exists(self.greet_classfile(workdir, 'Greeting.class')))
self.assertFalse(os.path.exists(self.greet_classfile(workdir, 'GreetingTest.class')))
run = self.run_pants_with_workdir(cmd + ['--include-dependees=direct'], workdir)
self.assert_success(run)
# The changed target's and its direct dependees' (eg its tests) classfiles exist.
self.assertTrue(os.path.exists(self.greet_classfile(workdir, 'Greeting.class')))
self.assertTrue(os.path.exists(self.greet_classfile(workdir, 'GreetingTest.class')))
@expectedFailure
def test_test_changed(self):
with self.temporary_workdir() as workdir:
cmd = ['test-changed', '--diffspec={}'.format(self.ref_for_greet_change())]
junit_out = os.path.join(workdir, 'test', 'junit',
'org.pantsbuild.example.hello.greet.GreetingTest.out.txt')
self.assertFalse(os.path.exists(junit_out))
run = self.run_pants_with_workdir(cmd, workdir)
self.assert_success(run)
self.assertFalse(os.path.exists(junit_out))
run = self.run_pants_with_workdir(cmd + ['--include-dependees=direct'], workdir)
self.assert_success(run)
self.assertTrue(os.path.exists(junit_out))
|
# Enter script code
keyboard.send_key("<backspace>")
keyboard.send_keys(" | fpp")
keyboard.send_keys("<ctrl>+m") |
# Sorting the Tokens
# Perform sorting of the token list: first by tokens (alphabetical order), and then by document ids
# Input to this component will be a concatenated list of tokens from all documents.
# Input: list of pairs < token , document id >
# Output: sorted list of pairs < token , document id >
from CONST import *
from Directory_Listing import ListFiles
from File_Reading import GetFileContents
from Tokenization import GenerateTokens
from Linguistic_Modules import LingModule
def SortTokens(token_pairs_list):
sortedTokens = sorted(token_pairs_list, key=lambda element: (element[0], element[1]))
return sortedTokens
if __name__ == "__main__":
# Standalone Test
fileList = ListFiles(rootDir)
fileContent_1 = GetFileContents(fileList[0])
tokenPair_1 = GenerateTokens(fileContent_1, fileList[0])
fileContent_2 = GetFileContents(fileList[1])
tokenPair_2 = GenerateTokens(fileContent_2, fileList[1])
tokenPair = tokenPair_1 + tokenPair_2
original_list = LingModule(tokenPair)
print(original_list)
sorted_list = SortTokens(original_list)
print(sorted_list) |
# 1. create a configuration
#2. create the cluster
#3. provision the VM
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
# here my cluster name
cluster_name = "manjunathcluster1"
# write the exception block to check if compute target exists
# if not then create new compute target
try:
compute_target = ComputeTarget(workspace=ws, name=cluster_name)
print('Found existing compute target')
except ComputeTargetException:
print('Creating new compute target...')
compute_config = AmlCompute.provisioning_configuration(vm_size='Standard_D2_V2',max_nodes=4)
# now create the cluster
compute_target = ComputeTarget.create(ws, cluster_name, compute_config)
compute_target.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20)
print(compute_target.get_status().serialize()) |
from select_factor import get_factors
from mylib import get_data
from mylib import train_test_split
from label_generator import generate_label
from mltool import method
from sklearn.metrics import classification_report
filename='E:/300354.csv'
high,low,dopen,close,vol=get_data(filename)
datasets=get_factors(high,low,close,vol,BBANDS=True,DEMA=True,EMA=True,AD=True,ADOSC=True,OBV=True)
train_data,test_data=train_test_split(datasets)
label=generate_label(close,sign=1)
train_label,test_label=train_test_split(label)
method.fit(train_data,train_label)
pred=method.predict(test_data)
print(classification_report(test_label,pred)) |
DIGITS = set('0123456789')
def unused_digits(*args):
return ''.join(sorted(DIGITS.difference(''.join(str(a) for a in args))))
|
import random
class Dice():
""" The game WH40k is a D6 base game. This class will simulate dice rolling."""
def __init__(self, dice, hit, wound, save, top=6,) :
self.dice = [random.randint(1, top) for die in range(dice)]
self.hit = hit
self.save = save
self.wound = wound
self.top = top
def ToHit(self):
""" This will compare the number of dice rolled to the user input for what is needed to hit. The number of hits
dealt is the number greater than or equal to the user input value for what they need to hit with."""
hits = len([die for die in self.dice if die >= self.hit])
self.dice = [random.randint(1, self.top) for die in range(hits)]
return hits
def ToWound(self):
""" This will compare the number of dice that hit to the user input for what is needed to wound. The number of
wounds dealt needs to be greater than or equal to the user inputted value for what they need to wound with."""
wounds = len([die for die in self.dice if die >= self.wound])
self.dice = [random.randint(1, self.top) for die in range(wounds)]
return wounds
def WoundsDealt(self):
""" This is to compare the number of wounds to the inputted save value. The output should be the number
of wounds not saved, meaning the defending unit is taking this amount of wounds"""
saved = len([die for die in self.dice if die >= self.save])
return len(self.dice) - saved
def statistics(runtime = 100):
""" In this section we want the program to run X amount of times and produce statistics from the results. To keep it
simple we just want to see the maximum, minimum, and average for hit, wound and saved."""
count = 0
results = []
while count < runtime:
d = Dice(20,4,4,3)
results.append((d.ToHit(), d.ToWound(), d.WoundsDealt()))
count += 1
print("The maximum number of hits:" + str(max([r[0] for r in results])))
print("The minimum number of hits:" + str(min([r[0] for r in results])))
print("The average number of hits:" + str(sum([r[0] for r in results])/len([r[0] for r in results])))
print("The maximum number of wounds:" + str(max([r[1] for r in results])))
print("The minimum number of wounds:" + str(min([r[1] for r in results])))
print("The average number of wounds:" + str(sum([r[1] for r in results])/len([r[1] for r in results])))
print("The maximum number of saves:" + str(max([r[2] for r in results])))
print("The minimum number of saves:" + str(min([r[2] for r in results])))
print("The average number of saves:" + str(sum([r[2] for r in results])/len([r[2] for r in results])))
statistics() |
#!/usr/bin/python3.6
import paramiko
import yaml
import time
import multiprocessing
def svn_update(project,config):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 作用是允许连接不在know_hosts文件中的主机
try:
ssh.connect(project[2], config['port'], config['username'], project[1])
except Exception:
print("connection %s is time out" % project[0])
return False
stdin, stdout, stderr = ssh.exec_command('''
echo 'server{
listen 80;
server_name %s-m.iposecure.com;
#告诉浏览器有效期内只准用 https 访问
add_header Strict-Transport-Security max-age=15768000;
return 301 https://$server_name$request_uri;
}
server{
listen 80;
server_name %s-agent.iposecure.com;
#告诉浏览器有效期内只准用 https 访问
add_header Strict-Transport-Security max-age=15768000;
return 301 https://$server_name$request_uri;
}
server{
listen 80;
server_name %s-op.iposecure.com;
#告诉浏览器有效期内只准用 https 访问
add_header Strict-Transport-Security max-age=15768000;
return 301 https://$server_name$request_uri;
}
' > /www/wdlinux/nginx/conf/vhost/https.conf;
service nginxd restart
''' % (project[0],project[0],project[0]))
result = stdout.read()
error = stderr.read().decode('utf-8')
result = result.decode('utf-8')
if not error:
print("<<< " + str(project[0]) + ":\n" + result)
else:
print("<<< " + str(project[0]) + ":\n" + error)
ssh.close()
return True
if __name__ == '__main__':
timeout = 1000
f = open('./config.yaml')
config = yaml.load(f)
for project in config['projects']:
my_thread = multiprocessing.Process(target=svn_update,args=(project,config))
my_thread.start()
my_thread.join()
print('all finished update')
|
# coding: utf-8
"""
HardeningApi.py
Copyright 2015 SmartBear Software
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
import sys
import os
# python 2 and python 3 compatibility library
from six import iteritems
from ..configuration import Configuration
from ..api_client import ApiClient
class HardeningApi(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not config.api_client:
config.api_client = ApiClient()
self.api_client = config.api_client
def create_hardening_apply_item(self, hardening_apply_item, **kwargs):
"""
Apply hardening on the cluster.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_hardening_apply_item(hardening_apply_item, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param HardeningApplyItem hardening_apply_item: (required)
:return: CreateHardeningApplyItemResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['hardening_apply_item']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_hardening_apply_item" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'hardening_apply_item' is set
if ('hardening_apply_item' not in params) or (params['hardening_apply_item'] is None):
raise ValueError("Missing the required parameter `hardening_apply_item` when calling `create_hardening_apply_item`")
resource_path = '/platform/3/hardening/apply'.replace('{format}', 'json')
method = 'POST'
path_params = {}
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
if 'hardening_apply_item' in params:
body_params = params['hardening_apply_item']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['basic_auth']
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='CreateHardeningApplyItemResponse',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_hardening_resolve_item(self, hardening_resolve_item, **kwargs):
"""
Resolve issues related to hardening, found in current cluster configuration.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_hardening_resolve_item(hardening_resolve_item, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param HardeningResolveItem hardening_resolve_item: (required)
:param bool accept: If true, execution proceeds to resolve all issues. If false, executrion aborts. This is a required argument.
:return: CreateHardeningResolveItemResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['hardening_resolve_item', 'accept']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_hardening_resolve_item" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'hardening_resolve_item' is set
if ('hardening_resolve_item' not in params) or (params['hardening_resolve_item'] is None):
raise ValueError("Missing the required parameter `hardening_resolve_item` when calling `create_hardening_resolve_item`")
resource_path = '/platform/3/hardening/resolve'.replace('{format}', 'json')
method = 'POST'
path_params = {}
query_params = {}
if 'accept' in params:
query_params['accept'] = params['accept']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'hardening_resolve_item' in params:
body_params = params['hardening_resolve_item']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['basic_auth']
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='CreateHardeningResolveItemResponse',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_hardening_revert_item(self, hardening_revert_item, **kwargs):
"""
Revert hardening on the cluster.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_hardening_revert_item(hardening_revert_item, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param Empty hardening_revert_item: (required)
:param bool force: If specified, revert operation continues even in case of a failure. Default is false in which case revert stops at the first failure.
:return: CreateHardeningRevertItemResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['hardening_revert_item', 'force']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_hardening_revert_item" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'hardening_revert_item' is set
if ('hardening_revert_item' not in params) or (params['hardening_revert_item'] is None):
raise ValueError("Missing the required parameter `hardening_revert_item` when calling `create_hardening_revert_item`")
resource_path = '/platform/3/hardening/revert'.replace('{format}', 'json')
method = 'POST'
path_params = {}
query_params = {}
if 'force' in params:
query_params['force'] = params['force']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'hardening_revert_item' in params:
body_params = params['hardening_revert_item']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['basic_auth']
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='CreateHardeningRevertItemResponse',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def get_hardening_state(self, **kwargs):
"""
Get the state of the current hardening operation, if one is happening. Note that this is different from the /status resource, which returns the overall hardening status of the cluster.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_hardening_state(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: HardeningState
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_hardening_state" % key
)
params[key] = val
del params['kwargs']
resource_path = '/platform/3/hardening/state'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['basic_auth']
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='HardeningState',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def get_hardening_status(self, **kwargs):
"""
Get a message indicating whether or not the cluster is hardened. Note that this is different from the /state resource, which returns the state of a specific hardening operation (apply or revert).
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_hardening_status(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: HardeningStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_hardening_status" % key
)
params[key] = val
del params['kwargs']
resource_path = '/platform/3/hardening/status'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['basic_auth']
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='HardeningStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
|
# coding=utf8
from lib.corp import Corp
import re, itertools
class TZRCCorp(Corp):
def __init__(self):
config = {
'info_from': '台州人才网',
'corplist_url': 'http://www.tzrc.com/job/?PageNo={page_no}&JobType=&JobArea=&PublishDate=&Key=&n=20&s=0',
'corp_url': 'http://www.tzrc.com/company/company_info.asp?coid={corp_code}',
'corplist_reg': re.compile(r'/company/company_info\.asp\?frombh=\d+&coid=(?P<corp_code>\d+)[^>]+>(?:<font color="#0033FF">)?(?P<name>[^<]+)', re.S),
'corp_regs': [
re.compile(r'联 系 人:(?P<contact_person>[^<]+)', re.S),
re.compile(r'电 话:(?P<contact_tel_no>[^<]+)', re.S),
re.compile(r'联系地址:[ ]?(?P<addr>[^<]+)', re.S),
],
'commit_each_times': 30,
'has_cookie': True,
'charset': 'gbk',
'timeout': 30,
}
super().__init__(**config)
self.pages = 50
def get_next_page_url(self):
yield 'http://www.tzrc.com/'
for page in range(1, self.pages+1):
yield self.corplist_url.format(page_no=page)
|
# Generated by Django 2.1.2 on 2018-12-23 14:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('systemoptions', '0006_auto_20181223_1611'),
]
operations = [
migrations.AlterField(
model_name='emailwebservice',
name='email_use_tls',
field=models.BooleanField(default=True, max_length=5, verbose_name='EMAIL_USE_TLS'),
),
]
|
import torch
from torch_geometric.nn import MemPooling
from torch_geometric.utils import to_dense_batch
def test_mem_pool():
mpool = MemPooling(4, 8, heads=3, num_clusters=2)
assert mpool.__repr__() == 'MemPooling(4, 8, heads=3, num_clusters=2)'
x = torch.randn(17, 4)
batch = torch.tensor([0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4])
_, mask = to_dense_batch(batch, batch)
out, S = mpool(x, batch)
loss = MemPooling.kl_loss(S)
assert out.size() == (5, 2, 8)
assert S[~mask].sum() == 0
assert S[mask].sum() == x.size(0)
assert float(loss) > 0
|
import pickle
try:
with open('sample_pickle.dat','rb') as f:
n = pickle.load(f)
print(n)
for i in range(n):
x = pickle.load(f)
print(x)
f.close()
except EOFError:
print()
|
#Comment 1
def useless():
#Comment 2
return
a = "#Comment 1%cdef useless():%c%c#Comment 2%c%creturn%ca = %c%s%c%cprint a %c (10,10,9,10,9,10,34,a,34,10,37)"
print a % (10,10,9,10,9,10,34,a,34,10,37)
|
#!/usr/bin/python
import socket
ip = raw_input("Enter the ip:")
port = input("Enter the port no:")
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
if s.connect_ex((ip,port)):
print "Port",port,"is closed"
else:
print "Port",port,"is open"
connect=s.connect(('192.168.233.129',23))
banner=s.recv(1024)
s.send('VRFY'+sys.argv[1]+'\r\n')
results=s.recv(1024)
print result
s.close()
|
class House: # Creating our first class which also served as the parent class later in the discussion
def permission(self):
print(f'You have acres of land to build with')
return ' '
class Bungalow(House): # Inheritance: creating a subclass to inherit the properties of the House class
# the __init__ method also called the constructor method
def __init__(self, colour, length, width, height):
self.colour = colour
self.length = length
self.width = width
self.height = height
def structureb(self):
print(
f'The house has {self.length}, {self.width}, {self.height} dimensions')
return 'House completed'
def build(self):
print('Building completed')
class Storey(House): # Inheritance: a subclass to inherit the properties of the House class
def __init__(self, colour, length, width, height, floors, stairs):
self.colour = colour
self.length = length
self.width = width
self.height = height
self.floors = floors
self.stairs = stairs
def structure(self):
print(
f'The house has {self.length}, {self.width}, {self.height} dimensions with {self.floors} floors')
return 'House completed'
def stairs_type(self):
print(f'Your chosen stair type is {self.stairs}')
return ' '
def build(self):
print('Coooompleeeted!')
class Multi(Storey, Bungalow):
pass
house1 = House() # creating an object from our House class
print(house1.permission())
# OOP gives us the ability to create multiple objects from a single class without code repetition
storey1 = Storey('red', 34, 56, 76, 3, 'curly')
storey2 = Storey('white', 304, 126, 64, 7, 'straight')
storey3 = Storey('blue', 22, 56, 76, 1, 'wavy')
bungalow1 = Bungalow('white', 26, 89, 46)
bungalow2 = Bungalow('brown', 126, 49, 26)
# checking the output of our methods and objects
print(storey1.colour)
print(storey1.structure())
print(bungalow1.colour)
print(bungalow1.structureb())
print(storey1.stairs_type())
multi1 = Multi('white', 304, 126, 64, 7, 'straight')
print(multi1.structureb())
|
# -*- coding: utf-8 -*-
# EYNES- Ingenieria de software - 2019. See LICENSE file for full copyright and licensing details.
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.tools.safe_eval import safe_eval
from odoo.exceptions import ValidationError
import logging
import datetime
from datetime import timedelta
import pdb
_logger = logging.getLogger(__name__)
class EmployeeObjectivePanel(models.Model):
_inherit = 'employee.objective'
_name = 'employee.objective.panel'
_description = 'Panels group employee\'s objectives.'
employee_ids = fields.One2many(
'hr.employee',
'id',
string="No employee should be selected here..",
compute='_get_employees',
store=True
)
name = fields.Char(
string="Panel id",
store=True,
default=None,
required=False
)
monetary_objective = fields.Integer(
string="GENERAL Objective",
compute='_compute_monetary_obj',
readonly=False
)
type = fields.Selection([
('so', 'Total Sale Orders'),
('inv', 'Total Invoicing'),
('marg','Revenue Margin')
],
index=True,
required=False,
store=True,
default=lambda self: 'marg',
help="Type is used to separate different objectives for employees."
)
objective_type = fields.Selection([
('employee', 'For Employee'),
('panel', 'For Panel'),
],
index=True,
required=True,
store=True,
default=lambda self: 'panel',
help="Is this objective meant to be grouped on a panel?"
)
date_open = fields.Datetime(
'Assignation Date',
default=fields.Datetime.now,
required=False
)
period = fields.Selection([
('custom', 'Custom lapse'),
('day', '1 Day'),
('week', '1 Week'),
('fortnight', '1 Fortnight'),
('month','1 Month'),
('trim','1 Trimester'),
('quad','1 Quadrimester'),
('year','1 Year')],
index=True,
required=False,
store=True,
default=lambda self: 'month',
help="Assign this employee's objective period."
)
isPanel = fields.Boolean(
string="Is panel?",
readonly=True,
default=True,
store=True,
compute='_compute_is_panel'
)
objective_ids = fields.One2many(
'employee.objective',
'objective_id',
string="Associated objectives for this panel",
store=True,
readonly=False
)
@api.depends('objective_type')
def _compute_is_panel(self):
for pan in self:
if pan.objective_type == 'employee':
pan.isPanel = False
if pan.objective_type == 'panel':
pan.isPanel = True
@api.depends('objective_ids')
def _get_employees(self):
for pan in self:
_employees = []
for obj in pan.objective_ids:
_employees.append(obj.employee_id.id)
pan.employee_ids = pan.env['hr.employee'].browse(_employees)
@api.depends('objective_ids')
def _compute_monetary_obj(self):
for pan in self:
#orders_data = pan.env['sale.order']
_monetary_objective = 0
for obj in pan.objective_ids:
_monetary_objective += obj.monetary_objective
pan.monetary_objective = _monetary_objective
@api.depends('objective_ids')
def _compute_planned_revenue(self):
for pan in self:
#orders_data = pan.env['sale.order']
_monetary_objective = 0
_actual_revenue = 0
_state = True
_done_percentage = 0
_type = { pan.objective_ids[0].type }
for obj in pan.objective_ids:
"""orders_data += orders_data.search([
('user_id', '=', obj.employee_id.user_id.id),
('state','in',['sale','done']),
('date_order','>=',obj.date_open),
('date_order','<=',obj.date_closed)
])
"""
if (obj.type in _type): #Don't compare apples with oranges
_monetary_objective += obj.monetary_objective
_actual_revenue += obj.actual_revenue
_state = _state and obj.objective_state
#IF at least one of the objectives_state is false, then this panel
#state, is also false.
_done_percentage = round((_actual_revenue * 100)/(_monetary_objective or 1),2)
_logger.info('PANEL DATA : ______ %s , %s , %s , %s %',_monetary_objective,_actual_revenue,_state,_done_percentage)
pan.monetary_objective = _monetary_objective
pan.actual_revenue = _actual_revenue
pan.objective_state = _state
pan.done_percentage = _done_percentage
_logger.info('CONTROL TEST DATA : ______ %s , %s , %s , %s %',pan.monetary_objective,pan.actual_revenue,pan.objective_state,pan.done_percentage)
#pdb.set_trace()
|
from urllib.request import urlopen
from bs4 import BeautifulSoup as bs
import os
from urllib.parse import quote_plus
# 검색 대분류(순서) 왼쪽부터 1 ~
item = [4, 5, 6, 7, 8, 10]
# 대분류 상품명
items1 = []
# 대분류 링크
link1 = []
# 중분류 소분류 상품명
items2 = []
# 류중분류 소분류 링크
link2 = []
# 웹사이트 설정
baseUrl = 'https://phone2joy.com'
# 출력데이타
csvData = []
# 에러메세지파일
errorFile = "ErrorMsg.txt"
# 다운로드완료 상품 목록 리스트파일
itemsList = "ImageDownLoadItemsList.txt"
# 슬래쉬 -> 스페이스 변환
def slashChange(str):
str = str.replace("/", " ")
return str
# error내용 출력
def makeErrorTxt(msg):
file = ""
if os.path.isfile(errorFile):
# 파일에 추가
file = open(errorFile, 'a')
else:
# 파일 작성
file = open(errorFile, 'w')
# 데이타 출력
file.write(msg)
file.write("\n")
file.close()
# 다룬로드체크파일 작성
def downloadFileWrite(itemName):
if os.path.isfile(itemsList):
# 파일에 추가
file = open(itemsList, 'a')
else:
# 파일 작성
file = open(itemsList, 'w')
# 파일에 추가
file.write(itemName + "\n")
file.close()
# 다운로드 유무 확인(다운로드O:False, 다운로드X:True)
def downloadCheck(url, itemName):
rstFlag = True
if os.path.isfile(url):
pass
else:
# 파일 작성
file = open(itemsList, 'w')
file.write("")
file.close()
return rstFlag
file = open(url, 'r')
readItems = file.read()
if 0 <= readItems.find(itemName):
rstFlag = False
file.close()
return rstFlag
# csv파일 작성
def makeCsv(fileName, data):
file = ""
if os.path.isfile(fileName):
# 파일에 추가
file = open(fileName, 'a')
else:
# 파일 작성
file = open(fileName, 'w')
# 데이타 출력
idx = 0
for i in data:
cnt = 0
file.write(i)
if idx != len(data) - 1:
file.write(",")
idx += 1
file.write("\n")
file.close()
# 디렉토리 생성 메소드
def createFolder(dir):
try:
if not os.path.exists(dir):
os.makedirs(dir)
except OSError:
makeErrorTxt("ERROR: Creating directory." + dir)
# 소분류 페이지 읽기
def getUrl(saveDir, siteUrl, data1, data2, data3):
# 한글url 치환
url = quote_plus(baseUrl + siteUrl)
url = url.replace("%2F", "/")
url = url.replace("%3A", ":")
# url open
html = urlopen(url)
# 페이지 파싱
soup = bs(html, "html.parser")
# 마지막페이지 구하기
lastPage = soup.select('.last')
txtTmp = lastPage[0]["href"]
txtPnt = txtTmp.find("=")
lastPageCnt = txtTmp[txtPnt + 1:]
# 헤더 데이타 쓰기
csvData = ["대분류", "중분류", "소분류", "상품명", "판매가", "소비자가", "기종", "색상", "디자인", "섬네일", "상세이미지", "링크"]
if data3 != " ":
if os.path.isfile(saveDir + "/" + data3 + ".csv"):
pass
else:
makeCsv(saveDir + "/" + data3 + ".csv", csvData)
elif data3 == " " and data2 != " ":
if os.path.isfile(saveDir + "/" + data2 + ".csv"):
pass
else:
makeCsv(saveDir + "/" + data2 + ".csv", csvData)
elif data3 == " " and data2 == " " and data1 != " ":
if os.path.isfile(saveDir + "/" + data1 + ".csv"):
pass
else:
makeCsv(saveDir + "/" + data1 + ".csv", csvData)
# 마지막 페이지가 없을 경우
if lastPageCnt == "#none":
lastPageCnt = 1
# 첫페이지부터 마지막페이지까지
for pageidx in range(1, int(lastPageCnt) + 1):
print("현재 페이지 = " + data1 + " , " + data2 + " , " + data3 + " , " + str(pageidx) + "페이지 출력중")
# 각페이지 url
urltmp = url + "?page=" + str(pageidx)
# url open
html = urlopen(urltmp)
# 페이지 파싱
soup = bs(html, "html.parser")
# 각페이지 읽어드리기
pageData = soup.select('.thumbnail')
for i in pageData:
link = i.find('a')['href']
tagImg = i.find_all('img')[5]
alt = tagImg['alt']
# 각CSV파일 다운로드 체크
eachOtherFileFlag = False
if data3 != " ":
eachOtherFileFlag = downloadCheck(saveDir + "/" + data3 + ".csv", alt)
elif data3 == " " and data2 != " ":
eachOtherFileFlag = downloadCheck(saveDir + "/" + data2 + ".csv", alt)
elif data3 == " " and data2 == " " and data1 != " ":
eachOtherFileFlag = downloadCheck(saveDir + "/" + data1 + ".csv", alt)
imgFileDownLoadFlag = downloadCheck(itemsList, alt)
print("상품명 : " + alt + " , eachOtherFileFlag : " + str(eachOtherFileFlag) + " , imgFileDownLoadFlag : ",
imgFileDownLoadFlag)
if eachOtherFileFlag or imgFileDownLoadFlag:
# CSVdata초기화
csvData = []
# 대분류 임시저장
csvData.append(data1)
# 중분류 임시저장
csvData.append(data2)
# 소분류 임시저장
csvData.append(data3)
# 상품명
csvData.append(alt)
# 한글url 치환
url1 = quote_plus(baseUrl + link)
url1 = url1.replace("%2F", "/")
url1 = url1.replace("%3A", ":")
print(url1)
# url open
html2 = urlopen(url1)
# 페이지 파싱
soup2 = bs(html2, "html.parser")
# 판매가
price = soup2.select('#span_product_price_text')
csvData.append(price[0].get_text().replace(",", ""))
# 소비자가
consumer = soup2.select('#span_product_price_custom')
csvData.append(consumer[0].get_text().replace(",", ""))
# 기종 색상 디자인
consumer = soup2.select('.xans-product-option')
kiFlg = 0
clrFlg = 0
dgnFlg = 0
for z in consumer:
thtmp = z.find_all('th')
# 기종 값 추출
if 0 != len(thtmp) and kiFlg == 0 and thtmp[0].get_text() in "기종":
designTmp = "["
design = soup2.select('#product_option_id1')
designOption = design[0].find_all('option')
for designText in designOption:
if designText['value'] != "*" and designText['value'] != "**":
designTmp = designTmp + designText.get_text() + ":"
designTmp = designTmp[:-1] + "]"
csvData.append(designTmp)
kiFlg = 1
# 기종 값 공백
if kiFlg == 0:
csvData.append(" ")
for z in consumer:
thtmp = z.find_all('th')
# 색상 값 추출
if 0 != len(thtmp) and clrFlg == 0 and thtmp[0].get_text() in "색상":
designTmp = "["
designOption = soup2.find_all(disabled="disabled")
for designText in designOption:
if designText['value'] != "*" and designText['value'] != "**":
designTmp = designTmp + designText.get_text() + ":"
designTmp = designTmp[:-1] + "]"
csvData.append(designTmp)
clrFlg = 1
# 색상 값 공백
if clrFlg == 0:
csvData.append(" ")
for z in consumer:
thtmp = z.find_all('th')
# 디자인 값 추출
if 0 != len(thtmp) and dgnFlg == 0 and thtmp[0].get_text() in "디자인":
designTmp = "["
design = soup2.select('#product_option_id1')
designOption = design[0].find_all('option')
for designText in designOption:
if designText['value'] != "*" and designText['value'] != "**":
designTmp = designTmp + designText.get_text() + ":"
designTmp = designTmp[:-1] + "]"
csvData.append(designTmp)
dgnFlg = 1
# 디자인 값 공백
if dgnFlg == 0:
csvData.append(" ")
# 상세 메인이미지 주소
img = soup2.select('.BigImage')
imgSrc = img[0]["src"]
# 상세 메인이미지 파일명 갖고오기
idx = imgSrc.rfind("/")
imgFileName = imgSrc[idx + 1:]
# 한글url 치환
url2 = quote_plus(imgSrc)
url2 = url2.replace("%2F", "/")
url2 = url2.replace("%3A", ":")
url2 = url2.replace("+", "%20")
# 다운로드 유무 체크
if imgFileDownLoadFlag:
try:
# 상세 메인이미지 다운로드 및 썸네일
with urlopen(url2) as f:
with open(saveDir + "/" + alt + "-main-" + imgFileName, 'wb') as h: # w - write b - binary
imgFile = f.read()
h.write(imgFile)
except ValueError:
try:
print("url2 : " + url2)
# 상세 메인이미지 다운로드 및 썸네일
with urlopen("https:" + url2) as f:
with open(saveDir + "/" + alt + "-main-" + imgFileName, 'wb') as h: # w - write b - binary
img = f.read()
h.write(img)
except:
makeErrorTxt("ValueError 에러 상품 : " + alt)
except Exception as e:
makeErrorTxt("Exception 에러 상품 : " + alt)
# 상세 내용 이미지 주소
img2 = soup2.select('.cont')
# 상세 내용 이미지 주소tmp
img2Tmp = "["
for j in img2:
src2 = j.find_all('img')
for k in src2:
src3 = k['ec-data-src']
imgFileName2 = ""
if "event" not in src3 and "shop_guide" not in src3 and "title" not in src3:
# 상세 메인이미지 파일명 갖고오기
idx2 = src3.rfind("/")
imgFileName2 = src3[idx2 + 1:]
imgSrc = src3[:idx2]
# 한글url 치환
url3 = quote_plus(imgFileName2)
url3 = url3.replace("%2F", "/")
url3 = url3.replace("%3A", ":")
url3 = url3.replace("+", "%20")
url3 = "https://phone2joy.com" + imgSrc + "/" + url3
# 다운로드 유무 체크
if imgFileDownLoadFlag:
try:
# 상세 메인이미지 다운로드 및 썸네일
with urlopen(url3) as f:
with open(saveDir + "/" + alt + "-detail-" + imgFileName2,
'wb') as h: # w - write b - binary
imgFile = f.read()
h.write(imgFile)
except Exception as e:
makeErrorTxt("문제 페이지 = " + data1 + " , " + data2 + " , " + data3 + " , " + str(
pageidx) + "페이지" + " , 상품명 : " + alt)
makeErrorTxt("ERROR not Found : " + url3)
# 상세 내용 이미지 주소tmp
img2Tmp = img2Tmp + alt + "-detail-" + imgFileName2 + ":"
# 섬네일
csvData.append(alt + "-main-" + imgFileName)
# 상세 이미지
img2Tmp = img2Tmp[:-1] + "]"
csvData.append(img2Tmp)
# 해당링크
csvData.append(baseUrl + link)
# 다운로드 유무 체크
if eachOtherFileFlag:
# csv 파일 쓰기
if data3 != " ":
makeCsv(saveDir + "/" + data3 + ".csv", csvData)
elif data3 == " " and data2 != " ":
makeCsv(saveDir + "/" + data2 + ".csv", csvData)
elif data3 == " " and data2 == " " and data1 != " ":
makeCsv(saveDir + "/" + data1 + ".csv", csvData)
if imgFileDownLoadFlag:
# 다운로드완료한 상품명 작성
downloadFileWrite(alt)
# 데이터 크롤링 메소드
def urlcwraling():
# 웹사이트 오픈
html = urlopen(baseUrl)
# 메인 페이지 파씽
soup = bs(html, "html.parser")
# 대구분 링크 읽기
alink1 = soup.find_all('ul', {'class': 'nav d1-wrap'})
# 대분류 및 중분류 링크 저장
for i in alink1:
for j in i.find_all('li'):
items1.append(j.get_text())
link1.append(j.find('a')['href'])
# 대분류 수 만큼 루프
for i in item:
# 대분류명
itemTop = items1[i-1]
url1 = baseUrl + link1[i-1]
# 한글url 치환
url1 = quote_plus(url1)
url1 = url1.replace("%2F", "/")
url1 = url1.replace("%3A", ":")
# url open
html1 = urlopen(url1)
# 메인 페이지 파씽
soup1 = bs(html1, "html.parser")
alink2 = soup1.find_all('ul', {'class': 'menuCategory'})
alink3 = alink2[0].find_all('li', {'class':'xans-element-'})
if 0 == len(alink3):
# 대구분만 있을경우
# 디렉토리 작성
makeDir = slashChange(itemTop)
createFolder(makeDir)
# 페이지 읽기
getUrl(makeDir, link1[i-1], itemTop, " ", " ")
else:
# 중분류가 있을경우
for k in range(0,len(alink3)):
alink4 = alink3[k].find_all('a')
# 중분류 소분류 링크 저장
items2 = []
link2 = []
for j in alink4:
items2.append(j.get_text()[:-2])
link2.append(j['href'])
if 1 == len(items2):
# 중분류만 있을경우
# 디렉토리 작성
makeDir = slashChange(itemTop) + "/" + slashChange(items2[0])
createFolder(makeDir)
# 페이지 읽기
getUrl(makeDir, link2[0], itemTop, items2[0], " ")
else:
# 소분류가 있을경우
# 디렉토리 작성
for ind in range(1, len(items2)):
makeDir = slashChange(itemTop) + "/" + slashChange(items2[0]) + "/" + slashChange(items2[ind])
createFolder(makeDir)
# 페이지 읽기
getUrl(makeDir, link2[ind], itemTop, items2[0], items2[ind])
# 데이터 크롤링
urlcwraling()
print("완료했습니다")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib.request
import re
from msgs import cprint, uprint, dprint, fatal
def formatFonts(fonts):
if len(fonts) == 0:
return []
block = []
for localname,googlename in fonts.items():
if getFontClass(localname):
continue
dprint(1, localname + ": " + googlename)
googlename = googlename.replace(' ', '+')
localFile = getGoogleFont(googlename)
block.append("@font-face {\n font-family: '" + localname + "';\n font-style: normal;\n src: url('" + localFile + "');\n}")
return block
def getGoogleFont(name):
cssurl = "http://fonts.googleapis.com/css?family=" + name
try:
with urllib.request.urlopen(cssurl) as r:
contents = r.read().decode('utf-8')
#contents = """
#@font-face {
# font-family: 'Tangerine';
# font-style: normal;
# font-weight: 700;
# src: local('Tangerine Bold'), local('Tangerine-Bold'), url(http://fonts.gstatic.com/s/tangerine/v7/UkFsr-RwJB_d2l9fIWsx3onF5uFdDttMLvmWuJdhhgs.ttf) format('truetype');
#}"""
except urllib.error.URLError as e:
fatal("Cannot find google font " + name + ": " + e.reason)
dprint(1, str(contents))
m = re.search("url\((.*?)\)[ ;]", str(contents))
if not m:
fatal("Bad font file " + cssurl + " from google: " + str(contents))
url = m.group(1)
dprint(1, "Remote ttf: " + url)
with urllib.request.urlopen(url) as r:
ttf = r.read()
# Turn something like Tangerine:bold into Tangerine-bold
#basename = re.sub(":", "-", name)
basename = name.replace(":", "-")
localFile = "images/font-" + basename + ".ttf"
with open(localFile, "wb") as f:
f.write(ttf)
f.close()
dprint(1, "Brought google font into " + localFile)
return localFile
def getFontClass(font):
if font.endswith("-class"):
return font[:-6]
return None
def getFontSpan(font, value):
clazz = getFontClass(font)
if clazz:
return """<span class="{}">""".format(value)
return """<span style="font-family:'{}';">""".format(font)
|
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,BooleanField,SubmitField
from wtforms.validators import DataRequired,Length,Email,EqualTo
class RegistrationForm(FlaskForm):
name=StringField('Name',validators=[DataRequired(),Length(min=2,max=20)])
username=StringField('Username',validators=[DataRequired(),Length(min=2, max=8)])
email=StringField('Email',validators=[DataRequired(),Email()])
password=PasswordField('Password',validators=[DataRequired()])
confirm_password=PasswordField('Confirm Password',validators=[DataRequired(),EqualTo('password')])
submit =SubmitField('Sign up')
class LoginForm(FlaskForm):
email=StringField('Email',validators=[DataRequired(),Email()])
password=PasswordField('Password',validators=[DataRequired()])
remember=BooleanField('Remember me')
submit =SubmitField('Log in')
|
# -*- coding: utf-8 -*-
'''@property 装饰器的用法'''
class Employee:
def __init__(self, name, salary):
self.__name = name #私有方法
self.__salary = salary #私有方法
# python 通过装饰器的写法
@property # 实现get方法,把方法当做是属性,只能看不能修改
def salary(self):
return self.__salary
@salary.setter # 通过装饰器修饰过的setter方法来修改属性
def salary(self, salary):
if 1000 < salary < 300000:
self.__salary = salary
else:
print('输入错误,{0}不在1000--300000之间'.format(salary))
''' #类似java的写法 set,get 方法
def get_salary(self):
return self.__salary
def set_salary(self, salary):
if 1000< salary <300000:
self.__salary = salary
else:
print('输入错误,{0}不在1000--300000之间'.format(salary))
'''
e = Employee('fanwei', 20000)
print(dir(e))
print('------------------------------------')
#python装饰器的写法的调用
print(e.salary) #调用 get
e.salary = 2000 #设置 set
print(e.salary) #调用
e.salary = -2000 #设置 set
print(e.salary) #调用
''' #类似java的写法的调用
print(e.get_salary())
e.set_salary(2000)
print(e.get_salary())
e.set_salary(-2000) #输入值不在范围,修改失败,值不变
print(e.get_salary())
'''
|
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.2'
# jupytext_version: 1.2.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %%
import pubchempy as pcp
import pandas
from pubchempy import Compound, get_compounds
import logging
logging.basicConfig(level=logging.DEBUG)
#Fetch a compound with cid
#c = pcp.Compound.from_cid(5090)
c = Compound.from_cid(1423)
cs1 = get_compounds('Aspirin', 'name')
cs2 = get_compounds('C1=CC2=C(C3=C(C=CC=N3)C=C2)N=C1','smiles')
# %%
#To get 3d information about compounds
cs1 = pcp.get_compounds('Aspirin', 'name', record_type='3d')
cs1
# %%
c.to_dict()
# %%
#Fetch a list of compounds based on cids and print their metadata (schema)
cs_list = []
blocksize = 10
no_blocks = int(250/blocksize)
for i in range(1,no_blocks):
if (i != no_blocks-1):
blockrange = list(range((i-1)*(blocksize)+1,i*blocksize))
cs_list.extend(pcp.get_compounds(blockrange,as_dataframe=False))
if (i == no_blocks-1):
blockrange = list(range((i-1)*(blocksize)+1,250))
cs_list.extend(pcp.get_compounds(blockrange,as_dataframe=False))
# %%
df1 = pcp.compounds_to_frame(cs_list)
df2 = pcp.compounds_to_frame(cs_list, properties=['isomeric_smiles', 'xlogp', 'rotatable_bond_count'])
print(df1.columns)
# %%
fp=open("../Results/metadata_compounds.csv","w")
schema_list = df1.columns.tolist()
for word in schema_list:
fp.write(word+"\n")
fp.close()
# %%
df1.to_csv("../Results/subset_compounds.csv",index=False)
# %%
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 4 14:49:27 2020
@author: nerohmot
"""
from . import command_ABC
class GET_CURR_GAINS(command_ABC):
'''
Description: get a list of the current gains for all rails.
Input: None
Output:
| Index | Name | Type | Description |
|:-----:|:-------------|:--------|:------------------------|
|0 | P12VoD_IGAIN | float32 | Current gain for P12V0D |
|1 | RAIL1_IGAIN | float32 | Current gain for RAIL1 |
|2 | RAIL2_IGAIN | float32 | Current gain for RAIL2 |
|3 | P25V0D_IGAIN | float32 | Current gain for P25V0D |
|4 | P17V0D_IGAIN | float32 | Current gain for P17V0D |
|5 | N7V0D_IGAIN | float32 | Current gain for N7V0D |
|6 | P15V0A_IGAIN | float32 | Current gain for P15V0A |
|7 | N15V0A_IGAIN | float32 | Current gain for N15V0A |
|8 | P5V0D_IGAIN | float32 | Current gain for P5V0D |
|9 | P5V0A_IGAIN | float32 | Current gain for P5V0A |
|10 | N5V0A_IGAIN | float32 | Current gain for N5V0A |
|11 | P3V3D_IGAIN | float32 | Current gain for P3V3D |
|12 | PVLB_IGAIN | float32 | Current gain for PVLB |
|13 | P5V0R_IGAIN | float32 | Current gain for P5V0R |
'''
command = 0x03
sub_command = 0x0A
default_send_payload = b''
def receive(self, DA, ACK, RXTX, PAYLOAD):
line = f"DA={DA} CMD={self.command} SCMD={self.sub_command} ACK={ACK} RXTX={RXTX} PAYLOAD={PAYLOAD}"
self.parent.output_te.append(line)
|
import webbrowser
class Movie:
# The constructor for the Movie class to initialize the values.
def __init__(self,
movie_title,
movie_storyline,
movie_poster_image_url,
movie_trailer_youtube_url):
# Assign values to the Movie class variables
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = movie_poster_image_url
self.trailer_youtube_url = movie_trailer_youtube_url
# This method opens the link in a browser for the selected movie's trailer.
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
|
tam = 12 # matriz é sempre quadrada
op = input()
matriz=[]
# ler os val1
# da matriz
for i in range(tam):
lista = []
for j in range(tam):
valor = float(input())
lista.append(valor)
matriz.append(lista)
#imprimir a matriz
#print(matriz)
# se S entao somar todos elementoss acima da diagonal princial
if (op == 'S'):
total = 0
for i in range(tam):
for j in range(tam):
if not (i>j) and not (i==j):
total += matriz[i][j]
# exibir a soma total acima da diagonal principal
print("{:.1f}".format(total))
# se M então calcular media acima da diagnonal principal
elif (op == 'M'):
total = 0
contador = 0
for i in range(tam):
for j in range(tam):
if not (i>j) and not (i==j):
total += matriz[i][j]
contador = contador + 1
total = total/(contador)
print("{:.1f}".format(total)) |
import webapp2
from controllers.base_controller import BaseController
from google.appengine.api import urlfetch
import secret
import urllib
import json
import state_controller
class OauthController(BaseController):
"""Retrieves data from Google after they are redirected back
after Oauth login"""
#validates google oauth response and sends request for token
#then uses token to retrieve google+ information for accout
def get(self):
redirect_params = secret.oauth_redirect_params()
state = self.request.get('state')
#make sure state matches
if state != state_controller.get_state():
#bad request
self.response.set_status(400)
self.response.write("State variable does not match")
return
#create payload for POST request to validate response from google
#and get toke
authorization_code = self.request.get('code')
validation_payload = secret.oauth_redirect_validation_params()
validation_payload['code'] = authorization_code
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
#post payload, and hopefully retrieve token
#based on: https://cloud.google.com/appengine/docs/python/issue-requests
try:
token_response = urlfetch.fetch(url="https://www.googleapis.com/oauth2/v4/token",
payload=urllib.urlencode(validation_payload),
method=urlfetch.POST,
headers=headers)
if token_response.status_code != 200:
self.response.set_status(token_response.status_code)
self.response.write("Google Oauth validation failed")
return
except urlfetch.Error:
self.response.set_status(500)
self.response.write("Error connecting to Google Oauth for validation")
return
#response is in json, so parse it
token_response_content = json.loads(token_response.content)
#check for token
if 'access_token' not in token_response_content:
self.response.set_status(500)
self.response.write("Error retrieving access token")
return
access_token = token_response_content['access_token']
#get the google+ info
headers = {'Authorization': 'Bearer ' + access_token}
try:
google_plus_response = urlfetch.fetch(url="https://www.googleapis.com/plus/v1/people/me",
method=urlfetch.GET,
headers=headers)
if google_plus_response.status_code != 200:
self.response.set_status(google_plus_response.status_code)
self.response.write("Failed getting Google+ info")
return
except urlfetch.Error:
self.response.set_status(500)
self.response.write("Error getting Google+ info")
return
google_plus_info = json.loads(google_plus_response.content)
#check for errors
if 'error' in google_plus_info:
self.response.set_status(400)
self.response.write("Access token for getting Google+ info was invalid")
return
#if we are here, we got the google+ info, so print it
#check if signed up for Google+
if google_plus_info['isPlusUser'] is False:
self.response.write('You have not signed up for Google+!')
return
#print out first and last name, link to Google+ account, and original state variable
self.response.write('Your first name is: ' + google_plus_info['name']['givenName'] + '<br>')
self.response.write('Your last name is: ' + google_plus_info['name']['familyName'] + '<br>')
self.response.write('The url to your Google+ account is: <a href="' + google_plus_info['url'] + '">'+ google_plus_info['url'] +'</a><br>')
self.response.write('The original state variable was: ' + state)
|
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel("../data/data.xlsx", sheetname="spreads", skiprows=[0, 1],
index_col=0)
df.columns = ["US-AAA", "High-Yield EM", "US-BBB", "High-Yield-US"]
# charts
def gen_chart(df, title, y_title, date_ini):
""""""
plt.style.use("ggplot")
df_final = df[df.index >= date_ini]
# Choose colors from http://colorbrewer2.org/ under "Export"
fig = plt.figure()
ax = fig.add_subplot(111)
df_final.iloc[:, 0].plot(ax=ax, color='red', linewidth=2, legend=True)
#df_final.iloc[:, 0].tail(1).plot(ax=ax, style='-o', color='red', label='')
df_final.iloc[:, 1].plot(ax=ax, color='orange', linewidth=2, legend=True)
#df_final.iloc[:, 1].tail(1).plot(ax=ax, style='-o', color='orange', label='')
df_final.iloc[:, 2].plot(ax=ax, color='blue', linewidth=2, legend=True)
#df_final.iloc[:, 2].tail(1).plot(ax=ax, style='-o', color='blue', label='')
df_final.iloc[:, 3].plot(ax=ax, color='black', linewidth=2, legend=True)
#df_final.iloc[:, 3].tail(1).plot(ax=ax, style='-o', color='black', label='')
# labels labels
for label in ax.xaxis.get_ticklabels():
label.set_fontsize(14)
for label in ax.yaxis.get_ticklabels():
label.set_fontsize(14)
# title
ax.set_title(title, fontsize=24)
ax.title.set_position([.5,1.03])
ax.set_ylabel(y_title)
ax.set_xlabel('')
#margins
ax.margins(0.0, 0.2)
ax.set_xlim(ax.get_xlim()[0]-5, ax.get_xlim()[1]+ 5)
#legend
ax.legend(loc='upper left', fontsize=16)
# label
fig.tight_layout()
return fig
# vix
date_ini = "2013-06-01"
fig_cli = gen_chart(df, "Corporate Credit Spreads", "(%, 100=potential)", date_ini)
plt.savefig("./spreads.png")
|
class shape:
def __init__(self,w,l):
self.width = w
self.len = l
def print_size(self):
print("{}by{}".format(self.width, self.len))
class square(shape):
pass
a_sq = square(20, 25)
a_sq.print_size()
print("git") |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-09-07 09:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('garmin', '0005_auto_20170907_0920'),
]
operations = [
migrations.AlterField(
model_name='usergarmindataactivity',
name='start_time_duration_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='usergarmindataactivity',
name='start_time_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='usergarmindatabodycomposition',
name='start_time_duration_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='usergarmindatabodycomposition',
name='start_time_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='usergarmindatadaily',
name='start_time_duration_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='usergarmindatadaily',
name='start_time_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='usergarmindataepoch',
name='start_time_duration_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='usergarmindataepoch',
name='start_time_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='usergarmindatamanuallyupdated',
name='start_time_duration_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='usergarmindatamanuallyupdated',
name='start_time_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='usergarmindatasleep',
name='start_time_duration_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='usergarmindatasleep',
name='start_time_in_seconds',
field=models.IntegerField(blank=True, null=True),
),
]
|
from collections import Counter
def two_by_two(animals):
if not animals:
return False
return {k: 2 for k, v in Counter(animals).items() if v >= 2}
|
import ipaddress
def validateIp(userIp):
"""Small function to determine if string looks like an IP address in order to avoid
querying the API when user inputs a nonsensical string
:userIp (str): IP address that user inputs
:returns: tuple containing a cleaned-up version of the entered IP address (e.g
converting '1.1.01.1' to '1.1.1.1') and bool of whether the entered IP address
seems to be valid
"""
if userIp is None:
# return None and invalid if there is no search string
return None, False
try:
# try to create IPv4Address or IPv6Address object from string, which is the
# only way for function to return that IP address is valid
return str(ipaddress.ip_address(userIp)), True
except ValueError:
# otherwise, return original string saying that it is invalid
return userIp, False
|
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import dataclasses
import os
import textwrap
from typing import Iterable, Optional
from pants.backend.python.subsystems.debugpy import DebugPy
from pants.backend.python.target_types import (
ConsoleScript,
PexEntryPointField,
ResolvedPexEntryPoint,
ResolvePexEntryPointRequest,
)
from pants.backend.python.util_rules.interpreter_constraints import InterpreterConstraints
from pants.backend.python.util_rules.pex import Pex, PexRequest, VenvPex, VenvPexRequest
from pants.backend.python.util_rules.pex_environment import PexEnvironment, PythonExecutable
from pants.backend.python.util_rules.pex_from_targets import PexFromTargetsRequest
from pants.backend.python.util_rules.python_sources import (
PythonSourceFiles,
PythonSourceFilesRequest,
)
from pants.core.goals.run import RunDebugAdapterRequest, RunRequest
from pants.core.subsystems.debug_adapter import DebugAdapterSubsystem
from pants.engine.addresses import Address
from pants.engine.fs import CreateDigest, Digest, FileContent, MergeDigests
from pants.engine.rules import Get, MultiGet
from pants.engine.target import TransitiveTargets, TransitiveTargetsRequest
from pants.util.frozendict import FrozenDict
def _in_chroot(relpath: str) -> str:
return os.path.join("{chroot}", relpath)
async def _create_python_source_run_request(
address: Address,
*,
entry_point_field: PexEntryPointField,
pex_env: PexEnvironment,
run_in_sandbox: bool,
pex_path: Iterable[Pex] = (),
console_script: Optional[ConsoleScript] = None,
) -> RunRequest:
addresses = [address]
entry_point, transitive_targets = await MultiGet(
Get(
ResolvedPexEntryPoint,
ResolvePexEntryPointRequest(entry_point_field),
),
Get(TransitiveTargets, TransitiveTargetsRequest(addresses)),
)
pex_filename = (
address.generated_name.replace(".", "_") if address.generated_name else address.target_name
)
pex_request, sources = await MultiGet(
Get(
PexRequest,
PexFromTargetsRequest(
addresses,
output_filename=f"{pex_filename}.pex",
internal_only=True,
include_source_files=False,
include_local_dists=True,
# `PEX_EXTRA_SYS_PATH` should contain this entry_point's module.
main=console_script or entry_point.val,
additional_args=(
# N.B.: Since we cobble together the runtime environment via PEX_EXTRA_SYS_PATH
# below, it's important for any app that re-executes itself that these environment
# variables are not stripped.
"--no-strip-pex-env",
),
),
),
Get(
PythonSourceFiles,
PythonSourceFilesRequest(transitive_targets.closure, include_files=True),
),
)
pex_request = dataclasses.replace(pex_request, pex_path=(*pex_request.pex_path, *pex_path))
if run_in_sandbox:
# Note that a RunRequest always expects to run directly in the sandbox/workspace
# root, hence working_directory=None.
complete_pex_environment = pex_env.in_sandbox(working_directory=None)
else:
complete_pex_environment = pex_env.in_workspace()
venv_pex, python = await MultiGet(
Get(VenvPex, VenvPexRequest(pex_request, complete_pex_environment)),
Get(PythonExecutable, InterpreterConstraints, pex_request.interpreter_constraints),
)
input_digests = [
venv_pex.digest,
# Note regarding not-in-sandbox mode: You might think that the sources don't need to be copied
# into the chroot when using inline sources. But they do, because some of them might be
# codegenned, and those won't exist in the inline source tree. Rather than incurring the
# complexity of figuring out here which sources were codegenned, we copy everything.
# The inline source roots precede the chrooted ones in PEX_EXTRA_SYS_PATH, so the inline
# sources will take precedence and their copies in the chroot will be ignored.
sources.source_files.snapshot.digest,
]
merged_digest = await Get(Digest, MergeDigests(input_digests))
chrooted_source_roots = [_in_chroot(sr) for sr in sources.source_roots]
# The order here is important: we want the in-repo sources to take precedence over their
# copies in the sandbox (see above for why those copies exist even in non-sandboxed mode).
source_roots = [
*([] if run_in_sandbox else sources.source_roots),
*chrooted_source_roots,
]
extra_env = {
**complete_pex_environment.environment_dict(python=python),
"PEX_EXTRA_SYS_PATH": os.pathsep.join(source_roots),
}
append_only_caches = (
FrozenDict({}) if venv_pex.append_only_caches is None else venv_pex.append_only_caches
)
return RunRequest(
digest=merged_digest,
args=[_in_chroot(venv_pex.pex.argv0)],
extra_env=extra_env,
append_only_caches={
**complete_pex_environment.append_only_caches,
**append_only_caches,
},
)
async def _create_python_source_run_dap_request(
regular_run_request: RunRequest,
*,
debugpy: DebugPy,
debug_adapter: DebugAdapterSubsystem,
run_in_sandbox: bool,
) -> RunDebugAdapterRequest:
launcher_digest = await Get(
Digest,
CreateDigest(
[
FileContent(
"__debugpy_launcher.py",
textwrap.dedent(
"""
import os
CHROOT = os.environ["PANTS_CHROOT"]
del os.environ["PEX_INTERPRETER"]
import debugpy._vendored.force_pydevd
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
orig_resolve_remote_root = PyDevJsonCommandProcessor._resolve_remote_root
def patched_resolve_remote_root(self, local_root, remote_root):
if remote_root == ".":
remote_root = CHROOT
return orig_resolve_remote_root(self, local_root, remote_root)
PyDevJsonCommandProcessor._resolve_remote_root = patched_resolve_remote_root
from debugpy.server import cli
cli.main()
"""
).encode("utf-8"),
),
]
),
)
merged_digest = await Get(
Digest,
MergeDigests(
[
regular_run_request.digest,
launcher_digest,
]
),
)
extra_env = dict(regular_run_request.extra_env)
extra_env["PEX_INTERPRETER"] = "1"
# See https://github.com/pantsbuild/pants/issues/17540
# and https://github.com/pantsbuild/pants/issues/18243
# For `run --debug-adapter`, the client might send a `pathMappings`
# (this is likely as VS Code likes to configure that by default) with a `remoteRoot` of ".".
#
# For `run`, CWD is the build root. If `run_in_sandbox` is False, everything is OK.
# If `run_in_sandbox` is True, breakpoints won't be hit as CWD != sandbox root.
#
# We fix this by monkeypatching pydevd (the library powering debugpy) so that a remoteRoot of "."
# means the sandbox root.
# See https://github.com/fabioz/PyDev.Debugger/pull/243 for a better solution.
extra_env["PANTS_CHROOT"] = _in_chroot("").rstrip("/") if run_in_sandbox else "."
args = [
*regular_run_request.args,
_in_chroot("__debugpy_launcher.py"),
*debugpy.get_args(debug_adapter),
]
return RunDebugAdapterRequest(
digest=merged_digest,
args=args,
extra_env=extra_env,
append_only_caches=regular_run_request.append_only_caches,
immutable_input_digests=regular_run_request.immutable_input_digests,
)
|
from time import time
from core.event_hub import ClientContext
from utils.timestamp import timestamp
from repository.external_resource_repository import ExternalUser, ExternalChat, ExternalResourceRepository
class ExternalResourceService:
def __init__(self, repo: ExternalResourceRepository):
self._repo = repo
def remember_client(self, client: ClientContext):
telegram = client.telegram
is_pm = telegram.chat_id == telegram.user_id
chat_name = f'{telegram.chat_name} [pm]' if is_pm else telegram.chat_name
user = ExternalUser(telegram.user_id, telegram.user_name, timestamp())
chat = ExternalChat(telegram.chat_id, chat_name, timestamp())
self._repo.remember_user(user)
self._repo.remember_chat(chat)
def get_users(self):
return self._repo.get_users()
def get_chats(self):
return self._repo.get_chats() |
from flask import Flask, render_template, redirect
from data import db_session, jobs, users
from datetime import datetime
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired
class RegisterForm(FlaskForm):
username = StringField('Login / email', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
repeat_password = PasswordField('Repeat assword', validators=[DataRequired()])
surname = StringField('Surname', validators=[DataRequired()])
name = StringField('Name', validators=[DataRequired()])
age = StringField('Age', validators=[DataRequired()])
position = StringField('Position', validators=[DataRequired()])
speciality = StringField('Speciality', validators=[DataRequired()])
address = StringField('Address', validators=[DataRequired()])
submit = SubmitField('Войти')
app = Flask(__name__, template_folder="template/")
app.config['SECRET_KEY'] = 'yandexlyceum_secret_key'
@app.route("/")
def index():
global actions
return render_template("works.html", actions=actions, enumerate=enumerate)
@app.route('/register', methods=['GET', 'POST'])
def reqister():
global session
form = RegisterForm()
if form.validate_on_submit():
if form.password.data != form.repeat_password.data:
return render_template('register.html', title='Регистрация',
form=form,
message="Пароли не совпадают")
if session.query(User).filter(User.email == form.username.data).first():
return render_template('register.html', title='Регистрация',
form=form,
message="Такой пользователь уже есть")
user = User()
user.surname = form.surname.data
user.name = form.name.data
user.age = int(form.age.data)
user.position = form.position.data
user.speciality = form.speciality.data
user.address = form.address.data
user.email = form.username.data
user.set_password(form.password.data)
session.add(user)
session.commit()
return redirect('/register')
return render_template('register.html', title='Регистрация', form=form)
def main():
global actions, session, User
try:
db_session.global_init("db/blogs.sqlite")
session = db_session.create_session()
Jobs = jobs.Jobs
User = users.User
actions = []
for job in session.query(Jobs).all():
user = session.query(User).filter(User.id == job.team_leader).first()
actions.append((job.job, ' '.join([user.name, user.surname]), job.work_size, job.collaborators, job.is_finished))
app.run(debug=False)
except Exception as s:
input(s)
actions = None
session = None
User = None
if __name__ == '__main__':
main() |
"""
Script for analyzing numpy arrays and extracting dF/F from them.
This script takes in a numpy array which is a video file extracted from CaImAn,
and another array which is a mask for each of the neurons.
"""
import os
import numpy as np
import scipy
from scipy import signal
import pyqtgraph as pg
from pyqtgraph import FileDialog
import matplotlib.pyplot as plt
import caiman as cm
import math
def generate_baseline_image(video):
# This function generates a single baseline average image, by average a
# video into a single frame
# Args:
# video : 3D image of dimensions TxYxX to flatten into a YxX image.
return np.sum(video, 0)//video.shape[0]
def get_mask_centroid(mask):
# This function gets the coordinates of the centroid (center of mass) of a
# mask
# Args:
# mask : 2D array as the mask for which to find the center of mass.
# Return should be integers as they are pixel coordinates
maskon = np.argwhere(mask)
center = np.rint(maskon.sum(0)/maskon.shape[0])
return center.astype(int)
def get_mask_shape(mask):
# This function gets the shape of the active area of a mask layer by finding
# the smallest and largest coordinates in each dimension that are True. So
# it returns a rectangular shape
# Args:
# mask : 2D array as the mask for which to find the shape
coords = np.argwhere(mask)
width = np.amax(coords[:,0]) - np.amin(coords[:,0]) + 1
height = np.amax(coords[:,1]) - np.amin(coords[:,1]) + 1
return [width, height]
def extract_neuron_trace_none(video, mask):
# This function extracts an intensity trace for a neuron, without
# subtracting any background (i.e. this is just the spatial average of the
# masked pixels)
# video : 3D video containing neuron
# mask : 2D array masking the neuron we want to extract
neurons = apply_mask(video, mask)
Npix = np.sum(mask)
Nvals = np.zeros(neurons.shape[0])
for t, frame in enumerate(neurons):
Nvals[t]= np.sum(frame)//Npix
return Nvals
def get_mask_rectangle(mask):
# This function gets a rectangle that exactly covers the X and Y dims of
# the mask in question
# Args:
# mask : 2D array as the mask for which to find the shape
# Return is a 2D array as the rectangular outline of the mask.
maskout = np.array(mask, copy=True)
coords = np.argwhere(maskout)
topleft = [np.amin(coords[:,0]), np.amin(coords[:,1])]
botright = [np.amax(coords[:,0]), np.amax(coords[:,1])]
maskout[topleft[0]:botright[0]+1, topleft[1]:botright[1]+1] = True
return maskout
def get_background_mask(mask, method = "rectangle", r=10):
# This function gets the background mask shape of the neuron.
# Args:
# mask : 2D array as the mask for which to find the local background
# method : "rectangle" gets a rectangle surrounding the input mask, with
# dimensions twice the dimensions of the mask on either side.
# "disk" uses a disk shaped kernel to calculate dilation
# function on the input mask.
# "dilation" uses a square shaped kernel to calculate the
# dilation function on the input mask.
# r : radius for disk or edge size for rectangle to use for the kernel.
# Return is a 2D array with the same shape as the mask array, in which the
# local background is 1 but the input mask and external background is 0.
if method=="rectangle":
dims = get_mask_shape(mask)
bgmask = get_mask_rectangle(mask)
bgmask = dilation(bgmask, rectangle(dims[0]+1, dims[1]+1))
return np.logical_xor(bgmask, mask)
elif method=="disk":
dkern = disk(r)
bgmask = dilation(mask, dkern)
return np.logical_xor(bgmask, mask)
elif method=="dilation":
dkern = rectangle(r,r)
bgmask = dilation(mask, dkern)
return np.logical_xor(bgmask, mask)
else:
# default to rectangle
print('Incorrect method specified, defaulting to rectangle')
dims = get_mask_shape(mask)
bgmask = get_mask_rectangle(mask)
bgmask = dilation(bgmask, rectangle(dims[0], dims[1]))
return np.logical_xor(bgmask, mask)
def apply_mask(video, mask):
# This function applies a mask to a video file, returning only the pixels
# of the video which are exposed by the mask. Automatically transposes the
# mask if the video and mask are different dimensions, and if that also
# fails it throws an error
# Args:
# video : 3D array containing video data
# mask : 2D array of bools
try:
return np.multiply(video, mask)
except:
return np.multiply(video, mask.T)
def extract_neuron_trace_uniform(video, mask, flatmask, method = "rectangle", r=10):
# This function extracts an intensity trace for a neuron, subtracting the
# baseline background intensity first with uniform weighting
# video : 3D video containing neuron
# mask : 2D array masking the neuron we want to extract
# flatmask: 2D array of masks of all of the detected neurons
# method : Method for the background calculation
# r : radius/edge length for certain values of method.
# Neuron trace values: apply mask, count number of active pixels (or sum
# values if it is weighted), then sum each frame and divide to average.
Nvid = apply_mask(video, mask)
Npixs = np.sum(mask)
Nvals = np.sum(Nvid, (1,2))//Npixs
# Background trce values: As above but using the calculated background
# masks. Get the background, remove the flatmasks (logical AND of the
# enabled background with the inverse of the enabled flatmask should give
# only the spaces which are unique)
bmask = get_background_mask(mask, method, r)
bmask = np.logical_and(bmask, np.logical_not(flatmask))
Bvid = apply_mask(video, bmask)
Bpixs = np.sum(bmask)
Bvals = np.sum(Bvid, (1,2))//Bpixs
return Nvals, Bavg
def flatten_masks(masks):
# This function flattens a set of individual neuron maks into a single mask
# of all of the neurons. Better than a summation method as there may be
# overlap between neurons.
# Args:
# mask : 3D array of bools of dimension AxXxY to be flattened into a
# 2D array of bools of dimension XxY
maskout = np.copy(masks[0])
for mask in masks:
maskout = np.logical_or(maskout, mask)
return maskout
def filter_movingaverage(tracein, n):
# Performs moving average filtering on an input trace, with filter kernel
# of width N.
# Args:
# tracein : Input trace (1D array)
# n : Filter width
ret = np.cumsum(tracein, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def trace_df(tracein, Nwdw, Nbase):
# Attempts to extract the dF of a trace. dF should be the trace value minus
# the "baseline" trace value, where baseline is a kind of trendline
# corresponding to the neuron's intensity when it is not active.
# This is done by moving a window of width Nwdw across the image, and
# taking the bottom Nbase points within that window to be the "baseline"
# Args:
# tracein : Input trace for which to calculate this.
# Nwdw : Window size for baseline calculation
# Nbase : Number of points to consider to be baseline
l = tracein.shape[0]
base = np.zeros(l)
for i in range(l-Nwdw):
wdw = tracein[i:i+Nwdw]
base[i+Nwdw//2] = np.mean(wdw[np.argpartition(wdw, Nbase)[:Nbase]])
base[0:Nwdw//2] = base[Nwdw//2]
base[l-Nwdw//2:] = base[l-Nwdw//2-1]
return np.subtract(tracein, base), base
def trace_df_f(tracein, Bavg):
# Computes delta-F over F for the input trace and background region. The
# input trace is asssumed to have already had the background average
# subtracted out. This algorithm finds delta-F of the input trace using a
# windowing method (trace_df(tracein, Nwdw, Nbase)), then re-adds the
# background intensity to the calcualted baseline to get F.
# Args:
# tracein : Input trace for which to calculate this
# Bavg : Background intensity trace
df, base = trace_df(tracein, 70, 10)
f = np.add(base, Bavg)
return np.divide(df, f)
def argsort_traces(tracearray):
# Sorts the array of traces by some maximum dF/F. Returns the indices that
# sorts the array
# Args:
# tracearray : NxT array, where N is the number of traces and T is time
maxdff = np.amax(tracearray, axis = -1)
indices = np.argsort(maxdff)
return indices
def mask_joint(maska, maskb, thresh):
# Generates a set of masks that is the overlap between maska and maskb.
# The overlap must contain more pixels than thresh to be kept.
# Args:
# maska : NxXxY array, where N is the number of masks, XxY is the size
# maskb : MxXxY array, where M is the number of masks, XxY is the size
# thresh : Overlap regions with fewer pixels than this are discarded
flata = flatten_masks(maska)
flatb = flatten_masks(maskb)
flatov = np.logical_and(flata, flatb)
masko = []
for mask in maska:
if np.sum(np.logical_and(mask, flatov)) >= thresh:
masko.append(mask)
return np.asarray(masko)
def mask_disjoint(maska, maskb, thresh):
# Generates a set of masks that is the disjoint set of the two masks. Check
# for overlap between any mask area in the sets of maska and maskb, and
# discard when the overlap is greater than thresh pixels.
# Args:
# maska : NxXxY array, where N is the number of masks, XxY is the size
# maskb : MxXxY array, where M is the number of masks, XxY is the size
# thresh : Overlap regions with more pixels than this are discarded
flata = flatten_masks(maska)
flatb = flatten_masks(maskb)
flatov = np.logical_and(flata, flatb)
masko = []
for mask in np.concatenate([maska, maskb], axis=0):
if np.sum(np.logical_and(mask, flatov)) < thresh:
masko.append(mask)
return np.asarray(masko)
def mask_union(maska, maskb, thresh):
# Generates a set of masks that is the set union of the two sets of input
# masks. This is the combination set of the joint and disjoint sets.
# Args:
# maska : NxXxY array, where N is the number of masks, XxY is the size
# maskb : MxXxY array, where M is the number of masks, XxY is the size
# thresh : Neurons with this much overlap are considered to be the same
joint = mask_joint(maska, maskb, thresh)
djoint = mask_disjoint(maska, maskb, thresh)
if not (joint.size>0):
return djoint
if not (djoint.size>0):
return joint
return np.concatenate([joint, djoint], axis=0)
def calculate_dff_set(vid, masks):
# Generates the dF/F curves for a full set of masks for a given video
# Args:
# vid
# masks
flatmask = flatten_masks(masks)
traces = np.empty((masks.shape[0], vid.shape[0]))
bval = np.empty((masks.shape[0], vid.shape[0]))
dff = np.empty((masks.shape[0], vid.shape[0]))
for i, mask in enumerate(masks):
traces[i], bval[i] = extract_neuron_trace_uniform(vid, mask, flatmask, 2)
dff[i] = trace_df_f(traces[i], bval[i])
return dff
def mask_outline(mask):
# Generates a new mask that is the outline shape of a given mask.
# Args:
# mask : Input mask for which to generate the outline
mask_dx = np.diff(mask, n=1, axis=0, prepend=0)
mask_dy = np.diff(mask, n=1, axis=1, prepend=0)
return np.logical_or(mask_dx, mask_dy)
def main():
# Prompt user for directory containing files to be analyzed
F = FileDialog() # Calls Qt backend script to create a file dialog object
mcdir = F.getExistingDirectory(caption='Select Motion Corrected Video Directory')
fvids=[]
for file in os.listdir(mcdir):
if file.endswith("_mc.tif"):
fvids.append(os.path.join(mcdir, file))
# Set up a variable to determine which sections are lightsheet and which
# are epi. This is a horrible way to handle it - need to write new code to
# either automatically determine or prompt user for input.
# Use 1 for lightsheet and 0 for epi.
lsepi = [1, 0, 1, 0, 1, 0, 0, 1, 0]
# Grab the first two masks and assume that they are representative of every
# lightsheet and epi neuron. Also generate an overlap mask by logical ANDing
# the two masks together.
maskLSin = np.transpose(np.load(fvids[0]+'.npy'), axes=(2,1,0))
maskEpiin = np.transpose(np.load(fvids[1]+'.npy'), axes=(2,1,0))
maskLSt = []
maskEpit = []
for mask in maskLSin:
if (np.argwhere(mask).size > 0):
maskLSt.append(mask)
for mask in maskEpiin:
if (np.argwhere(mask).size > 0):
maskEpit.append(mask)
maskLS = np.asarray(maskLSt)
maskEpi = np.asarray(maskEpit)
# Take the first lightsheet vid, find the top N neurons, do the same for
# the first epi vid. Take the 2N masks corresponding to this, find the set
# of unique ones, and then use the remaining masks to go through all of the
# other vids.
N = 14
# Lightsheet:
vid = cm.load(fvids[0])
LSdff = calculate_dff_set(vid, maskLS)
# Epi:
vid = cm.load(fvids[1])
EPdff = calculate_dff_set(vid, maskEpi)
# Sort by top, get the overlap:
threshold = 10
topsLS = argsort_traces(LSdff)
topsEpi = argsort_traces(EPdff)
masks = mask_union(maskLS[topsLS[-N:]], maskEpi[topsEpi[-N:]], threshold)
masksTopLS = mask_disjoint(maskLS[topsLS[-N:]], masks, threshold)
masksTopEpi = mask_disjoint(maskEpi[topsEpi[-N:]], masks, threshold)
maskov = mask_joint(maskLS[topsLS[-N:]], maskEpi[topsEpi[-N:]], threshold)
print(masksTopLS.shape)
print(masksTopEpi.shape)
print(maskov.shape)
# The variable tops now contains the non-overlapping union of the top N
# neurons from epi and from light sheet. Now run through the rest of the
# analyses using only these masks.
# Can grab the top epi and top lightsheet values for each neuron. Can also
# grab on a neuron-by-neuron basis whether the peak dF/F was lightsheet or
# epi.
dff = np.empty((masks.shape[0], 0))
divs = np.zeros(len(fvids))
max_idx = np.zeros((masks.shape[0], 1))
max_val = np.zeros((masks.shape[0], 1))
maxepi_idx = np.zeros((masks.shape[0], 1))
maxepi_val = np.zeros((masks.shape[0], 1))
maxls_idx = np.zeros((masks.shape[0], 1))
maxls_val = np.zeros((masks.shape[0], 1))
flatmask = flatten_masks(masks)
lspeaks = [[] for k in range(masks.shape[0])]
lspeakvals = np.empty((0))
epipeaks = [[] for k in range(masks.shape[0])]
epipeakvals = np.empty((0))
rawtraces = np.empty((masks.shape[0], 0))
rawbckgnd = np.empty((masks.shape[0], 0))
for i, fvid in enumerate(fvids):
vid = cm.load(fvid)
traces = np.empty((masks.shape[0], vid.shape[0]))
bval = np.empty((masks.shape[0], vid.shape[0]))
dff_i = np.empty((masks.shape[0], vid.shape[0]))
for j, mask in enumerate(masks):
traces[j], bval[j] = extract_neuron_trace_uniform(vid, mask, flatmask, 2)
dff_i[j] = trace_df_f(traces[j], bval[j])
peaks, props = scipy.signal.find_peaks(dff_i[j], distance=10, prominence=(0.1, None))
if (peaks.size > 0):
if lsepi[i]:
lspeaks[j].append(peaks)
lspeakvals = np.append(lspeakvals, dff_i[j][peaks])
else:
epipeaks[j].append(peaks)
epipeakvals = np.append(epipeakvals, dff_i[j][peaks])
if (max(dff_i[j]) > max_val[j]):
max_idx[j] = i
max_val[j] = max(dff_i[j])
if lsepi[i]:
maxls_idx[j] = i
maxls_val[j] = max_val[j]
else:
maxepi_idx[j] = i
maxepi_val[j] = max_val[j]
dff = np.concatenate([dff, dff_i], axis = 1)
rawtraces = np.concatenate([rawtraces, traces], axis = 1)
rawbckgnd = np.concatenate([rawbckgnd, bval], axis = 1)
divs[i] = dff.shape[1]
# Save generated values for post-post-processing
masksout = np.transpose(masks, axes=(2,1,0))
np.save(os.path.join(mcdir, 'top_masks_out.npy'), masksout)
np.save(os.path.join(mcdir, 'top_epi_sections.npy'), maxepi_idx)
np.save(os.path.join(mcdir, 'top_epi_values.npy'), maxepi_val)
np.save(os.path.join(mcdir, 'top_ls_sections.npy'), maxls_idx)
np.save(os.path.join(mcdir, 'top_ls_values.npy'), maxls_val)
np.save(os.path.join(mcdir, 'ls_peak_vals.npy'), lspeakvals)
np.save(os.path.join(mcdir, 'epi_peak_vals.npy'), epipeakvals)
np.save(os.path.join(mcdir, 'dff_traces.npy'), dff)
np.save(os.path.join(mcdir, 'dff_div_points.npy'), divs)
# Plot out the dF/F traces, and put vertical markers at the dividers
# between video segments. User would have to manually label them as there's
# no real way to determine what segments are what.
nrow = 6
ncol = 1
dffig, ax = plt.subplots(nrow, ncol, sharex = True, sharey = True)
ll = dff[0].shape[0]
axrange = np.linspace(0, (ll-1)/10, num=ll)
for i, dfft in enumerate(dff):
if i == nrow:
ax[i-1].set_xlabel('Time (seconds)')
break
ax[i].plot(axrange, dfft)
ax[i].set_ylabel(str(i+1))
for div in divs:
ax[i].axvline(div/10, color='r', linestyle='--')
dffig.suptitle('Neuron dF/F Curves')
plt.show()
tfig, ax = plt.subplots(nrow, ncol, sharex = True, sharey = True)
ll = rawtraces[0].shape[0]
axrange = np.linspace(0, (ll-1)/10, num=ll)
for i, tr in enumerate(rawtraces):
if i >= nrow:
ax[i-1].set_xlabel('Time (seconds)')
break
ax[i].plot(axrange, np.add(tr, rawbckgnd[i]))
ax[i].plot(axrange, rawbckgnd[i])
ax[i].set_ylabel(str(i+1))
for div in divs:
ax[i].axvline(div/10, color='r', linestyle='--')
tfig.suptitle('Neuron Raw Traces + Background')
plt.show()
"""
# Next do line plot with averages + error bars.
# Set up lines for a given neuron, showing increase or decrease of max
# intensity on that neuron between lightsheet and epi.
#
intensity_lineplot = np.concatenate([maxepi_val, maxls_val], axis=1).T
avg_ls = np.mean(maxls_val)
std_ls = np.std(maxls_val)/math.sqrt(maxls_val.shape[0])
avg_epi = np.mean(maxepi_val)
std_epi = np.std(maxepi_val)/math.sqrt(maxepi_val.shape[0])
binplot, ax = plt.subplots()
plt.plot(intensity_lineplot)
ax.bar([0, 1], [avg_epi, avg_ls], yerr=[std_epi, std_ls], align='center', capsize=10, alpha=0.5)
ax.set_ylabel('Peak dF/F')
ax.set_xticks([0, 1])
ax.set_xticklabels(['Epi', 'Light-sheet'])
ax.set_title('Contrast change, Epi vs. LS')
plt.show()
"""
# Histogram of spike intensities.
histfig, ax = plt.subplots()
if not (lspeakvals.size>0):
lspeakvals = np.zeros(1)
if not (epipeakvals.size>0):
epipeakvals = np.zeros(1)
binrange = np.amax(np.concatenate([lspeakvals, epipeakvals]))
binrange = 1.5 if binrange >1.5 else math.ceil(binrange*10)/10
binset = np.linspace(0, binrange, num=int(binrange*10+1))
nls = lspeakvals.shape[0]
nepi = epipeakvals.shape[0]
epi_n, epi_bins, epi_patches = ax.hist(epipeakvals, bins=binset, alpha=0.5, label='Epi-illumination', histtype='barstacked', ec='black', lw=0, color='#7f86c1')
ls_n, ls_bins, ls_patches = ax.hist(lspeakvals, bins=binset, alpha=0.5, label='Light-sheet', histtype='barstacked', ec='black', lw=0, color='#f48466')
plt.legend(loc='upper right')
histfig.suptitle('Lightsheet vs. Epi-illumination dF/F')
plt.xlabel('dF/F')
plt.ylabel('Spike Count')
plt.show()
# Plot the image with the contours (outlines of neurons), labeled
Asparse = scipy.sparse.csc_matrix(masksout.reshape((masksout.shape[1]*masksout.shape[0], masksout.shape[2])))
lstop = np.transpose(masksTopLS, axes=(2,1,0))
epitop = np.transpose(masksTopEpi, axes=(2,1,0))
ovtop = np.transpose(maskov, axes=(2,1,0))
AsparseLS = scipy.sparse.csc_matrix(lstop.reshape((lstop.shape[1]*lstop.shape[0], lstop.shape[2])))
AsparseEpi = scipy.sparse.csc_matrix(epitop.reshape((epitop.shape[1]*epitop.shape[0], epitop.shape[2])))
AsparseOv = scipy.sparse.csc_matrix(ovtop.reshape((ovtop.shape[1]*ovtop.shape[0], ovtop.shape[2])))
vid = cm.load(fvids[0])
#Cn = cm.local_correlations(vid.transpose(1,2,0))
Cn = np.zeros((vid.shape[1], vid.shape[2]))
Cn[np.isnan(Cn)] = 0
out=plt.figure()
cm.utils.visualization.plot_contours(Asparse, Cn)
out=plt.figure()
cm.utils.visualization.plot_contours(AsparseLS, Cn)
out=plt.figure()
cm.utils.visualization.plot_contours(AsparseEpi, Cn)
out=plt.figure()
cm.utils.visualization.plot_contours(AsparseOv, Cn)
scipy.io.savemat(os.path.join(mcdir, 'epi_histogram.mat'), {'n':epi_n, 'bins':epi_bins, 'patches':epi_patches})
scipy.io.savemat(os.path.join(mcdir, 'ls_histogram.mat'), {'n':ls_n, 'bins':ls_bins, 'patches':ls_patches})
scipy.io.savemat(os.path.join(mcdir, 'epi_spike_values.mat'), {'epispikes':epipeakvals})
scipy.io.savemat(os.path.join(mcdir, 'ls_spike_values.mat'), {'lsspikes':lspeakvals})
scipy.io.savemat(os.path.join(mcdir, 'df_over_f.mat'), {'data':dff, 'indices_between_ls_or_epi':divs})
scipy.io.savemat(os.path.join(mcdir, 'rawtraces.mat'), {'data':rawtraces, 'indices_between_ls_or_epi':divs})
scipy.io.savemat(os.path.join(mcdir, 'rawbackground.mat'), {'data':rawbckgnd, 'indices_between_ls_or_epi':divs})
if __name__ == "__main__":
main() |
from Pyskell.Language.TypeClasses import *
from Pyskell.Language.Syntax import __
from Pyskell.Language.EnumList import *
from Pyskell.Language.PyskellTypeSystem import *
from Pyskell.Language.Syntax.Pattern import *
from Pyskell.Language.Syntax.Guard import *
from Pyskell.Language.Syntax.ADTs import *
from Pyskell.Language.EnumList import *
import unittest
class TypedFuncTest(unittest.TestCase):
def test_typed_func(self):
@TS(C / int >> bool >> str)
def some_func(int_var, bool_var):
return str(int_var) + str(bool_var)
@TS(C / (C / "a" >> "b" >> "c") >> "b" >> "a" >> "c")
def flipper(fn, y, _x):
return fn(_x, y)
self.assertEqual(flipper % some_func % False * (__ + 1) % 1, "2False")
@TS(C[(Show, "a"), (Show, "b")] / "a" >> "b" >> str)
def show_2(var1, var2):
return show(var1) + show(var2)
self.assertEqual(show_2 % 1 * show % 12, "112")
self.assertEqual(str(type_of(show * ((__ + " verb test") ** (C / str >> str)))),
"(str -> str)")
|
import os, sys, time
import pickle
from argparse import ArgumentParser
import xml.etree.ElementTree as ET
import numpy as np
import scipy
from sklearn.preprocessing import normalize
_LightGray = '\x1b[38;5;251m'
_Bold = '\x1b[1m'
_Underline = '\x1b[4m'
_Orange = '\x1b[38;5;215m'
_SkyBlue = '\x1b[38;5;38m'
_Reset = '\x1b[0m'
class EventTimer():
def __init__(self, name = '', description = ''):
self.name = name
self.description = description
def __enter__(self):
print(_LightGray + '------------------ Begin "' + _SkyBlue + _Bold + _Underline + self.name + _Reset + _LightGray +
'" ------------------' + _Reset, file = sys.stderr)
self.beginTimestamp = time.time()
def __exit__(self, type, value, traceback):
elapsedTime = time.time() - self.beginTimestamp
print(_LightGray + '------------------ End "' + _SkyBlue + _Bold + _Underline + self.name + _Reset + _LightGray +
' (Elapsed ' + _Orange + f'{elapsedTime:.4f}' + _Reset + 's)" ------------------' + _Reset + '\n', file = sys.stderr)
def getArguments():
parser = ArgumentParser()
parser.add_argument('-r', action = 'store_true',
help = 'If specified, turn on relevance feedback.')
parser.add_argument('-c', type = str, nargs = 1, metavar = 'my-model-dir',
help = 'My model directory')
parser.add_argument('-i', type = str, nargs = 1, metavar = 'query-file',
help = 'The input query file')
parser.add_argument('-o', type = str, nargs = 1, metavar = 'ranked-list',
help = 'The output ranked list file')
parser.add_argument('-m', type = str, nargs = 1, metavar = 'model-dir',
help = 'The input model directory')
parser.add_argument('-d', type = str, nargs = 1, metavar = 'NTCIR-dir',
help = 'The directory of NTCIR documents.')
parser.add_argument('--preprocessing', action = 'store_true',
help = 'Perform preprocessing')
parser.add_argument('--tfidf', action = 'store_true',
help = 'Calculate TFIDF')
parser.add_argument('--model-name', type = str, nargs = 1, metavar = 'MODEL-NAME', dest = 'name',
help = 'The name used in TF IDF models')
return parser.parse_args()
def SavePkl(obj, path):
with open(path, 'wb') as f:
pickle.dump(obj, f)
def LoadPkl(path):
with open(path, 'rb') as f:
return pickle.load(f)
def SaveSPM(matrix, path):
scipy.sparse.save_npz(path, matrix)
def LoadSPM(path):
return scipy.sparse.load_npz(path)
def SaveNPY(array, path):
np.save(path, array)
def LoadNPY(path):
return np.load(path)
def getVocabularies(vocFilePath):
with open(vocFilePath, 'rb') as f:
encoding = f.readline().strip().decode()
rawLines = f.readlines()
ID2Voc = {i + 1 : v for i, v in enumerate(map(lambda s : s.strip().decode(encoding), rawLines))}
Voc2ID = {v : k for k, v in ID2Voc.items()}
return ID2Voc, Voc2ID
def getFileList(fileListPath, docDirectory):
with open(fileListPath, 'r') as f:
return list(map(lambda l : os.path.join(docDirectory, l.strip()), f.readlines()))
def getDocumentIDs(docList):
def getID(doc):
root = ET.parse(doc).getroot().find('doc')
return root.find('id').text
return list(map(getID, docList))
def getQueryList(queryFilePath):
# Returns a document of (ID, title, question, narrative, concept)
tree = ET.parse(queryFilePath)
root = tree.getroot()
queries = [{ele.tag : ele.text.strip() for ele in topic} for topic in root]
for q in queries:
q['concepts'] = q['concepts'].split('、')
return queries
def translateQuery(queryList, terms, Voc2ID, features = [], weights = None):
term2ID = {t : i for i, t in enumerate(terms)}
def str2Tokens(s):
return [Voc2ID[c] if c in Voc2ID else 0 for c in s]
def tokens2Terms(l):
ret = []
for u in l:
if u in term2ID:
ret.append(term2ID[u])
for b in zip(l[:-1], l[1:]):
if b in term2ID:
ret.append(term2ID[b])
return ret
def trans(Q):
ret = np.zeros(len(terms))
for q in Q:
ret[q] += 1
return ret
if weights is None:
weights = [1] * len(features)
assert len(features) == len(weights), "The weights length should be the same as features"
queryIDs = []
queryVectors = []
for query in queryList:
vec = np.zeros(len(terms))
for f, w in zip(features, weights):
if f == 'concepts':
for c in query[f]:
Q = tokens2Terms(str2Tokens(c))
vec += trans(Q) * w
else:
Q = tokens2Terms(str2Tokens(query[f]))
vec += trans(Q) * w
queryIDs.append(query['number'][-3:])
queryVectors.append(vec)
return queryIDs, normalize(np.stack(queryVectors), axis = 1, copy = False)
|
#!/usr/bin/env python
# coding=utf-8
from torch.utils.data import DataLoader
import torch
#from DogsDataset import DogsDataset
from RAPDataset import RAPDataset
from GlassesDataset import GlassesDataset
from InceptionV3 import *
from HydraPlusNet import *
import skimage.io as io
from torch.autograd import Variable
import matplotlib.pyplot as plt
from torchvision import transforms
from torchvision import models
from torch import nn
import numpy as np
import logging
import os.path
import time
learning_rate = 0.0001
num_class = 51
train_batch_size = 32 #60000/64=937.5
test_batch_size = 8
image_rate = 1 #每张图片经过预处理扩展的倍数
iter_display = 100 #迭代多少次显示一次
num_epoch = 200
is_test = True #决定是否进行训练过程中的测试
test_iterval = 500 #每训练多少次进行一次测试
iter_save = 500 #美巡多少次进行一次参数保存 可用于断点训练
save_path = "./weight/InceptionV3" #参数保存路径 会在后面加后缀 例如 ./weight/AlexNet_1000.weight
load_path = "./weight/InceptionV3_24000.weight" #参数读取路径
use_save_parameter = False #决定是否使用保存参数
checkpoint_train = False #决定是否进行断点训练
#test_iter = 150 #测试进行多少次 10000/64 = 156
#label_name = ["Female","AgeOver60","Age18-60","AgeLess18","Front","Side", #PA100K
# "Back","Hat","Glasses","HandBag","ShoulderBag","Backpack","HoldObjectsInFront",
# "ShortSleeve","LongSleeve","UpperStride","UpperLogo","UpperPlaid","UpperSplice",
# "LowerStripe","LowerPattern","LongCoat","Trousers","Shorts","Skirt&Dress","boots"]
#label_name = ["personalLess30","personalLess45","personalLess60","personalLarger60","carryingBackpack", #PETA
# "carryingOther","lowerBodyCasual","upperBodyCasual","lowerBodyFormal","upperBodyFormal",
# "accessoryHat","upperBodyJacket","lowerBodyJeans","footwearLeatherShoes","upperBodyLogo",
# "hairLong","personalMale","carryingMessengerBag","accessoryMuffler","accessoryNothing",
# "carryingNothing","upperBodyPlaid","carryingPlasticBags","footwearSandals","footwearShoes",
# "lowerBodyShorts","upperBodyShortSleeve","lowerBodyShortSkirt","footwearSneaker","upperBodyThinStripes",
# "accessorySunglasses","lowerBodyTrousers","upperBodyTshirt","upperBodyOther","upperBodyVNeck"]
label_name = ["Female","AgeLess16","Age17-30","Age31-45","BodyFat","BodyNormal","BodyThin","Customer","Clerk", #RAP
"BaldHead","LongHair","BlackHair","Hat","Glasses","Muffler","Shirt","Sweater","Vest","TShirt",
"Cotton","Jacket","Suit-Up","Tight","ShortSleeve","LongTrousers","Skirt","ShortSkirt","Dress",
"Jeans","TightTrousers","LeatherShoes","SportShoes","Boots","ClothShoes","CasualShoes",
"Backpack","SSBag","HandBag","Box","PlasticBag","PaperBag","HandTrunk","OtherAttchment",
"Calling","Talking","Gathering","Holding","Pusing","Pulling","CarryingbyArm","CarryingbyHand"]
#日志设置
#第一步 创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#第二步 创建两个handler 一个写入日志文件 一个打印屏幕
rq = time.strftime("%Y%m%d%H%M",time.localtime(time.time()))
log_name = "./" + rq + ".log"
file_handler = logging.FileHandler(log_name,mode= "w")
file_handler.setLevel(logging.INFO)
print_handler = logging.StreamHandler()
print_handler.setLevel(logging.DEBUG)
#第三步 设置两个handler的输出格式
file_formatter = logging.Formatter("%(asctime)s-%(filename)s[line:%(lineno)d] - %(levelname)s:%(message)s")
file_handler.setFormatter(file_formatter)
#第四步 将handler添加到logger里
logger.addHandler(file_handler)
logger.addHandler(print_handler)
#logger.debug("debug")
#logger.info("info")
#logger.warning("warning")
#logger.error("error")
#logger.critical("critical")
torch.cuda.set_device(0)
train_dataset = RAPDataset("/home/dataset/human_attribute/RAP/RAP_annotation/train.txt",
transform = transforms.Compose([transforms.ToPILImage(),transforms.ColorJitter(0.05,0.05,0.05),transforms.RandomHorizontalFlip(),transforms.Resize(320),transforms.RandomCrop((299,299)),transforms.ToTensor()]))
test_dataset = RAPDataset("/home/dataset/human_attribute/RAP/RAP_annotation/test.txt",
transform = transforms.Compose([transforms.ToPILImage(),transforms.Resize(320),transforms.RandomCrop((299,299)),transforms.ToTensor()]))
train_loader = DataLoader(train_dataset,train_batch_size,True) #数据加载器 主要实现了批量加载 数据打乱 以及并行化读取数据 pytorch自带 也可以自己实现
test_loader = DataLoader(test_dataset,test_batch_size,True)
#inception_v3 = Inception3(26,False,False) #实例化类LeNet 实际上也调用了LeNet的__init__()函数
hydraplus_net = HydraPlusNet(num_class,is_fusion = False)
#alex_model.initialize_parameters()
#从pytorch官方的预训练模型复制参数
inception_v3_pretrain = models.inception_v3(True) #使用pytorch的预训练模型
pretrain_dict = inception_v3_pretrain.state_dict()
hydraplus_net_dict = hydraplus_net.state_dict()
pretrain_dict = {k:v for k,v in pretrain_dict.items() if k in hydraplus_net_dict}
hydraplus_net_dict.update(pretrain_dict)
hydraplus_net.load_state_dict(hydraplus_net_dict)
hydraplus_net = hydraplus_net.cuda() #转移到GPU上
logger.info(hydraplus_net)
optimizer = torch.optim.SGD(hydraplus_net.parameters(),learning_rate,0.99,0.0005) #实例化一个SGD优化器 参数:需要更新的参数 学习率 momentum(默认为0) 正则化项系数(默认为0) dampening(动量抑制因子 默认为0) nesterov(是否使用Nesterov 默认为false)
#loss_func = torch.nn.CrossEntropyLoss() #softmax loss函数
weight = torch.Tensor([1.7226262226969686, 2.6802565029531618, 1.0682133644154836, 2.580801475214588,
1.8984257687918218, 2.046590013290684, 1.9017984669155032, 2.6014006200502586,
2.272458988404639, 2.2625669787021203, 2.245380512162444, 2.3452980639899033,
2.692210221689372, 1.5128949487853383, 1.7967419553099035, 2.5832221110933764,
2.3302195718894034, 2.438480257574324, 2.6012705532709526, 2.704589108443237,
2.6704246374231753, 2.6426970354162505, 1.3377813061118478, 2.284449325734624,
2.417810793601295, 2.7015143874115033])
loss_func = torch.nn.BCEWithLogitsLoss()
loss_func.cuda()
start_epoch = 0
#读取断点训练参数
if use_save_parameter == True:
checkpoint = torch.load(load_path)
pretrain_dict = checkpoint["net"]
model_dict = hydraplus_net.state_dict()
pretrain_dict = {k:v for k,v in pretrain_dict.items() if k in model_dict}
model_dict.update(pretrain_dict)
hydraplus_net.load_state_dict(model_dict)
# alex_model.load_state_dict(checkpoint["net"])
if checkpoint_train == True:
optimizer.load_state_dict(checkpoint["optimizer"])
start_epoch = checkpoint["epoch"] +1
logger.info("success to load parameter")
train_loss = 0.0
train_acc = 0.0
test_loss = 0.0
test_acc = 0.0
num_iter = 0
recoder = {"num_iter":[],"train_loss":[],"train_acc":[],"test_loss":[],"test_acc":[]}
logger.info("start_epoch:%d",start_epoch)
for epoch in range(start_epoch,num_epoch):
for batch_img,batch_label in train_loader:
num_iter += 1
# print type(batch_img)
# print type(batch_label)
# print batch_label.shape
batch_img = Variable(batch_img.cuda()) #将数据拷贝到GPU上运行,并且放入到Variable中
batch_label = Variable(batch_label.cuda())
hydraplus_net.train()
output = hydraplus_net(batch_img) #进行前向计算
# print output #output输出为batch_size*10
# print batch_label.data.size()
loss = loss_func(output,batch_label) #计算loss 此loss已经在一个batch_size上做了平均
# print loss.shape #loss输出为一个标量
# train_loss += loss.item()
train_loss += loss.item()
result = (output>= 0) #输出大于等于0的设为1,小于0的设为0
result = result.float()
# print result
train_correct = torch.sum((result == batch_label),0) #统计一个batch中预测正确的数量
# print "train_correct:",train_correct.size()
# print train_acc
train_correct = train_correct.cpu().numpy() #转成numpy
train_acc += train_correct
# print "train_acc:",train_acc
#反向传播
hydraplus_net.zero_grad() #因为梯度是累计的 所以先将梯度清0
loss.backward() #将自动计算所有可学习参数的梯度
optimizer.step() #调用优化器来更新参数
#显示设置
if(num_iter % iter_display == 0 or num_iter == 1):
logger.info("iter_num:%d",num_iter)
if num_iter == 1:
k = 1
else:
k = iter_display
train_loss = train_loss/k
train_acc = train_acc/float(k*train_batch_size*image_rate)
recoder["num_iter"].append(num_iter)
recoder["train_loss"].append(train_loss)
recoder["train_acc"].append(train_acc)
logger.info("train loss:%f",train_loss)
logger.info("train acc:")
for i in range(num_class):
logger.info("%s:%f",label_name[i],train_acc[i])
logger.info("mAP:%f",np.sum(train_acc)/num_class)
train_loss = 0
train_acc = 0
#测试
if(is_test and (num_iter % test_iterval == 0)):
test_loss = 0
test_acc = 0
test_num_iter = 0
hydraplus_net.eval()
##################
# TP = [0.0] *26
# P = [0.0] *26
# TN = [0.0] *26
# N = [0.0] *26
# Acc = 0.0
# Prec = 0.0
# Rec = 0.0
###################
for test_batch_img,test_batch_label in test_loader:
#####################
# Yandf = 0.1
# Yorf = 0.1
# Y = 0.1
# f = 0.1
######################
# print test_batch_img.shape
test_num_iter += 1
#test_batch_img = test_batch_img.view(-1,test_batch_img.shape[2],test_batch_img.shape[3],test_batch_img.shape[4])
# test_batch_img = test_batch_img.view(-1,test_batch_img.shape[2],test_batch_img.shape[3],test_batch_img.shape[4])
# test_batch_label = test_batch_label.view(test_batch_label.shape[0]*test_batch_label.shape[1])
#test_batch_label = test_batch_label.view(test_batch_label.shape[0])
test_batch_img = Variable(test_batch_img.cuda())
test_batch_label = Variable(test_batch_label.cuda())
# bs,ncrops,c,h,w = test_batch_img.size()
output = hydraplus_net(test_batch_img) #测试前向计算
# output_avg = output.view(bs,ncrops,-1).mean(1)
loss = loss_func(output,test_batch_label)
test_loss += loss.item()
# test_loss += loss.data[0]
# print test_batch_label.data
result = (output>=0)
result = result.float()
test_correct = torch.sum((result == test_batch_label),0)
test_correct = test_correct.cpu().numpy()
test_acc += test_correct
#############################
i = 0
#print output.shape
# for item in output[0]:
# if item.data[0] > 0:
# f = f+1
# Yorf = Yorf + 1
# if test_batch_label[0][i].data[0] == 1:
# TP[i] = TP[i] + 1
# P[i] = P[i] + 1
# Y = Y +1
# Yandf = Yandf + 1
# else:
# N[i] = N[i] + 1
# else:
# if test_batch_label[0][i].data[0] == 0:
# TN[i] = TN[i] + 1
# N[i] = N[i] + 1
# else:
# P[i] = P[i] + 1
# Yorf = Yorf + 1
# Y = Y +1
# i = i +1
# Acc = Acc + Yandf/Yorf
# Prec = Prec + Yandf/f
# Rec = Rec + Yandf/Y
#################################
test_loss = test_loss/test_num_iter
test_acc = test_acc/float(len(test_dataset))
recoder["test_loss"].append(test_loss)
recoder["test_acc"].append(test_acc)
logger.info("test loss:%f",test_loss)
logger.info("test acc:")
mAP = 0
for i in range(num_class):
logger.info("%s:%f",label_name[i],test_acc[i])
logger.info("mAP:%f",np.sum(test_acc)/num_class)
#####################################
# Accuracy = 0
# for l in range(26):
# # print("%s : %f" %(classes[l],(TP[l]/P[l] + TN[l]/N[l])/2))
# Accuracy = TP[l]/P[l] + TN[l]/N[l] + Accuracy
# meanAccuracy = Accuracy/52
# Acc = Acc/10000
# Prec = Prec/10000
# Rec = Rec/10000
# F1 = 2*Prec*Rec/(Prec+Rec)
# print "mA:",meanAccuracy
# print "Acc:",Acc
# print "Prec:",Prec
# print "Rec:",Rec
# print "F1:",F1
#参数保存
if(num_iter % iter_save == 0):
state = {"net":hydraplus_net.state_dict(),"optimizer":optimizer.state_dict(),"epoch":epoch}
full_save_path = save_path +"_" + str(num_iter) +".weight"
torch.save(state,full_save_path)
logger.info("success to save parameter")
#训练完成 再进行一次存储权重
state = {"net":hydraplus_net.state_dict(),"optimizer":optimizer.state_dict(),"epoch":epoch}
full_save_path = save_path +"_" + str(num_iter) +".weight"
torch.save(state,full_save_path)
#绘图
plt.figure("loss")
plt.plot(recoder["num_iter"],recoder["train_loss"])
x = []
for iter in recoder["num_iter"]:
if iter % test_iterval ==0:
x.append(iter)
plt.plot(x,recoder["test_loss"])
plt.figure("acc")
plt.plot(recoder["num_iter"],recoder["train_acc"])
plt.plot(x,recoder["test_acc"])
plt.show()
|
#!/usr/bin/python
from numpy import count_nonzero
tau_seq = 'MAEPRQEFEVMEDHAGTYGLGDRKDQGGYTMHQDQEGDTDAGLKESPLQTPTEDGSEEPGSETSDAKSTPTAEDVTAPLVDEGAPGKQAAAQPHTEIPEGTTAEEAGIGDTPSLEDEAAGHVTQARMVSKSKDGTGSDDKKAKGADGKTKIATPRGAAPPGQKGQANATRIPAKTPPAPKTPPSSGEPPKSGDRSGYSSPGSPGTPGSRSRTPSLPTPPTREPKKVAVVRTPPKSPSSAKSRLQTAPVPMPDLKNVKSKIGSTENLKHQPGGGKVQIINKKLDLSNVQSKCGSKDNIKHVPGGGSVQIVYKPVDLSKVTSKCGSLGNIHHKPGGGQVEVKSEKLDFKDRVQSKIGSLDNITHVPGGGNKKIETHKLTFRENAKAKTDHGAEIVYKSPVVSGDTSPRHLSNVSSTGSIDMVDSPQLATLADEVSASLAKQGL'
"""
with open('fibril_wt_set-d-selected-columns-relevant-2N4R-records.txt', 'r') as r:
ms_raw = [line.strip().split('\t') for line in r.readlines()]
header=ms_raw.pop(0)
# Cuts treated as downstream, i.e. a cut at residue 2 breaks the bond between residues 2 and 3, not 1 and 2
cut_counts = [[0 for j in range(440)] for i in range(4)]
cut_intensities = [[0 for j in range(440)] for i in range(4)]
for line in ms_raw:
if not 'N/A' in line[0:2]:
cleave_sites = [int(line[0])-1, int(line[1])]
# cleavage is upstream of peptide start, downstream of peptide end
expt_count = [float(count_nonzero([int(i) for i in line[ 7:10]])) / 3, float(count_nonzero([int(i) for i in line[10:13]])) / 3, float(count_nonzero([int(i) for i in line[13:16]])) / 3, float(count_nonzero([int(i) for i in line[16:19]])) / 3]
expt_intensity = [sum([int(i) for i in line[ 7:10]]), sum([int(i) for i in line[10:13]]), sum([int(i) for i in line[13:16]]), sum([int(i) for i in line[16:19]])]
for i in range(4):
for site in cleave_sites:
if site != 441:
cut_counts[i][site - 1] += expt_count[i]
cut_intensities[i][site - 1] += expt_intensity[i]
with open('intensities_by_site.txt', 'w') as o:
o.write('site\t' + '\t'.join(['10min', '60min', '180min', 'overnight'] * 2) + '\n')
for n, i in enumerate(range(1,440)):
ints = [str(i)]
ints += [str(cut_counts[x][n]) for x in range(4)]
ints += [str(cut_intensities[x][n]) for x in range(4)]
o.write('\t'.join(ints) + '\n')
"""
with open('Export_MS_data.txt', 'r') as r:
txt=r.readlines()
with open('ehrmann_tau_ms_excerpts.txt','w') as w:
w.write(txt[0])
for l in txt[2::2]:
if l.split('\t')[0] in tau_seq:
w.write(txt[1])
w.write(l)
def pick_expt_columns(first_expt_col, num_expts, num_cond, reps):
"""
Generates lists of the columns within the mass spec data that correspond
to each experiment and condition
Requires list to be ordered by UMSAP
first_expt_col is the first column with experimental data
num_expts is the number of different experimental sets
ex: WT, WT+SA, WT+SA_dPDZ
num_cond is the number of conditions for each experimental set
ex: 4 if samples were taken at 10min, 1 hour, 3 hours, and overnight
reps is the number of repetitions for each point, ex: 3
"""
num_cols_per_expt = num_cond * reps
last_expt_col = first_expt_col + num_expts * num_cols_per_expt
e_cols = []
for i in range(first_expt_col, last_expt_col, num_cols_per_expt):
c = [list(range(j, j + reps)) for j in range(i, i + num_cols_per_expt, reps)]
e_cols.append(c)
return e_cols
class expt_ms_set:
def __init__(self, ms_set, expt_cols, prot_len):
self.ms_set = ms_set
self.expt_cols = expt_cols
self.prot_len = prot_len
self.cut_counts = [[0 for j in range(prot_len - 1)] for i in range(len(self.expt_cols))]
self.cut_intensities = [[0 for j in range(prot_len - 1)] for i in range(len(self.expt_cols))]
self.populate_counts()
def populate_counts(self):
"""
Go through each line (with each line corresponding to an identified
protein fragment) of the data file and do the folowing:
1: Identify the cleavage sites demonstrated by that fragment. These
are the residue just before the fragment and the last residue in the
fragment, unless either is a terminal residue. These numbers are in
the first column of each line.
2: In the columns specific to this data set (given at construction),
collect two values across all repetitions for each sample condition.
The values are the average number of reps in which any cleavage
activity was identified, and the total intensity of the identified
fragment.
3: Add the collected values to the appropriate sites in a list of all
sites in the target protein. Thus multiple fragments with an end
corresponding to a cut site will produce values for that site which
are the sum of all counts/sums for each fragment.
"""
for line in self.ms_set:
# cleavage is upstream of peptide start, downstream of peptide end
cleave_sites = [int(line[0])-1, int(line[1])]
frag_counts = []
frag_intensities = []
for c in self.expt_cols:
frag_counts.append(float(count_nonzero([int(line[i]) for i in c])) / len(c))
frag_intensities.append(sum([int(line[i]) for i in c]))
for i in range(len(self.expt_cols)):
for site in cleave_sites:
if site not in [1, self.prot_len]:
self.cut_counts[i][site - 1] += frag_counts[i]
self.cut_intensities[i][site - 1] += frag_intensities[i]
my_cols = pick_expt_columns(7, 6, 4, 3)
the_sets = []
for x in my_cols:
the_sets.append(expt_ms_set(ms_raw, x, 441))
lines_out = []
for i in range(440):
line = []
for j in range(6):
for k in range(4):
line.append(the_sets[j].cut_counts[k][i])
for k in range(4):
line.append(the_sets[j].cut_intensities[k][i])
lines_out.append(line)
with open('intensities_by_site.txt', 'w') as o:
for l in lines_out:
line_text = '\t'.join([str(i) for i in l]) + '\n'
o.write(line_text)
|
from dbconnection import DatabaseConnection
from superuser import SuperUser
from config import Settings
from take_quiz import TakeQuiz
class MainQuiz:
def __init__(self):
self.dbc = DatabaseConnection()
self.su = SuperUser(self.dbc)
self.tq = TakeQuiz(self.dbc)
def display_message(self):
print(" Welcome To the Quiz Application....!! ")
print(" Please Select one of the following options...!!")
print(" Press 1 to Add/Delete Questions (NOTE: You can add questions only if you are admin/superuser) ....!!")
print(" Press 2 to Take Part in the Quiz...!!")
print(" Press 3 to Quit....!!")
print("Enter Your Choice....!!")
def run(self):
choice = None
while True:
self.display_message()
choice = input()
if choice == "1":
uname= input("Enter your username...!! ")
pa= input("Enter your Password...!! ")
self.su.validate_credentials(uname,pa)
elif choice == "2":
self.tq.run()
else:
self.dbc.close_conection()
print("Thank You..!!")
break
if __name__=='__main__':
mq = MainQuiz()
mq.run()
|
# !/usr/bin/env python
# pylint: disable=C0116
import os
from telegram.ext import Updater, CommandHandler
from threading import Timer
import time
from callbacks import CallBacks
bot_key: str = os.environ['BOT_KEY']
class RepeatTimer(Timer):
def run(self) -> None:
while not self.finished.wait(self.interval):
self.function(*self.args, **self.kwargs)
print("done")
def main() -> None:
# Print "Starting up"
print("Spinning up the bot ...")
# Create the Updater and pass it your bots token.
updater = Updater(bot_key)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# on different commands - answer in Telegram
dispatcher.add_handler(CommandHandler("track", CallBacks.track_channel))
timer = RepeatTimer(1, CallBacks.check_channels)
timer.start()
# Start the Bot
updater.start_polling()
print("Polling started")
# Block until you press Ctrl-C or the process receives SIGINT, SIGTERM or
# SIGABRT. This should be used most of the time, since start_polling() is
# non-blocking and will stop the bot gracefully.
updater.idle()
timer.cancel()
if __name__ == '__main__':
main()
|
from __future__ import print_function
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as anim
from tqdm import tqdm
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
import torch
from torch import nn,optim
from torch.utils.data import TensorDataset, DataLoader
from torchvision import datasets, transforms
import torch.backends.cudnn as cudnn
class View(nn.Module):
def __init__(self, shape):
super().__init__()
self.shape = shape
def forward(self, x):
return x.view(*self.shape)
# I want this program to run on CUDA.
# However, runs without it. How come?
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--no-cuda', action='store_true', default='False')
args = parser.parse_args()
use_cuda = (not args.no_cuda) and torch.cuda.is_available()
print(args.no_cuda)
print(torch.cuda.is_available())
print(use_cuda)
print(args)
# idk why this line dosen't run correctly. tell me.
#device = torch.device('cuda' if use_cuda else 'cpu')
device = torch.device('cuda')
print(device)
ds_train = datasets.MNIST('../dataset', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
]))
ds_test = datasets.MNIST('../dataset', train=False,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
]))
kwargs = {'num_workers': 4, 'pin_memory': True}
train_loader = DataLoader(ds_train, batch_size=64, shuffle=True, **kwargs)
test_loader = DataLoader(ds_test, batch_size=64, shuffle=False, **kwargs)
#disp_ds(ds_train, 10)
model = nn.Sequential()
model.add_module('view1', View((-1, 28*28)))
model.add_module('fc1', nn.Linear(28*28*1, 100))
model.add_module('relu1', nn.ReLU())
model.add_module('fc2', nn.Linear(100, 100))
model.add_module('relu2', nn.ReLU())
model.add_module('fc3', nn.Linear(100, 10))
model.to(device)
#cudnn.benchmark = True
loss_fn = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-2)
for epoch in tqdm(range(1, 11)):
train(model, device, train_loader, loss_fn, optimizer, epoch)
test(model, device, test_loader, loss_fn)
def get_mnsit():
return fetch_openml('MNIST original', data_home='./datasets/')
def disp_ds(ds, num=None):
if num is None: num = 100
fig = plt.figure()
ims = []
for i in range(num):
img = ds[i][0].numpy().reshape(28, 28)
ims.append([plt.imshow(img)])
animation = anim.ArtistAnimation(fig, ims, interval=100, repeat=False)
plt.show()
def train(model, device, train_loader, loss_fn, optimizer, epoch):
model.train()
for data, target in tqdm(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = loss_fn(output, target)
loss.backward()
optimizer.step()
#print('epoch:{} Loss:{}'.format(epoch, loss))
def test(model, device, test_loader, loss_fn):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
#test_loss += loss_fn(output, target, reduction='sum').item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.data.view_as(pred)).sum()
#test_loss /= len(test_loader.dataset)
print('accracy : {:.0f}%'.format(100. * correct / len(test_loader.dataset)))
'''
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
'''
if __name__ == '__main__':
main()
|
from flask import Flask
from flask_login import LoginManager
import os
app = Flask(__name__)
app.config['SECRET_KEY'] = 'Hoooray!'
LOCAL_IP = "10.35.2.26"
GLOBAL_IP = "zanner.org.ua"
DOCKER_IP = "mysql_db"
#app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql://ka7605:123456@{GLOBAL_IP}:33321/bMRI_db'
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql://user:password@{DOCKER_IP}:3306/bMRI_db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['UPLOADED_PHOTOS_DEST'] = os.path.join(os.path.abspath(".."), 'uploads') # you'll need to create a folder named uploads
#os.makedirs(app.config['UPLOADED_PHOTOS_DEST'], exist_ok=True)
login = LoginManager(app)
login.login_view = 'login'
#should be the last line
from app import views
|
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import sys
if __name__ == "__main__":
# Print the content of the env var given on the command line.
print(os.environ[sys.argv[1]])
|
from django.contrib.auth.backends import ModelBackend
from apps.users.models import User
class EmailBackend(ModelBackend):
def authenticate(self, request, email="", password="", **kwargs):
users = User.objects.filter(email=email)
for user in users:
if user.check_password(password) and self.user_can_authenticate(user):
return user
return None
|
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_login import LoginManager
from flask_mongoengine import MongoEngine
app = Flask(__name__)
app.config['SECRET_KEY'] = 'you-will-never-guess'
app.config['MONGODB_SETTINGS'] = {
'db': 'storage',
'host': 'mongodb://storage.loadtest.m1.tinkoff.cloud:27017/storage'
}
db = MongoEngine(app)
login = LoginManager(app)
login.login_view = 'login'
login.login_message = "Пожалуйста, войдите, чтобы открыть эту страницу."
bootstrap = Bootstrap(app)
from app import routes, models, errors
|
"""
Created by Alex Wang on 2018-04-19
Use Hough line detect algorithm to split image
"""
import os
import math
import time
import traceback
from collections import Counter
import numpy as np
import scipy.stats
import cv2
def merge_group(group, width, debug):
"""
merge lines in each group
:param group:
:param width:
:param debug:
:return:
"""
flag_arr = np.zeros([width], dtype=np.int16)
y_axis = group[0][1]
count = 0
for line in group:
for i in range(line[0], line[2] + 1):
flag_arr[i] |= 1
# y_axis += line[1]
# count += 1
# y_axis = int(y_axis/count)
length = np.sum(flag_arr)
if debug:
print('lines_group:')
print(group)
print('length:', length)
return length, y_axis
def cal_patches_laplacian(img, y_axis_list, debug):
"""
cal patches laplacian value to filt dump patches
:param img:
:param y_axis_list:
:param debug:
:return:
"""
laplacian_val_threshold = 400
height, width = img.shape[0:2]
img_patches = []
for i in range(len(y_axis_list) - 1):
y_min = y_axis_list[i]
y_max = y_axis_list[i + 1]
if y_max - y_min <= 20: # filter small patches
continue
img_temp = img[y_min:y_max, :, :]
if debug:
print('shape of img_temp laplacian:', img_temp.shape)
laplacian_val = cv2.Laplacian(img_temp, cv2.CV_64F).var()
if laplacian_val >= laplacian_val_threshold:
img_patches.append(img_temp)
if debug:
print('y_min:', y_min, 'y_max:', y_max)
print('laplacian_val', laplacian_val)
return img_patches
def edge_length_in_canny(img_canny, y_axis):
"""
horizontal line detection in y_axis on img_canny
:param img_canny:
:param y_axis:
:return:
"""
white_pixel_num = 0
line_pixels = img_canny[y_axis, :]
for pixel in line_pixels:
if pixel >= 200:
white_pixel_num += 1
return white_pixel_num
def cal_patches_entropy(img_gray, img_org, y_axis_list, debug):
"""
cal patches entropy and white pixel ratio
:param img_gray:
:param img_org:
:param y_axis_list:
:param debug:
:return:
"""
height, width = img_org.shape[0:2]
entropy_threshold = 3
white_ratio_threshold = 0.85
img_patches = []
img_patches_axis_list = []
entropy_list = []
white_ratio_list = []
y_split_list = [0]
for i in range(len(y_axis_list) - 1):
y_min = y_axis_list[i]
y_max = y_axis_list[i + 1]
# if y_max - y_min == 0: # filter small patches
# continue
img_temp = img_gray[y_min + 1:y_max - 1, :]
if debug:
print('shape of img_temp entropy:', img_temp.shape)
hist = cv2.calcHist([img_temp], [0], None, [256], [0, 256])
hist = np.reshape(hist, newshape=(256))
hist_prob = hist / (np.sum(hist) + math.exp(-6)) + math.exp(-10)
entropy = scipy.stats.entropy(hist_prob)
entropy_list.append(entropy)
white_ratio = np.sum(img_gray[y_min + 1:y_max - 1, :] >= 240) / \
((y_max - y_min - 2) * width + math.exp(-6))
white_ratio_list.append(white_ratio)
if debug:
print('y_min:', y_min, 'y_max:', y_max)
print('image entropy val:', entropy)
print('image white pixel ratio:', white_ratio)
print('')
for i in range(1, len(y_axis_list) - 1):
# if debug:
# print('{}/{}, y_axis_list:{}'.format(i, len(entropy_list), len(y_axis_list)))
prev_entropy = entropy_list[i - 1]
curr_entropy = entropy_list[i]
prev_white_ratio = white_ratio_list[i - 1]
curr_white_ratio = white_ratio_list[i]
if (prev_white_ratio < white_ratio_threshold and
curr_white_ratio >= 0.95) or \
(prev_white_ratio >= 0.95 and
curr_white_ratio < white_ratio_threshold):
y_split_list.append(y_axis_list[i])
continue
if (prev_entropy < entropy_threshold and curr_entropy >= entropy_threshold) or \
(prev_entropy >= entropy_threshold and curr_entropy < entropy_threshold):
if (prev_white_ratio < white_ratio_threshold and
curr_white_ratio >= white_ratio_threshold) or \
(prev_white_ratio >= white_ratio_threshold and
curr_white_ratio < white_ratio_threshold):
y_split_list.append(y_axis_list[i])
y_split_list.append(y_axis_list[len(y_axis_list) - 1]) # append image_height
if (len(y_split_list) <= 2):
return img_patches, img_patches_axis_list
for i in range(len(y_split_list) - 1):
y_min = y_split_list[i]
y_max = y_split_list[i + 1]
if (y_max - y_min) * 1.0 / width < 0.3:
if debug:
print('(y_max - y_min)/width < 0.3:{},{},{}'.format(y_max, y_min, width))
continue
if y_max - y_min > 20:
img_temp = img_gray[y_min:y_max, :]
hist = cv2.calcHist([img_temp], [0], None, [256], [0, 256])
hist = np.reshape(hist, newshape=(256))
hist_prob = hist / (np.sum(hist) + math.exp(-6))
entropy = scipy.stats.entropy(hist_prob)
# print('round2:y_min:{}, y_max:{}, entropy:{}'.format(y_min, y_max, entropy))
if entropy > entropy_threshold:
img_patches.append(img_org[y_min:y_max, :])
img_patches_axis_list.append((y_min, y_max))
return img_patches, img_patches_axis_list
def horizontal_lines_filt(lines_p, img_canny, debug):
"""
file lines
:param lines_p:
:param img_canny:
:param debug: if True, print debug info.
:return:
"""
height, width = img_canny.shape[0:2]
width_threshold = width * 0.25
# keep horizontal lines
lines_horizontal = [line for line in lines_p[:, 0, :] if abs(line[1] - line[3]) <= 1]
lines_horizontal_sorted = sorted(lines_horizontal, key=lambda x: x[1])
lines_length = np.array([line[2] - line[0] for line in lines_horizontal_sorted])
if len(lines_length) == 0:
return [], []
# fetch max lines
fetch_seize = min(len(lines_length), 100)
max_lines_index = lines_length.argsort()[-fetch_seize:][::-1]
max_lines = [lines_length[index] for index in max_lines_index]
minimal_in_max_line_length = min(max_lines)
if debug:
print('max length:', max_lines)
# cluster lines into groups
lines_group = []
line_used_flag = [0 for line in lines_horizontal] # record if line has been used
index = 0
while index < len(lines_horizontal_sorted):
if line_used_flag[index]:
index += 1
continue
line = lines_horizontal_sorted[index]
line_length = line[2] - line[0]
if line_length < minimal_in_max_line_length:
index += 1
continue
line_used_flag[index] = True
max_y = line[1]
if line[2] - line[0] > width_threshold:
temp_group = []
inner_index = 0
while inner_index < len(lines_horizontal_sorted):
inner_line = lines_horizontal_sorted[inner_index]
if abs(inner_line[1] - max_y) <= 2 and abs(inner_line[1] - line[1]) <= 3:
temp_group.append(inner_line)
if (inner_line[2] - inner_line[0]) >= line_length:
max_y = inner_line[1]
line_used_flag[inner_index] = True
elif inner_index > index: # && abs(inner_line[1] - line[1]) > 2
inner_index += len(lines_horizontal_sorted)
inner_index += 1 # inner_index <= index
lines_group.append(temp_group)
index += 1
# merge lines in group
split_lines_info = []
y_axis_list = [0]
line_threshold = width * 0.7
for group in lines_group:
length, y_axis = merge_group(group, width, debug)
if length > line_threshold:
split_lines_info.append([0, y_axis, width, y_axis])
y_axis_list.append(y_axis)
elif edge_length_in_canny(img_canny, y_axis) > line_threshold: #TODO:need validation
y_axis_list.append(y_axis)
y_axis_list.append(height)
return split_lines_info, y_axis_list
def split_img_path(img_path, debug=False, plot=False):
print('img_path', img_path)
img = cv2.imread(img_path)
split_img(img, debug, plot)
def split_img(img, debug=False, plot=False):
if debug:
print('image shape:', img.shape)
start_time = time.time()
img_org = img.copy()
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, img_mask = cv2.threshold(img_gray, 250, 255, cv2.THRESH_BINARY)
img_canny = cv2.Canny(img_mask, 50, 120, L2gradient=False)
img_canny = cv2.dilate(img_canny, None)
try:
lines_p = cv2.HoughLinesP(img_canny, 1, np.pi / 2, 100, minLineLength=10, maxLineGap=3)
if lines_p is None:
print('img has no hough line')
return [], []
split_lines_info, y_axis_list = horizontal_lines_filt(lines_p, img_canny, debug)
# fetch good patches
if len(split_lines_info) == 0:
img_patches = []
img_patches_axis_list = []
else:
img_patches, img_patches_axis_list = cal_patches_entropy(img_gray, img_org, y_axis_list, debug)
for x1, y1, x2, y2 in split_lines_info: # for x1, y1, x2, y2 in lines_p[:, 0, :]:
cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
except Exception as e:
traceback.print_exc()
return [], []
if plot:
end_time = time.time()
print('spend time:', end_time - start_time)
for axis in img_patches_axis_list:
print('img_patches_axis_list---y_min:{}, y_max:{}'.format(axis[0], axis[1]))
ratio = 0.5
img_org_resize = cv2.resize(img_org, None, fx=ratio, fy=ratio, interpolation=cv2.INTER_LINEAR)
img_plot = cv2.resize(img, None, fx=ratio, fy=ratio, interpolation=cv2.INTER_LINEAR)
img_canny_plot = cv2.resize(img_canny, None, fx=ratio, fy=ratio, interpolation=cv2.INTER_LINEAR)
# cv2.imshow('org', img_org_resize)
cv2.imshow('img_resize', img_plot)
cv2.moveWindow('img_resize', 300, 0)
cv2.imshow('img_canny', img_canny_plot)
cv2.moveWindow('img_canny', 600, 0)
save = True
save_dir = 'split_result'
if save:
cv2.imwrite(os.path.join(save_dir, 'img_org_resize.jpg'), img_org_resize)
cv2.imwrite(os.path.join(save_dir, 'img_canny_plot.jpg'), img_canny_plot)
patch_index = 1
print('length of img_patches:', len(img_patches))
for img_patch in img_patches:
print('shape of img pathes', img_patch.shape)
cv2.imshow('img_patches{}'.format(patch_index), img_patch)
patch_index += 1
if save:
cv2.imwrite(os.path.join(save_dir, 'img_patches{}.jpg'.format(patch_index)), img_patch)
cv2.waitKey(0)
cv2.destroyAllWindows()
return img_patches, img_patches_axis_list
if __name__ == '__main__':
# for i in range(1, 11):
# split_img_path('data/long_img_{}.jpg'.format(i), debug=True, plot=True)
# split_img_path('data/long_img_2.jpg', debug=True, plot=True)
root_dir = 'split_data'
for file in os.listdir(root_dir):
if file.endswith('.jpg') or file.endswith('.png'):
print(file)
split_img_path(os.path.join(root_dir, file), debug=True, plot=True)
# split_img_path(os.path.join(root_dir, 'TB2uA_pdAfb_uJkSndVXXaBkpXa_!!1031751943.jpg'), debug=True, plot=True)
# split_img_path(os.path.join(root_dir, 'badcase1.png'), debug=True, plot=True)
# split_img_path(os.path.join(root_dir, 'TB2d41OelE_1uJjSZFOXXXNwXXa_!!892448154.jpg'), debug=True, plot=True)
# split_img_path(os.path.join(root_dir, 'TB2D8oFarMlyKJjSZFAXXbkLXXa_!!1020389393.jpg'), debug=True, plot=True)
# split_img_path(os.path.join(root_dir, 'TB2bzEqdBNkpuFjy0FaXXbRCVXa_!!2090463889.jpg'), debug=True, plot=True)
# split_img_path(os.path.join(root_dir, 'TB2bJVGguSSBuNjy0FlXXbBpVXa_!!2189540184.jpg'), debug=True, plot=True)
# split_img_path(os.path.join(root_dir, 'TB2AIn4c6gy_uJjSZKbXXXXkXXa_!!96719295.jpg'), debug=True, plot=True)
# split_img_path(os.path.join(root_dir, 'TB2_JAmwgJkpuFjSszcXXXfsFXa_!!2405892019.jpg'), debug=True, plot=True)
# split_img_path(os.path.join(root_dir, 'TB2a..3clE_1uJjSZFOXXXNwXXa_!!2120740155.jpg'), debug=True, plot=True)
# split_img_path(os.path.join(root_dir, 'TB2A4uuagLD8KJjSszeXXaGRpXa_!!2011771924.jpg'), debug=True, plot=True)
#
# # TODO:need debug
# split_img_path(os.path.join(root_dir, 'TB2adBDXSGFJuJjSZFuXXcAyFXa_!!1132383995.jpg'), debug=True, plot=True)
# split_img_path(os.path.join(root_dir, 'TB2BbneX_TI8KJjSsphXXcFppXa_!!2261059285.jpg'), debug=True, plot=True)
|
# #Now do the reverse. Convert the dollar amount into the coins that make up that dollar amount. The final result is an object with the correct number of quarters, dimes, nickels, and pennies.
# dollarAmount = 8.69
# piggyBank = {
# "pennies": 0,
# "nickels": 0,
# "dimes": 0,
# "quarters": 0
# }
# # Your magic Python code here
# That should produce the following output.
# >>> print(piggyBank)
# { 'quarters': 34, 'nickels': 1, 'dimes': 1, 'pennies': 4 }
def calc_dollars():
dollar_amount = 8.69
piggy_bank = {
"quarters":0,
"dimes":0,
"nickels":0,
"pennies": 0
}
cents_amount = dollar_amount *100
q_quarters = int(cents_amount/25)
piggy_bank["quarters"] = q_quarters
cents_amount = (cents_amount % 25)
d_dimes = int(cents_amount/10)
piggy_bank["dimes"] = d_dimes
cents_amount = (cents_amount % 10)
n_nickels = int(cents_amount/5)
piggy_bank["nickels"] = n_nickels
cents_amount = (cents_amount % 5)
p_pennies = int(cents_amount)
piggy_bank["pennies"] = p_pennies
print('quarters',piggy_bank)
calc_dollars()
#another Way to do the same thing as above
# dollarAmount = 8.69
# piggyBank = {
# "pennies": 0,
# "nickels": 0,
# "dimes": 0,
# "quarters": 0
# }
# def convert_to_change(dollarAmount, quarters, dimes, nickels, pennies):
# piggyBank["pennies"] = int((dollarAmount - (dollarAmount - pennies*.01))/.01)
# piggyBank["nickels"] = int((dollarAmount - (dollarAmount - nickels*.05))/.05)
# piggyBank["dimes"] = round((dollarAmount - (dollarAmount - dimes*.1))/.1)
# piggyBank["quarters"] = (dollarAmount - (dollarAmount - quarters*.25))/.25
# print(piggyBank)
# convert_to_change(dollarAmount, 34, 1, 1, 4) |
"""Script that starts up dev web server with our app"""
from app import app
app.run(debug = True) |
# -*- coding: utf-8 -*-
"""
flask_store.providers
=====================
Base store functionality and classes.
"""
from urllib.parse import urljoin
import os
import shortuuid
from flask import current_app
from flask_store.utils import is_path, path_to_uri
from werkzeug.utils import secure_filename
from werkzeug.datastructures import FileStorage
class Provider(object):
"""Base provider class all storage providers should inherit from. This
class provides some of the base functionality for all providers. Override
as required.
"""
#: By default Providers do not require a route to be registered
register_route = False
def __init__(self, fp, location=None):
"""Constructor. When extending this class do not forget to call
``super``.
This sets up base instance variables which can be used thoughtout the
instance.
Arguments
---------
fp : werkzeug.datastructures.FileStorage, str
A FileStorage instance or absolute path to a file
Keyword Arguments
-----------------
location : str, optional
Relative location directory, this is appended to the
``STORE_PATH``, default None
"""
# The base store path for the provider
self.store_path = self.join(current_app.config["STORE_PATH"])
# Save the fp - could be a FileStorage instance or a path
self.fp = fp
# Get the filename
if is_path(fp):
self.filename = os.path.basename(fp)
else:
if not isinstance(fp, FileStorage):
raise ValueError(
"File pointer must be an instance of a "
"werkzeug.datastructures.FileStorage"
)
self.filename = fp.filename
# Save location
self.location = location
# Appends location to the store path
if location:
self.store_path = self.join(self.store_path, location)
@property
def relative_path(self):
"""Returns the relative path to the file, so minus the base
path but still includes the location if it is set.
Returns
-------
str
Relative path to file
"""
parts = []
if self.location:
parts.append(self.location)
parts.append(self.filename)
return self.join(*parts)
@property
def absolute_path(self):
"""Returns the absollute file path to the file.
Returns
-------
str
Absolute file path
"""
return self.join(self.store_path, self.filename)
@property
def relative_url(self):
"""Returns the relative URL, basically minus the domain.
Returns
-------
str
Realtive URL to file
"""
parts = [
current_app.config["STORE_URL_PREFIX"],
]
if self.location:
parts.append(self.location)
parts.append(self.filename)
return path_to_uri(self.url_join(*parts))
@property
def absolute_url(self):
"""Absolute url contains a domain if it is set in the configuration,
the url predix, location and the actual file name.
Returns
-------
str
Full absolute URL to file
"""
if not current_app.config["STORE_DOMAIN"]:
path = self.relative_url
path = urljoin(current_app.config["STORE_DOMAIN"], self.relative_url)
return path_to_uri(path)
def safe_filename(self, filename):
"""If the file already exists the file will be renamed to contain a
short url safe UUID. This will avoid overwtites.
Arguments
---------
filename : str
A filename to check if it exists
Returns
-------
str
A safe filenaem to use when writting the file
"""
while self.exists(filename):
dir_name, file_name = os.path.split(filename)
file_root, file_ext = os.path.splitext(file_name)
uuid = shortuuid.uuid()
filename = secure_filename("{0}_{1}{2}".format(file_root, uuid, file_ext))
return filename
def url_join(self, *parts):
"""Safe url part joining.
Arguments
---------
\*parts : list
List of parts to join together
Returns
-------
str
Joined url parts
"""
path = ""
for i, part in enumerate(parts):
if i > 0:
part = part.lstrip("/")
path = urljoin(path.rstrip("/") + "/", part.rstrip("/"))
return path.lstrip("/")
def join(self, *args, **kwargs):
"""Each provider needs to implement how to safely join parts of a
path together to result in a path which can be used for the provider.
Raises
------
NotImplementedError
If the "join" method has not been implemented
"""
raise NotImplementedError(
'You must define a "join" method in the {0} provider.'.format(
self.__class__.__name__
)
)
def exists(self, *args, **kwargs):
"""Placeholder "exists" method. This should be overridden by custom
providers and return a ``boolean`` depending on if the file exists
of not for the provider.
Raises
------
NotImplementedError
If the "exists" method has not been implemented
"""
raise NotImplementedError(
'You must define a "exists" method in the {0} provider.'.format(
self.__class__.__name__
)
)
def save(self, *args, **kwargs):
"""Placeholder "sabe" method. This should be overridden by custom
providers and save the file object to the provider.
Raises
------
NotImplementedError
If the "save" method has not been implemented
"""
raise NotImplementedError(
'You must define a "save" method in the {0} provider.'.format(
self.__class__.__name__
)
)
|
# -*- coding: utf-8 -*-
from flask import current_app
from sqlalchemy import or_
from pygit2 import Repository, init_repository
from ..extensions import db
from .models import Repo
def create_repo(user_id, repo_name):
repo = Repo(repo_name, user_id)
db.session.add(repo)
return repo
def rename_repo(repo_id, repo_name):
raise NotImplementedError
def delete_repo(repo_id):
raise NotImplementedError
def transfer_repo(repo_id, new_user_id, new_repo_name=None):
raise NotImplementedError
def fork_repo(repo_id, new_user_id, new_repo_name=None):
raise NotImplementedError
def get_repo(repo_id=None, **kwargs):
"""
"""
def create_repository(namespace, repo_name):
repositories_root = current_app.config["REPOSITORIES_ROOT"]
repo_path = "%s%s%s.git" % (repositories_root, namespace, repo_name)
return init_repository(repo_path, True)
def get_repository(namespace, repo_name):
"""
"""
repositories_root = current_app.config['REPOSITORIES_ROOT']
repo_path = "%s%s%s.git" % (repositories_root, namespace, repo_name)
try:
return Repository(repo_path)
except:
return None
def get_repo_like(query):
return Repo.query.filter(or_(Repo.name,like('%'+query+'%'))).limit(10).all()
|
import sys
import random
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QMessageBox, QLabel
from PyQt5.QtGui import QPixmap, QFont
from PyQt5.QtCore import Qt
# Интерфейс главного окна:
from interface import Ui_MainWindow
# Работа с базой слов
import getting_words_from_db
EASY = 1
MEDIUM = 2
HARD = 3
column_names_of_difficulties = {EASY: 'easy_words', MEDIUM: 'medium_words',
HARD: 'hard_words'}
STAGES_PICTURES_DIRECTORIES = {0: 'pictures/stage_0.png', 1: 'pictures/stage_1.png',
2: 'pictures/stage_2.png', 3: 'pictures/stage_3.png',
4: 'pictures/stage_4.png', 5: 'pictures/stage_5.png',
6: 'pictures/stage_6.png', 7: 'pictures/stage_7.png',
8: 'pictures/stage_8.png', 9: 'pictures/stage_9.png',
10: 'pictures/stage_10.png', }
GALLOWS_STAGES_PICTURE_DIRECTORY = 'pictures/gallows_stages.png'
LOGO_DIRECTORY = 'pictures/logo.png'
ABOUT_FILE_DIRECTORY = 'about.txt'
RULES_FILE_DIRECTORY = 'rules.txt'
difficulties_to_names = {EASY: 'Лёгкая', MEDIUM: 'Средняя', HARD: 'Сложная'}
names_to_difficulties = {'Лёгкая': EASY, 'Средняя': MEDIUM, 'Сложная': HARD}
ENTERED_LETTERS_DEFAULT_TEXT = 'Список введённых букв: '
RUSSIAN_LETTERS = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя '
ABOUT_WINDOW_SIZE = [400, 200]
MAIN_WINDOW_SIZE = [600, 700]
GALLOWS_WINDOW_SIZE = [800, 440]
RULES_WINDOW_SIZE = [700, 700]
LOGO_SCALE_SIZE = [256, 40]
STANDARD_FONT = 'Tahoma'
# Класс ошибки отстутствия базы данных в файлах игры:
class DataBaseNotFound(FileExistsError):
pass
# Три класса побочных окон:
class AboutWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
global ABOUT_WINDOW_SIZE, LOGO_DIRECTORY, LOGO_SCALE_SIZE, STANDARD_FONT
self.setGeometry(500, 500, *ABOUT_WINDOW_SIZE)
self.setWindowTitle('О программе')
font = QFont()
font.setFamily(STANDARD_FONT)
font.setPointSize(12)
self.about_text = QLabel(self)
self.setFont(font)
self.about_text.setGeometry(20, 10, ABOUT_WINDOW_SIZE[0] - 20, ABOUT_WINDOW_SIZE[1] - 10)
self.about_text.setWordWrap(True)
self.about_text.setAlignment(Qt.AlignHCenter)
self.about_text.setText(self.read_text_from_file())
self.about_text.setTextInteractionFlags(Qt.TextSelectableByMouse)
self.logo = QLabel(self)
self.logo.move((ABOUT_WINDOW_SIZE[0] - LOGO_SCALE_SIZE[0]) // 2,
(ABOUT_WINDOW_SIZE[1] - LOGO_SCALE_SIZE[1]) - 15)
try:
logo = open(LOGO_DIRECTORY)
except FileNotFoundError:
error = (f'Директория "{LOGO_DIRECTORY}" не найдена. '
'Проверьте целостность файлов игры')
QMessageBox.critical(self, 'Ошибка', error)
else:
logo.close()
self.logo_pixmap = QPixmap(LOGO_DIRECTORY).scaled(*LOGO_SCALE_SIZE)
self.logo.setPixmap(self.logo_pixmap)
def read_text_from_file(self):
global ABOUT_FILE_DIRECTORY
try:
about_text = open(ABOUT_FILE_DIRECTORY)
except FileNotFoundError:
error = (f'Директория "{ABOUT_FILE_DIRECTORY}" не найдена. '
'Проверьте целостность файлов игры')
QMessageBox.critical(self, 'Ошибка', error)
else:
text = about_text.read()
about_text.close()
return text
class GallowsStagesPictureWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
global GALLOWS_STAGES_PICTURE_DIRECTORY
self.setGeometry(300, 300, *GALLOWS_WINDOW_SIZE)
self.setWindowTitle('Этапы виселицы (Число - количество совершённых ошибок)')
self.picture = QLabel(self)
self.picture.move(0, 0)
try:
picture = open(GALLOWS_STAGES_PICTURE_DIRECTORY)
except FileNotFoundError:
error = (f'Директория "{GALLOWS_STAGES_PICTURE_DIRECTORY}" не найдена. '
'Проверьте целостность файлов игры')
QMessageBox.critical(self, 'Ошибка', error)
else:
picture.close()
self.pixmap = QPixmap(GALLOWS_STAGES_PICTURE_DIRECTORY)
self.picture.setPixmap(self.pixmap)
class RulesWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
global RULES_FILE_DIRECTORY, STANDARD_FONT
self.setGeometry(300, 100, *RULES_WINDOW_SIZE)
self.setWindowTitle('Правила игры')
font = QFont()
font.setFamily(STANDARD_FONT)
font.setPointSize(14)
self.rules_text = QLabel(self)
self.setFont(font)
self.rules_text.setGeometry(20, 10, RULES_WINDOW_SIZE[0] - 20, RULES_WINDOW_SIZE[1] - 10)
self.rules_text.setWordWrap(True)
self.rules_text.setText(self.read_rules_from_file())
def read_rules_from_file(self):
global RULES_FILE_DIRECTORY
try:
rules_text = open(RULES_FILE_DIRECTORY)
except FileNotFoundError:
error = (f'Директория "{RULES_FILE_DIRECTORY}" не найдена. '
'Проверьте целостность файлов игры')
QMessageBox.critical(self, 'Ошибка', error)
else:
text = rules_text.read()
rules_text.close()
return text
# Класс главного окна:
class MyGame(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.initUI()
def initUI(self):
global EASY, MEDIUM, HARD, difficulties_to_names
self.move(400, 200)
self.setFixedSize(*MAIN_WINDOW_SIZE)
self.setWindowTitle('Игра "Виселица"')
self.difficulty = EASY
self.current_stage = 0
self.entered_letters_list = []
self.entered_words_list = []
self.is_game_over = False
self.enter_bind_is_on = True
self.restart_bind_is_on = False
self.gallows_picture = QLabel(self)
self.gallows_picture.move(50, 100)
self.gallows_picture.resize(400, 400)
# Перепопределение элементов интерфейса:
self.difficultyLabel.setText(f'Сложность: {difficulties_to_names[self.difficulty]}')
self.restartBtn.clicked.connect(self.start_new_game)
self.action_1.triggered.connect(self.change_difficulty)
self.action_2.triggered.connect(self.change_difficulty)
self.action_3.triggered.connect(self.change_difficulty)
self.action_rules.triggered.connect(self.open_widget_with_rules)
self.action_stages.triggered.connect(self.open_widget_with_stages)
self.action_enter_bind.triggered.connect(self.on_off_enter_bind)
self.action_restart_bind.triggered.connect(self.on_off_restart_bind)
self.enterLetterBtn.clicked.connect(self.enter_letter)
self.enterWordBtn.clicked.connect(self.enter_word)
self.action_about.triggered.connect(self.open_about)
self.start_new_game()
def on_off_enter_bind(self):
if self.action_enter_bind.isChecked():
self.enter_bind_is_on = True
else:
self.enter_bind_is_on = False
def on_off_restart_bind(self):
if self.action_restart_bind.isChecked():
self.restart_bind_is_on = True
else:
self.restart_bind_is_on = False
def keyPressEvent(self, event):
if (event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return) and self.enter_bind_is_on:
self.enter_letter()
elif event.key() == Qt.Key_F1 and self.restart_bind_is_on:
self.start_new_game()
def check_win(self):
if set(self.hidden_word) <= set(self.entered_letters_list):
self.is_game_over = True
self.infoLabel.setText('Вы победили! Поздравляем')
def change_difficulty(self):
global names_to_difficulties, difficulties_to_names
new_dif_text = self.sender().text()
new_difficulty = names_to_difficulties[new_dif_text]
if new_difficulty != self.difficulty:
# Сброс "галочки" прошлой выбранной сложности в меню выбора сложности:
exec(f'self.action_{self.difficulty}.setChecked(False)')
# Установка галочки для нужного уровня сложности:
exec(f'self.action_{new_difficulty}.setChecked(True)')
self.difficulty = new_difficulty
self.infoLabel.setText('Сложность будет изменена на'
f' "{difficulties_to_names[self.difficulty]}" '
'в начале следующей игры')
else:
# Возврат снятой галочки:
exec(f'self.action_{new_difficulty}.setChecked(True)')
def change_picture(self):
global STAGES_PICTURES_DIRECTORIES
try:
f = open(STAGES_PICTURES_DIRECTORIES[self.current_stage])
except FileNotFoundError:
error = f'Директория {STAGES_PICTURES_DIRECTORIES[self.current_stage]} не найдена. ' \
'Проверьте целостность файлов игры'
QMessageBox.critical(self, 'Ошибка', error)
else:
f.close()
gallows_pixmap = QPixmap(STAGES_PICTURES_DIRECTORIES[self.current_stage])
self.gallows_picture.setPixmap(gallows_pixmap)
def enter_letter(self):
global RUSSIAN_LETTERS, ENTERED_LETTERS_DEFAULT_TEXT
if self.is_game_over:
return
entered_letter = self.enterLetterLineEdit.text().lower()
if entered_letter not in RUSSIAN_LETTERS:
self.infoLabel.setText('Вы ввели букву нерусского алфавита')
elif entered_letter in self.entered_letters_list:
self.infoLabel.setText('Вы уже вводили данную букву')
elif entered_letter.isalpha():
global ENTERED_LETTERS_DEFAULT_TEXT
# Добавляем букву в список введённых и отображаем её на соотвествущем QLabel:
self.entered_letters_list += entered_letter
self.enteredLettersListLabel.setText(ENTERED_LETTERS_DEFAULT_TEXT +
' '.join(self.entered_letters_list))
if entered_letter in self.hidden_word:
self.infoLabel.setText(f'Верно! Буква "{entered_letter}" есть в загаданном слове')
reformatted_hidden_word = list(self.hiddenWordLineEdit.text())
for i, let in enumerate(self.hidden_word):
if let == entered_letter:
reformatted_hidden_word[i * 2] = let
# Изменение отображения загаданного слова:
self.hiddenWordLineEdit.setText(''.join(reformatted_hidden_word))
# Проверка победы:
self.check_win()
else:
self.infoLabel.setText(f'Буквы "{entered_letter}" не оказалось в загаданном слове')
# Переход к следующему этапу виселицы:
self.current_stage += 1
self.next_stage()
else:
self.infoLabel.setText('Проверьте корректность введённой буквы.')
def enter_word(self):
global RUSSIAN_LETTERS
if self.is_game_over:
return
entered_word = self.enterWordLineEdit.text().lower().strip()
for letter in entered_word:
if letter not in RUSSIAN_LETTERS:
self.infoLabel.setText('Введённое слово содержит букву нерусского алфавита')
return
if entered_word in self.entered_words_list:
self.infoLabel.setText('Вы уже вводили данное слово')
elif entered_word.isalpha():
if len(entered_word) != len(self.hidden_word):
self.infoLabel.setText('Длина введённого слова не соответствует длине загаданного')
elif entered_word == self.hidden_word:
global ENTERED_LETTERS_DEFAULT_TEXT
self.entered_letters_list.extend(list(entered_word))
self.enteredLettersListLabel.setText(ENTERED_LETTERS_DEFAULT_TEXT +
' '.join(self.entered_letters_list))
# Изменение отображения загаданного слова:
self.hiddenWordLineEdit.setText(' '.join(list(self.hidden_word)))
# Запуск функции победы:
self.check_win()
else:
self.infoLabel.setText('Вы не угадали слово. Это засчиталось как 2 ошибки')
self.current_stage += 2
self.next_stage()
else:
self.infoLabel.setText('Проверьте корректность введённого слова.')
def generate_hidden_word(self, difficulty):
# Задаём имя столбца(в базе данных), из которого будем брать слова:
column_name = column_names_of_difficulties[difficulty]
# Получаем список слов нужной сложности
words_list = getting_words_from_db.get_words(column_name)
# Проверяем на ошибки:
if words_list[0] == 'no_db':
error = (f'Директория "{words_list[1]}" не найдена. '
'Проверьте целостность файлов игры')
QMessageBox.critical(self, 'Ошибка', error)
raise DataBaseNotFound(f'База данных в директории "{words_list[1]}" не найдена')
generated_word = random.choice(words_list)
return generated_word
def next_stage(self):
# Изменение рисунка виселицы:
self.change_picture()
# Изменение значения прогресс-бара:
self.mistakesProgressBar.setValue(self.current_stage)
if self.current_stage >= 10:
self.is_game_over = True
self.hiddenWordLineEdit.setText(' '.join(list(self.hidden_word)))
self.infoLabel.setText('К сожалению, вы проиграли. Но вы можете сыграть снова!')
self.current_stage = 0
def open_about(self):
self.about_widget = AboutWidget()
self.about_widget.show()
def open_widget_with_rules(self):
self.rules_widget = RulesWidget()
self.rules_widget.show()
def open_widget_with_stages(self):
self.gallows_widget = GallowsStagesPictureWidget()
self.gallows_widget.show()
def start_new_game(self):
global difficulties_to_names, ENTERED_LETTERS_DEFAULT_TEXT
self.is_game_over = False
self.difficultyLabel.setText(f'Сложность: {difficulties_to_names[self.difficulty]}')
self.entered_letters_list = []
self.entered_words_list = []
self.current_stage = 0
# Очистка информационной таблички:
self.infoLabel.setText('')
# Очистка полей для ввода буквы и слова:
self.enterLetterLineEdit.setText('')
self.enterWordLineEdit.setText('')
# Очистка прогресс-бара:
self.mistakesProgressBar.setValue(self.current_stage)
# Очистка списка введённых букв:
self.enteredLettersListLabel.setText(ENTERED_LETTERS_DEFAULT_TEXT)
# Вставляем рисунок для нулевого этапа:
self.change_picture()
# Генерация загадываемого слова:
self.hidden_word = self.generate_hidden_word(self.difficulty)
# Вставка загадываемого слова в поле вывода в скрытом виде:
formatted_hidden_word = ' '.join('_' for _ in range(len(self.hidden_word)))
self.hiddenWordLineEdit.setText(formatted_hidden_word)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyGame()
window.show()
sys.exit(app.exec())
|
#coding=utf-8
import os
import sys
from envs.python35.Tools.scripts.treesync import raw_input
if os.getuid()==0:
pass
else:
print("当前不是root用户!!")
sys.exit(1)
version = raw_input('请输入你想安装的python版本')
if version=='2.7':
url = 'http://'
elif version=='3.5':
url = 'http://'
else:
print('输入有误,请输入。。。')
sys.exit(1)
cmd = 'wget '+url
res = os.system(cmd)
if res!=0:
print('下载源码包失败,请检查当前网络!')
if version=='2.7':
package_name = 'Python-2.7.12'
else:
package_name = 'Python-3.5.2'
cmd = 'tar xf '+ package_name+'.tgz'
res = os.system(cmd)
if res !=0:
os.system('rm '+package_name+' .tgz')
print('解压源码包,请重新下载运行这个源码包')
sys.exit(1)
cmd = 'cd '+package_name+' && ./configure --prefix=/usr/local/python && make && make install'
res = os.system(cmd)
if res!=0:
print('编译源码失败,请重新检查依赖库')
sys.exit(1) |
from indexed import Indexed
from searcher import Searcher
from signal_handlers import register_signal_handlers
from backends import get_search_backend |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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.
#
"""
datedfolder.py
================
Find dated folders beneath a base directory argument or beneath the current directory.
::
[blyth@localhost issues]$ ~/opticks/ana/datedfolder.py /home/blyth/local/opticks/results/geocache-bench
INFO:__main__:DatedFolder.find searching for date stamped folders beneath : /home/blyth/local/opticks/results/geocache-bench
/home/blyth/local/opticks/results/geocache-bench/OFF_TITAN_RTX/20190422_175618
/home/blyth/local/opticks/results/geocache-bench/ON_TITAN_RTX/20190422_175618
/home/blyth/local/opticks/results/geocache-bench/OFF_TITAN_V/20190422_175618
/home/blyth/local/opticks/results/geocache-bench/ON_TITAN_V/20190422_175618
/home/blyth/local/opticks/results/geocache-bench/OFF_TITAN_V_AND_TITAN_RTX/20190422_175618
[blyth@localhost issues]$
"""
from datetime import datetime
import os, re, sys, logging
log = logging.getLogger(__name__)
class DateParser(object):
ptn = re.compile("(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})")
def __call__(self, name):
"""
:param name: basename of a directory
:return dt: datetime if matches the date format 20160819_153245 otherwise return None
"""
m = self.ptn.match(name)
if m is None:return None
if len(m.groups()) != 6:return None
dt = datetime(*map(int, m.groups()))
return dt
dateparser = DateParser()
def finddir(base, dirfilter=lambda _:True, relative=True):
"""
:param base: directory to walk looking for directories to be dirfiltered
:param dirfilter: function that takes directory path argument and returns true when selected
:param relative: when True returns the base relative path, otherwise absolute paths are returned
:return paths: all directory paths found that satisfy the filter
"""
paths = []
for root, dirs, files in os.walk(base):
for name in dirs:
path = os.path.join(root,name)
d = dirfilter(path)
if d is not None:
paths.append(path[len(base)+1:] if relative else path)
pass
pass
pass
return paths
class DatedFolder(object):
@classmethod
def find(cls, base):
"""
:param base: directory
:return dirs, dfolds, dtimes:
Groups of executable runs are grouped together by them using
the same datestamp datedfolder name.
So there can be more dirs that corresponding dfolds and dtimes.
"""
while base.endswith("/"):
base = base[:-1]
pass
df = cls()
log.info("DatedFolder.find searching for date stamped folders beneath : %s " % base)
dirs = finddir(base, df) # list of dated folders beneath base
dfolds = list(set(map(os.path.basename, dirs))) # list of unique basenames of the dated folders
dtimes = list(map(dateparser, dfolds )) # list of datetimes
return dirs, dfolds, dtimes
def __call__(self, path):
"""
:param path: directory
:return datetime or None:
"""
name = os.path.basename(path)
#log.info(name)
return dateparser(name)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
base = sys.argv[1] if len(sys.argv) > 1 else "."
dirs, dfolds, dtimes = DatedFolder.find(base)
print("\n".join(dfolds))
for df in sorted(dfolds):
print("\n".join(filter(lambda _:_.endswith(df),dirs)))
pass
|
from setuptools import setup
from Cython.Build import cythonize
from distutils.extension import Extension
from Cython.Distutils import build_ext
#setup(ext_modules=cythonize("env2.pyx", compiler_directives={'language_level' : "3"}, extra_compile_args=["-std=c++11"]))
#setup(ext_modules=cythonize("env2.pyx", compiler_directives={'language_level' : "3"}))
setup(
name = 'Test app',
ext_modules=[
Extension('env2',
sources=['env2.pyx'],
extra_compile_args=['-std=c++11'],
language='c++')
],
cmdclass = {'build_ext': build_ext}
)
|
#print()
# 文字列をアウトプットする
print('Hello, World')
# => Hello, World
# 複数の文字列をまとめて出力する
print('This', 'is', 'a', 'python program.')
# => This is a python program.
# 文字列以外のオブジェクトを出力する
print(2019, '年')
# => 2019 年
# 区切り文字を変える
# デフォルトは半角空白
print('2019', '08', '01', sep='-')
# => 2019-08-01
# 通常最後に追加される改行を別の文字列に変える
print('ABC', end='\n-------\n')
print('DEF')
# => ABC
# => -------
# => DEF
# 通常最後に追加される改行を削除する
print('ABC', end='')
print('DEF')
# => ABCDEF
|
from kafka import KafkaConsumer
import json
from textblob import TextBlob
from kafka import KafkaProducer
key='dow'
consumer1 = KafkaConsumer('sample1')
producer = KafkaProducer(bootstrap_servers=['localhost:9092'])
for msg in consumer1:
tweet_text_json=json.loads(msg.value.decode('utf-8'))
tweet = TextBlob(tweet_text_json['text'])
if tweet.sentiment.polarity < 0:
producer.send(key+'_'+'negative', msg.value)
tweet_text_json['sentiment'] ='negative'
# sentiment = "negative"
elif tweet.sentiment.polarity == 0:
# sentiment = "neutral"
producer.send(key+'_'+'neutral', msg.value)
tweet_text_json['sentiment'] ='neutral'
else:
producer.send(key+'_'+'positive', msg.value)
tweet_text_json['sentiment'] ='positive'
# sentiment = "positive"
tweet_text_json['sentiment_value'] =tweet.sentiment.polarity
producer.send(key+'_'+'sentiment', bytes(json.dumps(tweet_text_json),'utf-8'))
print(tweet_text_json['sentiment'])
|
#!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verify that static library dependencies don't traverse none targets, unless
explicitly specified.
"""
import TestGyp
import sys
test = TestGyp.TestGyp()
test.run_gyp('none_traversal.gyp')
test.build('none_traversal.gyp', test.ALL)
test.run_built_executable('needs_chain', stdout="2\n")
test.run_built_executable('doesnt_need_chain', stdout="3\n")
test.pass_test()
|
from django.conf.urls import patterns, url
from apps.characters import views
urlpatterns = patterns('',
#base character
url(r'^character/create/$', views.create_character, name='create_character'),
url(r'^character/$', views.character, name='character'),
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = 'wulf'
import mysql.connector as mysql
import csv
output_file = './file.xlsx'
conn = mysql.connect(user='root', password='123321', database='db_test')
cursor = conn.cursor()
query = "SELECT * FROM test LIMIT 3"
cursor.execute(query)
fields = [field[0] for field in cursor.description]
result = list()
for row in cursor:
result.append(row)
with open(output_file, 'wb') as csvfile:
data_writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
data_writer.writerow(fields)
for row in result:
data_writer.writerow(row)
csvfile.close()
cursor.close()
conn.close()
|
from . import (household, family_member, grant)
|
from gnuText import gnu as texte
# nb of chars
print()
print("nb of chars : ", len(texte))
# nb of symboles
print()
print("nb of symboles : ", len(set(texte)) )
# occurence of each symbole
print()
print("occurence of each symbole : ")
mySet = set(texte)
print("Method 1")
myDict = dict((d,0) for d in mySet)
for i in texte :
myDict[i] += 1
print("myDict len :" , len(myDict))
print(myDict)
print()
print("Method 2")
myDict = dict((d,texte.count(d)) for d in mySet)
print()
print("myDict len :" , len(myDict))
print(myDict)
# for i in myDict :
# print(i, " : ", myDict[i])
print()
print("occurence of each symbole in order : ")
myList = list(myDict.items())
# myList = list( (k, myDict[k]) for k in myDict.keys())
print("myList in ascending order by symboles in ascii")
myList.sort()
print(myList)
print()
print("myList in descending order by symboles in ascii")
myList.sort(reverse=True)
print(myList)
print()
print("myList in descending order by occurences of symbole")
myList.sort(key=lambda b : b[1], reverse=True)
print(myList)
|
# coding:utf-8
from __future__ import absolute_import, unicode_literals
import click, json
from jspider.cli.common import common_pass, common_options
__author__ = "golden"
__date__ = '2018/6/9'
@click.group(name='list')
def list_obj():
"""show something"""
pass
@list_obj.command()
@common_options
@common_pass
def projects(pub):
"""show all projects"""
data = pub.manager.list_projects()
print(json.dumps(data, sort_keys=True, indent=2, ensure_ascii=False))
@list_obj.command()
@common_options
@common_pass
def spiders(pub):
"""show all spiders"""
data = pub.manager.list_spiders()
print(json.dumps(data, sort_keys=True, indent=2, ensure_ascii=False))
|
BAD_COMMENTS_ENABLED = False
GOOD_COMMENTS_ENABLED = False
MAX_ARGUMENTS = 7
MAX_ARRAY_DECL_DIMENSION = 5
MAX_BLOCK_STATEMENTS = 20
MAX_CLASS_MEMBERS = 15
MAX_CLASSES = 10
MAX_EXPRESSION_REPEAT = 2
MAX_PARAMETERS = 7
MAX_POSTFIX_OPS = 5
MAX_STRING_LENGTH = 10
# This recursion limit only generates the bin ops ||, &&, ==, !=, <=, >=, <, >
# For more bin ops set this limit up
# CAUTION: This will result in a ugly unreadable file and the processing time
# will go up drastically
RECURSION_LIMIT = 13
|
a,b=int(input("Enter 1st number: ")),int(input("Enter 2nd number: "))
print(a+b)
print(abs(a-b))
print(a*b) |
from collections import Counter
def combine(*args):
return sum((Counter(a) for a in args), Counter())
|
# 前缀和
class Solution:
def canReach(self, s: str, minJump: int, maxJump: int) -> bool:
n = len(s)
dp = [0] * n
pre_sum = [0] * (n+1)
dp[0] = pre_sum[1] = 1
for i in range(1, n):
if s[i] == "0":
l, r = max(0, i - maxJump), min(n-1, i - minJump)
if r >= 0 and pre_sum[r+1] - pre_sum[max(l, 0)] > 0:
dp[i] = 1
pre_sum[i+1] = pre_sum[i] + dp[i]
return dp[n-1] == 1
# bfs + 右指针剪枝
class Solution:
def canReach(self, s: str, minJump: int, maxJump: int) -> bool:
last, n = 0, len(s)
if s[-1] == '1': return False
q = deque([0])
while q:
t = q.popleft()
for i in range(max(last+1, t + minJump), min(n, t+maxJump+1)):
last = i
if s[i] != '0': continue
q.append(i)
if i == n-1:
return True
return False |
""" script to check the GENIE file gntp.101.gst.root of Julia for possible atmospheric CC background on C12.
Info about gntp.101.gst.root file from Email of Julia:
Hierbei ist gntp.101.gst.root das "Original" File welches aus der Simulation kommt: Hier ist folgendes simuliert:
* solmax Honda Fluesse fuer nu_e, nu_e_bar, nu_mu, nu_mu_bar
* scintillator zusammensetzung: 1000060120[0.87924],1000010010[0.1201],1000080160[0.00034],1000070140[0.00027],
1000160320[5e-5]
* von 0-10 GeV
* insgesamt 1 Mio reaktionen
"""
import ROOT
import numpy as np
# path, where GENIE file is saved:
input_path = "/home/astro/blum/juno/atmoNC/data_Julia/"
# file name:
input_file = input_path + "gntp.101.gst.root"
# load gntp.101.gst.root file:
rfile_input = ROOT.TFile(input_file)
# get the "gst"-TTree from the TFile:
rtree_input = rfile_input.Get("gst")
# get the number of events in the 'gst' Tree:
num_events = rtree_input.GetEntries()
# define max. energy, that one event can have (normally 100 MeV is the edge for indirect DM search) in GeV:
energy_max = 0.1
# define number of events that pass the cuts for each neutrino type:
number = 0
# loop over entries of gst tree:
for event in range(num_events):
# get current event in tree:
rtree_input.GetEntry(event)
# total kinetic energy of final state particles in GeV:
energy = 0.0
# array, where pdgf is stored:
pdgf_array = np.array([])
# array, where pf is stored:
pf_array = np.array([])
# set flag for final state particles:
# no muon in final state:
flag_no_muon = True
# no pion in final state
flag_no_pion = True
# no proton in final state:
flag_no_proton = True
# no lambda, kaon or other exotic particles in final state:
flag_no_exotic = True
# neutron in final state:
flag_neutron = False
# flag_neutron = True
# get the target PDG and check if the target is C12:
tgt = rtree_input.GetBranch('tgt').GetLeaf('tgt').GetValue()
tgt = int(tgt)
if tgt == 1000060120:
# if tgt == 2112:
# get interaction type and check, if interaction type is charged current (cc==1):
cc = int(rtree_input.GetBranch('cc').GetLeaf('cc').GetValue())
nc = int(rtree_input.GetBranch('nc').GetLeaf('nc').GetValue())
if cc == 1:
# if nc == 1:
# event is CC on C12:
# check the type of the incoming neutrino:
neu = int(rtree_input.GetBranch('neu').GetLeaf('neu').GetValue())
if neu < 20:
# neutrino + C12 -> ...
# get number of final state particles:
nf = int(rtree_input.GetBranch('nf').GetLeaf('nf').GetValue())
# loop over nf_nu_e and add Ef[index] to energy_nu_e:
for index in range(nf):
# momentum of final state particle:
pxf = float(rtree_input.GetBranch('pxf').GetLeaf('pxf').GetValue(index))
pyf = float(rtree_input.GetBranch('pyf').GetLeaf('pyf').GetValue(index))
pzf = float(rtree_input.GetBranch('pzf').GetLeaf('pzf').GetValue(index))
# total momentum / kinetic energy of final state particle:
pf = np.sqrt(pxf**2 + pyf**2 + pzf**2)
energy += pf
pf_array = np.append(pf_array, pf)
pdgf = int(rtree_input.GetBranch('pdgf').GetLeaf('pdgf').GetValue(index))
pdgf_array = np.append(pdgf_array, pdgf)
if pdgf == 13 or pdgf == -13:
# muon in final state:
print("muon")
flag_no_muon = False
elif pdgf == 11 or pdgf == -11:
# electron in final state:
print("electron")
elif pdgf == 211 or pdgf == -211 or pdgf == 111:
# print("pion")
# pion in final state:
flag_no_pion = False
elif (pdgf == 311 or pdgf == -311 or pdgf == 321 or pdgf == -321 or pdgf == 3222 or pdgf == 3122 or
pdgf == 3112 or pdgf == 130 or pdgf == 3212 or pdgf == 8285 or pdgf == -2112 or
pdgf == -2212 or pdgf == 1000060120 or pdgf == 4122 or pdgf == 4222 or pdgf == 421 or
pdgf == 4212 or pdgf == 411 or pdgf == -421 or pdgf == -411 or pdgf == 431):
# kaon, lambda or other exotic particles in final state:
flag_no_exotic = False
# elif pdgf == 2212 and pf > 1.0:
# # proton with Ef > 1 GeV in final state:
# flag_no_proton = False
elif pdgf == 2112:
# neutron in final state:
flag_neutron = True
elif pdgf != 2112 and pdgf != 2212 and pdgf != 22 and pdgf != 1000060120:
print(pdgf)
else:
continue
else:
continue
# check the final state energies:
if 0 < energy < energy_max and flag_no_muon and flag_no_pion and flag_no_exotic and flag_no_proton and flag_neutron:
# print(pdgf_array)
# print(Ef_array)
number += 1
print(number)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
update_language_element_query = """
UPDATE public.language AS lng SET
(name, short_code, default_language, active) = ($2, $3, $4, $5) WHERE lng.id = $1 RETURNING *;
"""
|
from django.shortcuts import render, redirect
from django.contrib import messages
from ..login_reg.decorators import required_login
from .models import Book
from ..users.models import User
from .models import Review
# Create your views here.
@required_login
def create(request):
print('reviews create method, adding new review to db')
previous_page = request.META['HTTP_REFERER']
errors = Review.objects.review_valid(request.POST)
if errors:
for category, error in errors.items():
messages.error(request, error, extra_tags=category)
else:
review = Review.objects.create_review(request.POST, request.session['user_id'])
return redirect(previous_page)
|
"""
Class to geerate C Header Files
"""
__author__ = "Tibor Schneider"
__email__ = "sctibor@student.ethz.ch"
__version__ = "0.1.1"
__date__ = "2020/01/28"
__license__ = "Apache 2.0"
__copyright__ = """
Copyright (C) 2020 ETH Zurich. All rights reserved.
Author: Tibor Schneider, ETH Zurich
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
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 os
import re
from textwrap import wrap
import numpy as np
MAX_WIDTH = 100
TAB = " "
class HeaderFile():
"""
Enables comfortable generation of header files
if with_c is set, then generate a c file of the same name, but with a .c ending.
"""
def __init__(self, filename, define_guard=None, with_c=False):
assert filename.endswith(".h")
self.filename = filename
self.with_c = with_c
if with_c:
self.c_filename = self.filename.rstrip("h") + "c"
self.define_guard = define_guard
if self.define_guard is None:
self.define_guard = "__" + re.sub("[./]", "_", filename.upper()) + "__"
self.elements = []
def add(self, element):
self.elements.append(element)
def header_str(self):
ret = ""
ret += "#ifndef {}\n".format(self.define_guard)
ret += "#define {}\n\n".format(self.define_guard)
ret += "#include \"rt/rt_api.h\"\n\n"
for element in self.elements:
ret += element.header_str(self.with_c)
ret += "#endif//{}".format(self.define_guard)
return ret
def source_str(self):
assert self.with_c
ret = ""
ret += "#include \"{}\"\n\n".format(os.path.split(self.filename)[-1])
for element in self.elements:
ret += element.source_str()
return ret
def write(self):
with open(self.filename, "w") as _f:
_f.write(self.header_str())
if self.with_c:
with open(self.c_filename, "w") as _f:
_f.write(self.source_str())
class HeaderEntry():
def __init__(self):
pass
def header_str(self, with_c=False):
return ""
def source_str(self):
return ""
class HeaderConstant(HeaderEntry):
def __init__(self, name, value, blank_line=True):
self.name = name
self.value = value
self.blank_line = blank_line
def header_str(self, with_c=False):
ret = "#define {} {}\n".format(self.name, self.value)
if self.blank_line:
ret += "\n"
return ret
def source_str(self):
return ""
class HeaderScalar(HeaderEntry):
def __init__(self, name, dtype, value, blank_line=True):
self.name = name
self.dtype = dtype
self.value = value
self.blank_line = blank_line
def header_str(self, with_c=False):
if with_c:
ret = "extern const {} {};\n".format(self.dtype, self.name, self.value)
else:
ret = "const {} {} = {};\n".format(self.dtype, self.name, self.value)
if self.blank_line:
ret += "\n"
return ret
def source_str(self):
ret = "const {} {} = {};\n".format(self.dtype, self.name, self.value)
if self.blank_line:
ret += "\n"
return ret
class HeaderArray(HeaderEntry):
def __init__(self, name, dtype, data, locality="RT_L2_DATA", blank_line=True, const=True):
assert locality in ["RT_LOCAL_DATA", "RT_L2_DATA", "RT_CL_DATA", "RT_FC_SHARED_DATA",
"RT_FC_GLOBAL_DATA", ""]
self.name = name
self.dtype = dtype
self.data = data
self.locality = locality
self.const = const
self.blank_line = blank_line
def header_str(self, with_c=False):
const_str = "const " if self.const else ""
if with_c:
ret = "extern {} {}{} {}[{}];\n".format(self.locality, const_str, self.dtype, self.name, len(self.data))
else:
# first, try it as a one-liner (only if the length is smaller than 16)
if len(self.data) <= 16:
ret = "{} {}{} {}[] = {{ {} }};".format(self.locality, const_str, self.dtype, self.name,
", ".join([str(item) for item in self.data]))
if len(ret) <= MAX_WIDTH:
ret += "\n"
if self.blank_line:
ret += "\n"
return ret
# It did not work on one line. Make it multiple lines
ret = ""
ret += "{} {}{} {}[] = {{\n".format(self.locality, const_str, self.dtype, self.name)
long_str = ", ".join([str(item) for item in self.data])
parts = wrap(long_str, MAX_WIDTH-len(TAB))
ret += "{}{}".format(TAB, "\n{}".format(TAB).join(parts))
ret += "};\n"
if self.blank_line:
ret += "\n"
return ret
def source_str(self):
const_str = "const " if self.const else ""
# first, try it as a one-liner
if len(self.data) <= 16:
ret = "{} {}{} {}[] = {{ {} }};".format(self.locality, const_str, self.dtype, self.name,
", ".join([str(item) for item in self.data]))
if len(ret) <= MAX_WIDTH:
ret += "\n"
if self.blank_line:
ret += "\n"
return ret
# It did not work on one line. Make it multiple lines
ret = ""
ret += "{} {}{} {}[] = {{\n".format(self.locality, const_str, self.dtype, self.name)
long_str = ", ".join([str(item) for item in self.data])
parts = wrap(long_str, MAX_WIDTH-len(TAB))
ret += "{}{}".format(TAB, "\n{}".format(TAB).join(parts))
ret += "};\n"
if self.blank_line:
ret += "\n"
return ret
class HeaderComment(HeaderEntry):
def __init__(self, text, mode="//", blank_line=True):
assert mode in ["//", "/*"]
self.text = text
self.mode = mode
self.blank_line = blank_line
def header_str(self, with_c=False):
if self.mode == "/":
start = "// "
mid = "\n// "
end = ""
else:
start = "/*\n * "
mid = "\n * "
end = "\n */"
ret = start
ret += mid.join([mid.join(wrap(par, MAX_WIDTH-3)) for par in self.text.split("\n")])
ret += end
ret += "\n"
if self.blank_line:
ret += "\n"
return ret
def source_str(self):
return self.header_str(True)
def align_array(x, n=4, fill=0):
"""
Aligns the array to n elements (i.e. Bytes) by inserting fill bytes
Parameters:
- x: np.array(shape: [..., D])
- n: number of elements to be aligned with
- fill: value of the added elements
Return: np.array(shape: [..., D']), where D' = ceil(D / n) * n
"""
new_shape = (*x.shape[:-1], align_array_size(x.shape[-1]))
y = np.zeros(new_shape, dtype=x.dtype)
original_slice = tuple(slice(0, d) for d in x.shape)
fill_slice = (*tuple(slice(0, d) for d in x.shape[:-1]), slice(x.shape[-1], y.shape[-1]))
y[original_slice] = x
y[fill_slice] = fill
return y
def align_array_size(D, n=4):
"""
Computes the required dimension D' such that D' is aligned and D <= D'
Parameters:
- D: Dimension to be aligned
- n: number of elements to be aligned with
Return: D'
"""
return int(np.ceil(D / n) * n)
|
import pyautogui
from pyautogui import *
import ppadb
from ppadb.client import Client
from PIL import Image
import numpy
import time
from mss import mss
from pynput.mouse import Controller,Button,Listener
def on_click(x,y,button,pressed):
if pressed:
print('Mouse Clicked at ({0},{1})'.format(x,y))
with Listener(on_click=on_click) as listener:
listener.join()
|
# 10/30/17
# count to 1,000 by any multiple
print('')
print('_____________________________________________')
print('Enter A Number For Their Multiples Up To 1000')
print('_____________________________________________')
print('')
while True:
print("")
num = int(input('Enter A Number: '))
for i in range(0, 1001, num):
print(i)
# Done
|
#User function Template for python3
def multiplicationTable(N):
for i in range(1,11):
print(i*N, end=" ")
def main():
testcases=int(input()) #testcases
while(testcases>0):
numbah=int(input())
multiplicationTable(numbah)
print()
testcases-=1
if __name__=='__main__':
main() |
from django.shortcuts import render
from .models import Bootcamp, User, Course, Review
from rest_framework import viewsets, filters, views, response, authentication, permissions
from .serializers import BootcampSerializer, UserSerializer, CourseSerializer, ReviewSerializer
from .permissions import UsersPermissions, BootcampsPermissions, CoursesPermissions, ReviewsPermissions
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.authtoken.views import ObtainAuthToken
class TokenViewSet(viewsets.ViewSet):
serializer_class = AuthTokenSerializer
def create(self, request):
return ObtainAuthToken().post(request)
class UpdatePasswordView(views.APIView):
def get(self, request):
return response.Response(
{"ExpectedRequest": {'username': 'actualUsername', 'password': 'ToBeUpdatedPassword'}})
def post(self, request):
print(request.data['password'])
if request.user.username != request.data['username']:
return None
user = User.objects.get(username=request.data['username'])
user.set_password(request.data['password'])
user.save()
return response.Response({'Password Changed': True})
class CoursesOfBootcamps(views.APIView):
def get(self, request, id):
bootcamp = Bootcamp.objects.get(id=id)
coursesquery = list(bootcamp.courses.all())
courses = []
for course in coursesquery:
courses.append(course.title)
return response.Response(
{f'Courses Offered By {bootcamp.name} are': courses})
class ReviewsOfBootcamps(views.APIView):
def get(self, request, id):
bootcamp = Bootcamp.objects.get(id=id)
reviewsquery = Review.objects.filter(forWhichBootcamp=id)
reviews = []
for review in reviewsquery:
reviews.append({review.title: review.rating})
return response.Response(
{f'{bootcamp.name} Bootcamp Reviews': reviews})
class UsersViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
permission_classes = (
permissions.IsAuthenticatedOrReadOnly, UsersPermissions,)
authentication_classes = (authentication.TokenAuthentication,)
queryset = User.objects.all()
class BootcampsViewSet(viewsets.ModelViewSet):
serializer_class = BootcampSerializer
permission_classes = (
permissions.IsAuthenticatedOrReadOnly, BootcampsPermissions,)
authentication_classes = (authentication.TokenAuthentication,)
queryset = Bootcamp.objects.all()
filter_backends = (filters.SearchFilter,)
search_fields = ('zipcode',)
class CoursesViewSet(viewsets.ModelViewSet):
serializer_class = CourseSerializer
permission_classes = (
permissions.IsAuthenticatedOrReadOnly, CoursesPermissions,)
authentication_classes = (authentication.TokenAuthentication,)
queryset = Course.objects.all()
filter_backends = (filters.SearchFilter,)
search_fields = ('title',)
class ReviewsViewSet(viewsets.ModelViewSet):
serializer_class = ReviewSerializer
permission_classes = (ReviewsPermissions,)
queryset = Review.objects.all()
|
n=input("Enter the number of names:")
a=0
for i in range(1,n+1):
b=raw_input("Enter the name:")
if b>a:
a=b
print a
|
import unittest
from katas.kyu_7.money_money_money import calculate_years
class CalculateYearsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(calculate_years(1000, 0.05, 0.18, 1100), 3)
def test_equals_2(self):
self.assertEqual(calculate_years(1000, 0.01625, 0.18, 1200), 14)
def test_equals_3(self):
self.assertEqual(calculate_years(1000, 0.05, .18, 1000), 0)
|
import argparse
import pickle
import re
from collections import Counter
from os import walk, mkdir, makedirs
from os.path import relpath, join, exists
from typing import Set
from tqdm import tqdm
import config
from config import CORPUS_DIR, CORPUS_NAME_TO_PATH
from docqa.data_processing.text_utils import NltkAndPunctTokenizer
from docqa.triviaqa.read_data import normalize_wiki_filename
from docqa.utils import group, split, flatten_iterable
from bert.tokenization import BasicTokenizer
"""
Build and cache a tokenized version of the evidence corpus
Modified from docqa/triviaqa/evidence_corpus.py
"""
class ChineseTokenizer():
def __init__(self):
self._tokenizer = BasicTokenizer(do_lower_case=False)
def tokenize_paragraph(self, paragraph):
sentences = re.split("。|?|!", paragraph)
ret = []
for sent in sentences:
if sent:
ret.append(self._tokenizer.tokenize(sent) + ["。"])
return ret
def tokenize_paragraph_flat(self, paragraph):
return self._tokenizer.tokenize(paragraph)
def _gather_files(input_root, output_dir, skip_dirs, wiki_only):
if not exists(output_dir):
mkdir(output_dir)
all_files = []
for root, dirs, filenames in walk(input_root):
if skip_dirs:
output = join(output_dir, relpath(root, input_root))
if exists(output):
continue
path = relpath(root, input_root)
normalized_path = normalize_wiki_filename(path)
if not exists(join(output_dir, normalized_path)):
mkdir(join(output_dir, normalized_path))
all_files += [join(path, x) for x in filenames]
if wiki_only:
all_files = [x for x in all_files if "wikipedia/" in x]
return all_files
def build_tokenized_files(filenames, input_root, output_root, tokenizer, override=True) -> Set[str]:
"""
For each file in `filenames` loads the text, tokenizes it with `tokenizer, and
saves the output to the same relative location in `output_root`.
@:return a set of all the individual words seen
"""
voc = set()
for filename in filenames:
out_file = normalize_wiki_filename(filename[:filename.rfind(".")]) + ".txt"
out_file = join(output_root, out_file)
if not override and exists(out_file):
continue
with open(join(input_root, filename), "r") as in_file:
text = in_file.read().strip()
paras = [x for x in text.split("\n") if len(x) > 0]
paragraphs = [tokenizer.tokenize_paragraph(x) for x in paras]
for para in paragraphs:
for i, sent in enumerate(para):
voc.update(sent)
with open(join(output_root, out_file), "w") as in_file:
in_file.write("\n\n".join("\n".join(" ".join(sent) for sent in para) for para in paragraphs))
return voc
def build_tokenized_corpus(input_root, tokenizer, output_dir, skip_dirs=False,
n_processes=1, wiki_only=False):
if not exists(output_dir):
makedirs(output_dir)
all_files = _gather_files(input_root, output_dir, skip_dirs, wiki_only)
if n_processes == 1:
voc = build_tokenized_files(tqdm(all_files, ncols=80), input_root, output_dir, tokenizer)
else:
voc = set()
from multiprocessing import Pool
with Pool(n_processes) as pool:
chunks = split(all_files, n_processes)
chunks = flatten_iterable(group(c, 500) for c in chunks)
pbar = tqdm(total=len(chunks), ncols=80)
for v in pool.imap_unordered(_build_tokenized_files_t,
[[c, input_root, output_dir, tokenizer] for c in chunks]):
voc.update(v)
pbar.update(1)
pbar.close()
voc_file = join(output_dir, "vocab.txt")
with open(voc_file, "w") as f:
for word in sorted(voc):
f.write(word)
f.write("\n")
def _build_tokenized_files_t(arg):
return build_tokenized_files(*arg)
def extract_voc(corpus, doc_ids):
voc = Counter()
for i, doc in enumerate(doc_ids):
voc.update(corpus.get_document(doc, flat=True))
return voc
def _extract_voc_tuple(x):
return extract_voc(*x)
def get_evidence_voc(corpus, n_processes=1):
doc_ids = corpus.list_documents()
voc = Counter()
if n_processes == 1:
for doc in tqdm(doc_ids):
voc = corpus.get_document(doc, flat=True)
else:
from multiprocessing import Pool
chunks = split(doc_ids, n_processes)
chunks = flatten_iterable(group(x, 10000) for x in chunks)
pbar = tqdm(total=len(chunks), ncols=80)
with Pool(n_processes) as pool:
for v in pool.imap_unordered(_extract_voc_tuple, [[corpus, c] for c in chunks]):
voc += v
pbar.update(1)
pbar.close()
return voc
def build_evidence_voc(corpus, override, n_processes):
target_file = join(corpus.directory, "vocab.txt")
if exists(target_file) and not override:
raise ValueError()
voc = get_evidence_voc(XQAEvidenceCorpusTxt(), n_processes=n_processes).keys()
with open(target_file, "w") as f:
for word in sorted(voc):
f.write(word)
f.write("\n")
class XQAEvidenceCorpusTxt(object):
"""
Corpus of the tokenized text from the given XQA evidence documents.
Allows the text to be retrieved by document id
"""
_split_all = re.compile("[\n ]")
_split_para = re.compile("\n\n+") # FIXME we should not have saved document w/extra spaces...
def __init__(self, corpus_name, file_id_map=None):
self.directory = join(CORPUS_DIR, corpus_name, "evidence")
print("corpus name !: ", corpus_name)
print("corpus path !: ", self.directory)
self.file_id_map = file_id_map
def get_vocab(self):
with open(join(self.directory, "vocab.txt"), "r") as f:
return {x.strip() for x in f}
def load_word_vectors(self, vec_name):
filename = join(self.directory, vec_name + "_pruned.pkl")
if exists(filename):
with open(filename, "rb"):
return pickle.load(filename)
else:
return None
def list_documents(self):
if self.file_id_map is not None:
return list(self.file_id_map.keys())
f = []
for dirpath, dirnames, filenames in walk(self.directory):
if dirpath == self.directory:
# Exclude files in the top level dir, like the vocab file
continue
if self.directory != dirpath:
rel_path = relpath(dirpath, self.directory)
f += [join(rel_path, x[:-4]) for x in filenames]
else:
f += [x[:-4] for x in filenames]
return f
def get_document(self, doc_id, n_tokens=None, flat=False):
if self.file_id_map is None:
file_id = doc_id
else:
file_id = self.file_id_map.get(doc_id)
if file_id is None:
return None
file_id = join(self.directory, file_id + ".txt")
if not exists(file_id):
return None
with open(file_id, "r") as f:
if n_tokens is None:
text = f.read()
if flat:
return [x for x in self._split_all.split(text) if len(x) > 0]
else:
paragraphs = []
for para in self._split_para.split(text):
paragraphs.append([sent.split(" ") for sent in para.split("\n")])
return paragraphs
else:
paragraphs = []
paragraph = []
cur_tokens = 0
for line in f:
if line == "\n":
if not flat and len(paragraph) > 0:
paragraphs.append(paragraph)
paragraph = []
else:
sent = line.split(" ")
sent[-1] = sent[-1].rstrip()
if len(sent) + cur_tokens > n_tokens:
if n_tokens != cur_tokens:
paragraph.append(sent[:n_tokens-cur_tokens])
break
else:
paragraph.append(sent)
cur_tokens += len(sent)
if flat:
return flatten_iterable(paragraph)
else:
if len(paragraph) > 0:
paragraphs.append(paragraph)
return paragraphs
def main():
parse = argparse.ArgumentParser("Pre-tokenize the XQA evidence corpus")
parse.add_argument("--corpus",
choices=["en", "fr", "de", "ru", "pt", "zh", "pl", "uk", "ta",
"en_trans_de", "en_trans_zh",
"fr_trans_en", "de_trans_en", "ru_trans_en", "pt_trans_en",
"zh_trans_en", "pl_trans_en", "uk_trans_en", "ta_trans_en"],
required=True)
# This is slow, using more processes is recommended
parse.add_argument("-n", "--n_processes", type=int, default=1, help="Number of processes to use")
parse.add_argument("--wiki_only", action="store_true")
args = parse.parse_args()
output_dir = join(config.CORPUS_DIR, args.corpus, "evidence")
source = join(config.CORPUS_NAME_TO_PATH[args.corpus], "evidence")
if args.corpus == "en_trans_zh" or args.corpus == "zh":
tokenizer = ChineseTokenizer()
else:
tokenizer = NltkAndPunctTokenizer()
build_tokenized_corpus(source, tokenizer, output_dir,
n_processes=args.n_processes, wiki_only=args.wiki_only)
if __name__ == "__main__":
main()
|
__author__ = 'Justin'
from MapLoad import mapload
import os
import networkx as nx
import geojson
# I) Generate Full Network
# DESCRIPTION:
# This script converts geojson road geometry files to a tractable networkx object (.gexf)
# Geojson map data such as node positions, edge connections, edge types, max speeds, and edge names are extracted
# The Geojson network is pruned to remove redundant network nodes.
#
# This reduced load does include residential sections as part of the core network.
#
# INPUT:
# converted Open Street Map extract (.geojson format)
#
# OUTPUT:
# networkx object file (.gexf)
# Create file path to geojson information
cwd = os.getcwd()
filename = 'cstat_map.geojson'
filepath = os.path.abspath(os.path.join(cwd, '..', 'Project Data','Geojson',filename))
# Load Network
restrictedTypes = ['service','track','rail','footway','path','steps',
'raceway','unknown','pedestrian','construction','road']
RoadNetwork = mapload(filepath,restrictedTypes)
print("Number of edges:",len(RoadNetwork.edges()))
print("Number of nodes:",len(RoadNetwork.nodes()))
# Save Network Graph
cwd = os.getcwd()
filename = 'OSMNetwork.gexf'
string = os.path.abspath(os.path.join(cwd, '..', 'Project Data','Networks',filename))
nx.write_gexf(RoadNetwork,string)
# Export RoadNetwork Nodes (geoJSON format)
Features =[]
lons = nx.get_node_attributes(RoadNetwork,'lon')
lats = nx.get_node_attributes(RoadNetwork,'lat')
for point in RoadNetwork.nodes():
Features.append(geojson.Feature(geometry=geojson.Point((lons[point], lats[point]))))
Collection = geojson.FeatureCollection(Features)
dump = geojson.dumps(Collection)
filename = 'OSMRoadNetwork.txt'
string = os.path.abspath(os.path.join(cwd, '..', 'Project Data','Display',filename))
text_file = open(string, "w")
text_file.write(dump)
text_file.close()
# Export Edges (geoJSON format)
Features = []
for edge in RoadNetwork.edges():
pointa = (lons[edge[0]], lats[edge[0]])
pointb = (lons[edge[1]], lats[edge[1]])
Features.append(geojson.Feature(geometry=geojson.LineString([pointa,pointb])))
Collection = geojson.FeatureCollection(Features)
dump = geojson.dumps(Collection)
filename = 'OSMEdges.txt'
string = os.path.abspath(os.path.join(cwd, '..', 'Project Data','Display',filename))
text_file = open(string, "w")
text_file.write(dump)
text_file.close()
# II) Generate Reduced Network
# DESCRIPTION:
# This script converts geojson road geometry files to a tractable networkx object (.gexf)
# Geojson map data such as node positions, edge connections, edge types, max speeds, and edge names are extracted
# The Geojson network is pruned to remove redundant network nodes.
#
# This reduced load does not include residential sections as part of the core network.
#
# INPUT:
# converted Open Street Map extract (.geojson format)
#
# OUTPUT:
# networkx object file (.gexf)
# Create file path to geojson information
cwd = os.getcwd()
filename = 'cstat_map.geojson'
filepath = os.path.abspath(os.path.join(cwd, '..', 'Project Data','Geojson',filename))
# Load Network
restrictedTypes = ['service','track','residential','living_street','rail','footway','path','steps','cycleway',
'raceway','unknown','pedestrian','construction','road']
RoadNetwork = mapload(filepath,restrictedTypes)
print("Number of reduced edges:",len(RoadNetwork.edges()))
print("Number of reduced nodes:",len(RoadNetwork.nodes()))
# Save Network Graph
cwd = os.getcwd()
filename = 'OSMNetworkReduced.gexf'
string = os.path.abspath(os.path.join(cwd, '..', 'Project Data','Networks',filename))
nx.write_gexf(RoadNetwork,string)
# Export RoadNetwork Nodes (geoJSON format)
Features =[]
lons = nx.get_node_attributes(RoadNetwork,'lon')
lats = nx.get_node_attributes(RoadNetwork,'lat')
for point in RoadNetwork.nodes():
Features.append(geojson.Feature(geometry=geojson.Point((lons[point], lats[point]))))
Collection = geojson.FeatureCollection(Features)
dump = geojson.dumps(Collection)
filename = 'OSMRoadNetworkReduced.txt'
string = os.path.abspath(os.path.join(cwd, '..', 'Project Data','Display',filename))
text_file = open(string, "w")
text_file.write(dump)
text_file.close()
# Export Edges (geoJSON format)
Features = []
for edge in RoadNetwork.edges():
pointa = (lons[edge[0]], lats[edge[0]])
pointb = (lons[edge[1]], lats[edge[1]])
Features.append(geojson.Feature(geometry=geojson.LineString([pointa,pointb])))
Collection = geojson.FeatureCollection(Features)
dump = geojson.dumps(Collection)
filename = 'OSMEdgesReduced.txt'
string = os.path.abspath(os.path.join(cwd, '..', 'Project Data','Display',filename))
text_file = open(string, "w")
text_file.write(dump)
text_file.close()
|
import sys
sys.path.append('/usr/local/lib/python3.4/site-packages')
import numpy as np
import argparse
import cv2
import sys
import time
from networktables import NetworkTables
import logging
logging.basicConfig(level=logging.DEBUG)
NetworkTables.initialize(server='172.22.11.2')
sd = NetworkTables.getTable("SmartDashboard")
count = 1
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image file")
ap.add_argument("-r", "--radius", type = int,
help = "radius of Gaussian blur; must be odd")
args = vars(ap.parse_args())
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
orig = frame.copy()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5,5), 0)
(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(gray)
image = orig.copy()
cv2.rectangle(image, (int(maxLoc[0]+50),int(maxLoc[1])-50), (int(maxLoc[0]-50),int(maxLoc[1])+50), (255, 0, 0), 2)
cv2.line(image, (int(maxLoc[0]+50),int(maxLoc[1])-50), (int(maxLoc[0]-50),int(maxLoc[1])+50), (255,0,255), 2)
cv2.line(image, (int(maxLoc[0]-50),int(maxLoc[1])-50), (int(maxLoc[0]+50),int(maxLoc[1])+50), (255,0,255), 2)
cv2.circle(image, maxLoc, 5, (0, 255, 255), -1)
print(str(count) + ": " + str(maxLoc))
count += 1
cv2.imshow("Detect Tape", image)
sd.putNumber('maxLoc x', maxLoc[0])
sd.putNumber('maxLoc y', maxLoc[1])
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
|
#abstracting the storytelling infrastructure
import random
import time
import os
def display_page(text,choice):
print(text)
raw_input(choice)
text_1 = 'Test this out. I know that the console can word wrap, but it doesn\' respect words. It wraps lines and cuts words in half.'
choice_1 = 'Please press a key to finish the program.'
display_page(text_1,choice_1)
|
import time
from subprocess import call
__author__ = 'sxh112430'
# run this once every half second. Start this script once every minute.
for i in range((59 * 2) + 1):
time.sleep(.5) # wait one half second
call(['curl','http://np.spencer-hawkins.com/cron_trigger/']) |
import unittest
from requests import Response
from pyyoutube.error import ErrorCode, ErrorMessage, PyYouTubeException
class ErrorTest(unittest.TestCase):
BASE_PATH = "testdata/"
with open(BASE_PATH + "error_response.json", "rb") as f:
ERROR_DATA = f.read()
with open(BASE_PATH + "error_response_simple.json", "rb") as f:
ERROR_DATA_SIMPLE = f.read()
def testResponseError(self) -> None:
response = Response()
response.status_code = 400
response._content = self.ERROR_DATA
ex = PyYouTubeException(response=response)
self.assertEqual(ex.status_code, 400)
self.assertEqual(ex.message, "Bad Request")
self.assertEqual(ex.error_type, "YouTubeException")
error_msg = "YouTubeException(status_code=400,message=Bad Request)"
self.assertEqual(repr(ex), error_msg)
self.assertTrue(str(ex), error_msg)
def testResponseErrorSimple(self) -> None:
response = Response()
response.status_code = 400
response._content = self.ERROR_DATA_SIMPLE
ex = PyYouTubeException(response=response)
self.assertEqual(ex.status_code, 400)
def testErrorMessage(self):
response = ErrorMessage(status_code=ErrorCode.HTTP_ERROR, message="error")
ex = PyYouTubeException(response=response)
self.assertEqual(ex.status_code, 10000)
self.assertEqual(ex.message, "error")
self.assertEqual(ex.error_type, "PyYouTubeException")
|
n=int(input("enter th integer"))
temp=str(n)
t1=temp+temp
t2=temp+temp+temp
tem=n+int(t1)+int(t2)
print(tem) |
import numpy as np
import matplotlib.pyplot as plt
#method for relaxation method works for both systems of relaxation and single variables x must be a list
def relax(x,f,error):
newerror=[]
#create the error vector
for l in x:
newerror.append(10)
i=0
stop=False
#interate through function
while(not stop and i<10000):
i+=1
#pass x into a vector function that takes a vector and outputs another vector
newx=f(x)
for n in range(0,len(newerror)):
newerror[n]=abs(x[n]-newx[n])
x=newx
c=0
#checks that all of the values in vector x have the desired error
for j in newerror:
if(j<error):
c+=1
#if they all have the desired ammount of error we can stop interating
if(c==len(newerror)):
stop=True
#this places a limit on the number of times the function can interate
if(i>10000):
print("this did not converge")
return x,i
# newton raphson for a single variable function follows a similar patten as relaxation except for single variables
def NR(f,df,error,x):
newerror=1
i=0
while(error<newerror or i>1000):
i+=1
newx=x-(f(x)/df(x))
print(newx)
newerror=abs(x-newx)
x=newx
if(i>1000):
print("This did not converge")
return x
#secant method for a single variable function follows a similar patten as relaxation except for single variables
def secant(f,error,x1,x2):
newerror=1
x=0
i=0
while(error<newerror and i<1000):
i+=1
try:
df=(x2-x1)/(f(x2)-f(x1))
except ZeroDivisionError:
df=0
x=x2-f(x2)*df
x1=x2
x2=x
newerror=abs(x1-x2)
if(i>1000):
print("This did not converge")
return x
#this is a help function for the binary search method that produces a plot of the function you are trying to find the root of and allows a manual rechange of the domain
#it will then check if this domain is acceptable
def changerange(a,b,f):
bad=True
#print("this is a "+ str(a))
#print("this is b "+ str(b))
while(bad):
y1=f(a)
y2=f(b)
#check that the signs of beginning and end of the domain are opposite
if(((y1<0 and y2)>0) or ((y1>0 and y2)<0)):
return y1,y2,a,b
else:
#if the domain is bad we plot the function with a domain 10X greater and 10X small of the function
print("this domain is bad please enter a new one")
x=np.linspace(10*a,10*b,1000)
y=f(x)
fig1=plt.figure()
ax= fig1.add_subplot(2,1,1)
ax.plot(x,y)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("zoomed out")
x=np.linspace(0.1*a,0.1*b,1000)
y=f(x)
ax2= fig1.add_subplot(2,1,2)
ax2.plot(x,y)
ax2.set_xlabel("X")
ax2.set_ylabel("Y")
ax2.set_title("zoomed out")
fig1.tight_layout(pad=3.0)
plt.show()
#we request that the user uses the plots produced to change the domain
a=float(input("Enter the beginning of the domain "))
b=float(input("Enter the end of the domain "))
#perfom binary search recursivels
def binary(a,b,f,error):
y1,y2,a,b=changerange(a,b,f)
newerror=abs(y1-y2)
avg=(a+b)/2
yavg=f(avg)
#if the domain is sufficiently small output a result
if(newerror<error):
return avg
elif(yavg==0):
return avg
#splice the based on the value of yavg and the sign of the end points
elif(yavg<0):
if(y1<0):
return binary(avg,b,f,error)
if(y2<0):
return binary(a,avg,f,error)
elif(yavg>0):
if(y1>0):
return binary(avg,b,f,error)
if(y2>0):
return binary(a,avg,f,error)
#perfomr newton raphson on a system
def NRsys(f,J,error,x):
newerror=[]
for l in x:
newerror.append(10)
i=0
stop=False
while(not stop and i<10000):
i+=1
#jacobian matrix become A
A=J(x)
# our b matrix is simply our function
b=f(x)
#we then solve for change in our function at x
A=np.array(A)
b=np.array(b)
dx=np.linalg.solve(A,b)
newx=x-dx
#calculate the new error
for n in range(0,len(newerror)):
newerror[n]=abs(x[n]-newx[n])
c=0
for j in newerror:
if(j<error):
c+=1
if(c==len(newerror)):
stop=True
x=newx
#print(np.array(x).real)
if(i>10000):
print("This did not converge")
return x,i
|
def superReducedString(s):
res = []
for i in s:
if not res:
res.append(i)
elif res[-1]==i:
res.pop()
else:
res.append(i)
return ''.join(res)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.