text
stringlengths 8
6.05M
|
|---|
#!/usr/bin/python
import sys
from kbhit2 import TKBHit
def KBHit():
kbhit= TKBHit()
return kbhit.KBHit(timeout=0.1)
if __name__=='__main__':
import time
disp= '.'
while 1:
c= KBHit()
print c
if c is not None:
sys.stdout.write('> %r\n'%c)
sys.stdout.flush()
if c=='q': break
else: disp= c
for i in range(40):
sys.stdout.write(disp)
sys.stdout.flush()
time.sleep(0.05)
sys.stdout.write('\n')
print 'done'
|
import pandas as pd
import urllib.request
import traceback
from backend.common import *
DATA_PATH = f'{get_root()}/data/world.xlsx'
def consolidate_country_col(df, country_col, country_id_col, covid_df):
"""
This method adjusts the values in the country field of the passed DF
so that the values are matching those in the covid_DF whenever possible,
so that we can subsequently join them on the country field.
"""
covid_countries = covid_df[['country_id', 'country']].drop_duplicates()
covid_countries['country_lower'] = covid_countries['country'].str.lower()
covid_countries['country_id_lower'] = covid_countries['country_id'].str.lower()
df = df.rename(columns={
country_col: 'country_other',
country_id_col: 'country_id_other',
})
df['country_other_lower'] = df['country_other'].str.lower()
df['country_id_other_lower'] = df['country_id_other'].str.lower()
def _take_first_non_null_col(_df, _cols):
return _df[_cols].fillna(method='bfill', axis=1).iloc[:, 0]
def _consolidate_on(_df, col):
_join_df = covid_countries.set_index(f'{col}_lower')
_df = _df.join(_join_df, on=f'{col}_other_lower')
_df['country_other'] = _take_first_non_null_col(_df, ['country', 'country_other'])
for c in _join_df.columns:
del _df[c]
return _df
df = _consolidate_on(df, 'country_id')
df = _consolidate_on(df, 'country')
df = df[df['country_other'].isin(covid_countries['country'])]
del df['country_id_other']
del df['country_other_lower']
del df['country_id_other_lower']
df = df.rename(columns={
'country_other': 'country'
})
return df
def get_google_mobility_df(covid_df):
url = 'https://www.gstatic.com/covid19/mobility/Global_Mobility_Report.csv'
df = pd.read_csv(url, nrows=1)
dtypes = {col: 'float' if col.endswith('baseline') else 'object' for col in df.columns}
df = pd.read_csv(url, dtype=dtypes)
del df['iso_3166_2_code']
del df['census_fips_code']
df = consolidate_country_col(df, 'country_region', 'country_region_code', covid_df)
df = df[pd.isna(df['sub_region_1'])]
del df['sub_region_1']
del df['sub_region_2']
to_rep = '_percent_change_from_baseline'
for col in df.columns:
if col.endswith(to_rep):
df = df.rename(columns={col: 'pc_' + col.replace(to_rep, '')})
df = df[pd.isnull(df['metro_area'])]
del df['metro_area']
return df
def get_covid_df():
# get the data
url = 'https://www.ecdc.europa.eu/sites/default/files/documents/COVID-19-geographic-disbtribution-worldwide.xlsx'
df = pd.read_excel(url)
# basic processing
df = df.rename(columns={
'dateRep': 'date',
'countriesAndTerritories': 'country',
'popData2019': 'population',
'geoId': 'country_id',
'continentExp': 'continent'
})
del df['countryterritoryCode']
df.loc[df['country'] == 'Namibia', 'country_id'] = 'NAMIBIA'
df.loc[df['country'] == 'Czechia', 'population'] = 10650000
df['population'] = df['population'].fillna(0)
df['country'] = df['country'].str.replace('_', ' ')
if df['date'].dtype.name == 'object':
df['date'] = pd.to_datetime(df['date'], format="%d/%m/%Y")
df['date'] = df['date'].dt.strftime('%Y-%m-%d')
# add new columns - totals
def _apply(g):
g = g.sort_values(by='date', ascending=False)
g['tot_deaths'] = g['deaths'][::-1].cumsum()[::-1]
g['tot_cases'] = g['cases'][::-1].cumsum()[::-1]
return g
df = df.groupby('country').apply(_apply)
df['cases'] = df['cases'].apply(lambda x: max(0, x))
df['deaths'] = df['deaths'].apply(lambda x: max(0, x))
df.index = range(len(df))
# check all fields are filled
df = df.dropna()
assert all(df.count()['date'] == x for x in df.count())
return df
def get_stringency_df(covid_df):
df = pd.read_csv('https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest.csv')
df['CountryCode'] = df['CountryCode'].replace({
'SVK': 'SK',
'CZE': 'CZ',
'USA': 'US'
})
df = consolidate_country_col(df, 'CountryName', 'CountryCode', covid_df)
df['Date'] = df['Date'].astype('str').apply(lambda x: f'{x[:4]}-{x[4:6]}-{x[6:]}')
for c in [
'LegacyStringencyIndex',
'LegacyStringencyIndexForDisplay',
'ConfirmedCases',
'ConfirmedDeaths'
]:
if c in df.columns:
del df[c]
df = df.rename(columns={
'StringencyIndex': 'stringency',
'StringencyIndexForDisplay': 'stringency_disp'
})
df.columns = [c.lower() for c in df.columns]
for letter in ['c', 'e', 'h', 'm']:
for i in range(1, 100):
cols = [c for c in df.columns if f'{letter}{i}_' in c]
if len(cols) == 0:
continue
name = '_'.join(cols[0].split('_')[1].split(' '))
name_flag = f'{name}_flag'
name_notes = f'{name}_note'
new_names = [f'mtr_{letter}_{c}' for c in [name, name_flag, name_notes]]
df = df.rename(columns={
cols[i]: new_names[i] for i in range(len(cols))
})
df['stringency'] = df['stringency']/100
df['stringency_disp'] = df['stringency_disp']/100
return df
def _get_final_df():
covid_df = get_covid_df()
df = covid_df
gm_df = get_google_mobility_df(covid_df)
df = df.join(gm_df.set_index(['country', 'date']), on=['country', 'date'])
str_df = get_stringency_df(covid_df)
df = df.join(str_df.set_index(['country', 'date']), on=['country', 'date'])
cols_to_drop = [
'day', 'month', 'year',
'country_id',
'stringency_disp'
]
cols_to_drop.extend([c for c in df.columns if 'mtr_' in c and 'mtr_c' not in c])
cols_to_drop.extend([c for c in df.columns if '_note' in c or '_flag' in c])
for c in set(cols_to_drop):
del df[c]
mtr_cols = [c for c in df.columns if c.startswith('mtr_c')]
df[mtr_cols] = df[mtr_cols]/df[mtr_cols].max()
return df
def get_final_df(load_ok=None):
# try:
# df = _get_final_df()
# if type(load_ok) == list:
# load_ok.append(True)
#
#
# cols = [
# 'date',
# 'cases',
# 'deaths',
# 'country',
# 'continent',
# 'population',
# 'tot_deaths',
# 'tot_cases',
# 'pc_retail_and_recreation',
# 'pc_grocery_and_pharmacy',
# 'pc_parks',
# 'pc_transit_stations',
# 'pc_workplaces',
# 'pc_residential',
# 'mtr_c_school_closing',
# 'mtr_c_workplace_closing',
# 'mtr_c_cancel_public_events',
# 'mtr_c_restrictions_on_gatherings',
# 'mtr_c_close_public_transport',
# 'mtr_c_stay_at_home_requirements',
# 'mtr_c_restrictions_on_internal_movement',
# 'mtr_c_international_travel_controls',
# 'stringency',
# ]
# return df[cols]
# except Exception as e:
# traceback.print_exc()
# print(f'Exception getting the data: {e}')
print('Using backup')
if type(load_ok) == list:
load_ok.append(False)
return pd.read_csv(f'{get_root()}/backend/bck_data.csv', index_col=0)
|
class Rectangle:
count = 0 # 클래스 변수 >> 모든 클래스가 공유해요.
# 초기자(initializer)
def __init__(self, width, height):
# self.* : 인스턴스변수 >> 객체마다 값이 달라요.
self.width = width
self.height = height
Rectangle.count += 1
# 메서드
def calcArea(self):
area = self.width * self.height
return area
# public 메서드
def publicFunction(self):
return "public function"
# public 메서드
def publicFunctionForPrivateFunction(self):
return self.__privateFunction()
# private 메서드
def __privateFunction(self):
return "private function"
r1 = Rectangle(1, 2)
r2 = Rectangle(2, 3)
print(r1.count)
print(r2.count)
print("width: %s, height: %s" % (r1.width, r1.height)) # r1 인스턴스 변수 출력
print("width: %s, height: %s" % (r2.width, r2.height)) # r2 인스턴스 변수 출력
print(r1.publicFunction())
print(r1.publicFunctionForPrivateFunction())
|
from wsgiref.simple_server import make_server
def f1():
return "F1"
def f2():
return "F2"
def f3():
return "F3"
routers = {
"/index/": f1,
"/news/": f2,
"/home/": f3
}
def RunServer(environ, start_response):
start_response("200 OK", [('Content-Type', 'text/html')])
# return '<h1>Hello, web!</h1>'
url = environ['PATH_INFO']
if url in routers.keys():
func_name = routers[url]
return func_name()
else:
return "404"
if __name__ == "__main__":
httpd = make_server("", 8000, RunServer)
print("Serving HTTP on port 8000...")
# while循环,等到用户请求到来
# 只要有请求进来,执行RunServer函数
httpd.serve_forever()
|
from django import forms
from .models import (
Utilisateur
)
class Form_ajout_utilisateur(forms.Form):
nom = forms.CharField(max_length=40, required=False)
prenom = forms.CharField(max_length=40, required=False)
|
#!/usr/bin/env python
# Funtion:
# Filename:
import urllib.request
url = "http://blog.csdn.net/lovingprince/article/details/6627555"
file = urllib.request.urlopen(url)
file.getcode()
|
import sqlite3
def setUserVoice(user_id, photo):
conn = sqlite3.connect('Database.db3')
FH = open("voice.dat", "r")
line = FH.readline()
voice_id = int(line) + 1
FH.close()
FH = open("voice.dat", "w")
FH.write(str(voice_id))
FH.close()
# Create a file object in "write" mode
FH = open("./Voice/" + str(voice_id), "w")
# Write all the lines at once to the file handle
FH.write(Phototo)
FH.close()
conn.execute("UPDATE User SET voice_id = '" + str(voice_id) + "' WHERE user_id = '" + user_id + "'")
conn.commit()
conn.close()
return True
|
#!/usr/bin/env python
from mayavi import mlab
import sys, os
vtkname = sys.argv[1]
src = mlab.pipeline.open(vtkname)
src2 = mlab.pipeline.set_active_attribute(src, point_scalars='T')
iso_surface = mlab.pipeline.iso_surface(src2)
iso_surface.contour.auto_contours = False
iso_surface.contour.contours[0:1] = [0.995]
objname = os.path.splitext(vtkname)[0] + ".obj"
mlab.savefig(objname)
|
# 加法群
# 加法ついて群をなす(可換)
from abc import abstractclassmethod, ABCMeta
from typing import TypeVar
AdditiveGroupType = TypeVar("AdditiveGroupType", bound="AdditiveGroup")
class AdditiveGroup(metaclass=ABCMeta):
# 加法
@abstractclassmethod
def __add__(self: AdditiveGroup, x: AdditiveGroup) -> AdditiveGroup:
pass
@abstractclassmethod
# 零元
def zero(self: AdditiveGroup) -> AdditiveGroup:
pass
@abstractclassmethod
# 逆元
def __neg__(self: AdditiveGroup) -> AdditiveGroup:
pass
# 差
def __sub__(self: AdditiveGroup, x: AdditiveGroup) -> AdditiveGroup:
return self + (-x)
@abstractclassmethod
# イコール
def __eq__(self, x):
pass
# 結合律
def testAdditiveAssociation(self: AdditiveGroup, a: AdditiveGroup, b: AdditiveGroup) -> bool:
return (self + a) + b == self + (a + b)
# 零元
def testZero(self: AdditiveGroup) -> bool:
return self + self.zero() == self
# 零元の存在
def testNegative(self: AdditiveGroup) -> bool:
return self + (-self) == self.zero()
# 可換
def testAbelian(self: AdditiveGroup, a: AdditiveGroup) -> bool:
return self + a == a + self
|
from schemas import BaseSchema, JSONBSchema
bs = BaseSchema()
bs.load()
js = JSONBSchema()
js.load()
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='KMin',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('code', models.CharField(max_length=8)),
('market', models.CharField(max_length=8)),
('p', models.DecimalField(max_digits=8, decimal_places=5)),
('o', models.DecimalField(max_digits=8, decimal_places=5)),
('h', models.DecimalField(max_digits=8, decimal_places=5)),
('l', models.DecimalField(max_digits=8, decimal_places=5)),
('c', models.DecimalField(max_digits=8, decimal_places=5)),
('amt', models.DecimalField(max_digits=16, decimal_places=2)),
('vol', models.DecimalField(max_digits=16, decimal_places=0)),
('date', models.DateField()),
('time', models.TimeField()),
],
),
migrations.AlterField(
model_name='kdaily',
name='vol',
field=models.DecimalField(max_digits=16, decimal_places=0),
),
]
|
#_*_coding:utf-8_*_
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^$','apps.vipuser.views.vipuser_api',name='vipuser'),
url(r'^nonvipuser/?$','apps.vipuser.views.nonvipuser',name='nonvipuser'),
url(r'^access_user/?$','apps.vipuser.views.access_user',name='access_user'),
url(r'^vipuser_api/?$','apps.vipuser.views.vipuser_api',name='vipuser'),
url(r'^vipuser_test/(\w+)/(.+)/?$','apps.vipuser.views.vipuser_test',name='vipuser_test'),
)
|
import os
import argparse
import pandas as pd
from sklearn.model_selection import train_test_split
from src.get_data import read_params
def split_and_save_data(config_path):
config = read_params(config_path)
test_data_path = config['split_data']['test_path']
train_data_path = config['split_data']['train_path']
raw_data_path = config['load_data']['raw_data_set']
split_ratio = config['split_data']['test_size']
random_state = config['base']['random_state']
df = pd.read_csv(raw_data_path, sep=',')
train, test = train_test_split(
df, test_size=split_ratio, random_state=random_state)
train.to_csv(train_data_path, sep=',', index=False,
encoding='utf-8', header=True)
test.to_csv(test_data_path, sep=',', index=False,
encoding='utf-8', header=True)
if __name__ == '__main__':
# args = argparse.ArgumentParser()
default_config_path = os.path.join("config", 'params.yaml')
# args.add_argument("--config",default=default_config_path)
# # args.add_argument("--datasource",default=None)
# parsed_args = args.parse_args()
data = split_and_save_data(config_path=default_config_path)
|
temp = int(input())
if temp > 30: print('hace calor')
elif temp < 10: print('hace frio')
else: print('esta bien')
if temp >= 100: print('hierve')
if temp <= 0: print('se congela')
|
import pandas as pd
from sklearn.model_selection import train_test_split;
from sklearn.datasets import *
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.decomposition import PCA, KernelPCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from test.MachineLearning.plots import *
f = plt.figure()
df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None)
X, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
sc = StandardScaler()
X_train_std = sc.fit_transform(X_train); X_test_std = sc.transform(X_test)
X_stack = np.vstack((X_train_std, X_test_std)); Y_stack = np.hstack((y_train, y_test))
#No dimensinality reduction
ax=f.add_subplot(221)
lr=LogisticRegression()
lr.fit(X_train_std[:,[0,1]],y_train)
plot_decision_regions(X=X_stack[:,[0,1]], y=Y_stack, classifier=lr)
plt.text(0.1, 0.9,'LR by 2 random features', transform=ax.transAxes)
#PCA
ax=f.add_subplot(222)
pca = PCA(n_components=2)
X_train_pca = pca.fit_transform(X_train_std); X_test_pca=pca.transform(X_test_std)
X_stack_pca = np.vstack((X_train_pca, X_test_pca));
lr1=LogisticRegression()
lr1.fit(X_train_pca,y_train)
plot_decision_regions(X=X_stack_pca, y=Y_stack, classifier=lr1)
plt.text(0.1, 0.9,'LR with PCA', transform=ax.transAxes)
#LDA
ax=f.add_subplot(223)
lda = LinearDiscriminantAnalysis(n_components=2)
X_train_lda = lda.fit_transform(X_train_std, y_train); X_test_lda=lda.transform(X_test_std)
X_stack_lda = np.vstack((X_train_lda, X_test_lda));
lr2=LogisticRegression()
lr2.fit(X_train_lda,y_train)
plot_decision_regions(X=X_stack_lda, y=Y_stack, classifier=lr2)
plt.text(0.1, 0.9,'LR with LDA', transform=ax.transAxes)
#RBF kernel PCA
ax=f.add_subplot(224)
X,y = make_circles(n_samples=1000, noise=0.1, factor=0.23)
X_pca = KernelPCA(n_components=2, kernel='rbf', gamma=15).fit_transform(X)
plt.scatter(X[y==0,0], X[y==0,1], color='green', marker='o', alpha=0.5)
plt.scatter(X[y==1,0], X[y==1,1], color='yellow', marker='o', alpha=0.5)
plt.scatter(X_pca[y==0,0], X_pca[y==0,1], color='red', marker='^', alpha=0.5)
plt.scatter(X_pca[y==1,0], X_pca[y==1,1], color='blue', marker='^', alpha=0.5)
plt.tight_layout()
plt.text(0.1, 0.9,'RBF Kernel PCA', transform=ax.transAxes)
plt.tight_layout()
plt.show()
|
"""This package provides statistics objects to be used by Gaussian Family
likelihoods.
"""
# flake8: noqa
|
input_file = open('./twain.txt')
# word_count = {}
# for line in input_file:
# line =line.rstrip()
# words = line.split()
# for word in words:
# word_count[word]=word_count.get(word,0) +1
# for word, count in word_count.items():
# print(word, count)
word_counts ={}
for line in input_file:
line = line.rstrip()
words = line.split()
for word in words:
word_counts[word]=word_counts.get(word,0)+1
for word,count in word_counts.items():
print(word,count)
|
from decimal import Decimal, getcontext
getcontext().prec=60
summation = 0
for k in range(50):
summation = summation + 1/Decimal(16)**k * (
Decimal(4)/(8*k+1)
- Decimal(2)/(8*k+4)
- Decimal(1)/(8*k+5)
- Decimal(1)/(8*k+6)
)
print(summation)
|
"""
"""
import phantom.rules as phantom
import json
from datetime import datetime, timedelta
def on_start(container):
phantom.debug('on_start() called')
# call 'Format_Caller_Level_1' block
Format_Caller_Level_1(container=container)
return
def Format_Caller_Level_1(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
phantom.debug('Format_Caller_Level_1() called')
input_parameter_0 = ""
Format_Caller_Level_1__caller_level_1_playbook_run_id = None
################################################################################
## Custom Code Start
################################################################################
# Write your custom code here...
pinfo = phantom.get_playbook_info()[0]
Format_Caller_Level_1__caller_level_1_playbook_run_id = '/rest/playbook_run/{}'.format(pinfo['parent_playbook_run_id'])
################################################################################
## Custom Code End
################################################################################
phantom.save_run_data(key='Format_Caller_Level_1:caller_level_1_playbook_run_id', value=json.dumps(Format_Caller_Level_1__caller_level_1_playbook_run_id))
Get_Caller_Level_1_Playbook_Run(container=container)
return
def Get_Caller_Level_1_Playbook_Run(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
phantom.debug('Get_Caller_Level_1_Playbook_Run() called')
Format_Caller_Level_1__caller_level_1_playbook_run_id = json.loads(phantom.get_run_data(key='Format_Caller_Level_1:caller_level_1_playbook_run_id'))
# collect data for 'Get_Caller_Level_1_Playbook_Run' call
parameters = []
# build parameters list for 'Get_Caller_Level_1_Playbook_Run' call
parameters.append({
'location': Format_Caller_Level_1__caller_level_1_playbook_run_id,
'verify_certificate': False,
'headers': "",
})
phantom.act(action="get data", parameters=parameters, assets=['http_rest'], callback=decision_1, name="Get_Caller_Level_1_Playbook_Run")
return
def Format_Archer_Result(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
phantom.debug('Format_Archer_Result() called')
template = """User: {0}
Playbook Executed: {1}
Result: {2}
Message: {3}"""
# parameter list for template variable replacement
parameters = [
"Compile_Results:custom_function:user",
"Compile_Results:custom_function:playbook",
"Get_Caller_Level_1_Playbook_Run:action_result.data.*.response_body.status",
"Compile_Results:custom_function:message",
]
phantom.format(container=container, template=template, parameters=parameters, name="Format_Archer_Result")
Update_Archer_Incident(container=container)
return
def Format_Caller_User(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
phantom.debug('Format_Caller_User() called')
results_data_1 = phantom.collect2(container=container, datapath=['Get_Caller_Level_1_Playbook_Run:action_result.data.*.response_body.effective_user'], action_results=results)
results_item_1_0 = [item[0] for item in results_data_1]
Format_Caller_User__caller_user_endpoint = None
################################################################################
## Custom Code Start
################################################################################
Format_Caller_User__caller_user_endpoint = '/rest/ph_user/{}'.format(results_item_1_0[0])
################################################################################
## Custom Code End
################################################################################
phantom.save_run_data(key='Format_Caller_User:caller_user_endpoint', value=json.dumps(Format_Caller_User__caller_user_endpoint))
Get_Caller_User(container=container)
return
def decision_1(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
phantom.debug('decision_1() called')
# check for 'if' condition 1
matched = phantom.decision(
container=container,
action_results=results,
conditions=[
["Get_Caller_Level_1_Playbook_Run:action_result.data.*.response_body.misc.parent_playbook_run", "!=", ""],
])
# call connected blocks if condition 1 matched
if matched:
join_Compile_Results(action=action, success=success, container=container, results=results, handle=handle, custom_function=custom_function)
return
# call connected blocks for 'else' condition 2
Format_Caller_User(action=action, success=success, container=container, results=results, handle=handle, custom_function=custom_function)
return
def Get_Caller_User(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
phantom.debug('Get_Caller_User() called')
#phantom.debug('Action: {0} {1}'.format(action['name'], ('SUCCEEDED' if success else 'FAILED')))
Format_Caller_User__caller_user_endpoint = json.loads(phantom.get_run_data(key='Format_Caller_User:caller_user_endpoint'))
# collect data for 'Get_Caller_User' call
parameters = []
# build parameters list for 'Get_Caller_User' call
parameters.append({
'location': Format_Caller_User__caller_user_endpoint,
'verify_certificate': False,
'headers': "",
})
phantom.act(action="get data", parameters=parameters, assets=['http_rest'], callback=join_Compile_Results, name="Get_Caller_User")
return
def Compile_Results(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
phantom.debug('Compile_Results() called')
id_value = container.get('id', None)
results_data_1 = phantom.collect2(container=container, datapath=['Get_Caller_Level_1_Playbook_Run:action_result.data.*.response_body.misc.parent_playbook_run', 'Get_Caller_Level_1_Playbook_Run:action_result.data.*.response_body.message', 'Get_Caller_Level_1_Playbook_Run:action_result.data.*.response_body'], action_results=results)
results_item_1_0 = [item[0] for item in results_data_1]
results_item_1_1 = [item[1] for item in results_data_1]
results_item_1_2 = [item[2] for item in results_data_1]
Compile_Results__user = None
Compile_Results__playbook = None
Compile_Results__message = None
################################################################################
## Custom Code Start
################################################################################
# Write your custom code here...
# Get User that ran the playbook
if results_item_1_0[0]:
# if parent_playbook_run is not empty, it indicates the parent playbook was called thus user is automation
Compile_Results__user = 'automation'
else:
# if parent_playbook_run is empty, parent playbook was executed by a user
users = phantom.collect2(container=container, datapath=['Get_Caller_User:action_result.data.*.response_body.username'], action_results=results)
users = [item[0] for item in users]
Compile_Results__user = users[0]
# Get Playbook Called
playbook = json.loads(results_item_1_1[0]) #[0].split('/')[-1].strip()
Compile_Results__playbook = playbook['playbook'].split('/')[-1].strip()
Compile_Results__message = phantom.get_object(key='0BJ3CT K3Y', container_id=id_value, clear_data=True)
Compile_Results__message = Compile_Results__message[0]['value']['results']
#phantom.debug(Compile_Results__user)
#phantom.debug(Compile_Results__playbook)
#phantom.debug(Compile_Results__message)
################################################################################
## Custom Code End
################################################################################
phantom.save_run_data(key='Compile_Results:user', value=json.dumps(Compile_Results__user))
phantom.save_run_data(key='Compile_Results:playbook', value=json.dumps(Compile_Results__playbook))
phantom.save_run_data(key='Compile_Results:message', value=json.dumps(Compile_Results__message))
Format_Archer_Result(container=container)
return
def join_Compile_Results(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None):
phantom.debug('join_Compile_Results() called')
# if the joined function has already been called, do nothing
if phantom.get_run_data(key='join_Compile_Results_called'):
return
# no callbacks to check, call connected block "Compile_Results"
phantom.save_run_data(key='join_Compile_Results_called', value='Compile_Results', auto=True)
Compile_Results(container=container, handle=handle)
return
def Update_Archer_Incident(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
phantom.debug('Update_Archer_Incident() called')
container_data = phantom.collect2(container=container, datapath=['artifact:*.cef.data', 'artifact:*.id'])
formatted_data_1 = phantom.get_format_data(name='Format_Archer_Result')
container_item_0 = [item[0] for item in container_data]
################################################################################
## Custom Code Start
################################################################################
phantom.debug(formatted_data_1)
phantom.debug(container_item_0)
################################################################################
## Custom Code End
################################################################################
return
def on_finish(container, summary):
phantom.debug('on_finish() called')
# This function is called after all actions are completed.
# summary of all the action and/or all details of actions
# can be collected here.
# summary_json = phantom.get_summary()
# if 'result' in summary_json:
# for action_result in summary_json['result']:
# if 'action_run_id' in action_result:
# action_results = phantom.get_action_results(action_run_id=action_result['action_run_id'], result_data=False, flatten=False)
# phantom.debug(action_results)
return
|
# coding:utf-8
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n==0: return 0
g = [0 for _ in range(n+1)]
g[0] = g[1] = 1
for x in range(2,n+1):
for i in range(1,x+1):
g[x] += g[i-1]*g[x-i]
return g[n]
print(Solution().numTrees(4))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Name: RealSR ncnn Vulkan Python wrapper
Author: ArchieMeng
Date Created: February 4, 2021
Last Modified: February 13, 2022
Dev: K4YT3X
Last Modified: February 13, 2022
"""
# built-in imports
import importlib
import math
import pathlib
import sys
# third-party imports
from PIL import Image
# local imports
if __package__ is None:
import realsr_ncnn_vulkan_wrapper as wrapped
else:
wrapped = importlib.import_module(f"{__package__}.realsr_ncnn_vulkan_wrapper")
class Realsr:
def __init__(
self,
gpuid=0,
model="models-DF2K",
tta_mode=False,
scale: float = 4,
tilesize=0,
num_threads=1,
**_kwargs,
):
"""
RealSR class which can do image super resolution.
:param gpuid: the id of the gpu device to use.
:param model: the name or the path to the model
:param tta_mode: whether to enable tta mode or not
:param scale: scale ratio. value: float. default: 2
:param tilesize: tile size. 0 for automatically setting the size. default: 0
:param num_threads: number of threads. default: 1
"""
self._raw_realsr = wrapped.RealSRWrapped(gpuid, tta_mode, num_threads)
self.model = model
self.gpuid = gpuid
self.scale = scale # the real scale ratio
self.set_params(scale, tilesize)
self.load()
def set_params(self, scale=4.0, tilesize=0):
"""
set parameters for realsr object
:param scale: 1/2. default: 2
:param tilesize: default: 0
:return: None
"""
self._raw_realsr.scale = (
4 # control the real scale ratio at each raw process function call
)
self._raw_realsr.tilesize = self.get_tilesize() if tilesize <= 0 else tilesize
self._raw_realsr.prepadding = self.get_prepadding()
def load(
self, param_path: pathlib.Path = None, model_path: pathlib.Path = None
) -> None:
"""
Load models from given paths. Use self.model if one or all of the parameters are not given.
:param param_path: the path to model params. usually ended with ".param"
:param model_path: the path to model bin. usually ended with ".bin"
:return: None
"""
if param_path is None or model_path is None:
model_dir = pathlib.Path(self.model)
# try to load it from module path if not exists as directory
if not model_dir.is_dir():
model_dir = pathlib.Path(__file__).parent / "models" / self.model
param_path = model_dir / f"x{self._raw_realsr.scale}.param"
model_path = model_dir / f"x{self._raw_realsr.scale}.bin"
if param_path.exists() and model_path.exists():
param_path_str, model_path_str = wrapped.StringType(), wrapped.StringType()
if sys.platform in ("win32", "cygwin"):
param_path_str.wstr = wrapped.new_wstr_p()
wrapped.wstr_p_assign(param_path_str.wstr, str(param_path))
model_path_str.wstr = wrapped.new_wstr_p()
wrapped.wstr_p_assign(model_path_str.wstr, str(model_path))
else:
param_path_str.str = wrapped.new_str_p()
wrapped.str_p_assign(param_path_str.str, str(param_path))
model_path_str.str = wrapped.new_str_p()
wrapped.str_p_assign(model_path_str.str, str(model_path))
self._raw_realsr.load(param_path_str, model_path_str)
else:
raise FileNotFoundError(f"{param_path} or {model_path} not found")
def process(self, im: Image) -> Image:
"""
Upscale the given PIL.Image, and will call RealSR.process() more than once for scale ratios greater than 4
:param im: PIL.Image
:return: PIL.Image
"""
if self.scale > 1:
cur_scale = 1
w, h = im.size
while cur_scale < self.scale:
im = self._process(im)
cur_scale *= 4
w, h = math.floor(w * self.scale), math.floor(h * self.scale)
im = im.resize((w, h))
return im
def _process(self, im: Image) -> Image:
"""
Call RealSR.process() once for the given PIL.Image
:param im: PIL.Image
:return: PIL.Image
"""
in_bytes = bytearray(im.tobytes())
channels = int(len(in_bytes) / (im.width * im.height))
out_bytes = bytearray((self._raw_realsr.scale ** 2) * len(in_bytes))
raw_in_image = wrapped.Image(in_bytes, im.width, im.height, channels)
raw_out_image = wrapped.Image(
out_bytes,
self._raw_realsr.scale * im.width,
self._raw_realsr.scale * im.height,
channels,
)
self._raw_realsr.process(raw_in_image, raw_out_image)
return Image.frombytes(
im.mode,
(self._raw_realsr.scale * im.width, self._raw_realsr.scale * im.height),
bytes(out_bytes),
)
def get_prepadding(self) -> int:
if self.model.find("models-DF2K") or self.model.find("models-DF2K_JPEG"):
return 10
else:
raise NotImplementedError(f'model "{self.model}" is not supported')
def get_tilesize(self):
if self.model.find("models-DF2K") or self.model.find("models-DF2K_JPEG"):
if self.gpuid >= 0:
heap_budget = wrapped.get_heap_budget(self.gpuid)
if heap_budget > 1900:
return 200
elif heap_budget > 550:
return 100
elif heap_budget > 190:
return 64
else:
return 32
else:
return 200
else:
raise NotImplementedError(f'model "{self.model}" is not supported')
class RealSR(Realsr):
...
|
lines = []
with open("Sample Text.txt", 'r+') as f:
lines = f.read().split("\n")
words = []
for line in lines:
for word in line.split():
words.append(word)
characters = []
for word in words:
for character in word:
characters.append(character)
print("Number of Lines :", len(lines))
print("Number of Words :", len(words))
print("Number of Characters :", len(characters))
|
{
PDBConst.Name: "family",
PDBConst.Columns: [
{
PDBConst.Name: "ID",
PDBConst.Attributes: ["int", "not null", "auto_increment", "primary key"]
},
{
PDBConst.Name: "Name",
PDBConst.Attributes: ["varchar(128)", "not null"]
}],
PDBConst.Initials: [
{"Name": "\"E&J\'s\""}
]
}
|
import sys
import paper_scissor_rock
if __name__ == "__main__":
game = paper_scissor_rock.RockPaperScissors()
# options needed to RockPaperScissors instance with parameters
# options = {'rock': 0, 'paper': 1, 'scissors': 2}
# test_dict = {
# "ties": 0,
# "wins": 0,
# "losses": 0,
# }
# player1 = options['scissors']
# Below example of using with player1 fixed
# game.play_ngames(n=5, random_pl1=False, player1=options["rock"])
while True:
result = game.play_ngames()
game.print_score(result)
while True:
user_input = input('\nDo you wish to play again? (y/n): ').lower()
if user_input == 'n':
sys.exit("Exit the game")
elif user_input == 'y':
break
else:
print("Invalid input!\n")
continue
|
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------------------
from unittest import main
from io import StringIO
import os
import pandas as pd
from tornado.escape import json_decode
from qiita_db.metadata_template.util import load_template_to_dataframe
from qiita_db.metadata_template.prep_template import PrepTemplate
from qiita_pet.test.rest.test_base import RESTHandlerTestCase
from qiita_db.util import get_mountpoint
class StudyPrepCreatorTests(RESTHandlerTestCase):
def test_post_non_existant_study(self):
# study id that does not exist
prep = StringIO(EXP_PREP_TEMPLATE.format(0))
prep_table = load_template_to_dataframe(prep)
response = self.post('/api/v1/study/0/preparation?'
'&data_type=16S',
data=prep_table.T.to_dict(),
headers=self.headers, asjson=True)
self.assertEqual(response.code, 404)
def test_post_non_matching_identifiers(self):
prep = StringIO(EXP_PREP_TEMPLATE.format(100))
prep_table = load_template_to_dataframe(prep)
response = self.post('/api/v1/study/1/preparation?'
'data_type=16S',
data=prep_table.T.to_dict(),
headers=self.headers, asjson=True)
self.assertEqual(response.code, 406)
obs = json_decode(response.body)
self.assertCountEqual(obs.keys(), ['message'])
self.assertGreater(len(obs['message']), 0)
def test_post_valid_study(self):
prep = StringIO(EXP_PREP_TEMPLATE.format(1))
prep_table = load_template_to_dataframe(prep)
response = self.post('/api/v1/study/1/preparation?data_type=16S',
data=prep_table.T.to_dict(),
headers=self.headers, asjson=True)
self.assertEqual(response.code, 201)
exp = json_decode(response.body)
exp_prep = PrepTemplate(exp['id']).to_dataframe()
prep_table.index.name = 'sample_id'
# sort columns to be comparable
prep_table = prep_table[sorted(prep_table.columns.tolist())]
exp_prep = exp_prep[sorted(exp_prep.columns.tolist())]
exp_prep.drop('qiita_prep_id', axis=1, inplace=True)
pd.util.testing.assert_frame_equal(prep_table, exp_prep)
class StudyPrepArtifactCreatorTests(RESTHandlerTestCase):
def test_post_non_existant_study(self):
uri = '/api/v1/study/0/preparation/0/artifact'
body = {'artifact_type': 'foo', 'filepaths': [['foo.txt', 1],
['bar.txt', 1]],
'artifact_name': 'a name is a name'}
response = self.post(uri, data=body, headers=self.headers, asjson=True)
exp = {'message': 'Study not found'}
self.assertEqual(response.code, 404)
obs = json_decode(response.body)
self.assertEqual(obs, exp)
def test_post_non_existant_prep(self):
uri = '/api/v1/study/1/preparation/1337/artifact'
body = {'artifact_type': 'foo', 'filepaths': [['foo.txt', 1],
['bar.txt', 1]],
'artifact_name': 'a name is a name'}
response = self.post(uri, data=body, headers=self.headers, asjson=True)
exp = {'message': 'Preparation not found'}
self.assertEqual(response.code, 404)
obs = json_decode(response.body)
self.assertEqual(obs, exp)
def test_post_unknown_artifact_type(self):
uri = '/api/v1/study/1/preparation/1/artifact'
body = {'artifact_type': 'foo', 'filepaths': [['foo.txt', 1],
['bar.txt', 1]],
'artifact_name': 'a name is a name'}
response = self.post(uri, data=body, headers=self.headers, asjson=True)
self.assertEqual(response.code, 406)
obs = json_decode(response.body)
self.assertCountEqual(obs.keys(), ['message'])
self.assertGreater(len(obs['message']), 0)
def test_post_unknown_filepath_type_id(self):
uri = '/api/v1/study/1/preparation/1/artifact'
body = {'artifact_type': 'foo', 'filepaths': [['foo.txt', 123123],
['bar.txt', 1]],
'artifact_name': 'a name is a name'}
response = self.post(uri, data=body, headers=self.headers, asjson=True)
self.assertEqual(response.code, 406)
obs = json_decode(response.body)
self.assertCountEqual(obs.keys(), ['message'])
self.assertGreater(len(obs['message']), 0)
def test_post_files_notfound(self):
uri = '/api/v1/study/1/preparation/1/artifact'
body = {'artifact_type': 'foo', 'filepaths': [['foo.txt', 1],
['bar.txt', 1]],
'artifact_name': 'a name is a name'}
response = self.post(uri, data=body, headers=self.headers, asjson=True)
self.assertEqual(response.code, 406)
obs = json_decode(response.body)
self.assertCountEqual(obs.keys(), ['message'])
self.assertGreater(len(obs['message']), 0)
def test_post_valid(self):
dontcare, uploads_dir = get_mountpoint('uploads')[0]
foo_fp = os.path.join(uploads_dir, '1', 'foo.txt')
bar_fp = os.path.join(uploads_dir, '1', 'bar.txt')
with open(foo_fp, 'w') as fp:
fp.write("@x\nATGC\n+\nHHHH\n")
with open(bar_fp, 'w') as fp:
fp.write("@x\nATGC\n+\nHHHH\n")
prep = StringIO(EXP_PREP_TEMPLATE.format(1))
prep_table = load_template_to_dataframe(prep)
response = self.post('/api/v1/study/1/preparation?data_type=16S',
data=prep_table.T.to_dict(),
headers=self.headers, asjson=True)
prepid = json_decode(response.body)['id']
uri = '/api/v1/study/1/preparation/%d/artifact' % prepid
# 1 -> fwd or rev sequences in fastq
# 3 -> barcodes
body = {'artifact_type': 'FASTQ', 'filepaths': [['foo.txt', 1],
['bar.txt',
'raw_barcodes']],
'artifact_name': 'a name is a name'}
response = self.post(uri, data=body, headers=self.headers, asjson=True)
self.assertEqual(response.code, 201)
obs = json_decode(response.body)['id']
prep_instance = PrepTemplate(prepid)
exp = prep_instance.artifact.id
self.assertEqual(obs, exp)
EXP_PREP_TEMPLATE = (
'sample_name\tbarcode\tcenter_name\tcenter_project_name\t'
'ebi_submission_accession\temp_status\texperiment_design_description\t'
'instrument_model\tlibrary_construction_protocol\tplatform\tprimer\t'
'bar\trun_prefix\tstr_column\n'
'{0}.SKB7.640196\tCCTCTGAGAGCT\tANL\tTest Project\t\tEMP\tBBBB\t'
'Illumina MiSeq\tAAAA\tIllumina\tGTGCCAGCMGCCGCGGTAA\tfoo\t'
's_G1_L002_sequences\tValue for sample 3\n'
'{0}.SKB8.640193\tGTCCGCAAGTTA\tANL\tTest Project\t\tEMP\tBBBB\t'
'Illumina MiSeq\tAAAA\tIllumina\tGTGCCAGCMGCCGCGGTAA\tfoo\t'
's_G1_L001_sequences\tValue for sample 1\n'
'{0}.SKD8.640184\tCGTAGAGCTCTC\tANL\tTest Project\t\tEMP\tBBBB\t'
'Illumina MiSeq\tAAAA\tIllumina\tGTGCCAGCMGCCGCGGTAA\tfoo\t'
's_G1_L001_sequences\tValue for sample 2\n')
if __name__ == '__main__':
main()
|
from django.conf import settings
from daemonextension import DaemonCommand
from django.core.management import call_command
class Command(DaemonCommand):
def handle_daemon(self, *args, **options):
options.pop('pidfile',None)
call_command('celerycam',*args,**options)
|
# Generated by Django 2.2.6 on 2019-10-27 10:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('techei', '0031_eventimage'),
]
operations = [
migrations.AlterField(
model_name='eventimage',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='techei.InstitutionProfile'),
),
migrations.AlterField(
model_name='eventmodel',
name='fee',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='eventmodel',
name='paylink',
field=models.CharField(blank=True, max_length=30, null=True),
),
migrations.AlterField(
model_name='eventmodel',
name='prize',
field=models.IntegerField(blank=True, null=True),
),
]
|
"""模块的公开方法.
避免让外部直接访问定义的对象,以此来进行解耦.
"""
import contextlib
from typing import Type
from playhouse.db_url import connect
from .user import User
from ._base import (
db,
BaseModel,
Tables
)
def bind_db(dburl: str):
"""指定数据库的url初始化代理对象并创建表.
Args:
dburl (str): 支持peewee所支持的数据库url写法
"""
database = connect(dburl)
db.initialize(database)
db.create_tables(list(Tables.values()), safe=True)
def drop_tables():
"""清理数据库.
注意通常用于测试环境或清理脚本
"""
db.drop_tables(list(Tables.values()), safe=True)
db.close()
def get_table(name: str)->Type[BaseModel]:
"""避免暴露类而使用一个方法来作为工厂.
Args:
name (str): 表名
Returns:
Type[BaseModel]: [description]
"""
return Tables.get(name)
def moke_data():
"""创建假数据.
通常用于测试环境.
"""
data_source = [
{
"age": 11,
"name": "Liu"
},
{
"age": 10,
"name": "Li"
},
{
"age": 11,
"name": "Lu"
},
{
"age": 9,
"name": "Xu"
},
]
User.insert_many(data_source).execute()
@contextlib.contextmanager
def query():
"""确保对数据库的请求有连接可用,并且在使用完后关闭连接的上下文管理器."""
try:
db.connect()
except:
pass
yield db
db.close()
__all__ = ["drop_tables", "bind_db", "get_table", "query","moke_data"]
|
soma = 0
cont = 0
for c in range(1,7):
n= int(input(f'Digite o {c}º valor: '))
if n % 2 == 0:
cont += 1
soma += n
print(f'Você informou {cont} número(s) par(es), e a soma entre todos eles é {soma}')
|
from random import randrange
def playgame():
Choices = ["Rock","Paper","Scissors","ROCK","PAPER","SCISSORS","rock","paper","scissors","R","P","S","r","p","s"]
choosing = True
user_input = 0
while choosing:
user_input = raw_input("Rock(r), Paper(p), or Scissors(s): ")
if user_input in Choices:
choosing = False
user_input = Choices.index(user_input) % 3
else:
print("Please try again")
comp_input = randrange(3)
result = ""
if user_input == comp_input:
result = "Its a tie!"
elif (user_input + 1) % 3== comp_input:
result = "You lose!"
else:
result = "You win!"
print "Computer's Choice: %s \nPlayer's Choice: %s \n%s" % (Choices[comp_input], Choices[user_input], result)
Playing = True
while Playing:
playgame()
again = raw_input("Play Again? Yes(y) / No(n): ")
if not again in ["Yes", "YES", "yes", "Y", "y"]:
Playing = False
|
# -*- coding: utf-8 -*-
from snippets.admin.actions import deactivate_action, activate_action # NOQA
from snippets.admin.filters import IsNullFieldListFilter # NOQA
from snippets.admin.admin import SuperUserDeletableAdminMixin, BaseModelAdmin # NOQA
|
from collections import deque
def solve(data, upper):
sorted_intervals = deque(sorted([(int(start), int(end)) for line in data for start, end in [line.split('-')]], key=lambda x: x[0]))
# [(0, 2), (4, 7), (5, 8)]
answers = []
total, n, index = 0, 0, 0
while n < upper:
start, end = sorted_intervals[index]
if n >= start:
if n <= end:
n = end + 1
continue
index += 1
else:
total += 1
answers.append(n)
n += 1
return total, sorted(answers)
if __name__ == '__main__':
with open('input.txt') as f:
data = f.read().splitlines()
print(solve(data, 2**32))
#data = ['5-8','0-2','4-7']
#print(solve(data, 9))
|
# Author : Dharatiben Shah
# Date : 04-17-2021
import os
import sqlite3
import random
from getpass import getpass
# create a database - sqllite3 as it comes with python installation
# this will create a database called "auth.sqlite3" in the same directory as the script
DEFAULT_PATH = os.path.join(os.path.dirname(__file__), "auth.sqllite3")
def init():
print("****** Welcome to bankPHP *******")
have_account = int(
input("Do you have an account with us ? Select 1(yes), 2(No) \n")
)
if have_account == 1:
login()
elif have_account == 2:
# run the function to create the user_info table in sqlite3 database
create_db_object(db_connect())
register()
else:
print(
f"You have selected - {have_account} which is NOT a valid option ! Try again"
)
init()
def db_connect(db_path=DEFAULT_PATH):
"""Returns a connection string back
with sqlite3 database
"""
con = sqlite3.connect(db_path)
return con
def generation_account_number():
"""Generate 10 digit random integer account number"""
return random.randrange(1111111111, 9999999999)
def create_db_object(con):
"""Creates a table in sqlite3 database"""
sql = """CREATE table if not exists user_info (account_number INT, first_name TEXT, last_name TEXT, email TEXT, password TEXT, balance int default 0);"""
try:
cur = con.cursor()
cur.execute(sql)
con.commit()
return True
except:
con.rollback()
raise RuntimeError(
"There is a problem creating user_info table in the sqlite database"
)
def create_new_login_in_db(con, first_name, last_name, email, password):
"""Given first_name, last_name, email, password - this function generates a random account number
and inserts the values in the user_info table in sqlite3 database"""
sql = """
INSERT INTO user_info (account_number, first_name, last_name, email, password)
values (?, ?, ?, ?, ?);"""
# open cursor
cur = con.cursor()
try:
account_number = generation_account_number()
cur.execute(sql, (account_number, first_name, last_name, email, password))
# commit the transaction
con.commit()
con.close()
return account_number
except:
con.rollback()
raise RuntimeError("There is a problem inserting record in sqlite database")
def register():
"""Asks new users their email, first_name, last_name, password
and provides them with an account number
"""
email = input("What is your email address? \n")
first_name = input("What is your first name? \n")
last_name = input("What is your last name? \n")
password = getpass("Create a password for yourself \n")
account_created = create_new_login_in_db(
db_connect(), first_name, last_name, email, password
)
if account_created:
print("Your Account Has been created with the password you provided")
print(" == ==== ====== ===== ===")
print(f"Your account number is: {account_created}")
print("Make sure you keep it safe and remember your password")
print(" == ==== ====== ===== ===")
# take the user to login
login()
else:
print("Account registration failed .. please try again")
register()
def is_account_number_valid(con, account_number):
"""This function checks if a given account number is valid or not by querying the sqlite3 database"""
cur = con.cursor()
cur.execute(
"select account_number, password, first_name, last_name, balance from user_info where account_number=?",
(account_number,),
)
results = cur.fetchone()
# this will be a tuple
con.close()
return results
def login():
"""This function facilitates the login process
given a valid account number and password"""
print("****** Welcome to Bank Login ******")
user_account_number = input("Please provide your account number to login: \n")
user_password = getpass("What is your password ? \n")
valid_account = is_account_number_valid(db_connect(), user_account_number)
if valid_account is not None and (user_password == valid_account[1]):
print(
f"Account number {user_account_number} matches the account number {valid_account[0]} found in database "
)
bank_operation(valid_account)
else:
print(
f"Try Again -- Account number - {user_account_number} and/or Password are incorrect \n"
)
# send back to login to try again
login()
# bank operations
def bank_operation(valid_account):
print(f"Welcome {valid_account[2]} {valid_account[3]}")
operation_selected = int(
input(
"What would you like to do ? (1) deposit, (2) withdrawl, (3) Logout, (4) Exit \n"
)
)
if operation_selected == 1:
deposit_operation(valid_account)
elif operation_selected == 2:
withdrawal_operation(valid_account)
elif operation_selected == 3:
logout()
elif operation_selected == 4:
exit()
else:
print("Invalid option selected")
bank_operation(valid_account)
def update_database(con, valid_account, amount, operation):
account_details = is_account_number_valid(db_connect(), valid_account[0])
account_number = account_details[0]
current_balance = account_details[4]
if operation == "deposit":
new_balance = current_balance + amount
elif operation == "withdraw":
new_balance = current_balance - amount
else:
print("invalid operation - has to be deposit or withdraw")
cur = con.cursor()
cur.execute(
"UPDATE user_info SET balance =? WHERE account_number=?",
(new_balance, account_number),
)
con.commit()
print(f"updated current_balance: {current_balance} to new_balance: {new_balance} for account number : {account_number}")
con.close()
def withdrawal_operation(valid_account):
print("withdrawal")
# get current balance
account_details = is_account_number_valid(db_connect(), valid_account[0])
current_balance = account_details[4]
print(f"Your current balance is $ {current_balance}")
# get amount to withdraw
withdraw_amount = int(input("How much you want to withdraw from your account ?\n"))
# check if current balance > withdraw balance
# deduct withdrawn amount form current balance
# display current balance
if current_balance >= withdraw_amount:
update_database(db_connect(), account_details, withdraw_amount,"withdraw")
print(f"Thank you for withdrawing {withdraw_amount}")
print(f"Your current balance is :{current_balance - withdraw_amount}")
bank_operation(valid_account)
else:
print(
f"Sorry, you cant withdraw more money than you have in your account. You have {current_balance}."
)
bank_operation(valid_account)
# deduct withdrawn amount form current balance
# display current balance
def deposit_operation(valid_account):
print("Deposit Operations")
# get current balance
account_details = is_account_number_valid(db_connect(), valid_account[0])
current_balance = account_details[4]
print(f"Your current balance is $ {current_balance}")
# get amount to deposit
deposit_amount = int(input("How much you want to deposit in your account ?\n"))
# add deposited amount to current balance
# display current balance
update_database(db_connect(), account_details, deposit_amount, "deposit")
print(f"Thank you for depositing {deposit_amount}")
print(f"Your NEW balance is :{current_balance + deposit_amount}")
bank_operation(valid_account)
def logout():
print("You are successfully logged out")
login()
# Run the init function
init()
|
from ED6ScenarioHelper import *
def main():
# 蔡斯
CreateScenaFile(
FileName = 'T3105 ._SN',
MapName = 'Zeiss',
Location = 'T3105.x',
MapIndex = 1,
MapDefaultBGM = "ed60084",
Flags = 0,
EntryFunctionIndex = 0xFFFF,
Reserved = 0,
IncludedScenario = [
'',
'',
'',
'',
'',
'',
'',
''
],
)
BuildStringList(
'@FileName', # 8
'格斯塔夫维修长', # 9
'吉拉尔', # 10
'玛多克工房长', # 11
'朵洛希', # 12
'安东尼', # 13
'凯诺娜上尉', # 14
'鲁特尔', # 15
'多杰', # 16
'巴拉特', # 17
'蔡斯市·工房区', # 18
)
DeclEntryPoint(
Unknown_00 = 0,
Unknown_04 = 0,
Unknown_08 = 6000,
Unknown_0C = 4,
Unknown_0E = 0,
Unknown_10 = 0,
Unknown_14 = 9500,
Unknown_18 = -10000,
Unknown_1C = 0,
Unknown_20 = 0,
Unknown_24 = 0,
Unknown_28 = 2800,
Unknown_2C = 262,
Unknown_30 = 45,
Unknown_32 = 0,
Unknown_34 = 360,
Unknown_36 = 0,
Unknown_38 = 0,
Unknown_3A = 0,
InitScenaIndex = 0,
InitFunctionIndex = 0,
EntryScenaIndex = 0,
EntryFunctionIndex = 1,
)
AddCharChip(
'ED6_DT07/CH01290 ._CH', # 00
'ED6_DT07/CH02440 ._CH', # 01
'ED6_DT07/CH02620 ._CH', # 02
'ED6_DT07/CH02070 ._CH', # 03
'ED6_DT07/CH01700 ._CH', # 04
'ED6_DT07/CH02100 ._CH', # 05
'ED6_DT07/CH01020 ._CH', # 06
'ED6_DT07/CH01140 ._CH', # 07
'ED6_DT07/CH01450 ._CH', # 08
)
AddCharChipPat(
'ED6_DT07/CH01290P._CP', # 00
'ED6_DT07/CH02440P._CP', # 01
'ED6_DT07/CH02620P._CP', # 02
'ED6_DT07/CH02070P._CP', # 03
'ED6_DT07/CH01700P._CP', # 04
'ED6_DT07/CH02100P._CP', # 05
'ED6_DT07/CH01020P._CP', # 06
'ED6_DT07/CH01140P._CP', # 07
'ED6_DT07/CH01450P._CP', # 08
)
DeclNpc(
X = -37000,
Z = -3800,
Y = 145500,
Direction = 180,
Unknown2 = 0,
Unknown3 = 1,
ChipIndex = 0x1,
NpcIndex = 0x181,
InitFunctionIndex = 0,
InitScenaIndex = 2,
TalkFunctionIndex = 0,
TalkScenaIndex = 8,
)
DeclNpc(
X = -20110,
Z = 8000,
Y = 121830,
Direction = 177,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x0,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = 0,
TalkScenaIndex = 10,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 180,
Unknown2 = 0,
Unknown3 = 2,
ChipIndex = 0x2,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = 0,
TalkScenaIndex = 11,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 180,
Unknown2 = 0,
Unknown3 = 3,
ChipIndex = 0x3,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 180,
Unknown2 = 0,
Unknown3 = 4,
ChipIndex = 0x4,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = 0,
TalkScenaIndex = 9,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 180,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x0,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 180,
Unknown2 = 0,
Unknown3 = 6,
ChipIndex = 0x6,
NpcIndex = 0x181,
InitFunctionIndex = 0,
InitScenaIndex = 2,
TalkFunctionIndex = 0,
TalkScenaIndex = 12,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 180,
Unknown2 = 0,
Unknown3 = 7,
ChipIndex = 0x7,
NpcIndex = 0x181,
InitFunctionIndex = 0,
InitScenaIndex = 2,
TalkFunctionIndex = 0,
TalkScenaIndex = 13,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 180,
Unknown2 = 0,
Unknown3 = 8,
ChipIndex = 0x8,
NpcIndex = 0x181,
InitFunctionIndex = 0,
InitScenaIndex = 2,
TalkFunctionIndex = 0,
TalkScenaIndex = 7,
)
DeclNpc(
X = -18770,
Z = 8000,
Y = 89560,
Direction = 0,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x0,
NpcIndex = 0xFF,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclActor(
TriggerX = -41010,
TriggerZ = 8000,
TriggerY = 122500,
TriggerRange = 800,
ActorX = -41010,
ActorZ = 10200,
ActorY = 122500,
Flags = 0x7C,
TalkScenaIndex = 0,
TalkFunctionIndex = 19,
Unknown_22 = 0,
)
DeclActor(
TriggerX = -38900,
TriggerZ = 8400,
TriggerY = 122040,
TriggerRange = 800,
ActorX = -38900,
ActorZ = 9900,
ActorY = 122040,
Flags = 0x7C,
TalkScenaIndex = 0,
TalkFunctionIndex = 20,
Unknown_22 = 0,
)
ScpFunction(
"Function_0_27A", # 00, 0
"Function_1_4DC", # 01, 1
"Function_2_4EF", # 02, 2
"Function_3_66C", # 03, 3
"Function_4_690", # 04, 4
"Function_5_6B4", # 05, 5
"Function_6_6D8", # 06, 6
"Function_7_6FC", # 07, 7
"Function_8_F5E", # 08, 8
"Function_9_11B9", # 09, 9
"Function_10_11F2", # 0A, 10
"Function_11_2414", # 0B, 11
"Function_12_3271", # 0C, 12
"Function_13_35EE", # 0D, 13
"Function_14_36D6", # 0E, 14
"Function_15_36DB", # 0F, 15
"Function_16_3F81", # 10, 16
"Function_17_44F5", # 11, 17
"Function_18_4835", # 12, 18
"Function_19_5924", # 13, 19
"Function_20_59DF", # 14, 20
)
def Function_0_27A(): pass
label("Function_0_27A")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 3)), scpexpr(EXPR_END)), "loc_2B7")
ClearChrFlags(0xE, 0x80)
SetChrPos(0xE, -17880, 8000, 118110, 183)
OP_43(0xE, 0x0, 0x0, 0x3)
ClearChrFlags(0x10, 0x80)
SetChrPos(0x10, -44660, 8000, 129500, 5)
Jump("loc_4DB")
label("loc_2B7")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 1)), scpexpr(EXPR_END)), "loc_2F4")
ClearChrFlags(0xE, 0x80)
SetChrPos(0xE, -17880, 8000, 118110, 183)
OP_43(0xE, 0x0, 0x0, 0x3)
ClearChrFlags(0x10, 0x80)
SetChrPos(0x10, -44660, 8000, 129500, 5)
Jump("loc_4DB")
label("loc_2F4")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 5)), scpexpr(EXPR_END)), "loc_314")
ClearChrFlags(0x10, 0x80)
SetChrPos(0x10, -44750, -4000, 146070, 81)
Jump("loc_4DB")
label("loc_314")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 1)), scpexpr(EXPR_END)), "loc_37D")
ClearChrFlags(0xE, 0x80)
SetChrPos(0xE, -47500, -4000, 151780, 261)
ClearChrFlags(0xF, 0x80)
SetChrPos(0xF, -47500, -4000, 152840, 261)
ClearChrFlags(0xC, 0x80)
SetChrPos(0xC, -40130, 8000, 125930, 237)
OP_43(0xC, 0x0, 0x0, 0x4)
ClearChrFlags(0x10, 0x80)
SetChrPos(0x10, -44750, -4000, 146070, 81)
Jump("loc_4DB")
label("loc_37D")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAA, 0)), scpexpr(EXPR_END)), "loc_3BD")
ClearChrFlags(0x8, 0x80)
SetChrPos(0x8, -44530, -4000, 142000, 176)
SetChrFlags(0x8, 0x10)
ClearChrFlags(0x10, 0x80)
SetChrPos(0x10, -44510, -4000, 140610, 21)
SetChrFlags(0x10, 0x10)
Jump("loc_4DB")
label("loc_3BD")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 7)), scpexpr(EXPR_END)), "loc_3FA")
ClearChrFlags(0x8, 0x80)
SetChrPos(0x8, -58040, 4000, 125930, 187)
OP_43(0x8, 0x0, 0x0, 0x6)
ClearChrFlags(0x10, 0x80)
SetChrPos(0x10, -44750, -4000, 146070, 81)
Jump("loc_4DB")
label("loc_3FA")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA5, 0)), scpexpr(EXPR_END)), "loc_404")
Jump("loc_4DB")
label("loc_404")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_441")
ClearChrFlags(0x8, 0x80)
SetChrPos(0x8, -49800, 8000, 117400, 3)
OP_43(0x8, 0x0, 0x0, 0x5)
ClearChrFlags(0x10, 0x80)
SetChrPos(0x10, -44750, -4000, 146070, 81)
Jump("loc_4DB")
label("loc_441")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 3)), scpexpr(EXPR_END)), "loc_461")
ClearChrFlags(0x10, 0x80)
SetChrPos(0x10, -44750, -4000, 146070, 81)
Jump("loc_4DB")
label("loc_461")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 1)), scpexpr(EXPR_END)), "loc_481")
ClearChrFlags(0x10, 0x80)
SetChrPos(0x10, -44750, -4000, 146070, 81)
Jump("loc_4DB")
label("loc_481")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA1, 6)), scpexpr(EXPR_END)), "loc_4A1")
ClearChrFlags(0x10, 0x80)
SetChrPos(0x10, -44750, -4000, 146070, 81)
Jump("loc_4DB")
label("loc_4A1")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 2)), scpexpr(EXPR_END)), "loc_4DB")
ClearChrFlags(0xC, 0x80)
SetChrPos(0xC, -40130, 8000, 125930, 237)
OP_43(0xC, 0x0, 0x0, 0x4)
ClearChrFlags(0x10, 0x80)
SetChrPos(0x10, -44750, -4000, 146070, 81)
label("loc_4DB")
Return()
# Function_0_27A end
def Function_1_4DC(): pass
label("Function_1_4DC")
OP_16(0x2, 0xFA0, 0xFFFD6020, 0x4E20, 0x30053)
Return()
# Function_1_4DC end
def Function_2_4EF(): pass
label("Function_2_4EF")
RunExpression(0x1, (scpexpr(EXPR_RAND), scpexpr(EXPR_PUSH_LONG, 0xE), scpexpr(EXPR_IMOD), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_514")
OP_99(0xFE, 0x0, 0x7, 0x672)
Jump("loc_656")
label("loc_514")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_52D")
OP_99(0xFE, 0x1, 0x7, 0x640)
Jump("loc_656")
label("loc_52D")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0x2), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_546")
OP_99(0xFE, 0x2, 0x7, 0x60E)
Jump("loc_656")
label("loc_546")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0x3), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_55F")
OP_99(0xFE, 0x3, 0x7, 0x5DC)
Jump("loc_656")
label("loc_55F")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0x4), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_578")
OP_99(0xFE, 0x4, 0x7, 0x5AA)
Jump("loc_656")
label("loc_578")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0x5), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_591")
OP_99(0xFE, 0x5, 0x7, 0x578)
Jump("loc_656")
label("loc_591")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0x6), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_5AA")
OP_99(0xFE, 0x6, 0x7, 0x546)
Jump("loc_656")
label("loc_5AA")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0x7), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_5C3")
OP_99(0xFE, 0x0, 0x7, 0x677)
Jump("loc_656")
label("loc_5C3")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0x8), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_5DC")
OP_99(0xFE, 0x1, 0x7, 0x645)
Jump("loc_656")
label("loc_5DC")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0x9), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_5F5")
OP_99(0xFE, 0x2, 0x7, 0x613)
Jump("loc_656")
label("loc_5F5")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0xA), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_60E")
OP_99(0xFE, 0x3, 0x7, 0x5E1)
Jump("loc_656")
label("loc_60E")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0xB), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_627")
OP_99(0xFE, 0x4, 0x7, 0x5AF)
Jump("loc_656")
label("loc_627")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0xC), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_640")
OP_99(0xFE, 0x5, 0x7, 0x57D)
Jump("loc_656")
label("loc_640")
Jc((scpexpr(EXPR_GET_RESULT, 0x1), scpexpr(EXPR_PUSH_LONG, 0xD), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_656")
OP_99(0xFE, 0x6, 0x7, 0x54B)
label("loc_656")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_66B")
OP_99(0xFE, 0x0, 0x7, 0x5DC)
Jump("loc_656")
label("loc_66B")
Return()
# Function_2_4EF end
def Function_3_66C(): pass
label("Function_3_66C")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_68F")
OP_8D(0xFE, -19390, 119560, -16690, 116060, 3000)
Jump("Function_3_66C")
label("loc_68F")
Return()
# Function_3_66C end
def Function_4_690(): pass
label("Function_4_690")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_6B3")
OP_8D(0xFE, -35820, 123780, -43940, 129220, 3000)
Jump("Function_4_690")
label("loc_6B3")
Return()
# Function_4_690 end
def Function_5_6B4(): pass
label("Function_5_6B4")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_6D7")
OP_8D(0xFE, -45240, 117320, -51970, 121500, 3000)
Jump("Function_5_6B4")
label("loc_6D7")
Return()
# Function_5_6B4 end
def Function_6_6D8(): pass
label("Function_6_6D8")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_6FB")
OP_8D(0xFE, -56420, 122640, -59470, 129340, 3000)
Jump("Function_6_6D8")
label("loc_6FB")
Return()
# Function_6_6D8 end
def Function_7_6FC(): pass
label("Function_7_6FC")
TalkBegin(0xFE)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 3)), scpexpr(EXPR_END)), "loc_77F")
ChrTalk(
0xFE,
(
"呼……\x01",
"都不通知一下就检查,\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"王国军真是的,\x01",
"实在太乱来了。\x02",
)
)
CloseMessageWindow()
Jump("loc_F5A")
label("loc_77F")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 1)), scpexpr(EXPR_END)), "loc_7EB")
ChrTalk(
0xFE,
(
"一会儿『赛希莉亚号』\x01",
"就要开过来了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"必须马上开始\x01",
"确认下拢岸的状况了。\x02",
)
)
CloseMessageWindow()
Jump("loc_F5A")
label("loc_7EB")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 5)), scpexpr(EXPR_END)), "loc_8AB")
ChrTalk(
0xFE,
(
"工房船现在\x01",
"马上就要出航了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"不过,\x01",
"却比预定去要塞的时间提前了很多……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
"那边发生了什么事吗?\x02",
)
CloseMessageWindow()
Jump("loc_F5A")
label("loc_8AB")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 1)), scpexpr(EXPR_END)), "loc_8FB")
ChrTalk(
0xFE,
(
"好了,\x01",
"这样飞船起航就告一段落了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"总之,\x01",
"趁这段时间整理一下货物吧。\x02",
)
)
CloseMessageWindow()
Jump("loc_F5A")
label("loc_8FB")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAA, 0)), scpexpr(EXPR_END)), "loc_9E6")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 5)), scpexpr(EXPR_END)), "loc_97D")
ChrTalk(
0xFE,
(
"话说回来,这种时候\x01",
"真是羡慕雷曼那家伙啊。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"那家伙兼任驾驶员,\x01",
"飞行前为了调整身体状态,\x01",
"早早地就回家去了。\x02",
)
)
CloseMessageWindow()
Jump("loc_9E3")
label("loc_97D")
OP_A2(0x5)
ChrTalk(
0xFE,
"呼,明天还是要去要塞啊。\x02",
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"最近的工作\x01",
"好像很多啊。\x02",
)
)
CloseMessageWindow()
ClearChrFlags(0xFE, 0x10)
label("loc_9E3")
Jump("loc_F5A")
label("loc_9E6")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 7)), scpexpr(EXPR_END)), "loc_ABB")
ChrTalk(
0xFE,
(
"中央工房的事件\x01",
"应该解决了吧。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"哎?\x01",
"犯人到现在都还没抓到?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"那还真是糟糕啊。\x01",
"下次不会来袭击工房船吧。\x02",
)
)
CloseMessageWindow()
Jump("loc_F5A")
label("loc_ABB")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_D03")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 5)), scpexpr(EXPR_END)), "loc_BB2")
ChrTalk(
0xFE,
(
"呼,都是因为那个公爵大人,\x01",
"搞得大家都对王家的印象变差了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"哼,很久以前\x01",
"那种快乐纯粹的女王诞辰庆典\x01",
"是很难再出现了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"该死,那个混账公爵。\x01",
"还我的诞辰庆典来!\x02",
)
)
CloseMessageWindow()
Jump("loc_D00")
label("loc_BB2")
OP_A2(0x5)
ChrTalk(
0xFE,
(
"之前的休假\x01",
"我去参观了\x01",
"艾尔·雷登瀑布……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"竟遇到那个叫杜什么的公爵,\x01",
"那个王家的人微服出行。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"而且那个人\x01",
"还蛮横任性得要命。\x01",
"真是倒了大霉了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"唔,大家都没想到\x01",
"王家的人竟会是那个样子。\x01",
"真是失望透了。\x02",
)
)
CloseMessageWindow()
label("loc_D00")
Jump("loc_F5A")
label("loc_D03")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 3)), scpexpr(EXPR_END)), "loc_DB4")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 7)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_D33")
ChrTalk(
0xFE,
(
"嗯……\x01",
"差不多该到返航的时候了。\x02",
)
)
CloseMessageWindow()
Jump("loc_DB1")
label("loc_D33")
ChrTalk(
0xFE,
"怎么样?很漂亮吧。\x02",
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"这可是中央工房引以为傲的\x01",
"『莱普尼兹号』啊。\x02",
)
)
CloseMessageWindow()
label("loc_DB1")
Jump("loc_F5A")
label("loc_DB4")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 1)), scpexpr(EXPR_END)), "loc_F16")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 5)), scpexpr(EXPR_END)), "loc_E40")
ChrTalk(
0xFE,
(
"工房好像还没找出\x01",
"昨天那种现象的原因所在吧。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"不管怎样,\x01",
"希望不要再发生这种事情。\x02",
)
)
CloseMessageWindow()
Jump("loc_F13")
label("loc_E40")
OP_A2(0x5)
ChrTalk(
0xFE,
"昨天晚上,导力供应停止了吧?\x02",
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"不过还好不是在白天发生,\x01",
"真是万幸呀。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"如果在飞艇上出现这种情况,\x01",
"真不知道会发生什么事。\x02",
)
)
CloseMessageWindow()
label("loc_F13")
Jump("loc_F5A")
label("loc_F16")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA1, 6)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 2)), scpexpr(EXPR_OR), scpexpr(EXPR_END)), "loc_F5A")
ChrTalk(
0xFE,
"好的,拢岸准备好了。\x02",
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"接下来,\x01",
"要快点进行出发前的检查了。\x02",
)
)
CloseMessageWindow()
label("loc_F5A")
TalkEnd(0xFE)
Return()
# Function_7_6FC end
def Function_8_F5E(): pass
label("Function_8_F5E")
TalkBegin(0xFE)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAA, 0)), scpexpr(EXPR_END)), "loc_FF8")
ChrTalk(
0xFE,
(
"#690F哦,稍微晚了些真是不好意思。\x02\x03",
"要塞那边又来要求我们出动了。\x01",
"我想今天之内\x01",
"就可以做好准备了。\x02\x03",
"嗯,希望和平时一样\x01",
"不要发生什么意外就行了。\x02",
)
)
CloseMessageWindow()
Jump("loc_11B5")
label("loc_FF8")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 7)), scpexpr(EXPR_END)), "loc_10BF")
ChrTalk(
0xFE,
(
"#690F哦,是提妲丫头。\x01",
"没有受伤吧。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x107,
(
"#060F…………………………\x02\x03",
"啊…………\x02\x03",
"啊……是、是的!\x01",
"没事呢。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"#690F怎么啦?\x01",
"你一直在发呆啊。\x02\x03",
"不过,没受伤的话,\x01",
"那比什么都好。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x107,
"#060F…………………………\x02",
)
CloseMessageWindow()
Jump("loc_11B5")
label("loc_10BF")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_11B5")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 4)), scpexpr(EXPR_END)), "loc_10F1")
ChrTalk(
0xFE,
(
"#690F哦,是提妲丫头。\x01",
"多多保重哦。\x02",
)
)
CloseMessageWindow()
Jump("loc_11B5")
label("loc_10F1")
OP_A2(0x4)
ChrTalk(
0xFE,
(
"#690F哦,是提妲丫头。\x02\x03",
"又是拉赛尔老爷子的差使吗。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x107,
(
"#060F啊,是呢。\x02\x03",
"要到亚尔摩村去一趟。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"#690F是吗,那么\x01",
"多多保重哦。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x107,
(
"#060F嗯,\x01",
"那么我们就出发了。\x02",
)
)
CloseMessageWindow()
label("loc_11B5")
TalkEnd(0xFE)
Return()
# Function_8_F5E end
def Function_9_11B9(): pass
label("Function_9_11B9")
TalkBegin(0xFE)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 1)), scpexpr(EXPR_END)), "loc_11D7")
OP_22(0x192, 0x0, 0x64)
ChrTalk(
0xFE,
"喵-噢。\x02",
)
CloseMessageWindow()
Jump("loc_11EE")
label("loc_11D7")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 2)), scpexpr(EXPR_END)), "loc_11EE")
OP_22(0x192, 0x0, 0x64)
ChrTalk(
0xFE,
"喵~噢?\x02",
)
CloseMessageWindow()
label("loc_11EE")
TalkEnd(0xFE)
Return()
# Function_9_11B9 end
def Function_10_11F2(): pass
label("Function_10_11F2")
TalkBegin(0x9)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 2)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 4)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_1600")
OP_A2(0x604)
EventBegin(0x0)
Fade(1000)
SetChrPos(0x101, -20510, 8000, 119230, 0)
SetChrPos(0x102, -18980, 8000, 119430, 0)
def lambda_1233():
OP_6C(0, 2000)
ExitThread()
QueueWorkItem(0x102, 1, lambda_1233)
def lambda_1243():
OP_6B(2750, 2000)
ExitThread()
QueueWorkItem(0x102, 2, lambda_1243)
OP_6D(-20210, 8000, 122050, 2000)
ChrTalk(
0x9,
"啊,是你们啊。\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"就像刚才我说的,\x01",
"飞艇什么时候能来还不知道呢。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"实在抱歉,\x01",
"你们在游击士协会等一会儿吧。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F嗯~其实……\x01",
"我们稍微改变了一下计划。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F抱歉,\x01",
"搭乘手续能取消吗?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"是这样吗……\x01",
"唉,也是没办法的事。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"在定期船到来之前,\x01",
"不需要付取消手续费的。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"把刚才的船票\x01",
"还给我就可以了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F嗯,明白了。\x02",
)
CloseMessageWindow()
FadeToDark(300, 0, 100)
AnonymousTalk(
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"把两张船票还给了接待员。\x02",
)
)
CloseMessageWindow()
OP_56(0x0)
FadeToBright(300, 0)
OP_3F(0x36A, 2)
ChrTalk(
0x9,
(
"哦……\x01",
"好像是军用警备飞艇来了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
"来的还真早啊。\x02",
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F那、那么\x01",
"我们赶快……!\x02",
)
)
CloseMessageWindow()
def lambda_14BC():
OP_8E(0xFE, 0xFFFFB12C, 0x1F40, 0x192A8, 0x1388, 0x0)
ExitThread()
QueueWorkItem(0x101, 1, lambda_14BC)
ChrTalk(
0x102,
(
"#010F麻烦您了,\x01",
"真是不好意思。\x02",
)
)
CloseMessageWindow()
def lambda_14FA():
OP_8E(0xFE, 0xFFFFB7F8, 0x1F40, 0x192A8, 0x1388, 0x0)
ExitThread()
QueueWorkItem(0x102, 1, lambda_14FA)
ChrTalk(
0x9,
(
"啊啊。\x01",
"欢迎下次再来乘坐啊。\x02",
)
)
CloseMessageWindow()
Sleep(1000)
ChrTalk(
0xD,
(
"#180F哼哼……\x01",
"还真是忙啊。\x02\x03",
"首先,还是去\x01",
"拜见一下工房长吧。\x02\x03",
"不过,不愧是上校大人……\x01",
"能想出这样的方法。\x02",
)
)
CloseMessageWindow()
OP_A2(0x3FB)
NewScene("ED6_DT01/T3101 ._SN", 100, 0, 0)
IdleLoop()
Jump("loc_2410")
label("loc_1600")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 1)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 2)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_17BC")
OP_A2(0x602)
OP_28(0x54, 0x1, 0x2)
EventBegin(0x0)
OP_69(0x9, 0x3E8)
ChrTalk(
0x9,
"啊,你们好。\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"我已经从雾香那里听说了。\x01",
"现在就办理搭乘手续吗?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F嗯,麻烦您了。\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"那么,在这张单子上\x01",
"填写姓名和联络方式吧。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F明白了。\x02",
)
CloseMessageWindow()
FadeToDark(300, 0, 100)
AnonymousTalk(
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"艾丝蒂尔\x01",
"办理了搭乘手续。\x02",
)
)
CloseMessageWindow()
OP_56(0x0)
FadeToBright(300, 0)
ChrTalk(
0x9,
(
"好了,\x01",
"这个就是你们的船票。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"定期船到了之后,\x01",
"把这个出示给乘务员就可以了。\x02",
)
)
CloseMessageWindow()
FadeToDark(300, 0, 100)
AnonymousTalk(
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"得到两张船票。\x02",
)
)
CloseMessageWindow()
OP_56(0x0)
FadeToBright(300, 0)
OP_3E(0x36A, 2)
EventEnd(0x1)
Jump("loc_2410")
label("loc_17BC")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 6)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 7)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_1E09")
OP_A2(0x517)
ClearMapFlags(0x1)
OP_69(0x9, 0x3E8)
ChrTalk(
0x9,
"哟!要乘坐飞行船吗?\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"去西面的定期船的话\x01",
"正好刚刚开走……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F没有啊,\x01",
"我们不是来乘飞行船的。\x02\x03",
"格斯塔夫维修长\x01",
"我想让你们两人办点事。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
"什么,找大叔的?\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"大叔的话,\x01",
"现在不在这里……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F哎!出去了吗?\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"是呀。有两三天了。\x01",
"去了雷斯顿要塞。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"好像很急,是个有\x01",
"军用警备飞艇的家伙的委托。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F到雷斯顿要塞呀……\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F是位于瓦雷利亚湖畔的\x01",
"王国军最大的军事基地。\x02\x03",
"在蔡斯地区的北侧。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F呼~~这样的话\x01",
"就不是简单能回来的了。\x02\x03",
"博士要的准备,怎么办呀?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"虽然不知道你们有什么事,\x01",
"但我想他差不多要回来了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
"刚刚有连络通信过来……\x02",
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F哎……\x01",
"下一班定期船已经来了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
"不是的,真是不听人说话的家伙。\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
"#20A莱普尼兹号进入飞艇坪(※假定)\x05\x02",
)
ChrTalk(
0x101,
(
"#000F橙色的定期船……\x02\x03",
"哎呀!\x01",
"有那样的定期船吗?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F不……\x01",
"那好像不是定期船。\x02\x03",
"无论哪里形状都不同,\x01",
"还带有作业用的扶手。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F嗯,的确……\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"这是中央工房所有的\x01",
"工房船《莱普尼兹号》。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"虽然和定期船是相同型号,\x01",
"但追加了各种设备。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"这个主要是用来\x01",
"大型设备的支持和制品的搬运。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F哎~~!\x01",
"飞空的工房呀。\x02\x03",
"那么维修长\x01",
"应该在那艘船上吧?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
"就是这样。\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"你们快点\x01",
"去找他吧。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F嗯,好的。\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F那么我们就告辞了。\x02",
)
CloseMessageWindow()
OP_69(0x0, 0x3E8)
SetMapFlags(0x1)
Jump("loc_2410")
label("loc_1E09")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 1)), scpexpr(EXPR_END)), "loc_1E79")
ChrTalk(
0x9,
(
"嗯?怎么了?\x01",
"手续已经办好了哦。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"定期船到了之后,\x01",
"凭刚才的票就可以乘坐了。\x02",
)
)
CloseMessageWindow()
Jump("loc_2410")
label("loc_1E79")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 5)), scpexpr(EXPR_END)), "loc_1EF8")
ChrTalk(
0x9,
"哟,你们也很忙呀。\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"好像工房船\x01",
"有很紧急的任务要执行。\x01",
"这边也已经乱成一团了。\x02",
)
)
CloseMessageWindow()
Jump("loc_2410")
label("loc_1EF8")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 1)), scpexpr(EXPR_END)), "loc_1F41")
ChrTalk(
0x9,
(
"『赛希莉亚号』\x01",
"已经按预定的时间出航了………\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"唔,就趁现在难得的空闲\x01",
"集中精神看《利贝尔通讯》吧。\x02",
)
)
CloseMessageWindow()
Jump("loc_2410")
label("loc_1F41")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 7)), scpexpr(EXPR_END)), "loc_20F3")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_2008")
ChrTalk(
0x9,
"嗯嗯,对了……\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"说到封面……\x01",
"最近《利贝尔通讯》上面的照片\x01",
"都变得好漂亮啊。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"嗯,一想到这个,\x01",
"就很期待下期的封面啊。\x01",
"……偷偷告诉你们啊。\x02",
)
)
CloseMessageWindow()
Jump("loc_20F0")
label("loc_2008")
OP_A2(0x0)
ChrTalk(
0x9,
(
"中央工房的骚动\x01",
"好像是起严重的事件。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"竟然敢袭击中央工房,\x01",
"世上还有这样无法无天的家伙啊。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"唉,这样一来\x01",
"下期《利贝尔通讯》的封面\x01",
"就会是蔡斯了吧。\x02",
)
)
CloseMessageWindow()
label("loc_20F0")
Jump("loc_2410")
label("loc_20F3")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_21D4")
ChrTalk(
0x9,
(
"那个,你们看过\x01",
"《利贝尔通讯》最新一期了吗。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"听说卢安的市长\x01",
"是个无法无天的坏家伙,\x01",
"已经被逮捕了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"不过,空贼事件也好,\x01",
"这个叫戴尔蒙的家伙也好……\x01",
"最近这个世界真是不太平啊。\x02",
)
)
CloseMessageWindow()
Jump("loc_2410")
label("loc_21D4")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 3)), scpexpr(EXPR_END)), "loc_21FC")
ChrTalk(
0x9,
"你们见到维修长了吗?\x02",
)
CloseMessageWindow()
Jump("loc_2410")
label("loc_21FC")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 1)), scpexpr(EXPR_END)), "loc_235F")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_228E")
ChrTalk(
0x9,
(
"听说,最后好像是游击士\x01",
"解决了这次空贼事件。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"真是的,明明发生了这么严重的事情,\x01",
"王国军却什么事也做不了。\x02",
)
)
CloseMessageWindow()
Jump("loc_235C")
label("loc_228E")
OP_A2(0x0)
ChrTalk(
0x9,
(
"我读过利贝尔通讯了,\x01",
"前段时间柏斯的空贼骚动\x01",
"好像闹得很大啊。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"定期船停航了,\x01",
"对我们接待员来说可真是噩梦啊。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"要把事情向客人解释清楚,\x01",
"可是一件很难的事情。\x02",
)
)
CloseMessageWindow()
label("loc_235C")
Jump("loc_2410")
label("loc_235F")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA1, 6)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 2)), scpexpr(EXPR_OR), scpexpr(EXPR_END)), "loc_2410")
ChrTalk(
0x9,
(
"目前,西向航线的『赛希莉亚号』\x01",
"正停靠在飞艇坪中。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"去往格兰赛尔的旅客,\x01",
"请前往入口处准备登船。\x02",
)
)
CloseMessageWindow()
label("loc_2410")
TalkEnd(0x9)
Return()
# Function_10_11F2 end
def Function_11_2414(): pass
label("Function_11_2414")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAE, 2)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAC, 1)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_2608")
EventBegin(0x0)
ChrTalk(
0x8,
"#690F出发去雷斯顿要塞吗?\x02",
)
CloseMessageWindow()
FadeToDark(300, 0, 100)
RunExpression(0x0, (scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
OP_4F(0x28, (scpexpr(EXPR_PUSH_LONG, 0x18), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Menu(
0,
10,
10,
0,
(
"出发\x01", # 0
"整理装备\x01", # 1
)
)
MenuEnd(0x0)
OP_5F(0x0)
OP_4F(0x28, (scpexpr(EXPR_PUSH_LONG, 0xFFFF), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
OP_56(0x0)
FadeToBright(300, 0)
Switch(
(scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_END)),
(0, "loc_24A4"),
(1, "loc_25CB"),
(SWITCH_DEFAULT, "loc_2605"),
)
label("loc_24A4")
OP_A2(0x561)
OP_28(0x43, 0x1, 0x400)
OP_28(0x44, 0x4, 0x2)
OP_28(0x44, 0x4, 0x4)
ChrTalk(
0x8,
(
"#690F好,\x01",
"那么快上去吧!\x02\x03",
"工房船《莱普尼兹号》\x01",
"出发去雷斯顿要塞。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xA,
(
"#800F游击士的各位,\x01",
"博士的事就拜托你们了。\x02\x03",
"另外……\x01",
"请保护好提妲。\x02",
)
)
CloseMessageWindow()
def lambda_2558():
TurnDirection(0xFE, 0xA, 400)
ExitThread()
QueueWorkItem(0x101, 1, lambda_2558)
def lambda_2566():
TurnDirection(0xFE, 0xA, 400)
ExitThread()
QueueWorkItem(0x102, 1, lambda_2566)
def lambda_2574():
TurnDirection(0xFE, 0xA, 400)
ExitThread()
QueueWorkItem(0x106, 1, lambda_2574)
TurnDirection(0x107, 0xA, 400)
ChrTalk(
0x107,
"#060F工房长……\x02",
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F嗯,都交给我吧。\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F那么我们走了。\x02",
)
CloseMessageWindow()
Call(0, 17)
Jump("loc_2605")
label("loc_25CB")
OP_A2(0x572)
ChrTalk(
0x8,
(
"#690F我知道了。\x01",
"准备好了就告诉我一声。\x02",
)
)
CloseMessageWindow()
EventEnd(0x0)
Return()
label("loc_2605")
Jump("loc_3270")
label("loc_2608")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAC, 0)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAC, 1)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_311E")
EventBegin(0x0)
SetChrPos(0x101, -46160, -4000, 141480, 90)
SetChrPos(0x106, -44780, -4000, 140260, 0)
SetChrPos(0x107, -45700, -4000, 140390, 45)
SetChrPos(0x102, -45780, -4000, 142250, 135)
Fade(1000)
def lambda_2665():
OP_6C(45000, 0)
ExitThread()
QueueWorkItem(0x101, 1, lambda_2665)
OP_6D(-45150, -4000, 141460, 0)
ChrTalk(
0xA,
(
"#800F噢,等一下,\x01",
"你们准备好了吗?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x106,
"#050F是啊,随时都能出发。\x02",
)
CloseMessageWindow()
ChrTalk(
0x107,
(
"#060F《莱普尼兹号》的\x01",
"准备也完成了吗?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xA,
(
"#800F啊,我们运气真好,\x01",
"军队急着要我们发货。\x02\x03",
"正好准备出发\x01",
"要去雷斯顿要塞。\x02\x03",
"随时都可以出发呀。\x02",
)
)
CloseMessageWindow()
OP_8C(0x101, 135, 400)
Sleep(500)
OP_8C(0x101, 0, 400)
Sleep(500)
TurnDirection(0x101, 0xA, 400)
ChrTalk(
0x101,
(
"#000F随时……\x02\x03",
"那个橙色的飞行船\x01",
"可我怎么没找到呢?\x02",
)
)
CloseMessageWindow()
OP_8C(0x102, 315, 400)
Sleep(200)
OP_62(0x102, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
OP_22(0x27, 0x0, 0x64)
Sleep(500)
OP_8E(0x102, 0xFFFF467E, 0xFFFFF060, 0x230F0, 0x7D0, 0x0)
ChrTalk(
0x102,
"#010F艾丝蒂尔,往下面看。\x02",
)
CloseMessageWindow()
TurnDirection(0x101, 0x102, 400)
def lambda_287C():
OP_8E(0x101, 0xFFFF4688, 0xFFFFF060, 0x22CE0, 0xBB8, 0x0)
ExitThread()
QueueWorkItem(0x101, 2, lambda_287C)
def lambda_2897():
OP_6C(314000, 2000)
ExitThread()
QueueWorkItem(0x101, 1, lambda_2897)
OP_6D(-49360, -4000, 145960, 2000)
ChrTalk(
0x101,
(
"#000F啊,竟然在那里……\x02\x03",
"那么我们要\x01",
"下到下面去吧。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x107,
(
"#060F呵呵,姐姐,\x01",
"不用下去的。\x02",
)
)
CloseMessageWindow()
TurnDirection(0x101, 0x107, 400)
ChrTalk(
0x101,
"#000F哎……\x02",
)
CloseMessageWindow()
OP_62(0x101, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
OP_22(0x27, 0x0, 0x64)
def lambda_2934():
label("loc_2934")
TurnDirection(0xFE, 0x101, 0)
OP_48()
Jump("loc_2934")
QueueWorkItem2(0xA, 2, lambda_2934)
def lambda_2945():
label("loc_2945")
TurnDirection(0xFE, 0x101, 0)
OP_48()
Jump("loc_2945")
QueueWorkItem2(0x107, 2, lambda_2945)
def lambda_2956():
label("loc_2956")
TurnDirection(0xFE, 0x101, 0)
OP_48()
Jump("loc_2956")
QueueWorkItem2(0x106, 2, lambda_2956)
Sleep(1000)
OP_8C(0x101, 315, 400)
ChrTalk(
0x101,
"#000F为什么……!?\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F呀,飞行船的轨道……!\x02",
)
CloseMessageWindow()
ChrTalk(
0x106,
(
"#050F呀,你们不知道呀吗?\x02\x03",
"这里的飞行场都是\x01",
"用超乎常识的方法造的。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F超,超乎常识?\x02",
)
CloseMessageWindow()
def lambda_2A3F():
OP_8E(0x101, 0xFFFF4688, 0xFFFFF060, 0x22CE0, 0xBB8, 0x0)
ExitThread()
QueueWorkItem(0x101, 2, lambda_2A3F)
def lambda_2A5A():
OP_6C(314000, 2000)
ExitThread()
QueueWorkItem(0x101, 1, lambda_2A5A)
OP_6D(-49360, -4000, 145960, 2000)
OP_6F(0x0, 500)
OP_70(0x0, 0x4B0)
def lambda_2A89():
OP_6C(339000, 1500)
ExitThread()
QueueWorkItem(0x101, 1, lambda_2A89)
OP_6D(-55390, -4000, 147110, 1500)
def lambda_2AAA():
OP_6B(2200, 2000)
ExitThread()
QueueWorkItem(0x101, 1, lambda_2AAA)
OP_67(0, 21600, -10000, 2000)
def lambda_2ACB():
OP_6B(3500, 3100)
ExitThread()
QueueWorkItem(0x101, 2, lambda_2ACB)
def lambda_2ADB():
OP_6C(27000, 3100)
ExitThread()
QueueWorkItem(0x101, 1, lambda_2ADB)
OP_6D(-36640, -4000, 148800, 3100)
SetChrPos(0x101, -46240, -4000, 141000, 90)
SetChrPos(0x102, -46280, -4000, 142120, 90)
def lambda_2B1E():
OP_6B(5500, 5000)
ExitThread()
QueueWorkItem(0x101, 2, lambda_2B1E)
def lambda_2B2E():
OP_67(0, 11000, -10000, 5000)
ExitThread()
QueueWorkItem(0x101, 1, lambda_2B2E)
OP_6C(90000, 5000)
OP_73(0x0)
Sleep(1000)
def lambda_2B57():
OP_6B(3500, 2000)
ExitThread()
QueueWorkItem(0x101, 1, lambda_2B57)
OP_6D(-45210, -4000, 142090, 2000)
ChrTalk(
0x101,
(
"#000F大致上我开始\x01",
"对这种事渐渐习惯了……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F嗯,想要弄清楚结构的话\x01",
"得花一番工夫呀。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xA,
(
"#800F而且这个\x01",
"飞行场的构造也是……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F知道了,\x01",
"是拉赛尔博士吧。\x02\x03",
"提妲。\x01",
"你的爷爷真是\x01",
"无所不能呀。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x107,
(
"#060F呵呵……\x01",
"我也同感。\x02",
)
)
CloseMessageWindow()
SetChrFlags(0x8, 0x4)
ClearChrFlags(0x8, 0x80)
SetChrPos(0x8, -36460, -4000, 144380, 270)
ChrTalk(
0x8,
"#690F哟,久等了。\x02",
)
CloseMessageWindow()
OP_6D(-40270, -4000, 143040, 1000)
ChrTalk(
0x107,
"#060F呀,维修长。\x02",
)
CloseMessageWindow()
def lambda_2D0C():
label("loc_2D0C")
TurnDirection(0xFE, 0x8, 0)
OP_48()
Jump("loc_2D0C")
QueueWorkItem2(0xA, 2, lambda_2D0C)
def lambda_2D1D():
label("loc_2D1D")
TurnDirection(0xFE, 0x8, 0)
OP_48()
Jump("loc_2D1D")
QueueWorkItem2(0x102, 2, lambda_2D1D)
def lambda_2D2E():
label("loc_2D2E")
TurnDirection(0xFE, 0x8, 0)
OP_48()
Jump("loc_2D2E")
QueueWorkItem2(0x101, 2, lambda_2D2E)
def lambda_2D3F():
label("loc_2D3F")
TurnDirection(0xFE, 0x8, 0)
OP_48()
Jump("loc_2D3F")
QueueWorkItem2(0x107, 2, lambda_2D3F)
def lambda_2D50():
label("loc_2D50")
TurnDirection(0xFE, 0x8, 0)
OP_48()
Jump("loc_2D50")
QueueWorkItem2(0x106, 2, lambda_2D50)
def lambda_2D61():
OP_6D(-44110, -3800, 143890, 3000)
ExitThread()
QueueWorkItem(0x101, 1, lambda_2D61)
def lambda_2D79():
OP_8E(0xFE, 0xFFFF4C0A, 0xFFFFF060, 0x2385C, 0x7D0, 0x0)
ExitThread()
QueueWorkItem(0x102, 3, lambda_2D79)
def lambda_2D94():
OP_8E(0xFE, 0xFFFF4A8E, 0xFFFFF060, 0x2341A, 0x7D0, 0x0)
ExitThread()
QueueWorkItem(0x101, 3, lambda_2D94)
Sleep(100)
def lambda_2DB4():
OP_8E(0xFE, 0xFFFF4AFC, 0xFFFFF060, 0x23082, 0x7D0, 0x0)
ExitThread()
QueueWorkItem(0x107, 3, lambda_2DB4)
Sleep(100)
def lambda_2DD4():
OP_8E(0xFE, 0xFFFF4B56, 0xFFFFF060, 0x22CFE, 0x7D0, 0x0)
ExitThread()
QueueWorkItem(0x106, 3, lambda_2DD4)
OP_8E(0x8, 0xFFFF57A4, 0xFFFFF128, 0x2329E, 0x7D0, 0x0)
ChrTalk(
0x8,
(
"#690F提妲呀,\x01",
"事情我已经听工房长说了。\x02\x03",
"没想到老爷子\x01",
"会遇到这样的事。\x02\x03",
"能帮上忙的话,\x01",
"我们维修员随时乐意效劳。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x107,
"#060F谢谢。\x02",
)
CloseMessageWindow()
ChrTalk(
0x106,
"#050F不好意思,麻烦你了。\x02",
)
CloseMessageWindow()
ChrTalk(
0x8,
(
"#690F不要客气,\x01",
"老爷子也是我的恩人呀。\x02\x03",
"那么\x01",
"我们已经准备好了。\x02\x03",
"出发去雷斯顿要塞吗?\x02",
)
)
CloseMessageWindow()
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
OP_44(0x107, 0xFF)
OP_44(0x106, 0xFF)
OP_44(0xA, 0xFF)
FadeToDark(300, 0, 100)
RunExpression(0x0, (scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
OP_4F(0x28, (scpexpr(EXPR_PUSH_LONG, 0x18), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Menu(
0,
10,
10,
0,
(
"出发\x01", # 0
"整理装备\x01", # 1
)
)
MenuEnd(0x0)
OP_5F(0x0)
OP_4F(0x28, (scpexpr(EXPR_PUSH_LONG, 0xFFFF), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
OP_56(0x0)
FadeToBright(300, 0)
Switch(
(scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_END)),
(0, "loc_2FBA"),
(1, "loc_30E1"),
(SWITCH_DEFAULT, "loc_311B"),
)
label("loc_2FBA")
OP_A2(0x561)
OP_28(0x43, 0x1, 0x400)
OP_28(0x44, 0x4, 0x2)
OP_28(0x44, 0x4, 0x4)
ChrTalk(
0x8,
(
"#690F好,\x01",
"那么快上去吧!\x02\x03",
"工房船《莱普尼兹号》\x01",
"出发去雷斯顿要塞。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xA,
(
"#800F游击士的各位,\x01",
"博士的事就拜托你们了。\x02\x03",
"另外……\x01",
"请保护好提妲。\x02",
)
)
CloseMessageWindow()
def lambda_306E():
TurnDirection(0xFE, 0xA, 400)
ExitThread()
QueueWorkItem(0x101, 1, lambda_306E)
def lambda_307C():
TurnDirection(0xFE, 0xA, 400)
ExitThread()
QueueWorkItem(0x102, 1, lambda_307C)
def lambda_308A():
TurnDirection(0xFE, 0xA, 400)
ExitThread()
QueueWorkItem(0x106, 1, lambda_308A)
TurnDirection(0x107, 0xA, 400)
ChrTalk(
0x107,
"#060F工房长……\x02",
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F嗯,都交给我吧。\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F那么我们走了。\x02",
)
CloseMessageWindow()
Call(0, 17)
Jump("loc_311B")
label("loc_30E1")
OP_A2(0x572)
ChrTalk(
0x8,
(
"#690F我知道了。\x01",
"准备好了就告诉我一声。\x02",
)
)
CloseMessageWindow()
EventEnd(0x0)
Return()
label("loc_311B")
Jump("loc_3270")
label("loc_311E")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_END)), "loc_3198")
ChrTalk(
0xA,
(
"#800F这边现在\x01",
"也正由格斯塔夫维修长\x01",
"指挥进行起飞前的准备呢。\x02\x03",
"如果你们准备好了,\x01",
"就再到这儿来找我吧。\x02",
)
)
CloseMessageWindow()
Jump("loc_3270")
label("loc_3198")
OP_A2(0x3)
ChrTalk(
0xA,
(
"#800F哦哦,是你们啊。\x01",
"已经准备好了吗?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F非常抱歉,\x01",
"可能还要再费些时间。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xA,
(
"#800F是吗,这边现在\x01",
"也正由格斯塔夫维修长\x01",
"指挥进行起飞前的准备呢。\x02\x03",
"如果你们准备好了,\x01",
"就再到这儿来找我吧。\x02",
)
)
CloseMessageWindow()
label("loc_3270")
Return()
# Function_11_2414 end
def Function_12_3271(): pass
label("Function_12_3271")
TalkBegin(0xFE)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 3)), scpexpr(EXPR_END)), "loc_3350")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_32D9")
ChrTalk(
0xFE,
(
"看起来定期船\x01",
"好像会晚点很长时间啊……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"我还是先回家\x01",
"再做打算吧。\x02",
)
)
CloseMessageWindow()
Jump("loc_334D")
label("loc_32D9")
OP_A2(0x1)
ChrTalk(
0xFE,
(
"看起来定期船\x01",
"好像会晚点很长时间啊……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"听说军队要盘检,\x01",
"真是麻烦啊。\x02",
)
)
CloseMessageWindow()
label("loc_334D")
Jump("loc_35EA")
label("loc_3350")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 1)), scpexpr(EXPR_END)), "loc_3454")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_3389")
ChrTalk(
0xFE,
(
"说起来\x01",
"我是不是来得太早了?\x02",
)
)
CloseMessageWindow()
Jump("loc_3451")
label("loc_3389")
OP_A2(0x1)
ChrTalk(
0xFE,
(
"哦~早上好啊。\x01",
"你们也是要去王都吗?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"我呀,\x01",
"是要去飞艇公社办些事情。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"而且还想赶快把工作搞定,\x01",
"顺便参观诞辰庆典……\x02",
)
)
CloseMessageWindow()
label("loc_3451")
Jump("loc_35EA")
label("loc_3454")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 1)), scpexpr(EXPR_END)), "loc_35EA")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_34EE")
ChrTalk(
0xFE,
(
"飞艇的技术\x01",
"真是越来越进步了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"乘坐定期船\x01",
"到多杰的故乡\x01",
"也不再是遥远的梦想了。\x02",
)
)
CloseMessageWindow()
Jump("loc_35EA")
label("loc_34EE")
OP_A2(0x1)
ChrTalk(
0xFE,
(
"今天早上,\x01",
"偶然遇到了来自共和国的\x01",
"导力器商人多杰。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"因为他要在飞艇坪参观,\x01",
"我就热情地为他介绍了一下。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"看,多杰。\x01",
"那是器材的搬入口,\x01",
"造船设施就在那个地下哦。\x02",
)
)
CloseMessageWindow()
label("loc_35EA")
TalkEnd(0xFE)
Return()
# Function_12_3271 end
def Function_13_35EE(): pass
label("Function_13_35EE")
TalkBegin(0xFE)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 1)), scpexpr(EXPR_END)), "loc_36D2")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 2)), scpexpr(EXPR_END)), "loc_367A")
ChrTalk(
0xFE,
(
"我将来也要\x01",
"把飞艇作为商品……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
(
"但在那之前,\x01",
"我的城镇得有个飞艇坪才行。\x02",
)
)
CloseMessageWindow()
Jump("loc_36D2")
label("loc_367A")
OP_A2(0x2)
ChrTalk(
0xFE,
(
"呼,\x01",
"现在只能感叹眼前的景象了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xFE,
"实在是太棒了。\x02",
)
CloseMessageWindow()
label("loc_36D2")
TalkEnd(0xFE)
Return()
# Function_13_35EE end
def Function_14_36D6(): pass
label("Function_14_36D6")
Call(0, 10)
Return()
# Function_14_36D6 end
def Function_15_36DB(): pass
label("Function_15_36DB")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 7)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_3F80")
OP_A2(0x518)
OP_28(0x3F, 0x1, 0x800)
Jc((scpexpr(EXPR_EXEC_OP, "OP_29(0x3F, 0x1, 0x1000)"), scpexpr(EXPR_END)), "loc_3701")
OP_28(0x3F, 0x1, 0x2000)
label("loc_3701")
ClearMapFlags(0x1)
EventBegin(0x0)
ClearChrFlags(0x8, 0x80)
NpcTalk(
0x8,
"年长的维修员",
(
"唔……?\x01",
"这位小姐。\x02",
)
)
CloseMessageWindow()
OP_6D(-42300, -3800, 143800, 1000)
ChrTalk(
0x101,
"#000F啊……\x02",
)
CloseMessageWindow()
NpcTalk(
0x8,
"年长的维修员",
(
"这个《莱普尼兹号》\x01",
"无关人员是不能进入的。\x02",
)
)
CloseMessageWindow()
NpcTalk(
0x8,
"年长的维修员",
"对不起,请你们离开吧。\x02",
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F嘿嘿,我们就是有关人员哦。\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F我们找格斯塔夫维修长\x01",
"有些事情商量……\x02",
)
)
CloseMessageWindow()
NpcTalk(
0x8,
"年长的维修员",
"呀,你们找我什么事呀?\x02",
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F叔叔是\x01",
"维修长呀。\x02",
)
)
CloseMessageWindow()
FadeToDark(300, 0, 100)
AnonymousTalk(
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"艾丝蒂尔他们把\x01",
"拉赛尔博士委托想要借内燃引擎设备\x01",
"的事说明了一下。\x02",
)
)
CloseMessageWindow()
OP_56(0x0)
FadeToBright(300, 0)
ChrTalk(
0x8,
(
"#690F呀,\x01",
"是拉赛尔老爷子的事呀。\x02\x03",
"是要内燃引擎设备的话,\x01",
"那来得正好呀。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F哎?\x02",
)
CloseMessageWindow()
ChrTalk(
0x8,
"#690F稍微等一下呀……\x02",
)
CloseMessageWindow()
SetChrFlags(0x8, 0x80)
SetChrPos(0x8, -42300, -3800, 143800, 0)
ChrTalk(
0x101,
"#000F怎么了?\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F嗯……\x02",
)
CloseMessageWindow()
ClearChrFlags(0x8, 0x80)
OP_6D(-43500, -3800, 143700, 1000)
ChrTalk(
0x8,
(
"#690F嘿。\x01",
"很重,小心啦。\x02",
)
)
CloseMessageWindow()
OP_92(0x8, 0x0, 0x2BC, 0xBB8, 0x0)
FadeToDark(300, 0, 100)
AnonymousTalk(
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"艾丝蒂尔他们得到了内燃引擎设备设备。\x02",
)
)
CloseMessageWindow()
OP_56(0x0)
FadeToBright(300, 0)
OP_8F(0x8, 0xFFFF5AC4, 0xFFFFF128, 0x231B8, 0xBB8, 0x0)
Jc((scpexpr(EXPR_PUSH_VALUE_INDEX, 0xA), scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_3BD9")
ChrTalk(
0x101,
(
"#000F哇哇……\x01",
"的确是沉甸甸的呀。\x02\x03",
"的确是沉甸甸的呀。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x8,
(
"#690F哎!想不到\x01",
"小姑娘还很能干嘛。\x02\x03",
"哈哈,我很中意你呀。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F嘿嘿,没什么啦。\x02",
)
CloseMessageWindow()
Jump("loc_3C9D")
label("loc_3BD9")
ChrTalk(
0x102,
(
"#010F确实是很重……\x01",
"不过也不至于重到拿不动就是了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x8,
(
"#690F哎……\x01",
"现在的年轻人\x01",
"小姑娘还很能干嘛。\x02\x03",
"哈哈,我很中意你呀。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F您过奖了。\x02",
)
CloseMessageWindow()
label("loc_3C9D")
ChrTalk(
0x8,
(
"#690F不过,这也真是个\x01",
"有趣的偶然呀。\x02\x03",
"刚从军方里还回来后\x01",
"马上就被老爷子借走了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F哎……\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F从军方,怎么回事?\x02",
)
CloseMessageWindow()
ChrTalk(
0x8,
(
"#690F啊,那个货样\x01",
"被王国军借了一阵子。。\x02\x03",
"好像什么研究要用到的。\x02\x03",
"总算是\x01",
"今天还回来了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F哎~。\x01",
"的确是很偶然呀。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F…………………………\x02",
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F嗯,怎么了?\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F呀,不……没什么。\x02",
)
CloseMessageWindow()
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 1)), scpexpr(EXPR_END)), "loc_3EBF")
ChrTalk(
0x102,
(
"#010F需要的东西都已经拿到了,\x01",
"快点回博士那里吧。\x02",
)
)
CloseMessageWindow()
Jump("loc_3F0A")
label("loc_3EBF")
ChrTalk(
0x102,
(
"#010F剩下的就是汽油了。\x01",
"去地下工场吧?\x02",
)
)
CloseMessageWindow()
label("loc_3F0A")
ChrTalk(
0x101,
(
"#000F嗯,我知道了。\x02\x03",
"维修长,THANK YOU!\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x8,
(
"#690F噢。\x01",
"帮我向老爷子问好。\x02",
)
)
CloseMessageWindow()
SetChrFlags(0x8, 0x80)
EventEnd(0x0)
label("loc_3F80")
Return()
# Function_15_36DB end
def Function_16_3F81(): pass
label("Function_16_3F81")
EventBegin(0x0)
SetChrPos(0x108, -45670, -4000, 146000, 0)
SetChrPos(0x101, -46540, -4000, 147540, 0)
SetChrPos(0x102, -47220, -4000, 146840, 0)
SetChrPos(0x107, -47150, -4000, 145610, 0)
TurnDirection(0x101, 0x108, 0)
TurnDirection(0x102, 0x108, 0)
TurnDirection(0x107, 0x108, 0)
TurnDirection(0x108, 0x102, 0)
OP_6D(-45760, -4000, 146000, 0)
OP_67(0, 9090, -10000, 0)
OP_6B(2650, 0)
OP_6C(111000, 0)
OP_6E(262, 0)
OP_A2(0x559)
ChrTalk(
0x108,
(
"#070F……真是不好意思,\x01",
"特地要你们来送我。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F这是当然的啰,\x01",
"我们受了你那么多照顾。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F金,你就这样\x01",
"乘定期船直接去王都吗?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x108,
(
"#070F啊,我还有\x01",
"其他事必须去办。\x02\x03",
"办完事我也\x01",
"帮忙调查\x01",
"绑架事件的……\x02",
)
)
CloseMessageWindow()
TurnDirection(0x108, 0x107, 400)
ChrTalk(
0x108,
"#070F对不起了,小姐。\x02",
)
CloseMessageWindow()
ChrTalk(
0x107,
(
"#060F没这回事的啦。\x01",
"你已经帮了我很多忙了……\x02\x03",
"真的\x01",
"多谢你们了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x108,
(
"#070F哈哈……\x01",
"你能这么说真是太好了。\x02",
)
)
CloseMessageWindow()
AnonymousTalk(
(
scpstr(SCPSTR_CODE_COLOR, 0x0),
"开往王都的定期船\x01",
"《赛希莉亚号》马上就要起飞了。\x02",
)
)
CloseMessageWindow()
AnonymousTalk(
(
scpstr(SCPSTR_CODE_COLOR, 0x0),
"请没有上船的乘客尽快上船。\x02",
)
)
CloseMessageWindow()
OP_56(0x0)
ChrTalk(
0x108,
(
"#070F呀……\x01",
"差不多要出发了。\x02",
)
)
CloseMessageWindow()
def lambda_42CC():
OP_6D(-40990, -4000, 146200, 3000)
ExitThread()
QueueWorkItem(0x101, 2, lambda_42CC)
def lambda_42E4():
OP_6B(3360, 3000)
ExitThread()
QueueWorkItem(0x101, 3, lambda_42E4)
def lambda_42F4():
OP_6C(32000, 3000)
ExitThread()
QueueWorkItem(0x102, 2, lambda_42F4)
SetChrFlags(0x108, 0x4)
OP_8E(0x108, 0xFFFF4BEC, 0xFFFFF060, 0x23780, 0xBB8, 0x0)
OP_8E(0x108, 0xFFFF4C6E, 0xFFFFF060, 0x232B2, 0xBB8, 0x0)
def lambda_4331():
OP_8E(0xFE, 0xFFFF50B0, 0xFFFFF060, 0x23A50, 0x7D0, 0x0)
ExitThread()
QueueWorkItem(0x101, 1, lambda_4331)
def lambda_434C():
OP_8E(0xFE, 0xFFFF4BD8, 0xFFFFF060, 0x23898, 0x7D0, 0x0)
ExitThread()
QueueWorkItem(0x102, 1, lambda_434C)
def lambda_4367():
OP_8E(0xFE, 0xFFFF4BF6, 0xFFFFF060, 0x23532, 0x7D0, 0x0)
ExitThread()
QueueWorkItem(0x107, 1, lambda_4367)
OP_8E(0x108, 0xFFFF720C, 0xFFFFF060, 0x236C2, 0xBB8, 0x0)
TurnDirection(0x108, 0x107, 400)
ChrTalk(
0x108,
(
"#070F那再见了,\x01",
"有机会还会碰面的。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F啊,好。\x02\x03",
"对了,金要在\x01",
"利贝尔呆到什么时候呢?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x108,
(
"#070F明确时间还不知道……\x01",
"我想会呆到女王生日庆典吧。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F啊,那样的话\x01",
"也许会再见面的。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F到时候还请多多关照。\x02",
)
CloseMessageWindow()
ChrTalk(
0x108,
"#070F呵呵,彼此彼此。\x02",
)
CloseMessageWindow()
FadeToDark(2000, 0, -1)
OP_0D()
RemoveParty(0x7, 0xFF)
OP_A2(0x3FA)
NewScene("ED6_DT01/T3101 ._SN", 100, 0, 0)
IdleLoop()
Return()
# Function_16_3F81 end
def Function_17_44F5(): pass
label("Function_17_44F5")
SetChrFlags(0x101, 0x80)
SetChrFlags(0x102, 0x80)
SetChrFlags(0x107, 0x80)
SetChrFlags(0x106, 0x80)
SetChrFlags(0x8, 0x80)
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
OP_44(0x107, 0xFF)
OP_44(0x106, 0xFF)
OP_44(0xA, 0xFF)
SetChrPos(0xB, -45980, 0, 129680, 0)
ClearChrFlags(0xB, 0x80)
Fade(1000)
OP_6D(-40270, -4000, 145060, 0)
OP_67(0, 11000, -10000, 0)
OP_6B(3500, 0)
OP_6C(89000, 0)
OP_6E(262, 0)
ChrTalk(
0xA,
(
"#800F拜托你们了,游击士的各位……\x01",
"(※假定莱普尼兹号出发动画)\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xB,
"啊,等一下~!\x02",
)
CloseMessageWindow()
def lambda_45BE():
OP_6D(-45610, -3800, 142980, 2000)
ExitThread()
QueueWorkItem(0xA, 3, lambda_45BE)
def lambda_45D6():
label("loc_45D6")
TurnDirection(0xFE, 0xB, 400)
OP_48()
Jump("loc_45D6")
QueueWorkItem2(0xA, 1, lambda_45D6)
OP_8E(0xB, 0xFFFF4A52, 0xFFFFF060, 0x23348, 0x1388, 0x0)
ChrTalk(
0xB,
(
"#150F哈哈……\x02\x03",
"啊,走掉了……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xA,
(
"#800F哎呀……\x01",
"朵洛希呀。\x02",
)
)
CloseMessageWindow()
OP_44(0xA, 0xFF)
OP_8E(0xA, 0xFFFF4A2A, 0xFFFFF060, 0x22AC4, 0x7D0, 0x0)
TurnDirection(0xA, 0xB, 0)
TurnDirection(0xB, 0xA, 400)
ChrTalk(
0xB,
(
"#150F啊,工房长。\x02\x03",
"刚才的船上,\x01",
"艾丝蒂尔他们乘着吧。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xA,
(
"#800F是呀……\x01",
"你怎么知道的?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xB,
(
"#150F游击会的\x01",
"接待员告诉我的。\x02\x03",
"我和编辑部连络后\x01",
"知道了不得了的事,\x01",
"我想不告诉他们不行。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xA,
"#800F不得了的事?\x02",
)
CloseMessageWindow()
ChrTalk(
0xB,
(
"#150F呀……\x01",
"这个是公告。\x02\x03",
"在王都的亲卫队\x01",
"以反逆罪被逮捕了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xA,
"#800F什,什么?\x02",
)
CloseMessageWindow()
OP_A2(0x3FA)
NewScene("ED6_DT01/E0012 ._SN", 100, 0, 0)
IdleLoop()
Return()
# Function_17_44F5 end
def Function_18_4835(): pass
label("Function_18_4835")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 2)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_5923")
EventBegin(0x0)
OP_A2(0x603)
OP_28(0x54, 0x1, 0x4)
OP_28(0x54, 0x1, 0x8)
SetChrPos(0xC, -46060, 0, 127820, 0)
ClearChrFlags(0xC, 0x80)
ChrTalk(
0xC,
"喵~呵。\x02",
)
CloseMessageWindow()
def lambda_487B():
OP_6D(-46010, -1000, 131740, 2500)
ExitThread()
QueueWorkItem(0x0, 1, lambda_487B)
def lambda_4893():
OP_67(0, 7390, -10000, 4000)
ExitThread()
QueueWorkItem(0x0, 2, lambda_4893)
def lambda_48AB():
OP_6B(3700, 4000)
ExitThread()
QueueWorkItem(0x1, 1, lambda_48AB)
def lambda_48BB():
OP_6C(158000, 4000)
ExitThread()
QueueWorkItem(0x1, 2, lambda_48BB)
Sleep(3000)
SetChrPos(0x101, -45400, -4000, 140210, 0)
SetChrPos(0x102, -46510, -4000, 139810, 0)
def lambda_48F2():
label("loc_48F2")
TurnDirection(0xFE, 0xC, 0)
OP_48()
Jump("loc_48F2")
QueueWorkItem2(0x101, 3, lambda_48F2)
def lambda_4903():
label("loc_4903")
TurnDirection(0xFE, 0xC, 0)
OP_48()
Jump("loc_4903")
QueueWorkItem2(0x102, 3, lambda_4903)
def lambda_4914():
OP_8E(0xFE, 0xFFFF4D18, 0xFFFFF060, 0x21D40, 0xBB8, 0x0)
ExitThread()
QueueWorkItem(0xC, 2, lambda_4914)
def lambda_492F():
OP_6D(-45610, -4000, 139000, 3000)
ExitThread()
QueueWorkItem(0x0, 1, lambda_492F)
Sleep(3000)
ChrTalk(
0x101,
"#000F啊,那只猫是……\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F就是那个时候\x01",
"钻进集装箱里的那只猫吧。\x02\x03",
"我记得,\x01",
"好像是叫做安东尼。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xC,
"喵呜~\x02",
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F啊哈哈~真可爱。\x02\x03",
"真是的,都是因为你,\x01",
"害我吓了一大跳呢。\x02\x03",
"你是不是该反省一下呢,嗯?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xC,
"咪呜?\x02",
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F都不听我说话啊。\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F哈哈,说不定\x01",
"它是在装傻呢。\x02",
)
)
CloseMessageWindow()
SetChrPos(0x8, -47160, 0, 129750, 0)
ClearChrFlags(0x8, 0x80)
ChrTalk(
0x8,
"哦,是你们啊!\x02",
)
CloseMessageWindow()
def lambda_4B01():
OP_6D(-46010, -4000, 137720, 2000)
ExitThread()
QueueWorkItem(0x0, 1, lambda_4B01)
def lambda_4B19():
label("loc_4B19")
TurnDirection(0xFE, 0x8, 400)
OP_48()
Jump("loc_4B19")
QueueWorkItem2(0x101, 3, lambda_4B19)
def lambda_4B2A():
label("loc_4B2A")
TurnDirection(0xFE, 0x8, 400)
OP_48()
Jump("loc_4B2A")
QueueWorkItem2(0x102, 3, lambda_4B2A)
def lambda_4B3B():
OP_8E(0xFE, 0xFFFF4ADE, 0xFFFFF060, 0x21AD4, 0xBB8, 0x0)
ExitThread()
QueueWorkItem(0x8, 1, lambda_4B3B)
Sleep(1000)
def lambda_4B5B():
label("loc_4B5B")
TurnDirection(0xFE, 0x8, 0)
OP_48()
Jump("loc_4B5B")
QueueWorkItem2(0x101, 3, lambda_4B5B)
def lambda_4B6C():
label("loc_4B6C")
TurnDirection(0xFE, 0x8, 0)
OP_48()
Jump("loc_4B6C")
QueueWorkItem2(0x102, 3, lambda_4B6C)
def lambda_4B7D():
OP_8E(0xFE, 0xFFFF4D4A, 0x0, 0x1F521, 0x5DC, 0x0)
ExitThread()
QueueWorkItem(0xC, 1, lambda_4B7D)
WaitChrThread(0x8, 0x1)
ChrTalk(
0x101,
"#000F啊,维修长先生!\x02",
)
CloseMessageWindow()
ChrTalk(
0x8,
(
"#690F工房长都告诉我了。\x01",
"能成功救出博士,干得真是漂亮啊。\x02\x03",
"博士对我们这些技术人员来说,\x01",
"算是师傅一样的人物了。\x02\x03",
"我也要好好感谢你们呢。\x02",
)
)
CloseMessageWindow()
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
OP_8E(0x101, 0xFFFF4F20, 0xFFFFF060, 0x21E58, 0x7D0, 0x0)
TurnDirection(0x101, 0xC, 400)
ChrTalk(
0x101,
(
"#000F嘿嘿,这也多亏了\x01",
"维修长你们的帮忙啊。\x02\x03",
"我真是被那孩子\x01",
"吓坏了呢。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F那个,\x01",
"果然是你故意把它放进去的吧?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x8,
(
"#690F啊哈哈,要想欺骗敌人,\x01",
"首先要瞒过伙伴才行啊。\x02\x03",
"对了,\x01",
"你们来飞艇坪有什么事吗?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F嗯,受博士的委托,\x01",
"现在要赶去王都。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F要乘坐11点的飞艇,\x01",
"看来好像来得早了点。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x8,
(
"#690F啊啊……\x01",
"好像要稍微迟到一会儿呢。\x02\x03",
"因为还要花点时间卸货,\x01",
"你们到街上再转一会儿\x01",
"我想也没关系啦。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F嗯,这样啊……\x02",
)
CloseMessageWindow()
SetChrPos(0x9, -47640, 0, 129250, 0)
ChrTalk(
0x9,
"喂,你们!\x02",
)
CloseMessageWindow()
def lambda_4F46():
OP_8E(0x9, 0xFFFF4EF8, 0xFFFFF15A, 0x2189A, 0xBB8, 0x0)
ExitThread()
QueueWorkItem(0x9, 1, lambda_4F46)
def lambda_4F61():
OP_6D(-46700, -2500, 134910, 1500)
ExitThread()
QueueWorkItem(0x0, 1, lambda_4F61)
def lambda_4F79():
label("loc_4F79")
TurnDirection(0xFE, 0x9, 400)
OP_48()
Jump("loc_4F79")
QueueWorkItem2(0x101, 2, lambda_4F79)
def lambda_4F8A():
label("loc_4F8A")
TurnDirection(0xFE, 0x9, 400)
OP_48()
Jump("loc_4F8A")
QueueWorkItem2(0x102, 2, lambda_4F8A)
def lambda_4F9B():
label("loc_4F9B")
TurnDirection(0xFE, 0x9, 400)
OP_48()
Jump("loc_4F9B")
QueueWorkItem2(0x8, 2, lambda_4F9B)
Sleep(1500)
def lambda_4FB1():
label("loc_4FB1")
TurnDirection(0xFE, 0x9, 0)
OP_48()
Jump("loc_4FB1")
QueueWorkItem2(0x101, 2, lambda_4FB1)
def lambda_4FC2():
label("loc_4FC2")
TurnDirection(0xFE, 0x9, 0)
OP_48()
Jump("loc_4FC2")
QueueWorkItem2(0x102, 2, lambda_4FC2)
def lambda_4FD3():
label("loc_4FD3")
TurnDirection(0xFE, 0x9, 0)
OP_48()
Jump("loc_4FD3")
QueueWorkItem2(0x8, 2, lambda_4FD3)
def lambda_4FE4():
OP_6D(-46010, -4000, 137720, 2000)
ExitThread()
QueueWorkItem(0x0, 1, lambda_4FE4)
WaitChrThread(0x9, 0x1)
TurnDirection(0x9, 0x102, 0)
ChrTalk(
0x8,
(
"#690F什么啊,这不是吉拉尔吗。\x02\x03",
"什么事这么慌张?\x02",
)
)
CloseMessageWindow()
TurnDirection(0x9, 0x8, 400)
ChrTalk(
0x9,
(
"正好,\x01",
"老爹也在啊。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
"实际上,事情变得麻烦起来了。\x02",
)
CloseMessageWindow()
ChrTalk(
0x8,
"#690F你说什么,麻烦?\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"嗯,\x01",
"从飞艇公社来的联络说……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"定期船可能要\x01",
"晚几个小时才能到达呢。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F哎……!\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F…………………………\x02",
)
CloseMessageWindow()
ChrTalk(
0x8,
(
"#690F喂喂,\x01",
"到底是怎么回事啊?\x02\x03",
"又有空贼作乱吗?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
"啊,说起来也差不多。\x02",
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"据说,有一伙打算妨碍\x01",
"女王的生日庆典的恐怖分子\x01",
"不知道在哪里潜伏着。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"为了调查这件事,\x01",
"所有的空降庭都被军队设下了哨卡。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F(那,那个是……)\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F(大概是为了\x01",
"搜寻逃走的博士他们吧……)\x02",
)
)
CloseMessageWindow()
TurnDirection(0x9, 0x101, 400)
ChrTalk(
0x9,
(
"所以,开往王都的飞艇\x01",
"现在还滞留在卢安。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"取而代之的好像是\x01",
"雷斯顿要塞的军用警备飞艇。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x8,
(
"#690F原来如此,是这样啊。\x02\x03",
"不过这样一来,\x01",
"你不是就要很忙了?\x02",
)
)
CloseMessageWindow()
TurnDirection(0x9, 0x8, 400)
ChrTalk(
0x9,
(
"是啊,\x01",
"不把这件事告诉旅客们不行啊。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"就因为这样,\x01",
"你们也得再等一段时间了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x9,
(
"对了……\x01",
"如果你们愿意在游击士协会等的话,\x01",
"我去帮你们联系一下吧?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F嗯、嗯……\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F请多指教。\x02",
)
CloseMessageWindow()
OP_8E(0x9, 0xFFFF46F6, 0x0, 0x1F8E2, 0xBB8, 0x0)
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
OP_44(0x8, 0xFF)
SetChrPos(0x9, -18300, 8000, 121700, 180)
ChrTalk(
0x8,
(
"#690F……真是可疑啊。\x02\x03",
"如果军队那伙人这样干的话,\x01",
"莱普尼兹号肯定也会被检查的。\x02\x03",
"我这就去和工房长说这件事。\x02",
)
)
CloseMessageWindow()
def lambda_560F():
label("loc_560F")
TurnDirection(0xFE, 0x8, 400)
OP_48()
Jump("loc_560F")
QueueWorkItem2(0x101, 2, lambda_560F)
def lambda_5620():
label("loc_5620")
TurnDirection(0xFE, 0x8, 400)
OP_48()
Jump("loc_5620")
QueueWorkItem2(0x102, 2, lambda_5620)
ChrTalk(
0x101,
(
"#000F对啊,要是调查昨天那件事的话\x01",
"就不好办了。\x02",
)
)
CloseMessageWindow()
def lambda_5682():
label("loc_5682")
TurnDirection(0xFE, 0x101, 400)
OP_48()
Jump("loc_5682")
QueueWorkItem2(0x8, 2, lambda_5682)
ChrTalk(
0x102,
"#010F请一定要小心啊。\x02",
)
CloseMessageWindow()
ChrTalk(
0x8,
(
"#690F哈哈,我还没有老得不中用到\x01",
"让你们这些小孩子担心的份儿上呢。\x02\x03",
"那么告辞了!\x02",
)
)
CloseMessageWindow()
OP_44(0x8, 0xFF)
OP_8E(0x8, 0xFFFF46F6, 0x0, 0x1F8E2, 0xBB8, 0x0)
SetChrFlags(0x8, 0x80)
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
TurnDirection(0x101, 0x102, 400)
ChrTalk(
0x101,
(
"#000F约修亚……\x01",
"这样岂不是很危险吗?\x02",
)
)
CloseMessageWindow()
TurnDirection(0x102, 0x101, 400)
ChrTalk(
0x102,
(
"#010F嗯……\x01",
"这样的话乘定期船就危险了。\x02\x03",
"虽然要花点时间,\x01",
"还是走街道比较好吧。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F呜,还以为好不容易\x01",
"可以乘坐久违的飞艇了呢……\x02\x03",
"我饶不了你,理查德上校!\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F算了算了。\x01",
"当成是继续修行不也很好吗?\x02\x03",
"那么我们赶快去接待那里\x01",
"把搭乘手续取消吧。\x02",
)
)
CloseMessageWindow()
SetChrFlags(0xC, 0x80)
EventEnd(0x0)
label("loc_5923")
Return()
# Function_18_4835 end
def Function_19_5924(): pass
label("Function_19_5924")
FadeToDark(300, 0, 100)
SetChrName("")
SetMessageWindowPos(-1, -1, -1, -1)
AnonymousTalk(
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"定期船起降坪\x01",
"≡ 开往王都格兰赛尔\x01",
"≡ 开往卢安市\x02",
)
)
CloseMessageWindow()
AnonymousTalk(
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
"※请勿携带易燃物和危险品\x01",
" 利贝尔飞艇公社\x02",
)
)
CloseMessageWindow()
OP_56(0x0)
FadeToBright(300, 0)
SetMessageWindowPos(72, 320, 56, 3)
TalkEnd(0xFF)
Return()
# Function_19_5924 end
def Function_20_59DF(): pass
label("Function_20_59DF")
FadeToDark(300, 0, 100)
SetChrName("")
SetMessageWindowPos(-1, -1, -1, -1)
AnonymousTalk(
(
scpstr(SCPSTR_CODE_COLOR, 0x5),
" 飞艇坪塔台 \x01",
" ※无关人员禁止入内 \x01",
"『利贝尔飞艇公社』 \x02",
)
)
CloseMessageWindow()
OP_56(0x0)
FadeToBright(300, 0)
SetMessageWindowPos(72, 320, 56, 3)
TalkEnd(0xFF)
Return()
# Function_20_59DF end
SaveToFile()
Try(main)
|
#Oops Concept
class Cars:
def __init__(self,name,color,price):
self.name = name
self.color = color
self.price = price
def start(self):
print(self.name + " Engine started")
car1 = Cars("Maruti", "Red", 10000)
car2 = Cars("BMW", "Black", 200000)
print(car1.name, car1.color, car1.price)
print(car2.name, car2.color, car2.price)
car1.start()
car2.start()
|
from django.db import models
class Residence(models.Model):
residence = models.CharField(max_length=20, verbose_name='Residencia')
class Meta:
verbose_name = 'residencia'
verbose_name_plural = 'residencias'
def __str__(self):
return self.residence.title()
class Category(models.Model):
category = models.CharField(max_length=20, verbose_name='Categoría')
class Meta:
verbose_name = 'categoría'
verbose_name_plural = 'categorías'
def __str__(self):
return self.category.title()
class Agent(models.Model):
cf = models.IntegerField(unique=True, primary_key=True, verbose_name='C.F.')
name = models.CharField(max_length=50, verbose_name='Nombre')
surnames = models.CharField(max_length=100, verbose_name='Apellidos')
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, verbose_name='Categoría')
residence = models.ForeignKey(Residence, on_delete=models.DO_NOTHING, verbose_name="Residencia")
class Meta:
verbose_name = 'agente'
verbose_name_plural = 'agentes'
ordering = ['name']
def __str__(self):
return f"{self.cf} {self.name.title()} {self.surnames.title()}"
class Shift(models.Model):
name = models.CharField(max_length=10, unique=True, verbose_name='Turno')
start = models.TimeField(verbose_name='Inicio', null=True, blank=True)
end = models.TimeField(verbose_name='Fin', null=True, blank=True)
category = models.CharField(max_length=20, verbose_name='Categoría', null=True, blank=True)
class Meta:
verbose_name = 'turno'
verbose_name_plural = 'turnos'
ordering = ['name']
def __str__(self):
return self.name
class AgentShift(models.Model):
shift = models.ForeignKey(Shift, on_delete=models.DO_NOTHING, verbose_name='Turno')
agent = models.ForeignKey(Agent, on_delete=models.DO_NOTHING, verbose_name='Agente')
shift_date = models.DateField(verbose_name='Fecha')
modified = models.BooleanField(verbose_name='Modificado')
class Meta:
verbose_name = 'turno agente'
verbose_name_plural = 'turnos agente'
ordering = ['agent', 'shift_date']
def __str__(self):
return f"{self.shift_date} {self.agent} {self.shift}"
class Document(models.Model):
document = models.FileField(upload_to='documents/', verbose_name='Archivo excel')
uploaded_at = models.DateTimeField(auto_now_add=True, verbose_name='Subido el')
class Meta:
verbose_name = 'documento'
verbose_name_plural = 'documentos'
class Calendar(models.Model):
agent = models.ForeignKey(Agent, on_delete=models.DO_NOTHING, verbose_name="Agente")
calendar = models.CharField(max_length=100, unique=True, verbose_name='Calendario')
class Meta:
verbose_name = 'calendario'
verbose_name_plural = 'calendarios'
|
import pandas as pd
from sklearn import datasets
from kmeans import mkmeans
from make_gif import make_gif, delete_png
if __name__ == '__main__':
# load data
wine = datasets.load_wine()
wine_df = pd.DataFrame(wine.data, columns=wine.feature_names)
# execute
sample_df = mkmeans(wine_df, ['alcohol', 'flavanoids'])
# make GIF
make_gif('fig/kmeans.gif')
# delete png
delete_png('fig')
|
"""
Module with invoke tasks
"""
import invoke
import net.invoke.analyze
import net.invoke.host
import net.invoke.train
import net.invoke.tests
import net.invoke.visualize
# Default invoke collection
ns = invoke.Collection()
# Add collections defined in other files
ns.add_collection(net.invoke.analyze)
ns.add_collection(net.invoke.host)
ns.add_collection(net.invoke.train)
ns.add_collection(net.invoke.tests)
ns.add_collection(net.invoke.visualize)
|
# Write a Python program that asks the user for the radius of a circle.
# Next, ask the user if they would like to calculate the area or circumference of a circle.
# If they choose area, display the area of the circle using the radius.
# Otherwise, display the circumference of the circle using the radius.
#Area = πr^2
#Circumference = 2πr
|
from turtle import *
colors=["red","blue","brown","yellow","grey"]
for n in range(3, 8):
for i in range(n):
color(colors[n-3])
forward(100)
left(360/n)
from turtle import *
colors = ["red","blue","brown","yellow","grey"]
for n in range(0,5):
begin_fill()
color(colors[n])
for i in range(2):
forward(50)
left(90)
forward(100)
left(90)
forward(50)
end_fill()
|
#config.py
WIN = True
|
#__author: "Jing Xu"
#date: 2018/1/23
import sys
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from module import main
main.main()
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
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 django.db import models
# Create your models here.
from datetime import datetime
from django.db import models
class History(models.Model):
username = models.CharField(max_length=32, verbose_name=u'用户名')
bk_biz_name = models.CharField(max_length=64, verbose_name=u'业务名称', null=True)
bk_job_id = models.IntegerField(verbose_name=u'作业ID', null=True)
ip_list = models.TextField(verbose_name=u'主机列表', null=True)
result = models.IntegerField(verbose_name=u'作业执行结果', null=True)
log = models.TextField(verbose_name=u'作业执行日志', null=True)
status = models.IntegerField(verbose_name=u'作业执行状态', null=True)
created = models.DateField(verbose_name=u'创建时间', default=datetime.now)
class Meta:
db_table = 'history'
verbose_name = u'执行历史'
verbose_name_plural = verbose_name
|
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# author: Stanford cs231n 2016 winter assignment teaching-assistant, Justin Johnson
# modified by zhaofeng-shu33
import numpy as np
def rel_error(x, y):
""" returns relative error """
return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
def eval_numerical_gradient(f, x, verbose=True, h=0.00001):
"""
a naive implementation of numerical gradient of f at x
- f should be a function that takes a single argument
- x is the point (numpy array) to evaluate the gradient at
"""
fx = f(x) # evaluate function value at original point
grad = np.zeros_like(x)
# iterate over all indexes in x
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
# evaluate function at x+h
ix = it.multi_index
oldval = x[ix]
x[ix] = oldval + h # increment by h
fxph = f(x) # evalute f(x + h)
x[ix] = oldval - h
fxmh = f(x) # evaluate f(x - h)
x[ix] = oldval # restore
# compute the partial derivative with centered formula
grad[ix] = (fxph - fxmh) / (2 * h) # the slope
if verbose:
print(ix, grad[ix])
it.iternext() # step to next dimension
return grad
def report_gradient(net, X, y, regularization):
_, grads = net.loss(X, y, reg=regularization)
f = lambda W: net.loss(X, y, reg=regularization)[0]
rel_error_total = 0
for param_name in grads:
param_grad_num = eval_numerical_gradient(f, net.params[param_name], verbose=False)
rel_error_total += rel_error(param_grad_num, grads[param_name])
return rel_error_total
def int2bin(i):
if i == 0: return np.array([0,0,0,0,0,0,0,0])
s = []
cnt = 0
while i:
s.append(i & 1)
cnt += 1
i = int(i/2)
bin_array = np.zeros(8)
s.reverse()
bin_array[(8-len(s)):8] = s
return bin_array
|
from pyquil.quilbase import *
from pyquil.gates import QUANTUM_GATES
from quil_run import quil_run
class MeasurementReset(AbstractInstruction):
"""
This is the pyQuil object for a Quil measurement instruction.
"""
def __init__(self, qubit, classical_reg):
if not isinstance(qubit, (Qubit, QubitPlaceholder)):
raise TypeError("qubit should be a Qubit")
if classical_reg and not isinstance(classical_reg, MemoryReference):
raise TypeError("classical_reg should be None or a MemoryReference instance")
self.qubit = qubit
self.classical_reg = classical_reg
def out(self):
if self.classical_reg:
return "MEASURE_RESET {} {}".format(self.qubit.out(), self.classical_reg.out())
else:
return "MEASURE_RESET {}".format(self.qubit.out())
def __str__(self):
if self.classical_reg:
return "MEASURE_RESET {} {}".format(_format_qubit_str(self.qubit), str(self.classical_reg))
else:
return "MEASURE_RESET {}".format(_format_qubit_str(self.qubit))
def get_qubits(self, indices=True):
return {_extract_qubit_index(self.qubit, indices)}
def MEASURE_RESET(qubit, classical_reg):
"""
Produce a MEASURE_RESET instruction.
:param qubit: The qubit to measure.
:param classical_reg: The classical register to measure into, or None.
:return: A Measurement instance.
"""
print("@@@@")
qubit = unpack_qubit(qubit)
if classical_reg is None:
address = None
elif isinstance(classical_reg, int):
warn("Indexing measurement addresses by integers is deprecated. "
+ "Replacing this with the MemoryReference ro[i] instead.")
address = MemoryReference("ro", classical_reg)
else:
address = unpack_classical_reg(classical_reg)
return MeasurementReset(qubit, address)
QUANTUM_GATES['MEASURE_RESET'] = MEASURE_RESET
if __name__ == "__main__":
quil_run("MEASURE 0 ro[0]")
|
#!/usr/bin/python3
from sys import argv, stdin
from docopt import docopt
from collections import defaultdict
import re
import codecs
from signal import signal, SIGPIPE, SIG_DFL
doc = r"""
Usage: ./column.py [options] [<input> ...]
-h,--help show this
-s,--separator <sep> specify the regex used for delimiting columns
[default: \\s+]
-r <right-align-mode> Right align "all" columns, "numeric" columns,
or "no" columns [default: numeric]
-o --output-separator <ofs> Delimiter to use between columns in the output
table [default: ]
"""
def main():
# Handle broken pipes when piping the output of this process to other
# processes.
signal(SIGPIPE,SIG_DFL)
options = docopt(doc)
def isValidLine(x):
y = x.strip()
if y.startswith("#") or len(y) == 0:
return False
return True
def isNumericColumn(x):
for item in x:
if item in ("", "N/A", "NA"): continue
try:
float(item)
except:
return False
return True
lines = None
if len(options["<input>"]) == 0:
# read from stdin
lines = [x.strip().encode("utf-8") for x in stdin.readlines() \
if isValidLine(x)]
else:
linesList = []
for name in options["<input>"]:
with codecs.open(name, "r", "utf-8") as f:
linesList.append([x.strip().encode("utf-8") \
for x in f.readlines() if isValidLine(x)])
lines = reduce(lambda x, a: x + a, linesList, [])
sep = re.compile(options['--separator'])
# Derive the number of columns from the header column
headerLine = lines.pop(0)
headerColumns = sep.split(headerLine)
columnLists = defaultdict(list)
for line in lines:
columns = sep.split(line)
for i in xrange(len(headerColumns)):
if i < len(columns):
columnLists[headerColumns[i]].append(columns[i])
else:
columnLists[headerColumns[i]].append("")
for key in columnLists:
maxWidth = max(len(x) for x in (columnLists[key] + [key]))
if options['-r'] == "all":
columnLists[key] = [key.rjust(maxWidth)] + \
[x.rjust(maxWidth) for x in columnLists[key]]
elif options['-r'] == "no":
columnLists[key] = [key.ljust(maxWidth)] + \
[x.ljust(maxWidth) for x in columnLists[key]]
else:
if isNumericColumn(columnLists[key]):
columnLists[key] = [key.rjust(maxWidth)] + \
[x.rjust(maxWidth) for x in columnLists[key]]
else:
columnLists[key] = [key.ljust(maxWidth)] + \
[x.ljust(maxWidth) for x in columnLists[key]]
orderedColumns = \
[columnLists[headerColumns[i]] for i in xrange(len(headerColumns))]
for row in zip(*orderedColumns):
print(options['--output-separator'].join(row))
if __name__ == '__main__':
main()
|
from flask import Blueprint, render_template, request, redirect, url_for
import json
import os
from . import crud
import sys
main = Blueprint('main', __name__)
#cannot define function and use in a route. try creating a module of functions and importing
@main.route('/')
def index():
lists = crud.read_lists()
return render_template('homepage.html', lists=lists)
@main.route('/list', methods=['POST'])
def list():
name = request.form.get('chooselist')
items = crud.open_file(name)
return render_template('list.html', items=items, name=name)
@main.route('/list_post/<name>', methods=['POST'])
def list_post(name):
items = crud.open_file(name)
list_item = request.form.get('items')
if list_item:
items.append(f'{list_item}')
crud.append_file(name, items)
return render_template('list.html',items=items, name=name)
@main.route('/drop_down_remove/<name>', methods=['POST'])
def drop_down(name):
items = crud.open_file(name)
list_remove = request.form.get('drop_down')
if list_remove:
items.remove(f'{list_remove}')
crud.append_file(name, items)
return render_template('list.html', items=items, name=name)
@main.route('/create_list', methods=['POST'])
def create_list():
name = request.form.get('new_list')
crud.append_file(name, [])
lists = crud.read_lists()
lists.append(f'{name}')
crud.append_lists(lists)
items = crud.open_file(name)
return render_template('list.html', items=items, name=name)
@main.route('/delete_list', methods=['POST'])
def delete_list():
name = request.form.get('current_lists')
try:
os.remove('/Users/austin/src/web_app/lists/' + name + '.json')
lists = crud.read_lists()
lists.remove(f'{name}')
crud.append_lists(lists)
return render_template('homepage.html', lists=lists)
except FileNotFoundError:
lists = crud.read_lists()
return render_template('homepage.html', lists=lists)
except TypeError:
lists = crud.read_lists()
return render_template('homepage.html', lists=lists)
|
import subprocess
from tests import helpers as h
from tests.paths import LIB_SH
class Case:
def __init__(self, args, rc, stdout, stderr):
self.args = args
self.rc = rc
self.stdout = stdout.encode()
self.stderr = stderr.encode()
def __str__(self):
return self.args.replace(' ', '~')
def cases():
yield Case('', 0, '', h.cyan("$ ''") + '\n' + h.green("0 ''") + '\n')
yield Case(
'echo a', 0, 'a\n',
h.cyan('$ echo a') + '\n' + h.green('0 echo a') + '\n',
)
yield Case(
'false', 1, '',
h.cyan('$ false') + '\n' + h.red('1 false') + '\n',
)
yield Case(
'--only-failure false', 1, '',
h.red('1 false') + '\n',
)
@h.cases(cases())
def test(_, case):
c = f'. {LIB_SH}; verbose {case.args}'
argv = ['bash', '-c', c]
pr = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
assert pr.returncode == case.rc
assert pr.stdout == case.stdout
assert pr.stderr == case.stderr
|
import cv2
import numpy as np
image = cv2.imread('image.jpg')
img_bgr = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
template = cv2.imread('template.jpg', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_bgr, template, cv2.TM_CCOEFF_NORMED)
res1 = cv2.cvtColor(res, cv2.COLOR_GRAY2BGR)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(image, pt, (pt[0]+w, pt[1]+h), (0, 255, 0), 1)
# result
cv2.imshow("template", image)
cv2.imshow("RES", res)
cv2.waitKey(0)
cv2.imwrite('9_templateMatching(res).jpg', image)
cv2.destroyAllWindows()
|
# Generated by Django 2.1.15 on 2020-02-21 05:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ibookApp', '0005_auto_20200221_1049'),
]
operations = [
migrations.AddField(
model_name='feeds',
name='byEmailID',
field=models.CharField(default=None, max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='feeds',
name='feedDate',
field=models.DateTimeField(default='2020-02-21 11:13:53'),
),
migrations.AlterField(
model_name='userregistration',
name='signupDate',
field=models.DateTimeField(default='2020-02-21 11:13:53'),
),
]
|
# simple network to demonstrate what the contours of the cost
# function look like in various scenarios
# now stochastic...
import matplotlib.pyplot as plt
import numpy as np
import pdb
m = 200
X = np.random.randn(2, m)
Y = np.zeros(m)
p_range = [[-3, 3], [-3, 3]]
# generate the data
for i in range(0, m):
if 1*X[0][i] - 1*X[1][i] < 0:
Y[i] = 1
def display_data(m, X, Y, ax=None):
for i in range(0, m):
color = 'r'
if Y[i] == 1:
color = 'g'
if ax == None:
plt.scatter(X[0][i], X[1][i], c=color)
else:
ax.scatter(X[0][i], X[1][i], c=color)
def display_data_error(m, X, Y, A, ax=None):
for i in range(0, m):
color = 'r'
if Y[i] == 1:
color = 'g'
if Y[i] != np.round(A[i]):
color='k'
if ax == None:
plt.scatter(X[0][i], X[1][i], c=color)
else:
ax.scatter(X[0][i], X[1][i], c=color)
def display_error(W, b, ax=None):
nxs = 10; nys = 10;
xr = p_range[0]; yr = p_range[1];
heats = [[0 for i in range(0, nxs)] for j in range(0, nys)]
xs = np.linspace(xr[0], xr[1], nxs)
ys = np.linspace(yr[0], yr[1], nys)
for i in range(0, nys):
for j in range(0, nxs):
Z = W[0][0]*xs[j] + W[0][1]*ys[i] + b
A = sigmoid(Z)
heats[i][j] = A
if ax == None:
plt.imshow(heats, extent=[p_range[0][0],p_range[0][1],p_range[1][1],p_range[1][0]]) # wierd range to reverse from matrix indexing
# (top is smaller to grid indexing top is larger)
else:
ax.imshow(heats, extent=[p_range[0][0],p_range[0][1],p_range[1][1],p_range[1][0]])
def percent_error(Y, A, m):
return np.sum(np.abs(Y-np.round(A))) / m
# what is the cost asociated with a certain choice of W and b, given the data
def J_Mb(Wx, Wy, b, X, Y):
Z = np.dot(np.array([[Wx, Wy]]), X) + b
A = sigmoid(Z)[0]
return avg(cross_entropy(Y, A))
def J_contours(X, Y, b, ax=None):
nxs = 200; nys = 200;
xr = [-30,30]; yr = [-30,30];
heats = [[0 for j in range(0, nxs)] for i in range(0, nys)]
wxs = np.linspace(xr[0], xr[1], nxs)
wys = np.linspace(yr[0], yr[1], nys)
for i in range(0, nys):
for j in range(0, nxs):
heats[i][j] = J_Mb(wxs[j], wys[i], b, X, Y)
return heats, wxs, wys
def plot_J_stuff(X, Y, b, ws=[], js=[], ax=None, ax3d=None):
heats, wxs, wys = J_contours(X, Y, b, ax=ax)
rxw, ryw = np.meshgrid(wxs, wys)
if ax == None:
# plt.contour(X, Y, Z)
plt.imshow(heats, extent=[-30,30,-30,30])
else:
# ax.imshow(heats, extent=[-10,10,-10,10])
ax.contour(rxw, ryw, np.array(heats))
if ax3d != None:
ax3d.plot_surface(rxw, ryw, np.array(heats))
ax3d.scatter([w[0][0] for w in ws], [w[0][1] for w in ws], js, c='r')
ax3d.plot([w[0][0] for w in ws], [w[0][1] for w in ws], js, c='k')
def sigmoid(Z):
return 1 / ( 1 + np.exp(-Z) )
def cross_entropy(Y, A):
eps = 10**(-8)
return -Y*np.log(A+eps) - (1-Y)*np.log(1-A+eps)
def avg(a):
return np.sum(a) / len(a)
# we will use a linear decision boundary
# AKA take Z = np.dot(W, X) + b
# and then do A = sigmoid(Z) element wise for predictions
# then compute the cost
# we use J(A; Y) = cross entropy = -Y*log(A) - (1-Y)*log(1-A)
# average this over all training examples for total cost
# the backpropogation is also trivial
# dJ/dA = dA = (A-Y) / ((A)(1-A))
# dZ = A - Y
# db = average(dZ)
# Note Z[i] = X[0][i]*W[0] + X[1][i]*W[1]
# thus dZ[i]/dW[j] = X[j][i]
# But those are already the dimensions of X
# dJ/dW[j] = dJ / dZ * dZ / dW[j]
# the multipliction show above is done ELEMENT WISE
# every training example has an asociated dJ/dZ[i] and dZ[i]/dW[j]
# thus simply np.dot(dZ, X.T) gives dW
W = np.random.randn(1, 2)*0.01
W = np.array([[2.,1.3]])
b = 0
itterations = 10**6
alpha = 10**(3)
fig = plt.figure()
# note the args in add_subplot are grid size 1 grid size 2 and then which one it is
# not what I thought previously
cost_p = fig.add_subplot(2,2,1)
data_p = fig.add_subplot(2,2,2)
contour_p = fig.add_subplot(2,2,3)
fig3d = plt.figure()
from mpl_toolkits.mplot3d import Axes3D
d3_p = Axes3D(fig3d)
plt_gap = 30
ws = []
js = []
for it in range(0, itterations):
# pdb.set_trace()
# current example!!!!
ex = np.random.randint(0, m)
# forward propogation
Z = W[0][0]*X[0][ex] + W[0][1]*X[1][ex] + b
A = sigmoid(Z)
# J = avg(cross_entropy(Y, A))
J = cross_entropy(Y[ex], A)
# backwards propogation
dZ = A - Y[ex]
db = dZ
dW = dZ * X.T[ex].T / m
# W[0][0] -= alpha * dW[0]
W -= alpha * dW
# b -= alpha * db
# plot it (sometimes)
if it % plt_gap == 0:
Z = np.dot(W, X) + b
A = sigmoid(Z)[0]
J = avg(cross_entropy(Y, A))
# plt.cla()
# plt.axis((-3,3,-3,3))
data_p.clear()
data_p.set_xlim(-3, 3)
data_p.set_ylim(-3, 3)
display_error(W, b, ax=data_p)
display_data_error(m, X, Y, A, ax=data_p)
cost_p.scatter(it, J)
print(percent_error(Y, A, m), W, b)
ws.append(np.copy(W))
js.append(J)
d3_p.clear()
plot_J_stuff(X, Y, b, ws = ws, js = js, ax=contour_p, ax3d=d3_p)
plt.pause(0.2)
# pdb.set_trace()
plt.show()
|
from setuptools import setup, find_packages
version = '0.9.4'
long_description = open("README.txt").read()
long_description += """
CHANGES
==========
"""
long_description += open("CHANGES.txt").read()
setup(name='fa.extjs',
version=version,
description="jQuery widgets for formalchemy",
long_description=long_description,
# Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
],
keywords='extjs formalchemy pyramid',
author='Gael Pasgrimaud',
author_email='gael@gawel.org',
url='http://docs.formalchemy.org/fa.jquery/index.html',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['fa'],
message_extractors = { 'fa/extjs': [
('*.py', 'lingua_python', None ),
('templates/**.pt', 'chameleon_xml', None ),
]},
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'FormAlchemy',
'pyramid_formalchemy',
'pyramid',
'simplejson',
'fanstatic',
'js.extjs',
],
entry_points="""
[fanstatic.libraries]
fa.extjs = fa.extjs.fanstatic_resources:library
""",
)
|
import turtle
turtle.shape("turtle")
turtle.speed(4)
# 궁극의 방법
def drawSomething(size, angle):
for i in range(angle):
turtle.forward(size)
turtle.right(360/angle)
drawSomething(100, 5)
drawSomething(200, 6)
drawSomething(10, 10)
|
from django.conf.urls import url
from areas import views
from rest_framework.routers import DefaultRouter
urlpatterns = [
]
# 1 创建路由
router = DefaultRouter()
# 2 注册路由
router.register(r'infos',views.AreaViewSet,base_name='area')
# 3 将router自动生成的url添加到urlpatterns
urlpatterns += router.urls
|
import json
import requests
op = -1
def imprimirHabitacion(habitacion):
id = habitacion['id']
plazas = habitacion['plazas']
equipamiento = habitacion['equipamiento']
n = len(equipamiento)
cadequip = equipamiento[0]
if(n > 1):
i = 1
while(i < n):
if(i < n-1):
cadequip += ", "+equipamiento[i]
else:
cadequip += " y "+equipamiento[i]
i += 1
ocupada = habitacion['ocupada']
print("Habitación "+str(id))
print("\t- "+plazas+" plazas")
print("\t- Equipamiento: "+cadequip)
if(ocupada):
print("\t- Ocupada")
else:
print("\t- Libre")
def altaHabitacion():
plazas = input("Introduce el número de plazas: ")
equipamiento = input("Introduce el equipamiento separado por (,): ")
ocupada = input("Ocupada(s/n): ")
if(ocupada == "s"):
bOcupada = True
else:
bOcupada = False
res = requests.post("http://localhost:8080/altaHabitacion",json={"plazas": plazas, "equipamiento": equipamiento.split(","), "ocupada": bOcupada})
if(res.text == ""):
print("Los datos no se introdujeron correctamente")
else:
print("Se ha creado la siguiente habitación: ")
imprimirHabitacion(json.loads(res.text))
def modificarHabitacion():
id = input("Identificador de la habitación: ")
op = -1
res = requests.get("http://localhost:8080/buscarHabitacion/"+id)
if(res.text == ""):
print("La habitación buscada no existe")
else:
imprimirHabitacion(res.json())
while(op != "0"):
print("\n|MODIFICAR HABITACIÓN "+id+"|")
print("1.Modificar plazas")
print("2.Modificar equipamiento")
print("3.Modificar estado de ocupación")
print("0.Salir")
op = input("\nOpción: ")
if(op == "1"):
plazas = input("Introduce el número de plazas: ")
res = requests.put("http://localhost:8080/modificarHabitacion/"+id,json={"plazas": plazas})
elif(op == "2"):
equipamiento = input("Introduce el equipamiento separado por (,): ")
res = requests.put("http://localhost:8080/modificarHabitacion/"+id,json={"equipamiento": equipamiento.split(",")})
elif(op == "3"):
ocupada = input("Ocupada(s/n): ")
if(ocupada == "s"):
bOcupada = True
else:
bOcupada = False
res = requests.put("http://localhost:8080/modificarHabitacion/"+id,json={"ocupada": bOcupada})
if(op == "1" or op == "2" or op == "3"):
if(res.text == ""):
print("La modificación introducida es incorrecta")
else:
print("Habitación modificada:")
imprimirHabitacion(json.loads(res.text))
elif op != '0':
print('Operación no contemplada.\n')
def listaHabitaciones():
res = requests.get("http://localhost:8080/listaHabitaciones")
if(res.text == "{}"):
print("No existen habitaciones")
else:
print("\n|LISTA DE HABITACIONES|")
for valor in res.json():
imprimirHabitacion(res.json()[valor])
def buscarHabitacion():
id = input("Identificador de la habitacion: ")
res = requests.get("http://localhost:8080/buscarHabitacion/"+id)
if(res.text == ""):
print("La habitación buscada no existe")
else:
print("|HABITACIÓN "+id+"|")
imprimirHabitacion(res.json())
def eliminarHabitacion():
id = input("Identificador de la habitacion: ")
res = requests.delete("http://localhost:8080/eliminarHabitacion/"+id)
if(res.text == ""):
print("La habitación a eliminar no existe")
else:
print("La habitacion "+res.text+" ha sido eliminada")
def habitacionesDesocupadas():
res = requests.get('http://localhost:8080/habitaciones/Desocupadas')
if(res.text == "{}"):
print("No hay habitaciones vacías.")
else:
print("|LISTA DE HABITACIONES DESOCUPADAS|")
for valor in res.json():
imprimirHabitacion(valor)
def habitacionesOcupadas():
res = requests.get('http://localhost:8080/habitaciones/Ocupadas')
if(res.text == "{}"):
print("No hay habitaciones ocupadas.")
else:
print("|LISTA DE HABITACIONES OCUPADAS|")
for valor in res.json():
imprimirHabitacion(valor)
while(op != "0"):
print("\n|API HOTEL|")
print("1. Dar de alta habitación")
print("2. Modificar habitación")
print("3. Lista de habitaciones")
print("4. Buscar habitación")
print('5. Habitaciones desocupadas')
print('6. Habitaciones ocupadas')
print("7. Eliminar habitacion")
print("0. Salir")
op = input("\nOpción: ")
if(op == "1"):
altaHabitacion()
elif(op == "2"):
modificarHabitacion()
elif(op == "3"):
listaHabitaciones()
elif(op == "4"):
buscarHabitacion()
elif(op == '5'):
habitacionesDesocupadas()
elif(op == '6'):
habitacionesOcupadas()
elif(op == "7"):
eliminarHabitacion()
|
try:
result = 4/0
print(result)
except Exception as e:
print(e)
print("Program End")
|
from sample_device.tsne_ecg import scatter
from np_datasets_wizard.json_to_np_randomly import get_numpy_from_json
from np_datasets_wizard.json_to_np_by_qrs import get_numpy_from_json as get_np_by_shift
from sample_device.utils import load_json
from settings import PATH_TO_METADATASETS_FOLDER
from np_datasets_wizard.downsamplle_np_datset import downsample_dataset
import os
import numpy as np
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
RS = 20150101
def get_contrast(patch_len, amount_of_patches):
file_path = os.path.join(PATH_TO_METADATASETS_FOLDER, "unnormal_axis30.json")
json_data = load_json(file_path)
leads_names = ['i']
results, labels= get_numpy_from_json(json_data, patch_len, leads_names, amount_of_patches)
ecg_patches = np.squeeze(results, axis=1)
return ecg_patches, labels
def get_control_results(patch_len, control):
file_path = os.path.join(PATH_TO_METADATASETS_FOLDER, "7_pacients_ideally_healthy_and_normal_axis.json" )
json_data=load_json(file_path)
results, labels= get_np_by_shift(json_data, patch_len, ['i'], "qrs", control)
ecg_patches = np.squeeze(results, axis=1)
return ecg_patches, labels
def make_experiment(controls_list, patch_len, name, maxpool):
"""
Saves clasterisation picture for every control from list.
:param controls_list: list of integers
:param patch_len: a number >0
:param name: Save them into folder with name.
:return:
"""
os.makedirs(name, exist_ok=True)
amount_of_patches = 250
ecg_contrast, patient_ids_contrast = get_contrast(patch_len, amount_of_patches)
labels_contrast =[0] * len(ecg_contrast)
for control in controls_list:
pic = str(control)+"_len"+ str(patch_len)+".png"
picname = os.path.join(name , pic)
control_results, patients_ids = get_control_results(patch_len, control)
labels_results =[1] * len(control_results)
labels = np.concatenate((labels_results, labels_contrast), axis=0)
ecg_patches = np.concatenate((control_results, ecg_contrast), axis=0)
if maxpool <2:
pass
else:
ecg_patches = downsample_dataset(ecg_patches, maxpool)
print(ecg_patches.shape)
digits_proj = TSNE(random_state=RS).fit_transform(ecg_patches)
scatter(digits_proj, labels)
plt.savefig(picname)
def make_seria_of_experiments(name, patch_lens,controls_list, maxpool):
print ("start seria...")
for patch_len in patch_lens:
make_experiment(controls_list, patch_len, name, maxpool)
if __name__ == "__main__":
controls_list = [ 0, 200]
patch_lens = [64]
name = "TEST"
make_seria_of_experiments(name, patch_lens, controls_list, 16)
|
import sqlite3
#name = input()
#idade = input()
db = sqlite3.connect("projeto.db")
c1 = db.cursor()
c1.execute("select * from users")
for item in c1.fetchall():
print(item)
c1.close()
#db.commit()
|
a = int(input())
b = int(input())
s = a * b
print(s)
|
# -*- coding: utf-8 -*-
import time
from report import report_sxw
import logging
_logger = logging.getLogger('reportes')
class reportes_report_v(report_sxw.rml_parse):
gran_cantidad = 0.0
gran_exento = 0.0
gran_neto = 0.0
gran_iva = 0.0
gran_total = 0.0
final_exento=0.0
final_neto=0.0
final_iva=0.0
final_total=0.0
def __init__(self, cr, uid, name, context):
super(reportes_report_v, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
'time': time,
'_periodos_v': self._periodos_v,
'corto_dat_v': self.corto_dat_v,
'get__v': self._get__v,
'convert':self.convert,
'nuevo':self.nuevo
, 'detalle':self.detalle
, 'subtotales':self.subtotales
, 'totales':self.totales
})
def conversor(self, numero):
numero_total = ''
for z in numero:
if z != '.':
numero_total += z
return int(numero_total)
def convert(self, amount, cur):
amt_en = amount_to_text_es.amount_to_text(amount, 'es', cur)
return amt_en
def _periodos_v(self, period_list):
aux_ = 0
feci = 0
fecf = 0
for period_id in period_list:
if aux_ == 0:
self.cr.execute("select name from account_period where id=" + str(period_id) + "")
for record in self.cr.fetchall():
feci = record[0]
aux_ = aux_ + 1
self.cr.execute("select name from account_period where id=" + str(period_id) + "")
for record in self.cr.fetchall():
fecf = record[0]
return 'Desde ' + feci + ' Hasta ' + fecf
def corto_dat_v(self, arg1, largo):
if len(arg1) > largo:
descripcion = arg1[:largo - 1]
else:
descripcion = arg1
return descripcion
def _get__v(self, co, pe, si, ty):
d = []
Lds = ''
Lds_ = ''
cc = 0
tpOo = ""
aeOo = 0
aeS = 0
txS = 0
unS = 0
toS = 0
cl = 0
sum_ae = 0
sum_tx = 0
sum_un = 0
sum_to = 0
d.append({'auxiliar':'t', })
for p in pe:
Lds = Lds + str(p) + ","
while cc < len(Lds) - 1:
Lds_ = Lds_ + Lds[cc]
cc = cc + 1
sql = """SELECT ai.number
,date_invoice
,rp.vat
, rp.name
, aj.code
, ai.amount_untaxed
, ai.amount_tax
, ai.amount_total
, (
select
CASE WHEN sum(ait.base_amount) is null
then 0 else sum(ait.base_amount)
end as a
from account_invoice_tax ait
where UPPER(ait.name) like UPPER('%exento%')
and ait.invoice_id = ai.id
) base_amount
,aj.name
FROM public.account_invoice ai
, public.account_journal aj
, public.res_partner rp
WHERE ai.state not in ('draft', 'cancel')
and ai.partner_id = rp.id
AND aj.id = ai.journal_id
and aj.code between '200' and '299'
and ai.period_id in (""" + "".join(map(str, Lds_)) + """)
and ai.company_id = """ + str(co[0]) + """
order by aj.name, ai.number"""
print(sql)
self.cr.execute(sql)
for record in self.cr.fetchall():
nmOo = record[0]
dtOo = record[1]
rtOo = record[2]
clOo = record[3]
tpOo = ""
aeOo = record[8]
if record[4] == "201":
tpOo = "FN"
elif record[4] == "202":
tpOo = "FE"
elif record[4] == "203":
tpOo = "BV"
elif record[4] == "211" or record[4] == "212":
tpOo = "EX"
elif record[4] == "213":
tpOo = "EEX"
elif record[4] == "221":
tpOo = "ND"
elif record[4] == "241":
tpOo = "NCN"
elif record[4] == "242":
tpOo = "NCE"
txOo = record[6] # tax
unOo = record[5] # untax
toOo = record[7] # total
sum_ae += aeOo
sum_tx += txOo
sum_un += unOo
sum_to += toOo
if cl == 56:
OoO = {
'number': '',
'x_tipo_doc': '',
'date_invoice': '',
'rut': '',
'cliente': '',
'afe_exe':self.formatLang(aeS, digits=0),
'cc_amount_tax': self.formatLang(txS, digits=0),
'cc_amount_untaxed': self.formatLang(unS, digits=0),
'cc_amount_total': self.formatLang(toS, digits=0),
'auxiliar':'dT'
}
d.append(OoO)
aeS = 0
txS = 0
unS = 0
toS = 0
cl = 0
d.append({'auxiliar':'t', })
OoO = {
'number': nmOo,
'x_tipo_doc': tpOo,
'date_invoice': dtOo,
'rut': rtOo,
'cliente': clOo,
'afe_exe':self.formatLang(aeOo, digits=0),
'cc_amount_tax': self.formatLang(txOo, digits=0),
'cc_amount_untaxed': self.formatLang(unOo, digits=0),
'cc_amount_total': self.formatLang(toOo, digits=0),
'auxiliar':'d'
}
aeS += aeOo
txS += txOo
unS += unOo
toS += toOo
d.append(OoO)
cl += 1
# preguntar k onda
OoO = {
'number': '',
'x_tipo_doc': '',
'date_invoice': '',
'rut': '',
'cliente': 'SUB TOTAL',
'afe_exe':self.formatLang(aeS, digits=0),
'cc_amount_tax': self.formatLang(txS, digits=0),
'cc_amount_untaxed': self.formatLang(unS, digits=0),
'cc_amount_total': self.formatLang(toS, digits=0),
'auxiliar':'dT'
}
d.append(OoO)
aeS = 0
txS = 0
unS = 0
toS = 0
OoO = {
'number': '',
'x_tipo_doc': '',
'date_invoice': '',
'rut': '',
'cliente': 'TOTAL',
'afe_exe':self.formatLang(sum_ae, digits=0),
'cc_amount_tax': self.formatLang(sum_tx, digits=0),
'cc_amount_untaxed': self.formatLang(sum_un, digits=0),
'cc_amount_total': self.formatLang(sum_to, digits=0),
'auxiliar':'dT'
}
d.append(OoO)
return d
def nuevo(self, co, pe, si, ty):
data = []
periodos = ",".join(map(str, pe))
sql = """
select id, name from account_journal aj where id in (
select journal_id
from account_invoice ai
where ai.state not in ('draft', 'cancel')
and ai.period_id in ({0})
and ai.company_id = {1}
and ai.type in ('out_invoice','out_refund')
)
""".format(periodos, str(co[0]))
print sql
self.cr.execute(sql)
for record in self.cr.fetchall():
data.insert(len(data) + 1, {'id':record[0],
'name':record[1],
})
return data
def detalle(self, journal_id, co, pe, si, ty):
neto = 0.0
iva = 0.0
total = 0.0
exento = 0.0
data = []
periodos = ",".join(map(str, pe))
sql = """
SELECT ai.number
,date_invoice
,rp.vat
, rp.name
, ai.amount_untaxed
, ai.amount_tax
, ai.amount_total
, (
select
CASE WHEN sum(ait.base_amount) is null
then 0 else sum(ait.base_amount)
end as a
from account_invoice_tax ait
where UPPER(ait.name) like UPPER('%exento%')
and ait.invoice_id = ai.id
) base_amount
,(select public.res_currency.name from public.res_currency where public.res_currency.id = ai.currency_id)
,(select public.account_journal.name from public.account_journal where public.account_journal.id = ai.journal_id)
,(select public.res_currency.id from public.res_currency where public.res_currency.id = ai.currency_id)
,ai.state
FROM public.account_invoice ai
, public.res_partner rp
WHERE ai.state not in ('draft')
and ai.partner_id = rp.id
AND ai.journal_id = {0}
and ai.period_id in ({1})
and ai.company_id = {2}
order by ai.number
""".format(journal_id, periodos, str(co[0]))
self.cr.execute(sql)
for record in self.cr.fetchall():
self.gran_cantidad+=1
print record[8] # busco la moneda del movimiento
print record[9] # busco el nombre del journal
print record[10] # busco el id de res currency
print record[1] # la fecha
if (record[8] == 'USD') and (record[9] == 'FACTURA DE EXPORTACION MANUAL'):
print 'se mete'
sql7 = """select rcr.rate from public.res_currency_rate rcr
where rcr.currency_id = (select id from public.res_currency rc where rc.name = 'CLP')
and rcr.name <= '{0}'
order by rcr.name desc limit 1
""".format(record[1])
print sql7
self.cr.execute(sql7)
for rt in self.cr.fetchall():
ratio = rt[0]
print ratio
exento=record[7]
neto = record[4]
iva = record[5]
total = record[6]
neto *= ratio
iva *= ratio
total *= ratio
else:
neto = record[4]
iva = record[5]
total = record[6]
if record[9] == 'FACTURA DE EXPORTACION MANUAL':
temporal=0.0
temporal=neto
neto=exento
exento=temporal
if record[5] == 0 and 'EXENT' in str(record[9]):
exento=neto
neto=0
sql8 = """select type from account_journal where id = {0} limit 1""".format(journal_id)
self.cr.execute(sql8)
for buscacode in self.cr.fetchall():
code = buscacode[0]
if code == 'sale_refund':
self.gran_exento-= self.conversor(self.formatLang(exento, digits=0))
self.gran_neto-= self.conversor(self.formatLang(neto, digits=0))
self.gran_iva-= self.conversor(self.formatLang(iva, digits=0))
self.gran_total-= self.conversor(self.formatLang(total, digits=0))
self.final_exento -= self.conversor(self.formatLang(exento, digits=0))
self.final_neto-=self.conversor(self.formatLang(neto, digits=0))
self.final_iva-=self.conversor(self.formatLang(iva, digits=0))
self.final_total-=self.conversor(self.formatLang(total, digits=0))
else:
self.gran_exento+= self.conversor(self.formatLang(exento, digits=0))
self.gran_neto+= self.conversor(self.formatLang(neto, digits=0))
self.gran_iva+= self.conversor(self.formatLang(iva, digits=0))
self.gran_total+= self.conversor(self.formatLang(total, digits=0))
self.final_exento += self.conversor(self.formatLang(exento, digits=0))
self.final_neto+=self.conversor(self.formatLang(neto, digits=0))
self.final_iva+=self.conversor(self.formatLang(iva, digits=0))
self.final_total+=self.conversor(self.formatLang(total, digits=0))
print total
print self.gran_total
rut = record[2] or '' # arregla el rut sacandole las letras del principio y agrega el guion del DV
vat = ''
contador_rut = 0
if len(rut) > 0 :
for r in rut:
contador_rut += 1
if not r.isalpha() and not r == '.' and not r == '-' and contador_rut != len(rut):
vat += r
if contador_rut == len(rut):
vat += '-'
vat += r
numero_factura = record[0]
if numero_factura and len(numero_factura) > 7:
numero_factura = numero_factura[9:20] # trunca los primeros caracteres del numero de factura
print record[11]
if record[11] == 'cancel':
self.gran_neto-=neto
self.gran_iva-=iva
self.gran_total-=total
self.final_neto-=neto
self.final_iva-=iva
self.final_total-=total
record3 = 'Nulo'
total = 0
neto = 0
iva = 0
else:
record3 = record[3]
data.insert(len(data) + 1,
{
'number': numero_factura,
'x_tipo_doc': "",
'date_invoice': record[1],
'rut': vat,
'cliente': record3,
'afe_exe':self.formatLang(exento, digits=0),
'cc_amount_tax': self.formatLang(iva, digits=0),
'cc_amount_untaxed': self.formatLang(neto, digits=0),
'cc_amount_total': self.formatLang(total, digits=0),
'auxiliar':'d',
'gran_exento':self.formatLang(self.gran_exento, digits=0),
'gran_neto':self.formatLang(self.gran_neto, digits=0),
'gran_iva':self.formatLang(self.gran_iva, digits=0),
'gran_total':self.formatLang(self.gran_total, digits=0),
'final_exento':self.formatLang(self.final_exento, digits=0),
'final_neto':self.formatLang(self.final_neto, digits=0),
'final_iva':self.formatLang(self.final_iva, digits=0),
'final_total':self.formatLang(self.final_total, digits=0),
})
self.gran_total=0.0
self.gran_neto=0.0
self.gran_iva=0.0
self.gran_exento=0.0
return data
def subtotales(self, journal_id, co, pe, si, ty):
neto = 0.0
iva = 0.0
total = 0.0
cantidad=0
exento=0.0
data = []
periodos = ",".join(map(str, pe))
sql = """
SELECT ai.number
,date_invoice
,rp.vat
, rp.name
, ai.amount_untaxed
, ai.amount_tax
, ai.amount_total
, (
select
CASE WHEN sum(ait.base_amount) is null
then 0 else sum(ait.base_amount)
end as a
from account_invoice_tax ait
where UPPER(ait.name) like UPPER('%exento%')
and ait.invoice_id = ai.id
) base_amount
,(select public.res_currency.name from public.res_currency where public.res_currency.id = ai.currency_id)
,(select public.account_journal.name from public.account_journal where public.account_journal.id = ai.journal_id)
,(select public.res_currency.id from public.res_currency where public.res_currency.id = ai.currency_id)
,ai.state
FROM public.account_invoice ai
, public.res_partner rp
WHERE ai.state not in ('draft')
and ai.partner_id = rp.id
AND ai.journal_id = {0}
and ai.period_id in ({1})
and ai.company_id = {2}
order by ai.number
""".format(journal_id, periodos, str(co[0]))
self.cr.execute(sql)
for record in self.cr.fetchall():
cantidad+=1
#print record[8] # busco la moneda del movimiento
#print record[9] # busco el nombre del journal
#print record[10] # busco el id de res currency
#print record[1] # la fecha
if (record[8] == 'USD') and (record[9] == 'FACTURA DE EXPORTACION MANUAL'):
print 'se mete'
sql7 = """select rcr.rate from public.res_currency_rate rcr
where rcr.currency_id = (select id from public.res_currency rc where rc.name = 'CLP')
and rcr.name <= '{0}'
order by rcr.name desc limit 1
""".format(record[1])
print sql7
self.cr.execute(sql7)
for rt in self.cr.fetchall():
ratio = rt[0]
print ratio
exento=record[7]
neto = record[4]
iva = record[5]
total = record[6]
neto *= ratio
iva *= ratio
total *= ratio
else:
neto = record[4]
iva = record[5]
total = record[6]
if record[9] == 'FACTURA DE EXPORTACION MANUAL':
temporal=0.0
temporal=neto
neto=exento
exento=temporal
if record[5] == 0 and 'EXENT' in str(record[9]):
exento=neto
neto=0
sql8 = """select type from account_journal where id = {0} limit 1""".format(journal_id)
self.cr.execute(sql8)
for buscacode in self.cr.fetchall():
code = buscacode[0]
if code == 'sale_refund':
self.gran_exento-= self.conversor(self.formatLang(exento, digits=0))
self.gran_neto-= self.conversor(self.formatLang(neto, digits=0))
self.gran_iva-= self.conversor(self.formatLang(iva, digits=0))
self.gran_total-= self.conversor(self.formatLang(total, digits=0))
else:
self.gran_exento+= self.conversor(self.formatLang(exento, digits=0))
self.gran_neto+= self.conversor(self.formatLang(neto, digits=0))
self.gran_iva+= self.conversor(self.formatLang(iva, digits=0))
self.gran_total+= self.conversor(self.formatLang(total, digits=0))
print total
print self.gran_total
rut = record[2] or '' # arregla el rut sacandole las letras del principio y agrega el guion del DV
vat = ''
contador_rut = 0
if len(rut) > 0 :
for r in rut:
contador_rut += 1
if not r.isalpha() and not r == '.' and not r == '-' and contador_rut != len(rut):
vat += r
if contador_rut == len(rut):
vat += '-'
vat += r
numero_factura = record[0]
if numero_factura and len(numero_factura) > 7:
numero_factura = numero_factura[9:20] # trunca los primeros caracteres del numero de factura
print record[11]
if record[11] == 'cancel':
self.gran_neto-=neto
self.gran_iva-=iva
self.gran_total-=total
#self.final_neto-=neto
#self.final_iva-=iva
#self.final_total-=total
record3 = 'Nulo'
total = 0
neto = 0
iva = 0
exento=0
else:
record3 = record[3]
print neto
print self.gran_neto
data.insert(len(data) + 1,
{
'number': numero_factura,
'x_tipo_doc': "",
'date_invoice': record[1],
'rut': vat,
'cliente': record3,
'afe_exe':self.formatLang(exento, digits=0),
'cc_amount_tax': self.formatLang(iva, digits=0),
'cc_amount_untaxed': self.formatLang(neto, digits=0),
'cc_amount_total': self.formatLang(total, digits=0),
'auxiliar':'d',
'gran_exento':self.formatLang(self.gran_exento, digits=0),
'gran_neto':self.formatLang(self.gran_neto, digits=0),
'gran_iva':self.formatLang(self.gran_iva, digits=0),
'gran_total':self.formatLang(self.gran_total, digits=0),
'final_neto':self.formatLang(self.final_neto, digits=0),
'final_iva':self.formatLang(self.final_iva, digits=0),
'final_total':self.formatLang(self.final_total, digits=0),
'cantidad': cantidad,
})
self.gran_total=0.0
self.gran_neto=0.0
self.gran_iva=0.0
self.gran_exento=0.0
return data
def totales(self, co, pe):
periodos = ",".join(map(str, pe))
data = []
sql = """select sum(cantidad) cantidad, sum(amount_untaxed) amount_untaxed, sum(amount_tax) amount_tax,sum(amount_total) amount_total, sum(base_amount) base_amount
from (
select count(*) as cantidad
, coalesce(sum(ai.amount_untaxed),0) amount_untaxed
, coalesce(sum(ai.amount_tax),0) amount_tax
, coalesce(sum(ai.amount_total),0) amount_total
, coalesce(sum((
select
CASE WHEN sum(ait.base_amount) is
null
then 0 else sum(ait.base_amount)
end as a
from account_invoice_tax ait
where UPPER(ait.name) like UPPER('%exento%')
and ait.invoice_id = ai.id
)),0) base_amount
FROM public.account_invoice ai
, public.res_partner rp
WHERE ai.state not in ('draft', 'cancel')
and ai.partner_id = rp.id
AND ai.journal_id in (
select id from account_journal aj where aj.code between '200' and '299' and not
UPPER(name) like UPPER('%nota%') and not UPPER(name) like UPPER('%credito%')
)
and ai.period_id in ({0})
and ai.company_id = {1}
union
select count(*)*-1 as cantidad
, coalesce(sum(ai.amount_untaxed),0)*-1 amount_untaxed
, coalesce(sum(ai.amount_tax),0)*-1 amount_tax
, coalesce(sum(ai.amount_total),0)*-1 amount_total
, coalesce(sum((
select
CASE WHEN sum(ait.base_amount) is
null
then 0 else sum(ait.base_amount)
end as a
from account_invoice_tax ait
where UPPER(ait.name) like UPPER('%exento%')
and ait.invoice_id = ai.id
)),0)*-1 base_amount
FROM public.account_invoice ai
, public.res_partner rp
WHERE ai.state not in ('draft', 'cancel')
and ai.partner_id = rp.id
AND ai.journal_id in (
select id from account_journal aj where aj.code between '200' and '299' and
UPPER(name) like UPPER('%nota%') and UPPER(name) like UPPER('%credito%')
)
and ai.period_id in ({0})
and ai.company_id = {1}
) as a
""".format(periodos, str(co[0]))
#print(sql)
#print self.gran_cantidad
#self.gran_cantidad /= 2
#print self.gran_cantidad
self.cr.execute(sql)
for record in self.cr.fetchall():
data.insert(len(data) + 1,
{
'cantidad':self.formatLang(self.gran_cantidad, digits=0)
, 'base_amount':self.formatLang(self.final_exento, digits=0)
, 'amount_untaxed':self.formatLang(self.final_neto, digits=0)
, 'amount_tax':self.formatLang(self.final_iva, digits=0)
, 'amount_total':self.formatLang(self.final_total, digits=0)
})
return data
report_sxw.report_sxw('report.reportes_print_libven', 'reportes',
'addons/reportes/reportes_report_v.rml', parser=reportes_report_v, header=False)
|
import config
from sqlalchemy import create_engine
import pandas as pd
## Enter DBname here
config.POSTGRES_DBNAME = 'dvdrental'
## Connection string
postgres_str = ('postgresql://{username}:{password}@{ipaddress}:{port}/{dbname}'.format(username=config.POSTGRES_USERNAME,
password=config.POSTGRES_PASSWORD,
ipaddress=config.POSTGRES_ADDRESS,
port=config.POSTGRES_PORT,
dbname=config.POSTGRES_DBNAME))
## Create the connection
cnx = create_engine(postgres_str)
## Test the connection
query = '''SELECT * FROM film;'''
film = pd.read_sql_query(query, cnx)
print(film.head(10))
## Getting all customers who have spent more than $50
query_spend = '''
SELECT
c.customer_id, c.first_name, c.last_name, c.store_id,
count(p.rental_id) as trx_count, sum(p.amount) as total_spend
FROM customer c
INNER JOIN payment p
ON c.customer_id = p.customer_id
GROUP BY c.customer_id
HAVING sum(p.amount) > 50
ORDER BY c.first_name;'''
high_spend_customers = pd.read_sql_query(query_spend, cnx)
print(high_spend_customers.head(10))
|
import logging
import argparse
import os
import json
from os.path import join as pjoin
import tarfile
import errno
from utils import sha1_for_path, canonical_path, makedirs, mygzip
from .models import (ZincIndex, load_index, ZincError, ZincErrors,
ZincOperation, ZincConfig, load_config, ZincManifest, load_manifest,
CreateBundleVersionOperation, ZincCatalog, create_catalog_at_path,
ZincFlavorSpec)
from .defaults import defaults
from .pathfilter import PathFilter
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s')
### Commands #################################################################
def _cmd_verify(path):
catalog = ZincCatalog(path)
results = catalog.verify()
error_count = total_count = 0
for (file, error) in results.items():
if error.code != ZincErrors.OK.code:
print error.message + " : " + file
error_count = error_count + 1
total_count = total_count + 1
print "Verified %d files, %d errors" % (total_count, error_count)
def catalog_create(args):
dest = args.catalog_path
if dest is None:
dest = './%s' % (args.catalog_id)
create_catalog_at_path(dest, args.catalog_id)
def catalog_clean(args):
catalog = ZincCatalog(args.catalog_path)
catalog.clean(dry_run=not args.force)
def bundle_list(args):
catalog = ZincCatalog(args.catalog_path)
for bundle_name in catalog.bundle_names():
versions = catalog.versions_for_bundle(bundle_name)
print bundle_name, versions
def bundle_update(args):
flavors = None
if args.flavors is not None:
with open(args.flavors) as f:
flavors_dict = json.load(f)
flavors = ZincFlavorSpec.from_dict(flavors_dict)
catalog = ZincCatalog(args.catalog_path)
bundle_name = args.bundle_name
path = args.path
force = args.force
manifest = catalog.create_bundle_version(
bundle_name, path, flavor_spec=flavors, force=force)
print "Updated %s v%d" % (manifest.bundle_name, manifest.version)
def bundle_delete(args):
bundle_name = args.bundle_name
version = args.version
catalog = ZincCatalog(args.catalog_path)
if version == 'all':
versions_to_delete = catalog.versions_for_bundle(bundle_name)
else:
versions_to_delete = [version]
for v in versions_to_delete:
catalog.delete_bundle_version(bundle_name, int(v))
def distro_update(args):
catalog = ZincCatalog(args.catalog_path)
bundle_name = args.bundle_name
distro_name = args.distro_name
bundle_version = args.version
if bundle_version != "latest":
bundle_version = int(bundle_version)
catalog.update_distribution(
distro_name, bundle_name, bundle_version)
def distro_delete(args):
catalog = ZincCatalog(args.catalog_path)
bundle_name = args.bundle_name
distro_name = args.distro_name
catalog.delete_distribution(distro_name, bundle_name)
### Main #####################################################################
def main():
parser = argparse.ArgumentParser(description='')
subparsers = parser.add_subparsers(title='subcommands',
description='valid subcommands',
help='additional help')
# catalog:create
parser_catalog_create = subparsers.add_parser('catalog:create', help='catalog:create help')
parser_catalog_create.add_argument('catalog_id')
parser_catalog_create.add_argument('-c', '--catalog_path',
help='Destination path. Defaults to "./<catalog_id>"')
parser_catalog_create.set_defaults(func=catalog_create)
# catalog:clean
parser_catalog_clean = subparsers.add_parser('catalog:clean',
help='catalog:clean help')
parser_catalog_clean.add_argument('-c', '--catalog_path', default='.',
help='Destination path. Defaults to "."')
parser_catalog_clean.add_argument('-f', '--force', default=False, action='store_true',
help='This command does a dry run by default. Specifying this flag '
'will cause files to actually be removed.')
parser_catalog_clean.set_defaults(func=catalog_clean)
# bundle:list
parser_bundle_list = subparsers.add_parser('bundle:list', help='bundle:list help')
parser_bundle_list.add_argument('-c', '--catalog_path', default='.',
help='Catalog path. Defaults to "."')
parser_bundle_list.set_defaults(func=bundle_list)
# bundle:update
parser_bundle_update = subparsers.add_parser('bundle:update', help='bundle:update help')
parser_bundle_update.add_argument('-c', '--catalog_path', default='.',
help='Catalog path. Defaults to "."')
parser_bundle_update.add_argument('--flavors',
help='Flavor spec path. Should be JSON.')
parser_bundle_update.add_argument('-f', '--force', default=False, action='store_true',
help='Update bundle even if no files changed.')
parser_bundle_update.add_argument('bundle_name',
help='Name of the bundle. Must not contain a period (.).')
parser_bundle_update.add_argument('path',
help='Path to files for this bundle.')
parser_bundle_update.set_defaults(func=bundle_update)
# bundle:delete
parser_bundle_delete = subparsers.add_parser('bundle:delete', help='bundle:delete help')
parser_bundle_delete.add_argument('-c', '--catalog_path', default='.',
help='Catalog path. Defaults to "."')
parser_bundle_delete.add_argument('bundle_name',
help='Name of the bundle. Must exist in catalog.')
parser_bundle_delete.add_argument('version',
help='Version number to delete or "all".')
parser_bundle_delete.set_defaults(func=bundle_delete)
# distro:update
parser_distro_update = subparsers.add_parser('distro:update', help='distro:update help')
parser_distro_update.add_argument('-c', '--catalog_path', default='.',
help='Catalog path. Defaults to "."')
parser_distro_update.add_argument('bundle_name',
help='Name of the bundle. Must exist in the catalog.')
parser_distro_update.add_argument('distro_name',
help='Name of the distro.')
parser_distro_update.add_argument('version',
help='Version number or "latest".')
parser_distro_update.set_defaults(func=distro_update)
# distro:delete
parser_distro_delete = subparsers.add_parser('distro:delete', help='distro:delete help')
parser_distro_delete.add_argument('-c', '--catalog_path', default='.',
help='Catalog path. Defaults to "."')
parser_distro_delete.add_argument('bundle_name',
help='Name of the bundle. Must exist in the catalog.')
parser_distro_delete.add_argument('distro_name',
help='Name of the distro.')
parser_distro_delete.set_defaults(func=distro_delete)
args = parser.parse_args()
args.func(args)
# if command == "catalog:verify":
# if len(args) < 2:
# parser.print_usage()
# exit(2)
# path = args[1]
# _cmd_verify(path)
# exit(0)
if __name__ == "__main__":
main()
|
from sqlalchemy.dialects.postgresql import HSTORE as HSTOREBase
from sqlalchemy.ext.mutable import MutableDict
class HSTORE(HSTOREBase):
""" Extends the default HSTORE type to make it mutable by default. """
MutableDict.associate_with(HSTORE)
|
import time
from selenium.common.exceptions import NoSuchElementException
from threading import Thread
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from to_import_secret import sendEmail, comandExecutor
from to_import import acceptConsent, URL, URL_fmExotika, caps
def FM_isDisplayed(desired_cap):
driver = webdriver.Remote(
command_executor=comandExecutor,
desired_capabilities=desired_cap)
driver.get(URL_fmExotika)
wait = WebDriverWait(driver, 1500)
driver.maximize_window()
time.sleep(2)
acceptConsent(driver)
time.sleep(1.5)
try:
zajezdyFMsingle = driver.find_element_by_xpath("//*[@class='page-tour']")
zajezdyFMall = driver.find_elements_by_xpath("//*[@class='page-tour']")
wait.until(EC.visibility_of(zajezdyFMsingle))
if zajezdyFMsingle.is_displayed():
for WebElement in zajezdyFMall:
jdouvidet = WebElement.is_displayed()
if jdouvidet == True:
pass
else:
url = driver.current_url
msg = "Problem s FM - zajezdy se neukazuji " + url
sendEmail(msg)
except NoSuchElementException:
url = driver.current_url
msg = "Problem s FM - zajezdy se neukazuji " + url
sendEmail(msg)
try:
rozbal = driver.find_element_by_xpath("//*[@class='page-tour-cell page-tour-control']")
wait.until(EC.visibility_of(rozbal))
driver.execute_script("arguments[0].click();", rozbal)
time.sleep(2)
except NoSuchElementException:
url = driver.current_url
msg = " Nepodarilo se rozbalit FM zajezd " + url
sendEmail(msg)
try:
rozbalenyZajezd = driver.find_element_by_xpath("//*[@class='page-tour-hotel-name']")
rozbalenyZajezdAll = driver.find_elements_by_xpath("//*[@class='page-tour-hotel-name']")
wait.until(EC.visibility_of(rozbalenyZajezd))
if rozbalenyZajezd.is_displayed():
for WebElement in rozbalenyZajezdAll:
jdouvidet = WebElement.is_displayed()
if jdouvidet == True:
pass
else:
url = driver.current_url
msg = "Nenasel se zadny zajezd pri rozbaleni zajezdu ve FM " + url
sendEmail(msg)
except NoSuchElementException:
url = driver.current_url
msg = "Nenasel se zadny zajezd pri rozbaleni zajezdu ve FM " + url
sendEmail(msg)
driver.quit()
for cap in caps:
Thread(target=FM_isDisplayed, args=(cap,)).start()
|
import numpy as np
import os
import pytest
import unittest
from geopyspark.geotrellis import SpatialKey, Extent, Tile
from geopyspark.geotrellis.layer import TiledRasterLayer
from geopyspark.tests.base_test_class import BaseTestClass
from geopyspark.geotrellis.constants import LayerType, Operation, Neighborhood
from geopyspark.geotrellis.neighborhood import Square, Annulus, Wedge, Circle, Nesw
class FocalTest(BaseTestClass):
cells = np.array([[
[1.0, 1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 0.0]]])
tile = Tile.from_numpy_array(cells, -1.0)
layer = [(SpatialKey(0, 0), tile),
(SpatialKey(1, 0), tile),
(SpatialKey(0, 1), tile),
(SpatialKey(1, 1), tile)]
rdd = BaseTestClass.pysc.parallelize(layer)
extent = {'xmin': 0.0, 'ymin': 0.0, 'xmax': 33.0, 'ymax': 33.0}
layout = {'layoutCols': 2, 'layoutRows': 2, 'tileCols': 5, 'tileRows': 5}
metadata = {'cellType': 'float32ud-1.0',
'extent': extent,
'crs': '+proj=longlat +datum=WGS84 +no_defs ',
'bounds': {
'minKey': {'col': 0, 'row': 0},
'maxKey': {'col': 1, 'row': 1}},
'layoutDefinition': {
'extent': extent,
'tileLayout': {'tileCols': 5, 'tileRows': 5, 'layoutCols': 2, 'layoutRows': 2}}}
raster_rdd = TiledRasterLayer.from_numpy_rdd(LayerType.SPATIAL, rdd, metadata)
@pytest.fixture(autouse=True)
def tearDown(self):
yield
BaseTestClass.pysc._gateway.close()
def test_focal_sum_square(self):
result = self.raster_rdd.focal(
operation=Operation.SUM,
neighborhood=Neighborhood.SQUARE,
param_1=1.0)
self.assertTrue(result.to_numpy_rdd().first()[1].cells[0][1][0] >= 6)
def test_focal_sum_wedge(self):
neighborhood = Wedge(radius=1.0, start_angle=0.0, end_angle=180.0)
self.assertEqual(str(neighborhood), repr(neighborhood))
result = self.raster_rdd.focal(
operation=Operation.SUM,
neighborhood=neighborhood)
self.assertTrue(result.to_numpy_rdd().first()[1].cells[0][1][0] >= 3)
def test_focal_sum_circle(self):
neighborhood = Circle(radius=1.0)
self.assertEqual(str(neighborhood), repr(neighborhood))
result = self.raster_rdd.focal(
operation=Operation.SUM,
neighborhood=neighborhood)
self.assertTrue(result.to_numpy_rdd().first()[1].cells[0][1][0] >= 4)
def test_focal_sum_nesw(self):
neighborhood = Nesw(extent=1.0)
self.assertEqual(str(neighborhood), repr(neighborhood))
result = self.raster_rdd.focal(
operation=Operation.SUM,
neighborhood=neighborhood)
self.assertTrue(result.to_numpy_rdd().first()[1].cells[0][1][0] >= 4)
def test_focal_sum_annulus(self):
neighborhood = Annulus(inner_radius=0.5, outer_radius=1.5)
self.assertEqual(str(neighborhood), repr(neighborhood))
result = self.raster_rdd.focal(
operation=Operation.SUM,
neighborhood=neighborhood)
self.assertTrue(result.to_numpy_rdd().first()[1].cells[0][1][0] >= 5.0)
def test_square(self):
neighborhood = Square(extent=1.0)
self.assertEqual(str(neighborhood), repr(neighborhood))
result = self.raster_rdd.focal(
operation=Operation.SUM,
neighborhood=neighborhood)
self.assertTrue(result.to_numpy_rdd().first()[1].cells[0][1][0] >= 6.0)
def test_focal_sum_int(self):
result = self.raster_rdd.focal(
operation=Operation.SUM,
neighborhood=Neighborhood.SQUARE,
param_1=1)
self.assertTrue(result.to_numpy_rdd().first()[1].cells[0][1][0] >= 6)
def test_focal_sum_square_with_square(self):
square = Square(extent=1.0)
result = self.raster_rdd.focal(
operation=Operation.SUM,
neighborhood=square)
self.assertTrue(result.to_numpy_rdd().first()[1].cells[0][1][0] >= 6)
def test_focal_min(self):
result = self.raster_rdd.focal(operation=Operation.MIN, neighborhood=Neighborhood.ANNULUS,
param_1=2.0, param_2=1.0)
self.assertEqual(result.to_numpy_rdd().first()[1].cells[0][0][0], -1)
def test_focal_min_annulus(self):
annulus = Annulus(inner_radius=2.0, outer_radius=1.0)
result = self.raster_rdd.focal(operation=Operation.MIN, neighborhood=annulus)
self.assertEqual(result.to_numpy_rdd().first()[1].cells[0][0][0], -1)
def test_focal_min_int(self):
result = self.raster_rdd.focal(operation=Operation.MIN, neighborhood=Neighborhood.ANNULUS,
param_1=2, param_2=1)
self.assertEqual(result.to_numpy_rdd().first()[1].cells[0][0][0], -1)
def test_tobler(self):
result = self.raster_rdd.tobler()
if __name__ == "__main__":
unittest.main()
BaseTestClass.pysc.stop()
|
# Create your views here.
#from django import form
import urlparse
import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import Context, loader, RequestContext
from django.views.decorators.debug import sensitive_post_parameters
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.forms import AuthenticationForm
from django.shortcuts import redirect, render_to_response
from django.contrib.auth import logout
from django.views.decorators.http import require_POST
from django.contrib.auth import get_backends, REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout, authenticate as auth_authenticate
from django.contrib import messages
from django.contrib.auth.models import User, Group
from c2g.models import Course, Institution
from accounts.forms import *
from registration import signals
from django.core.validators import validate_email, RegexValidator
from django.core.exceptions import ValidationError, MultipleObjectsReturned
from django.http import HttpResponseBadRequest
from django.contrib.auth.decorators import permission_required
from django.db.models import Q
import random
import os
import string
import base64
def index(request):
return HttpResponse("Hello, world. You're at the user index.")
def profile(request):
group_list = request.user.groups.all()
courses = Course.objects.filter(Q(student_group_id__in=group_list, mode='ready') | Q(instructor_group_id__in=group_list, mode='ready') | Q(tas_group_id__in=group_list, mode='ready') | Q(readonly_tas_group_id__in=group_list, mode='ready'))
if request.user.is_authenticated():
user_profile = request.user.get_profile()
is_student_list = user_profile.is_student_list(group_list, courses)
else:
user_profile = None
is_student_list = []
has_webauth = False
if request.user.is_authenticated() and (request.user.get_profile().institutions.filter(title='Stanford').exists()):
has_webauth = True
return render_to_response('accounts/profile.html',
{'request': request,
'courses': courses,
'is_student_list': is_student_list,
'has_webauth': has_webauth,},
context_instance=RequestContext(request))
def edit(request):
uform = None
pform = None
if request.user.is_authenticated():
uform = EditUserForm(instance=request.user)
pform = EditProfileForm(instance=request.user.get_profile())
has_webauth = False
if request.user.is_authenticated() and (request.user.get_profile().institutions.filter(title='Stanford').exists()):
has_webauth = True
return render_to_response('accounts/edit.html', {'request':request, 'uform':uform, 'pform':pform, 'has_webauth': has_webauth,}, context_instance=RequestContext(request))
@csrf_protect
def save_edits(request):
uform = EditUserForm(request.POST, instance=request.user)
pform = EditProfileForm(request.POST, instance=request.user.get_profile())
if uform.is_valid() and pform.is_valid():
uform.save()
pform.save()
return HttpResponseRedirect(reverse('accounts.views.profile'))
return render_to_response('accounts/edit.html', {'request':request, 'uform':uform, 'pform':pform}, context_instance=RequestContext(request))
@csrf_protect
@require_POST
def save_piazza_opts(request):
email = request.POST.get('email')
name = request.POST.get('name')
str_id = request.POST.get('id')
try:
validate_email(email)
except ValidationError:
return HttpResponseBadRequest('You did not enter a valid email address.')
try:
nameValidator = RegexValidator(regex=r'^[\w -]+$')
nameValidator(name.strip())
except ValidationError:
return HttpResponseBadRequest('Names on Piazza should only contain letters, numbers, underscores, hyphens, and spaces.')
try:
int_id = int(str_id)
except ValueError:
return HttpResponseBadRequest('Not a integer id')
try:
user = User.objects.get(id=str_id)
except User.DoesNotExist:
return HttpResponseBadRequest('User not found')
profile=user.get_profile()
profile.piazza_name=name
profile.piazza_email=email
profile.save()
return HttpResponse("Successfully Saved Piazza Options")
def logout(request):
logout(request)
return redirect('c2g.views.home')
@sensitive_post_parameters()
@csrf_protect
@never_cache
def register(request, template_name='accounts/register.html'):
form=AuthenticationForm(request)
t=loader.get_template(template_name)
c=Context({
'test': 'test',
'form': form,
});
return HttpResponse(t.render(c))
def impersonate(request,username):
if not request.user.is_superuser:
return HttpResponse('Permission denied')
try:
u1 = User.objects.get(username=username)
u1.backend = 'django.contrib.auth.backends.ModelBackend'
except User.DoesNotExist:
return HttpResponse('User not found')
auth_logout(request)
auth_login(request,u1)
return HttpResponse('You are now logged in as ' + username)
@never_cache
def shib_login(request):
#check if there is valid remote user.
#if one exists, try to match them
#if one does not exist, create it and assign to proper institution
#then redirect
#setup the redirect first: code borrowed from django contrib library
redir_to = request.GET.get('next', '/accounts/profile')
netloc = urlparse.urlparse(redir_to)[1]
# Heavier security check -- don't allow redirection to a different
# host.
if netloc and netloc != request.get_host():
redir_to = '/accounts/profile'
#Use EduPersonPrincipalName http://www.incommonfederation.org/attributesummary.html#eduPersonPrincipal
#as username in our system. We could support other persistent identifiers later, but it will take some
#work
if ('REMOTE_USER' in request.META) and ('eppn' in request.META) and (request.META['REMOTE_USER']==request.META['eppn']) and request.META['eppn']:
#if we get here, the user has authenticated properly
shib = {'givenName':'',
'sn':'',
'mail':'',
'affiliation':'',
'Shib-Identity-Provider':'',}
shib.update(request.META)
#Clean up first name, last name, and email address
shib['sn'] = string.split(shib['sn'],";")[0]
shib['givenName'] = string.split(shib['givenName'],";")[0]
if not shib['mail']:
shib['mail'] = shib['eppn']
if not User.objects.filter(username=shib['REMOTE_USER']).exists():
#here, we need to create the new user
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
rg = random.SystemRandom(random.randint(0,100000))
password = (''.join(rg.choice(ALPHABET) for i in range(16))) + '1' #create a random password, which they will never use
User.objects.create_user(shib['REMOTE_USER'], shib['mail'], password)
# authenticate() always has to be called before login(), and
# will return the user we just created.
new_user = auth_authenticate(username=shib['REMOTE_USER'], password=password)
new_user.first_name, new_user.last_name = shib['givenName'].capitalize(), shib['sn'].capitalize()
new_user.save()
profile = new_user.get_profile()
profile.site_data = shib['affiliation']
if 'stanford.edu' in shib['affiliation']:
profile.institutions.add(Institution.objects.get(title='Stanford'))
profile.save()
auth_login(request, new_user)
signals.user_registered.send(sender=__file__,
user=new_user,
request=request)
else:
#User already exists, so log him/her in
user = User.objects.get(username=shib['REMOTE_USER'])
user.backend = 'django.contrib.auth.backends.ModelBackend'
auth_login(request, user)
messages.add_message(request,messages.SUCCESS, 'You have successfully logged in!')
else:
messages.add_message(request,messages.ERROR, 'WebAuth did not return your identity to us! Please try logging in again. If the problem continues please contact c2g-techsupport@class.stanford.edu')
return HttpResponseRedirect(redir_to)
|
#!/usr/bin/env python3
import pandas as pd
csvData = pd.read_csv("data/MOCK_DATA.csv")
#print(csvData)
print()
|
from django.urls import path
from . import views
app_name = 'afrivent'
urlpatterns = [
path('', views.home, name="home"),
path('all/events', views.all_events, name="all-events"),
path('event-order/details/<int:eventId>', views.event_order_details, name='event-order-details'),
path('edit/event/<event_slug>', views.eventUpdate, name='edit-event' ),
path('event/<slug>', views.EventDetailView, name='event-detail'),
path('profile/<pk>', views.userdashboard, name='user-profile'),
path('create/event', views.createEventForm, name='create-event'),
path('new/event/created', views.eventCreated, name='event-created'),
path('search', views.search, name='search'),
path('payout/<pk>', views.requestPayout, name='request-payout'),
path('generate-ticket/<pk>', views.generateTicket, name='generate-ticket')
]
|
#!/usr/bin/python3
def common_elements(set_1, set_2):
new_list = []
for i in set_2:
for b in set_1:
if (i == b):
new_list.append(i)
return new_list
|
import sys
import numpy as np
# r_tags={0,1,2,3,4,5,6,7,8,9,10,11,12}
# map_dict={'institution': 4, 'journal': 5, 'booktitle': 1, 'pages': 8, 'author': 0,
# 'note': 7, 'editor': 3, 'publisher': 9, 'location': 6, 'date': 2, 'tech':10, 'title':11, 'volume':12}
r_tags = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
map_dict = {'author': 0,
'booktitle': 1,
'year': 2,
'editor': 3,
'institution': 4,
'journal': 5,
'location': 6,
'note': 7,
'pages': 8,
'publisher': 9,
'title': 10,
'volume': 11,
'X': 12}
confusion = np.ndarray((len(r_tags),len(r_tags)),dtype=float)
#confusion.fill(0.00000000000001)
confusion.fill(1)
# print confusion
filename = '/Users/waingram/Projects/citation-parsing/grobid_analysis.txt'
k = open(filename, 'r')
for lines in k:
a=lines.strip().split()
#print a
if len(a)==0:
continue
confusion[map_dict[a[-2]]][map_dict[a[-1]]] = confusion[map_dict[a[-2]]][map_dict[a[-1]]]+1
tp = np.zeros(len(set(r_tags)))
fp = np.zeros(len(set(r_tags)))
fn = np.zeros(len(set(r_tags)))
f1 = np.zeros(len(set(r_tags)))
for j in xrange(len(set(r_tags))):
tp[j] = confusion[j][j]
fp[j] = np.sum(confusion, axis = 1)[j] - tp[j]
fn[j] = np.sum(confusion, axis = 0)[j] - tp[j]
f1[j] = float(2*tp[j])/float(2*tp[j] + fn[j] +fp[j])
print 'True Distribution'
print np.sum(confusion,axis=1)
print 'F1s'
print f1
print 'Print average'
print np.average(f1)
print confusion
|
import csv
import os
import math
import os.path
import ROOT
def formatUnc(unc):
return "{0:4.3f}".format(unc)
tableHeader=["","systematic"]
tableTotal=["","total uncertainty"]
tableRows=[
['stat', "statistical"],
["line"],
#fitting
['fiterror', "ML-fit uncertainty"],
['diboson', "Diboson fraction"],
['dyjets', "Drell-Yan fraction"],
['schan', "s-channel fraction"],
['twchan', "tW fraction"],
['qcd_antiiso', "QCD shape"],
['qcd_yield', "QCD yield"],
["line"],
#detector
['btag_bc', "b tagging"],
['btag_l', "mistagging"],
['jer', "JER"],
['jes', "JES"],
['met', "unclustered \\MET"],
['pu', "pileup"],
['lepton_id', "lepton ID"],
['lepton_iso', "lepton isolation"],
['lepton_trigger', "trigger efficiency"],
["line"],
#add reweighting
['top_weight', "top \\pT reweighting"],
['wjets_pt_weight', "\\wjets W \\pT reweighting"],
['wjets_flavour_heavy', "\\wjets heavy flavor fraction"],
['wjets_flavour_light', "\\wjets light flavor fraction"],
['wjets_shape', "\\wjets shape reweighting"],
#['bias', "unfolding bias"],
["line"],
#theory
['generator', "generator model"],
['mass', "top quark mass"],
#['tchan_scale', "$Q^{2}$ scale t-channel"],
['tchan_qscale_me_weight', "$Q^{2}$ scale t-channel"],
['ttjets_scale', "\\ttbar $Q^{2}$ scale"],
#['ttjets_qscale_me_weight', "\\ttbar $Q^{2}$ scale"],
['ttjets_matching', "\\ttbar matching"],
['wzjets_scale', "\\wjets $Q^{2}$ scale"],
#['wzjets_qscale_me_weight', "\\wjets $Q^{2}$ scale"],
['wzjets_matching', "\\wjets matching"],
['pdf', "PDF"],
["line"],
['mcstat', "limited MC"],
]
tmp=["nominal"]
for sys in tableRows:
if sys[0]=="line":
continue
tmp.append(sys[0])
sysNames=tmp
def addErrorMatrix(hist,error,scale=1.0):
for ibin in range(hist.GetNbinsX()):
hist.SetBinContent(ibin+1,hist.GetBinContent(ibin+1)+scale*math.sqrt(error.GetBinContent(ibin+1,ibin+1)))
def readHistograms(folder,sysNames,prefix="mu__"):
histDict={}
norm = None
for sys in sysNames:
if sys in ["nominal","stat","mcstat","fiterror"]:
fileName=os.path.join(folder,prefix+sys+".root")
if os.path.exists(fileName):
histDict[sys]={"isShape":False,"unfolded":{},"input":{}, "gen":{}}
rootFile=ROOT.TFile(fileName)
histDict[sys]["input"]["nominal"]=rootFile.Get("substractedData")
histDict[sys]["input"]["nominal"].SetDirectory(0)
histDict[sys]["unfolded"]["nominal"]=rootFile.Get("unfolded")
histDict[sys]["unfolded"]["nominal"].SetDirectory(0)
histDict[sys]["unfolded"]["error"]=rootFile.Get("error")
histDict[sys]["unfolded"]["error"].SetDirectory(0)
histDict[sys]["unfolded"]["up"]=histDict[sys]["unfolded"]["nominal"].Clone()
histDict[sys]["unfolded"]["up"].SetDirectory(0)
histDict[sys]["unfolded"]["down"]=histDict[sys]["unfolded"]["nominal"].Clone()
histDict[sys]["unfolded"]["down"].SetDirectory(0)
for ibin in range(histDict[sys]["unfolded"]["nominal"].GetNbinsX()):
histDict[sys]["unfolded"]["up"].SetBinContent(ibin+1,histDict[sys]["unfolded"]["nominal"].GetBinContent(ibin+1)+math.sqrt(histDict[sys]["unfolded"]["error"].GetBinContent(ibin+1,ibin+1)))
histDict[sys]["unfolded"]["down"].SetBinContent(ibin+1,histDict[sys]["unfolded"]["nominal"].GetBinContent(ibin+1)-math.sqrt(histDict[sys]["unfolded"]["error"].GetBinContent(ibin+1,ibin+1)))
if sys=="nominal":
norm=histDict["nominal"]["unfolded"]["nominal"].Integral()
histDict[sys]["unfolded"]["nominal"].Scale(3.0/norm)
histDict[sys]["unfolded"]["up"].Scale(3.0/norm)
histDict[sys]["unfolded"]["down"].Scale(3.0/norm)
histDict[sys]["unfolded"]["error"].Scale((3.0/norm)**2)
histDict[sys]["gen"]["nominal"]=rootFile.Get("gen")
histDict[sys]["gen"]["nominal"].SetDirectory(0)
histDict[sys]["gen"]["nominal"].Scale(3.0/histDict[sys]["gen"]["nominal"].Integral())
rootFile.Close()
elif sys == "generator":
fileName=os.path.join(folder,prefix+sys+".root")
if os.path.exists(fileName):
histDict[sys]={"isShape":True,"unfolded":{},"input":{}, "gen":{}}
rootFile=ROOT.TFile(fileName)
histDict[sys]["input"]["up"]=rootFile.Get("substractedData")
histDict[sys]["input"]["up"].SetDirectory(0)
histDict[sys]["unfolded"]["up"]=rootFile.Get("unfolded")
histDict[sys]["unfolded"]["up"].SetDirectory(0)
histDict[sys]["unfolded"]["up"].Scale(3.0/norm)
#symmetrize uncertainty
histDict[sys]["input"]["down"]=histDict[sys]["input"]["up"].Clone()
histDict[sys]["input"]["down"].SetDirectory(0)
histDict[sys]["input"]["down"].Scale(-1.0)
histDict[sys]["input"]["down"].Add(histDict["nominal"]["input"]["nominal"],2.0)
histDict[sys]["unfolded"]["down"]=histDict[sys]["unfolded"]["up"].Clone()
histDict[sys]["unfolded"]["down"].SetDirectory(0)
histDict[sys]["unfolded"]["down"].Scale(-1.0)
histDict[sys]["unfolded"]["down"].Add(histDict["nominal"]["unfolded"]["nominal"],2.0)
histDict[sys]["gen"]["nominal"]=rootFile.Get("gen")
histDict[sys]["gen"]["nominal"].SetDirectory(0)
rootFile.Close()
else:
upFileName=os.path.join(folder,prefix+sys+"__up.root")
downFileName=os.path.join(folder,prefix+sys+"__down.root")
if os.path.exists(upFileName) and os.path.exists(downFileName):
histDict[sys]={"isShape":True,"unfolded":{},"input":{}, "gen":{}}
rootFile=ROOT.TFile(upFileName)
histDict[sys]["input"]["up"]=rootFile.Get("substractedData")
histDict[sys]["input"]["up"].SetDirectory(0)
histDict[sys]["unfolded"]["up"]=rootFile.Get("unfolded")
histDict[sys]["unfolded"]["up"].SetDirectory(0)
histDict[sys]["unfolded"]["up"].Scale(3.0/norm)
histDict[sys]["gen"]["up"]=rootFile.Get("gen")
histDict[sys]["gen"]["up"].SetDirectory(0)
histDict[sys]["gen"]["up"].Scale(3.0/histDict[sys]["gen"]["up"].Integral())
rootFile.Close()
rootFile=ROOT.TFile(downFileName)
histDict[sys]["input"]["down"]=rootFile.Get("substractedData")
histDict[sys]["input"]["down"].SetDirectory(0)
histDict[sys]["unfolded"]["down"]=rootFile.Get("unfolded")
histDict[sys]["unfolded"]["down"].SetDirectory(0)
histDict[sys]["unfolded"]["down"].Scale(3.0/norm)
histDict[sys]["gen"]["down"]=rootFile.Get("gen")
histDict[sys]["gen"]["down"].SetDirectory(0)
histDict[sys]["gen"]["down"].Scale(3.0/histDict[sys]["gen"]["down"].Integral())
rootFile.Close()
return histDict
folderTUnfold=os.path.join(os.getcwd(),"histos","bdt_Jun22_final_antitop","tunfold","0.45")
sysDict = readHistograms(folderTUnfold,sysNames)
nominalHist=sysDict["nominal"]["unfolded"]["nominal"]
def addColumn(sysDict):
for ibin in range(6):
tableHeader.append("bin "+str(ibin+1))
totalSum2=0.0
for row in range(len(tableRows)):
if tableRows[row][0]=="line":
continue
sysName=tableRows[row][0]
valueNominal = nominalHist.GetBinContent(ibin+1)
valueUp = sysDict[sysName]["unfolded"]["up"].GetBinContent(ibin+1)
valueDown = sysDict[sysName]["unfolded"]["down"].GetBinContent(ibin+1)
value = max(math.fabs(valueUp-valueNominal),math.fabs(valueDown-valueNominal))
totalSum2+=value**2
if value*1000.0<0.5:
#tableRows[row].append("$<10^{-3}$")
tableRows[row].append("$<0.1$")
else: #math.fabs(sysDict[sysName]["dup"]+sysDict[sysName]["ddown"])<0.01:
tableRows[row].append("$%4.1f$" % (value*1000.0))
'''
else:
tableRows[row].append("${}^{%+4.3f}_{%+4.3f}$" % (sysDict[sysName]["dup"],sysDict[sysName]["ddown"] ))
'''
tableTotal.append("$%4.1f$" % (math.sqrt(totalSum2)*1000.0))
addColumn(sysDict)
#addColumn("electron",readCSV("histos/scan/2bin/0.45","ele_"))
#addColumn("combined",readCSV("histos/scan/2bin/0.45","combined_"))
outFile = open("table.tex","w")
outFile.write("\\begin{tabular}[htc]{|r || r | r | r | r | r | r |}\n")
outFile.write("\\hline \n")
outFile.write("\\parbox[t][][c]{2.3cm}{\\centering "+tableHeader[1]+"} & ")
for h in tableHeader[2:-1]:
outFile.write("\\parbox[t][][c]{2.3cm}{\\centering $\\delta\\big[$"+h+"$\\big]\\cdot 10^{3}$} & ")
outFile.write("\\parbox[t][][c]{2.3cm}{\\centering $\\delta\\big[$"+tableHeader[-1]+"$\\big]\\cdot 10^{3}$} \\\\[0.5cm] \n")
outFile.write("\\hline \n")
outFile.write("\\hline \n")
for row in range(len(tableRows)):
if tableRows[row][0]=="line":
outFile.write("\\hline\n")
continue
formattedRow=""
for i in range(1,len(tableRows[row])-1):
formattedRow+=tableRows[row][i]+ " \\hspace{0.1cm} & " #.replace(".","$&$")
formattedRow+=tableRows[row][-1]+ " \\hspace{0.1cm} "
formattedRow+=" \\\\ "#\\hline"
outFile.write(formattedRow+"\n")
outFile.write("\\hline \n")
outFile.write("\\hline \n")
formattedRow=""
for i in range(1,len(tableTotal)-1):
formattedRow+=tableTotal[i] + " \\hspace{0.1cm} & "#.replace(".","$&$")
formattedRow+=tableTotal[-1]+ " \\hspace{0.1cm} "
formattedRow+=" \\\\ "
outFile.write(formattedRow+"\n")
outFile.write("\\hline \n")
outFile.write("\\end{tabular}\n")
outFile.close()
|
# -*- coding: utf-8 -*-
__author__ = 'Yuvv'
import functools
from predictor.models import Rule, Knowledge
def valid_rule_filter_fixed(rule, knowledge):
rule.cf_e = 0
if rule.relationship == '&':
for rkf in rule.related_knowledge_factor.all():
if rkf.mark.mark not in knowledge:
return False
else:
for rkw in rule.related_knowledge_weight.all():
if rkf.mark.mark == rkw.mark.mark:
rule.cf_e += rkf.factor * rkw.weight
break
elif rule.relationship == '|':
flag = True
for rkf in rule.related_knowledge_factor.all():
if rkf.mark.mark in knowledge:
rule.cf_e = max(map(lambda x: x.factor, rule.related_knowledge_factor.all()))
flag = False
break
if flag:
return False
elif rule.relationship == '-':
cdt = rule.related_knowledge_factor.all()[0]
if cdt.mark.mark in knowledge:
rule.cf_e = cdt.factor
else:
return False
else:
pass
if rule.cf_e < rule.certainty_range:
return False
return True
def conflict_rule_filter(rules, knowledge):
r_single = []
r_or = []
r_and = []
for rule in rules:
if rule.relationship == '&':
r_and.append(rule)
elif rule.relationship == '|':
r_or.append(rule)
elif rule.relationship == '-':
r_single.append(rule)
else:
pass
# single vs or
i = 0
while i < len(r_single):
rs_mark = r_single[i].related_knowledge_factor.all()[0].mark.mark
j = 0
while j < len(r_or):
ro_marks_on = filter(
lambda mo: True if mo in knowledge else False,
map(lambda rkf: rkf.mark.mark, r_or[j].related_knowledge_factor.all())
)
if rs_mark in ro_marks_on:
if r_single[i].cf_e < r_or[j].cf_e:
r_single.remove(r_single[i])
i -= 1
break
else:
r_or.remove(r_or[j])
j -= 1
j += 1
i += 1
# single vs and
i = 0
while i < len(r_single):
rs_mark = r_single[i].related_knowledge_factor.all()[0].mark.mark
j = 0
while j < len(r_and):
for ra_rkf in r_and[j].related_knowledge_factor.all():
if ra_rkf.mark.mark == rs_mark:
if r_single[i].cf_e < r_and[j].cf_e:
r_single.remove(r_single[i])
i -= 1
break
else:
r_and.remove(r_and[j])
j -= 1
break
j += 1
i += 1
# or vs and
i = 0
while i < len(r_or):
ro_marks_on = filter(
lambda mo: True if mo in knowledge else False,
map(lambda rkf: rkf.mark.mark, r_or[i].related_knowledge_factor.all())
)
j = 0
while j < len(r_and):
for ra_mark in map(lambda y: y.mark.mark, r_and[j].related_knowledge_factor.all()):
if ra_mark in ro_marks_on:
if r_and[j].cf_e < r_or[i].cf_e:
r_and.remove(r_and[j])
j -= 1
else:
r_or.remove(r_or[i])
i -= 1
break
j += 1
i += 1
r_and.extend(r_or)
r_and.extend(r_single)
return r_and
def rule_reduce(a, b):
if a >= 0 and b >= 0:
return a + b - a * b
elif a <= 0 and b <= 0:
return a + b + a * b
else:
return (a + b) / (1 - min(abs(a), abs(b)))
def collect_knowledge(temp, humi, visi, speed):
knowledge = set()
for k in Knowledge.objects.all():
if k.category.name == 'temperature':
if k.max_value >= temp >= k.min_value:
knowledge.add(k.mark)
elif k.category.name == 'humidity':
if k.max_value >= humi >= k.min_value:
knowledge.add(k.mark)
elif k.category.name == 'visibility':
if k.max_value >= visi >= k.min_value:
knowledge.add(k.mark)
elif k.category.name == 'wind speed':
if k.max_value >= speed >= k.min_value:
knowledge.add(k.mark)
else:
pass
return knowledge
def infer_v2(target, temp=0, humi=0, visi=0, speed=0):
target_mark = Knowledge.objects.get(detail=target)
rules = Rule.objects.filter(expression__endswith=target_mark)
knowledge = collect_knowledge(temp, humi, visi, speed)
try:
rules = filter(lambda x: valid_rule_filter_fixed(x, knowledge), rules)
# rules = conflict_rule_filter(rules, knowledge)
cf_hs = map(lambda rule: rule.certainty_factor * max(0, rule.cf_e), rules)
result = functools.reduce(rule_reduce, cf_hs)
except TypeError:
result = 'cannot calculate!'
pass
return result
|
import os
import signal
from string import Template
import subprocess
import time
from TdcPlugin import TdcPlugin
from tdc_config import *
class SubPlugin(TdcPlugin):
def __init__(self):
self.sub_class = 'ns/SubPlugin'
super().__init__()
def pre_suite(self, testcount, testidlist):
'''run commands before test_runner goes into a test loop'''
super().pre_suite(testcount, testidlist)
if self.args.namespace:
self._ns_create()
else:
self._ports_create()
def post_suite(self, index):
'''run commands after test_runner goes into a test loop'''
super().post_suite(index)
if self.args.verbose:
print('{}.post_suite'.format(self.sub_class))
if self.args.namespace:
self._ns_destroy()
else:
self._ports_destroy()
def add_args(self, parser):
super().add_args(parser)
self.argparser_group = self.argparser.add_argument_group(
'netns',
'options for nsPlugin(run commands in net namespace)')
self.argparser_group.add_argument(
'-N', '--no-namespace', action='store_false', default=True,
dest='namespace', help='Don\'t run commands in namespace')
return self.argparser
def adjust_command(self, stage, command):
super().adjust_command(stage, command)
cmdform = 'list'
cmdlist = list()
if not self.args.namespace:
return command
if self.args.verbose:
print('{}.adjust_command'.format(self.sub_class))
if not isinstance(command, list):
cmdform = 'str'
cmdlist = command.split()
else:
cmdlist = command
if stage == 'setup' or stage == 'execute' or stage == 'verify' or stage == 'teardown':
if self.args.verbose:
print('adjust_command: stage is {}; inserting netns stuff in command [{}] list [{}]'.format(stage, command, cmdlist))
cmdlist.insert(0, self.args.NAMES['NS'])
cmdlist.insert(0, 'exec')
cmdlist.insert(0, 'netns')
cmdlist.insert(0, self.args.NAMES['IP'])
else:
pass
if cmdform == 'str':
command = ' '.join(cmdlist)
else:
command = cmdlist
if self.args.verbose:
print('adjust_command: return command [{}]'.format(command))
return command
def _ports_create(self):
cmd = '$IP link add $DEV0 type veth peer name $DEV1'
self._exec_cmd('pre', cmd)
cmd = '$IP link set $DEV0 up'
self._exec_cmd('pre', cmd)
if not self.args.namespace:
cmd = '$IP link set $DEV1 up'
self._exec_cmd('pre', cmd)
def _ports_destroy(self):
cmd = '$IP link del $DEV0'
self._exec_cmd('post', cmd)
def _ns_create(self):
'''
Create the network namespace in which the tests will be run and set up
the required network devices for it.
'''
self._ports_create()
if self.args.namespace:
cmd = '$IP netns add {}'.format(self.args.NAMES['NS'])
self._exec_cmd('pre', cmd)
cmd = '$IP link set $DEV1 netns {}'.format(self.args.NAMES['NS'])
self._exec_cmd('pre', cmd)
cmd = '$IP -n {} link set $DEV1 up'.format(self.args.NAMES['NS'])
self._exec_cmd('pre', cmd)
if self.args.device:
cmd = '$IP link set $DEV2 netns {}'.format(self.args.NAMES['NS'])
self._exec_cmd('pre', cmd)
cmd = '$IP -n {} link set $DEV2 up'.format(self.args.NAMES['NS'])
self._exec_cmd('pre', cmd)
def _ns_destroy(self):
'''
Destroy the network namespace for testing (and any associated network
devices as well)
'''
if self.args.namespace:
cmd = '$IP netns delete {}'.format(self.args.NAMES['NS'])
self._exec_cmd('post', cmd)
def _exec_cmd(self, stage, command):
'''
Perform any required modifications on an executable command, then run
it in a subprocess and return the results.
'''
if '$' in command:
command = self._replace_keywords(command)
self.adjust_command(stage, command)
if self.args.verbose:
print('_exec_cmd: command "{}"'.format(command))
proc = subprocess.Popen(command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=ENVIR)
(rawout, serr) = proc.communicate()
if proc.returncode != 0 and len(serr) > 0:
foutput = serr.decode("utf-8")
else:
foutput = rawout.decode("utf-8")
proc.stdout.close()
proc.stderr.close()
return proc, foutput
def _replace_keywords(self, cmd):
"""
For a given executable command, substitute any known
variables contained within NAMES with the correct values
"""
tcmd = Template(cmd)
subcmd = tcmd.safe_substitute(self.args.NAMES)
return subcmd
|
#!/usr/bin/env python
# Copyright (c) 2011, 2012 Nicira, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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 paramiko
import ovn_utils as utils
import ovn_lswitch as lswitch
def create_host(host, ip, mac, gw, ip4):
ns = host
if utils.create_net_namespace(ns) == False:
return None
lpeer, rpeer = utils.create_veth_peer(ns)
if lpeer == None or rpeer == None:
utils.destroy_net_namespace(ns)
return None
utils.add_veth_to_ns(lpeer, ns)
if ip4:
utils.config_netdev_ns(ns, lpeer, ip, gw, mac)
else:
utils.config_netdev_ns_ipv6(ns, lpeer, ip, gw, mac)
# enable the net device
utils.enable_veth_peer(rpeer)
return rpeer
def destroy_host(host):
if utils.destroy_veth_peer(host) == False:
return False
if utils.destroy_net_namespace(host) == False:
return False
return True
def add_host_to_lswitch(ips, ls = None, host = None, ip = None, mac = None, gw = None, ipv4 = True):
if ls is None or host is None or ip is None or gw is None:
return False
if lswitch.ovn_nbctl_is_lswitch(ips, ls) == False:
print 'ERROR, %s switch does not exist in NB' % ls
return False
# prepare the lswitch port
lport = host
if mac is None or mac == '':
mac = utils.gen_random_mac()
if lswitch.ovn_nbctl_add_lswitch_port(ips, ls, lport, mac) == False:
print 'ERROR, when add %s lport to lswitch %s' % (lport, ls)
return False
# create the ns and veth
dev = create_host(host, ip, mac, gw, ipv4)
if dev:
# mapping the veth to lport
lswitch.mapping_netdev_to_lport(dev, lport)
return True
else:
# can not create the host
lswitch.ovn_nbctl_del_lswitch_port(ips, lport)
return False
def remove_host_from_lswitch(ips, ls = None, host = None):
if ls is None or host is None:
return False
if lswitch.ovn_nbctl_is_lswitch(ips, ls) == False:
print 'ERROR, %s switch does not exist in NB' % ls
return False
lport = host
if lswitch.ovn_nbctl_del_lswitch_port(ips, lport) == False:
print 'ERROR, when del %s lport to lswitch %s' % (lport, ls)
return False
# remove the netdev to lswitch
destroy_host(host)
lswitch.unmapping_netdev(lport + '-r')
return True
def show_host_netdev(hostname):
print utils.show_netdev_from_net_namespace(hostname)
def show_host_routeinfo(hostname):
print utils.show_routeinfo_from_net_namespace(hostname)
def ping_host(hostname, ip, count = 1):
print utils.ping_from_net_namespace(hostname, ip, count)
|
# -*- coding: utf-8 -*-
import nysol._nysolshell_core as n_core
from nysol.mcmd.nysollib.core import NysolMOD_CORE
from nysol.mcmd.nysollib import nysolutil as nutil
class Nysol_Mnewnumber(NysolMOD_CORE):
_kwd ,_inkwd,_outkwd = n_core.getparalist("mnewnumber",3)
def __init__(self,*args, **kw_args) :
super(Nysol_Mnewnumber,self).__init__("mnewnumber",nutil.args2dict(args,kw_args,Nysol_Mnewnumber._kwd))
|
import random
import socket
import sys
import tqdm
import os
import numpy as np
PRIME_LIMIT = 1000000000
# Check if number is prime
def is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num ** 0.5) + 2, 2):
if num % n == 0:
return False
return True
# Return primer number
def get_prime(limit = PRIME_LIMIT):
num = 0
while True:
num = random.randint(0,limit)
if is_prime(num):
break
return num
# Calculate the greatest common divisor between two numbers
def greatest_common_divisor(a, b):
while b != 0:
a, b = b, a % b
return a
# Calculate modular multiplicative inverse
def modular_multiplicative_inverse(e, phi):
if e == 0:
return (phi, 0, 1)
else:
g, y, x = modular_multiplicative_inverse(phi % e, e)
return (g, x - (phi // e) * y, y)
# Public and Private Key generation
def generate_keys(p, q):
if not (is_prime(p) and is_prime(q)):
raise ValueError('Ambos numeros deben ser primos')
elif p == q:
raise ValueError('Ambos numeros deben ser distintos')
# Compute n
n = p * q
# Compute phi
phi = (p - 1) * (q - 1)
# Calculate encryption key
e = random.randrange(1, phi) # Choose an integer number
g = greatest_common_divisor(e, phi) # Calculate greatest common divisor
while g != 1: # Calculate until find coprime numbers
e = random.randrange(1, phi) # Choose an integer number
g = greatest_common_divisor(e, phi) # Calculate greatest common divisor
# Calculate decryption key
d = modular_multiplicative_inverse(e, phi)[1]
d = d % phi
if d < 0:
d += phi
# Return public key (e), private key (d) and n
return (e, d, n)
# Desencripta los hashes RSA
def decrypt(private_key, n, cipher_text):
# print('params', private_key, type(private_key), n, type(n), cipher_text, type(cipher_text))
try:
#password = [chr((int(char) ** int(private_key)) % n) for char in cipher_text]
password = [chr(pow(ord(char), private_key, n)) for char in cipher_text]
# print('PASS', password)
return ''.join(password)
except TypeError as e:
pass
# Procesa el recibir el archivo con las contrasenas cifradas
def receive_file(connection):
print('=== Recibiendo arvchivo ===')
received = connection.recv(4096).decode()
filesize, filename = received.split(':')
# Elimina la path absoluta (siesque esta)
filename = os.path.basename(filename)
# Convierte el tamano del archivo a entero
filesize = int(filesize)
# Actualiza el nombre del archivo para diferenciarlo del archivo enviado por el cliente
filename = 'server-' + filename
# Comienza a recibir el archivo
progress = tqdm.tqdm(range(filesize), f'Receiving {filename}', unit='B', unit_scale=True, unit_divisor=1024 )
with open(filename, 'wb') as file:
for _ in progress:
# Lee 1024 bytes desde el socket
bytes_read = connection.recv(4096)
if not bytes_read:
# Nada es recibido
break
# Escribe al archivo los bytes recibidos
file.write(bytes_read)
# Actualiza la barra de progreso
progress.update(len(bytes_read))
print('=== Finaliza de recibir archivo ===')
return filename
# Desencripta los hash de RSA a bcrypt
def decrypt_file(private_key, n, filename):
print('=== Desencriptar archivo ===')
file = open(filename, 'r')
for rsa_password in file:
bcrypt_password = decrypt(private_key, n, rsa_password)
print('=== Finaliza desencriptado ===')
# Guarda los bcrypt en un archivo sqlite
def save_to_sqlite():
pass
# Create TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10009)
print('Server started on {} port {}'.format(*server_address))
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
BUFFER_SIZE = 1024
while True:
print('Waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
p,q = get_prime(), get_prime()
while p == q:
q = get_prime()
# Receive the request and send the keys
while True:
request = connection.recv(BUFFER_SIZE)
print('request: ', request)
if request.decode('utf-8') == 'REQUEST_PUBLIC_KEY':
public_key, private_key, n = generate_keys(p, q)
print ('Public key: ', public_key)
print ('Private key: ', private_key)
print ('n: ', n)
public_key = str(public_key) + ':' + str(n)
package = str(sys.getsizeof(public_key)) + ':' + str(public_key)
connection.sendall(bytes(package.encode('utf-8')))
filename = receive_file(connection)
decrypt_file(str(private_key), n, filename)
save_to_sqlite()
else:
print('no data required')
break
finally:
# Clean up the connection
connection.close()
|
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import Twist
def position_command_talker():
pub = rospy.Publisher('/drone_1/cmd_vel', Twist, queue_size=100)
#pub_2 = rospy.Publisher('/drone_2/command/pose', PoseStamped, queue_size=100)
rospy.init_node('velocity_command_talker', anonymous=True)
rate = rospy.Rate(10)
count = 0
while not rospy.is_shutdown():
# Conmmand to drone_1
velocity_command = Twist()
velocity_command.linear.x = 0
velocity_command.linear.y = 0
velocity_command.linear.z = 0.5
if count > 5:
if count % 2 != 0:
velocity_command.linear.z = 0.5
else:
velocity_command.linear.z = -0.5
count = count + 1
#velocity_command.header.frame_id = "drone_1/world"
pub.publish(velocity_command)
rate.sleep()
if __name__ == '__main__':
try:
position_command_talker()
except rospy.ROSInterruptException:
pass
|
#!/usr/bin/python3
MyInt = __import__('100-my_int').MyInt
my_i = MyInt(3)
print(my_i)
print(my_i == 3)
print(my_i != 3)
|
#箐优网APP签到脚本
import requests
import json
#sever酱SCkey
SCkey = '***********'
Cookie = '*************************'
##################################################以下内容请勿修改###############################################
def start():
headers={
'version': '139',
'authorization': 'Token 9F5BBF8F752F060B00D38F7C81686852695A463CD5661FE0848CBEADB3ACFD5E25FB42EF1D4D08242D7CBEFE5DE9358F8FF34CE90E2404ED1810F66F464007F19BF66EDD2BB06B3A7651C2D453332F0C2EE87E2810C5850A71E6CA0758650940332187A92844AFB9AE1528B9986BAA02F2DC61A3F0878B9CECD2FFB4599B19EE41E8572D6FB5569B8D535EA8F8B2D3BB5C67941B071C72BF703EA8BBF56AF087',
'deviceid': '99001301564902',
'package': 'jyeoo.app.ystudy',
'imei': '99001301564902',
'platformname': 'AndroidPhone',
'versionname': 'ystudy3.7.9',
'mac': '02:00:00:00:00:00',
'platform': '2',
'fingerprint': 'Xiaomi/raphael/raphael:9/PKQ1.181121.001/V10.3.7.0.PFKCNXM:user/release-keys',
'content-length': '0',
'user-agent': 'Apache-HttpClient/UNAVAILABLE (java 1.4)',
'mato-app-id': 'jyeoo.app.ystudy',
'x-maa-pic-param': '01246400',
'x-maa-auth': '783958689_1577699365_9a313da9f7ef0873c3fca50bb9aee03d',
'x-remove-iphost': '0',
'x-maa-alias': '.wifi.maa.f924b2d.maasdk.com',
'mato-net': 'CM,WIFI',
'mato-version': '7.8.0.12.0,2',
'x-maa-display-id': '3939303031333031353634393032',
'accept-encoding': 'gzip, deflate,wzip',
'x-maa-mark': '6c47e4cd98359d2bd88a43280c1d2f7b',
'cookie': 'jyean=tlnG9NAWoPhxyuoE72RMusIJbvmmqzri_GbBvxk9ETbClGscbBtN4CmTvKOaiyqIwmQKzn-e76QltM6cWikH6cywYPZmxVkDyg5_-RYvkUlQ0qvHwlJ_IxE0oG-MVAcd0',
'Cookie': Cookie ,
}
url="http://api.jyeoo.com/AppTag/UserSign"
# session = requests.Session()
# session.trust_env = False # No proxy settings from the OS
# r = session.post(url=url,headers=headers, verify=True)
c=requests.post(url=url,headers=headers)
d=json.loads(c.text)
e = d['Msg']
def pdj():
if e == '' :
return '签到成功'
else:
return e
f = str(pdj())
requests.get('https://sc.ftqq.com/'+ SCkey +'.send?text=' + '箐优自动签到:' + f + '&desp=' + '箐优网APP自动签到已执行')
print('箐优网APP签到已完成',f)
def main_handler(event, context):
return start()
if __name__ == '__main__':
start()
|
ans = [0]
for x in range(1,10):
for y in range(1,x+1):
print(y,end='')
print("\n")
|
#!/etc/anaconda3/bin/python
import tensorflow as tf
import os
import numpy as np
from attr import Attr
# Setup the configuration for GPU
#os.environ['CUDA_VISIBLE_DEVICES'] = '0'
#config = tf.ConfigProto()
#config.gpu_options.per_process_gpu_memory_fraction = 0.19
#session = tf.Session(config=config)
def next_batch(num, data, labels):
idx = np.arange(0, len(data))
np.random.shuffle(idx)
idx = idx[:num]
data_shuffle = [data[i] for i in idx]
labels_shuffle = [labels[i] for i in idx]
return np.asarray(data_shuffle), np.asarray(labels_shuffle)
def build_CNN_classifier(x):
x_image = x
W_conv1 = tf.Variable(tf.truncated_normal(shape=[5,5,3,1], stddev=5e-2))
b_conv1 = tf.Variable(tf.constant(0.1, shape=[1]))
h_conv1 = tf.nn.relu(tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], padding='SAME') + b_conv1)
W_fc1 = tf.Variable(tf.truncated_normal(shape=[200 * 300 * 1, 1000], stddev=5e-2))
b_fc1 = tf.Variable(tf.constant(0.1, shape=[1000]))
h_conv1_flat = tf.reshape(h_conv1, [-1, 200 * 300 * 1])
h_fc1 = tf.nn.relu(tf.matmul(h_conv1_flat, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = tf.Variable(tf.truncated_normal(shape=[1000, 1000], stddev=5e-2))
b_fc2 = tf.Variable(tf.constant(0.1, shape=[1000]))
logits = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
y_pred = tf.nn.softmax(logits)
return y_pred, logits
x = tf.placeholder(tf.float32, shape=[None, 200, 300, 3])
y = tf.placeholder(tf.float32, shape=[None, 1000])
keep_prob = tf.placeholder(tf.float32)
#pre.dataset = pre.dataset.batch(128)
#iterator = pre.dataset.make_one_shot_iterator()
#x_train, y_train = iterator.get_next()
with tf.Session() as sess:
tmp = Attr()
tmp.parsing()
x_train = list()
y_train = tmp.file_attr
for item in tmp.file_name:
with tf.gfile.FastGFile(item, 'rb') as f:
image_data = f.read()
decoded_image = tf.image.decode_jpeg(image_data, channels=3)
resized_image = tf.image.resize_images(decoded_image, [200,300])
image = sess.run(resized_image)
x_train.append(image)
y_pred, logits = build_CNN_classifier(x)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=logits))
train_step = tf.train.AdamOptimizer(1e-3).minimize(loss)
correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(10):
batch = next_batch(128, x_train, y_train)
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y: batch[1], keep_prob: 1.0})
loss_print = loss.eval(feed_dict={x: batch[0], y: batch[1], keep_prob: 1.0})
print("epoch: %d, training data accuracy: %f, loss: %f" % (i, train_accuracy, loss_print))
sess.run(train_step, feed_dict={x: batch[0], y: batch[1], keep_prob: 0.8})
|
s='aaabbaa'
s.replace('a','z')
|
"""Drop SurveyAnswer flag Column
Revision ID: eb83b734b11d
Revises: f6f2d282fd3f
Create Date: 2018-12-09 10:53:38.674905
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'eb83b734b11d'
down_revision = 'f6f2d282fd3f'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('survey_answer', 'flag')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('survey_answer', sa.Column('flag', mysql.TINYINT(display_width=1), server_default=sa.text("'0'"), autoincrement=False, nullable=True))
# ### end Alembic commands ###
|
#!/usr/bin/env python
from lib.command.remove_command import RemoveCommand
if __name__ == '__main__':
command = RemoveCommand()
command.run()
|
#导入外部函数库
from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup
import urllib.request
import os
#导入自建函数库
from make_pic2pdf import conpdf
#定义要处理网页、浏览器位置、存储路径
url = 'https://wenku.baidu.com/view/6e329617580102020740be1e650e52ea5418ce76.html?sxts=1537239654915'
chrome_path = 'E:\汪圣利\python\chromedriver.exe'
path = 'E:\\汪圣利\\python\\'
#打开浏览器,浏览网页
options = webdriver.ChromeOptions()
options.add_argument('user-agent="Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19"')
driver = webdriver.Chrome(executable_path=chrome_path ,options=options )
driver.get(url)
sleep(5)
#读取网页
html = driver.page_source
bf = BeautifulSoup(html,'lxml')
#建存储网页的目录
path = path+bf.title.string+'\\'
isExists=os.path.exists(path)
if not isExists:
os.makedirs(path)
print('make %s successfully !'%path)
else:
print('%s already exists'%path)
#把PPT图片存储到指定目录下
result = bf.find_all('div',class_='ppt-image-wrap')
x=1
for each_result in result:
bf_tmp = BeautifulSoup(str(each_result),'html.parser')
image = bf_tmp.find_all('img')
for each_image in image:
print(x)
try:
urllib.request.urlretrieve(each_image['src'], path+'%s.jpg'%(x))
except:
urllib.request.urlretrieve(each_image['data-src'], path+'%s.jpg'%(x))
x=x+1
#从图片创建成PDF文件,便于浏览和存储
conpdf(path+bf.title.string+'.pdf',path,'.jpg')
|
import sys, os
sys.path.append(os.path.abspath('C:/Users/Maciek/Desktop/stepik/lab1/zad3/src/App.py'))
import unittest
from src import App
song = App.song
class SongTest(unittest.TestCase):
def test_one_verse_first(self):
self.assertEqual(song.sing(2), "On the second day of Christmas my true love gave to me: two Turtle Doves, "
"and a Partridge in a Pear Tree.")
def test_one_verse_zero(self):
self.assertEqual(song.sing(1), "On the first day of Christmas my true love gave to me: a Partridge in a Pear "
"Tree.")
def test_one_verse_second(self):
self.assertEqual(song.sing(3), "On the third day of Christmas my true love gave to me: three French Hens, "
"two Turtle Doves, and a Partridge in a Pear Tree.")
def test_one_verse_third(self):
self.assertEqual(song.sing(4), "On the fourth day of Christmas my true love gave to me: four Calling Birds, "
"three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.")
def test_one_verse_fourth(self):
self.assertEqual(song.sing(5), "On the fifth day of Christmas my true love gave to me: five Gold Rings, "
"four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a"
" Pear Tree.")
def test_one_verse_fifth(self):
self.assertEqual(song.sing(6), "On the sixth day of Christmas my true love gave to me: six Geese-a-Laying, "
"five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, "
"and a Partridge in a Pear Tree.")
def test_one_verse_sixth(self):
self.assertEqual(song.sing(7), "On the seventh day of Christmas my true love gave to me: seven "
"Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, "
"three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.")
def test_one_verse_seventh(self):
self.assertEqual(song.sing(8), "On the eighth day of Christmas my true love gave to me: eight "
"Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, "
"four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a "
"Pear Tree.")
def test_one_verse_eighth(self):
self.assertEqual(song.sing(9), "On the ninth day of Christmas my true love gave to me: nine Ladies Dancing, "
"eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, "
"five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, "
"and a Partridge in a Pear Tree.")
def test_one_verse_ninth(self):
self.assertEqual(song.sing(10), "On the tenth day of Christmas my true love gave to me: ten Lords-a-Leaping, "
"nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, "
"six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, "
"two Turtle Doves, and a Partridge in a Pear Tree.")
def test_one_verse_tenth(self):
self.assertEqual(song.sing(11), "On the eleventh day of Christmas my true love gave to me: eleven Pipers "
"Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, "
"seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling "
"Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.")
def test_one_verse_eleventh(self):
self.assertEqual(song.sing(12), "On the twelfth day of Christmas my true love gave to me: twelve Drummers "
"Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, "
"eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, "
"five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, "
"and a Partridge in a Pear Tree.")
def test_verses_1_3(self):
self.assertEqual(song.sing(1, 3), "On the first day of Christmas my true love gave to me: a Partridge in a "
"Pear Tree.\n\nOn the second day of Christmas my true love gave to me: two "
"Turtle Doves, and a Partridge in a Pear Tree.\n\nOn the third day of "
"Christmas my true love gave to me: three French Hens, two Turtle Doves, "
"and a Partridge in a Pear Tree.")
def test_whole_song(self):
self.assertEqual(song.sing(1, 12), "On the first day of Christmas my true love gave to me: a Partridge in a "
"Pear Tree.\n\nOn the second day of Christmas my true love gave to me: two "
"Turtle Doves, and a Partridge in a Pear Tree.\n\nOn the third day of "
"Christmas my true love gave to me: three French Hens, two Turtle Doves, "
"and a Partridge in a Pear Tree.\n\nOn the fourth day of Christmas my true "
"love gave to me: four Calling Birds, three French Hens, two Turtle Doves, "
"and a Partridge in a Pear Tree.\n\nOn the fifth day of Christmas my true "
"love gave to me: five Gold Rings, four Calling Birds, three French Hens, "
"two Turtle Doves, and a Partridge in a Pear Tree.\n\nOn the sixth day of "
"Christmas my true love gave to me: six Geese-a-Laying, five Gold Rings, "
"four Calling Birds, three French Hens, two Turtle Doves, and a Partridge "
"in a Pear Tree.\n\nOn the seventh day of Christmas my true love gave to "
"me: seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, "
"four Calling Birds, three French Hens, two Turtle Doves, and a Partridge "
"in a Pear Tree.\n\nOn the eighth day of Christmas my true love gave to "
"me: eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, "
"five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, "
"and a Partridge in a Pear Tree.\n\nOn the ninth day of Christmas my true "
"love gave to me: nine Ladies Dancing, eight Maids-a-Milking, "
"seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling "
"Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear "
"Tree.\n\nOn the tenth day of Christmas my true love gave to me: ten "
"Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, "
"seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling "
"Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear "
"Tree.\n\nOn the eleventh day of Christmas my true love gave to me: eleven "
"Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, "
"eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, "
"five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, "
"and a Partridge in a Pear Tree.\n\nOn the twelfth day of Christmas my "
"true love gave to me: twelve Drummers Drumming, eleven Pipers Piping, "
"ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, "
"seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling "
"Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear "
"Tree.")
def test_disallow_negative_first(self):
with self.assertRaisesWithMessage(ValueError):
song.sing(-1, 2)
def test_disallow_negative_second(self):
with self.assertRaisesWithMessage(ValueError):
song.sing(1, -2)
def test_disallow_greater_then_12(self):
with self.assertRaisesWithMessage(ValueError):
song.sing(13)
def test_disallow_greater_then_12_range(self):
with self.assertRaisesWithMessage(ValueError):
song.sing(3, 15)
def test_disallow_first_bigger_then_second(self):
with self.assertRaisesWithMessage(ValueError):
song.sing(6, 2)
def test_disallow_different_types(self):
with self.assertRaisesWithMessage(ValueError):
song.sing("1", True)
def test_disallow_zero(self):
with self.assertRaisesWithMessage(ValueError):
song.sing(0, 0)
def setUp(self):
try:
self.assertRaisesRegex
except AttributeError:
self.assertRaisesRegex = self.assertRaisesRegexp
def assertRaisesWithMessage(self, exception):
return self.assertRaisesRegex(exception, r".+")
|
import formatNum as fN
import os
import urllib
__author__ = 'syao'
def _fetch(file_url, local_file_name):
print 'start download from {}'.format(file_url)
if not os.path.exists(local_file_name):
urllib.urlretrieve(file_url, local_file_name)
print '{} is completed!'.format(local_file_name)
else:
print '{} already exists!'.format(local_file_name)
def mi1b2t(date, path, orbit, cam):
from constant import HEADER_MI1B2T_FILENAME
from constant import HEADER_MI1B2T_URL
orbit = fN.orbit2str(orbit)
path = fN.path2str(path)
dir_radiance = '../../projects/aerosol/products/MI1B2T/' + date
if not os.path.exists(dir_radiance):
os.makedirs(dir_radiance)
file_name = HEADER_MI1B2T_FILENAME + path + '_O' + orbit + '_' + cam + '_F03_0024.hdf'
local_file_name = dir_radiance + '/' + file_name
file_url = HEADER_MI1B2T_URL + date + '/' + file_name
_fetch(file_url, local_file_name)
def mil2asae(date, path, orbit):
from constant import HEADER_MIL2ASAE_FILENAME, HEADER_MIL2ASAE_URL
orbit = fN.orbit2str(orbit)
path = fN.path2str(path)
dir_aerosol = '../../projects/aerosol/products/MIL2ASAE/' + date
if not os.path.exists(dir_aerosol):
os.makedirs(dir_aerosol)
file_name = HEADER_MIL2ASAE_FILENAME + path + '_O' + orbit + '_F12_0022.hdf'
local_file_name = dir_aerosol + '/' + file_name
file_url = HEADER_MIL2ASAE_URL + date + '/' + file_name
_fetch(file_url, local_file_name)
def miancagp(path):
from constant import HEADER_MIANCAGP_FILENAME, HEADER_MIANCAGP_URL1, HEADER_MIANCAGP_URL2
path = fN.path2str(path)
dir_geo = 'product/MIANCAGP'
if not os.path.exists(dir_geo):
os.makedirs(dir_geo)
file_name = HEADER_MIANCAGP_FILENAME + path + '_F01_24.hdf'
local_file_name = dir_geo + '/' + file_name
file_url = [HEADER_MIANCAGP_URL1+file_name,HEADER_MIANCAGP_URL2+file_name]
for i in [0, 1]:
try:
_fetch(file_url[i], local_file_name)
break
except IOError:
print "file doesn't exist at {}".format(file_url[i])
|
#-*- coding:utf8 -*-
__author__ = 'meixqhi'
import json
import time
import random
from django.db import models
from django.db.models import Sum
from shopback.base.models import BaseModel
from shopback.base.fields import BigIntegerAutoField,BigIntegerForeignKey
from shopback.users.models import User
from shopback.monitor.models import TradeExtraInfo
from common.utils import parse_datetime
from auth import apis
import logging
logger = logging.getLogger('django.request')
LOGISTICS_FINISH_STATUS = ['ACCEPTED_BY_RECEIVER']
AREA_TYPE_CHOICES = (
(1,'country/国家'),
(2,'province/省/自治区/直辖市'),
(3,'city/地区'),
(4,'district/县/市/区'),
)
class Area(models.Model):
id = models.BigIntegerField(primary_key=True,verbose_name='地区编号')
parent_id = models.BigIntegerField(db_index=True,default=0,verbose_name='父级编号')
type = models.IntegerField(default=0,choices=AREA_TYPE_CHOICES,verbose_name='区域类型')
name = models.CharField(max_length=64,blank=True,verbose_name='地域名称')
zip = models.CharField(max_length=10,blank=True,verbose_name='邮编')
class Meta:
db_table = 'shop_logistics_area'
verbose_name=u'地理区划'
verbose_name_plural = u'地理区划列表'
def __unicode__(self):
return '<%d,%d,%s,%s>'%(self.id,self.type,self.name,self.zip)
class DestCompany(models.Model):
""" 区域指定快递选择 """
state = models.CharField(max_length=64,blank=True,verbose_name='省/自治区/直辖市')
city = models.CharField(max_length=64,blank=True,verbose_name='市')
district = models.CharField(max_length=64,blank=True,verbose_name='县/市/区')
company = models.CharField(max_length=10,blank=True,verbose_name='快递编码')
class Meta:
db_table = 'shop_logistics_destcompany'
verbose_name=u'区域快递分配'
verbose_name_plural = u'区域快递分配'
def __unicode__(self):
return '<%s,%s,%s,%s>'%(self.state,self.city,self.district,self.company)
@classmethod
def get_destcompany_by_addr(cls,state,city,district):
companys = None
if district:
companys = cls.objects.filter(district__startswith=district)
if city:
if companys and companys.count()>0:
companys = companys.filter(city__startswith=city)
else:
companys = cls.objects.filter(city__startswith=city,district='')
if state:
if companys and companys.count()>0:
companys = companys.filter(state__startswith=state)
else:
companys = cls.objects.filter(state__startswith=state,city='',district='')
if companys and companys.count()>0:
cid = companys[0].company
logistic = LogisticsCompany.objects.get(code=cid.upper())
return logistic
return None
class LogisticsCompany(models.Model):
NOPOST = 'HANDSALE'
id = models.BigIntegerField(primary_key=True,verbose_name='ID')
code = models.CharField(max_length=64,unique=True,blank=True,verbose_name='快递编码')
name = models.CharField(max_length=64,blank=True,verbose_name='快递名称')
reg_mail_no = models.CharField(max_length=500,blank=True,verbose_name='单号匹配规则')
district = models.TextField(blank=True,verbose_name='服务区域(,号分隔)')
priority = models.IntegerField(null=True,default=0,verbose_name='优先级')
status = models.BooleanField(default=True,verbose_name='使用')
class Meta:
db_table = 'shop_logistics_company'
verbose_name=u'物流公司'
verbose_name_plural = u'物流公司列表'
def __unicode__(self):
return '<%s,%s>'%(self.code,self.name)
@classmethod
def getNoPostCompany(cls):
company,state = cls.objects.get_or_create(code=cls.NOPOST)
if state:
company.name = u'无需物流'
company.save()
return company
@classmethod
def get_recommend_express(cls,state,city,district):
if not state:
return None
#获取指定地区快递
company = DestCompany.get_destcompany_by_addr(state,city,district)
if company:
return company
#根据系统规则选择快递
logistics = cls.objects.filter(status=True).order_by('-priority')
total_priority = logistics.aggregate(total_priority=Sum('priority')).get('total_priority')
priority_ranges = []
cur_range = 0
for logistic in logistics:
districts = set([lg.strip()[0:2] for lg in logistic.district.split(',') if len(lg)>1])
if state[0:2] in districts:
return logistic
start_range = total_priority-cur_range-logistic.priority
end_range = total_priority-cur_range
priority_range = (start_range,end_range,logistic)
cur_range += logistic.priority
priority_ranges.append(priority_range)
index = random.randint(1,total_priority)
for rg in priority_ranges:
if index>=rg[0] and index<=rg[1]:
return rg[2]
return None
@classmethod
def save_logistics_company_through_dict(cls,user_id,company_dict):
company,state = cls.objects.get_or_create(id=company_dict['id'])
for k,v in company_dict.iteritems():
hasattr(company, k) and setattr(company,k,v)
company.save()
return company
class Logistics(models.Model):
tid = BigIntegerAutoField(primary_key=True)
user = models.ForeignKey(User,null=True,related_name='logistics')
order_code = models.CharField(max_length=64,blank=True)
is_quick_cod_order = models.BooleanField(default=True)
out_sid = models.CharField(max_length=64,blank=True)
company_name = models.CharField(max_length=30,blank=True)
seller_id = models.CharField(max_length=64,blank=True)
seller_nick = models.CharField(max_length=64,blank=True)
buyer_nick = models.CharField(max_length=64,blank=True)
item_title = models.CharField(max_length=64,blank=True)
delivery_start = models.DateTimeField(db_index=True,null=True,blank=True)
delivery_end = models.DateTimeField(db_index=True,null=True,blank=True)
receiver_name = models.CharField(max_length=64,blank=True)
receiver_phone = models.CharField(max_length=20,blank=True)
receiver_mobile = models.CharField(max_length=20,blank=True)
location = models.TextField(max_length=500,blank=True)
type = models.CharField(max_length=7,blank=True) #free(卖家包邮),post(平邮),express(快递),ems(EMS).
created = models.DateTimeField(db_index=True,null=True,blank=True)
modified = models.DateTimeField(db_index=True,null=True,blank=True)
seller_confirm = models.CharField(max_length=3,default='no')
company_name = models.CharField(max_length=32,blank=True)
is_success = models.BooleanField(default=False)
freight_payer = models.CharField(max_length=6,blank=True)
status = models.CharField(max_length=32,blank=True)
class Meta:
db_table = 'shop_logistics_logistic'
verbose_name=u'订单物流'
verbose_name_plural = u'订单物流列表'
def __unicode__(self):
return '<%s,%s>'%(self.tid,self.company_name)
@classmethod
def get_or_create(cls,user_id,tid):
logistic,state = cls.objects.get_or_create(tid=tid)
if not logistic.is_success:
try:
response = apis.taobao_logistics_orders_detail_get(tid=tid,tb_user_id=user_id)
logistic_dict = response['logistics_orders_detail_get_response']['shippings']['shipping'][0]
logistic = cls.save_logistics_through_dict(user_id, logistic_dict)
except Exception,exc:
logger.error('淘宝后台更新交易(tid:%s)物流信息出错'.decode('utf8')%str(tid),exc_info=True)
return logistic
@classmethod
def save_logistics_through_dict(cls,user_id,logistic_dict):
logistic,state = cls.objects.get_or_create(tid=logistic_dict['tid'])
logistic.user = User.objects.get(visitor_id=user_id)
logistic.seller_id = user_id
for k,v in logistic_dict.iteritems():
hasattr(logistic,k) and setattr(logistic,k,v)
location = logistic_dict.get('location',None)
logistic.location = json.dumps(location)
logistic.delivery_start = parse_datetime(logistic_dict['delivery_start'])\
if logistic_dict.get('delivery_start',None) else None
logistic.delivery_end = parse_datetime(logistic_dict['delivery_end'])\
if logistic_dict.get('delivery_end',None) else None
logistic.created = parse_datetime(logistic_dict['created'])\
if logistic_dict.get('created',None) else None
logistic.modified = parse_datetime(logistic_dict['modified'])\
if logistic_dict.get('modified',None) else None
logistic.save()
if logistic_dict['status'] in LOGISTICS_FINISH_STATUS:
trade_extra_info,state = TradeExtraInfo.objects.get_or_create(tid=logistic_dict['tid'])
trade_extra_info.is_update_logistic = True
trade_extra_info.save()
return logistic
|
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
# --- Do not remove these libs ---
import numpy as np # noqa
import pandas as pd # noqa
from pandas import DataFrame
from freqtrade.strategy.interface import IStrategy
# --------------------------------
# Add your lib to import here
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib
from technical.util import resample_to_interval, resampled_merge
from freqtrade.strategy import IStrategy, merge_informative_pair
from technical.indicators import ichimoku
class Ichimoku_v38(IStrategy):
# ROI table:
minimal_roi = {
"0": 100
}
# Stoploss:
stoploss = -0.99
# Optimal timeframe for the strategy.
timeframe = '4h'
inf_tf = '1d'
# Run "populate_indicators()" only for new candle.
process_only_new_candles = True
# These values can be overridden in the "ask_strategy" section in the config.
use_sell_signal = True
sell_profit_only = False
ignore_roi_if_buy_signal = True
# Number of candles the strategy requires before producing valid signals
startup_candle_count = 150
# Optional order type mapping.
order_types = {
'buy': 'market',
'sell': 'market',
'stoploss': 'market',
'stoploss_on_exchange': False
}
def informative_pairs(self):
if not self.dp:
# Don't do anything if DataProvider is not available.
return []
# Get access to all pairs available in whitelist.
pairs = self.dp.current_whitelist()
# Assign tf to each pair so they can be downloaded and cached for strategy.
informative_pairs = [(pair, '1d') for pair in pairs]
return informative_pairs
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
if not self.dp:
# Don't do anything if DataProvider is not available.
return dataframe
dataframe_inf = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_tf)
#Heiken Ashi Candlestick Data
heikinashi = qtpylib.heikinashi(dataframe_inf)
dataframe_inf['ha_open'] = heikinashi['open']
dataframe_inf['ha_close'] = heikinashi['close']
dataframe_inf['ha_high'] = heikinashi['high']
dataframe_inf['ha_low'] = heikinashi['low']
ha_ichi = ichimoku(heikinashi,
conversion_line_period=20,
base_line_periods=60,
laggin_span=120,
displacement=30
)
#Required Ichi Parameters
dataframe_inf['senkou_a'] = ha_ichi['senkou_span_a']
dataframe_inf['senkou_b'] = ha_ichi['senkou_span_b']
dataframe_inf['cloud_green'] = ha_ichi['cloud_green']
dataframe_inf['cloud_red'] = ha_ichi['cloud_red']
# Merge timeframes
dataframe = merge_informative_pair(dataframe, dataframe_inf, self.timeframe, self.inf_tf, ffill=True)
"""
Senkou Span A > Senkou Span B = Cloud Green
Senkou Span B > Senkou Span A = Cloud Red
"""
return dataframe
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
(
(
(dataframe['ha_close_1d'].crossed_above(dataframe['senkou_a_1d'])) &
(dataframe['ha_close_1d'].shift() < (dataframe['senkou_a_1d'])) &
(dataframe['cloud_green_1d'] == True)
) |
(
(dataframe['ha_close_1d'].crossed_above(dataframe['senkou_b_1d'])) &
(dataframe['ha_close_1d'].shift() < (dataframe['senkou_b_1d'])) &
(dataframe['cloud_red_1d'] == True)
)
),
'buy'] = 1
return dataframe
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
(
(dataframe['ha_close_1d'] < dataframe['senkou_a_1d']) |
(dataframe['ha_close_1d'] < dataframe['senkou_b_1d'])
),
'sell'] = 1
return dataframe
|
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------------------
from tornado.web import authenticated, HTTPError
from os.path import join, exists
from os import remove
from json import loads, dumps
from collections import defaultdict
from shutil import rmtree, move
from .util import check_access
from .base_handlers import BaseHandler
from qiita_core.qiita_settings import qiita_config, r_client
from qiita_core.util import execute_as_transaction
from qiita_db.util import (get_files_from_uploads_folders,
get_mountpoint, move_upload_files_to_trash)
from qiita_db.study import Study
from qiita_db.processing_job import ProcessingJob
from qiita_db.software import Software, Parameters
from qiita_db.exceptions import QiitaDBUnknownIDError
from qiita_db.util import create_nested_path
UPLOAD_STUDY_FORMAT = 'upload_study_%s'
class StudyUploadFileHandler(BaseHandler):
@authenticated
@execute_as_transaction
def display_template(self, study_id, msg):
"""Simple function to avoid duplication of code"""
study_id = int(study_id)
study = Study(study_id)
user = self.current_user
level = 'info'
message = ''
remote_url = ''
remote_files = []
check_access(user, study, no_public=True, raise_error=True)
job_info = r_client.get(UPLOAD_STUDY_FORMAT % study_id)
if job_info:
job_info = defaultdict(lambda: '', loads(job_info))
job_id = job_info['job_id']
job = ProcessingJob(job_id)
job_status = job.status
processing = job_status not in ('success', 'error')
url = job.parameters.values['url']
if processing:
if job.command.name == 'list_remote_files':
message = 'Retrieving remote files: listing %s' % url
else:
message = 'Retrieving remote files: download %s' % url
elif job_status == 'error':
level = 'danger'
message = job.log.msg.replace('\n', '</br>')
# making errors nicer for users
if 'No such file' in message:
message = 'URL not valid: <i>%s</i>, please review.' % url
else:
remote_url = job_info['url']
remote_files = job_info['files']
level = job_info['alert_type']
message = job_info['alert_msg'].replace('\n', '</br>')
# getting the ontologies
self.render('upload.html',
study_title=study.title, study_info=study.info,
study_id=study_id, is_admin=user.level == 'admin',
extensions=','.join(qiita_config.valid_upload_extension),
max_upload_size=qiita_config.max_upload_size, level=level,
message=message, remote_url=remote_url,
remote_files=remote_files,
files=get_files_from_uploads_folders(str(study_id)))
@authenticated
@execute_as_transaction
def get(self, study_id):
try:
study = Study(int(study_id))
except QiitaDBUnknownIDError:
raise HTTPError(404, reason="Study %s does not exist" % study_id)
check_access(self.current_user, study, no_public=True,
raise_error=True)
self.display_template(study_id, "")
@authenticated
@execute_as_transaction
def post(self, study_id):
try:
study = Study(int(study_id))
except QiitaDBUnknownIDError:
raise HTTPError(404, reason="Study %s does not exist" % study_id)
check_access(self.current_user, study, no_public=True,
raise_error=True)
files_to_move = []
for v in self.get_arguments('files_to_erase', strip=True):
v = v.split('-', 1)
# if the file was just uploaded JS will not know which id the
# current upload folder has so we need to retrieve it
if v[0] == 'undefined':
v[0], _ = get_mountpoint("uploads")[0]
files_to_move.append((int(v[0]), v[1]))
move_upload_files_to_trash(study.id, files_to_move)
self.display_template(study_id, "")
class StudyUploadViaRemote(BaseHandler):
@authenticated
@execute_as_transaction
def post(self, study_id):
method = self.get_argument('remote-request-type')
url = self.get_argument('inputURL')
ssh_key = self.request.files['ssh-key'][0]['body']
status = 'success'
message = ''
try:
study = Study(int(study_id))
except QiitaDBUnknownIDError:
raise HTTPError(404, reason="Study %s does not exist" % study_id)
check_access(
self.current_user, study, no_public=True, raise_error=True)
_, upload_folder = get_mountpoint("uploads")[0]
upload_folder = join(upload_folder, study_id)
ssh_key_fp = join(upload_folder, '.key.txt')
create_nested_path(upload_folder)
with open(ssh_key_fp, 'wb') as f:
f.write(ssh_key)
qiita_plugin = Software.from_name_and_version('Qiita', 'alpha')
if method == 'list':
cmd = qiita_plugin.get_command('list_remote_files')
params = Parameters.load(cmd, values_dict={
'url': url, 'private_key': ssh_key_fp, 'study_id': study_id})
elif method == 'transfer':
cmd = qiita_plugin.get_command('download_remote_files')
params = Parameters.load(cmd, values_dict={
'url': url, 'private_key': ssh_key_fp,
'destination': upload_folder})
else:
status = 'error'
message = 'Not a valid method'
if status == 'success':
job = ProcessingJob.create(self.current_user, params, True)
job.submit()
r_client.set(
UPLOAD_STUDY_FORMAT % study_id, dumps({'job_id': job.id}))
self.write({'status': status, 'message': message})
class UploadFileHandler(BaseHandler):
# """ main upload class
# based on
# https://github.com/23/resumable.js/blob/master/samples/Backend%20on%20PHP.md
# """
def validate_file_extension(self, filename):
"""simple method to avoid duplication of code
This validation is server side in case they can go around the client
side validation
"""
if not filename.endswith(tuple(qiita_config.valid_upload_extension)):
self.set_status(415)
raise HTTPError(415, reason="User %s is trying to upload %s" %
(self.current_user, str(filename)))
@authenticated
@execute_as_transaction
def post(self):
resumable_identifier = self.get_argument('resumableIdentifier')
resumable_filename = self.get_argument('resumableFilename')
resumable_chunk_number = int(self.get_argument('resumableChunkNumber'))
resumable_total_chunks = int(self.get_argument('resumableTotalChunks'))
study_id = self.get_argument('study_id')
data = self.request.files['file'][0]['body']
check_access(self.current_user, Study(int(study_id)),
no_public=True, raise_error=True)
self.validate_file_extension(resumable_filename)
_, base_fp = get_mountpoint("uploads")[0]
# creating temporal folder for upload of the file
temp_dir = join(base_fp, study_id, resumable_identifier)
create_nested_path(temp_dir)
# location of the file as it is transmitted
temporary_location = join(temp_dir, resumable_filename)
# this is the result of a failed upload
if resumable_chunk_number == 1 and exists(temporary_location):
remove(temporary_location)
# append every transmitted chunk
with open(temporary_location, 'ab') as tmp_file:
tmp_file.write(bytes(data))
if resumable_chunk_number == resumable_total_chunks:
final_location = join(base_fp, study_id, resumable_filename)
if exists(final_location):
remove(final_location)
move(temporary_location, final_location)
rmtree(temp_dir)
self.set_status(200)
@authenticated
@execute_as_transaction
def get(self):
""" this is the first point of entry into the upload service
this should either set the status as 400 (error) so the file/chunk is
sent via post or 200 (valid) to not send the file
"""
study_id = self.get_argument('study_id')
resumable_filename = self.get_argument('resumableFilename')
check_access(self.current_user, Study(int(study_id)),
no_public=True, raise_error=True)
self.validate_file_extension(resumable_filename)
# in the original version we used to check if a chunk was already
# uploaded and if it was we would send self.set_status(200). Now, as
# we are not chunking by file we can simply pass the no exists
# response
self.set_status(400)
|
#MUHAMMET ENES AY
import time
urunler = dict()
keyler=[] # unique barkod numaralari olusturmak için kontrol saglıyor
def ana():
print(
"""***DEPO STOK TAKİP OTOMASYONU***
1)ÜRÜN EKLE \n2)ÜRÜN GÜNCELLE \n3)ÜRÜN ARA \n4)ÜRÜN SİL \n5)KDV'Lİ FİYAT HESAPLA \n6)ÜRÜN LİSTELE \n7)SATIŞ YAP \n8)STOK KONTROL\n9)ÇIKIŞ""")
sec = int(input("Lütfen seçiminizi giriniz:"))
if sec == 1:
urun_ekle()
if sec == 2:
urun_guncelle()
if sec == 3:
urun_ara()
if sec == 4:
urun_sil()
if sec == 5:
kdv_hesapla()
if sec == 6:
urun_listele()
if sec==7:
satisyap()
if sec==8:
stok_kontrol()
return sec
def urun_ekle():
while True:
try:
sayi = int(input("Lütfen eklenecek ürün sayısını giriniz :"))
def dosyaya_yaz():
with open("19010011077.txt", "a", encoding="utf-8") as dosya:
for a, d in urunler.items():
dosya.write('%s:%s\n' % (a, d))
def bilgi_al():
for i in range(1, int(sayi) + 1):
liste = []
while True:
with open("19010011077.txt", "r", encoding="utf=8") as dosya1:
kontrol = dosya1.readlines()
kontrol_tf = None
barkod = int(input("{}. ürünün barkod numarasını giriniz :".format(i)))
for a in kontrol: # Aynı barkod numarasının girilmesini engeller.
if str(barkod) == a.split(":")[0]:
kontrol_tf = True
else:
continue
if kontrol_tf == True:
print("Bu barkod numarasını kullanan ürün halihazırda bulunuyor.Tekrar deneyiniz.")
elif barkod in keyler:
print("Bu barkod numarasını kullanan ürün halihazırda bulunuyor.Tekrar deneyiniz.")
else:
break
ad = input("{}. ürünün adını giriniz :".format(i))
fiyat = int(input("{}. ürünün fiyatını giriniz :".format(i)))
adet = int(input("{}. ürünün adetini giriniz :".format(i)))
liste.append(ad.upper())
liste.append(fiyat)
liste.append(adet)
urunler[barkod] = liste
keyler.append(barkod)
bilgi_al() #İNNER FONKSİYON
dosyaya_yaz() #İNNER FONKSİYON
urunler.clear()
print("Ürün(ler) başarıyla eklendi.")
while True:
ekle_secim = input("Tekrar ürün eklemek içim (D) Menüye dönmek için (M) :")
if ekle_secim.upper() != "D" and ekle_secim.upper() != "M":
print("HATA! lütfen geçerli bir seçim yapınız.")
else:
break
if ekle_secim.upper() == "D":
continue
elif ekle_secim.upper() == "M":
break
except ValueError:
print("HATA! Sayı değeri haricinde değer girilemez!")
continue
def urun_ara():
while True:
barkod_ara=input("Lütfen aranacak ürünün barkod numarasını giriniz : ")
with open("19010011077.txt", "r", encoding="utf=8") as dosya2:
oku_urun = dosya2.readlines()
check=None
for a in oku_urun:
if barkod_ara == a.split(":")[0] :
check=True
print("ÜRÜN ADI : "+ a.split("'")[1]) #urun adına ulasmamızı saglayan koordınat
print("ÜRÜN FİYATI :"+ a.split(",")[1] +"TL")
print("ÜRÜN ADEDİ :"+ a.split(",")[2].replace("]",""))
if check!=True:
print("Bu barkod numarası ile ürün bulunmuyor!")
devam=input("Tekrar sorgulamak için (D) menüye dönmek için (M):")
if devam.upper()=="D":
continue
elif devam.upper()=="M":
break
def urun_sil():
while True:
barkod_sil=input("Lütfen silmek istediğiniz ürünün barkod numarasını giriniz : ")
with open("19010011077.txt", "r", encoding="utf=8") as dosya3:
sil_urun = dosya3.readlines()
check2=None
secim_sil=None
for sil in sil_urun:
if barkod_sil == sil.split(":")[0] :
check2=True
print("ÜRÜN ADI : "+ sil.split("'")[1]) #urun adına ulasmamızı saglayan koordınat
print("ÜRÜN FİYATI :"+ sil.split(",")[1] +"TL")
print("ÜRÜN ADEDİ :"+ sil.split(",")[2].replace("]",""))
secim_sil=input("Seçili ürünü silmek istediğinize emin misiniz? (E)(H) : ")
if str(secim_sil).upper()=="E":
with open("19010011077.txt","w",encoding="utf=8") as dosya4:
for sil in sil_urun:
if barkod_sil != sil.split(":")[0]:
dosya4.write(sil)
if not keyler: #ilk açılışta silme yaparken keyler listesi boş olacagından,hata olmasını engeller.
pass
else:
if int(barkod_sil) in keyler:
keyler.remove(int(barkod_sil)) #ürün silindiginde tekrar eklenirse barkod hatası vermesini engeller
if check2!=True:
print("Bu barkod numarası ile ürün bulunmuyor!")
else:
if str(secim_sil).upper() == "E":
print("Ürün başarıyla silindi.")
devams=input("Tekrar ürün silmek için (S) menüye dönmek için (M):")
if devams.upper()=="S":
pass
elif devams.upper()=="M":
break
def urun_guncelle():
while True:
urunler_gnc=dict()
liste2=[]
barkod_guncelle = input("Lütfen güncellemek istediğiniz ürünün barkod numarasını giriniz : ")
with open("19010011077.txt", "r", encoding="utf=8") as dosya5:
guncelle_urun = dosya5.readlines()
devam3=None
check3 = None
secim_guncelle = None
for gnc in guncelle_urun:
if barkod_guncelle == gnc.split(":")[0]:
check3 = True
print("ÜRÜN ADI : " + gnc.split("'")[1]) # urun adına ulasmamızı saglayan koordınat
print("ÜRÜN FİYATI :" + gnc.split(",")[1] + "TL")
print("ÜRÜN ADEDİ :" + gnc.split(",")[2].replace("]", ""))
secim_guncelle = input("Seçili ürünü güncellemek istediğinize emin misiniz? (E)(H) : ")
if str(secim_guncelle).upper()=="H":
break
if check3!=True:
print("Bu barkod numarası ile ürün bulunmuyor!")
devam3=input("Tekrar sorgulamak için (D) menüye dönmek için (M):")
if str(devam3).upper()=="D":
continue
elif str(devam3).upper()=="M":
break
if secim_guncelle.upper()=="E":
gnc_ad = input("Yeni ürün adını giriniz : ")
gnc_fiyat = int(input("Yeni ürün fiyatını giriniz : "))
gnc_adet = int(input("Yeni ürün adedini giriniz : "))
liste2.append(gnc_ad.upper())
liste2.append(gnc_fiyat)
liste2.append(gnc_adet)
urunler_gnc[barkod_guncelle] = liste2
print("GUNCELLENİYOR", end="")
for i in range(3):
time.sleep(0.4)
print(".", end="")
with open("19010011077.txt","w",encoding="utf=8") as dosya6:
for sil in guncelle_urun:
if barkod_guncelle != sil.split(":")[0]:
dosya6.write(sil)
with open("19010011077.txt","a",encoding="utf=8") as dosya7:
for a, d in urunler_gnc.items():
dosya7.write('%s:%s\n' % (a, d))
print("Ürün güncellendi")
break
def urun_listele():
with open("19010011077.txt", "r", encoding="utf=8") as dosya8:
listele_urun = dosya8.readlines()
i=0
for l in listele_urun:
i=i+1
print(str(i)+")"+" ÜRÜN BARKOD NO : "+l.split(":")[0]+"\t"+"|",end="")
print(" ÜRÜN ADI : " + l.split("'")[1] + "\t" + "|", end = "")
print(" ÜRÜN FİYATI :" + l.split(",")[1] + "TL"+"\t"+"|",end="")
print(" ÜRÜN ADEDİ :" + l.split(",")[2].replace("]", ""),end="")
time.sleep(0.5)
input("Menüye dönmek için bir tuşa basınız : ")
def kdv_hesapla():
while True:
try:
barkod_kdv = input("Lütfen kdv dahil fiyatı hesaplanacak ürünün barkod numarasını giriniz : ")
with open("19010011077.txt", "r", encoding="utf=8") as dosya9:
kdv_urun = dosya9.readlines()
kontrol = None
for kdv in kdv_urun:
if barkod_kdv == kdv.split(":")[0]:
kontrol = True
print("ÜRÜN ADI : " + kdv.split("'")[1])
print("ÜRÜN FİYATI :" + kdv.split(",")[1] + "TL")
print("ÜRÜN ADEDİ :" + kdv.split(",")[2].replace("]", ""))
oran = int(input("Lütfen seçili ürün için güncel kdv oranını giriniz % :"))
kdvli = (int(kdv.split(",")[1]) * (oran / 100) + int(kdv.split(",")[1]))
print(kdv.split("'")[1] + " adlı ürün için" + " kdv dahil fiyat :" + str(kdvli) + "TL")
if kontrol != True:
print("Bu barkod numarası ile ürün bulunmuyor!")
devam_kdv = input("Tekrar hesaplamak için (D) menüye dönmek için (M):")
if devam_kdv.upper() == "D":
continue
elif devam_kdv.upper() == "M":
break
except ValueError:
print("HATA! girdiğiniz alan ile girilen değer uyumsuz.(İşlem tekrar başlatıldı)")
def satisyap():
def sat_urun(barkod_sat):
fiyat=None
adet=None
ad=None
with open("19010011077.txt", "r", encoding="utf=8") as dosya_sat2:
oku2_urun = dosya_sat2.readlines()
for sat2 in oku2_urun:
if barkod_sat == sat2.split(":")[0]:
ad=sat2.split("'")[1]
fiyat=sat2.split(",")[1]
adet=sat2.split(",")[2].replace("]", "")
urunler_sat = dict()
liste_sat = []
sat_fiyat = int(input("Lütfen satış fiyatını giriniz : "))
while True:
sat_adet = int(input("Satış adedini giriniz : "))
if int(adet)<(sat_adet):
print("Stoktaki adeti aştınız lütfen tekrar deneyiniz.")
continue
else:
break
liste_sat.append(ad)
liste_sat.append(int(fiyat))
liste_sat.append(int(adet)-(sat_adet))
urunler_sat[barkod_sat] = liste_sat
with open("19010011077.txt", "w", encoding="utf=8") as dosya_yaz:
for sat in oku2_urun:
if barkod_sat != sat.split(":")[0]:
dosya_yaz.write(sat)
with open("19010011077.txt", "a", encoding="utf=8") as dosya_ekle:
for b, c in urunler_sat.items():
dosya_ekle.write('%s:%s\n' % (b, c))
print("Ürün satıldı.")
print("Net kar : {} TL".format((sat_fiyat*sat_adet)-(int(fiyat)*sat_adet)))
devam_sat2 = input("Tekrar satış yapmak için (D) menüye dönmek için (M):")
a="devam"
b="menü"
if devam_sat2.upper()=="D":
return a
if devam_sat2.upper()=="M":
return b
while True:
barkod_sat = input("Lütfen satılacak ürünün barkod numarasını giriniz : ")
with open("19010011077.txt", "r", encoding="utf=8") as dosya_oku:
oku_urun = dosya_oku.readlines()
kontrol_sat = None
secim_sat=None
devam_sat=None
for sat in oku_urun:
if barkod_sat == sat.split(":")[0]:
kontrol_sat = True
print("ÜRÜN ADI : " + sat.split("'")[1]) # urun adına ulasmamızı saglayan koordınat
print("ÜRÜN FİYATI :" + sat.split(",")[1] + "TL")
print("ÜRÜN ADEDİ :" + sat.split(",")[2].replace("]", ""))
secim_sat = input("Seçili ürünü satmak istediğinize emin misiniz? (E)(H) : ")
if kontrol_sat !=True:
print("Bu barkod numarası ile ürün bulunmuyor!")
devam_sat = input("Tekrar denemek için (D) menüye dönmek için (M):")
if str(devam_sat).upper()=="D":
continue
elif str(devam_sat).upper()=="M":
break
if str(secim_sat).upper() == "H":
break
if secim_sat.upper()=="E":
secim=sat_urun(barkod_sat)
if secim=="devam":
continue
if secim=="menü":
break
def stok_kontrol():
with open("19010011077.txt", "r", encoding="utf=8") as dosya_stok:
stok_urun = dosya_stok.readlines()
i = 0
for stk in stok_urun:
if int(stk.split(",")[2].replace("]", ""))<5:
i = i + 1
print(str(i) + ")" + " ÜRÜN BARKOD NO : " + stk.split(":")[0] + "\t" + "|", end="")
print(" ÜRÜN ADI : " + stk.split("'")[1] + "\t" + "|", end="")
print(" ÜRÜN FİYATI :" + stk.split(",")[1] + "TL" + "\t" + "|", end="")
print(" ÜRÜN ADEDİ :" + stk.split(",")[2].replace("]", ""), end="")
time.sleep(0.5)
input("Menüye dönmek için bir tuşa basınız : ")
while True:
try:
secim = ana()
if secim == 9:
break
if secim > 9 or secim < 1:
print("HATA! Lütfen seçim sınırlarına uygun bir sayı giriniz!")
continue
except ValueError:
print("HATA! sayısal değer girilmelidir.")
print("OTOMASYON SONLANDIRILIYOR",end="")
for i in range(3):
print(".",end="")
time.sleep(0.2)
|
data = []
with open('/home/cyagen1/Downloads/rosalind_seto.txt','r') as f:
for line in f:
data.append(line.strip('\n'))
U = set(str(i)for i in range(1, int(data[0])+1))
A = set([x for x in data[1].strip('{}').replace(' ','').split(',')])
B = set([x for x in data[2].strip('{}').replace(' ','').split(',')])
union = A.union(B)
intersection = A.intersection(B)
diff_AB = A-B
diff_BA = B-A
A_comp = U-A
B_comp = U-B
ff=open('/home/cyagen1/Downloads/s.txt','w')
ff.write('{'+','.join(union)+'}')
ff.write('{'+','.join(intersection)+'}')
ff.write('{'+','.join(diff_AB)+'}')
ff.write('{'+','.join(diff_BA)+'}')
ff.write('{'+','.join(A_comp)+'}')
ff.write('{'+','.join(B_comp)+'}')
#def get_sets(n, a, b):
# return [a | b, a & b, a - b, b - a, set(range(1, n + 1)) - a, set(range(1, n + 1)) - b]
#def format_output(result):
# b = open('/home/cyagen1/Downloads/rosalind_setoout.txt', 'w')
# for r in result:
# print "{" + ', '.join(map(str, r)) + "}"
# b.write("{" + ', '.join(map(str, r)) + "}\n")
#def parse(line):
# return [s.strip() for s in line.strip()[1:-1].split(",")]
#if __name__ == '__main__':
# n, a, b = open('/home/cyagen1/Downloads/rosalind_seto.txt').readlines()
# n = int(n.strip())
# a = set(map(int, parse(a)))
# b = set(map(int, parse(b)))
# format_output(get_sets(n, a, b))
|
import tkinter as tk
from tkinter import ttk
class Checkbar(tk.Frame):
def __init__(self, parent=None, picks=[], side=tk.LEFT, anchor=tk.W):
tk.Frame.__init__(self, parent)
self.setUsers(picks)
def state(self):
return map((lambda var: var.get()), self.vars)
def setUsers(self, userList):
picks = userList
self.vars = []
for pick in picks:
var = tk.IntVar()
chk = tk.Checkbutton(self, text=pick, variable=var)
chk.pack(anchor=tk.W, expand=tk.YES)
self.vars.append(var)
root = tk.Tk()
root.title('Blabla')
root.geometry("500x400")
#Create Main Frame
main_frame = tk.Frame(root)
main_frame.pack(fill=tk.BOTH, expand=1)
#Create a canvas
my_canvas = tk.Canvas(main_frame)
my_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
#Add a scrollbar to the Canvas
my_scrollbar = ttk.Scrollbar(main_frame, orient=tk.VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
#Configure another frame inside the canvas
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion=my_canvas.bbox("all")))
#Create another frame inside the canvas
checkbar = Checkbar(my_canvas)
#add that new fdrame to a new windo
my_canvas.create_window((0,0), window=checkbar, anchor="nw")
checkbar.setUsers(["option_"+str(option) for option in range(100)])
root.mainloop()
|
# -*- coding: utf-8 -*-
import logging
from collections import OrderedDict
try:
import PyV8
except:
pass
from .abstract import AbstractBackend
from .exceptions import ArgumentError, JSFunctionNotExists
__all__ = ['PyV8Backend', ]
class PyV8Backend(AbstractBackend):
""" Backend class for PyV8 """
logger = logging.getLogger(__name__)
can_precompile = True
can_run_str = True
def run(
self, func=None, fargs=[], precompil_only=False,
compil_only=False):
"""
Run JS code with libraries and return last operand result or
`func` result if it present
:param str func: (optional) JS function name
:param list fargs: (optional) list of JS function args
:param bool precompil_only: (optional) if true, then it will
return precommiled data all JS code
:param bool compil_only: (optional) if true, then it
will compile the JS code and throw errors if they were
:raise SyntaxError: JS syntax error
:raise PyV8.JSError: JS runtime error (contain fields:
name, message, scriptName, lineNum, startPos, endPos,
startCol, endCol, sourceLine, stackTrace)
"""
precompiled = OrderedDict()
compiled = OrderedDict()
with PyV8.JSLocker():
with PyV8.JSContext() as js_context:
self.logger.debug('Set JS global context class attributes')
for k, v in self.js_global_vars.items():
self.logger.debug(
'Set attribute name=%s, value=%s' % (k, v))
# Convert to JS objects
setattr(
js_context.locals, k,
self._get_js_obj(js_context, v))
with PyV8.JSEngine() as engine:
precompil_error = False
try:
for js_lib, js_code in self.js_libs_code.items():
self.logger.debug('Precompile JS lib: %s' % js_lib)
precompiled[js_lib] = engine.precompile(js_code)
except SyntaxError:
precompil_error = True
if not precompil_error and precompil_only:
return precompiled
for js_lib, js_code in self.js_libs_code.items():
self.logger.debug('Compile JS lib: %s' % js_lib)
cparams = dict(
source=self.js_libs_code[js_lib],
name=js_lib)
if js_lib in precompiled:
cparams['precompiled'] = precompiled[js_lib]
compiled[js_lib] = engine.compile(**cparams)
if compil_only:
return True
result = None
for js_lib, js_script in compiled.items():
self.logger.debug('Run JS lib: %s' % js_lib)
result = js_script.run()
if not func or type(func) != str:
return result
if fargs and not isinstance(fargs, (list, tuple)):
raise ArgumentError(
'The "fargs" must be list or tuple')
if func not in js_context.locals:
raise JSFunctionNotExists(
'Function "%s" not exists in JS context' % func)
# Convert to JS objects
for i in range(len(fargs)):
fargs[i] = self._get_js_obj(js_context, fargs[i])
# Convert to Python objects
return self._get_py_obj(
js_context,
js_context.locals[func](*fargs))
def _get_js_obj(self, ctx, obj):
"""
Convert Python object to JS object and return it
:param PyV8.JSContext ctx: current JS context
:param mixed obj: object for convert
"""
if isinstance(obj, (list, tuple)):
js_list = []
for entry in obj:
js_list.append(self._get_js_obj(ctx, entry))
return PyV8.JSArray(js_list)
elif isinstance(obj, dict):
js_obj = ctx.eval('new Object();')
for key in obj.keys():
try:
js_obj[key] = self._get_js_obj(ctx, obj[key])
except Exception as e:
if (not str(e).startswith('Python argument types in')):
raise
import unicodedata
nkey = unicodedata.normalize(
'NFKD', key).encode('ascii', 'ignore')
js_obj[nkey] = self._get_js_obj(ctx, obj[key])
return js_obj
else:
return obj
def _get_py_obj(self, ctx, obj, route=[]):
"""
Convert JS object to Python object and return it
:param PyV8.JSContext ctx: current JS context
:param mixed obj: object for convert
:param list route: key list for lookup
in iterable objects (internal usage)
"""
def access(obj, key):
if key in obj:
return obj[key]
return None
cloned = None
if isinstance(obj, (list, tuple, PyV8.JSArray)):
cloned = []
num_elements = len(obj)
for index in range(num_elements):
elem = obj[index]
cloned.append(self._get_py_obj(ctx, elem, route + [index]))
elif isinstance(obj, (dict, PyV8.JSObject)):
cloned = {}
for key in obj.keys():
cloned_val = None
if type(key) == int:
val = None
try:
val = access(obj, str(key))
except KeyError:
pass
if val is None:
val = access(obj, key)
cloned_val = self._get_py_obj(ctx, val, route + [key])
else:
cloned_val = self._get_py_obj(
ctx, access(obj, key), route + [key])
cloned[key] = cloned_val
elif isinstance(obj, (str, bytes)):
cloned = obj.decode('utf-8')
else:
cloned = obj
return cloned
|
# Test
# Local settings for kegbot.
# Edit settings, then copy this file to /etc/kegbot/local_settings.py or
# ~/.kegbot/local_settings.py
# Disable DEBUG mode when serving external traffic.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
import os
### Database configuration
import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
### General
# Make this unique, and don't share it with anybody.
SECRET_KEY = os.environ['SECRET_KEY']
### Media and Static Files
AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']
AWS_QUERYSTRING_AUTH = False
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_S3_CUSTOM_DOMAIN = os.environ['AWS_S3_CUSTOM_DOMAIN']
KEGBOT_ROOT = ''
# Absolute path to the directory where uploaded media (profile pictures, etc)
# should go.
#MEDIA_ROOT = '/path/to/media/'
# URL of the directory above. The default is '/media/'. Note that the directory
# name given in MEDIA_ROOT does not affect this.
MEDIA_URL = '/media/'
# A directory where non-media static files will be stored. You should create
# this directory, and use 'kegbot collectstatic' to fill it.
STATIC_ROOT = ''
# URL of the directory above. The default is '/static/'. Note that the directory
# name given in STATIC_ROOT does not affect this.
STATIC_URL = 'http://' + os.environ['AWS_S3_CUSTOM_DOMAIN'] + '/'
### Cache
from memcacheify import memcacheify
CACHES = memcacheify()
### Celery
BROKER_URL = os.environ['REDIS_URL']
CELERY_RESULT_BACKEND = os.environ['REDIS_URL']
### Facebook
# Want to use Facebook Connect for registration/login? You will need to set
# these values up to the correct strings.
FACEBOOK_API_KEY = None
FACEBOOK_SECRET_KEY = None
### Twitter
TWITTER_CONSUMER_KEY = ''
TWITTER_CONSUMER_SECRET_KEY =''
### Foursquare
FOURSQUARE_CLIENT_ID = ''
FOURSQUARE_CLIENT_SECRET = ''
FOURSQUARE_REQUEST_PERMISSIONS = ''
### Untappd
# You'll need an API key from Untappd to enable Untappd features.
UNTAPPD_API_KEY = ''
GMT_OFFSET = '-5'
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Tell Kegbot use the SMTP e-mail backend.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# SMTP server hostname (default: 'localhost') and port (default: 25).
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_PORT = 25
# Credentials for SMTP server.
EMAIL_HOST_USER = os.environ['SENDGRID_USER']
EMAIL_HOST_PASSWORD = os.environ['SENDGRID_PASSWORD']
EMAIL_USE_SSL = False
EMAIL_USE_TLS = False
# "From" address for e-mails.
EMAIL_FROM_ADDRESS = 'kask@sendgrid.com'
|
def float_to_binary(f):
BINARY_LENGTH = 32
assert 0 <= f <= 1
binary = ['0' for i in range(32)]
base = 1.
for i in range(BINARY_LENGTH):
if f == 0:
break
base /= 2
if f >= base:
f -= base
binary[i] = '1'
if f != 0:
return None
else:
return ''.join(binary)
def binary_to_float(*bit_positions):
f = 0
for x in bit_positions:
f += 2**-x
return f
def test_1():
assert float_to_binary(0.72) is None
assert binary_to_float(1, 3, 7) == 0.6328125
assert float_to_binary(binary_to_float(1, 3, 7)) == '10100010000000000000000000000000'
|
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
"""
from setuptools import setup, find_packages
from mechanical_markdown import __version__ as version
# The text of the README file
README = ""
try:
with open("README.md", "r") as fh:
README = fh.read()
except FileNotFoundError:
pass
# This call to setup() does all the work
setup(
name="mechanical-markdown",
version=version,
description="Run markdown recipes as shell scripts",
long_description=README,
long_description_content_type="text/markdown",
url="https://github.com/dapr/mechanical-markdown",
author="Charlie Stanley",
author_email="Charlie.Stanley@microsoft.com",
license="MIT",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7"
],
packages=find_packages(exclude='tests'),
include_package_data=True,
install_requires=["termcolor", "pyyaml", "mistune", "requests", "colorama"],
entry_points={
"console_scripts": [
"mm.py = mechanical_markdown.__main__:main"
]
},
)
|
# Generated by Django 2.1.7 on 2019-03-31 17:37
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import main.fields
import main.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Block_Section',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('year', models.PositiveIntegerField(default=1, validators=[django.core.validators.MaxValueValidator(5), django.core.validators.MinValueValidator(1)])),
('section', models.CharField(max_length=4)),
],
),
migrations.CreateModel(
name='Prof',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('prof_img', models.ImageField(blank=True, null=True, upload_to=main.models.path_and_rename)),
('title', main.fields.StaffTitle(choices=[('1', 'Mr.'), ('2', 'Ms.'), ('3', 'Mrs.'), ('4', 'Engr.'), ('5', 'Dr.')], default=4, max_length=1)),
('first_name', models.CharField(max_length=30)),
('last_name', models.CharField(max_length=30)),
('role', main.fields.StaffRole(choices=[('1', 'Chairperson'), ('2', 'Staff')], default=2, max_length=1)),
('is_onleave', models.BooleanField(default=False)),
('biography', models.TextField()),
('email', models.EmailField(default='', max_length=40)),
('contact_number', models.IntegerField()),
],
),
migrations.CreateModel(
name='Room_Schedule',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('room_id', models.CharField(max_length=8)),
('day', main.fields.DayOfTheWeekField(choices=[('1', 'Monday'), ('2', 'Tuesday'), ('3', 'Wednesday'), ('4', 'Thursday'), ('5', 'Friday'), ('6', 'Saturday'), ('7', 'Sunday')], default=1, max_length=1)),
('start_time', models.TimeField(null=True)),
('end_time', models.TimeField(null=True)),
('block', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='main.Block_Section')),
],
),
migrations.CreateModel(
name='Subject',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('subject_code', models.CharField(max_length=16)),
('subject_title', models.CharField(max_length=50)),
],
),
migrations.AddField(
model_name='room_schedule',
name='subject',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='main.Subject'),
),
migrations.AddField(
model_name='prof',
name='schedule',
field=models.ManyToManyField(to='main.Room_Schedule'),
),
]
|
from django.urls import path
from .views import RealtorListView,RealtorView,TopSellerView
urlpatterns = [
path('',RealtorListView.as_view()),
path('topseller',TopSellerView.as_view()),
path('<pk>',RealtorView.as_view())
]
|
#Iris Identification
import numpy as np
import csv
syn=[]
X=[]
y=[]
def getData():
data=[]
with open('../data/006/iris.csv','r') as f:
spamreader=csv.reader(f)
for row in spamreader:
i=[]
for thing in row:
i.append(float(thing))
data.append(i)
for k in range(150):
i=[]
for j in range(4):
i.append(data[k][j])
i.append(1)
X.append(i)
o=[]
for j in range(4,7):
o.append(data[k][j])
y.append(o)
def train(n,iter_n):
for j in range(iter_n):
l=[]
l.append(X)
g=1
while g<(n+2):
l.append(nonlin(np.dot(l[g-1],syn[g-1])))
g+=1
# Back propagation of errors using the chain rule.
errors = []
deltas = []
#Top level error and delta
top_error = y - l[n+1]
errors.append(top_error)
top_delta = top_error*nonlin(l[n+1],deriv=True)
deltas.append(top_error)
#Deeper level error and delta
for k in range(n):
e=deltas[k].dot(syn[n-k].T)
errors.append(e)
d=e*nonlin(l[n-k],deriv=True)
deltas.append(d)
#Original for n=3
#l4_error = y - l[4]
#l4_delta = l4*nonlin(l[4],deriv=True)
#l3_error = l4_delta.dot(syn[3].T)
#l3_delta = l3_error*nonlin(l[3],deriv=True)
#l2_error = l3_delta.dot(syn[2].T)
#l2_delta = l2_error*nonlin(l[2], deriv=True)
#l1_error = l2_delta.dot(syn[1].T)
#l1_delta = l1_error * nonlin(l[1],deriv=True)
if(j % 1) == 0: # Only print the error every 10000 steps, to save time and limit the amount of output.
print("Error: ",str(np.mean(np.abs(top_error))))
#update weights (no learning rate term)
for k in range(n+1):
#print(l[k])
syn[k] += np.transpose(l[k]).dot(deltas[n-k])
#Original for n=3
#syn[3] += l[3].T.dot(l4_delta)/2
#syn[2] += l[2].T.dot(l3_delta)/2
#syn[1] += l[1].T.dot(l2_delta)/2
#syn[0] += l[0].T.dot(l1_delta)/2
def build(numIn,numOut,numHiddenLayers,numNeuronsHidden):
last=numIn
#np.random.seed(1)
for i in range(numHiddenLayers):
syn.append(2*np.random.random((last,numNeuronsHidden))-1)
last = numNeuronsHidden
syn.append(2*np.random.random((last,numOut))-1)
def test(n):
l=[]
l.append(X)
g=1
while g<(n+2):
l.append(nonlin(np.dot(l[g-1], syn[g-1])))
g+=1
print(l[n+1])
def nonlin(x, deriv=False):
if(deriv==True):
return (x*(1-x))
return 1/(1+np.exp(-x))
def main():
numInputs=5
#2 inputs plus a bias
numOutputs=3
#And, Or, and Xor
n=1
k=10
getData()
for a in range(150):
print(X[a])
print(y[a])
#build(numInputs,numOutputs,n,k)
#train(n,100000)
#test(n)
#Next steps
#-Program Persistance (save to file and load weights)
#-Allow inputing of inputs and outputs for training
#-Separating data into test and train data inputs and outputs
#-Learning rate to get faster results(?)
#-Speed(?)
#-Apply to something(?)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.