branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>JerryBluesnow/PythonLearning<file_sep>/multi_process_thread/multi_thread_2.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
# 多线程 -
# 死锁
# mutex = threading.Lock()
# mutex.acquire([timeout])
# mutex.release()
# 同步阻塞
#-------------------------------------------------------------------------------------------#
# encoding: UTF-8
import threading
import time
class MyThread(threading.Thread):
def do1(self):
global resA, resB
if mutexA.acquire():
msg = self.name+' got resA'
print msg
if mutexB.acquire(1):
msg = self.name+' got resB'
print msg
mutexB.release()
mutexA.release()
def do2(self):
global resA, resB
if mutexB.acquire():
msg = self.name+' got resB'
print msg
if mutexA.acquire(1):
msg = self.name+' got resA'
print msg
mutexA.release()
mutexB.release()
def run(self):
self.do1()
self.do2()
resA = 0
resB = 0
mutexA = threading.Lock()
mutexB = threading.Lock()
def test():
for i in range(5):
t = MyThread()
t.start()
if __name__ == '__main__':
test()<file_sep>/stock/stock2/stock/getRealtimeData.py
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
##############################################################################
# version 1.0:
# add thread,
# add ctrl+c to control the quit
#
##############################################################################
"""This script parse stock info"""
import tushare as ts
import sys
import pandas as pd
import time
import datetime
import threading
from threading import Event
import signal
import os
import inspect
import ctypes
import itertools
import platform
def get_all_price(code_list):
'''process all stock'''
global final_df
df = ts.get_realtime_quotes(STOCK)
#print df[['code','price','pre_close','ask','volume','amount','time']]
#final_df = pd.DataFrame()
index = 0
for index in range(0, len(STOCK)):
final_df = final_df.append(
pd.DataFrame([[df.loc[index,'code'],
df.loc[index,'pre_close'],
df.loc[index,'open'],
df.loc[index,'price'],
df.loc[index,'high'],
df.loc[index,'low'],
df.loc[index,'time'],
format( float(df.loc[index,'price']) * 100 / float(df.loc[index,'pre_close']) - 100, '.2f')]],
columns = list(['code', 'pre_close', 'open', 'price', 'high', 'low', 'time', 'rate']) ,
index=[index]))
return final_df
class Producer(threading.Thread):
def run(self):
global is_exit
global final_df
#final_df = pd.DataFrame()
while True:
if cond.acquire():
if is_exit: #每次获取锁之后,先检查全局状态变量
cond.notifyAll() #退出前必须唤醒其他所有线程
cond.release() #退出前必须释放锁
break
if len(final_df) > 0:
cond.wait()
else:
final_df = get_all_price(STOCK)
cond.notify()
cond.release()
def wait_loop(interval):
global is_exit
second_hand = 0
while True:
print second_hand,
time.sleep(2)
second_hand = second_hand + 2
if second_hand >= interval:
break
if is_exit == True:
break
print second_hand
class Consumer(threading.Thread):
def run(self):
global is_exit
global final_df
while True:
if cond.acquire():
if is_exit:
cond.notifyAll()
cond.release()
break
if len(final_df) == 0:
cond.wait()
else:
sysstr = platform.system()
if(sysstr =="Windows"):
os.system('cls')
elif(sysstr == "Linux"):
os.system('clear')
else:
os.system('clear')
print "=========================",datetime.datetime.now(),"=================================="
print final_df
# after print, need to clear the content in the DataFrame final_df
final_df.drop(final_df.index,inplace=True)
wait_loop(REPORT_INTERVAL) # wait 60 seconds to get data
cond.notify()
cond.release()
REPORT_INTERVAL = 60 # wait for one minutes
cond = threading.Condition()
is_exit = False #全局变量
def signal_handler(signum, frame): #信号处理函数
global is_exit
is_exit = True #主线程信号处理函数修改全局变量,提示子线程退出
print "" # make sure below information be printed in a new line
print "Exit from the process...."
def test():
global final_df
final_df = pd.DataFrame()
producers = []
consumers = []
for i in xrange(4):
p = Producer()
producers.append(p)
p.setDaemon(True) #子线程daemon
p.start()
for j in xrange(2):
c = Consumer()
consumers.append(c)
c.setDaemon(True) #子线程daemon
c.start()
while 1:
alive = False
for t in itertools.chain(producers, consumers): #循环检查所有子线程
alive = alive or t.isAlive() #保证所有子线程退出
if not alive:
break
STOCK = ['000651',
'000750',
'002470',
'002594',
'300119',
'600016',
'600326',
'601360',
'603888']
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal_handler) #注册信号处理函数
signal.signal(signal.SIGTERM, signal_handler) #注册信号处理函数
test()<file_sep>/multi_process_thread/simulate_web_sipder.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
#
#-------------------------------------------------------------------------------------------#
import threading # 导入线程包
import time
detail_url_list = []
# 爬取文章详情页
def get_detail_html(detail_url_list, id):
while True:
if len(detail_url_list)==0: # 列表中为空,则等待另一个线程放入数据
continue
url = detail_url_list.pop()
time.sleep(2) # 延时2s,模拟网络请求
print("thread {id}: get {url} detail finished".format(id=id,url=url))
# 爬取文章列表页
def get_detail_url(detail_url_list):
for i in range(10000):
time.sleep(1) # 延时1s,模拟比爬取文章详情要快
detail_url_list.append("http://projectedu.com/{id}".format(id=i))
print("get detail url {id} end".format(id=i))
if __name__ == "__main__":
# 创建读取列表页的线程
thread = threading.Thread(target=get_detail_url, args=(detail_url_list,))
# 创建读取详情页的线程
html_thread= []
for i in range(4):
thread2 = threading.Thread(target=get_detail_html, args=(detail_url_list,i))
html_thread.append(thread2)
start_time = time.time()
# 启动两个线程
thread.start()
for i in range(4):
html_thread[i].start()
# 等待所有线程结束
thread.join()
for i in range(4):
html_thread[i].join()
print("last time: {} s".format(time.time()-start_time))<file_sep>/gamefucker/C_hook.md
# This is for C HOOK for Game
# [全系统注入-游戏安全实验室](http://gslab.qq.com/article-204-1.html)
# [游戏修改器制作教程七:注入DLL的各种姿势](http://blog.csdn.net/xfgryujk/article/details/50478295)
# [游戏注入教程(一)--远程线程注入](http://blog.csdn.net/wyansai/article/details/52077963)
# [农民工の博客-5篇文章](http://blog.csdn.net/wyansai/article/category/6328876)
# [郁金香外挂技术](http://www.yjxsoft.com/forum.php?mod=forumdisplay&fid=4)
# [外挂制作技术](http://blog.sina.com.cn/s/articlelist_1457737921_0_1.html)
# [[视频]编写代码读取游戏数据-注入DLL](http://www.iqiyi.com/w_19rteanr1h.html)
# [[讨论]绕开游戏对全局钩子的检测](http://bbs.csdn.net/topics/370046194)
# [游戏外挂编程之神器CE的使用 ](http://www.cnblogs.com/egojit/archive/2013/06/14/3135147.html)
# [游戏外挂编程三之游戏进程钩子](https://www.cnblogs.com/egojit/archive/2013/06/16/3138266.html)
# [HOOK钩子的概念](https://jingyan.baidu.com/article/e75aca855afa03142fdac643.html)
# [HOOK钩子教程](http://blog.sina.com.cn/s/blog_651cccf70100tkv6.html)
# [多线程防关,防杀,防删除自身保护程序编写思路](https://www.2cto.com/kf/201002/44758.html)
# [如何让你的程序避开全局键盘钩子的监视](http://blog.okbase.net/BlueSky/archive/3839.html)
# [[CSDN]API HOOK 全局钩子, 防止进程被杀](http://download.csdn.net/download/lygf666/4164019)
# [XueTr这个牛B工具的进程钩子检测如何实现??](https://bbs.pediy.com/thread-163373.htm)
# [[知乎]Win10下用SetWindowsHookEx设置钩子后部分进程假死?](https://www.zhihu.com/question/64221483)
# [SetWindowsHookEx为某个进程安装钩子](http://blog.csdn.net/hczhiyue/article/details/18449455)
# [HOOK API(四)—— 进程防终止](https://www.cnblogs.com/fanling999/p/4601118.html)
# [PChunter里边有个扫描指定进程中所有钩子的功能,原理是什么?](https://bbs.pediy.com/thread-210688.htm)
# [GOON](http)
# [GOON](http)
# [GOON](http)
# [GOON](http)
# [GOON](http)
# [GOON](http)
# [GOON](http)
# [GOON](http)
# Tips
## 驱动级注入
教程:1、打开驱动级别的dll注入器.exe 2、加载驱动 填写要操作的进程名 填写要注入 dll的路径 3 点设置完毕 注意不要关掉
可以打开要注入的进程测试一下,可注入大部分有保护的游戏
## 游戏应用层钩子
1. 直接加载驱动的办法过掉钩子,不需要什么XT
2. 代码直接注入到游戏进程
3. 好像很多游戏把钩子什么的都屏蔽了吧,话说我也不怎么懂啊
@ 春色园
是的,但是普通游戏是没有屏蔽掉的。即使屏蔽了我们还是有其它办法把我们的代码写入游戏 内存。只要技术够牛连Windows系统内核占据的内存都可以操作,何况运行在windows下的游戏进程内存??
4. LPWSTR s1=(LPWSTR)(LPCTSTR)txt_prc_name;
好丑的代码,建议楼主以后不要用这样的代码了。丑陋不说,还有重大隐患。正确做法是使用 CString::GetBuffer.外挂除了实现功能外最重要是稳定,一些细节你不注意你的外挂就没 市场了。
说到代码的健壮性,还有你的SetHook 形参没必要用LPWSTR啊,直接LPCWSTR就OK,更好的 是LPCTSTR。
建议楼主打好扎实的基础知识,走稳了再跑。
话可能有些不好听,请见谅
<file_sep>/pmkpi_parse/pmkpi_parse.1.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
import sys
#tree = ET.parse(sys.argv[1])
import xml.dom.minidom
DOMTree = xml.dom.minidom.parse(sys.argv[1])
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
print("Root element : %s" % collection.getAttribute("type"))
# get attribute of an element
measInfos = collection.getElementsByTagName("measInfo")
# get child elements' collection by tag name
for measInfo in measInfos:
print "======================measInfo======================"
# get granPeriod
granPeriod = measInfo.getElementsByTagName('granPeriod')[0]
print "granPeriod",
if granPeriod.hasAttribute("duration"):
print "duration=%s" % granPeriod.getAttribute("duration"),
if granPeriod.hasAttribute("endTime"):
print "endTime=%s" % granPeriod.getAttribute("endTime")
# get measType name in loop
measTypeList = measInfo.getElementsByTagName('measType')
for measTypeItem in measTypeList:
print "measType: %s" % measTypeItem.childNodes[0].data
# get measType value in loop
measValueList = measInfo.getElementsByTagName('measValue')
for measValueItem in measValueList:
if measValueItem.hasAttribute("measObjLdn"):
print "measValue measObjLdn=%s" % measValueItem.getAttribute("measObjLdn")
rvalueList = measValueItem.getElementsByTagName('r')
for rvalueItem in rvalueList:
if rvalueItem.hasAttribute("p"):
print "r p=%s" % rvalueItem.getAttribute("p"),
print "rvalue=%s" % rvalueItem.childNodes[0].data
#parser.parse(sys.argv[1])<file_sep>/PhoneOP/python.selenium.md
+ [python selenium TouchAction模拟移动端触摸操作(十八)](https://www.cnblogs.com/mengyu/p/8136421.html)
+ [python 自动生成useragent/User-Agent方法全解析](https://www.jb51.cc/python/538552.html)
+ [谷歌修改useragent,chrome模拟微信、QQ内置浏览器](https://blog.csdn.net/two_too/article/details/96099019)
+ [利用Chrome在PC电脑上模拟微信内置浏览器](https://blog.csdn.net/xialong_927/article/details/95180583)
+ [selenium+python配置chrome浏览器的选项](https://blog.csdn.net/zwq912318834/article/details/78933910)
+ [查找User-Agent](http://www.fynas.com/ua)
+ [TouchAction实现连续滑动设置手势密码](https://www.cnblogs.com/bendouyao/p/9462788.html)
+ [find_element_by_xpath()的6种方法](https://www.cnblogs.com/liangblog/p/11943877.html)
## 安卓微信内置浏览器 UA:
Mozilla/5.0 (Linux; Android 5.0; SM-N9100 Build/LRX21V) > AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 > Chrome/37.0.0.0 Mobile Safari/537.36 > MicroMessenger/6.0.2.56_r958800.520 NetType/WIFI
## IOS 微信内置浏览器 UA:
Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) > AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D257 > MicroMessenger/6.0.1 NetType/WIFI
## TouchAction提供的方法:
```
double_tap(on_element) #双击
flick_element(on_element, xoffset, yoffset, speed) #从元素开始以指定的速度移动
long_press(on_element) #长按不释放
move(xcoord, ycoord) #移动到指定的位置
perform() #执行链中的所有动作
release(xcoord, ycoord) #在某个位置松开操作
scroll(xoffset, yoffset) #滚动到某个位置
scroll_from_element(on_element, xoffset, yoffset) #从某元素开始滚动到某个位置
tap(on_element) #单击
tap_and_hold(xcoord, ycoord) #某点按住
```
<file_sep>/cdr_to_csv/python.time.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
import datetime
import os
if __name__ == "__main__":
# make 10 seconds as a different, to make it exact in 5
current_time = datetime.datetime.now()
current_time.strftime('%m%d%H%M%S')
second = current_time.strftime('%S')
minute = current_time.strftime('%M')
hour = current_time.strftime('%H')
minute_offset = int(minute) % 5
if minute_offset == 0 and int(second) < 50:
print 0
os._exit(0)
minute_offset = 5 - minute_offset
wait_seconds = minute_offset * 60 - int(second)
wait_seconds = wait_seconds + 10
print wait_seconds<file_sep>/parseHTTP.py
# encoding:utf-8
import json
import re
import sys
import os
import os.path
from optparse import OptionParser
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
def menu():
parser = OptionParser(usage = '''''')
parser.add_option('-f', '--file', dest='file', action='store',
help="master log")
parser.add_option('-r', '--regex', dest='regex', action='store_true',
help="use regular express to match, instead of the default 'glob'")
parser.add_option('-v', '--invert',dest='invert',action='store_true',
help="invert the logic. (match is not match, vice versa)")
parser.add_option('-t', '--topline', dest='topline', action='store',
help="HTTP message topline")
parser.add_option('-p', '--param', dest='param', action='store',
help="searched key")
parser.add_option('-H', '--Header', dest='header', action='store',
help="searched header")
(options, args) = parser.parse_args()
if not options.file or not os.path.exists(options.file):
print("invalid input log file, please check:")
sys.exit(1)
if not options.topline:
print("invalid input topline, please check:" + options.file)
sys.exit(1)
return options.file, options.topline, options.param, options.header
def parseHTTPJsonContent(file, topline, param):
with open(file) as file_obj:
contents = file_obj.read()
json_content = re.findall(topline + '.*HTTP/1.1.*[\r\n](.*^{.*[\r\n]^})', contents, re.S|re.M)
if not json_content:
print("Unmatched")
sys.exit()
json2parse = json_content[0].replace('\r', '').replace('\n', '')
#print(json_content[0])
if is_json(json2parse) == False:
print("invalid Json Format")
sys.exit()
strDict = json.loads(json2parse)
search_str = param.split('.')
if len(search_str) == 1:
if search_str[0] not in strDict.keys():
print("Invalid Key:" + search_str[0])
sys.exit(0)
print(strDict[search_str[0]])
elif len(search_str) == 2:
if search_str[0] not in strDict.keys():
print("Invalid Key:" + search_str[0])
sys.exit(0)
if search_str[1] not in strDict[search_str[0]].keys():
print("Invalid Key:" + search_str[1])
sys.exit(0)
print(strDict[search_str[0]][search_str[1]])
elif len(search_str) == 3:
if search_str[0] not in strDict.keys():
print("Invalid Key:" + search_str[0])
sys.exit(0)
if search_str[1] not in strDict[search_str[0]].keys():
print("Invalid Key:" + search_str[1])
sys.exit(0)
if search_str[2] not in strDict[search_str[0]][search_str[1]].keys():
print("Invalid Key:" + search_str[2])
sys.exit(0)
print(strDict[search_str[0]][search_str[1]][search_str[2]])
elif len(search_str) == 4:
if search_str[0] not in strDict.keys():
print("Invalid Key:" + search_str[0])
sys.exit(0)
if search_str[1] not in strDict[search_str[0]].keys():
print("Invalid Key:" + search_str[1])
sys.exit(0)
if search_str[2] not in strDict[search_str[0]][search_str[1]].keys():
print("Invalid Key:" + search_str[2])
sys.exit(0)
if search_str[3] not in strDict[search_str[0]][search_str[1]][search_str[2]].keys():
print("Invalid Key:" + search_str[2])
sys.exit(0)
print(strDict[search_str[0]][search_str[1]][search_str[2]][search_str[3]])
def parseHTTPHeader(file, topline, param, header):
match_str = '(' + topline + '.*HTTP/1.1.*[\r\n].*^{.*[\r\n]^})'
with open(file) as file_obj:
contents = file_obj.read()
http_content = re.findall(match_str, contents, re.S|re.M)
if not http_content:
print("Unmatched")
sys.exit()
header_content = re.findall(header + ':(.*$)', http_content[0], re.M)
print(header_content[0].replace('\r', '').replace('\n', '').replace(' ', ''))
if __name__ == '__main__':
file, topline, param, header = menu()
http_raw_file = file + '.http'
if not os.path.exists(http_raw_file):
os.system('grep -A100 "HTTP\/.\.." '+ file + ' > ' + file + '.http')
if header:
parseHTTPHeader(http_raw_file, topline, param, header)
sys.exit(0)
parseHTTPJsonContent(http_raw_file, topline, param)
sys.exit(0)
<file_sep>/5seconds_sync.1.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
#----The script the created to simulate IBCF 5 seconds mcast sync mechanism to optimize the
#----factor in th vailable capacity allocation
#-------------------------------------------------------------------------------------------#
# version 1.0
#-------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------#
'''
Usage:
python 5seconds_sync.py -c 4000 -n 10 -l 20 -f 0.9
Tips:
'''
import sys
import time
import datetime
import csv
import codecs
import os
#from numpy import *
import random
import threading
import logging
import logging.handlers
from optparse import OptionParser
# if run out of disk, CDR decode will error, could not go further to proceed
Sync_Data_Flag = False
# the five interval multi-cast used
SYNC_INTERVAL = 5
# the global dict to save all instances' local_usage
global_dict_usage = {}
# the global dict to mark if all instances has alreay sync the data and calculate the upper_bound
global_dict_updated = {}
# the global dict to mark if the upper_bound has been run out in the specified instance
global_dict_runout = {}
#the global dict to save local_usage, pre_local_usage, prepre_local_usage for specified instance
global_dict_local_record = {}
class Logger_Handler(object):
def __init__(self, logger_name):
'''
logger_name must in string format
'''
try:
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename=logger_name,
filemode='w')
self.logger = logging.getLogger('LOG')
self.logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter)
file_handler = logging.FileHandler(logger_name)
file_handler.setLevel(logging.INFO)
#file_handler.setFormatter(formatter)
# create logger
self.logger.addHandler(console_handler)
self.logger.addHandler(file_handler)
except:
self.logger = None
return
CDR_LOG = Logger_Handler('5seconds_sync.log').logger
def create_global_dict_local_record(_index):
global global_dict_local_record
local_record = {}
local_record[0] = 0
local_record[1] = 0
local_record[2] = 0
local_record[3] = 0
global_dict_local_record[_index] = local_record
def update_global_dict_local_record(_index, _value):
global global_dict_local_record
local_record = global_dict_local_record[_index]
local_record[2] = local_record[1]
local_record[1] = local_record[0]
local_record[0] = _value
def main():
'''All parameters are mandatory, please make sure they are used'''
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-c", "--capacity", dest="capacity", default='4000',
help="_system_capacity")
parser.add_option("-n", "--nservers", dest="nservers",
help="_nservers: server instance count")
parser.add_option("-l", "--load_per_s", dest="load_per_s",
help="load_per_s: load per second")
parser.add_option("-f", "--factor", dest="factor",
help="factor: factor in formula")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose")
(options, args) = parser.parse_args()
if CDR_LOG is None:
logging.critical("Could not create log handler, exit")
return
CDR_LOG.info("system_capacity=%s, nServers=%s, load_per_seconds=%s, formula_factor=%s", options.capacity, options.nservers, options.load_per_s, options.factor)
system_capacity = int(options.capacity)
nservers = int(options.nservers)
load_per_s = int(options.load_per_s)
factor = float(options.factor)
global global_dict_updated
global global_dict_runout
global global_dict_usage
global Sync_Data_Flag
global global_dict_local_record
# CREATE CHILD THREAD TO MAKE CALLS, SYNC, re-ALLOCATION
threads_list = []
instance_index = 0
while instance_index < int(options.nservers):
thread_identify = threading.Thread(target=ibcf_call_process_instance,args=(system_capacity, nservers, load_per_s, instance_index, factor, ))
threads_list.append(thread_identify)
global_dict_updated[instance_index] = False
global_dict_runout[instance_index] = False
create_global_dict_local_record(instance_index)
CDR_LOG.debug("create instance_index=%d", instance_index)
instance_index = instance_index + 1
for thread_identify in threads_list:
thread_identify.setDaemon(True)
thread_identify.start()
# check diskusage to determine to stop child thread
Sync_Data_Flag = False
first_timestamp = datetime.datetime.now()
internal_interval = (SYNC_INTERVAL-0.2) * 1000
CDR_LOG.info("start to make call[+++++++++++++++++++++++++++++++++++++++++++]")
while True:
# sleep INTEVAL to let child thread make calls
if datetime.datetime.now() < first_timestamp + datetime.timedelta(milliseconds = internal_interval):
continue
# child instance finish making call in one INTERVAL, should let child update its local to global
Sync_Data_Flag = True
# if all instances run out of the allocation capacity
stop_process_flag = True
for value in global_dict_runout.values():
stop_process_flag = stop_process_flag & value
if stop_process_flag == True:
total_system_usage = 0
for value in global_dict_usage.values():
total_system_usage = total_system_usage + value
CDR_LOG.warning("system_usage=%d, system_capacity=%d, deviation=%f", total_system_usage, system_capacity, total_system_usage/float(system_capacity) - 1.0)
break
# check if all instances updation finish
flag = True
while flag == True:
flag = True
for value in global_dict_updated.values():
flag = value & flag
if flag == True:
# update timestamp
first_timestamp = datetime.datetime.now()
CDR_LOG.info("sync done! reset sync timer[+++++++++++++++++++++++++++++++++++++++++++]")
# reset all flags
Sync_Data_Flag = False
for key in global_dict_updated.keys():
global_dict_updated[key] = False
break
# when parent thread quit, the child thread will quit
for thread_identify in threads_list:
thread_identify.join()
return 0
def allocation_algorithm(_system_capacity, _nservers, _local_usage, _system_usage, _factor):
if _nservers == 0:
return 0
if _nservers == 1 or _system_capacity == 0:
return _system_capacity
available = _system_capacity - _system_usage
my_usage_fraction = 1.0
if _system_usage != 0:
my_usage_fraction = float(_local_usage) / float(_system_usage)
my_allocation = my_usage_fraction * available
if available >= 0:
my_allocation_fraction = max((_factor * my_usage_fraction), 1.0/_nservers)
my_allocation = min(my_allocation_fraction, 1.0) * available
upper_bound = _local_usage + my_allocation
CDR_LOG.debug("_system_capacity=%d, _nservers=%d, _local_usage=%d, _system_usage=%d, allocation_upper_bound=%d",_system_capacity, _nservers, _local_usage, _system_usage, upper_bound)
return upper_bound
def ibcf_call_process_instance(_system_capacity, _nservers, _load_per_s, _thread_index, _factor):
global Sync_Data_Flag
global global_dict_runout
local_usage = 0
interval_start_timestamp = datetime.datetime.now()
first_timestamp = datetime.datetime.now()
up_bound = _system_capacity
while local_usage < up_bound:
if global_dict_updated[_thread_index] == True:
continue
if Sync_Data_Flag == False:
if datetime.datetime.now() >= first_timestamp + datetime.timedelta(milliseconds=1000/_load_per_s) :
first_timestamp = datetime.datetime.now()
local_usage = local_usage + random.randint(0,3)
CDR_LOG.debug("[instance: %d]: make a new call, local_usage=%d, up_bound=%d", _thread_index, local_usage, up_bound)
continue
else:
# start to sync data
CDR_LOG.debug("[instance: %d]: %d seconds, start sync", _thread_index, SYNC_INTERVAL)
global_dict_usage[_thread_index] = local_usage
# wait for all instance has update local_usage to global
time.sleep(0.005)
# system usage for individual instance may be different, but close
system_usage = 0
for value in global_dict_usage.values():
system_usage = system_usage + value
# need Algorithm to adjust up_bound per SYNC_INTERVAL
up_bound = allocation_algorithm(_system_capacity, _nservers, local_usage, system_usage, _factor)
#up_bound = allocation_algorithm_2(_system_capacity, _nservers, local_usage, system_usage, _factor, _thread_index)
CDR_LOG.info("[instance: %d]: local_usage=%d, system_usage=%d, up_bound=%d, offset=%f", _thread_index, local_usage, system_usage, up_bound, system_usage/float(_system_capacity) - 1.0)
global_dict_updated[_thread_index] = True
continue
global_dict_updated[_thread_index] = True
global_dict_runout[_thread_index] = True
global_dict_usage[_thread_index] = local_usage
return # retrn from function: ibcf_call_process_instance
def allocation_algorithm_2(_system_capacity, _nservers, _local_usage, _system_usage, _factor, _index):
global global_dict_local_record
update_global_dict_local_record(_index, _local_usage)
record = global_dict_local_record[_index]
factor_A = 1.0
if record[0] == 0 and record[1] == 0 and record[2] == 0:
factor_A = 1.0
elif record[1] == 0 and record[2] == 0:
factor_A = 1.0
else:
factor_A = (record[1] - record[2]) / float(record[0] - record[1])
if record[0] != 0:
#factor_A = factor_A * (_local_usage / float(_system_usage)) * _system_capacity / float(record[0] * _nservers * 100)
factor_A = factor_A * (_local_usage / float(_system_usage)) * (1 - float((record[0] - record[1]) * _nservers) / _system_capacity)
#upper_bound = _system_capacity * factor_A
#upper_bound = (0.005 / _nservers ) * _system_capacity + _system_capacity / _nservers
upper_bound = _system_capacity * factor_A
return upper_bound
if __name__ == "__main__":
CDR_LOG.info("+++++++++++++++++++++++++++++++START the Script++++++++++++++++++++++++++++++++")
main()
CDR_LOG.info("+++++++++++++++++++++++++++++++Quit From the Script++++++++++++++++++++++++++++")
<file_sep>/jdBuyMask-master/jdBuyMask_V2.py
# -*- coding=utf-8 -*-
'''
2020/2/13
(避免滥用,代码已经废弃,现已不更新,有需要请适量使用exe版本)
京东抢购商品程序
通过商品的skuid、地区id抢购
'''
import sys
import io
import schedule
import requests
from bs4 import BeautifulSoup
from config import Config
from jdProgram import *
from message import message
from util import getconfigMd5, _setDNSCache
import threading
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
global cookies_String, mail, sc_key, messageType, modelType, area, skuidsString, skuids, captchaUrl, eid, fp, payment_pwd
global scheduled_time_start
global scheduled_time_end
global quit_scripts_falg
def getconfig():
global cookies_String, mail, sc_key, messageType, modelType, area, skuidsString, skuids, captchaUrl, eid, fp, payment_pwd
global scheduled_time_start
global scheduled_time_end
global quit_scripts_falg
quit_scripts_falg = False
global_config = Config()
# cookie 网页获取
cookies_String = global_config.getRaw('config', 'cookies_String')
# 有货通知 收件邮箱
mail = global_config.getRaw('config', 'mail')
# 方糖微信推送的key 不知道的请看http://sc.ftqq.com/3.version
sc_key = global_config.getRaw('config', 'sc_key')
# 推送方式 1(mail)或 2(wechat)
messageType = global_config.getRaw('config', 'messageType')
# 下单模式
modelType = global_config.getRaw('V2', 'model')
# 地区id
area = global_config.getRaw('config', 'area')
# 脚本开始检测时间end
scheduled_time_start = global_config.getRaw('Schedule', 'scheduled_time_start')
# 脚本开始检测时间
scheduled_time_end = global_config.getRaw('Schedule', 'scheduled_time_end')
# 商品id
skuidsString = global_config.getRaw('V2', 'skuids')
skuids = str(skuidsString).split(',')
# 验证码服务地址
captchaUrl = global_config.getRaw('Temporary', 'captchaUrl')
if not modelType:
logger.error('请在configDemo.ini文件填写下单model')
if len(skuids[0]) == 0:
logger.error('请在configDemo.ini文件中输入你的商品id')
sys.exit(1)
'''
备用
'''
# eid
eid = global_config.getRaw('Temporary', 'eid')
fp = global_config.getRaw('Temporary', 'fp')
# 支付密码
payment_pwd = global_config.getRaw('config', 'payment_pwd')
# 初次
configTime = int(time.time())
getconfig()
configMd5 = getconfigMd5()
message = message(messageType=messageType, sc_key=sc_key, mail=mail)
is_Submit_captcha = False
submit_captcha_rid = ''
submit_captcha_text = ''
encryptClientInfo = ''
submit_Time = 0
session = requests.session()
session.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Connection": "keep-alive"
}
checksession = requests.session()
checksession.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Connection": "keep-alive"
}
manual_cookies = {}
def get_tag_value(tag, key='', index=0):
if key:
value = tag[index].get(key)
else:
value = tag[index].text
return value.strip(' \t\r\n')
for item in cookies_String.split(';'):
name, value = item.strip().split('=', 1)
# 用=号分割,分割1次
manual_cookies[name] = value
# 为字典cookies添加内容
cookiesJar = requests.utils.cookiejar_from_dict(manual_cookies, cookiejar=None, overwrite=True)
session.cookies = cookiesJar
def validate_cookies():
for flag in range(1, 3):
try:
targetURL = 'https://order.jd.com/center/list.action'
payload = {
'rid': str(int(time.time() * 1000)),
}
resp = session.get(url=targetURL, params=payload, allow_redirects=False)
if resp.status_code == requests.codes.OK:
logger.info('校验是否登录[成功]')
return True
else:
logger.info('校验是否登录[失败]')
logger.info('请在configDemo.ini文件下更新cookie')
time.sleep(5)
continue
except Exception as e:
logger.info('第【%s】次请重新获取cookie', flag)
time.sleep(5)
continue
message.sendAny('脚本登录cookie失效了,请重新登录')
sys.exit(1)
def getUsername():
userName_Url = 'https://passport.jd.com/new/helloService.ashx?callback=jQuery339448&_=' + str(
int(time.time() * 1000))
session.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Referer": "https://order.jd.com/center/list.action",
"Connection": "keep-alive"
}
resp = session.get(url=userName_Url, allow_redirects=True)
resultText = resp.text
resultText = resultText.replace('jQuery339448(', '')
resultText = resultText.replace(')', '')
usernameJson = json.loads(resultText)
logger.info('登录账号名称[%s]', usernameJson['nick'])
'''
检查是否有货
'''
def check_item_stock(itemUrl):
response = session.get(itemUrl)
if (response.text.find('无货') > 0):
return True
if (response.text.find('此商品暂时售完') > 0):
return True
else:
return False
'''
取消勾选购物车中的所有商品
'''
def cancel_select_all_cart_item():
url = "https://cart.jd.com/cancelAllItem.action"
data = {
't': 0,
'outSkus': '',
'random': random.random()
}
resp = session.post(url, data=data)
if resp.status_code != requests.codes.OK:
print('Status: %u, Url: %s' % (resp.status_code, resp.url))
return False
return True
'''
购物车详情
'''
def cart_detail():
url = 'https://cart.jd.com/cart.action'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Referer": "https://order.jd.com/center/list.action",
"Host": "cart.jd.com",
"Connection": "keep-alive"
}
resp = session.get(url, headers=headers)
soup = BeautifulSoup(resp.text, "html.parser")
cart_detail = dict()
for item in soup.find_all(class_='item-item'):
try:
sku_id = item['skuid'] # 商品id
except Exception as e:
logger.info('购物车中有套装商品,跳过')
continue
try:
# 例如:['increment', '8888', '100001071956', '1', '13', '0', '50067652554']
# ['increment', '8888', '100002404322', '2', '1', '0']
item_attr_list = item.find(class_='increment')['id'].split('_')
p_type = item_attr_list[4]
promo_id = target_id = item_attr_list[-1] if len(item_attr_list) == 7 else 0
cart_detail[sku_id] = {
'name': get_tag_value(item.select('div.p-name a')), # 商品名称
'verder_id': item['venderid'], # 商家id
'count': int(item['num']), # 数量
'unit_price': get_tag_value(item.select('div.p-price strong'))[1:], # 单价
'total_price': get_tag_value(item.select('div.p-sum strong'))[1:], # 总价
'is_selected': 'item-selected' in item['class'], # 商品是否被勾选
'p_type': p_type,
'target_id': target_id,
'promo_id': promo_id
}
except Exception as e:
logger.error("商品%s在购物车中的信息无法解析,报错信息: %s,该商品自动忽略", sku_id, e)
logger.info('购物车信息:%s', cart_detail)
return cart_detail
'''
修改购物车商品的数量
'''
def change_item_num_in_cart(sku_id, vender_id, num, p_type, target_id, promo_id):
url = "https://cart.jd.com/changeNum.action"
data = {
't': 0,
'venderId': vender_id,
'pid': sku_id,
'pcount': num,
'ptype': p_type,
'targetId': target_id,
'promoID': promo_id,
'outSkus': '',
'random': random.random(),
# 'locationId'
}
session.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Referer": "https://cart.jd.com/cart",
"Connection": "keep-alive"
}
resp = session.post(url, data=data)
return json.loads(resp.text)['sortedWebCartResult']['achieveSevenState'] == 2
'''
添加商品到购物车
'''
def add_item_to_cart(sku_id):
url = 'https://cart.jd.com/gate.action'
payload = {
'pid': sku_id,
'pcount': 1,
'ptype': 1,
}
resp = session.get(url=url, params=payload)
if 'https://cart.jd.com/cart.action' in resp.url: # 套装商品加入购物车后直接跳转到购物车页面
result = True
else: # 普通商品成功加入购物车后会跳转到提示 "商品已成功加入购物车!" 页面
soup = BeautifulSoup(resp.text, "html.parser")
result = bool(soup.select('h3.ftx-02')) # [<h3 class="ftx-02">商品已成功加入购物车!</h3>]
if result:
logger.info('%s 已成功加入购物车', sku_id)
else:
logger.error('%s 添加到购物车失败', sku_id)
def get_checkout_page_detail():
"""获取订单结算页面信息
该方法会返回订单结算页面的详细信息:商品名称、价格、数量、库存状态等。
:return: 结算信息 dict
"""
url = 'http://trade.jd.com/shopping/order/getOrderInfo.action'
# url = 'https://cart.jd.com/gotoOrder.action'
payload = {
'rid': str(int(time.time() * 1000)),
}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Referer": "https://cart.jd.com/cart.action",
"Connection": "keep-alive",
'Host': 'trade.jd.com',
}
try:
resp = session.get(url=url, params=payload, headers=headers)
if not response_status(resp):
logger.error('获取订单结算页信息失败')
return ''
if '刷新太频繁了' in resp.text:
return '刷新太频繁了'
soup = BeautifulSoup(resp.text, "html.parser")
risk_control = get_tag_value(soup.select('input#riskControl'), 'value')
showCheckCode = get_tag_value(soup.select('input#showCheckCode'), 'value')
if not showCheckCode:
pass
else:
if showCheckCode == 'true':
logger.info('提交订单需要验证码')
global is_Submit_captcha, encryptClientInfo
encryptClientInfo = get_tag_value(soup.select('input#encryptClientInfo'), 'value')
is_Submit_captcha = True
order_detail = {
'address': soup.find('span', id='sendAddr').text[5:], # remove '寄送至: ' from the begin
'receiver': soup.find('span', id='sendMobile').text[4:], # remove '收件人:' from the begin
'total_price': soup.find('span', id='sumPayPriceId').text[1:], # remove '¥' from the begin
'items': []
}
logger.info("下单信息:%s", order_detail)
return risk_control
except requests.exceptions.RequestException as e:
logger.error('订单结算页面获取异常:%s' % e)
except Exception as e:
logger.error('下单页面数据解析异常:%s', e)
return ''
'''
下柜商品检测
'''
def item_removed(sku_id):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Referer": "http://trade.jd.com/shopping/order/getOrderInfo.action",
"Connection": "keep-alive",
'Host': 'item.jd.com',
}
url = 'https://item.jd.com/{}.html'.format(sku_id)
page = requests.get(url=url, headers=headers)
return '该商品已下柜' not in page.text
'''
购买环节
测试三次
'''
def normalModeBuyMask(sku_id):
cancel_select_all_cart_item()
cart = cart_detail()
if sku_id in cart:
logger.info('%s 已在购物车中,调整数量为 %s', sku_id, 1)
cart_item = cart.get(sku_id)
change_item_num_in_cart(
sku_id=sku_id,
vender_id=cart_item.get('vender_id'),
num=1,
p_type=cart_item.get('p_type'),
target_id=cart_item.get('target_id'),
promo_id=cart_item.get('promo_id')
)
else:
add_item_to_cart(sku_id)
risk_control = get_checkout_page_detail()
if risk_control == '刷新太频繁了':
return False
if len(risk_control) > 0:
if submit_order(session, risk_control, sku_id, skuids, submit_Time, encryptClientInfo, is_Submit_captcha,
payment_pwd, submit_captcha_text, submit_captcha_rid):
return True
return False
def fastModeBuyMask(sku_id):
add_item_to_cart(sku_id)
risk_control = get_checkout_page_detail()
if risk_control == '刷新太频繁了':
return False
if len(risk_control) > 0:
if submit_order(session, risk_control, sku_id, skuids, submit_Time, encryptClientInfo, is_Submit_captcha,
payment_pwd, submit_captcha_text, submit_captcha_rid):
return True
return False
'''
删除购物车选中商品
'''
def remove_item():
url = "https://cart.jd.com/batchRemoveSkusFromCart.action"
data = {
't': 0,
'null': '',
'outSkus': '',
'random': random.random(),
'locationId': '19-1607-4773-0'
}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.37",
"Accept": "application/json, text/javascript, */*; q=0.01",
"Referer": "https://cart.jd.com/cart.action",
"Host": "cart.jd.com",
"Content-Type": "application/x-www-form-urlencoded",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Encoding": "zh-CN,zh;q=0.9,ja;q=0.8",
"Origin": "https://cart.jd.com",
"Connection": "keep-alive"
}
resp = session.post(url, data=data, headers=headers)
logger.info('清空购物车')
if resp.status_code != requests.codes.OK:
print('Status: %u, Url: %s' % (resp.status_code, resp.url))
return False
return True
def select_all_cart_item():
url = "https://cart.jd.com/selectAllItem.action"
data = {
't': 0,
'outSkus': '',
'random': random.random()
}
resp = session.post(url, data=data)
if resp.status_code != requests.codes.OK:
print('Status: %u, Url: %s' % (resp.status_code, resp.url))
return False
return True
def normalModeAutoBuy(inStockSkuid):
for skuId in inStockSkuid:
if item_removed(skuId):
global submit_Time
submit_Time = int(time.time() * 1000)
logger.info('[%s]类型商品有货啦!马上下单', skuId)
skuidUrl = 'https://item.jd.com/' + skuId + '.html'
if normalModeBuyMask(skuId):
message.send(skuidUrl, True)
sys.exit(1)
else:
message.send(skuidUrl, False)
else:
logger.info('[%s]类型商品有货,但已下柜商品', skuId)
def fastModeAutoBuy(inStockSkuid):
for skuId in inStockSkuid:
global submit_Time
submit_Time = int(time.time() * 1000)
logger.info('[%s]类型商品有货啦!马上下单', skuId)
skuidUrl = 'https://item.jd.com/' + skuId + '.html'
if fastModeBuyMask(skuId):
message.send(skuidUrl, True)
sys.exit(1)
else:
if item_removed(skuId):
message.send(skuidUrl, False)
else:
logger.info('[%s]商品已下柜,商品列表中踢出', skuId)
skuids.remove(skuId)
select_all_cart_item()
remove_item()
def check_Config():
global configMd5, configTime
nowMd5 = getconfigMd5()
configTime = time.time()
if not nowMd5 == configMd5:
logger.info('配置文件修改,重新读取文件')
getconfig()
configMd5 = nowMd5
def normalMode():
global quit_scripts_falg
flag = 1
while (1):
if quit_scripts_falg == True:
logger.info('退出脚本')
sys.exit()
try:
if flag == 1:
validate_cookies()
getUsername()
# 检测配置文件是否修改
if int(time.time()) - configTime >= 60:
check_Config()
# modelType
logger.info('第' + str(flag) + '次 ')
flag += 1
# 检测库存
inStockSkuid = check_stock(checksession, skuids, area)
# 下单任务
normalModeAutoBuy(inStockSkuid)
# 休眠模块
timesleep = random.randint(1, 3) / 10
time.sleep(timesleep)
# 校验是否还在登录模块
if flag % 100 == 0:
logger.info('校验是否还在登录')
validate_cookies()
except Exception as e:
print(traceback.format_exc())
time.sleep(10)
def fastMode():
global quit_scripts_falg
flag = 1
while (1):
try:
if flag == 1:
validate_cookies()
getUsername()
select_all_cart_item()
remove_item()
# 检测配置文件修改
if int(time.time()) - configTime >= 600:
check_Config()
# modelType
logger.info('第' + str(flag) + '次 ')
flag += 1
# 检测库存
inStockSkuid = check_stock(checksession, skuids, area)
#inStockSkuid = [100012043978]
# 下单任务
fastModeAutoBuy(inStockSkuid)
# 休眠模块
timesleep = random.randint(1, 3) / 10
time.sleep(timesleep)
# 校验是否还在登录模块
if flag % 100 == 0:
logger.info('校验是否还在登录')
validate_cookies()
except Exception as e:
print(traceback.format_exc())
time.sleep(10)
def exitScript():
global quit_scripts_falg
quit_scripts_falg = True
def myMain():
# _setDNSCache()
if modelType == '2':
logger.info('V2版本当前模式[普通模式]')
normalMode()
elif modelType == '1':
logger.info('V2版本当前模式[极速模式]')
fastMode()
def normalModeInMultiProcess():
p1 = threading.Thread(target=normalMode, args=())
p1.start()
def fastModeInMultiProcess():
p2 = threading.Thread(target=fastMode, args=())
p2.start()
def exitScriptInMultiProcess():
p3 = threading.Thread(target=exitScript, args=())
p3.start()
schedule.every().day.at(scheduled_time_start).do(fastModeInMultiProcess)
logger.info('fastMode is scheduled at: ' + scheduled_time_start)
#schedule.every().day.at(scheduled_time_end).do(exitScriptInMultiProcess)
#logger.info('exitScript is scheduled at: ' + scheduled_time_end)
while True:
schedule.run_pending()<file_sep>/jdBuyMask-master/README.md
****
发现有人滥用,代码暂不更新了。
exe版本仅能购买一件,定时过期。
祝大家早点买到**自己所需**的口罩
****
使用方法 : https://blog.csdn.net/cyz52/article/details/104239558
## exe版本[口罩小助手] 最多添加99种口罩
链接:https://pan.baidu.com/s/1bgGXsH071GkHWGlLIwgRVw
提取码:do3f
看到有人在闲鱼转卖口罩,打码的接口已经改了
有需要的说明原因,加群要吧(1053467385)
祝大家早点买到口罩
.jpg)
.jpg)
避免抢购,程序自动一次只买一件
## V2版本(已不更新)
请在configDemo.ini 加入商品id、地区id、cookie等参数
区分下单模式(默认2正常模式)
**注意--极速模式默认清空购物车**
正常模式下单流程(1.7秒左右)
- [x] 检测有货
- [x] 检测下柜
- [x] 加入购物车
- [x] 查看购物车
- [x] 下单
极速模式下单流程(1.4秒左右)
- [x] 检测有货
- [x] 加入购物车
- [x] 下单
## V3版本(下单更快)(已不更新)
下单更快,但只能扫描单独一件商品
在配置文件configDemo.ini中,填写[V3]下面的skuid
**注意--V3版本默认清空购物车**
V3版本下单流程(1秒左右)
- [x] 提前加入购物车
- [x] 检测有货
- [x] 下单
## 温馨提示
- 在京东购物车结算页面设置发票为电子普通发票-个人设置支付方式为在线支付
- 地区id不知道如何获取的,请使用AreaTool.py获取
## 版本
- [x] python3
## 功能
- [x] 检查登录
- [x] 确认是否有货
- [x] 有货自动下单
- [x] 邮件、微信通知
## 更新记录
- 【2020.02.12】更新exe版本,代码暂不更新了。
- 【2020.02.10】每10分钟自动读取一次配置修改商品不需要退出重开,优化有货,不支持省份出售情况,优化日志,加快查询频率。
- 【2020.02.09】部分下单需要验证码识别问题,部分bug优化。
- 【2020.02.08】V2版本,区分下单模式,config中错别字,bug修复。
- 【2020.02.07】V3版本,减少提交订单的请求量,总而言之就是更快(只能监控一件商品)。
- 【2020.02.07】无货等情况下单失败不重试。
- 【2020.02.07】新增微信通知(http://sc.ftqq.com/3.version 查看sc_key),bug修复。
- 【2020.02.06】V2版本,刷新更快更频繁,通过配置文件添加商品和地区id。
- 【2020.02.06】提交失败之后会继续不会暂停。
- 【2020.02.06】购物车有套装商品导致解析skuid错误。
- 【2020.02.05】商品有货,但是该商品已下柜,提交会报错,对部分代码进行了优化。
## 反馈问题
- 如果有红包先花掉再开脚本,不然可能需要支付密码
- 出现下单地址不是默认地址的,在线下一单,取getOrderInfo.action链接的cookie
- CMD界面卡住、关闭CMD的快速编辑模式就行了<file_sep>/multi_process_thread/multiprocessing_first.py
#-*- coding: utf-8 -*-
import multiprocessing
from multiprocessing import Process
from time import sleep
import time
class MultiProcessProducer(multiprocessing.Process):
def __init__(self, num, queue):
"""Constructor"""
multiprocessing.Process.__init__(self)
self.num = num
self.queue = queue
def run(self):
t1 = time.time()
print('producer start ' + str(self.num))
for i in range(1000):
self.queue.put((i, self.num))
# print 'producer put', i, self.num
t2 = time.time()
print('producer exit ' + str(self.num))
use_time = str(t2 - t1)
print('producer ' + str(self.num) + ', use_time: '+ use_time)
class MultiProcessConsumer(multiprocessing.Process):
def __init__(self, num, queue):
"""Constructor"""
multiprocessing.Process.__init__(self)
self.num = num
self.queue = queue
def run(self):
t1 = time.time()
print('consumer start ' + str(self.num))
while True:
d = self.queue.get()
if d != None:
# print 'consumer get', d, self.num
continue
else:
break
t2 = time.time()
print('consumer exit ' + str(self.num))
print('consumer ' + str(self.num) + ', use time:' + str(t2 - t1))
def main():
# create queue
queue = multiprocessing.Queue()
# create processes
producer = []
for i in range(5):
producer.append(MultiProcessProducer(i, queue))
consumer = []
for i in range(5):
consumer.append(MultiProcessConsumer(i, queue))
# start processes
for i in range(len(producer)):
producer[i].start()
for i in range(len(consumer)):
consumer[i].start()
# wait for processs to exit
for i in range(len(producer)):
producer[i].join()
for i in range(len(consumer)):
queue.put(None)
for i in range(len(consumer)):
consumer[i].join()
print('all done finish')
if __name__ == "__main__":
main()<file_sep>/stock/stock2/stock/stock.md
1. 安装tushare
pip install tushare
2. https://blog.csdn.net/rytyy/article/details/78113373
https://blog.csdn.net/weixin_37450657/article/details/78789673
http://tushare.waditu.com/trading.html
https://blog.csdn.net/xieyan0811/article/details/75635780
https://blog.csdn.net/lanchunhui/article/details/52914466
https://download.csdn.net/download/qq_39579696/9994271
https://blog.csdn.net/cf406061841/article/details/79278685
https://blog.csdn.net/wu__di/article/details/79370056
http://quote.eastmoney.com/stocklist.html#sz
https://www.cnblogs.com/DreamRJF/p/8660630.html
阅读数:147
使用matplotlib和tushare绘制K线与成交量组合图
http://blog.csdn.net/u014281392/article/details/73611624
tushare应用小实例
http://blog.csdn.net/robertsong2004/article/details/50643198
使用tushare获取股票历史行情数据并导入数据库(后复权及未复权)
http://blog.csdn.net/hualugu_6/article/details/54944248?locationNum=1&fps=1
tushare获取数据并存入excel数据表
http://blog.csdn.net/elite666/article/details/62882229?locationNum=1&fps=1
使用tushare开发股票分析脚本
http://blog.csdn.net/stpenghui/article/details/75980032?locationNum=3&fps=1#-*- coding: utf-8 -*-
import tushare as ts
import sys
from openpyxl.reader.excel import load_workbook
import json
wb = load_workbook(filename=r'D:/PythonWorkplace/PythonLearning/stock/stock_s.xlsx')
print "Worksheet range(s):", wb.get_named_ranges()
print "Worksheet name(s):", wb.get_sheet_names()
def printChinese(chinese_str):
type = sys.getfilesystemencoding()
print chinese_str.decode('UTF-8').encode(type)
printChinese ("date:日期")阅读数:147
使用matplotlib和tushare绘制K线与成交量组合图
http://blog.csdn.net/u014281392/article/details/73611624
tushare应用小实例
http://blog.csdn.net/robertsong2004/article/details/50643198
使用tushare获取股票历史行情数据并导入数据库(后复权及未复权)
http://blog.csdn.net/hualugu_6/article/details/54944248?locationNum=1&fps=1
tushare获取数据并存入excel数据表
http://blog.csdn.net/elite666/article/details/62882229?locationNum=1&fps=1
使用tushare开发股票分析脚本
http://blog.csdn.net/stpenghui/article/details/75980032?locationNum=3&fps=1
#saved_filename = 'stock.xlsx'
#df = ts.get_hist_data('002415', start='2018-05-28', end='2018-05-30')
#df.to_excel(saved_filename)
阅读数:147
使用matplotlib和tushare绘制K线与成交量组合图
http://blog.csdn.net/u014281392/article/details/73611624
tushare应用小实例
http://blog.csdn.net/robertsong2004/article/details/50643198
使用tushare获取股票历史行情数据并导入数据库(后复权及未复权)
http://blog.csdn.net/hualugu_6/article/details/54944248?locationNum=1&fps=1
tushare获取数据并存入excel数据表
http://blog.csdn.net/elite666/article/details/62882229?locationNum=1&fps=1
使用tushare开发股票分析脚本
http://blog.csdn.net/stpenghui/article/details/75980032?locationNum=3&fps=1
<file_sep>/Spider/mess_code.py
import gzip
import StringIO
import urllib2
ur1='http://www.runoob.com/python/python-exercise-example1.html'
proxy_handler = urllib2.ProxyHandler({'http': 'xxx.xxx.xxx.xxx:xxxx'})
opener = urllib2.build_opener(proxy_handler)
reponse = opener.open(ur1)
r=reponse.read()
data = StringIO.StringIO(r)
gzipper = gzip.GzipFile(fileobj=data)
html = gzipper.read()
print html<file_sep>/blockchain/blockchain_first.md
# 块链的原理是什么?
<file_sep>/multi_process_thread/concurrent.futures_2.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
# Python并发编程之线程池/进程池
# https://segmentfault.com/a/1190000007926055#articleHeader3
# 使用submit
#-------------------------------------------------------------------------------------------#
'''
'''
# example2.py
from concurrent.futures import ProcessPoolExecutor
import time
def return_future_result(message):
time.sleep(2)
return message
pool = ProcessPoolExecutor(max_workers=2)
future1 = pool.submit(return_future_result, ("hello"))
future2 = pool.submit(return_future_result, ("world"))
print(future1.done())
time.sleep(3)
print(future2.done())
# example2.py
from concurrent.futures import ProcessPoolExecutor
import time
def return_future_result(message):
time.sleep(2)
return message
pool = ProcessPoolExecutor(max_workers=2)
future1 = pool.submit(return_future_result, ("hello"))
future2 = pool.submit(return_future_result, ("world"))
print(future1.done())
time.sleep(3)
print(future2.done())
print(future1.result())
print(future2.result())
print(future1.result())
print(future2.result())<file_sep>/multi_process_thread/multi_thread_sync_w_event.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
# 参考线程间的通讯– event:http://zhaochj.github.io/2016/08/14/2016-08-14-%E7%BA%BF%E7%A8%8B%E7%9A%84event%E7%89%B9%E6%80%A7/
#-------------------------------------------------------------------------------------------#
import threading
import logging
import time
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s [%(threadName)s] %(message)s')
def worker(event):
while not event.is_set():
event.wait(timeout=1)
logging.debug('in worker fun, event is set ? {0}'.format(event.is_set()))
logging.debug('event is set')
def set(event):
time.sleep(4)
event.set()
logging.debug('in set fun, event is set ? {0}'.format(event.is_set()))
if __name__ == '__main__':
event = threading.Event()
w = threading.Thread(target=worker, args=(event,), name="worker")
w.start()
s = threading.Thread(target=set, args=(event,), name="set")
s.start()
<file_sep>/spider/webSpider.py
import re
from bs4 import BeautifulSoup
email_id_example = """<br/>
<div>The below HTML has the information that has email ids.</div>
<EMAIL>
<div><EMAIL></div>
<span><EMAIL></span>
"""
soup = BeautifulSoup(email_id_example, "lxml")
emailid_regexp = re.compile("\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}")
first_email_id = soup.find(text=emailid_regexp)
print(first_email_id)
next_email_id = soup.find_next(text=emailid_regexp)
print(next_email_id) <file_sep>/OCR_baidu/extractManual.py
#-*- coding: utf-8 -*-
import os
from aip import AipOcr
from optparse import OptionParser
APP_ID = '15616936'
API_KEY = '<KEY>'
SECRET_KEY = '<KEY>'
# 读取图片
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
def main():
'''Not all parameters are mandatory, please make sure they are used'''
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-p", "--path", dest="path", default='',
help="the directory stored the images to be recognized")
parser.add_option("-f", "--file", dest="file", default='',
help="the isolate file to be recongnized")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
parser.add_option("-q", "--quit",
action="store_false", dest="verbose")
(options, args) = parser.parse_args()
print options.path, options.file
if len(options.path) == 0 and len(options.file) == 0:
print 'exit, without path and file input'
return
if len(options.path) > 0 and len(options.file) > 0:
print 'exit, with both path and file input'
return
# 初始化ApiOcr对象
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
if len(options.path) > 0:
if not os.path.isdir(options.path):
print 'exit, input path is not a directory'
return
ocr_w_path_input(client, options.path)
if len(options.file) > 0:
if not os.path.isfile(options.file):
print 'exit, input is not a file'
return
ocr_w_file_input(client, options.file)
return
def ocr_w_path_input(_client, _path):
file_list = os.listdir(_path)
for filename in file_list:
ocr_w_file_input(_client, _path + os.path.sep + _file_name)
print "ocr in path complete...."
return
def ocr_w_file_input(_client, _file_name):
try:
result = _client.basicGeneral(get_file_content(_file_name))
print 'for file:', _file_name, len(result[u'words_result']), 'generated'
for items in result[u'words_result']:
print items[u'words'].decode('utf-8')
except:
print "nothing generated"
return
if __name__ == "__main__":
main()<file_sep>/stock/stock_scriber/abc.py
#!/usr/bin/python
# coding: UTF-8
import requests
import re
import bs4
import traceback
def getHTMLText(url, code = "utf-8"):
# 获得股票页面
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = code
# r.encoding = r.apparent_encoding
# 直接用"utf-8"编码节省时间
return r.text
except:
return ""
def getStockList(lst, stockURL):
# 获取股票列表
html = getHTMLText(stockURL, "GB2312")
# 东方财富网用"GB2312"方式编码
soup = bs4.BeautifulSoup(html, "html.parser")
a = soup. find_all("a")
for i in a:
try:
href = i.attrs["href"]
lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
except:
continue
def getStockInfo(lst, stockURL, fpath):
count = 0
# 增加进度条
# 获取个股信息
for stock in lst:
url = stockURL + stock + ".html"
html = getHTMLText(url)
try:
if html == "":
# 判断页面是否为空
continue
infoDict = { }
# 定义一个字典用来储存股票信息
soup = bs4.BeautifulSoup(html, "html.parser")
stockInfo = soup.find("div", attrs={"class":"stock-bets"})
# 获得股票信息标签
name = stockInfo.find_all(attrs={"class":"bets-name"})[0]
# 在标签中查找股票名称
infoDict.update({"股票名称":name.text.split()[0]})
# 将股票名称增加到字典中
keyList = stockInfo.find_all("dt")
# "dt"标签是股票信息键的域
valueList = stockInfo.find_all("dd")
# "dd"标签是股票信息值的域
for i in range(len(keyList)):
# 还原键值对并存储到列表中
key = keyList[i].text
val = valueList[i].text
infoDict[key] = val
with open(fpath, "a", encoding="utf-8") as f:
f.write(str(infoDict) + "\n")
count += 1
# 增加进度条
print "\rcurrent process:%.2f" % (count*100/len(lst))
except:
count += 1
# 增加进度条
print 'current process:%.2f' % (count * 100 / len(lst))
# 用traceback获得异常信息
#traceback.print_exc()
continue
return ""
if __name__ == '__main__':
stock_list_url = "http://quote.eastmoney.com/stocklist.html"
# 获得个股链接
stock_info_url = "https://gupiao.baidu.com/stock/"
# 获取股票信息的主题部分
output_file = "C:\\Users\\W419L\\Desktop\\股票爬取.txt"
# 文件保存地址
slist = []
# 存储股票信息
getStockList(slist, stock_list_url)
getStockInfo(slist, stock_info_url, output_file)<file_sep>/window32API/2ExecuteMyAppDyc.py
# coding: utf-8
import win32gui, win32con
import win32api
import win32event
import win32process
import time
import re, traceback
import sys
from time import sleep
import json
'''
cd D:\PythonWorkspace\NewPython3\PythonLearning\window32API
pyinstaller -p D:/Python3/Lib/site-packages -D 2ExecuteMyApp.py
pyinstaller -p D:/Python3/Lib/site-packages -F -w 2ExecuteMyAppDyc.py
pyinstaller -p D:/Python3/Lib/site-packages -F -w 2ExecuteMyAppDyc.py
python 2ExecuteMyAppDyc.py "同花顺远航版" "D:\\Program Files (x86)\\ths\\THS\\hstart.exe" "MAX"
./2ExecuteMyAppDyc.exe "同花顺远航版" "D:\\Program Files (x86)\\ths\\THS\\hstart.exe" "MAX"
'''
class cWindow:
def __init__(self):
self._hwnd = None
def SetAsForegroundWindow(self):
# First, make sure all (other) always-on-top windows are hidden.
self.hide_always_on_top_windows()
win32gui.SetForegroundWindow(self._hwnd)
def Maximize(self):
win32gui.ShowWindow(self._hwnd, win32con.SW_MAXIMIZE)
def Minimize(self):
win32gui.ShowWindow(self._hwnd, win32con.SW_MINIMIZE)
def setSize(self, sizemode):
if sizemode == win32con.SW_MINIMIZE:
self.Minimize()
elif sizemode == win32con.SW_MAXIMIZE:
self.Maximize()
self.SetAsForegroundWindow()
def _window_enum_callback(self, hwnd, regex):
'''Pass to win32gui.EnumWindows() to check all open windows'''
if self._hwnd is None and re.match(regex, str(win32gui.GetWindowText(hwnd))) is not None:
self._hwnd = hwnd
def find_window_regex(self, regex):
self._hwnd = None
win32gui.EnumWindows(self._window_enum_callback, regex)
def hide_always_on_top_windows(self):
win32gui.EnumWindows(self._window_enum_callback_hide, None)
def _window_enum_callback_hide(self, hwnd, unused):
if hwnd != self._hwnd: # ignore self
# Is the window visible and marked as an always-on-top (topmost) window?
if win32gui.IsWindowVisible(hwnd) and win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) & win32con.WS_EX_TOPMOST:
# Ignore windows of class 'Button' (the Start button overlay) and
# 'Shell_TrayWnd' (the Task Bar).
className = win32gui.GetClassName(hwnd)
if not (className == 'Button' or className == 'Shell_TrayWnd'):
# Force-minimize the window.
# Fortunately, this seems to work even with windows that
# have no Minimize button.
# Note that if we tried to hide the window with SW_HIDE,
# it would disappear from the Task Bar as well.
win32gui.ShowWindow(hwnd, win32con.SW_FORCEMINIMIZE)
def startApp(self, path, sizemode):
if self._hwnd is None:
startinfo = win32process.STARTUPINFO()
startinfo.wShowWindow = sizemode
info = win32process.CreateProcess(None, path, None, None, 0, 0, None, None, startinfo)
subprocess = info [0]
rc = win32event.WaitForSingleObject (subprocess, win32event.INFINITE)
if rc == win32event.WAIT_TIMEOUT:
try:
win32process.TerminateProcess (subprocess, 0)
except pywintypes.error:
return -3
return -2
if rc == win32event.WAIT_OBJECT_0:
return win32process.GetExitCodeProcess(subprocess)
def main():
app_data = {}
app_data['Application Name'] = sys.argv[1]
app_data['Application Path'] = sys.argv[2]
app_data['Application Size'] = sys.argv[3]
print(app_data['Application Path'])
print(app_data['Application Name'])
print(app_data['Application Size'])
sizemode = win32con.SW_MAXIMIZE
if app_data['Application Size'] == "MAX":
sizemode = win32con.SW_MAXIMIZE
elif app_data['Application Size'] == "MIN":
sizemode = win32con.SW_MINIMIZE
try:
regex = ".*" + app_data['Application Name'] + ".*"
cW = cWindow()
cW.find_window_regex(regex)
if cW._hwnd is None:
cW.startApp(app_data['Application Path'], sizemode)
else:
cW.setSize(sizemode)
except:
f = open("log.txt", "w")
f.write(traceback.format_exc())
print(traceback.format_exc())
main()<file_sep>/cdr_to_csv/cdr_to_csv.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
import sys
import time
import datetime
#tree = ET.parse(sys.argv[1])
from numpy import *
import random
RecordHeader = "Record Header:"
IBCFRecord = "value IMSRecord ::= iBCFRecord :"
serviceDeliveryStartTimeStamp = "serviceDeliveryStartTimeStamp"
serviceDeliveryEndTimeStamp = "serviceDeliveryEndTimeStamp"
trunkGroupID = "trunkGroupID"
trunkGroupIDincoming = "incoming"
trunkGroupIDoutgoing = "outgoing"
RecordHeaderINDEX = 0
IBCFRecordINDEX = 1
serviceDeliveryStartTimeStampINDEX = 2
serviceDeliveryEndTimeStampINDEX = 3
trunkGroupIDINDEX = 4
trunkGroupIDincomingINDEX = 5
trunkGroupIDoutgoingINDEX = 6
# the above variable count
RECORD_LIST_LENGTH = 7
# check if the list element macth
def validateRecord(oneRecordList):
if len(oneRecordList) != RECORD_LIST_LENGTH:
return -1
if RecordHeader not in oneRecordList[0]:
return -1
if IBCFRecord not in oneRecordList[1]:
return -1
if serviceDeliveryStartTimeStamp not in oneRecordList[2]:
return -1
if serviceDeliveryEndTimeStamp not in oneRecordList[3]:
return -1
if trunkGroupID not in oneRecordList[4]:
return -1
if trunkGroupIDincoming not in oneRecordList[5]:
return -1
if trunkGroupIDoutgoing not in oneRecordList[6]:
return -1
# validation of the input passed
return 0
def printRecordList(RecordList):
for list_item in RecordList:
print list_item
return
def is_valid_date(str):
'''check if the input string is in a valide time format: "%Y/%m/%d %H:%M:%S"'''
try:
time.strptime(str, "%Y/%m/%d %H:%M:%S")
return True
except:
return False
# serviceDeliveryStartTimeStamp "18/09/04 11:05:44+0530",\n',
def decodeServiceDeliveryStartTimeStamp(inputstring):
if inputstring.find(serviceDeliveryStartTimeStamp) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('+')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = '20' + inputstring[first_delimiter+1: second_delimiter]
if is_valid_date(return_string):
#print time.strptime(return_string, "%Y/%m/%d %H:%M:%S")
return return_string
return ""
def decodeServiceDeliveryEndTimeStamp(inputstring):
if inputstring.find(serviceDeliveryEndTimeStamp) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('+')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = '20' + inputstring[first_delimiter+1: second_delimiter]
if is_valid_date(return_string):
#print time.strptime(return_string, "%Y/%m/%d %H:%M:%S")
return return_string
return ""
def decodetrunkGroupIDincoming(inputstring):
if inputstring.find(trunkGroupIDincoming) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('"')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = inputstring[first_delimiter+1: second_delimiter]
if len(return_string) != 8:
return (0,0)
return (int(return_string[0:4]), int(return_string[4:8]))
return (0,0)
def decodetrunkGroupIDoutgoing(inputstring):
if inputstring.find(trunkGroupIDoutgoing) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('"')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = inputstring[first_delimiter+1: second_delimiter]
if len(return_string) != 8:
return (0,0)
return (int(return_string[0:4]), int(return_string[4:8]))
return (0,0)
def getDecodedVN(inputtuple):
'''get VN "Virtual Network"'''
if len(inputtuple) != 2:
return 0
return inputtuple[0]
def getDecodedTG(inputtuple):
'''get TG "Trunk Group"'''
if len(inputtuple) != 2:
return 0
return inputtuple[1]
def calculatePerCallRecordDuriation(start_str_time, end_str_time):
'''during in seconds will be returned'''
starttime = string_toDatetime(start_str_time)
endtime = string_toDatetime(end_str_time)
return (endtime - starttime).seconds
def string_toDatetime(st):
'''convert timestamp in string fromat to datetime format'''
return datetime.datetime.strptime(st, "%Y/%m/%d %H:%M:%S")
def decodeRecord(RecordItem):
if len(RecordItem) != RECORD_LIST_LENGTH:
return -1
start_time = decodeServiceDeliveryStartTimeStamp(RecordItem[serviceDeliveryStartTimeStampINDEX])
end_time = decodeServiceDeliveryEndTimeStamp(RecordItem[serviceDeliveryEndTimeStampINDEX])
callDuriation = calculatePerCallRecordDuriation(start_time, end_time)
incomingVN = getDecodedVN(decodetrunkGroupIDincoming(RecordItem[trunkGroupIDincomingINDEX]))
incomingTG = getDecodedTG(decodetrunkGroupIDincoming(RecordItem[trunkGroupIDincomingINDEX]))
outgoingVN = getDecodedVN(decodetrunkGroupIDoutgoing(RecordItem[trunkGroupIDoutgoingINDEX]))
outgoingTG = getDecodedTG(decodetrunkGroupIDoutgoing(RecordItem[trunkGroupIDoutgoingINDEX]))
print "VN=%d" % incomingVN, "TG=%d" % incomingTG, "incoming CallDuration=%d" % callDuriation
print "VN=%d" % outgoingVN, "TG=%d" % outgoingTG, "outgoing CallDuration=%d" % callDuriation
## TODO:: need to print to csv
return 0
def decodeRecordList(RecordList):
''' used to parse the output of loadCDRdecodedFile() function'''
for list_item in RecordList:
#print list_item
decodeRecord(list_item)
return
# load input file
def loadCDRdecodedFile(fileName):
''' used to load the CDR decoded raw text file, and then parse records in the file '''
''' save each record in a list, and save each ist in RecordList '''
# print file name loaded
print "the file to be processed is:", fileName
# read lines from the file and print it out to the screen
RecordList = list()
temp_record = list()
with open(fileName, 'rt') as txtData:
lines=txtData.readlines()
for line in lines:
line.strip()
line.rstrip('\n')
if line.find(RecordHeader) != -1:
#print line
# append 0 -- RecordHeader
if line in temp_record:
if validateRecord(temp_record) != -1:
#print "save the previous record to the list"
#print temp_record
RecordList.append(temp_record)
## reset the list to a new one
temp_record = list()
temp_record.append(line)
elif line.find(IBCFRecord) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(serviceDeliveryStartTimeStamp) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(serviceDeliveryEndTimeStamp) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(trunkGroupID) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(trunkGroupIDincoming) != -1:
# when not save the "trunkGroupID" block, so the found incoming is not the right incoming
if len(temp_record) < 5:
#print "has not save the trunkGroupID block, so the found incoming is not the right incoming"
continue
if trunkGroupID not in temp_record[4]:
#print "has not save the trunkGroupID block, so the found incoming is not the right incoming"
continue
# save the trunkGroupIDincoming
temp_record.append(line)
elif line.find(trunkGroupIDoutgoing) != -1:
# when not save the "trunkGroupID" block, so the found outgoing is not the right outgoing
if len(temp_record) < 5:
#print "has not save the trunkGroupID block, so the found outgoing is not the right outgoing"
continue
if trunkGroupID not in temp_record[4]:
#print "has not save the trunkGroupID block, so the found outgoing is not the right outgoing"
continue
# save the trunkGroupIDoutgoing
temp_record.append(line)
## check if the list element macth
if validateRecord(temp_record) != -1:
RecordList.append(temp_record)
return RecordList
if __name__ == "__main__":
resultRecordList = loadCDRdecodedFile(sys.argv[1])
#printRecordList(resultRecordList)
decodeRecordList(resultRecordList)
<file_sep>/Spider/walkpath.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#[python中得到shell命令输出的方法](https://blog.csdn.net/wanglei_storage/article/details/54615952)
# usage: python walkpath.py /directory/ searched_string
# python ~/walkpath.py $OFROOT/glob/ obj ssp csp
# the script is used to list all files in the pointed path,
# but could exlude the files in the pointed path
# in the above example, files in obj ssp csp dir and subdir will be excluded.
import os, re, datetime
import sys
if __name__ == "__main__":
print datetime.datetime.now()
search_path = sys.argv[1]
print "execute script", sys.argv[0], "with", len(sys.argv), "arguments, searched path:", search_path
argv_idx = 2
subpath_filter = []
while argv_idx < len(sys.argv):
subpath_filter.append(sys.argv[argv_idx])
argv_idx = argv_idx + 1
fileList = []
for filename in os.listdir(search_path):
if filename in subpath_filter:
print os.path.join(search_path, filename), "is excluded......"
continue
filepath = os.path.join(search_path, filename)
if os.path.isfile(filepath):
fileList.append(filepath)
print filepath
else:
for root, dirs, files in os.walk(filepath):
for name in files:
print(os.path.join(root, name))
<file_sep>/Spider/walkfile2.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#[python中得到shell命令输出的方法](https://blog.csdn.net/wanglei_storage/article/details/54615952)
# usage: python walkfile2.py /directory/ searched_string
# python ~/walkfile2.py $OFROOT/glob/ LU3P.include out cpp c h out1 out2 out3 out4
import os, re, datetime
import sys
if __name__ == "__main__":
print datetime.datetime.now()
search_path = sys.argv[1]
search_string = sys.argv[2]
print "execute script", sys.argv[0], "with", len(sys.argv), "arguments, searched path:", search_path,"searched string:", search_string
argv_idx = 3
type_filter = []
while argv_idx < len(sys.argv):
type_filter.append(sys.argv[argv_idx])
argv_idx = argv_idx + 1
for fpathe, dirs, fs in os.walk(search_path):
for f in fs:
if os.path.splitext(f)[-1][1:] in type_filter:
print ".",
continue
file_found = os.path.join(fpathe,f)
process = os.popen('grep ' + search_string + ' ' + file_found) # return file
output = process.read()
process.close()
if len(output) != 0:
print ""
print "==============================", file_found, "=========================================================================================="
print output
else:
print ".",
print datetime.datetime.now()
<file_sep>/stock/stock2/stock/stockGet.py
import sys
import os
import datetime as dt
import json
import tushare as ts
from openpyxl import load_workbook
#def printChinese(chinese_str):
# type = sys.getfilesystemencoding()
# print chinese_str.decode('UTF-8').encode(type)
# return
#把datetime转成字符串
def datetime_toString(dt):
return dt.strftime("%Y-%m-%d")
#把字符串转成datetime
def string_toDatetime(string):
return dt.datetime.strptime(string, "%Y-%m-%d")
#把字符串转成时间戳形式
def string_toTimestamp(strTime):
return dt.mktime(string_toDatetime(strTime).timetuple())
#把时间戳转成字符串形式
def timestamp_toString(stamp):
return dt.strftime("%Y-%m-%d", time.localtime(stamp))
#把datetime类型转外时间戳形式
def datetime_toTimestamp(dateTim):
return dt.mktime(dateTim.timetuple())
#将字符串e.g.'2018-07-06'转化为datetime 然后+1,在转回字符串'2018-07-07'
def day_string_plus_one(_day_input):
date = string_toDatetime(_day_input) + dt.timedelta(days=1)
return datetime_toString(date)
def get_hist_data_days(_stock_code, _day_start, _day_counts):
df = ts.get_hist_data(_stock_code, start=_day_start, end=_day_start)
if df is None:
return df
return df[['open', 'close', 'high', 'low']]
def search_data(stock_code, input_day, input_limit):
count = 0
a_store_data = [[]]
try_times = 0
while (count < input_limit):
df = get_hist_data_days(stock_code, input_day, 1)
if df is None or len(df) == 0:
print 'got nothing:', 'stock:', stock_code, "day: ", input_day
input_day = day_string_plus_one(input_day)
try_times = try_times + 1
if try_times == 10:
return a_store_data
continue
close_price = df[u'close']
open_price = df[u'open']
high_price = df[u'high']
low_price = df[u'low']
#p_change_interval = df[u'p_change']
# there is no data in that day, move to next day and have a try
#if 0 == len(close_price) or 0 == len(open_price) or 0 == len(high_price) or 0 == len(low_price):
#print "There is no data in day: ", input_day
# input_day = day_string_plus_one(input_day)
#print "Try next day:", input_day
# continue
a_store_data.append([open_price[0], close_price[0], high_price[0], low_price[0]])
input_day = day_string_plus_one(input_day)
count = count + 1
return a_store_data
def main():
#df = ts.get_hist_data('002415', start = '2018-07-06', end = '2018-07-10')
#get_hist_data_days('002415', '2018-07-06', 1)
#
#df = ts.get_hist_data('000875')
dirname, filename = os.path.split(os.path.abspath(__file__))
#print dirname, filename
read_excel_file_name = dirname + '\stock_s.xlsx'
print read_excel_file_name
wb = load_workbook(read_excel_file_name)
# 获取所有表格(worksheet)的名字
sheets = wb.sheetnames
#print sheets
# # 第一个表格的名称
sheet_first = sheets[0]
# # 获取特定的worksheet
#
ws = wb[sheet_first]
rows = ws.rows
print "***"
print sheet_first
print ws.title
print "^^^"
input_limit = 5
print "stock_code: ", "date: ", "close: ", "open: ", "high: ", "low: "
# 迭代所有的行
row_index = 1
for row in rows:
line = [col.value for col in row]
#print line
if row_index == 1:
row_index = row_index + 1
continue
if row_index == 2:
row_index = row_index + 1
continue
stock_code = ws.cell(row=row_index, column=2).value
if stock_code == None:
break
print "going to get data for stock: ", stock_code
# go to get
get_day_from_table = ws.cell(row=row_index, column=3).value
print get_day_from_table
if get_day_from_table == None:
print "break when day is None"
break
got_datas_one_stock = search_data(stock_code, datetime_toString(get_day_from_table), input_limit)
if len(got_datas_one_stock) == 0:
print "could not get data for stock:", stock_code, "move to next stock"
row_index = row_index + 1
item_index = 7
for one_data in got_datas_one_stock:
flag_item_index = item_index
for item in one_data:
ws.cell(row=row_index, column=item_index).value = item
item_index = item_index + 1
if item_index == (flag_item_index + 4):
item_index = item_index + 1
# move to next row to search
row_index = row_index + 1
print "goning to save data in to file"
wb.save('stock_s.xlsx')
return
main()
<file_sep>/gamefucker/autoAndroidApp.py
# -*- coding: utf-8 -*-
# [pywinauto简明教程](https://gaianote.github.io/2018/06/13/pywinauto%E7%AE%80%E6%98%8E%E6%95%99%E7%A8%8B/)
# [pywinauto UserGuide](https://pywinauto.readthedocs.io/en/latest/getting_started.html)
# [PyWinAuto入门指南](https://zhuanlan.zhihu.com/p/37283722)
# [在中文windows下使用pywinauto进行窗口操作(一)](https://my.oschina.net/yangyanxing/blog/167042)
import pyautogui
from pywinauto.application import Application
pyautogui.PAUSE = 1.5
pyautogui.FAILSAFE = True
__DEBUG__=True
if __name__ == "__main__":
# get the size of the screen
if __DEBUG__ == True:
print "screen size:", pyautogui.size()
width, height = pyautogui.size()
#for i in range(1):
# pyautogui.moveTo(300, 300, duration=0.25)
# pyautogui.moveTo(400, 300, duration=0.25)
# pyautogui.moveTo(400, 400, duration=0.25)
# pyautogui.moveTo(300, 400, duration=0.25)
#
print "Process Complete!......"
#pyautogui.typewrite("Process Complete!......", 0.25)
app = Application(backend="uia").start("notepad.exe")
#app = Application().connect(class_name="Notepad")
dlg_spec = app['Untitled - Notepad']
dlg_spec.print_control_identifiers()
#app.notepad.type_keys("%FX")
#
#about_dlg = app.window_(title_re = u"关于", class_name = "#32770")
#app['Untitled - Notepad'].Edit.type_keys('test01')
#app['Untitled - Notepad'].menu_select("File->Save")
#
#app['Save As'].Edit.type_keys('test.txt')
#app['Save As']['Save'].click()
##app['确认另存为']['是'].click()
<file_sep>/window32API/readclipboard.py
# coding: utf-8
import win32gui, win32api, win32con
import time
import win32clipboard as w
import logging
def click_position(hwd, x_position, y_position, sleep):
"""
鼠标左键点击指定坐标
:param hwd:
:param x_position:
:param y_position:
:param sleep:
:return:
"""
# 将两个16位的值连接成一个32位的地址坐标
long_position = win32api.MAKELONG(x_position, y_position)
# win32api.SendMessage(hwnd, win32con.MOUSEEVENTF_LEFTDOWN, win32con.MOUSEEVENTF_LEFTUP, long_position)
# 点击左键
win32api.SendMessage(hwd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, long_position)
win32api.SendMessage(hwd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, long_position)
time.sleep(int(sleep))
def getText():
# 读取剪切板
w.OpenClipboard()
d = w.GetClipboardData(win32con.CF_TEXT)
w.CloseClipboard()
return d
def setText(aString):
# 写入剪切板
w.OpenClipboard()
w.EmptyClipboard()
w.SetClipboardData(win32con.CF_TEXT, aString.encode(encoding='gbk'))
w.CloseClipboard()
def input_content(hwd, content, sleep, is_enter):
"""
从站贴板中查找输入的内容
:param hwd:
:param content:
:param sleep:
:param is_enter 是否要在最后输入enter键,内容与enter之间间隔一秒
:return:
"""
setText(content)
time.sleep(0.3)
click_keys(hwd, win32con.VK_CONTROL, 86)
if is_enter:
time.sleep(1)
click_keys(hwd, win32con.VK_RETURN)
time.sleep(sleep)
def click_keys(hwd, *args):
"""
定义组合按键
:param hwd:
:param args:
:return:
"""
for arg in args:
win32api.SendMessage(hwd, win32con.WM_KEYDOWN, arg, 0)
for arg in args:
win32api.SendMessage(hwd, win32con.WM_KEYUP, arg, 0)
def wangwang_operation(hwd, salesname, content1, content2):
"""
阿里旺旺的操作
:param hwd: 句柄
:param salesname:
:param content1: 发送一
:param content2: 发送二
:return:
"""
# 下方联系人标签
click_position(hwd, 200, 685, 2)
# 新增好友按钮
click_position(hwd, 372, 44, 3)
# 搜索好友
input_content(hwd, salesname, 3, False)
# 点击搜索
click_position(hwd, 345, 117, 5)
# 点击发送消息
click_position(hwd, 350, 700, 3)
# 发送消息一
input_content(hwd, content1, 1, False)
click_keys(hwd, win32con.VK_CONTROL, win32con.VK_RETURN)
time.sleep(1)
input_content(hwd, content2, 1, False)
click_keys(hwd, win32con.VK_CONTROL, win32con.VK_RETURN)
time.sleep(1)
# 返回原始状态
click_position(hwd, 20, 45, 1)
time.sleep(1)
click_position(hwd, 20, 45, 1)
def wangwang_operation_by_file(hwd, file, content1, content2):
with open(file, 'r') as f:
line = f.readline()
while len(line) >= 1:
try:
line = line.replace('\r', '').replace('\n', '')
print("正在处理 %s ....................................." % line)
wangwang_operation(hwd, line, content1, content2)
line = f.readline()
except BaseException as e:
print("处理 %s 时出错了............." % line)
logging.exception(e)
if __name__ == "__main__":
# 查找句柄
hwnd = win32gui.FindWindow("Vim", None)
if int(hwnd) <= 0:
print("没有找到模拟器,退出进程................")
exit(0)
print("查询到模拟器句柄: %s " % hwnd)
win32gui.MoveWindow(hwnd, 20, 20, 405, 756, True)
time.sleep(2)
# 屏幕坐标到客户端坐标
# print(win32gui.ScreenToClient(hwnd, (1446, 722)))
# 设置为前台
# win32gui.SetForegroundWindow(hwnd)
# 设置为后台
win32gui.SetBkMode(hwnd, win32con.TRANSPARENT)
time.sleep(2)
# 下列的后三个参数分别表示: 文件路径 打招呼句子 广告语
wangwang_operation_by_file(hwnd, "D:/2.txt", "你好", "测试广告语")<file_sep>/multi_process_thread/multi_thread_6.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
# 多线程 -
# python多线程编程(7):线程间通信
# https://www.cnblogs.com/holbrook/archive/2012/03/21/2409031.html
#-------------------------------------------------------------------------------------------#
'''
很多时候,线程之间会有互相通信的需要。常见的情形是次要线程为主要线程执行特定的任务,在执行过程中需要不断报告执行的进度情况。前面的条件变量同步已经涉及到了线程间的通信(threading.Condition的notify方法)。更通用的方式是使用threading.Event对象。
threading.Event可以使一个线程等待其他线程的通知。其内置了一个标志,初始值为False。线程通过wait()方法进入等待状态,直到另一个线程调用set()方法将内置标志设置为True时,Event通知所有等待状态的线程恢复运行。还可以通过isSet()方法查询Envent对象内置状态的当前值。
'''
import threading
import random
import time
class MyThread(threading.Thread):
def __init__(self,threadName,event):
threading.Thread.__init__(self,name=threadName)
self.threadEvent = event
def run(self):
print "%s is ready" % self.name
self.threadEvent.wait()
print "%s run!" % self.name
sinal = threading.Event()
for i in range(10):
t = MyThread(str(i), sinal)
t.start()
sinal.set()<file_sep>/gamefucker/autoWin32API.py
# -*- coding: utf-8 -*-
# reference:
#
# [python win32api win32gui win32con 简单操作教程(窗口句柄 发送消息 常用方法 键盘输入)](https://blog.csdn.net/qq_16234613/article/details/79155632)
#
# [Python win32gui Module](https://www.programcreek.com/python/index/322/win32gui)
#
import win32gui
import win32con
import win32api
import pyautogui
# 从顶层窗口向下搜索主窗口,无法搜索子窗口
# FindWindow(lpClassName=None, lpWindowName=None) 窗口类名 窗口标题名
handle = None
try:
handle = win32gui.FindWindow('LDPlayerMainFrame', None)
except WindowsError:
print "dnplayer InstallDir query failed. not installed in the system, please install it before using this script"
sys.exit(0)
# 获取窗口位置
left, top, right, bottom = win32gui.GetWindowRect(handle)
#获取某个句柄的类名和标题
title = win32gui.GetWindowText(handle)
clsname = win32gui.GetClassName(handle)
print 'Title of ldplayer:', title
print 'Class of ldplayer:', clsname
# 十进制
print 'Handle of ldplayer:',"%x" %(handle)
# 搜索子窗口
# 枚举子窗口
hwndChildList = []
win32gui.EnumChildWindows(handle, lambda hwnd, param: param.append(hwnd), hwndChildList)
print 'Child Windows:', hwndChildList
menuHandle = win32gui.GetMenu(handle)
print menuHandle
my_window = pyautogui.getWindow(u'雷电模拟器')
print my_window
my_window.resize(400, 400)
my_window.moveRel(x=0, y=0)<file_sep>/disk/disk_info.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
import os
def disk_stat(folder):
"""
查看文件夹占用磁盘信息
:param folder: 文件夹路径
:return:
"""
hd={}
disk = os.statvfs(folder)
print(disk)
# 剩余
hd['free'] = disk.f_bavail * disk.f_frsize
# 总共
hd['total'] = disk.f_blocks * disk.f_frsize
# 已使用
hd['used'] = hd['total'] - hd['free']
# 使用比例
hd['used_proportion'] = float(hd['used']) / float(hd['total'])
return hd
if __name__ == "__main__":
hd = disk_stat('./')
print hd['used_proportion'] <file_sep>/cdr_to_csv/cdr_to_csv.5.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
import sys
import time
import datetime
import csv
import codecs
import os
from numpy import *
import random
from optparse import OptionParser
RecordHeader = "Record Header:"
IBCFRecord = "value IMSRecord ::= iBCFRecord :"
serviceDeliveryStartTimeStamp = "serviceDeliveryStartTimeStamp"
serviceDeliveryEndTimeStamp = "serviceDeliveryEndTimeStamp"
trunkGroupID = "trunkGroupID"
trunkGroupIDincoming = "incoming"
trunkGroupIDoutgoing = "outgoing"
RecordHeaderINDEX = 0
IBCFRecordINDEX = 1
serviceDeliveryStartTimeStampINDEX = 2
serviceDeliveryEndTimeStampINDEX = 3
trunkGroupIDINDEX = 4
trunkGroupIDincomingINDEX = 5
trunkGroupIDoutgoingINDEX = 6
# the above variable count
RECORD_LIST_LENGTH = 7
# check if the list element macth
def validateRecord(oneRecordList):
if len(oneRecordList) != RECORD_LIST_LENGTH:
return -1
if RecordHeader not in oneRecordList[0]:
return -1
if IBCFRecord not in oneRecordList[1]:
return -1
if serviceDeliveryStartTimeStamp not in oneRecordList[2]:
return -1
if serviceDeliveryEndTimeStamp not in oneRecordList[3]:
return -1
if trunkGroupID not in oneRecordList[4]:
return -1
if trunkGroupIDincoming not in oneRecordList[5]:
return -1
if trunkGroupIDoutgoing not in oneRecordList[6]:
return -1
# validation of the input passed
return 0
def printRecordList(RecordList):
for list_item in RecordList:
print list_item
return
def is_valid_date(str):
'''check if the input string is in a valide time format: "%Y/%m/%d %H:%M:%S"'''
try:
time.strptime(str, "%Y/%m/%d %H:%M:%S")
return True
except:
return False
# serviceDeliveryStartTimeStamp "18/09/04 11:05:44+0530",\n',
def decodeServiceDeliveryStartTimeStamp(inputstring):
if inputstring.find(serviceDeliveryStartTimeStamp) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('+')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = '20' + inputstring[first_delimiter+1: second_delimiter]
if is_valid_date(return_string):
#print time.strptime(return_string, "%Y/%m/%d %H:%M:%S")
return return_string
return ""
def decodeServiceDeliveryEndTimeStamp(inputstring):
if inputstring.find(serviceDeliveryEndTimeStamp) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('+')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = '20' + inputstring[first_delimiter+1: second_delimiter]
if is_valid_date(return_string):
#print time.strptime(return_string, "%Y/%m/%d %H:%M:%S")
return return_string
return ""
def decodetrunkGroupIDincoming(inputstring):
if inputstring.find(trunkGroupIDincoming) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('"')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = inputstring[first_delimiter+1: second_delimiter]
if len(return_string) != 8:
return (0,0)
return (int(return_string[0:4]), int(return_string[4:8]))
return (0,0)
def decodetrunkGroupIDoutgoing(inputstring):
if inputstring.find(trunkGroupIDoutgoing) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('"')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = inputstring[first_delimiter+1: second_delimiter]
if len(return_string) != 8:
return (0,0)
return (int(return_string[0:4]), int(return_string[4:8]))
return (0,0)
def getDecodedVN(inputtuple):
'''get VN "Virtual Network"'''
if len(inputtuple) != 2:
return 0
return inputtuple[0]
def getDecodedTG(inputtuple):
'''get TG "Trunk Group"'''
if len(inputtuple) != 2:
return 0
return inputtuple[1]
def calculatePerCallRecordDuriation(start_str_time, end_str_time):
'''during in seconds will be returned'''
starttime = string_toDatetime(start_str_time)
endtime = string_toDatetime(end_str_time)
return (endtime - starttime).seconds
def calculateCallRecordDuriationSum(durationRecordList):
'''Sum Call Record Duriation'''
resultDict = {}
for listitem in durationRecordList:
if len(listitem) == 4:
key = str(listitem[0]) + '-' + str(listitem[1])
print key
if key in resultDict.keys():
tmp = resultDict[key]
tmp[2] = tmp[2] + listitem[2]
tmp[3] = tmp[3] + listitem[3]
else:
resultDict[key] = listitem
durationSumRecordList=[]
for item in resultDict.values():
durationSumRecordList.append(item)
return durationSumRecordList
def saveDurtationInfoToCSV(durationRecordList, outputCSVfile):
''' used to save per CDR call duration result to CSV '''
with open(outputCSVfile,"ab+") as csvfile:
csvfile.write(codecs.BOM_UTF8)
writer = csv.writer(csvfile)
writer.writerow(['VN_ID','TG_ID','INCOMING_DURATION','OUTGOING_DURATION'])
writer.writerows(durationRecordList)
def decodeRecord(RecordItem):
if len(RecordItem) != RECORD_LIST_LENGTH:
return [],[]
start_time = decodeServiceDeliveryStartTimeStamp(RecordItem[serviceDeliveryStartTimeStampINDEX])
end_time = decodeServiceDeliveryEndTimeStamp(RecordItem[serviceDeliveryEndTimeStampINDEX])
callDuriation = calculatePerCallRecordDuriation(start_time, end_time)
incomingVN = getDecodedVN(decodetrunkGroupIDincoming(RecordItem[trunkGroupIDincomingINDEX]))
incomingTG = getDecodedTG(decodetrunkGroupIDincoming(RecordItem[trunkGroupIDincomingINDEX]))
outgoingVN = getDecodedVN(decodetrunkGroupIDoutgoing(RecordItem[trunkGroupIDoutgoingINDEX]))
outgoingTG = getDecodedTG(decodetrunkGroupIDoutgoing(RecordItem[trunkGroupIDoutgoingINDEX]))
print "VN=%d" % incomingVN, "TG=%d" % incomingTG, "incoming CallDuration=%d" % callDuriation
print "VN=%d" % outgoingVN, "TG=%d" % outgoingTG, "outgoing CallDuration=%d" % callDuriation
incomingRecordDurationList = []
incomingRecordDurationList.append(incomingVN)
incomingRecordDurationList.append(incomingTG)
incomingRecordDurationList.append(callDuriation)
incomingRecordDurationList.append(0)
outgoingRecordDurationList = []
outgoingRecordDurationList.append(outgoingVN)
outgoingRecordDurationList.append(outgoingTG)
outgoingRecordDurationList.append(0)
outgoingRecordDurationList.append(callDuriation)
return incomingRecordDurationList,outgoingRecordDurationList
def decodeRecordList(RecordList, durationOverAllList):
''' used to parse the output of loadCDRdecodedFile() function'''
for list_item in RecordList:
#print list_item
retvalue = decodeRecord(list_item)
for item in retvalue:
durationOverAllList.append(item)
return
# load input file
def loadCDRdecodedFile(fileName):
''' used to load the CDR decoded raw text file, and then parse records in the file '''
''' save each record in a list, and save each ist in RecordList '''
# print file name loaded
print "the file to be processed is:", fileName
# read lines from the file and print it out to the screen
RecordList = list()
temp_record = list()
with open(fileName, 'rt') as txtData:
lines=txtData.readlines()
for line in lines:
line.strip()
line.rstrip('\n')
if line.find(RecordHeader) != -1:
#print line
# append 0 -- RecordHeader
if line in temp_record:
if validateRecord(temp_record) != -1:
#print "save the previous record to the list"
#print temp_record
RecordList.append(temp_record)
## reset the list to a new one
temp_record = list()
temp_record.append(line)
elif line.find(IBCFRecord) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(serviceDeliveryStartTimeStamp) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(serviceDeliveryEndTimeStamp) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(trunkGroupID) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(trunkGroupIDincoming) != -1:
# when not save the "trunkGroupID" block, so the found incoming is not the right incoming
if len(temp_record) < 5:
#print "has not save the trunkGroupID block, so the found incoming is not the right incoming"
continue
if trunkGroupID not in temp_record[4]:
#print "has not save the trunkGroupID block, so the found incoming is not the right incoming"
continue
# save the trunkGroupIDincoming
temp_record.append(line)
elif line.find(trunkGroupIDoutgoing) != -1:
# when not save the "trunkGroupID" block, so the found outgoing is not the right outgoing
if len(temp_record) < 5:
#print "has not save the trunkGroupID block, so the found outgoing is not the right outgoing"
continue
if trunkGroupID not in temp_record[4]:
#print "has not save the trunkGroupID block, so the found outgoing is not the right outgoing"
continue
# save the trunkGroupIDoutgoing
temp_record.append(line)
## check if the list element macth
if validateRecord(temp_record) != -1:
RecordList.append(temp_record)
return RecordList
def CDRFileFormatString_toDatetime(filename):
'''"mum01-4_-_24.20180816_-_1801+0530.decoded" to "2018/08/16 18:01:00"'''
#filename[filename.find('.')+1 : filename[filename.rfind('.')]
print filename
# time info in filename
timeinfoinfile = filename[filename.find('.') + 1 : filename.rfind('+')]
#print timeinfoinfile
return datetime.datetime.strptime(timeinfoinfile, "%Y%m%d_-_%H%M")
def datetime_toString(dt):
return dt.strftime("%Y-%m-%d %H:%M:%S")
def datetime_string_to_filename_string(dt):
rt = string_toDatetime(dt)
return rt.strftime("%Y%m%d_%H%M%S")
def string_toDatetime(st):
'''convert timestamp in string fromat to datetime format'''
return datetime.datetime.strptime(st, "%Y/%m/%d %H:%M:%S")
def translateFileNametoTimeString(filename):
'''"mum01-4_-_24.20180816_-_1801+0530.decoded" to "2018/08/16 18:01:00"'''
return datetime_toString(CDRFileFormatString_toDatetime(filename))
def checkFileInTimeRange(starttime, endtime, inputfilename):
''''''
starttimeDatetime = string_toDatetime(starttime)
endtimeDatetime = string_toDatetime(endtime)
fileDatetime = CDRFileFormatString_toDatetime(inputfilename)
if (starttimeDatetime < fileDatetime < endtimeDatetime) or fileDatetime == starttimeDatetime:
print "in range"
return True
else:
print "out of range"
return False
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-p", "--path", dest="path",
help="list file from the path")
parser.add_option("-d", "--day", dest="day",
help="read day from input, in format 2018/10/11")
parser.add_option("-s", "--starttime", dest="starttimestamp",
help="read start time from input, in format 09:01:00")
parser.add_option("-e", "--endttime", dest="endtimestamp",
help="read end time from input, in format 11:01:35")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose")
(options, args) = parser.parse_args()
#if len(args) != 1:
# parser.error("incorrect number of arguments")
#if options.verbose:
# print "reading %s..." % options.filename
if options.path:
print "options.path: ", options.path
if options.day:
print "options.day: ", options.day
if options.starttimestamp:
print "options.starttimestamp: ", options.starttimestamp
if options.endtimestamp:
print "options.endtimestamp: ", options.endtimestamp
#resultRecordList = loadCDRdecodedFile(sys.argv[1])
#printRecordList(resultRecordList)
#durationOverAllList = []
#retvalue = decodeRecordList(resultRecordList, durationOverAllList)
#saveDurtationInfoToCSV(durationOverAllList, "Hello.csv")
#os.system('dir *')
#dt = translateFileNametoTimeString('mum01-4_-_24.20180816_-_1801+0530.decoded')
#print dt
starttime = options.day + ' ' + options.starttimestamp
endtime = options.day + ' ' + options.endtimestamp
#checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180816_-_1801+0530.decoded') # 0 - in range
#checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180816_-_1811+0530.decoded') # 1
#checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180816_-_1859+0530.decoded')
#checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180816_-_1900+0530.decoded')
# checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180816_-_1759+0530.decoded')
#checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180817_-_1801+0530.decoded') # out of range
#checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180815_-_1801+0530.decoded') # out of range
#filelist = os.system('dir *')
filelist = os.listdir(options.path)
durationOverAllList = []
for filename in filelist:
if checkFileInTimeRange(starttime, endtime, filename):
os.system('asnccflsearch ')
resultRecordList = loadCDRdecodedFile(options.path + '\\' + filename)
#printRecordList(resultRecordList)
retvalue = decodeRecordList(resultRecordList, durationOverAllList)
tosavedFilename = '/storage/duration_from_cdr/'+duration_' + datetime_string_to_filename_string(options.day + ' ' + options.starttimestamp) + '-' + datetime_string_to_filename_string(options.day + ' ' + options.endtimestamp) + '.csv'
print "Calculation Result is to be saved in", tosavedFilename
saveDurtationInfoToCSV(durationOverAllList, 'raw.'+tosavedFilename)
saveDurtationInfoToCSV(calculateCallRecordDuriationSum(durationOverAllList), tosavedFilename)
if __name__ == "__main__":
#main()<file_sep>/jdBuyMask-master/requirements.txt
beautifulsoup4==4.8.2
requests==2.22.0
pillow==7.0.0
schedule==0.6.0<file_sep>/VN_TG/create_target_list.py
#-*- coding: utf-8 -*-
import sys
import os
from optparse import OptionParser
if __name__ == "__main__":
'''All parameters are mandatory, please make sure they are used'''
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-s", "--sourcestring", dest="sourcestring",
help="input source string")
parser.add_option("-a", "--appendstring", dest="appendstring",
help="append the appendstring to sourcestring")
(options, args) = parser.parse_args()
source_string = options.sourcestring
append_string = options.appendstring
#source_string = source_string + append_string
#source_string = source_string + append_string
try:
tmp_fo = open('tmp_list_data.txt', "a")
tmp_fo.write(source_string)
except IOError:
print "failed to open tmp_list_data.txt"
#print source_string
tmp_fo.close()<file_sep>/parseMCAST_MSG.py
import sys
import struct
import binascii
import ctypes
#read struct by struct, below is the struct length
STRUCT_LENGTH = 36
MCAST_HEADER_LENGTH = 24*2
MSG_HEADER_LENGTH = 4*2
#below is the structure of the struct, the defination
#parse_model = struct.Struct('I3sf')
#prebuffer = ctypes.create_string_buffer(parse_model)
parse_model='IIII'
INTER_LENGTH=4
CHAR_LENGTH=1
SHORT_LENGTH=2
FACTOR_MY=2
#sys.argv.append("D:\NewPC\workingTips\parseMcastMsgPython\Data.txt")
if __name__ == '__main__':
f=open(sys.argv[1] ,'rb')
f.seek(0,0)
#read header
read_content = f.read(MCAST_HEADER_LENGTH)
if len(read_content) == MCAST_HEADER_LENGTH:
pool_type = f.read(CHAR_LENGTH*FACTOR_MY)
pool_id = f.read(CHAR_LENGTH*FACTOR_MY)
vg_count = f.read(CHAR_LENGTH*FACTOR_MY)
vg_count = f.read(CHAR_LENGTH*FACTOR_MY)+vg_count
print ("%10s%10s%10s"%('pooltype','poolid','vg_count'))
print ("%10s%10s%10s"%(int(pool_type,16),int(pool_id,16),int(vg_count,16)))
print ("%12s%12s%12s%12s%12s%12s%12s%12s%12s%12s"%('vn_id','tg_id','incmSess','outgSess','totalSess','incmBw','outgBw','totalBw','videoBw','audioBw'))
while True:
vn_id = f.read(CHAR_LENGTH*FACTOR_MY)
if len(vn_id) == 0:
break
vn_id = f.read(CHAR_LENGTH*FACTOR_MY) + vn_id
tg_id = f.read(CHAR_LENGTH*FACTOR_MY)
tg_id = f.read(CHAR_LENGTH*FACTOR_MY) + tg_id
incmSess = f.read(CHAR_LENGTH*FACTOR_MY)
incmSess = f.read(CHAR_LENGTH*FACTOR_MY) + incmSess
incmSess = f.read(CHAR_LENGTH*FACTOR_MY) + incmSess
incmSess = f.read(CHAR_LENGTH*FACTOR_MY) + incmSess
outgSess = f.read(CHAR_LENGTH*FACTOR_MY)
outgSess = f.read(CHAR_LENGTH*FACTOR_MY) + outgSess
outgSess = f.read(CHAR_LENGTH*FACTOR_MY) + outgSess
outgSess = f.read(CHAR_LENGTH*FACTOR_MY) + outgSess
totalSess = f.read(CHAR_LENGTH*FACTOR_MY)
totalSess = f.read(CHAR_LENGTH*FACTOR_MY) + totalSess
totalSess = f.read(CHAR_LENGTH*FACTOR_MY) + totalSess
totalSess = f.read(CHAR_LENGTH*FACTOR_MY) + totalSess
incmBw = f.read(CHAR_LENGTH*FACTOR_MY)
incmBw = f.read(CHAR_LENGTH*FACTOR_MY) + incmBw
incmBw = f.read(CHAR_LENGTH*FACTOR_MY) + incmBw
incmBw = f.read(CHAR_LENGTH*FACTOR_MY) + incmBw
outgBw = f.read(CHAR_LENGTH*FACTOR_MY)
outgBw = f.read(CHAR_LENGTH*FACTOR_MY) + outgBw
outgBw = f.read(CHAR_LENGTH*FACTOR_MY) + outgBw
outgBw = f.read(CHAR_LENGTH*FACTOR_MY) + outgBw
totalBw = f.read(CHAR_LENGTH*FACTOR_MY)
totalBw = f.read(CHAR_LENGTH*FACTOR_MY) + totalBw
totalBw = f.read(CHAR_LENGTH*FACTOR_MY) + totalBw
totalBw = f.read(CHAR_LENGTH*FACTOR_MY) + totalBw
videoBw = f.read(CHAR_LENGTH*FACTOR_MY)
videoBw = f.read(CHAR_LENGTH*FACTOR_MY) + videoBw
videoBw = f.read(CHAR_LENGTH*FACTOR_MY) + videoBw
videoBw = f.read(CHAR_LENGTH*FACTOR_MY) + videoBw
audioBw = f.read(CHAR_LENGTH*FACTOR_MY)
audioBw = f.read(CHAR_LENGTH*FACTOR_MY) + audioBw
audioBw = f.read(CHAR_LENGTH*FACTOR_MY) + audioBw
audioBw = f.read(CHAR_LENGTH*FACTOR_MY) + audioBw
#print
#try:
print ("%12d%12d%12d%12d%12d%12d%12d%12d%12d%12d"%(int(vn_id,16),int(tg_id,16),int(incmSess,16),int(outgSess,16),int(totalSess,16),int(incmBw,16),int(outgBw,16),int(totalBw,16),int(videoBw,16),int(audioBw,16)))
#except Exception,e:
# print "Error Happens:" + str(e)
#print vn_id.ljust(12), tg_id.ljust(12),incmSess.ljust(12),outgSess.ljust(12),totalSess.ljust(12),incmBw.ljust(12),outgBw.ljust(12),totalBw.ljust(12),videoBw.ljust(12),audioBw.ljust(12)
f.close()
print 'finish'
#wait any input to quit the display
raw_input()
<file_sep>/spider/sipder_1.py
# -*- coding: utf-8 -*-
import urllib
import urllib2
import gzip, StringIO
import zlib
'''
proxy_handler = urllib2.ProxyHandler({'http': '172.16.58.3:8000'})
opener = urllib2.build_opener(proxy_handler)
r = opener.open('http://finance.sina.com.cn/realstock/company/sz300033/nc.shtml')
print(r.read())
'''
request = urllib2.Request('http://www.163.com')
request.add_header('Accept-encoding', 'gzip')
# remember to update the proxy
proxy_handler = urllib2.ProxyHandler({'http': 'xxx.xxx.xxx.xxx:xxxx'})
opener = urllib2.build_opener(proxy_handler)
response = opener.open(request)
html = response.read()
gzipped = response.headers.get('Content-Encoding')
if gzipped:
html = StringIO.StringIO(html)
#html = zlib.decompress(html, 16 + zlib.MAX_WBITS)
gzipper = gzip.GzipFile(fileobj=html)
html = gzipper.read()
else:
typeEncode = sys.getfilesystemencoding()##系统默认编码
infoencode = chardet.detect(html).get('encoding','utf-8')##通过第3方模块来自动提取网页的编码
html = content.decode(infoencode,'ignore').encode(typeEncode)##先转换成unicode编码,然后转换系统编码输出
#print html
print html<file_sep>/git_tips.md
# get change from remote 相当于是从远程获取最新版本到本地,不会自动merge
git fetch origin master
git log -p master..origin/master
git merge origin/master
# get change from remote 相当于是从远程获取最新版本并merge到本地
git pull origin master
#
git add filename filename2 file...
git commit file1 -m "tips"
git commit -m "tips for all"
git push origin master
# get a new project from github
git clone https://github.com/JerryBluesnow/PythonLearning.git<file_sep>/stock/stock2/stock/stockGet.5.py
import sys
import os
import datetime as dt
import json
import tushare as ts
from openpyxl import load_workbook
columns_first_day = [12, 13, 14, 15]
columns_mid_1_day = [17, 18, 19, 20]
columns_mid_2_day = [22, 23, 24, 25]
columns_last_day = [27, 28, 29, 30]
setup_base_line = 10000
const_rate_interval = 0.05
const_lost_w_rate = 1 - const_rate_interval
const_benefit_w_rate = 1 + const_rate_interval
const_last_column = 31
const_row_max = 9999
def datetime_toString(dt):
return dt.strftime("%Y-%m-%d")
def string_toDatetime(string):
return dt.datetime.strptime(string, "%Y-%m-%d")
def string_toTimestamp(strTime):
return dt.mktime(string_toDatetime(strTime).timetuple())
def timestamp_toString(stamp):
return dt.strftime("%Y-%m-%d", time.localtime(stamp))
def datetime_toTimestamp(dateTim):
return dt.mktime(dateTim.timetuple())
def day_string_plus_one(_day_input):
date = string_toDatetime(_day_input) + dt.timedelta(days=1)
return datetime_toString(date)
def get_hist_data_days(_stock_code, _day_start, _day_counts):
df = ts.get_hist_data(_stock_code, start=_day_start, end=_day_start)
if df is None:
return df
return df[['open', 'close', 'high', 'low']]
def search_data(stock_code, input_day, input_limit):
count = 0
a_store_data = [[]]
try_times = 0
while (count < input_limit):
df = get_hist_data_days(stock_code, input_day, 1)
if df is None or len(df) == 0:
print 'got nothing:', 'stock:', stock_code, "day: ", input_day
input_day = day_string_plus_one(input_day)
try_times = try_times + 1
if try_times == 10:
return a_store_data
continue
close_price = df[u'close']
open_price = df[u'open']
high_price = df[u'high']
low_price = df[u'low']
a_store_data.append([open_price[0], close_price[0], high_price[0], low_price[0]])
input_day = day_string_plus_one(input_day)
count = count + 1
return a_store_data
def write_to_cell(ws, row_index, column_index, value):
print "write value: ", value, " to row=", row_index, "column=", column_index
ws.cell(row=row_index, column=column_index).value = value
# when lost_rate < const_rate_interval, we need to sell it out
def is_needed_buy_in(ws, row_index, columns, price, count):
print __name__, ":", "input price is ", price
mid_price = price
for col_index in columns:
get_price = ws.cell(row=row_index, column=col_index).value
if get_price is None:
print __name__, ":", "get Price is None"
break
if mid_price > get_price:
print __name__, ":", "set mid_price to ", get_price
mid_price = get_price
if mid_price <= (price * const_lost_w_rate):
print __name__, ":", "need 2 times buy in to update..."
return True
return False
# once profit_rate > 5%, we need to sell it out
def is_needed_sell_out(ws, row_index, columns, price, count):
print __name__, ":", "input price is ", price
mid_price = price
for col_index in columns:
get_price = ws.cell(row=row_index, column=col_index).value
if get_price is None:
print __name__, ":", "get Price is None"
break
if (price * const_benefit_w_rate) <= get_price:
print __name__, ":", "sell price is ", (price * const_benefit_w_rate)
# is_sell , sell_price, total_count, total_amount
return (True, (price * const_benefit_w_rate), count, (price * const_benefit_w_rate * count))
print __name__, ":", "will not sell in this check....."
return (True, (price * const_benefit_w_rate), count, (price * const_benefit_w_rate * count))
# return the rate of profit
def to_sell_in_final_day_with_close_price(ws, row_index, columns, price):
for col_index in columns:
get_price = ws.cell(row=row_index, column=col_index).value
if get_price is None:
print "get Price is None"
return (-1)
print "sell price of the final day: ", get_price
return ((get_price - price) / get_price) * 100
def calculate_from_excel():
dirname, filename = os.path.split(os.path.abspath(__file__))
read_excel_file_name = dirname + '\stock_s.xlsx'
print read_excel_file_name
wb = load_workbook(read_excel_file_name)
sheets = wb.sheetnames
sheet_first = sheets[0]
#
ws = wb[sheet_first]
print "***"
print sheet_first
print ws.title
print "^^^"
rows = ws.rows
input_limit = 5
#print "stock_code: ", "date: ", "close: ", "open: ", "high: ", "low: "
row_index = 3 # start from row 3 to calculate
while row_index < const_row_max:
total_count = 0
average_price = 0
stock_code = ws.cell(row=row_index, column=2).value
if stock_code is None:
print "Have finish the calculation......"
break
print "Going to calculate code: ", stock_code
# the open price of the first day
average_price = ws.cell(row=row_index, column=12).value
if average_price is None:
row_index = row_index + 1
continue
total_count = calc_count(average_price, setup_base_line)
total_amount = average_price * total_count
print "buy in code: ", stock_code, ", price: ", average_price, ", total count: ", total_count, ", totoal amount: ", total_amount
#is_sell = is_needed_sell_out(ws, row_index, columns_mid_1_day, average_price, total_count)
is_sell, sell_price, total_count, total_amount = is_needed_sell_out(
ws, row_index, columns_mid_1_day, average_price, total_count)
if is_sell == True:
print __name__, ":", stock_code, " is selled in the first day w ",
print " average_price : ", average_price, " sell_price : ", sell_price,
print " total_count : ", total_count, " total_amount : ", total_amount,
print " profit_rate : ", const_rate_interval
write_to_cell(ws, row_index, const_last_column,
const_rate_interval)
row_index = row_index + 1
continue
if is_needed_buy_in(ws, row_index, columns_mid_1_day, average_price, total_count) == True:
total_count = total_count * 3
average_price = calc_price(average_price)
total_amount = average_price * total_count
print "after second day, code: ", stock_code, ", price: ", average_price, ", total count: ", total_count, ", totoal amount: ", total_amount
is_sell, sell_price, total_count, total_amount = is_needed_sell_out(
ws, row_index, columns_mid_1_day, average_price, total_count)
if is_sell == True:
print __name__, ":", stock_code, " is selled in the first day w ",
print " average_price : ", average_price, " sell_price : ", sell_price,
print " total_count : ", total_count, " total_amount : ", total_amount,
print " profit_rate : ", const_rate_interval
write_to_cell(ws, row_index, const_last_column,
const_rate_interval)
row_index = row_index + 1
continue
if is_needed_buy_in(ws, row_index, columns_mid_2_day, average_price, total_count) == True:
total_count = total_count * 3
average_price = calc_price(average_price)
total_amount = average_price * total_count
print "after third day, code: ", stock_code, ", price: ", average_price, ", total count: ", total_count, ", totoal amount: ", total_amount
print "after calculation, with the open price of the forth day......", " average_price: ", average_price, "total_amount: ", total_amount
write_to_cell(ws, row_index, const_last_column, to_sell_in_final_day_with_close_price(
ws, row_index, columns_last_day, average_price))
row_index = row_index + 1
print "save calculation result to ", const_last_column
wb.save('stock_s.xlsx')
return
def calc_price(price): # standard_f 0.97
return ((1 + 2 * const_lost_w_rate) * price / 3)
def calc_count(price, set_up_value):
return (((set_up_value // price) // 100) * 100)
def main():
calculate_from_excel()
return
main()
<file_sep>/gamefucker/autoLD.py
# -*- coding: utf-8 -*-
import sys
import pyautogui
from pywinauto import application
# 读写注册表模块
import _winreg
import os
# 配置参数
pyautogui.PAUSE = 1.5
pyautogui.FAILSAFE = True
# 定义函数
def QueryDnplayerPath():
'''the function is used to find the installed directory of dnplayer.exe'''
# 打开注册表
# cmd --> regedit
# HKEY_CURRENT_USER/Software/ChangZhi2/dnplayer/InstallDir
# dnplayer
# dnmultiplayer.exe 雷电多开器
try:
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,r"Software\ChangZhi2\dnplayer")
except WindowsError:
print "dnplayer isn't installed in the system, please install it before using this script"
sys.exit(0)
try:
value, type = _winreg.QueryValueEx(key, "InstallDir")
except WindowsError:
print "dnplayer InstallDir query failed. not installed in the system, please install it before using this script"
sys.exit(0)
dnplayer_path = value + 'dnmultiplayer.exe'
print "dnplayer's path:", dnplayer_path
return dnplayer_path
def StartDnplayer(_dnplayer_path_):
if _dnplayer_path_ == '':
print "Invalid Path: ", _dnplayer_path_
sys.exit(0)
app = application.Application(backend='win32').start(_dnplayer_path_)
return app
if __name__ == '__main__':
# 查找dnplayer.exe安装路径
dnplayer_path = QueryDnplayerPath()
# 启动dnplayer.exe
app = StartDnplayer(dnplayer_path)
app.window().wait('visible')
#image = pyautogui.screenshot()
#image.save('testing.png')
#pyautogui.screenshot(region=(20, 20, 50, 50))
#sys.exit(0)
working_path = os.path.abspath('.')
selectAllButton = None
while selectAllButton is None:
print " try ..."
selectAllButton = pyautogui.locateOnScreen('images_ld/SelectAll.png', grayscale=True)#, confidence=0.999)
#print "SelectAll.png not matched, quit..."
#sys.exit(0)
print "found..."
current_button = selectAllButton
current_button_x, current_button_y = pyautogui.center(current_button)
print current_button_x, current_button_y
pyautogui.moveTo(current_button_x, current_button_y)
pyautogui.click(current_button_x, current_button_y)
copyMNQButton = None
while copyMNQButton is None:
print " try ..."
copyMNQButton = pyautogui.locateOnScreen('images_ld/CopyMNQ.png', grayscale=True)
print "found..."
current_button = copyMNQButton
current_button_x, current_button_y = pyautogui.center(current_button)
print current_button_x, current_button_y
pyautogui.moveTo(current_button_x, current_button_y)
pyautogui.click(current_button_x, current_button_y)
#print app.window(title_re = u'雷电模拟器', class_name = 'LDPlayerMainFrame').print_control_identifiers()
#print app.window(title_re = u'雷电多开器', class_name = 'LDMultiPlayerMainFrame').print_control_identifiers()
#dlg_spec = app[u'雷电多开器']
#dlg_spec.print_control_identifiers()
#app.LDPlayerMainFrame.MenuSelect('软件设置'.decode('gb2312'))
#app[LDPlayerMainFrame]
#try:
# app.connect(u'雷电模拟器')
#except WindowsError:
# print u'could not found 雷电模拟器'
#
#app.menu_click(window_name,menulist)
'''
Control Identifiers:
LDPlayerMainFrame - '雷电模拟器' (L159, T56, R1761, B994)
[u'\u96f7\u7535\u6a21\u62df\u5668LDPlayerMainFrame', u'LDPlayerMainFrame', u'\u96f7\u7535\u6a21\u62df\u5668']
child_window(title="雷电模拟器", class_name="LDPlayerMainFrame")
|
| RenderWindow - 'TheRender' (L160, T92, R1760, B992)
| [u'TheRenderRenderWindow', u'TheRender', u'RenderWindow']
| child_window(title="TheRender", class_name="RenderWindow")
None
'''<file_sep>/Spider/walkfile.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, re, datetime
class Find(object):
def __init__(self, root, input_file):
"""
--初始化
"""
self.root = root # 文件树的根
self.input_files = [] # 待查询的字符串集合
self.files = [] # 待匹配的文件集合
self.current = 0 # 正在匹配的文件集合的位置
f = file(input_file, "r")
old_content = f.read()
f.close()
self.input_files = old_content.split('\n') # 将待匹配字符串保存在数组中
@staticmethod
def find_file(self):
"""
--查找文件,即遍历文件树将查找到的文件放在文件集合中
:return:
"""
# python中的walk方法可以查找到所给路径下的所有文件和文件夹,这里只用文件
for root, dirs, files in os.walk(self.root, topdown=True):
for name in files:
self.files.append(os.path.join(root, name))
# print(os.path.join(root, name))
# for name in dirs:
# print(os.path.join(root, name))
@staticmethod
def walk(self):
"""
--逐一查找,并将结果存入result.txt文件中
:param self:
:return:
"""
for item1 in self.files:
Find.traverse_file(self, item1)
try:
result = ''
for item3 in self.input_files:
result += item3 + '\n'
f = file("./result_files.txt", "w")
f.write(result)
f.close()
except IOError, msg:
print "Error:", msg
else:
print "OK"
@staticmethod
def traverse_file(self, file_path):
"""
--遍历文件,匹配字符串
:return:
"""
f = file(file_path, "r")
file_content = f.read()
f.close()
input_files = []
for item2 in self.input_files:
if item2:
# 正则匹配,不区分大小写
searchObj = re.search(r'(.*)' + item2 + '.*', file_content, re.M | re.I)
if searchObj:
continue
else:
input_files.append(item2)
self.input_files = input_files
if __name__ == "__main__":
print datetime.datetime.now()
findObj = Find('.', "./input_files.txt")
findObj.find_file(findObj)
findObj.walk(findObj)
print datetime.datetime.now()
<file_sep>/multi_process_thread/concurrent.futures_5.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
# Python并发编程之线程池/进程池
# https://segmentfault.com/a/1190000007926055#articleHeader3
# 选择wait
#-------------------------------------------------------------------------------------------#
'''
'''
# example4.py
import concurrent.futures
#import urllib.request
import urllib2
URLS = ['http://httpbin.org', 'http://example.com/', 'https://api.github.com/']
def load_url(url):
with urllib2.urlopen(url, timeout=60) as conn:
return conn.read()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
for url, data in zip(URLS, executor.map(load_url, URLS)):
print('%r page is %d bytes' % (url, len(data)))<file_sep>/cdr_to_csv/python.time.1.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
import datetime
import os
PREFIX_NAME=''
SUFFIX_NAME=''
UP_WAIT_SECONDS=0
DOWN_WAIT_SECONDS=0
#A20181019.0145+0800-0200+0800_ManagedElement=lcp-1
INTERVAL_TIME=5
SECONDS_IN_MINUTE=60
if __name__ == "__main__":
# make 10 seconds as a different, to make it exact in 5
print "the script is used to make sure the scenario will be finished in not than 3.5 minutes in 5 interval"
current_timestamp = datetime.datetime.now()
current_timestamp.strftime('%m%d%H%M%S')
second = current_timestamp.strftime('%S')
minute = current_timestamp.strftime('%M')
hour = current_timestamp.strftime('%H')
minute_offset = int(minute) % INTERVAL_TIME
if minute_offset == 0:
up_timestamp = current_timestamp
down_timestamp = up_timestamp + datetime.timedelta(minutes=INTERVAL_TIME)
PREFIX_NAME = 'A' + up_timestamp.strftime('%Y%m%d') + '.' + up_timestamp.strftime('%H%M')
SUFFIX_NAME = down_timestamp.strftime('%H%M')
UP_WAIT_SECONDS = 0 * SECONDS_IN_MINUTE
DOWN_WAIT_SECONDS = (INTERVAL_TIME - 0) * SECONDS_IN_MINUTE - int(second)
elif minute_offset == 1:
up_timestamp = current_timestamp + datetime.timedelta(minutes=(0 - minute_offset))
down_timestamp = up_timestamp + datetime.timedelta(minutes=INTERVAL_TIME)
PREFIX_NAME = 'A' + up_timestamp.strftime('%Y%m%d') + '.' + up_timestamp.strftime('%H%M')
SUFFIX_NAME = down_timestamp.strftime('%H%M')
UP_WAIT_SECONDS = 0 * SECONDS_IN_MINUTE
DOWN_WAIT_SECONDS = (INTERVAL_TIME - minute_offset) * SECONDS_IN_MINUTE - int(second)
else:
up_timestamp = current_timestamp + datetime.timedelta(minutes=(INTERVAL_TIME - minute_offset))
down_timestamp = up_timestamp + datetime.timedelta(minutes=INTERVAL_TIME)
PREFIX_NAME = 'A' + up_timestamp.strftime('%Y%m%d') + '.' + up_timestamp.strftime('%H%M')
SUFFIX_NAME = down_timestamp.strftime('%H%M')
UP_WAIT_SECONDS = (INTERVAL_TIME - minute_offset) * SECONDS_IN_MINUTE - int(second)
DOWN_WAIT_SECONDS = INTERVAL_TIME * SECONDS_IN_MINUTE + UP_WAIT_SECONDS
print "PREFIX_NAME=%s" % PREFIX_NAME
print "SUFFIX_NAME=%s" % SUFFIX_NAME
print "UP_WAIT_SECONDS=%d" % UP_WAIT_SECONDS
print "DOWN_WAIT_SECONDS=%d" % DOWN_WAIT_SECONDS<file_sep>/DataFrame/pandas.dataframe.test1.py
import pandas as pd
import numpy as np
print pd.DataFrame([1, 2, 3, 4, 5], columns=['cols'], index=['a','b','c','d','e'])
print pd.DataFrame([[1, 2, 3],[4, 5, 6]], columns=['col1','col2','col3'], index=['a','b'])
print pd.DataFrame(np.array([[1,2],[3,4]]), columns=['col1','col2'], index=['a','b'])
print pd.DataFrame({'col1':[1,3],'col2':[2,4]},index=['a','b'])<file_sep>/first.py
import urllib2
import socket
socket.setdefaulttimeout(10) # 10 seconds later timeout
urllib2.socket.setdefaulttimeout(10) # 10 seconds later timeout
r = urllib2.Request("http://classweb.loxa.com.tw/dino123/air/P1000775.jpg")
try:
print 111111111111111111
f = urllib2.urlopen(r)
print 2222222222222222
result = f.read()
print result
except Exception, e:
print "444444444444444444---------" + str(e)
import time
localtime = time.asctime(time.localtime(time.time()))
print "current local time is :", localtime
import calendar
cal = calendar.month(2017, 3)
print cal
def powerpower(x, y=2):
sum = 1
while y > 0:
y = y - 1
sum = sum * x
return sum
def powerpower2(x, y, z):
return x * y * z
print powerpower(10, 4) + powerpower2(10, 20, 31) + powerpower(20)
def enrollstudent(name, sex, age=6, city="QD"):
print 'name', name.ljust(10), 'sex', sex.ljust(10), 'age', age, 'city', city.ljust(10)
enrollstudent("Jerryzhang", "male", city="BeiJing")
enrollstudent("MerryH", "female", age=7, city="Shanghai")
def add_end(LIST=None):
if LIST is None:
LIST = []
LIST.append('END')
return LIST
print add_end()
print add_end(['THIG'])
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print calc([1, 2, 3])
def calc2(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print calc2(1, 2, 3)
def person(name, age, **keyword):
if 'city' in keyword:
pass
if 'job' in keyword:
pass
print 'name', name.ljust(10), 'age', age, 'other', keyword
person('HengHeng', 1.6, city='Beijing', addr='Chaoyang', zipcode=123456)
# tail recursion
def tailRecursion(num, product=1):
print 'num:', num, 'prodcut:', product
if num == 1:
return product
return tailRecursion(num - 1, num * product)
print tailRecursion(5)
#Git fetch origin master
#git log -p master..origin/master
#git merge origin/master
#
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print key
print d[key]
for value in d.values():
print value
from collections import Iterable
print isinstance('abc', Iterable)
print isinstance([1,2,3], Iterable)
print isinstance(123, Iterable)
for i, value in enumerate(['A', 'B', 'C']):
print i, value
for x, y in [(1, 1), (2, 4), (3, 9)]:
print x, y
#print tailRecursion(0)
# advantaged feature
L = []
n = 1
while n <= 99:
L.append(n)
n = n + 2
print L
#print the front half of the List
print 9/2.0
print 9//2.0
for x in range(0, len(L)//2, -1):
print L[x]
print range(0, 5)
print range(0, -5, -2)
print range(-5)
print range(0)
print range(1)<file_sep>/installment_payment/installment_payment.py
# -*- coding: utf-8 -*-
import math
# 定义函数
def installment_payment( monthly_interest_rate, payment_periods, repayment_month_index ):
"计算中信银行新快现公式:"
"monthly_interest_rate - 官方月利率"
"payment_periods - 分期期数 3/6/9/12/15/24/36"
"repayment_month_index - 第几个月提前还款"
#分母 (1+2+3+...+n-1), n>=2,等差数列求和公式 ( (repayment_month_index * (repayment_month_index - 1)) / 2 )
denominator = 2 * repayment_month_index * (payment_periods - repayment_month_index) + repayment_month_index * (repayment_month_index + 1)
#分子 numerator:
numerator = 24 * (payment_periods * repayment_month_index * monthly_interest_rate + ((payment_periods - repayment_month_index) * 3 /(float)(100)) )
yearly_interest_rate = numerator/(float)(denominator)
print "++++++++++++++++++++++++++++++++++++++++++"
print "中信新快现月利率(百分之...):", monthly_interest_rate * 100, "%"
print "分期期数: ", payment_periods
print "第几个月提前还款: ", repayment_month_index
print "分期年化利率(百分之...): ", yearly_interest_rate * 100, "%"
print "++++++++++++++++++++++++++++++++++++++++++"
return
# 调用函数
for repayment_month_index in range(1, 36 + 1):
installment_payment(0.76/100, 36, repayment_month_index)
sequence = [3, 6, 12, 18, 24, 36]
for index, payment_periods in enumerate(sequence):
installment_payment(0.76/100, payment_periods, payment_periods)
<file_sep>/cdr_to_csv/version-1.2/cdr_to_csv.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------#
# version 1.2
# 1. take disk into consideration, in this version, the script will decode 1 cdr
# raw file and parse it, then delete the .decoded file; then go on to process
# the new file
# 2. 24 hours will be supported.
# 3. if the output .csv/.raw.csv file exist, will delete it and create a new one
#-------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------#
# version 1.1 add INGRESS_ERLANGS/EGRESS_ERLANGS to replace INGRESS_DURATION/EGRESS_DURATION
#-------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------#
'''
Usage:
python cdr_to_csv.py -d 2018/10/10 -s 14:00:00 -e 14:59:59 -p /storage/ccfl_app/charging/stream1/primary
Tips:
default filename format:
CCFL0_-_133.20181011_-_1651+0530.decoded
for UT test, need to: rename mum01-4 CCFL0 /storage/ccfl_app/charging/stream1/primary/*
'''
import sys
import time
import datetime
import csv
import codecs
import os
#from numpy import *
import random
from optparse import OptionParser
RecordHeader = "Record Header:"
IBCFRecord = "value IMSRecord ::= iBCFRecord :"
serviceDeliveryStartTimeStamp = "serviceDeliveryStartTimeStamp"
serviceDeliveryEndTimeStamp = "serviceDeliveryEndTimeStamp"
trunkGroupID = "trunkGroupID"
trunkGroupIDincoming = "incoming"
trunkGroupIDoutgoing = "outgoing"
PER_ERLANG_INTERVAL = 3600
RecordHeaderINDEX = 0
IBCFRecordINDEX = 1
serviceDeliveryStartTimeStampINDEX = 2
serviceDeliveryEndTimeStampINDEX = 3
trunkGroupIDINDEX = 4
trunkGroupIDincomingINDEX = 5
trunkGroupIDoutgoingINDEX = 6
# the above variable count
RECORD_LIST_LENGTH = 7
call_duration_stored_directory = '/storage/duration_from_cdr'
cdr_decoded_directory = '/export/home/lss/ccfl_decode'
cdrDecodedFileDir = '/export/home/lss/ccfl_decode'
# check if the list element macth
def validateRecord(oneRecordList):
if len(oneRecordList) != RECORD_LIST_LENGTH:
return -1
if RecordHeader not in oneRecordList[0]:
return -1
if IBCFRecord not in oneRecordList[1]:
return -1
if serviceDeliveryStartTimeStamp not in oneRecordList[2]:
return -1
if serviceDeliveryEndTimeStamp not in oneRecordList[3]:
return -1
if trunkGroupID not in oneRecordList[4]:
return -1
if trunkGroupIDincoming not in oneRecordList[5]:
return -1
if trunkGroupIDoutgoing not in oneRecordList[6]:
return -1
# validation of the input passed
return 0
def printRecordList(RecordList):
for list_item in RecordList:
print sys._getframe().f_code.co_name, ":", list_item
return
def is_valid_cdr_file_string(str):
'''check if the input string(mum01-4_-_24.20180816_-_1801+0530) is in a valide time format: "%Y%m%d_-_%H%M"'''
print "Verify File Name %s if in good format: mum01-4_-_24.20180816_-_1801+0530" % str
startpos = str.find('.')
endpos = str.rfind('+')
print sys._getframe().f_code.co_name, ":", startpos, endpos
if startpos == -1:
return False
if endpos == -1:
return False
if (startpos + 1) > endpos:
return False
if (startpos + 1) == endpos:
return False
try:
time.strptime(str[startpos+1:endpos], "%Y%m%d_-_%H%M")
return True
except:
return False
def is_valid_date(str):
'''check if the input string is in a valide time format: "%Y/%m/%d %H:%M:%S"'''
try:
time.strptime(str, "%Y/%m/%d %H:%M:%S")
return True
except:
return False
def is_valid_Day(str):
'''check if the input string is in a valide time format: "%Y/%m/%dS"'''
try:
time.strptime(str, "%Y/%m/%d")
return True
except:
return False
def is_valid_HourMinSec(str):
'''check if the input string is in a valide time format: "%H:%M:%S"'''
try:
time.strptime(str, "%H:%M:%S")
return True
except:
return False
# serviceDeliveryStartTimeStamp "18/09/04 11:05:44+0530",\n',
def decodeServiceDeliveryStartTimeStamp(inputstring):
if inputstring.find(serviceDeliveryStartTimeStamp) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('+')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = '20' + inputstring[first_delimiter+1: second_delimiter]
if is_valid_date(return_string):
#print time.strptime(return_string, "%Y/%m/%d %H:%M:%S")
return return_string
return ""
def decodeServiceDeliveryEndTimeStamp(inputstring):
if inputstring.find(serviceDeliveryEndTimeStamp) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('+')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = '20' + inputstring[first_delimiter+1: second_delimiter]
if is_valid_date(return_string):
#print time.strptime(return_string, "%Y/%m/%d %H:%M:%S")
return return_string
return ""
def decodetrunkGroupIDincoming(inputstring):
if inputstring.find(trunkGroupIDincoming) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('"')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = inputstring[first_delimiter+1: second_delimiter]
if len(return_string) != 8:
return (0,0)
return (int(return_string[0:4]), int(return_string[4:8]))
return (0,0)
def decodetrunkGroupIDoutgoing(inputstring):
if inputstring.find(trunkGroupIDoutgoing) == -1:
return
first_delimiter = inputstring.find('"')
second_delimiter = inputstring.rfind('"')
#print first_delimiter,second_delimiter
if first_delimiter != second_delimiter:
return_string = inputstring[first_delimiter+1: second_delimiter]
if len(return_string) != 8:
return (0,0)
return (int(return_string[0:4]), int(return_string[4:8]))
return (0,0)
def getDecodedVN(inputtuple):
'''get VN "Virtual Network"'''
if len(inputtuple) != 2:
return 0
return inputtuple[0]
def getDecodedTG(inputtuple):
'''get TG "Trunk Group"'''
if len(inputtuple) != 2:
return 0
return inputtuple[1]
def calculatePerCallRecordDuriation(start_str_time, end_str_time):
'''during in seconds will be returned'''
starttime = string_toDatetime(start_str_time)
endtime = string_toDatetime(end_str_time)
return (endtime - starttime).seconds
def calculateCallRecordDuriationSum(durationRecordList):
'''Sum Call Record Duriation'''
resultDict = {}
for listitem in durationRecordList:
if len(listitem) == 4:
key = str(listitem[0]) + '-' + str(listitem[1])
print sys._getframe().f_code.co_name,"VN_ID-TG_ID:", key
if key in resultDict.keys():
tmp = resultDict[key]
tmp[2] = tmp[2] + listitem[2]
tmp[3] = tmp[3] + listitem[3]
else:
resultDict[key] = listitem
for key in resultDict.keys():
tmp = resultDict[key]
tmp[2] = format(float(tmp[2]) / PER_ERLANG_INTERVAL, '.2f')
tmp[3] = format(float(tmp[3]) / PER_ERLANG_INTERVAL, '.2f')
durationSumRecordList=[]
for item in resultDict.values():
durationSumRecordList.append(item)
return durationSumRecordList
def saveTileInforamtionRowToList(informationRowList, hostname, starttime, endtime, erlang_duration):
first_row = []
first_row.append('sbchostname')
first_row.append('Starttime')
first_row.append('Endtime')
informationRowList.append(first_row)
second_row = []
second_row.append(hostname)
second_row.append(starttime)
second_row.append(endtime)
informationRowList.append(second_row)
if erlang_duration == 'DURATION':
informationRowList.append(['VN_ID','TG_ID','INCOMING_DURATION','OUTGOING_DURATION'])
elif erlang_duration == 'ERLANG':
informationRowList.append(['VN_ID','TG_ID','INGRESS_ERLANGS','EGRESS_ERLANGS'])
return
def saveDurtationInfoToCSV(InformationRowList, durationRecordList, outputCSVfile):
''' used to save per CDR call duration result to CSV '''
''' qa25b_20181011_000000-20181011_235959.raw.csv '''
'''
Final csv file format:
sbchostname,Starttime,Endtime
qa25b,20181011_000000,20181011_235959
VN_ID,TG_ID,INCOMING_DURATION,OUTGOING_DURATION
2,2,0.01,0.00
1,1,0.00,0.01
'''
with open(outputCSVfile,"ab+") as csvfile:
csvfile.write(codecs.BOM_UTF8)
writer = csv.writer(csvfile)
writer.writerows(InformationRowList)
writer.writerows(durationRecordList)
def saveErlangToCSV(InformationRowList, durationRecordList, outputCSVfile):
''' used to save per CDR call duration result to CSV '''
''' qa25b_20181011_000000-20181011_235959.csv '''
'''
Final csv file format:
sbchostname,Starttime,Endtime
qa25b,20181011_000000,20181011_235959
VN_ID,TG_ID,INGRESS_ERLANGS,EGRESS_ERLANGS
2,2,0.01,0.00
1,1,0.00,0.01
'''
with open(outputCSVfile,"ab+") as csvfile:
csvfile.write(codecs.BOM_UTF8)
writer = csv.writer(csvfile)
#writer.writerow(['VN_ID','TG_ID','INGRESS_ERLANGS','EGRESS_ERLANGS'])
writer.writerows(InformationRowList)
writer.writerows(durationRecordList)
def decodeRecord(RecordItem):
'''
RecordItem is the decoded object for one CDR,
it is in List format, from below indexs, associating information can be extracted.
RecordHeaderINDEX = 0
IBCFRecordINDEX = 1
serviceDeliveryStartTimeStampINDEX = 2
serviceDeliveryEndTimeStampINDEX = 3
trunkGroupIDINDEX = 4
trunkGroupIDincomingINDEX = 5
trunkGroupIDoutgoingINDEX = 6
'''
if len(RecordItem) != RECORD_LIST_LENGTH:
return [],[]
start_time = decodeServiceDeliveryStartTimeStamp(RecordItem[serviceDeliveryStartTimeStampINDEX])
end_time = decodeServiceDeliveryEndTimeStamp(RecordItem[serviceDeliveryEndTimeStampINDEX])
# FIX BUG-13169: if the returned start_time or end_time is invalid, then the sript will be stopped if
# the fix doesn't enabled
if is_valid_date(start_time) == False or is_valid_date(end_time) == False:
print "+drop the record, because of error timestamp in CDR decode files"
return None
# FIX BUG-13169: END
callDuriation = calculatePerCallRecordDuriation(start_time, end_time)
incomingVN = getDecodedVN(decodetrunkGroupIDincoming(RecordItem[trunkGroupIDincomingINDEX]))
incomingTG = getDecodedTG(decodetrunkGroupIDincoming(RecordItem[trunkGroupIDincomingINDEX]))
outgoingVN = getDecodedVN(decodetrunkGroupIDoutgoing(RecordItem[trunkGroupIDoutgoingINDEX]))
outgoingTG = getDecodedTG(decodetrunkGroupIDoutgoing(RecordItem[trunkGroupIDoutgoingINDEX]))
print "VN=%d" % incomingVN, "TG=%d" % incomingTG, "incoming CallDuration=%d" % callDuriation
print "VN=%d" % outgoingVN, "TG=%d" % outgoingTG, "outgoing CallDuration=%d" % callDuriation
incomingRecordDurationList = []
incomingRecordDurationList.append(incomingVN)
incomingRecordDurationList.append(incomingTG)
incomingRecordDurationList.append(callDuriation)
incomingRecordDurationList.append(0)
outgoingRecordDurationList = []
outgoingRecordDurationList.append(outgoingVN)
outgoingRecordDurationList.append(outgoingTG)
outgoingRecordDurationList.append(0)
outgoingRecordDurationList.append(callDuriation)
return incomingRecordDurationList,outgoingRecordDurationList
def decodeRecordList(RecordList, durationOverAllList):
''' used to parse the output of loadCDRdecodedFile() function'''
for list_item in RecordList:
#print list_item
retvalue = decodeRecord(list_item)
if retvalue is None:
continue
for item in retvalue:
durationOverAllList.append(item)
return
# load input file
def loadCDRdecodedFile(fileName):
''' used to load the CDR decoded raw text file, and then parse records in the file '''
''' save each record in a list, and save each ist in RecordList '''
# print file name loaded
print "the file to be processed is:", fileName
# read lines from the file and print it out to the screen
RecordList = list()
temp_record = list()
with open(fileName, 'rt') as txtData:
lines=txtData.readlines()
for line in lines:
line.strip()
line.rstrip('\n')
if line.find(RecordHeader) != -1:
#print line
# append 0 -- RecordHeader
if line in temp_record:
if validateRecord(temp_record) != -1:
#print "save the previous record to the list"
#print temp_record
RecordList.append(temp_record)
## reset the list to a new one
temp_record = list()
temp_record.append(line)
elif line.find(IBCFRecord) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(serviceDeliveryStartTimeStamp) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(serviceDeliveryEndTimeStamp) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(trunkGroupID) != -1:
#print line
temp_record.append(line)
#print temp_record
elif line.find(trunkGroupIDincoming) != -1:
# when not save the "trunkGroupID" block, so the found incoming is not the right incoming
if len(temp_record) < 5:
#print "has not save the trunkGroupID block, so the found incoming is not the right incoming"
continue
if trunkGroupID not in temp_record[4]:
#print "has not save the trunkGroupID block, so the found incoming is not the right incoming"
continue
# save the trunkGroupIDincoming
temp_record.append(line)
elif line.find(trunkGroupIDoutgoing) != -1:
# when not save the "trunkGroupID" block, so the found outgoing is not the right outgoing
if len(temp_record) < 5:
#print "has not save the trunkGroupID block, so the found outgoing is not the right outgoing"
continue
if trunkGroupID not in temp_record[4]:
#print "has not save the trunkGroupID block, so the found outgoing is not the right outgoing"
continue
# save the trunkGroupIDoutgoing
temp_record.append(line)
## check if the list element macth
if validateRecord(temp_record) != -1:
RecordList.append(temp_record)
return RecordList
def CDRFileFormatString_toDatetime(filename):
'''"mum01-4_-_24.20180816_-_1801+0530.decoded" to "2018/08/16 18:01:00"'''
#filename[filename.find('.')+1 : filename[filename.rfind('.')]
print sys._getframe().f_code.co_name, "input filename:", filename
# time info in filename
timeinfoinfile = filename[filename.find('.') + 1 : filename.rfind('+')]
#print timeinfoinfile
return datetime.datetime.strptime(timeinfoinfile, "%Y%m%d_-_%H%M")
def datetime_toString(dt):
return dt.strftime("%Y-%m-%d %H:%M:%S")
def datetime_string_to_filename_string(dt):
rt = string_toDatetime(dt)
return rt.strftime("%Y%m%d_%H%M%S")
def string_toDatetime(st):
'''convert timestamp in string fromat to datetime format'''
return datetime.datetime.strptime(st, "%Y/%m/%d %H:%M:%S")
def translateFileNametoTimeString(filename):
'''"mum01-4_-_24.20180816_-_1801+0530.decoded" to "2018/08/16 18:01:00"'''
return datetime_toString(CDRFileFormatString_toDatetime(filename))
def checkFileInTimeRange(starttime, endtime, inputfilename):
'''
checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180816_-_1801+0530.decoded') # 0 - in range
checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180816_-_1811+0530.decoded') # 1
checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180816_-_1859+0530.decoded')
checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180816_-_1900+0530.decoded')
checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180816_-_1759+0530.decoded')
checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180817_-_1801+0530.decoded') # out of range
checkFileInTimeRange('2018/08/16 17:59:00','2018/08/16 18:59:00','mum01-4_-_24.20180815_-_1801+0530.decoded') # out of range
'''
starttimeDatetime = string_toDatetime(starttime)
endtimeDatetime = string_toDatetime(endtime)
fileDatetime = CDRFileFormatString_toDatetime(inputfilename)
if (starttimeDatetime < fileDatetime < endtimeDatetime) or fileDatetime == endtimeDatetime:
print sys._getframe().f_code.co_name, inputfilename, "in range"
return True
else:
print sys._getframe().f_code.co_name, inputfilename, "out of range"
return False
def main():
'''All parameters are mandatory, please make sure they are used'''
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-p", "--path", dest="path",
help="read the absolute directory/path of cdr raw files stored")
parser.add_option("-d", "--day", dest="day",
help="read the day of cdr raw files to process, in Exact format 2018/10/11")
parser.add_option("-s", "--starttime", dest="starttimestamp",
help="read the start timestamp of cdr raw files to process, in Exact format 09:01:00, don't miss any charactors")
parser.add_option("-e", "--endttime", dest="endtimestamp",
help="read the end timestamp of cdr raw files to process, in Exact format 09:01:00, don't miss any charactors")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose")
(options, args) = parser.parse_args()
#if len(args) != 1:
# parser.error("incorrect number of arguments")
#if options.verbose:
# print "reading %s..." % options.filename
if os.path.isdir(options.path):
print "options.path: ", options.path
else:
print "-----------------WARNING:-----------------"
print options.path, "is not an absolute directory, please check it..."
print "quit the script...."
return -1
if is_valid_Day(options.day):
print "options.day: ", options.day
else:
print "-----------------WARNING:-----------------"
print options.day, " format wrong, good one is e.g. 2018/09/10, please check..."
print "quit the script...."
return -1
if is_valid_HourMinSec(options.starttimestamp):
print "options.starttimestamp: ", options.starttimestamp
else:
print "-----------------WARNING:-----------------"
print options.starttimestamp, " format wrong, good one is e.g. 09:01:00, please check..."
print "quit the script...."
return -1
if is_valid_HourMinSec(options.endtimestamp):
print "options.endtimestamp: ", options.endtimestamp
else:
print "-----------------WARNING:-----------------"
print options.endtimestamp, " format wrong, good one is e.g. 09:01:00, please check..."
print "quit the script...."
return -1
# if end timestamp is earlier than start timestamp, return from the script
if cmp(options.endtimestamp, options.starttimestamp) != 1:
print 'ERROR: input endtimestamp is not later than start timestamp, return...'
return -1
print "good parameters input, go for further processing..."
# /storage/ccfl_app/charging/stream1/primary
# /storage/duration_from_cdr/ folder is used to store the calculation call duration result based on the input CDR folder...
if os.path.isdir(call_duration_stored_directory):
print call_duration_stored_directory, "exist, no need to create the directory"
else:
print "create the folder ", call_duration_stored_directory
os.system('mkdir ' + call_duration_stored_directory)
if os.path.isdir(cdr_decoded_directory):
print cdr_decoded_directory, "exist, no need to create the directory"
print "clear up the folder", cdr_decoded_directory
os.system('rm ' + cdr_decoded_directory + '/*')
else:
print "create the folder", cdr_decoded_directory
os.system('mkdir ' + cdr_decoded_directory)
start_hour_stamp = string_toDatetime(options.day + ' ' + options.starttimestamp).replace(minute=0, second=0,microsecond=0)
end_hour_stamp = string_toDatetime(options.day + ' ' + options.endtimestamp).replace(minute=0, second=0,microsecond=0)
end_hour_stamp = end_hour_stamp + + datetime.timedelta(hours=1)
hour_stamp = start_hour_stamp
file_count = 0
while end_hour_stamp > hour_stamp:
cdr_process_per_hour_main(hour_stamp, options.path)
hour_stamp = hour_stamp + datetime.timedelta(hours=1)
file_count = file_count + 1
print '+ Generate', file_count, 'csv files...'
return 0
def cdr_process_per_hour_main(_date_stamp, _path):
# starttime/endtime in format "2018/10/10 18:59:00"
starttime_dt = _date_stamp
endtime_dt = _date_stamp + datetime.timedelta(hours=1)
#endtime = (string_toDatetime(_day + ' ' + _starttime) + datetime.timedelta(hours=1) ).strftime('%Y/%m/%d %H:%M:%S')
starttime = starttime_dt.strftime("%Y/%m/%d %H:%M:%S")
endtime = endtime_dt.strftime("%Y/%m/%d %H:%M:%S")
print '+++++++++++++++++++++++++++++++START+++++++++++++++++++++++++++++++++++++++++++'
print 'process cdr files with timestamp in the set (' + starttime + ',' + endtime + ']'
filelist = os.listdir(_path)
durationOverAllList = []
for filename in filelist:
# remove all files in the decoded directory
print "clearn up decoded file....."
os.system('rm '+ cdr_decoded_directory + '/*')
# valid the current file
if is_valid_cdr_file_string(filename) == False:
print "Invalid file Name Format:",filename,",ignore it"
continue
if checkFileInTimeRange(starttime, endtime, filename):
print "to process the file.....",filename
if _path[len(_path) - 1] == '/':
os.system('asnccflsearch '+ _path + filename)
else:
os.system('asnccflsearch '+ _path + '/' + filename)
# go on process the decoded file
#
filelist = os.listdir(cdr_decoded_directory)
for filename in filelist:
if is_valid_cdr_file_string(filename) == False:
print "Invalid file Name Format:",filename,",ignore it"
continue
if ".details" in filename:
print filename, "will not be processed as it is tmp file"
continue
if checkFileInTimeRange(starttime, endtime, filename):
print "process the decoded file", filename
resultRecordList = loadCDRdecodedFile( cdr_decoded_directory + '/' + filename)
#printRecordList(resultRecordList)
retvalue = decodeRecordList(resultRecordList, durationOverAllList)
print "clearn up decoded file....."
os.system('rm '+ cdr_decoded_directory + '/*')
# get hostname from server, suppose there is '-' in hostname, just use the part before '-'
hostname = os.popen('hostname').readline().split('-')[0]
filename_starttime_string = datetime_string_to_filename_string(starttime)
filename_endtime_string = datetime_string_to_filename_string(endtime)
# make file name in format hostname_20181010_100000-20181010_105959
# and will finally append ".csv"
tosavedFilename = call_duration_stored_directory \
+ '/' \
+ hostname \
+ '_'\
+ filename_starttime_string \
+ '-' \
+ filename_endtime_string
print "Calculation Result is to be saved in", tosavedFilename + '.csv'
print "Calculation Result Temp file is to be saved in", tosavedFilename + '.raw.csv'
InformationRowList = []
saveTileInforamtionRowToList(InformationRowList,
hostname,
filename_starttime_string,
filename_endtime_string,
'DURATION')
# if the output file exist, delete it
if os.path.exists(tosavedFilename + '.raw.csv'):
print tosavedFilename + '.raw.csv', 'exist, delete it'
os.system('rm ' + tosavedFilename + '.raw.csv')
if os.path.exists(tosavedFilename + '.csv'):
print tosavedFilename + '.csv', 'exist, delete it'
os.system('rm ' + tosavedFilename + '.csv')
saveDurtationInfoToCSV(InformationRowList, durationOverAllList, tosavedFilename + '.raw.csv')
print tosavedFilename + '.raw.csv','Generating Complete!'
InformationRowList = []
erlangList = calculateCallRecordDuriationSum(durationOverAllList)
saveTileInforamtionRowToList(InformationRowList,
hostname,
filename_starttime_string,
filename_endtime_string,
'ERLANG')
saveErlangToCSV(InformationRowList, erlangList, tosavedFilename+'.csv')
print tosavedFilename + '.csv','Generating Complete!'
print '+++++++++++++++++++++++++++++++END+++++++++++++++++++++++++++++++++++++++++++++'
return 0
if __name__ == "__main__":
main()
print "+ parse done............... "
print "+ please check everything is ok......"
print "+++++++++++++++++++++++++++++++Quit From the Script++++++++++++++++++++++++++++"
<file_sep>/gamefucker/gamefucker.py
# -*- coding: utf-8 -*-
import autopy
import time
import win32api
import win32con
#win32api.keybd_event(17,0,0,0) #ctrl键位码是17
#win32api.SetCursorPos([30,150]) #为鼠标焦点设定一个位置
while (1):
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0)
print("mouse down 1000")
#win32api.SetCursorPos([500,500])
time.sleep(1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0)
print("mouse up 2000")
time.sleep(16)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0)
#win32api.SetCursorPos([500,500])
print("mouse down 3")
time.sleep(1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0)
print("mouse up 3")
time.sleep(5)
print("mouse down 3")
win32api.keybd_event(27,0,0,0)
#autopy.alert.alert("hello,world")
##autopy.mouse.move(100, 100) # 移动鼠标
#autopy.mouse.smooth_move(400, 400) # 平滑移动鼠标(上面那个是瞬间的aa)<file_sep>/gamefucker/fsgui.md
## “One Button Replace FSGUI”
### /home/jzhan107/spFSGUI
the tool is placed in lsslogin1 server /home/jzhan107/bin/ folder
the tool is used to package DB binary and fsgui binary and XSD files, ship to lab and replace the fsgui associating binary.
#### option for the command ?
/home/jzhan107/bin/spFSGUI -h
-d : escape packaging DB binary
-D : escape shipping DB binary
-f : escape packaging FSGUI binary
-F : escape shipping FSGUI binary
-x : escape shipping XSD files
-h : get help
#### How to use ?
/home/jzhan107/bin/spFSGUI -h
-d : escape packaging DB binary
-D : escape shipping DB binary
-f : escape packaging FSGUI binary
-F : escape shipping FSGUI binary
-x : escape shipping XSD files
-h : get help
##### Notice:
before use, you must in the ROOT of your fsgui development directory
##### /home/jzhan107/bin/spFSGUI qa24c
will package below files and ship to LSP1 server, then to qa24c to replace fsgui in qa24c
BLZDBlsspkg.zip
DBCLIENTpkg.zip
LCPDBlsspkg.zip
fsguibin.tar(including host_manager .....)
##### /home/jzhan107/bin/spFSGUI qa24c
will package below files and ship to LSP1 server, then to qa24c to replace fsgui in qa24c
BLZDBlsspkg.zip
DBCLIENTpkg.zip
LCPDBlsspkg.zip
$ROOT/fsgui/config/cfgschema/*.xsd
fsguibin.tar(including host_manager .....)
##### /home/jzhan107/bin/spFSGUI -d qa24c
if you want to escape package DB file because it has already been packaged in the build folder , will ship the binary to LSP1 server
##### /home/jzhan107/bin/spFSGUI -dD qa24c
if you don't want to send DB file to LSP1 server, because there is binary in the server(the binary is under /home/jzhan107/fsgui/ folder in lsp1 server)
##### /home/jzhan107/bin/spFSGUI -dDfF qa24c
if you want to escape DB & fsgui file(host_manager....) ship to LSP1 server, because there is binary in the server
##### /home/jzhan107/bin/spFSGUI -dDfFx qa24c
if you want to escape DB & fsgui file(host_manager....) ship to LSP1 server, because there is binary in the server
##### and so on.......
## “One Button take your RCC & FScmd & MIcmd prim state back"
### /home/jzhan107/bin/PrimUp qa24c
## "One Button to package IMS/CFED/PFED and replace it to lab"
### /home/jzhan107/bin/sB CFED qa24c
### /home/jzhan107/bin/sB IMS qa24c
### /home/jzhan107/bin/sB PFED qa24c
## there are some shortcommings, I will continuously enhance the tool... <file_sep>/multi_process_thread/concurrent.futures_1.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
# Python并发编程之线程池/进程池
# https://segmentfault.com/a/1190000007926055#articleHeader3
# 使用submit来操作线程池/进程池
#-------------------------------------------------------------------------------------------#
'''
使用submit来操作线程池/进程池
'''
# example1.py
from concurrent.futures import ThreadPoolExecutor
import time
def return_future_result(message):
time.sleep(2)
return message
pool = ThreadPoolExecutor(max_workers=2) # 创建一个最大可容纳2个task的线程池
future1 = pool.submit(return_future_result, ("hello")) # 往线程池里面加入一个task
future2 = pool.submit(return_future_result, ("world")) # 往线程池里面加入一个task
print(future1.done()) # 判断task1是否结束
time.sleep(3)
print(future2.done()) # 判断task2是否结束
print(future1.result()) # 查看task1返回的结果
print(future2.result()) # 查看task2返回的结果<file_sep>/README.md
# PythonLearning
## this is for Python Learning
----------------------------------
# now add: makedown tips
# add git tips
<file_sep>/Tips_Folder/Tips_python.md
# python的安装
首先,从Python的官方网站 www.python.org下载最新的2.7.6版本,地址是这个:
http://www.python.org/ftp/python/2.7.6/python-2.7.6.msi
然后,运行下载的MSI安装包,不需要更改任何默认设置,直接一路点“Next”即可完成安装:
默认会安装到C:\Python27目录下,但是当你兴致勃勃地打开命令提示符窗口,敲入python后,会得到:
‘python’不是内部或外部命令,也不是可运行的程序或批处理文件。
这是因为Windows会根据一个Path的环境变量设定的路径去查找python.exe,如果没找到,就会报错。解决办法是把python.exe所在的路径C:\Python27添加到Path中。
现在,再打开一个新的命令行窗口(一定要关掉原来的命令行窗口,再新开一个),输入python:
你看到提示符>>>就表示我们已经在Python交互式环境中了,可以输入任何Python代码,回车后会立刻得到执行结果。现在,输入exit()并回车,就可以退出Python交互式环境(直接关掉命令行窗口也可以!)。
# pip安装
1. 在以下地址下载最新的PIP安装文件:http://pypi.python.org/pypi/pip#downloads
2. 下载pip-7.1.2.tar.gz (md5, pgp)完成之后,解压到一个文件夹,用CMD控制台进入解压目录,输入:
python setup.py install
安装好之后,我们直接在命令行输入pip,同样会显示‘pip’不是内部命令,也不是可运行的程序。因为我们还没有添加环境变量。
C:\Python27\Scripts
# 用pip去安装其他python库
python -m pip install jieta
pip install jieta
# join() function
## 对序列进行操作(分别使用' '与':'作为分隔符)
>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido
## 对字符串进行操作
>>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
## 对元组进行操作
>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido
## 对字典进行操作
>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello
## 合并目录
>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'
## 如果当前电脑里所有的python程序访问网页或者服务器的时候都需要用到代理可以去python库的源文件修改代理,这样所有用到该源文件访问
例如我在使用tushare访问数据的时候,实际上默认程序是不走代理的,虽然系统中配置了代理,依然不起任何作用,这个时候发现tushare在访问网页/服务器的时候,
最终调用的是urlib2.py, 而平时在自己写脚本的时候在脚本中使用build一个新的ProxyHandler就可以了,如下:
# -*- coding: utf-8 -*-
import urllib
import urllib2
import gzip, StringIO
import zlib
'''
proxy_handler = urllib2.ProxyHandler({'http': '172.16.31.10:8000'})
opener = urllib2.build_opener(proxy_handler)
r = opener.open('http://finance.sina.com.cn/realstock/company/sz300033/nc.shtml')
print(r.read())
'''
request = urllib2.Request('http://www.163.com')
request.add_header('Accept-encoding', 'gzip')
proxy_handler = urllib2.ProxyHandler({'http': '172.16.31.10:8000'})
opener = urllib2.build_opener(proxy_handler)
response = opener.open(request)
html = response.read()
gzipped = response.headers.get('Content-Encoding')
if gzipped:
html = StringIO.StringIO(html)
#html = zlib.decompress(html, 16 + zlib.MAX_WBITS)
gzipper = gzip.GzipFile(fileobj=html)
html = gzipper.read()
else:
typeEncode = sys.getfilesystemencoding()##系统默认编码
infoencode = chardet.detect(html).get('encoding','utf-8')##通过第3方模块来自动提取网页的编码
html = content.decode(infoencode,'ignore').encode(typeEncode)##先转换成unicode编码,然后转换系统编码输出
print html
但是在大量应用中很难做到直接去修改所有的库去build proxyhandler, 所以我们可以采用修改基础库urllib2中的ProxyHandler __init__的constext默认参数设置代理
class ProxyHandler(BaseHandler):
...
def __init__(self, proxies=None):
---->
def __init__(self, proxies={'http': 'xxx.xxx.xxx.xxx:xx'}):
其中xxx.xxx.xxx.xxx:xx具体的代理,在浏览器的代理中可以查到.
## Python程序打包成exe
+ [Python3.x:打包为exe执行文件(window系统)](https://www.cnblogs.com/lizm166/p/8315468.html)
+ [pyinstaller打包单个exe后无法执行错误的解决方法](https://www.jb51.net/article/163664.htm)
## python 代码模板
+ [Codeing Dict](http://codingdict.com/sources/py/win32process/20280.html)
## python pywin32
+ [Python win32gui调用窗口到最前面](https://www.cnblogs.com/zhizhao/p/11489691.html)
<file_sep>/window32API/ExecuteMyApp.py
# coding: utf-8
import win32gui, win32api, win32con
import time
import win32clipboard as w
import logging
def isRunning(process_name) :
try:
print('tasklist | findstr ' + process_name)
process=len(os.popen('tasklist | findstr ' + process_name).readlines())
print(process)
if process >=1 :
return True
else:
return False
except:
print("The application is not running: " + process_name)
return False
def get_all_hwnd(hwnd, mouse):
if (win32gui.IsWindow(hwnd)
and win32gui.IsWindowEnabled(hwnd)
and win32gui.IsWindowVisible(hwnd)):
hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})
if __name__ == '__main__':
hwnd = win32gui.FindWindow(None, "同花顺远航版")
if int(hwnd) <= 0:
print("没有找到模拟器,退出进程................")
exit(0)
print("查询到模拟器句柄: %s " % hwnd)
win32gui.MoveWindow(hwnd, 20, 20, 405, 756, True)<file_sep>/stock/stock_scriber/stockGet.6.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import datetime as dt
import json
import tushare as ts
from openpyxl import load_workbook
from optparse import OptionParser
_DEBUG_LOG = 0
OUTPUT_LIMIT_MAX = 5
ROW_START_INDEX = 3
COLUMN_FIRST_OUTPUT = 7
COLUMN_COUNT_OUTPUT = 4
COLUMN_COUNT_PER_ITEM = 6
COLUMN_OF_START_DAY = 3
COLUMN_OF_STOCK_CODE = 2
COLUMN_OF_STOCK_NAME = 1
CONST_2_SEARCH_ROW_MAX = 5
def datetime_toString(dt):
return dt.strftime("%Y-%m-%d")
def string_toDatetime(string):
return dt.datetime.strptime(string, "%Y-%m-%d")
def string_toTimestamp(strTime):
return dt.mktime(string_toDatetime(strTime).timetuple())
def timestamp_toString(stamp):
return dt.strftime("%Y/%m-%d", time.localtime(stamp))
def datetime_toTimestamp(dateTim):
return dt.mktime(dateTim.timetuple())
def day_string_plus_one(_day_input):
date = string_toDatetime(_day_input) + dt.timedelta(days=1)
return datetime_toString(date)
def get_hist_data_days(_stock_code, _day_start, _day_counts):
df = ts.get_hist_data(_stock_code, start=_day_start, end=_day_start)
if df is None:
return df
return df[['open', 'close', 'high', 'low']]
def search_data(stock_code, input_day, OUTPUT_LIMIT_MAX):
'''
stock_code - python string
input_day - must in excel in date format
OUTPUT_LIMIT_MAX - how many days will be query
'''
count = 0
a_store_data = []
try_times = 0
#day_2_search = input_day.replace("/", "-")
day_2_search = datetime_toString(input_day)
print '++++++++++++++++++++++++++++++++++++++++++++++++++++++'
print 'stock code information collection status:'
while (count < OUTPUT_LIMIT_MAX):
df = get_hist_data_days(stock_code, day_2_search, 1)
if df is None or len(df) == 0:
print 'got nothing of day: ', day_2_search
day_2_search = day_string_plus_one(day_2_search)
try_times = try_times + 1
if try_times == 10:
return a_store_data
continue
print 'got data of the day:', day_2_search,
close_price = round(df[u'close'], 2)
open_price = round(df[u'open'], 2)
high_price = round(df[u'high'], 2)
low_price = round(df[u'low'], 2)
one_item = [open_price, close_price, high_price, low_price]
a_store_data.append(one_item)
print one_item
day_2_search = day_string_plus_one(day_2_search)
count = count + 1
print '++++++++++++++++++++++++++++++++++++++++++++++++++++++'
return a_store_data
def write_to_cell(ws, row_index, column_index, value):
print "write value: ", value, " to row=", row_index, "column=", column_index
ws.cell(row=row_index, column=column_index).value = value
def search_and_write_stock_data_2_excel(_data_file):
#dirname, filename = os.path.split(os.path.abspath(__file__))
#read_excel_file_name = dirname + '\stock_s.xlsx'
read_excel_file_name = _data_file
print read_excel_file_name
wb = load_workbook(read_excel_file_name)
sheets = wb.sheetnames
sheet_first = sheets[0]
#
ws = wb[sheet_first]
print "***"
print sheet_first
print ws.title
print ws.max_row
print "^^^"
rows = ws.rows
row_index = ROW_START_INDEX # start from row 3 to calculate
while row_index < ws.max_row:
# get stock_code from column=2
stock_code = ws.cell(row=row_index, column=COLUMN_OF_STOCK_CODE).value
if stock_code is None:
print "Have finish the calculation......"
break
# the open price of the first day
search_start_day = ws.cell(row=row_index, column=COLUMN_OF_START_DAY).value
print 'stock_code:',stock_code, ", search_start_day:", search_start_day
returned_data_collection = search_data(stock_code, search_start_day, OUTPUT_LIMIT_MAX)
if returned_data_collection is None or len(returned_data_collection) == 0:
row_index = row_index + 1
continue
column_to_write = COLUMN_FIRST_OUTPUT
for item in returned_data_collection:
sub_index = 0
for sub_item in item:
write_to_cell(ws, row_index, column_to_write, item[sub_index])
column_to_write = column_to_write + 1
sub_index = sub_index + 1
column_to_write = column_to_write + (COLUMN_COUNT_PER_ITEM - COLUMN_COUNT_OUTPUT)
row_index = row_index + 1
print "save calculation result to "
wb.save('stock_s.xlsx')
return
def parse_stock_code_from_xml(_code_file):
stock_dict = {}
with open(_code_file,'r') as f:
lines = f.readlines()
for line in lines:
if line is None or len(line) == 0:
continue
line_after_replace = line.replace('<li>','')
line_after_replace = line_after_replace.replace('</a></li>','')
#print line_after_replace
right_branket_pos = line_after_replace.rfind(')')
left_branket_pos = line_after_replace.find('(')
stock_name_pos = line_after_replace.find('>') + 1
stock_code = line_after_replace[left_branket_pos+1:right_branket_pos]
stock_name = line_after_replace[stock_name_pos:left_branket_pos]
stock_dict[stock_name.decode('gbk').encode('utf-8')] = stock_code
#print stock_name, stock_code
if _DEBUG_LOG == 1:
print stock_dict
return stock_dict
def get_stock_code_from_dict_by_name(_stock_name, _stock_dict):
#print _stock_name.decode("string-escape")
#print _stock_name
try:
return _stock_dict[_stock_name.encode('utf-8')]
except:
print "Couldn't get stock code from dict..."
return None
def get_stock_code_from_dict_by_name_all_to_excell(_stock_dict, _data_file):
if _stock_dict is None or len(_stock_dict) == 0:
print "No data in _stock_dict, exit..."
return
if os.path.isfile(_data_file) != True:
print "input _data_file is not a file:", _data_file
return
#dirname, filename = os.path.split(os.path.abspath(__file__))
#read_excel_file_name = dirname + '\stock_s.xlsx'
read_excel_file_name = _data_file
print read_excel_file_name
wb = load_workbook(read_excel_file_name)
sheets = wb.sheetnames
sheet_first = sheets[0]
#
ws = wb[sheet_first]
print "***"
print sheet_first
print ws.title
print ws.max_row
print "^^^"
rows = ws.rows
row_index = ROW_START_INDEX # start from row 3 to calculate
while row_index <= ws.max_row:
# get stock_code from column=2
stock_name = ws.cell(row=row_index, column=COLUMN_OF_STOCK_NAME).value
if stock_name is None:
break
stock_code = get_stock_code_from_dict_by_name(stock_name, _stock_dict)
if stock_code is not None:
#print stock_name.encode('utf-8'), stock_code
print stock_name, stock_code
write_to_cell(ws, row_index, COLUMN_OF_STOCK_CODE, stock_code)
row_index = row_index + 1
wb.save('stock_s.xlsx')
return
def main():
'''All parameters are mandatory, please make sure they are used'''
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-c", "--code", dest="code",
help="get stock code by input.xml")
parser.add_option("-d", "--data", dest="data",
help="data files as input and output")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose")
(options, args) = parser.parse_args()
#reload(sys)
#sys.setdefaultencoding("string-escape")
#search_data('600547','2018/09/19',5)
#search_and_write_stock_data_2_excel()
if os.path.isfile(options.data) != True:
print "no input data file, exit...."
return
if os.path.isfile(options.code) != True:
print "++++++++++++++++++START++++++++++++++++++++++++++++"
print "+-going to parse stock code from file:", options.code
stock_dict = parse_stock_code_from_xml(options.code)
if stock_dict is None or len(stock_dict) == 0:
return
get_stock_code_from_dict_by_name_all_to_excell(stock_dict, options.data)
print "+Complete..."
return
print "+++++++++++++++++++END+++++++++++++++++++++++++++++"
print "++++++++++++++++++START++++++++++++++++++++++++++++"
search_and_write_stock_data_2_excel(options.data)
print "+++++++++++++++++++END+++++++++++++++++++++++++++++"
return
if __name__ == "__main__":
main()
<file_sep>/stock/stockGet.py
#-*- coding: utf-8 -*-
import sys
import datetime as dt
import json
import tushare as ts
from openpyxl import load_workbook
#from openpyxl.reader.excel import load_workbook
##wb = load_workbook(filename=r'D:/PythonWorkplace/PythonLearning/stock/stock_s_base.xlsx')
#print "Worksheet range(s):", wb.get_named_ranges()
#print "Worksheet name(s):", wb.get_sheet_names()
def printChinese(chinese_str):
type = sys.getfilesystemencoding()
print chinese_str.decode('UTF-8').encode(type)
return
#saved_filename = 'stock.xlsx'
#df = ts.get_hist_data('002415', start='2018-05-28', end='2018-05-30')
#df.to_excel(saved_filename)
#把datetime转成字符串
def datetime_toString(dt):
return dt.strftime("%Y-%m-%d")
#把字符串转成datetime
def string_toDatetime(string):
return dt.datetime.strptime(string, "%Y-%m-%d")
#把字符串转成时间戳形式
def string_toTimestamp(strTime):
return dt.mktime(string_toDatetime(strTime).timetuple())
#把时间戳转成字符串形式
def timestamp_toString(stamp):
return dt.strftime("%Y-%m-%d", tiem.localtime(stamp))
#把datetime类型转外时间戳形式
def datetime_toTimestamp(dateTim):
return dt.mktime(dateTim.timetuple())
#将字符串e.g.'2018-07-06'转化为datetime 然后+1,在转回字符串'2018-07-07'
def day_string_plus_one(_day_input):
date = string_toDatetime(_day_input) + dt.timedelta(days=1)
return datetime_toString(date)
def get_hist_data_days(_stock_code, _day_start, _day_counts):
df = ts.get_hist_data(_stock_code, start = _day_start, end = _day_start)
return df[['open', 'close', 'high', 'low']]
def search_data(stock_code, input_day, input_limit):
count = 0
while (count < input_limit):
df = get_hist_data_days(stock_code, input_day, 1)
close_price = df[u'close']
open_price = df[u'open']
high_price = df[u'high']
low_price = df[u'low']
# there is no data in that day, move to next day and have a try
if 0 == len(close_price):
print "There is no data in day: ", input_day
input_day = day_string_plus_one(input_day)
print "Try next day:", input_day
continue
#rint tuple(df)
#print df.open, df.close, df.high, df.low
#设定数据位置(从第3行,第6列开始插入数据)
#df.to_csv('D:/PythonWorkplace/PythonLearning/stock/1.xlsx')
#df.to_excel('D:/PythonWorkplace/PythonLearning/stock/stock_s.xlsx', startrow=2,startcol=5)
count = count + 1
print "stock_code: ", stock_code, "close: ", close_price[0], "open: ", open_price[0], "high: ", high_price[0], "low: ", low_price[0]
input_day = day_string_plus_one(input_day)
#print count
pass
def main():
#df = ts.get_hist_data('002415', start = '2018-07-06', end = '2018-07-10')
#get_hist_data_days('002415', '2018-07-06', 1)
#
#df = ts.get_hist_data('000875')
read_excel_file_name = 'D:/PythonWorkplace/PythonLearning/stock/stock_s.xlsx'
#df.to_excel('D:/PythonWorkplace/PythonLearning/stock/1.xlsx')
wb = load_workbook(read_excel_file_name)
#wb = load_workbook(filename=ExcelFullName)
# 获取当前活跃的worksheet,默认就是第一个worksheet
#ws = wb.active
# 当然也可以使用下面的方法
# 获取所有表格(worksheet)的名字
sheets = wb.get_sheet_names()
print sheets
# # 第一个表格的名称
sheet_first = sheets[0]
# # 获取特定的worksheet
#
ws = wb[sheet_first]
print "***"
print sheet_first
print ws.title
print "^^^"
# 获取表格所有行和列,两者都是可迭代的
rows = ws.rows
print rows
input_limit = 4
# 迭代所有的行
row_index = 1
for row in rows:
line = [col.value for col in row]
#print line
if row_index == 1:
row_index = row_index + 1
continue
if row_index == 2:
row_index = row_index + 1
continue
stock_code = ws.cell(row=row_index, column=2).value
#print datetime_toString(ws.cell(row=row_index, column=3).value)
input_day = datetime_toString(ws.cell(row=row_index, column=3).value)
search_data(stock_code, input_day, input_limit)
row_index = row_index + 1
return
main()
<file_sep>/multi_process_thread/README.md
# python多线程编程
以下是从网上找来的比较好用的文章
[Python多线程编程(1): python对多线程的支持](https://www.cnblogs.com/TsengYuen/archive/2012/04/19/2456697.html)
[python多线程编程(2): 线程的创建、启动、挂起和退出](http://www.cnblogs.com/holbrook/archive/2012/03/02/2376940.html)
[python多线程编程(5): 条件变量同步 Condition](https://www.cnblogs.com/holbrook/archive/2012/03/13/2394811.html)
[python多线程编程(6): 队列同步](https://www.cnblogs.com/holbrook/archive/2012/03/15/2398060.html)
[python多线程编程(7): 线程间通信](https://www.cnblogs.com/holbrook/archive/2012/03/21/2409031.html)
[Python多线程——线程间通信与同步机制](https://www.cnblogs.com/liubiao/p/6772873.html) (信号量Semaphore)
# python线程池
[python线程数量与线程池](https://juejin.im/post/5aa7314e6fb9a028d936d2a4)
[Python并发编程之线程池/进程池](https://segmentfault.com/a/1190000007926055) (非常好啊)
|
+---使用submit/map/wait来操作线程池/进程池
[Python中单线程、多线程和多进程的效率对比实验](https://segmentfault.com/a/1190000007495352)<file_sep>/multi_process_thread/multi_thread_5.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
# 多线程 -
# python多线程编程(6): 队列同步
# https://www.cnblogs.com/holbrook/archive/2012/03/15/2398060.html
#-------------------------------------------------------------------------------------------#
import threading
import time
'''
前面介绍了互斥锁和条件变量解决线程间的同步问题,并使用条件变量同步机制解决了生产者与消费者问题。
让我们考虑更复杂的一种场景:产品是各不相同的。这时只记录一个数量就不够了,还需要记录每个产品的细节。很容易想到需要用一个容器将这些产品记录下来。
Python的Queue模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列PriorityQueue。这些队列都实现了锁原语,能够在多线程中直接使用。可以使用队列来实现线程间的同步。
用FIFO队列实现上述生产者与消费者问题的代码如下:
'''
import threading
import time
from Queue import Queue
class Producer(threading.Thread):
def run(self):
global queue
count = 0
while True:
for i in range(100):
if queue.qsize() > 1000:
pass
else:
count = count + 1
msg = 'Procude Product ' + str(count)
queue.put(msg)
print msg
print ''
time.sleep(1)
class Consumer(threading.Thread):
def run(self):
global queue
while True:
for i in range(3):
if queue.qsize() < 100:
pass
else:
msg = self.name + 'Consume Product ' + queue.get()
print msg
print ''
time.sleep(1)
queue = Queue()
def test():
for i in range(500):
queue.put('initial Product ' + str(i))
for i in range(2):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()
if __name__ == '__main__':
test()
<file_sep>/Spider/douban.py
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import sys
import urllib2
import re
import time
from bs4 import BeautifulSoup
def get_html(url): #通过url获取网页内容
result = urllib2.urlopen(url)
return result.read()
# save_file(result.read(), 'thefile.txt')
def get_movie_all(html): #通过soup提取到每个电影的全部信息,以list返回
soup = BeautifulSoup(html)
movie_list = soup.find_all('div', class_='bd doulist-subject')
return movie_list
def get_movie_one(movie):
result = [] # 用于存储提取出来的电影信息
soup_all = BeautifulSoup(str(movie))
title = soup_all.find_all('div', class_='title')
soup_title = BeautifulSoup(str(title[0]))
for line in soup_title.stripped_strings: # 对获取到的<a>里的内容进行提取
result.append(line)
# num = soup_all.find_all('span', class_='rating_nums')
num = soup_all.find_all('span')
result.append(num[1].contents[0])
soup_num = BeautifulSoup(str(num[0]))
for line in soup_num.stripped_strings: # 对获取到的<span>里的内容进行提取
result = result + line
info = soup_all.find_all('div', class_='abstract')
soup_info = BeautifulSoup(str(info[0]))
result_str = ""
for line in soup_info.stripped_strings: # 对获取到的<div>里的内容进行提取
result_str = result_str + line
result.append(result_str)
return result #返回获取到的结果
def save_file(text, filename): #保存网页到文件
f= open(filename,'ab')
f.write(text)
f.close()
def read_file(filename): #读取文件
f = open(filename,'r')
text = f.read()
f.close()
return text
if __name__=='__main__':
print "strvice start..."
for i in range(0,426,25):
url = 'https://www.douban.com/doulist/3516235/?start='+str(i)+'&sort=seq&sub_type='
print "Now URI is :"
print url
html = get_html(url)
movie_list = get_movie_all(html)
for movie in movie_list: #将每一页中的每个电影信息放入函数中提取
print "go to get movie............................................"
result = get_movie_one(movie)
text = ''+'电影名:'+str(result[0])+' | 评分:'+str(result[1])+' | '+str(result[2])+'\n'+'\t'
print text
save_file(text,'thee.txt')
time.sleep(5) #每隔5秒抓取一页的信息
<file_sep>/multi_process_thread/multi_thread_4.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
# 多线程 -
# python多线程编程(5): 条件变量同步 Condition
# https://www.cnblogs.com/holbrook/archive/2012/03/13/2394811.html
#-------------------------------------------------------------------------------------------#
import threading
import time
'''
互斥锁是最简单的线程同步机制,Python提供的Condition对象提供了对复杂线程同步问题的支持。Condition被称为条件变量,除了提供与Lock类似的acquire和release方法外,还提供了wait和notify方法。线程首先acquire一个条件变量,然后判断一些条件。如果条件不满足则wait;如果条件满足,进行一些处理改变条件后,通过notify方法通知其他线程,其他处于wait状态的线程接到通知后会重新判断条件。不断的重复这一过程,从而解决复杂的同步问题。
可以认为Condition对象维护了一个锁(Lock/RLock)和一个waiting池。线程通过acquire获得Condition对象,当调用wait方法时,线程会释放Condition内部的锁并进入blocked状态,同时在waiting池中记录这个线程。当调用notify方法时,Condition对象会从waiting池中挑选一个线程,通知其调用acquire方法尝试取到锁。
Condition对象的构造函数可以接受一个Lock/RLock对象作为参数,如果没有指定,则Condition对象会在内部自行创建一个RLock。
除了notify方法外,Condition对象还提供了notifyAll方法,可以通知waiting池中的所有线程尝试acquire内部锁。由于上述机制,处于waiting状态的线程只能通过notify方法唤醒,所以notifyAll的作用在于防止有线程永远处于沉默状态。
演示条件变量同步的经典问题是生产者与消费者问题:假设有一群生产者(Producer)和一群消费者(Consumer)通过一个市场来交互产品。生产者的”策略“是如果市场上剩余的产品少于1000个,那么就生产100个产品放到市场上;而消费者的”策略“是如果市场上剩余产品的数量多余100个,那么就消费3个产品。用Condition解决生产者与消费者问题的代码如下:
'''
class Producer(threading.Thread):
def run(self):
global count
while True:
if con.acquire():
if count > 1000:
con.wait()
else:
count = count+100
msg = self.name+' produce 100, count=' + str(count)
print msg
con.notify()
con.release()
time.sleep(1)
class Consumer(threading.Thread):
def run(self):
global count
while True:
if con.acquire():
if count < 100:
con.wait()
else:
count = count-3
msg = self.name+' consume 3, count='+str(count)
print msg
con.notify()
con.release()
time.sleep(1)
count = 500
con = threading.Condition()
def test():
for i in range(2):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()
if __name__ == '__main__':
test()<file_sep>/Spider/cliczx/clickzx.py
import re
import requests
import itchat
import time
from urllib.parse import quote
# 如果上面的itchat库没有安装的话需要先 pip install itchat
# 下面的是从nopwdLogin的body包中抠出来填写的。
jscode = '011Mg6Qm1ZVM5q0VpXOm1dV0Qm1Mg6Qd'
# 上面这个每一个小时更新一次,下面的内容以后可以不更新。。
wx_code = '001khpvq1W4i5k0F6Kwq1PDpvq1khpv9'
wx_header = 'https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJEaibJlVrdF9raOyeEHNsug418YhSuFOaIyKfh3Xt1mUygorZQX31H1HlNgTp0ll8XaozdVmEtveg/132' # body包中的微信头像wx_header
wx_nickname = '我的网名' # body包中的微信昵称 wx_header 和wx_nickname其实不是很重要,主要是显示在助力的人列表下面的。
# '上面的定义好后才可以执行代码。。。。。。。。。。。。。。'
# '下面的内容都不要修改。。。。。。。。。。。。。。。。。。'
Cookie1 = {
'citicbank':'b9ceba79625e35f166de551f88f65dd3',
'JSESSIONID_BASEH5':'<KEY>',
'JSESSIONID_OAUTH':'<KEY>',
'citicbank_cookie':'!Tr<KEY>',
}
# 下面的不管他。。
itchat.auto_login()
headers ={
'Accept-Encoding': 'br, gzip, deflate',
'Connection': 'keep-alive',
'Content-Type': 'application/json;charset=utf-8',
'Accept': '*/*',
'Host': 's.creditcard.ecitic.com',
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16B92 MicroMessenger/6.7.4(0x1607042c) NetType/WIFI Language/zh_CN',
'Referer': 'https://servicewechat.com/wx13b9861d3e9fcdb0/11/page-frame.html',
'Accept-Language': 'zh-cn',
'X-Requested-With': 'XMLHttpRequest'
}
@itchat.msg_register([itchat.content.SHARING,itchat.content.TEXT], isGroupChat = True)
def group_reply(msg):
if 'unionid=' in str(msg):
searchObj = re.search('unionid=(.*?==)',str(msg))
if searchObj:
uid = searchObj.group().replace('unionid=', '')
ret = enjoy(uid) # 自动点击助力
ins(uid)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), msg.actualNickName, ret)
def enjoy(uid):
data ='{"code":"%s","encryptedData":"","iv":"JaX/ZnbekWj5kzDitJ9Bow==","channel":"WeChatMini"}' % (jscode)
r = requests.post('https://uc.creditcard.ecitic.com/citiccard/newucwap/wx/nopwdLogin.do',data=data, headers=headers,timeout=20)
try:
authKey = r.json()['authKey']
Cookie1['JSESSIONID_BASEH5'] = authKey
Cookie1['JSESSIONID_OAUTH'] = authKey
tmp = '77777777'
i = 0
while '777777' in tmp and i < 4: # 针对服务拥堵做4次尝试,还得避免死循环
i += 1
data = '{"wx_code":"%s","encryptedData":"","iv":"JaX/ZnbekWj5kzDitJ9Bow==","wx_header":"%s","wx_nickname":"%s"}' % (wx_code,wx_header,wx_nickname)
r = requests.post('https://s.creditcard.ecitic.com/citiccard/gwapi/winterpig/user/login',data=data.encode('utf-8'), headers=headers, cookies=Cookie1,timeout=20)
tmp = r.text
unionidSrc = r.json()['unionId']
citicbank_cookie = r.cookies.get_dict()
if len(citicbank_cookie) > 0:
Cookie1['citicbank_cookie'] = r.cookies.get_dict()['citicbank_cookie']
tmp = '77777777'
i = 0
while '777777' in tmp and i < 4: # 针对服务拥堵做4次尝试,还得避免死循环
i += 1
data = '{"unionidDst":"%s","unionidSrc":"%s",' \
'"wx_header":"%s","wx_nickname":"%s"}'%(uid,unionidSrc,wx_header,wx_nickname)
r = requests.post('https://s.creditcard.ecitic.com/citiccard/gwapi/winterpig/assistance/enjoy', data=data.encode('utf-8'), headers=headers, cookies=Cookie1,timeout=20)
ret = (r.json()['retMsg'])
tmp = r.text
if '登录' not in ret: # 这个及下面2行可以不要,主要是加了可以方便看自己有多少刷子了,不加的话速度能更快些吧
r = requests.post('https://s.creditcard.ecitic.com/citiccard/gwapi/uc/winterpig/pig/querycurrent', data='{}', headers=headers, cookies=Cookie1,timeout=20)
ret += ' 当前拥有刷子' + str(r.json()['data']['residue'])
return ret
except:
return r.text
def ins(id):
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Content-Type': 'application/x-www-form-urlencoded',
'Origin': 'http://www.wqh.tw',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.1 Safari/605.1.15',
'Referer': 'http://www.wqh.tw/ins.php'
}
data = 'fname=' + quote(id, encoding='gbk')
requests.post('http://wqh.tw/ins.php', data=data, headers=headers)
if __name__ == '__main__':
itchat.run()
# print(enjoy('ZtVTjjgITEpXjJz5I00t3A6yxSqgGdgoRNbV4iQEWwS4jprnYL0+uoGac2YV1yPvi3\/scv5hb49w8xP841JmAQ=='))
<file_sep>/Tips_Folder/git_tips.md
[Git教程--廖雪峰](https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000)
## get change from remote 相当于是从远程获取最新版本到本地,不会自动merge
git fetch origin master
git log -p master..origin/master
git merge origin/master
## get change from remote 相当于是从远程获取最新版本并merge到本地
git pull origin master
git add filename filename2 file...
git commit file1 -m "tips"
git commit -m "tips for all"
git push origin master
## [git设置用户名密码](http://blog.csdn.net/qq_15437667/article/details/51029757)
git config --global user.name [username]
git config --global user.email [email]
modify .git/config:
echo "[credential]" >> .git/config
echo " helper = store" >> .git/config
or [git设置用户/密码](http://blog.csdn.net/qq_28602957/article/details/52154384)
### git config查看配置
git config --list
http.proxy=http://xxx.xxx.xxx.xxx:xxxx
## git删除文件
local operation steps:
rm file_name
git status
git rm file_name
git status
git commit -m "remove file_name"
git push origin master
## 多个账号同时使用时,要需要设置的全局用户名和用户邮箱,在每个repo目录下单独设置
### 取消全局设置
git config --global --unset user.name //取消全局设置
git config --global --unset user.email //取消全局设置
### 单独设置
git config user.name "newname"
git config user.email "newemail"
## check out 单个文件
git checkout -- reademe.txt
## 更新单个文件
$ git fetch
remote: Counting objects: 8, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 8 (delta 3), reused 8 (delta 3), pack-reused 0
Unpacking objects: 100% (8/8), done.
From github.com:fffy2366/checkout
cd1768d..2408ca5 master -> origin/master
$ git checkout -m 2408ca5 1.php 2.php
## 更新单个目录
$ git fetch
remote: Counting objects: 8, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 8 (delta 3), reused 8 (delta 3), pack-reused 0
Unpacking objects: 100% (8/8), done.
From github.com:fffy2366/checkout
cd1768d..2408ca5 master -> origin/master
$ git checkout -m 2408ca5 test1
### [撤销修改也可以checkout,也可以reset HEAD](https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000/001374831943254ee90db11b13d4ba9a73b9047f4fb968d000)
## [github/gerrit 管理多个ssh key](http://blog.csdn.net/system1024/article/details/52044900)
## git tips for work
# .gitignore忽略,过滤
[Git忽略规则.gitignore梳理](https://www.cnblogs.com/kevingrace/p/5690241.html)
[git 已提交文件的 如何屏蔽git的track](http://blog.csdn.net/n517052183/article/details/45028293)
正确的做法应该是:git rm --cached logs/xx.log,
然后更新 .gitignore 忽略掉目标文件,
最后 git commit -m "We really don't want Git to track this anymore!"
# git rebase --continue / --skip
git rebase --abort 是无风险的操作,会回到rebase操作之前的状态,2个分支的commits毫发无损。
git rebase --skip 是高风险的操作,引起冲突的commits会被丢弃(这部分代码修改会丢失)
# git rm 如何删除中文文件?
例如手动删除一个中文文件后,执行git status,会得到如下信息
deleted: "stock/stock2/stock/\350\202\241\347\245\250\347\273\237\350\256\241.xlsx"
其实这是一个中文名的文件,执行git rm "stock/stock2/stock/\350\202\241\347\245\250\347\273\237\350\256\241.xlsx"
会失败,
这个时候需要执行如下命令
git config --global core.quotepath false
然后,执行git status,会得到中文名:
deleted: stock/stock2/stock/股票统计.xlsx
之后执行git rm stock/stock2/stock/股票统计.xlsx就可以了
<EMAIL>:/home_nbu/jzhan107/gitProject/sbc/ssp/ds/ims/ibcf>n$ git remote -v
origin https://gerrit.ext.net.nokia.com/gerrit/ENT/sbc (fetch)
origin https://gerrit.ext.net.nokia.com/gerrit/ENT/sbc (push
git commit -m "SBC-1110: this the second change to IBCF_prov_data.cpp to add file comments"
# amend 只能修改最近一次的commit 的comments
git commit --amend
# 如果有commit没有加SBC-XXXXX
git log # find commit id
commit <KEY>
Author: jzhan107 <<EMAIL>>
Date: Wed Aug 28 21:26:46 2019 -0500
add comments to IBCF_prov_data.cpp
Change-Id: I165efc1eea2eb52eef139a9edd590682051fd20c
# move commit to the head
git reset --soft <KEY>
# fix the comments
git commit --amend
# still need to push to remote
git push origin HEAD:refs/for/current_learning
今天执行git pull时,碰到如下提示:
First, rewinding head to replay your work on top of it...
参考链接:https://stackoverflow.com/questions/22320058/git-first-rewinding-head-to-replay
看到如下答案:
git fetch origin; git reset --hard origin/<branch>
————————————————
版权声明:本文为CSDN博主「从心所愿」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sanbingyutuoniao123/article/details/78187229
<file_sep>/DataFrame/pandas.dataframe.test2.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
s1=np.array([1,2,3,4])
s2=np.array([5,6,7,8])
df=pd.DataFrame([s1,s2])
print df
s1=pd.Series(np.array([1,2,3,4]))
s2=pd.Series(np.array([5,6,7,8]))
df=pd.DataFrame([s1,s2])
print df
s1=pd.Series(np.array([1,2,3,4]))
s2=pd.Series(np.array([5,6,7,8]))
df=pd.DataFrame({"a":s1,"b":s2})
print df<file_sep>/multi_process_thread/multi_thread_7.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------------#
# 多线程
# 线程池
#-------------------------------------------------------------------------------------------#
'''
所以比较好的方法是维护一个队列,两个线程都从中获取任务,直到把这个队列中的任务都做完。这个过程其实就是特殊的生产消费模式,只不过没有生产者,任务量是固定的而已
'''
import threadingimport requestsfrom bs4 import BeautifulSoupfrom queue import Queueclass MyThread(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): while not self.queue.empty(): # 如果while True 线程永远不会终止 url = self.queue.get() print(self.name, url) url_queue.task_done() r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') lis = soup.find('ol', class_='grid_view').find_all('li') for li in lis: title = li.find('span', class_="title").text print(title)url_queue = Queue()for i in range(10): url = 'https://movie.douban.com/top250?start={}&filter='.format(i*25) url_queue.put(url)th1 = MyThread(url_queue)th2 = MyThread(url_queue)th1.start()th2.start()th1.join()th2.join()url_queue.join()print('finish')
作者:dwzb
链接:https://juejin.im/post/5aa7314e6fb9a028d936d2a4
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。<file_sep>/window32API/parseJson.py
import json
with open('data.json', 'r', encoding='utf-8') as f:
app_data = json.load(f)
print(type(app_data))
print(app_data['Application Path'])
<file_sep>/stock/stock2/stock/stockGet.4.py
import sys
import os
import datetime as dt
import json
import tushare as ts
from openpyxl import load_workbook
#def printChinese(chinese_str):
# type = sys.getfilesystemencoding()
# print chinese_str.decode('UTF-8').encode(type)
# return
def datetime_toString(dt):
return dt.strftime("%Y-%m-%d")
def string_toDatetime(string):
return dt.datetime.strptime(string, "%Y-%m-%d")
def string_toTimestamp(strTime):
return dt.mktime(string_toDatetime(strTime).timetuple())
def timestamp_toString(stamp):
return dt.strftime("%Y-%m-%d", time.localtime(stamp))
def datetime_toTimestamp(dateTim):
return dt.mktime(dateTim.timetuple())
def day_string_plus_one(_day_input):
date = string_toDatetime(_day_input) + dt.timedelta(days=1)
return datetime_toString(date)
def get_hist_data_days(_stock_code, _day_start, _day_counts):
df = ts.get_hist_data(_stock_code, start=_day_start, end=_day_start)
if df is None:
return df
return df[['open', 'close', 'high', 'low']]
def search_data(stock_code, input_day, input_limit):
count = 0
a_store_data = [[]]
try_times = 0
while (count < input_limit):
df = get_hist_data_days(stock_code, input_day, 1)
if df is None or len(df) == 0:
print 'got nothing:', 'stock:', stock_code, "day: ", input_day
input_day = day_string_plus_one(input_day)
try_times = try_times + 1
if try_times == 10:
return a_store_data
continue
close_price = df[u'close']
open_price = df[u'open']
high_price = df[u'high']
low_price = df[u'low']
#p_change_interval = df[u'p_change']
# there is no data in that day, move to next day and have a try
#if 0 == len(close_price) or 0 == len(open_price) or 0 == len(high_price) or 0 == len(low_price):
#print "There is no data in day: ", input_day
# input_day = day_string_plus_one(input_day)
#print "Try next day:", input_day
# continue
a_store_data.append([open_price[0], close_price[0], high_price[0], low_price[0]])
input_day = day_string_plus_one(input_day)
count = count + 1
return a_store_data
def write_to_cell(ws, row_index, column_index, value):
print "write value: ", value, " to row=", row_index, "column=", column_index
ws.cell(row=row_index, column=column_index).value = value
def get_save_data_excel():
#get file path and file name
dirname, filename = os.path.split(os.path.abspath(__file__))
read_excel_file_name = dirname + '\stock_s.xlsx'
print read_excel_file_name
wb = load_workbook(read_excel_file_name)
sheets = wb.sheetnames
#print sheets
sheet_first = sheets[0]
#
ws = wb[sheet_first]
rows = ws.rows
print "***"
print sheet_first
print ws.title
print "^^^"
input_limit = 5
print "stock_code: ", "date: ", "close: ", "open: ", "high: ", "low: "
row_index = 1
for row in rows:
line = [col.value for col in row]
#print line
if row_index == 1:
row_index = row_index + 1
continue
if row_index == 2:
row_index = row_index + 1
continue
stock_code = ws.cell(row=row_index, column=2).value
if stock_code == None:
break
print "going to get data for stock: ", stock_code
# go to get
get_day_from_table = ws.cell(row=row_index, column=3).value
print get_day_from_table
if get_day_from_table == None:
print "break when day is None"
break
got_datas_one_stock = search_data(stock_code, datetime_toString(get_day_from_table), input_limit)
if len(got_datas_one_stock) == 0:
print "could not get data for stock:", stock_code, "move to next stock"
row_index = row_index + 1
item_index = 7
for one_data in got_datas_one_stock:
flag_item_index = item_index
for item in one_data:
ws.cell(row=row_index, column=item_index).value = item
item_index = item_index + 1
if item_index == (flag_item_index + 4):
item_index = item_index + 1
# move to next row to search
row_index = row_index + 1
print "goning to save data in to file"
wb.save('stock_s.xlsx')
return
columns_first_day = [12, 13, 14, 15]
columns_mid_1_day = [17, 18, 19, 20]
columns_mid_2_day = [22, 23, 24, 25]
columns_last_day = [27, 28, 29, 30]
setup_base_line = 10000
const_standard_rate = 0.97
const_last_column = 31
const_row_max = 9999
def is_need_buy_in(ws, row_index, columns, price, count):
print "input price is ", price
mid_price = price
for col_index in columns:
get_price = ws.cell(row=row_index, column=col_index).value
if get_price is None:
print "get Price is None"
break
if mid_price > get_price:
print "set mid_price to ", get_price
mid_price = get_price
if mid_price <= (price * const_standard_rate):
print "need 2 times buy in to update..."
return True
return False
# return the rate of profit
def to_sell_in_final_day_with_close_price(ws, row_index, columns, price):
for col_index in columns:
get_price = ws.cell(row=row_index, column=col_index).value
if get_price is None:
print "get Price is None"
return (-1)
print "sell price of the final day: ", get_price
return ((get_price - price) / get_price) * 100
def calculate_from_excel():
dirname, filename = os.path.split(os.path.abspath(__file__))
read_excel_file_name = dirname + '\stock_s.xlsx'
print read_excel_file_name
wb = load_workbook(read_excel_file_name)
sheets = wb.sheetnames
sheet_first = sheets[0]
#
ws = wb[sheet_first]
print "***"
print sheet_first
print ws.title
print "^^^"
rows = ws.rows
input_limit = 5
#print "stock_code: ", "date: ", "close: ", "open: ", "high: ", "low: "
row_index = 3 # start from row 3 to calculate
while row_index < const_row_max:
total_count = 0
average_price = 0
stock_code = ws.cell(row=row_index, column=2).value
if stock_code is None:
print "Have finish the calculation......"
break
print "Going to calculate code: ", stock_code
# the open price of the first day
average_price = ws.cell(row=row_index, column=12).value
if average_price is None:
row_index = row_index + 1
continue
total_count = calc_count(average_price, setup_base_line)
total_amount = average_price * total_count
print "buy in code: ", stock_code, ", price: ", average_price, ", total count: ", total_count, ", totoal amount: ", total_amount
if is_need_buy_in(ws, row_index, columns_mid_1_day, average_price, total_count) == True:
total_count = total_count * 3
average_price = calc_price(average_price)
total_amount = average_price * total_count
print "after second day, code: ", stock_code, ", price: ", average_price, ", total count: ", total_count, ", totoal amount: ", total_amount
if is_need_buy_in(ws, row_index, columns_mid_2_day, average_price, total_count) == True:
total_count = total_count * 3
average_price = calc_price(average_price)
total_amount = average_price * total_count
print "after third day, code: ", stock_code, ", price: ", average_price, ", total count: ", total_count, ", totoal amount: ", total_amount
print "after calculation, with the open price of the forth day......", " average_price: ", average_price, "total_amount: ", total_amount
write_to_cell(ws, row_index, const_last_column, to_sell_in_final_day_with_close_price(ws, row_index, columns_last_day, average_price))
row_index = row_index + 1
print "save calculation result to ", const_last_column
wb.save('stock_s.xlsx')
return
def calc_price(price): # standard_f 0.97
return ((1 + 2 * const_standard_rate) * price / 3)
def calc_count(price, set_up_value):
return (((set_up_value // price) // 100) * 100)
def main():
calculate_from_excel()
return
main()
<file_sep>/Spider/try_spider.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
import urllib2
from urllib2 import urlopen
# get all content of the wabpage
def askURL(url):
request = urllib2.Request(url) # send request
try:
response = urllib2.urlopen(request) # get response from the request
html= response.read() # get webpage content
print html
except urllib2.URLError, e:
if hasattr(e,"code"):
print e.code
if hasattr(e,"reason"):
print e.reason
return html
def main():
#html = urlopen('https://mp.weixin.qq.com')
askURL('https://mp.weixin.qq.com')
main()<file_sep>/Tips_Folder/shell_tips.md
# [getopt:命令行选项、参数处理](http://blog.csdn.net/tdmyl/article/details/24714297)
# [expect shell发送组合键](http://blog.csdn.net/iodoo/article/details/49175707)
# [组合键ASCII Table](http://blog.csdn.net/iodoo/article/details/49175749)
#<file_sep>/Spider/test.py
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import sys
#reload(sys)
#sys.setdefaultencoding( "utf-8" )
import urllib2
import re
import time
if __name__=='__main__':
print "hello world"
<file_sep>/python.jd.taobao.py
# encoding=utf8
from __future__ import print_function
import json
from time import sleep
from selenium import webdriver
import chardet
from selenium.webdriver import ActionChains
#初始化浏览器
driver = webdriver.Chrome(executable_path = "C:\chromedriver\chromedriver.exe")
#driver = webdriver.Firefox(executable_path = "e:\\geckodriver")
#driver = webdriver.Ie(executable_path = "e:\\IEDriverServer")
#定义全局遍变量url
url = "https://www.jd.com"
def login_cookie():
#打开浏览器
driver.get(url)
# 浏览器最大化
#driver.maximize_window()
#定位登录button
driver.find_element_by_xpath('//a[@class = "link-login"]').click()
#定位账户登录
driver.find_element_by_xpath('//a[text()="账户登录"]').click()
#定位账号框,并输入账号
driver.find_element_by_xpath('//input[@name="loginname"]').send_keys("18561714553")
#定位密码框,并输入密码
driver.find_element_by_xpath('//input[@type="password"]').send_keys("<PASSWORD>")
#点击登录button
driver.find_element_by_xpath('//a[@id="loginsubmit"]').click()
sleep(20)
#需要手动滑动图片,通过校验
#获取cookie
my_cookie = driver.get_cookies()
print(">> going to print cookies...")
print(my_cookie)
data_cookie = json.dumps(my_cookie)
with open("jd_coolies","w") as fp:
fp.write(data_cookie)
print(">> Save cookies done!")
#使用cookies
def get_url_with_cookies():
# 访问网站,清空旧cookies信息
driver.get(url)
driver.delete_all_cookies()
#获取cookies文件
with open("jd_coolies","r") as fp:
jd_cookies = fp.read()
#加载cookies信息
jd_cookies_dict = json.loads(jd_cookies)
for cookie in jd_cookies_dict:
#该字段有问题所以删除就可以 浏览器打开后记得刷新页面 有的网页注入cookie后仍需要刷新一下
if 'expiry' in cookie:
del cookie['expiry']
driver.add_cookie(cookie)
#验证是否登录成功
driver.get(url)
#browser.refresh()
assert '退出' in driver.page_source
print(url)
# 添加购物车
def shoppingMaotai():
#driver.get('https://item.jd.com/100012043978.html')
driver.get('https://item.jd.com/100012043978.html')
#driver.find_element_by_id("btn_reservation").submit()
# 添加到购物车
try_times = 1
while (True):
try:
driver.find_element_by_id("InitCartUrl").click()
break
except:
print(">> try to find <InitCartUrl> times: " , try_times)
try_times = try_times + 1
continue
# 去购物车结算
try_times = 1
while (True):
try:
driver.find_element_by_id("GotoShoppingCart").click()
break
except:
print(">> try to find <GotoShoppingCart> times: " , try_times)
try_times = try_times + 1
continue
# 去结算
#driver.find_element_by_link_text(str(u"去结算".encode('utf-8'))).click()
#driver.find_element_by_css_selector("p[class=\"submit-btn\"]") #根据元素属性
#driver.find_elements_by_tag_name("clickcart|keycount|xincart|cart_gotoOrder").click()
#driver.find_element_by_class_name("cart-floatbar")
#driver.find_element_by_class_name("submit-btn").click()
#driver.find_element_by_xpath("//div[@id='cart-floatbar']/div/div/div/div[2]/div[4]/div[1]/div/div[1]").click()
try_times = 1
while (True):
try:
driver.find_element_by_link_text("去结算").click()
break
except:
print(">> try to find <去结算> 次数: " , try_times)
try_times = try_times + 1
continue
try_times = 1
while (True):
try:
driver.find_element_by_xpath("//*[@id='order-submit']").click()
print(u">> Successfully submit order,tried times: " , try_times)
break
except:
print(">> try to find <order-submit> times: " , try_times)
try_times = try_times + 1
continue
# 获取当前窗口句柄
now_handle = driver.current_window_handle
# 打印当前窗口句柄
print("预约茅台")
print(now_handle)
# 添加购物车
def shopping():
driver.get('https://www.jd.com/')
# 定位搜索框,并输入:Python自动化
driver.find_element_by_xpath("//input[@clstag='h|keycount|head|search_c']").send_keys('Python自动化')
# 定位“搜索”button,并点击
driver.find_element_by_xpath('//button[@clstag="h|keycount|head|search_a"]/i').click()
# 获取当前窗口句柄
now_handle = driver.current_window_handle
# 打印当前窗口句柄
print("添加购物车窗口")
print(now_handle)
#判断 不是 当前窗口句柄
# 获取所有窗口句柄
all_handles = driver.window_handles
# 循环遍历所有新打开的窗口句柄,也就是说不包括主窗口
for handle in all_handles:
if handle != now_handle:
# 切换窗口
driver.switch_to.window(handle)
sleep(5)
# 点击加入购物车
driver.find_element_by_xpath("//div[@class='itemInfo-wrap']/div/div/a[contains(@onclick,'加入购物车')]").click()
# 调用driver的page_source属性获取页面源码
pageSource = driver.page_source
# 断言页面源码中是否包含“商品已成功加入购物车”关键字,以此判断页面内容是否正确
assert "商品已成功加入购物车" in pageSource
print("商品已成功加入购物车")
def payOrder():
# # 获取当前窗口句柄
current_handle = driver.current_window_handle
# 打印当前窗口句柄
print(current_handle)
print("点击购物车")
# 点击“我的购物车”
driver.find_element_by_xpath("//a[text()='我的购物车']").click()
sleep(2)
all_handles = driver.window_handles
# 循环遍历所有新打开的窗口句柄,也就是说不包括主窗口
for handle in all_handles:
if handle != current_handle:
# 切换窗口
driver.switch_to.window(handle)
sleep(5)
# 点击“去结算”button
driver.find_element_by_xpath("//div[@id='cart-floatbar']/div/div/div/div[2]/div[4]/div[1]/div/div[1]").click()
# driver.find_element_by_xpath("//a[contains(text(),'去结算')]").click()
sleep(2)
# 点击“提交订单”button
driver.find_element_by_xpath("//button[@id='order-submit']").click()
# 调用driver的page_source属性获取页面源码
pageSource = driver.page_source
# 断言页面源码中是否包含“商品已成功加入购物车”关键字,以此判断页面内容是否正确
assert "订单提交成功,请尽快付款" in pageSource
def buy_on_time(buytime):
while True:
now = datetime.datetime.now()
if now.strftime('%Y-%m-%d %H:%M:%S') == buytime:
for i in range(1, 21):#每隔0.2秒抢购一次,尝试抢购20次
webdriver.find_element_by_xpath("/html/body/div[4]/div[2]/div/div[1]/div/div[2]/div/div/div[1]/div[1]/input").click()
webdriver.find_element_by_link_text("去结算").click()
print(now.strftime('%Y-%m-%d %H:%M:%S'))
print("第%d次抢购" % i)
time.sleep(0.2)
time.sleep(3)
print('purchase success')
time.sleep(0.5)
if __name__=="__main__":
login_cookie()
get_url_with_cookies()
shoppingMaotai()
#shopping()
#payOrder()<file_sep>/Tips_Folder/markdown_tips.md
# 一级标题
## 二级标题
### 三级标题
#### 四级标题
****************************************
##### 无序列表
* 1 first
* 2 second
* 3 third
* 4 fourth
+ Red
+ Green
+ Blue
- Red
- Green
- Blue
##### 有序列表
1. 1 first
2. 2 second
3. 3 third
4. 4 fourth
1. Bird
1. McHale
1. Parish
****************************************
# 引用
> This is Quote
> This is Quote
****************************************
# 插入链接
[Baidu](http://www.baidu.com)
# 插入图片

****************************************
# Markdown 的粗体和斜体也非常简单,用两个 * 包含一段文本就是粗体的语法,用一个 * 包含一段文本就是斜体的语法。
**Here We are**
*Here we are*
****************************************
# 表格
| Tables | Are | Cool |
| ------------- |:-------------:| -----:|
| col 3 is | right-aligned | $1600 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |
## 我们同时可以用:指定表格单元格的对齐方式
| 水果 | 价格 | 数量 |
| -------- | -----: | :----: |
| 香蕉 | $1 | 5 |
| 苹果 | $1 | 6 |
| 草莓 | $1 | 7 |
教程标题| 主要内容
-------|----------
关于Markdown | 简介Markdown,Markdown的优缺点
Markdown基础 | Markdown的**基本语法**,格式化文本、代码、列表、链接和图片、分割线、转义符等
Markdown表格和公式 | Markdown的**扩展语法**,表格、公式
# 公式
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML"></script>
通过使用MathJax,我们可以让Markdown解析LaTeX数学表达式,通常情况下,我们需要引入MathJax插件才可能工作。
如果使用陈列公式,结果为:
一个简单的数学公式,求圆的面积。
$$
S=\pi r^2
$$
# code
`#include <iosteam.h>`
`using namespace std;`
`int main()`
`{`
`return 0;`
`}`
#include <iostream.h>
using namespace std;
int main()
---------------------------------------
# markdown 资料推荐
[认识与入门 Markdown](https://sspai.com/post/25137)
[Markdown 语法说明](http://www.appinn.com/markdown/)
[CSDN Markdown简明教程3-表格和公式](http://blog.csdn.net/whqet/article/details/44277965)
# 字体、字号、颜色
<font face="黑体">我是黑体字</font>
<font face="微软雅黑">我是微软雅黑</font>
<font face="STCAIYUN">我是华文彩云</font>
<font color=#0099ff size=12 face="黑体">黑体</font>
<font color=#00ffff size=3>null</font>
<font color=gray size=5>
thanks for coming
</font>
## [配置颜色](http://blog.csdn.net/testcs_dn/article/details/45719357/)
<file_sep>/Spider/sipder_2.py
# -*- coding: utf-8 -*-
import urllib
import urllib2
import gzip, StringIO
import zlib
request = urllib2.Request('http://www.google.cn')
request.add_header('Accept-encoding', 'gzip')
proxy_handler = urllib2.ProxyHandler({'http': 'xxx.xxx.xxx.xxx:xxxx'})
opener = urllib2.build_opener(proxy_handler)
response = opener.open(request)
html = response.read()
gzipped = response.headers.get('Content-Encoding')
if gzipped:
html = StringIO.StringIO(html)
#html = zlib.decompress(html, 16 + zlib.MAX_WBITS)
gzipper = gzip.GzipFile(fileobj=html)
html = gzipper.read()
else:
html = html.decode('utf-8').encode('gdk')
typeEncode = sys.getfilesystemencoding()##系统默认编码
infoencode = chardet.detect(html).get('encoding','utf-8')##通过第3方模块来自动提取网页的编码
html = content.decode(infoencode,'ignore').encode(typeEncode)##先转换成unicode编码,然后转换系统编码输出
print html
<file_sep>/PhoneOP/firsttry.py
# -*- coding: utf-8 -*-
# @Time : 2017/12/28 10:26
# @Author : Hunk
# @File : ex86.py.py
# @Software: PyCharm
import time
from selenium import webdriver
from selenium.webdriver.common.touch_actions import TouchActions
"""设置手机的大小"""
mobileEmulation = {'deviceName': 'iPhone 5/SE'}
options = webdriver.ChromeOptions()
options.add_experimental_option('mobileEmulation', mobileEmulation)
'''设置编码格式'''
options.add_argument('lang=zh_CN.UTF-8')
'''模拟iphone 6'''
options.add_argument('user-agent="Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"')
'''禁止加载图片'''
#prefs = {"profile.managed_default_content_settings.images": 2}
#options.add_experimental_option("prefs", prefs)
'''Cannot call non W3C standard command while in W3C mode问题解决'''
options.add_experimental_option('w3c', False)
driver = webdriver.Chrome(chrome_options=options)
driver.get('http://www.jrdxdnx.cn/')
driver.maximize_window()
"""定位操作元素"""
#button = driver.find_element_by_xpath('//*[@id="kw"]')
Action = TouchActions(driver)
"""从button元素像下滑动200元素,以50的速度向下滑动"""
#Action.flick_element(button, 0, 200, 50).perform()
#Action.scroll_from_element(button, 0, -200).perform()
Action.scroll(0, 400).perform()
time.sleep(3)
driver.close()<file_sep>/window32API/pythonVoice.py
#coding:utf-8
import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("B H C G price 19.25, this is the first try") | fa801dffb8a923daabac81ec09b605778bb1a64c | [
"Markdown",
"Python",
"Text"
] | 71 | Python | JerryBluesnow/PythonLearning | f8c8ccd613ab70cd16e823c4ec3d81293b753f94 | 2d03c5d9c56c4d694e9596c5461dfb4df1850f95 |
refs/heads/main | <file_sep> **PROGETTO MOVIDA**
**A.A 2019/2020**
**CORSO DI ALGORITMI E STRUTTURE DATI**
#Presentato da:
<NAME>
<NAME>
**Implementazione:**
Inizialmente è stata fatta un’implementazione base delle strutture dati in cui è stato provato a prendere dimistichezza con le funzioni, inserisci, cancella, ricerca. Una volta fatto, si è passato all’implementazione di una classe astratta “StrutturaDati” che serve per implementare le funzioni comuni al “LinkedList” e al Btree.
##LinkedList:
##BTree:
Per quanto riguarda il Btree ho deciso di implementarlo semplicemente come un albero binario, l’ordine è 2 e ho un’unica chiave. Per definizione il binarytree è sempre un btree con ordine 2.
Per l’inserimento dei film, all’interno del’albero, è stata implementata una funzione compareTo che dà un’ordine crescente(da riguardare) rispetto alle stringhe.
(spiegare come è stata fatta questa cosa).
Poi sono state implementate le funzioni search, delete, getMovies.
• Per la funzione search, che prende come parametri di input un nodo e il film, a seconda che la “stringa” di input sia più grande o più piccola, cerca rispettivamente nel ramo dx o sx corrispettivamente.
• Per la funzione delete, si cerca il nodo da cancellare, guardare I rispettivi casi, se il nodo non ha figli, si cancella semplicemente il nodo, se il nodo invece ha figli, bisogna cercare il nodo che deve essere sostituito al nodo target.
• La funzione getMovies invece scorre tutto l’albero e memorizza I dati in un array e questo viene dato come risultato della funzione.
La classe “StrutturaDati” è semplicemente una classe astratta che raggruppa le funzioni in comune che possono essere usate da entrambe le strutture dati.
##MovidaCore:
E infine abbiamo MovidaCore, dove vengono implementate le funzioni richieste.
Grazie alla classe “StrutturaDati” si è riusciti ad ottenere le informazioni richieste.
Con LoadFromFile (f), è stata fatta la lettura delle varie stringhe sul file.
<file_sep>package oulatolal;
import commons.Movie;
public class LinkedList extends StrutturaDati{
LinkedList(){
this.next=null;
}
Node next;
Movie movie;
public Node head=null;
public Node tail=null;
Node insertMovie(Node t, Movie m) {
if(t==null) {
t=new Node();
t.movie=m;
//controllo se la lista è vuota
if(head==null) head=t;
}
else {
//voglio mettere in ordine alfabetico i film in base al titolo
//in modo da avere una lista orinata
int cmp=t.compareTo(m);
//se l'oggetto in questione è più piccolo di quello con cui viene confrontato
if(cmp<1)
t.children[0]=insertMovie(t.children[0],m);
else
t.children[1]=insertMovie(t.children[1],m);
}
return t;
}
public Node search(Node t, Movie target) {
int cmp=0;
if(t==null) return t;
if(t.movie.getTitle()==target.getTitle()) return t;
else {
cmp=t.compareTo(target);
if(cmp<1) return search(t.children[0],target);
else return search(t.children[1], target);
}
}
//funzione per eliminare un nodo
public Node removeMovie(Node t, Movie m) {
int cmp=0;
if (head==null) return null;
//scendo tutta la lista in cerca del nodo giusto
cmp=t.compareTo(m);
if(cmp<1)
t.children[0]=removeMovie(t.children[0],m);
else
t.children[1]=removeMovie(t.children[1],m);
return t;
}
//funzione per riordinare la lista
void inorderMovie(Node t) {
if (t==null) return;
for (int i=0; i<t.order_M/2; i=i+1) {
inorderMovie(t.children[i]);
}
System.out.println(t.movie.getTitle());
//System.out.println(t.movie.getYear());
//System.out.println(t.movie.getVotes());
//for (int i=0; i<t.movie.getCast().length; i=i+1) {
// System.out.println(t.movie.getCast()[i].getName());
//}
//System.out.println(t.movie.getDirector().getName());
for (int i=t.order_M/2; i<t.order_M; i=i+1) {
inorderMovie(t.children[i]);
}
}
//funzione per inserire i film in un array
public void getMoviesInArray(Node t, Movie[] array, int i) {
if(t==null) return;
else {
array[i]=t.movie;
getMoviesInArray(t.children[0],array, whichIndex(array));
getMoviesInArray(t.children[1],array, whichIndex(array));
}
}
public int whichIndex(Movie[]array) {
int ind=0;
for(int i=0;i<array.length;i++) {
ind=i;
}
return ind;
}
public void clearMovies() {
head=null;
}
@Override
public void insert(Movie movie) {
insertMovie(this.head,movie);
}
@Override
public Movie searchMovie(Movie movie) {
Node n=search(this.head, movie);
if(n!=null)return n.movie;
return null;
}
@Override
public void delete(Movie movie) {
removeMovie(this.head, movie);
}
@Override
public Movie[] getMovies() {
// TODO Auto-generated method stub
return null;
}
@Override
public void clear() {
clearMovies();
}
}
<file_sep>package oulatolal;
import commons.Movie;
/**
* SPIEGAZIONE DEL PERCHE' UTILIZZARE UNA CLASSE ASTRATTA
*
* Consider using abstract classes if any of these statements apply
* to your situation:
You want to share code among several closely related classes.
You expect that classes that extend your abstract class
have many common methods or fields, or require access modifiers other
than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define
methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your situation:
You expect that unrelated classes would implement your interface. For example,
the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned
about who implements its behavior.
You want to take advantage of multiple inheritance of type.
*
*
*/
//in questa classe vengono gestite le funzioni in comune dalle due strutture dati
public abstract class StrutturaDati {
//il comparable serve a "dare il parametro adatto", per inserire nel btree,
//ad esempio, ho bisogno di un nodo dove poterlo inserire
//analogo discorso per il movie search
public abstract void insert(Movie movie);
public abstract Movie searchMovie(Movie movie);
public abstract void delete(Movie movie);
public abstract Movie[] getMovies();
public abstract void clear();
}
<file_sep>package oulatolal;
import commons.Movie;
public class Node implements Comparable {
int order_M=2;
Node[] children = new Node [order_M];
Movie movie;
public Node next;
Node()
{
for (int i=0; i<order_M; i=i+1)
{
children[i] = null;
}
}
//salvo i film in maniera che ordino i film
//in maniera alfabetica, usando dei compare
//che ordinano in modo, appunto alfabetico le stringhe
@Override
public int compareTo(Object arg0) {
// TODO Auto-generated method stub
Movie tmp = (Movie)arg0;
return this.movie.getTitle().compareTo(tmp.getTitle());
}
}
<file_sep>package oulatolal;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import commons.Collaboration;
import commons.IMovidaCollaborations;
import commons.IMovidaConfig;
import commons.IMovidaDB;
import commons.IMovidaSearch;
import commons.MapImplementation;
import commons.MovidaFileException;
import commons.Movie;
import commons.Person;
import commons.SortingAlgorithm;
public class MovidaCore implements IMovidaDB, IMovidaSearch, IMovidaConfig, IMovidaCollaborations{
StrutturaDati movies = new BTree();
StrutturaDati movies2= new LinkedList();
Sorting sorting_algorithm = new BubbleSort();
Sorting sorting_algorithm2 = new MergeSort();
@Override
public Person[] getDirectCollaboratorsOf(Person actor) {
// TODO Auto-generated method stub
return null;
}
@Override
public Person[] getTeamOf(Person actor) {
// TODO Auto-generated method stub
return null;
}
@Override
public Collaboration[] maximizeCollaborationsInTheTeamOf(Person actor) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean setSort(SortingAlgorithm a) {
// TODO Auto-generated method stub
if (a==SortingAlgorithm.BubbleSort) {
sorting_algorithm = new BubbleSort();
}
else if (a==SortingAlgorithm.MergeSort) {
sorting_algorithm2 = new MergeSort();
}
else {
System.out.println("L'algoritmo scelto non è presente");
}
return false;
}
@Override
public boolean setMap(MapImplementation m) {
// TODO Auto-generated method stub
if (m==MapImplementation.BTree && this.movies instanceof BTree)
this.movies = new BTree();
//else if (m==MapImplementation.ListaNonOrdinata && this.movies instanceof LinkedList)
//this.movies = new LinkedList();
else {
System.out.println("L'implementazione passata non è corretta!");
}
return false;
}
@Override
public Movie[] searchMoviesByTitle(String title) {
// TODO Auto-generated method stub
ArrayList<Movie> tmpResult = new ArrayList<Movie>();
Movie resultMovie = getMovieByTitle(title);
if (resultMovie!=null) {
tmpResult.add(resultMovie);
}
if (tmpResult.isEmpty())
System.out.println("Non esiste il film con il nome cercato");
Movie [] resultSearched = new Movie[tmpResult.size()];
if (resultSearched!=null) {
for (int i=0; i<tmpResult.size(); i=i+1) {
resultSearched[i] = tmpResult.get(i);
}
return resultSearched;
} else
return null;
}
@Override
public Movie[] searchMoviesInYear(Integer year) {
// TODO Auto-generated method stub
Movie [] result = movies.getMovies();
ArrayList<Movie> tmpResult = new ArrayList<Movie>();
if (result!=null) {
for (int i=0; i<result.length; i=i+1) {
if (result[i].getYear().equals(year))
tmpResult.add(result[i]);
}
if (tmpResult.isEmpty())
System.out.println("Non ci sono film presenti nell'anno indicato");
Movie [] searchedMovies = new Movie[tmpResult.size()];
for (int i=0; i<tmpResult.size(); i=i+1) {
searchedMovies[i] = tmpResult.get(i);
}
return searchedMovies;
}
return null;
}
@Override
public Movie[] searchMoviesDirectedBy(String name) {
// TODO Auto-generated method stub
Movie result[] = movies.getMovies();
ArrayList<Movie> tmpResult = new ArrayList<>();
Movie searchedMovies[];
if (result!=null) {
for (int i=0; i<result.length; i=i+1) {
if (result[i].getDirector().getName().equals(name))
tmpResult.add(result[i]);
}
if (tmpResult.isEmpty())
System.out.println("Non ci sono film diretti dal regista indicato");
searchedMovies = new Movie[tmpResult.size()];
for (int i=0; i<tmpResult.size(); i=i+1) {
searchedMovies[i] = tmpResult.get(i);
}
return searchedMovies;
}
return null;
}
@Override
public Movie[] searchMoviesStarredBy(String name) {
// TODO Auto-generated method stub
Movie result[] = movies.getMovies();
ArrayList<Movie> tmpResult = new ArrayList<>();
Movie searchedMovies[];
if (result!=null) {
for (int i=0; i<result.length; i=i+1) {
for (int j=0; j<result[i].getCast().length; j=j+1) {
if (result[i].getCast()[j].equals(name))
tmpResult.add(result[i]);
}
}
if (tmpResult.isEmpty())
System.out.println("Non ci sono film con l'attore indicato");
searchedMovies = new Movie[tmpResult.size()];
for (int i=0; i<tmpResult.size(); i=i+1) {
searchedMovies[i] = tmpResult.get(i);
}
return searchedMovies;
}
return null;
}
@Override
public Movie[] searchMostVotedMovies(Integer N) {
// TODO Auto-generated method stub
Movie[] result = movies.getMovies();
Movie[] tmpVotedMovies = new Movie[movies.getMovies().length];
Movie[] mostVotedMovies = new Movie[N];
if (result!=null) {
for (int i=0; i<result.length; i=i+1) {
for (int j=0; j<result.length; j=j+1) {
if (result[j].getVotes()>result[i].getVotes()) {
tmpVotedMovies[j] = result[j];
}
}
}
for (int k=0; k<N; k=k+1) {
mostVotedMovies[k] = tmpVotedMovies[k];
}
return mostVotedMovies;
}else
return null;
}
@Override
public Movie[] searchMostRecentMovies(Integer N) {
// TODO Auto-generated method stub
return null;
}
@Override
public Person[] searchMostActiveActors(Integer N) {
// TODO Auto-generated method stub
return null;
}
/**
* questa parte del codice serve per leggere valori dal file
* e poterli poi salvare in una struttura dati
* creo delle variabili temporanee che mi servono per potere salvare i dati
* e a seconda della necessità poi vengono convertiti.
* 1)Inizio con la lettura della stringa titolo, t;
*
* 2)Leggo poi l'anno. Essendo year: xxxx (valore numerico) una stringa,
* dovevo "rimuovere" ciò che non era necessario dalla stringa, per poi
* castarla in un intero.
*
* 3)Per il cast, che è un vettore di persone, ho pensato di usare le
* virgole per avere una lunghezza. Nel senso, se ho 4 attori nel cast,
* questi verranno delimitati da 3 virgole, quindi la lunghezza sarà
* virgole+1.
* Quindi una volta letta la stringa degli attori:
* -conto le virgole
* -creo la lunghezza del vettore persone[virgole+1]
* -uso un vettore d'appoggio stringa, per separare i valori salvati
* nella stringa, tramite string.split(",");
* -assegno poi al vettore persona iesimo, il valore iesmio
* del vettore stringa.
*
* 4) Alla fine per leggere l'ultimo valore relativo ai voti,
* è stata eseguita la stessa procedura fatta con l'anno, dove veniva
* letta la stringa, successivamente usando replaceAll, trim e replaceAll
* veniva "pulita" dai caratteri e poi castata come intero.
*/
//////////////////////////////////
/**
* il problema che mi sto ponendo è se usare bufferreader o scanner
* se scanner consuma i caratteri letti e li "brucia"
* pensavo di usare un count, in modo tale d'avere un'idea di quanto
* deve skippare, ma credo che scanner consumi
* e forse quindi devo usare il bufferreader
*
* quindi forse bisogna fare una versione alternativa con buffer
*/
////////////////////////
/**
* Uso il bufferreader, invece dello scanner, perché sembra che con
* scanner io bruci le righe e non riesca ad utilizzarle (vedo se
* cambiare scanner e tenere tutto con buffer)
* Uso il bufferedReader, per poter contare il numero delle righe
* nel file. In modo tale da poter costruire un vettore movie, di
* numero di righe nel file / il numero delle componenti
* ovvero, vedendo la struttura del file del testo so che c'è
* un titolo
* un anno
* un direttore
* un cast (si suppone che i vari nomi degli attori vengano tutti
* scritti in una riga sola).
* il voto
* e uno spazio bianco
* (Quindi sei righe).
*
*
*/
@Override
public void loadFromFile(File f) {
// TODO Auto-generated method stub
Scanner scan;
try {
scan = new Scanner(f);
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
int lines = 0;
try {
while (br.readLine() != null) lines = lines+1;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(lines);
/////////////////////////////////////////////////////////
int lunghezzaMovieVettore = lines/6;
//creo una variabile vettore movie per poter salvare i film letti dal file
Movie [] movie = new Movie[lunghezzaMovieVettore];
int k=0;
while((scan.hasNext())) {
for (k=0; k<lunghezzaMovieVettore; k=k+1) {
String title_string = scan.nextLine();
title_string = title_string.replaceAll("Title:", " ");
// Remove extra spaces from the beginning
// and the ending of the string
title_string = title_string.trim();
// Replace all the consecutive white
// spaces with a single space
title_string = title_string.replaceAll(" +", " ");
String year_string = scan.nextLine();
// Replacing every non-digit number
// with a space(" ")
year_string = year_string.replaceAll("Year:", " ");
// Remove extra spaces from the beginning
// and the ending of the string
year_string = year_string.trim();
// Replace all the consecutive white
// spaces with a single space
year_string = year_string.replaceAll(" +", " ");
int year_integer = Integer.parseInt(year_string); ///<--- per castare
String director_string = scan.nextLine();
director_string = director_string.replaceAll("Director:", " ");
// Remove extra spaces from the beginning
// and the ending of the string
director_string = director_string.trim();
// Replace all the consecutive white
// spaces with a single space
director_string = director_string.replaceAll(" +", " ");
Person director = new Person(director_string);
///leggiamo il cast
String cast_string = scan.nextLine();
// with a space(" ")
cast_string = cast_string.replaceAll("Cast:", " ");
// Remove extra spaces from the beginning
// and the ending of the string
cast_string = cast_string.trim();
// Replace all the consecutive white
// spaces with a single space
cast_string = cast_string.replaceAll(" +", " ");
String[] cast_array;
int commas = 0;
//conto le virgole presenti nel file
//nella riga degli attori/cast
//in modo da poter dare una lunghezza al vettore person
for(int i = 0; i < cast_string.length(); i++) {
if(cast_string.charAt(i) == ',')
commas++;
}
System.out.println(commas);
//creo il vettore di lunghezza commas+1 per il cast
Person cast[] = new Person[commas+1];
cast_array = cast_string.split(","); //<--- serve per separare i valori
//dalle virgole
//per l'iesima persona del cast, assegno l'iesimo valore salvato
//nel vettore stringa
for (int i=0; i<commas+1; i=i+1) {
cast[i] = new Person(cast_array[i]);
}
///leggo i valori riguardo ai voti del film
String vote_string = scan.nextLine();
vote_string = vote_string.replaceAll("Votes:", " ");
// Remove extra spaces from the beginning
// and the ending of the string
vote_string = vote_string.trim();
// Replace all the consecutive white
// spaces with a single space
vote_string = vote_string.replaceAll(" +", " ");
int vote_integer = Integer.parseInt(vote_string);
String whitespace = scan.nextLine();
System.out.println(whitespace);
movie[k] = new Movie(title_string,year_integer,vote_integer,cast, director);
}
} //una volta riempito il vettore, si chiama la funziona insert, grazie alla
//quale i film letti e memorizzati nel vettore movie, vengono caricati
//sulla strutturadati (a seconda del caso, linked list o btree)
for (int i=0; i<lunghezzaMovieVettore; i=i+1) {
movies.insert(movie[i]);
}
scan.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("The file doesn't exist");
} catch (MovidaFileException message) {
// TODO Auto-generated catch block
System.out.println(message.getMessage());
}
}
@Override
public void saveToFile(File f) {
// TODO Auto-generated method stub
}
@Override
public void clear() {
// TODO Auto-generated method stub
movies.clear();
}
@Override
public int countMovies() {
// TODO Auto-generated method stub
if (movies.getMovies().length > 0)
return movies.getMovies().length;
else
return 0;
}
@Override
public int countPeople() {
// TODO Auto-generated method stub
int conta = 0;
Movie [] result = movies.getMovies();
//ok, la dimensione del vettore è giusta
if (result!=null) {
for (int i=0; i<result.length; i=i+1) {
//per ogni film i-esimo, si prende il vettore cast
//si prende la lunghezza e la si aggiunge a conta, così
//per ogni film
conta = result[i].getCast().length + conta;
//qui viene aggiunto il direttore del film
//suppongo che sia uno
conta = conta+1;
}
return conta;
}
else
return 0;
}
@Override
public boolean deleteMovieByTitle(String title) {
// TODO Auto-generated method stub
Movie [] result = movies.getMovies();
if (result!=null) {
for (int i=0; i<result.length; i=i+1) {
if (result[i].getTitle().equals(title)) {
movies.delete(result[i]);
if (movies.searchMovie(result[i])==null)
return true;
}
}
}
return false;
}
@Override
public Movie getMovieByTitle(String title) {
// TODO Auto-generated method stub
Movie[] result = movies.getMovies();
if (result!=null) {
for (int i=0; i<result.length; i=i+1) {
if (result[i].getTitle().equals(title))
return result[i];
}
}
return null;
}
@Override
public Person getPersonByName(String name) {
// TODO Auto-generated method stub
Movie [] result = movies.getMovies();
if (result!=null) {
for (int i=0; i<result.length; i=i+1) {
for (int j=0; j<result[i].getCast().length; j=j+1) {
if (result[i].getCast()[j].getName().equals(name))
return result[i].getCast()[j];
}
}
}
return null;
}
@Override
public Movie[] getAllMovies() {
// TODO Auto-generated method stub
Movie[] result = movies.getMovies();
if (result!=null) {
return result;
}
else
return null;
}
//è necessario che ci sia il doppio controllo?
@Override
public Person[] getAllPeople() {
// TODO Auto-generated method stub
Person[] people = new Person[countPeople()];
int k=0;
if (people!=null) {
for (int i=0; i<movies.getMovies().length; i=i+1) {
for (int j=0; j<movies.getMovies()[i].getCast().length;j=j+1) {
people[k] = movies.getMovies()[i].getCast()[j];
k=k+1;
}
people[k] = movies.getMovies()[i].getDirector();
k=k+1;
}
return people;
}
return null;
}
} | 4678e0d3fd7b6cd3d954663d1227aa6bb27178bd | [
"Markdown",
"Java"
] | 5 | Markdown | user0x7419553/PROGETTO-ALGORITMI | 61ea4ec6ef4ac7423c4f4ff101d37000975c4c0f | bc88b8e1365600f6b041b6bfb8b8dfd5fd143ebb |
refs/heads/master | <repo_name>anthnd/libgdx-tetris<file_sep>/core/src/com/anthnd/tetris/Tetris.java
package com.anthnd.tetris;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Tetris extends ApplicationAdapter {
// TODO: Integrate speed up as game progresses
// TODO: Track score
// TODO: Refactor
// Spritebatch for drawing
public SpriteBatch batch;
// Game window height and width
public int height, width;
// Base square for grid and tetrominoes
public Texture texture;
public Sprite sprite;
public BitmapFont font;
// Arrays for tetrominoes in grounded and falling states
public ArrayList<Sprite> fallingTetromino;
public ArrayList<Sprite> groundedTetrominoes;
private int fallingPieceType;
private int fallingPieceOrientation;
// Grid settings
public final int GRID_SQUARE_SIZE = 30;
public final int GRID_HEIGHT = 18;
public final int GRID_WIDTH = 10;
public int GRID_X = 20;
public int GRID_Y = 20;
// Game time
public float time;
public float timeCounter;
// Constants for tetromino types
private final int PIECE_I = 0;
private final int PIECE_O = 1;
private final int PIECE_T = 2;
private final int PIECE_S = 3;
private final int PIECE_Z = 4;
private final int PIECE_J = 5;
private final int PIECE_L = 6;
private final int PIECE_RANDOM = 7;
// Constants for orientations
private final int ORIENTATION_UP = 0;
private final int ORIENTATION_RIGHT = 1;
private final int ORIENTATION_DOWN = 2;
private final int ORIENTATION_LEFT = 3;
@Override
public void create () {
// Libgdx initializers
batch = new SpriteBatch();
font = new BitmapFont();
// Get window dimensions
height = Gdx.graphics.getHeight();
width = Gdx.graphics.getWidth();
// Generate base square sprite
texture = new Texture("square.png");
sprite = new Sprite(texture);
sprite.setSize(GRID_SQUARE_SIZE, GRID_SQUARE_SIZE);
// Initialize tetromino arrays
fallingTetromino = new ArrayList<Sprite>();
groundedTetrominoes = new ArrayList<Sprite>();
generateTetromino(PIECE_I);
translate(fallingTetromino, 0, 1-GRID_HEIGHT);
setAsGrounded(fallingTetromino);
fallingTetromino.clear();
}
@Override
public void render () {
// Clear screen and set to black
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// Increment time
time += Gdx.graphics.getDeltaTime();
timeCounter += Gdx.graphics.getDeltaTime();
// Begin batch drawing
batch.begin();
// Draw grid background
drawGridBG();
// Every half-second
if (timeCounter >= 0.4) {
// Generate a new tetromino if there are no more falling pieces
if (fallingTetromino.isEmpty()) {
generateTetromino(PIECE_RANDOM);
}
// Shift-down all falling squares if they can go down
if (canTranslate(fallingTetromino, 0, -1)) {
translate(fallingTetromino, 0, -1);
} else { // Otherwise, set them as grounded squares and clear falling tetromino
setAsGrounded(fallingTetromino);
fallingTetromino.clear();
}
// Reset half-second counter
timeCounter = 0;
}
// Handle input
handleInput();
List<Integer> fullRows = getFullRows();
for (int row : fullRows) {
clearRow(row);
System.out.println("Clear row " + row);
ArrayList<Sprite> abovePieces = getAboveTetrominoes(row);
translate(abovePieces, 0, -1);
}
// Draw falling and grounded squares
drawTetrominoes(fallingTetromino);
drawTetrominoes(groundedTetrominoes);
// Time display rounded to 2 decimal places
font.draw(batch, "Time: " + String.format("%.2f", time), 400, 400);
// End batch drawing
batch.end();
}
@Override
public void dispose () {
batch.dispose();
}
private void clearRow(int row) {
for (int i = 0; i < groundedTetrominoes.size(); i++) {
if (Math.abs(groundedTetrominoes.get(i).getY() - row) < 0.10)
groundedTetrominoes.remove(i--);
}
}
private ArrayList<Sprite> getAboveTetrominoes(int row) {
ArrayList<Sprite> above = new ArrayList<Sprite>();
for (Sprite s : groundedTetrominoes) {
if (s.getY() > row) {
above.add(s);
}
}
return above;
}
private List<Integer> getFullRows() {
List<Integer> rows = new ArrayList<Integer>();
for (int y = GRID_Y; y < GRID_HEIGHT*GRID_SQUARE_SIZE + GRID_Y; y += GRID_SQUARE_SIZE) {
int count = 0;
for (int x = GRID_X; x < GRID_WIDTH*GRID_SQUARE_SIZE + GRID_X; x += GRID_SQUARE_SIZE) {
Vector2 pos = new Vector2(x, y);
for (Sprite s : groundedTetrominoes) {
Vector2 sPos = new Vector2(s.getX(), s.getY());
if (pos.epsilonEquals(sPos, 0.01f)) {
count++;
}
}
}
if (count == GRID_WIDTH)
rows.add(y);
}
return rows;
}
private void handleInput() {
if (Gdx.input.isKeyJustPressed(Input.Keys.LEFT)) {
if (canTranslate(fallingTetromino, -1, 0))
translate(fallingTetromino, -1, 0);
}
if (Gdx.input.isKeyJustPressed(Input.Keys.RIGHT)) {
if (canTranslate(fallingTetromino, 1, 0))
translate(fallingTetromino, 1, 0);
}
if (Gdx.input.isKeyJustPressed(Input.Keys.DOWN)) {
if (canTranslate(fallingTetromino, 0, -1))
translate(fallingTetromino, 0, -1);
}
if (Gdx.input.isKeyJustPressed(Input.Keys.Z)) {
if (canRotateTetrominoClockwise(fallingTetromino, 3))
rotateTetrominoClockwise(fallingTetromino, 3);
}
if (Gdx.input.isKeyJustPressed(Input.Keys.X)) {
if (canRotateTetrominoClockwise(fallingTetromino, 1))
rotateTetrominoClockwise(fallingTetromino, 1);
}
}
private boolean canTranslate(ArrayList<Sprite> tetromino, int xGridAmount, int yGridAmount) {
for (Sprite g : groundedTetrominoes) {
for (Sprite s : tetromino) {
Vector2 newSpritePos = new Vector2(s.getX() + xGridAmount * GRID_SQUARE_SIZE, s.getY() + yGridAmount * GRID_SQUARE_SIZE);
Vector2 gpos = new Vector2(g.getX(), g.getY());
if (newSpritePos.epsilonEquals(gpos, 0.10f) || !getGrid().contains(newSpritePos))
return false;
}
}
return true;
}
private void translate(ArrayList<Sprite> tetromino, int xGridAmount, int yGridAmount) {
for (Sprite s : tetromino) {
s.translate(xGridAmount * GRID_SQUARE_SIZE, yGridAmount * GRID_SQUARE_SIZE);
}
}
private void setAsGrounded(ArrayList<Sprite> tetromino) {
for (Sprite s : tetromino) {
groundedTetrominoes.add(s);
}
}
private void drawTetrominoes(ArrayList<Sprite> tetrominoes) {
for (Sprite s : tetrominoes) {
s.draw(batch);
}
}
/**
* Draw a dark grey grid from the base square sprites
*/
private void drawGridBG() {
sprite.setColor(rgb(15, 15, 15));
for (int x = GRID_X; x < GRID_WIDTH * GRID_SQUARE_SIZE + GRID_X; x += GRID_SQUARE_SIZE) {
for (int y = GRID_Y; y < GRID_HEIGHT * GRID_SQUARE_SIZE + GRID_Y; y += GRID_SQUARE_SIZE) {
sprite.setPosition(x, y);
sprite.draw(batch);
}
}
}
public Rectangle getGrid() {
return new Rectangle(GRID_X, GRID_Y, GRID_WIDTH * GRID_SQUARE_SIZE - GRID_SQUARE_SIZE, GRID_HEIGHT * GRID_SQUARE_SIZE - GRID_SQUARE_SIZE);
}
/**
* Spawns a specified-tetromino at the top of the board
* @param pieceType a PIECE_TYPE constant spawned
*/
public void generateTetromino(int pieceType) {
if (pieceType == PIECE_RANDOM) {
Random rand = new Random();
pieceType = rand.nextInt(7);
}
Color c = new Color(1, 1, 1, 1);
Vector2[] posarr = new Vector2[] {};
switch (pieceType) {
case PIECE_I:
// [ ][ ][ ][ ]
c = rgb(102, 255, 255);
posarr = new Vector2[] {
new Vector2(3, 17),
new Vector2(4, 17),
new Vector2(5, 17),
new Vector2(6, 17)
};
break;
case PIECE_O:
// [ ][ ]
// [ ][ ]
c = rgb(255, 255, 0);
posarr = new Vector2[] {
new Vector2(4, 17),
new Vector2(5, 17),
new Vector2(4, 16),
new Vector2(5, 16)
};
break;
case PIECE_T:
// [ ][ ][ ]
// [ ]
c = rgb(204, 0, 204);
posarr = new Vector2[] {
new Vector2(4, 17),
new Vector2(5, 17),
new Vector2(6, 17),
new Vector2(5, 16)
};
break;
case PIECE_S:
// [ ][ ]
// [ ][ ]
c = rgb(0, 255, 0);
posarr = new Vector2[] {
new Vector2(5, 17),
new Vector2(6, 17),
new Vector2(4, 16),
new Vector2(5, 16)
};
break;
case PIECE_Z:
// [ ][ ]
// [ ][ ]
c = rgb(255, 0, 0);
posarr = new Vector2[] {
new Vector2(4, 17),
new Vector2(5, 17),
new Vector2(5, 16),
new Vector2(6, 16)
};
break;
case PIECE_J:
// [ ][ ][ ]
// [ ]
c = rgb(0, 0, 255);
posarr = new Vector2[] {
new Vector2(4, 17),
new Vector2(5, 17),
new Vector2(6, 17),
new Vector2(6, 16)
};
break;
case PIECE_L:
// [ ][ ][ ]
// [ ]
c = rgb(255, 153, 51);
posarr = new Vector2[] {
new Vector2(4, 17),
new Vector2(5, 17),
new Vector2(6, 17),
new Vector2(4, 16)
};
break;
default:
break;
}
addTetromino(c, posarr);
fallingPieceType = pieceType;
fallingPieceOrientation = ORIENTATION_UP;
}
private boolean canRotateTetrominoClockwise(ArrayList<Sprite> tetromino, int numOfTurns) {
ArrayList<Sprite> temporomino = new ArrayList<Sprite>();
for (Sprite s : tetromino) {
temporomino.add(new Sprite(s));
}
pretendRotateTetrominoClockwise(temporomino, numOfTurns);
for (Sprite s : temporomino) {
System.out.println(getGrid() + " contains? (" + s.getX() + "," + s.getY() + ")");
if (!getGrid().contains(s.getX(), s.getY())) {
return false;
}
Vector2 spos = new Vector2(s.getX(), s.getY());
for (Sprite g : groundedTetrominoes) {
Vector2 gpos = new Vector2(g.getX(), g.getY());
if (spos.epsilonEquals(gpos, 0.01f)) {
return false;
}
}
}
return true;
}
private void updateTetrominoOrientation(ArrayList<Sprite> tetromino, boolean actuallyUpdate) {
Vector2[] translations = new Vector2[] {};
switch (fallingPieceType) {
case PIECE_I:
// [ ][ ][ ][ ]
if (fallingPieceOrientation == ORIENTATION_UP) {
translations = new Vector2[] {
new Vector2(1, 1),
new Vector2(0, 0),
new Vector2(-1, -1),
new Vector2(-2, -2)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_RIGHT;
} else {
translations = new Vector2[] {
new Vector2(-1, -1),
new Vector2(0, 0),
new Vector2(1, 1),
new Vector2(2, 2)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_UP;
}
break;
case PIECE_O:
// [ ][ ]
// [ ][ ]
break;
case PIECE_T:
// [ ][ ][ ]
// [ ]
switch(fallingPieceOrientation) {
case ORIENTATION_UP:
translations = new Vector2[] {
new Vector2(1, 1),
new Vector2(0, 0),
new Vector2(-1, -1),
new Vector2(-1, 1)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_RIGHT;
break;
case ORIENTATION_RIGHT:
translations = new Vector2[] {
new Vector2(1, -1),
new Vector2(0, 0),
new Vector2(-1, 1),
new Vector2(1, 1)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_DOWN;
break;
case ORIENTATION_DOWN:
translations = new Vector2[] {
new Vector2(-1, -1),
new Vector2(0, 0),
new Vector2(1, 1),
new Vector2(1, -1)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_LEFT;
break;
case ORIENTATION_LEFT:
translations = new Vector2[] {
new Vector2(-1, 1),
new Vector2(0, 0),
new Vector2(1, -1),
new Vector2(-1, -1)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_UP;
break;
default:
break;
}
break;
case PIECE_S:
// [ ][ ]
// [ ][ ]
if (fallingPieceOrientation == ORIENTATION_UP) {
translations = new Vector2[] {
new Vector2(-1, 0),
new Vector2(-2, 1),
new Vector2(1, 0),
new Vector2(0, 1)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_RIGHT;
} else {
translations = new Vector2[] {
new Vector2(1, 0),
new Vector2(2, -1),
new Vector2(-1, 0),
new Vector2(0, -1)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_UP;
}
break;
case PIECE_Z:
// [ ][ ]
// [ ][ ]
if (fallingPieceOrientation == ORIENTATION_UP) {
translations = new Vector2[] {
new Vector2(2, 1),
new Vector2(1, 0),
new Vector2(0, 1),
new Vector2(-1, 0)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_RIGHT;
} else {
translations = new Vector2[] {
new Vector2(-2, -1),
new Vector2(-1, 0),
new Vector2(0, -1),
new Vector2(1, 0)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_UP;
}
break;
case PIECE_J:
// [ ][ ][ ]
// [ ]
switch(fallingPieceOrientation) {
case ORIENTATION_UP:
translations = new Vector2[] {
new Vector2(1, 1),
new Vector2(0, 0),
new Vector2(-1, -1),
new Vector2(-2, 0)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_RIGHT;
break;
case ORIENTATION_RIGHT:
translations = new Vector2[] {
new Vector2(1, -2),
new Vector2(0, -1),
new Vector2(-1, 0),
new Vector2(0, 1)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_DOWN;
break;
case ORIENTATION_DOWN:
translations = new Vector2[] {
new Vector2(-1, -1),
new Vector2(0, 0),
new Vector2(1, 1),
new Vector2(2, 0)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_LEFT;
break;
case ORIENTATION_LEFT:
translations = new Vector2[] {
new Vector2(-1, 2),
new Vector2(0, 1),
new Vector2(1, 0),
new Vector2(0, -1)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_UP;
break;
default:
break;
}
break;
case PIECE_L:
// [ ][ ][ ]
// [ ]
switch(fallingPieceOrientation) {
case ORIENTATION_UP:
translations = new Vector2[] {
new Vector2(1, 0),
new Vector2(0, -1),
new Vector2(-1, -2),
new Vector2(0, 1)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_RIGHT;
break;
case ORIENTATION_RIGHT:
translations = new Vector2[] {
new Vector2(1, -1),
new Vector2(0, 0),
new Vector2(-1, 1),
new Vector2(2, 0)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_DOWN;
break;
case ORIENTATION_DOWN:
translations = new Vector2[] {
new Vector2(-1, 0),
new Vector2(0, 1),
new Vector2(1, 2),
new Vector2(0, -1)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_LEFT;
break;
case ORIENTATION_LEFT:
translations = new Vector2[] {
new Vector2(-1, 1),
new Vector2(0, 0),
new Vector2(1, -1),
new Vector2(-2, 0)
};
if (actuallyUpdate) fallingPieceOrientation = ORIENTATION_UP;
break;
default:
break;
}
break;
default:
break;
}
individualTranslate(tetromino, translations);
}
public void rotateTetrominoClockwise(ArrayList<Sprite> tetromino, int numOfTurns) {
for (int i = 0; i < numOfTurns; i++) {
updateTetrominoOrientation(tetromino, true);
}
}
private void pretendRotateTetrominoClockwise(ArrayList<Sprite> tetromino, int numOfTurns) {
for (int i = 0; i < numOfTurns; i++) {
updateTetrominoOrientation(tetromino, false);
}
}
private void individualTranslate(ArrayList<Sprite> tetromino, Vector2[] gridTranslations) {
if (gridTranslations.length > 0) {
for (int i = 0; i < tetromino.size(); i++) {
tetromino.get(i).translate(gridTranslations[i].x * GRID_SQUARE_SIZE, gridTranslations[i].y * GRID_SQUARE_SIZE);
}
}
}
private void addTetromino(Color color, Vector2[] posarr) {
for (int i = 0; i < 4; i++) {
Sprite s = baseSquareSprite();
Vector2 pos = gridToPixel((int)posarr[i].x, (int)posarr[i].y);
s.setPosition(pos.x, pos.y);
s.setColor(color);
System.out.println("Square spawned at " + pos);
fallingTetromino.add(s);
}
}
private Sprite baseSquareSprite() {
Sprite s = new Sprite(texture);
s.setSize(GRID_SQUARE_SIZE, GRID_SQUARE_SIZE);
return s;
}
/**
* Converts from game grid coordinates to pixel coordinates
* @param x x position on grid
* @param y y postiion on grid
* @return a Vector2 with pixel coordinates
*/
public Vector2 gridToPixel(int x, int y) {
return new Vector2(x * GRID_SQUARE_SIZE + GRID_X, y * GRID_SQUARE_SIZE + GRID_Y);
}
/**
* Converts from 255-scale RGB to percent-scale RGB
* @param r a value for red from 0 to 255
* @param g a value for green from 0 to 255
* @param b a value for blue from 0 to 255
* @return a Color object
*/
public Color rgb(float r, float g, float b) {
return new Color(r/255, g/255, b/255, 1);
}
}
| d496a6a5be5b086a32ca96d24660187b3256fc6c | [
"Java"
] | 1 | Java | anthnd/libgdx-tetris | 2faed91e2574b53024851962cf2c7a7d22a6966c | 4471c9df8da1072966a1645d9954a07efff06a43 |
refs/heads/master | <repo_name>darchevert/weatherapp-api<file_sep>/server.js
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static('static'));
var request = require('request');
var ville = [
];
app.get('/', function (req, res) {
res.render('home', {
list : ville,
});
});
app.get('/add', function (req, res) {
console.log(req.query);
request("http://api.openweathermap.org/data/2.5/weather?q="+req.query.ville+"&APPID=285d22b41e9939ae505b88f73274f9a3&units=metric&lang=fr", function(error, response, body) {
var body = JSON.parse(body);
req.query.name = body.name
req.query.description = body.weather[0].description
req.query.temp_min = body.main.temp_min
req.query.temp_max = body.main.temp_max
req.query.picto = body.weather[0].icon
});
ville.push(req.query);
res.render('home', {
list : ville,
});
});
app.get('/delete', function (req, res) {
console.log(req.query.indice);
ville.splice(req.query.indice, 1);
res.render('home', {
list: ville,
});
});
app.listen(80, function () {
console.log('Jusque là,tout va bien!');
});
| 24a899b3d7348c2c576582c4428ff460f905e0b3 | [
"JavaScript"
] | 1 | JavaScript | darchevert/weatherapp-api | 4a23f4d5c6ba2dc783c9d05dffdc1c91bd8d5bf2 | 5b7c0261b5522e288305c1f9a7b7331cb5757b93 |
refs/heads/master | <repo_name>rushabhshah95/frontend<file_sep>/src/app/module/moment/moment.routes.ts
/* Moment Feature Module Routes */
import { AddMomentComponent } from '../moment/add-moment/add-moment.component';
import { ListMomentComponent } from '../moment/list-moment/list-moment.component';
export const momentRoutes = [
{path:'moment', component: AddMomentComponent },
{path:'listMoment', component:ListMomentComponent}
];<file_sep>/src/app/service/auth.service.ts
/* A service to call API */
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { User } from '../model/user';
@Injectable({
providedIn: 'root'
})
export class AuthService {
API_URL: string = 'http://localhost:8081';
headers = new HttpHeaders().set('Content-Type', 'application/json');
currentUser = {};
constructor(private httpClient: HttpClient,public router: Router){}
// Register User API call
register(user: User): Observable<any> {
console.log(user);
return this.httpClient.post(`${this.API_URL}/auth/register`, user).pipe(
catchError(this.handleError)
)
}
// Login User API call
login(user: User) {
return this.httpClient.post<any>(`${this.API_URL}/auth/sign_in`, user)
.subscribe((res: any) => {
localStorage.setItem('access_token', res.token)
localStorage.setItem('email',res.email);
localStorage.setItem('uniqueId',res._id);
this.router.navigate(['user/moment']);
})
}
// Add Moment API call
addMoment(moment): Observable<any> {
moment['email'] = localStorage.getItem('email');
return this.httpClient.post(`${this.API_URL}/addMoment`, moment).pipe(
catchError(this.handleError)
)
}
// Provide Access token
getAccessToken() {
return localStorage.getItem('access_token');
}
// Check user is loggedIn
get isLoggedIn(): boolean {
let authToken = localStorage.getItem('access_token');
return (authToken !== null) ? true : false;
}
// Call on click of logut button
logout() {
if (localStorage.removeItem('access_token') == null) {
this.router.navigate(['login']);
}
}
getUserProfile(id): Observable<any> {
return this.httpClient.get(`${this.API_URL}/users/profile/${id}`, { headers: this.headers }).pipe(
map((res: Response) => {
return res || {}
}),
catchError(this.handleError)
)
}
// Get all moment API
getAllMoments(): Observable<any> {
let email = localStorage.getItem('email');
return this.httpClient.get(`${this.API_URL}/getAllMoment/${email}`, { headers: this.headers }).pipe(
map((res: Response) => {
return res || {}
}),
catchError(this.handleError)
)
}
// Get Moment Image
getMomentImage(fileName): Observable<any> {
return this.httpClient.get(`${this.API_URL}/getMoment/${fileName}`, { headers: this.headers }).pipe(
map((res: Response) => {
return res || {}
}),
catchError(this.handleError)
)
}
// Delete Moment
deleteMoment(momentId): Observable<any> {
return this.httpClient.delete(`${this.API_URL}/deleteMoment/${momentId}`, { headers: this.headers }).pipe(
map((res: Response) => {
return res || {}
}),
catchError(this.handleError)
)
}
// Handle API Error
handleError(error: HttpErrorResponse) {
let msg = '';
if (error.error instanceof ErrorEvent) {
// client-side error
msg = error.error.message;
} else {
// server-side error
msg = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
return throwError(msg);
}
}<file_sep>/src/app/log-in/log-in.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { AuthService } from '../service/auth.service';
@Component({
selector: 'app-login',
templateUrl: './log-in.component.html',
styleUrls: ['./log-in.component.css']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
userData: any;
hide = true;
constructor(
public formBuilder: FormBuilder,
public authService: AuthService,
public router: Router
) {
this.loginForm= this.formBuilder.group({
email: [null, Validators.required],
password: [null, Validators.required]
})
}
ngOnInit() {
}
loginUser(userData) {
this.userData = userData;
this.authService.login(this.userData)
}
}<file_sep>/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { MaterialModule } from './material.module';
import { FlexLayoutModule } from '@angular/flex-layout';
import { AppComponent } from './app.component';
import { SignUpComponent } from './sign-up/sign-up.component';
import {Ng2TelInputModule} from 'ng2-tel-input';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'
import { AuthInterceptor } from '../app/httpInterceptor/auth.interceptor';
import { LoginComponent } from './log-in/log-in.component';
import { NavBarComponent } from './nav-bar/nav-bar.component';
import { SidenavListComponent } from './nav-bar/sidenav-list/sidenav-list.component';
import { HeaderComponent } from './nav-bar/header/header.component';
import { NavbarService } from './nav-bar/navbar.service';
@NgModule({
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
MaterialModule,
FlexLayoutModule,
Ng2TelInputModule,
HttpClientModule
],
declarations: [ AppComponent, SignUpComponent, LoginComponent, NavBarComponent, SidenavListComponent, HeaderComponent ],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
},
NavbarService
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
<file_sep>/src/app/module/moment/add-moment/add-moment.component.ts
import { FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Component, OnInit} from '@angular/core';
import { AuthService } from '../../../service/auth.service';
import { Router } from '@angular/router';
import { NavbarService } from '../../../nav-bar/navbar.service';
@Component({
selector: 'app-add-moment',
templateUrl: './add-moment.component.html',
styleUrls: ['./add-moment.component.css']
})
export class AddMomentComponent implements OnInit {
isShown: boolean;
form: FormGroup = new FormGroup({});
constructor(public fb: FormBuilder,
public authService: AuthService,
public router: Router,
public nav: NavbarService ) {
this.form = this.fb.group({
title: [null,Validators.required,Validators.maxLength(100)],
file: [null,Validators.required],
tags:[null,Validators.required],
})
}
ngOnInit() {
this.nav.show();
this.isShown = true;
}
uploadFile(event) {
let reader = new FileReader();
if(event.target.files && event.target.files.length > 0) {
let file = event.target.files[0];
reader.readAsDataURL(file);
reader.onload = () => {
this.form.get('file').setValue({
filename: file.name,
filetype: file.type,
value: (<string>reader.result).split(',')[1]
})
};
}
}
submitForm() {
const formModel = this.form.value;
console.log(formModel)
this.authService.addMoment(formModel).subscribe((res) => {
if (res._id){
this.router.navigate(['/user/listMoment']);
}
})
}
}
<file_sep>/src/app/module/moment/moment.module.ts
/* A Moment Featue Module */
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { AddMomentComponent } from './add-moment/add-moment.component';
import { ListMomentComponent } from './list-moment/list-moment.component';
import { MaterialModule } from '../../../app/material.module';
import { momentRoutes } from './moment.routes';
@NgModule({
declarations: [AddMomentComponent, ListMomentComponent],
imports: [
CommonModule,
FormsModule,
RouterModule.forChild(momentRoutes),
ReactiveFormsModule,
MaterialModule
]
})
export class MomentModule { }
<file_sep>/src/app/module/moment/list-moment/list-moment.component.ts
import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { Moment } from '../../../model/moment';
import { AuthService } from '../../../service/auth.service';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'app-list-moment',
templateUrl: './list-moment.component.html',
styleUrls: ['./list-moment.component.css']
})
export class ListMomentComponent implements OnInit {
public displayedColumns = ['fileName', 'title', 'tags', 'update', 'delete'];
public dataSource = new MatTableDataSource<Moment>();
base64Image : any;
imageUrl;
constructor(public authService: AuthService,private sanitizer:DomSanitizer) { }
ngOnInit() {
this.getAllMoments();
}
public getAllMoments = () => {
this.authService.getAllMoments().subscribe(res => {
this.dataSource.data = res as Moment[];
});
}
public displayImage = (fileName: string) => {
this.authService.getMomentImage(fileName).subscribe(res => {
console.log(res);
this.base64Image = res;
let imageBase64String= btoa(this.base64Image);
this.imageUrl = 'data:image/jpeg;base64,' + imageBase64String;
})
}
transform(){
return this.sanitizer.bypassSecurityTrustResourceUrl(this.base64Image);
}
public DeleteMoment = (id:string) => {
this.authService.deleteMoment(id).subscribe(res => {
console.log(res);
if(res._id == id){
console.log("successfully deleted");
//or check status code or send status code from backend in response
}
})
}
}
<file_sep>/src/app/model/user.ts
// User Details Model
export class User {
_id: String;
firstName: String;
lastName: String;
mobileNumber: String;
email: String;
city: String;
hash_password: String;
}<file_sep>/src/app/model/moment.ts
// Moment details Model
export interface Moment {
_id: string;
filename: string;
title:string;
tags:string;
email:string;
}<file_sep>/src/app/sign-up/sign-up.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import {Observable} from 'rxjs'
import { AuthService } from '../service/auth.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-sign-up',
templateUrl: './sign-up.component.html',
styleUrls: ['./sign-up.component.css']
})
export class SignUpComponent {
formGroup: FormGroup;
rquiredAlert: string = 'This field is required';
userData: any;
isShown=false;
constructor(
public formBuilder: FormBuilder,
public authService: AuthService,
public router: Router) { }
ngOnInit() {
this.createForm();
}
createForm() {
let emailregex: RegExp = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
let phoneNumregex: RegExp = /^\+[1-9]{1}[0-9]{3,14}$/;
this.formGroup = this.formBuilder.group({
'email': [null, [Validators.required, Validators.pattern(emailregex)], this.checkInUseEmail],
'firstName': [null, Validators.required],
'lastName': [null, Validators.required],
'mobileNumber': [null, Validators.required,Validators.pattern(phoneNumregex)],
'city': [null, Validators.required, Validators.minLength(2), Validators.maxLength(20)],
'password': [null, [Validators.required, this.checkPassword]],
});
}
checkPassword(control) {
let enteredPassword = control.value
let passwordCheck = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/;
return (!passwordCheck.test(enteredPassword) && enteredPassword) ? { 'requirements': true } : null;
}
checkInUseEmail(control) {
// mimic http database access
let db = ['<EMAIL>'];
return new Observable(observer => {
setTimeout(() => {
let result = (db.indexOf(control.value) !== -1) ? { 'alreadyInUse': true } : null;
observer.next(result);
observer.complete();
}, 4000)
})
}
getErrorEmail() {
return this.formGroup.get('email').hasError('required') ? 'Field is required' :
this.formGroup.get('email').hasError('pattern') ? 'Not a valid emailaddress' :
this.formGroup.get('email').hasError('alreadyInUse') ? 'This emailaddress is already in use' : '';
}
getErrorPassword() {
return this.formGroup.get('password').hasError('required') ? 'AlphaNumeric password is required with atleast one capital letter' :
this.formGroup.get('password').hasError('requirements') ? 'Password needs to be alphanumeric with atleast one capital letter' : '';
}
onSubmit(userData) {
this.userData = userData;
this.authService.register(this.userData).subscribe((res) => {
if (res._id){
this.router.navigate(['login']);
}
})
}
onCountryChange(event)
{
console.log(event.dialCode);
console.log(event.name);
console.log(event.iso2);
}
}
| b745b379fb48eda9a6c9bf6c39ee7f3807ca9e5d | [
"TypeScript"
] | 10 | TypeScript | rushabhshah95/frontend | 468be3b97e3bd3bf74f79bc763194e2536952f0a | fa5a7b6a1adc388a21c718c059b7494ca8a921d0 |
refs/heads/master | <file_sep>"""An SQLite3 to PostgreSQL database migration tool."""
import os
import typing
from pathlib import Path
if os.name == "nt":
HOME_CONFIG = Path.home() / ".sqlite2pg"
LOG_CONFIG = HOME_CONFIG / "logs"
else:
HOME_CONFIG = Path.home() / ".config/sqlite2pg"
LOG_CONFIG = HOME_CONFIG / "logs"
DEV_HOME_CONFIG = Path(".") / ".config/sqlite2pg"
DEV_LOG_CONFIG = DEV_HOME_CONFIG / "logs"
from .cli import *
from .modules import *
__version__: str = "0.1.4"
__author__: str = "Jonxslays"
__maintainer__: str = "Jonxslays"
__license__: str = "BSD-3-Clause"
__url__: str = "https://github.com/Jonxslays/sqlite2pg"
__all__: typing.List[str] = [
"Worker",
"S2PLogger",
"Sqlite2pgError",
"SqliteError",
"LoggingConfigError",
"PostgresError",
"__version__",
"__author__",
"__maintainer__",
"__license__",
"__url__",
"CommandHandler",
"HOME_CONFIG",
"DEV_HOME_CONFIG",
"DEV_LOG_CONFIG",
"CONFIG_SCHEMA",
"CleanSchemaT",
"sqlite",
]
<file_sep>[tool.poetry]
name = "sqlite2pg"
version = "0.1.4"
description = "An SQLite3 to PostgreSQL database migration tool."
license = "BSD-3-Clause"
homepage = "https://github.com/Jonxslays/sqlite2pg"
repository = "https://github.com/Jonxslays/sqlite2pg"
authors = ["Jonxslays"]
readme = "README.md"
packages = [
{ include = "sqlite2pg" },
{ include = "sqlite2pg/py.typed" }
]
classifiers = [
"Development Status :: 2 - Pre-Alpha",
"License :: OSI Approved :: BSD License",
"Framework :: Pytest",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: System Administrators",
"Natural Language :: English",
"Operating System :: MacOS",
"Operating System :: POSIX",
"Operating System :: Unix",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Topic :: Database",
"Typing :: Typed",
]
[tool.poetry.scripts]
sqlite2pg = "sqlite2pg.cli:main"
[tool.poetry.dependencies]
python = ">=3.6,<=3.10"
aiofiles = "^0.7.0"
aiosqlite = "^0.17.0"
asyncpg = "^0.24.0"
click = "^8.0.1"
loguru = "^0.5.3"
[tool.poetry.dev-dependencies]
mypy = "^0.910"
nox = "^2021.6.12"
pytest = "^6.2.5"
types-aiofiles = "^0.1.9"
flake8 = "^3.9.2"
[tool.poetry.dev-dependencies.black]
python = ">=3.6.2,<=3.10"
version = "^21.8b0"
[tool.poetry.dev-dependencies.isort]
python = ">=3.6.1,<=3.10"
version = "^5.9.3"
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
<file_sep>import time
from pathlib import Path
import click
from loguru import logger
from sqlite2pg import CleanSchemaT, Worker
FILE_HEADER = """/*
*
* DATABASE:
* '{}'
*
* This schema is in '{}' format.
*
* File created by sqlite2pg at {:.0f} epoch.
* Use this generated file to import your schema at a later time.
* Thank you for using sqlite2pg.
*
*/\n"""
@click.command(name="schema")
@click.argument("database", type=click.Path(exists=True, path_type=Path))
@click.option("-f", "--file", type=Path, help="The optional PATH to write the schema to.")
@click.option(
"-c",
"--convert",
is_flag=True,
default=False,
help="If added, this flag converts the schema to postgres syntax.",
)
@click.pass_context
def schema(ctx: click.Context, database: Path, file: Path, convert: bool) -> None:
"""Get table schema from an sqlite DATABASE.
By default sqlite2pg will write the schema to stdout.
DATABASE The database to get the schema from.
"""
worker: Worker = Worker()
schema: CleanSchemaT = worker.get_sqlite_schema(database)
if convert:
schema = worker.convert_sqlite_to_pg(schema)
if file:
if file.is_dir():
logger.error("attempted to write schema to a directory. exiting...")
click.secho("ERROR:", fg="red", bold=True)
click.echo(f"can't write schema to '{file}'. it is a directory.")
return
elif file.exists():
click.confirm(f"'{file}' exists. overwrite it?", default=False, abort=True)
logger.debug("overwriting existing file in schema generation.")
with open(file, "w", encoding="utf-8") as f:
f.write(
FILE_HEADER.format(database, "PostgreSQL" if convert else "SQLite", time.time()),
)
for t, s in schema.items():
f.write(f"\n-- Schema for table '{t}':\n{s[0]}\n")
else:
for t, s in schema.items():
click.secho(f"\n-- schema for table '{t}'", fg="green", bold=True)
click.echo(f"{s[0]}")
<file_sep>import typing
__all__: typing.List[str] = [
"Sqlite2pgError",
"SqliteError",
"PostgresError",
"LoggingConfigError",
]
# Do we need these???
class Sqlite2pgError(Exception):
"""Base Exception that all sqlite2pg exceptions inherit from."""
__slots__: typing.Sequence[str] = ()
pass
class SqliteError(Sqlite2pgError):
"""Represents an error in an sqlite3 related action."""
__slots__: typing.Sequence[str] = ()
pass
class PostgresError(Sqlite2pgError):
"""Represents an error in an sqlite3 related action."""
__slots__: typing.Sequence[str] = ()
pass
class LoggingConfigError(Sqlite2pgError):
"""Represents an error in logging configuration."""
__slots__: typing.Sequence[str] = ()
pass
<file_sep>import os
import sqlite3
import time
import typing
from pathlib import Path
from loguru import logger
from sqlite2pg.modules import sqlite
__all__: typing.List[str] = [
"Worker",
"CleanSchemaT",
]
# Represents the schema dicts used later on.
RawSchemaT = typing.MutableMapping[str, typing.List[typing.Sequence[str]]]
CleanSchemaT = typing.MutableMapping[str, typing.List[str]]
class Worker:
"""The object that carries the workload of the program.
Args:
logger: logging.Logger
The logger to use for the worker. This logger will be
supplied automatically by the command line entry point.
"""
__slots__: typing.Sequence[str] = ("test_sqlite_db",)
def __init__(self) -> None:
logger.debug("worker initialized...")
self.test_sqlite_db: Path = Path("./database.db3")
def get_sqlite_schema(self, db: Path) -> CleanSchemaT:
"""Gets the schema for a given sqlite3 database.3
Args:
db: str
The path to the sqlite database to get the schema for.
Returns:
CleanSchemaT:
A mapping containing the schema for the tables found
in the database.
"""
start: float = time.time()
# Validate that the database file exists
if not os.path.isfile(db):
logger.error(f"can't connect to '{db}', the file doesnt exist.")
exit(1)
# Connect to the database, and obtain a cursor.
logger.debug(f"connecting to: '{db}'.")
conn: sqlite3.Connection = sqlite3.connect(db)
cur: sqlite3.Cursor = conn.cursor()
# Assign 2 mappings for raw and clean schema.
raw_schema: RawSchemaT = {}
clean_schema: CleanSchemaT = {}
try:
logger.debug("attempting to fetch tables from sqlite master.")
# Gather all table names
cur.execute(sqlite.get_tables())
# We were unable to fetch the data, likely it was not a database.
except sqlite3.DatabaseError as e:
logger.debug(f"{e.__class__.__name__}: {e}")
logger.error(f"'{db}' is not a database. exiting...")
exit(1)
else:
logger.info(f"connection to '{db}' secured.")
# Iterate through table names.
for table in [d[0] for d in cur.fetchall()]:
logger.info(f"fetching schema for '{table}'.")
# Gather the schema for that table.
cur.execute(sqlite.get_schema(table))
# If there is no schema, error.
data = cur.fetchall()
if not data:
logger.error(f"found '{table}' but no schema. exiting...")
conn.close()
exit(1)
# Assign that schema to our schema dict.
logger.debug(f"found schema for '{table}'.")
raw_schema[table] = data
# We didn't find tables or schema.
if not raw_schema:
logger.error("no tables found. exiting...")
conn.close()
exit(1)
# Replace tabs with 4 spaces and create
# a list of strings instead of a list
# of tuples with one string inside.
# Add this list to the clean mapping.
for t, q in raw_schema.items():
clean_schema[t] = [q[0][0].replace("\t", " ") + ";"]
# Close the connection to sqlite
logger.debug(f"closed connection to sqlite: '{db}'.")
conn.close()
end: float = time.time()
logger.info(
f"found {len(clean_schema)} tables and schema in {(end - start) * 1000:.4f} ms."
)
return clean_schema
def convert_sqlite_to_pg(self, schema: CleanSchemaT) -> CleanSchemaT:
"""Converts sqlite queries to postres syntax.
Args:
schema: CleanSchemaT
A mutable mapping of tables to table schema.
Returns:
CleanSchemaT:
A mapping containing the schema for the tables from
sqlite transformed to fit postgres syntax.
"""
start: float = time.time()
logger.debug("beginning conversion to postgres syntax")
# Iterate over each table and alter its schema
for table, query in schema.items():
buffer: str = query[0]
# Postgres doesn't like double quotes.
buffer = buffer.replace('"', "'")
# Sqlite integers can be larger than pgsql.
# Handle upper and lower case.
buffer = buffer.replace("integer", "bigint")
buffer = buffer.replace("INTEGER", "BIGINT")
# Assign the new schema back to the table
# now the that is has been converted.
query[0] = buffer
logger.debug(f"'{table}' has been converted.")
end: float = time.time()
return schema
def validate_input(self, message: str, bad_actor: int = 0) -> str:
"""Validates user confirmation input.
Args:
message: str
The message received from stdin.
bad_actor: int, optional
The amount of invalid inputs received thus far.
Defaults to 0.
Returns:
str: The text from the users confirmation
"""
logger.debug(f"Input validation (attempt {bad_actor + 1}).")
validated: str = input(message)
# Handle case where user inputs nothing.
while not validated or validated[0] not in "yYnN":
bad_actor += 1
if bad_actor >= 3:
logger.error("too many failed inputs. exiting...")
exit(1)
validated = self.validate_input(message, bad_actor)
if validated[0] not in "yY":
logger.debug(f"user chose to exit with input: '{validated}'.")
logger.info("exiting...")
exit(0)
logger.debug(f"user accepted with input: '{validated}'.")
return validated
def execute(self) -> None:
"""Execute the main logic of the program."""
# Gather the sqlite schema from the database.
sqlite_schema = self.get_sqlite_schema(self.test_sqlite_db)
# Validate we gather the correct schema.
self.validate_input("does the schema look correct [y/n]: ")
# Validate the converted schema is correct
converted_schema = self.convert_sqlite_to_pg(sqlite_schema)
# Validate the converted schema is correct
self.validate_input("does the converted schema look correct [y/n]: ")
print("No further logic is implemented.")
exit(0)
# TODO
# Connect to postgres
# Create the tables
# Get the actual data from the tables in sqlite
# Insert the data into postgres
# Could we use pandas to move the data?
<file_sep>import asyncio
import json
import pathlib
import typing
import click
from sqlite2pg import DEV_HOME_CONFIG, DEV_LOG_CONFIG
from sqlite2pg.modules import S2PLogger
__all__: typing.List[str] = [
"CommandHandler",
"CONFIG_SCHEMA",
]
COMMANDS_DIR: str = "./sqlite2pg/commands"
COMMANDS_FILES: typing.List[pathlib.Path] = [*pathlib.Path(".").glob(f"{COMMANDS_DIR}/*.py")]
ConfigSchemaT = typing.Mapping[str, typing.Mapping[str, typing.Union[str, bool, int]]]
CONFIG_SCHEMA: ConfigSchemaT = {
"logging": {
"enable": True,
"level": "INFO",
"to_cwd": False,
"retention": 7,
}
}
class CommandHandler(click.MultiCommand):
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
super().__init__(*args, **kwargs)
def list_commands(self, ctx: click.Context) -> typing.List[str]:
commands: typing.List[str] = []
commands.extend(p.stem for p in COMMANDS_FILES)
commands.sort()
return commands
def get_command(self, ctx: click.Context, name: str) -> typing.Optional[click.Command]:
namespace: typing.Dict[str, object] = {}
filepath = pathlib.Path(f"{COMMANDS_DIR}/{name}.py")
with open(filepath, "r") as f:
code = compile(f.read(), filepath, "exec")
eval(code, namespace, namespace)
cmd = namespace.get(name)
return cmd if isinstance(cmd, click.Command) else None
@staticmethod
def init_logging() -> None:
try:
with open(DEV_HOME_CONFIG / "config.json", "r") as f:
data: typing.MutableMapping[str, typing.Any] = json.loads(f.read())
except FileNotFoundError:
config_path = DEV_HOME_CONFIG / "config.json"
DEV_LOG_CONFIG.mkdir(parents=True, exist_ok=True)
config_path.touch()
schema = json.dumps(CONFIG_SCHEMA, indent=4, sort_keys=True)
with open(config_path, "w") as f2:
f2.write(schema)
except PermissionError:
click.echo(
f"{click.style('unable to access config file.', fg='red', bold=True)}\n"
"this is likely a permissions issue. please make sure the\n"
"sqlite2pg config.json exists, and has the correct permissions.\nusing bash: "
f"`{click.style('find / -wholename *sqlite2pg/config.json', fg='yellow', bold=True)}`"
)
click.secho("continuing anyways...", bold=True)
S2PLogger.configure(enable=False, to_cwd=False, log_level="", retention=0)
else:
S2PLogger.configure(
enable=data["logging"]["enable"],
to_cwd=data["logging"]["to_cwd"],
log_level=data["logging"]["level"],
retention=data["logging"]["retention"],
)
async def async_main() -> None:
await asyncio.sleep(0)
cli = CommandHandler(help="An SQLite3 to PostgreSQL database migration tool.")
cli.init_logging()
cli()
def main() -> None:
asyncio.run(async_main())
<file_sep>import re
from sqlite2pg import __author__, __license__, __maintainer__, __url__, __version__
def test_metadata() -> None:
with open("pyproject.toml", "r") as f:
meta = f.read()
ver = re.findall(r"version = \"(.*)\"", meta)[0]
author = re.findall(r"authors = \[\"(.*)\"\]", meta)[0]
license = re.findall(r"license = \"(.*)\"", meta)[0]
url = re.findall(r"repository = \"(.*)\"", meta)[0]
assert author == __author__
assert author == __maintainer__
assert license == __license__
assert url == __url__
assert ver == __version__
<file_sep>import click
@click.group(name="config", invoke_without_command=True)
@click.pass_context
def config(ctx: click.Context) -> None:
"""Configure sqlite2pg."""
click.secho(
"The `config` subcommand has not been implemented yet.",
fg="red",
bold=True,
)
@config.command(name="regen")
@click.pass_obj
def regen_command(obj: object) -> None:
# prints "magic string"
click.secho(
"The `config regen` subcommand has not been implemented yet.",
fg="red",
bold=True,
)
<file_sep>import typing
__all__: typing.List[str] = [
"get_tables",
"get_schema",
]
def get_tables() -> str:
return """
SELECT name FROM sqlite_master
WHERE type IS 'table'
AND name NOT LIKE 'sqlite_%'
ORDER BY 1
"""
def get_schema(table: str) -> str:
return f"""
SELECT sql
FROM sqlite_master
WHERE name='{table}'
"""
<file_sep># sqlite2pg
An SQLite3 to PostgreSQL database migration tool.
## WARNING
This project is still in very early development, and will not be ready until the v1.0 release.
Please refrain from using sqlite2pg for now. Thanks for reading.
## Why sqlite2pg
- An easy to use command line interface.
- Options to accomodate different use cases.
- Complete full migrations, or just generate schema.
## Installation
sqlite2pg requires python 3.6 or greater.
To get started:
```bash
pip install sqlite2pg
```
## License
sqlite2pg is licensed under the [BSD 3-Clause License](https://github.com/Jonxslays/sqlite2pg/blob/master/LICENSE).
<file_sep>import typing
from .errors import *
from .logging import *
from .sqlite import *
from .worker import *
__all__: typing.List[str] = [
"S2PLogger",
"Sqlite2pgError",
"SqliteError",
"LoggingConfigError",
"PostgresError",
"get_tables",
"get_schema",
"Worker",
"CleanSchemaT",
"sqlite",
]
<file_sep>import nox
def install(session: nox.Session, dev: bool = False) -> nox.Session:
if dev:
session.run("poetry", "install", "-n", external=True)
else:
session.run("poetry", "install", "-n", "--no-dev", external=True)
return session
@nox.session(reuse_venv=True)
def testing(session: nox.Session) -> None:
session = install(session, True)
session.run("pytest", "--verbose")
@nox.session(reuse_venv=True)
def type_checking(session: nox.Session) -> None:
session = install(session, True)
session.run("mypy", ".", "--strict")
@nox.session(reuse_venv=True)
def formatting(session: nox.Session) -> None:
session = install(session, True)
session.run("black", ".", "-l99")
@nox.session(reuse_venv=True)
def import_checking(session: nox.Session) -> None:
session = install(session, True)
session.run(
"flake8",
"sqlite2pg",
"tests",
"--select",
"F4",
"--extend-ignore",
"E,F",
"--extend-exclude",
"__init__.py",
)
session.run("isort", ".", "-cq", "--profile", "black")
<file_sep>import click
@click.command(name="migrate")
def migrate() -> None:
"""Make migrations from sqlite to postgres."""
click.secho(
"The `migrate` subcommand has not been implemented yet.",
fg="red",
bold=True,
)
<file_sep>import typing
from datetime import timedelta
import click
from loguru import logger
from sqlite2pg import DEV_LOG_CONFIG
__all__: typing.List[str] = [
"S2PLogger",
]
LOG_FILE_FMT: str = "./sqlite2pg.{time:X}.log"
class S2PLogger:
"""Logging for the program."""
FORMAT: str = "<green>{time}</green> | <level>{level: <8}</level> ||| <level>{message}</level>"
@staticmethod
def configure(
enable: bool,
to_cwd: bool,
log_level: str,
retention: int,
) -> None:
"""Configures logger object."""
logger.remove()
if not enable:
logger.disable("sqlite2pg")
return
try:
logger.add(
LOG_FILE_FMT if to_cwd else (DEV_LOG_CONFIG / LOG_FILE_FMT),
format=S2PLogger.FORMAT,
level=log_level.upper(),
retention=timedelta(days=retention),
)
except Exception as e:
print(e)
click.secho("ERROR:", fg="red", bold=True)
click.echo(
"invalid logging level retrieved from config.\n"
"please validate your config or run `sqlite2pg config regen`."
)
exit(1)
else:
logger.debug("logging configuration completed.")
| 4f9929e46b2f0a52fd0effd902d541abf9b72155 | [
"TOML",
"Python",
"Markdown"
] | 14 | Python | parafoxia/sqlite2pg | efbbc31e82aaac7fd470091c6a30fc1315d499c4 | 6a95ee5551d08c013b9f00e7e0a11bd78d542b98 |
refs/heads/master | <file_sep>using IdentityServer4.Core;
using IdentityServer4.Core.Models;
using IdentityServer4.Core.Services.InMemory;
using System.Collections.Generic;
using System.Security.Claims;
namespace PLM.Authorization
{
public class InMemoryManager
{
public List<InMemoryUser> GetUsers()
{
return new List<InMemoryUser> {
new InMemoryUser
{
Subject="<EMAIL>",
Username="<EMAIL>",
Password="<PASSWORD>",
Claims = new []
{
new Claim(Constants.ClaimTypes.ExternalProviderUserId, "<NAME>")
}
}
};
}
public IEnumerable<Scope> GetScopes()
{
return new[] {
StandardScopes.OpenId,
StandardScopes.Profile,
StandardScopes.OfflineAccess,
new Scope
{
Name="read",
DisplayName="Read User Data"
}
};
}
public IEnumerable<Client> GetClients()
{
return new[]
{
new Client
{
ClientId="socialnetwork",
ClientSecrets = new List<Secret>
{
new Secret ("secret".Sha256())
},
ClientName="CmsService",
Flow=Flows.ResourceOwner,
AllowedScopes =new List<string>
{
"read"
},
Enabled=true
},
new Client
{
ClientId = "socialnetwork_implicit",
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256())
},
ClientName = "SocialNetwork",
Flow = Flows.Implicit,
AllowedScopes = new List<string>
{
Constants.StandardScopes.OpenId,
Constants.StandardScopes.Profile,
"read"
},
RedirectUris = new List<string>
{
"http://localhost:8000/index.html/private"
},
PostLogoutRedirectUris = new List<string>
{
"http://localhost:8000/index.html/post-private"
},
AllowedCorsOrigins = new List<string>
{
"*"
},
Enabled=true
}
};
}
}
}<file_sep>(function() {
'use strict';
angular.module('PLM.Controllers.Main', []).
controller('MainController',['$scope','AuthService','localStorageService', function($scope, AuthService,localStorageService){
$scope.test = "Successfull "
//AuthService.authorize();
}])
})();<file_sep>using System.IO;
using System.Security.Cryptography.X509Certificates;
namespace PLM.Authorization
{
static class Certificate
{
public static X509Certificate2 Get()
{
var assembly = typeof(Certificate).Assembly;
using (var stream = assembly.GetManifestResourceStream("PLM.Authorization.AjainServerCert.pfx"))
{
var str = ReadStream(stream);
return new X509Certificate2(str, "Test123");
}
}
private static byte[] ReadStream(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
}<file_sep>(function() {
'use strict';
var app = angular.module('PLM.UI', [
'ngRoute',
'PLM.Controllers',
'PLM.Services',
'LocalStorageModule',
"ui.router"
]);
//Route configuration
app.config(['$routeProvider',
'$httpProvider',
'$locationProvider',
'$stateProvider',
'$urlRouterProvider',
function($routeProvider,httpProvider,$locationProvider,$stateProvider,$urlRouterProvider) {
//ToDo: Turn off for time being
// $locationProvider.html5Mode(true);
//$locationProvider.hashPrefix('!');
// $urlRouterProvider.otherwise("/");
$stateProvider.state('private',{
url: "/private",
templateUrl: "resource/private.html",
controller: "UserController"
})
.state('status',{
url: "/status", template: "The site is up and running"
})
.state('authorize',{
url: '/authorize', templateUrl: 'account/authorize.html', controller: 'AuthorizeController'
})
// var route = {templateUrl: 'account/authorize.html', controller: 'AuthorizeController'};
// $routeProvider.when('/authorize', route);
// $routeProvider.when('/status', {template:'The web server is up and running'});
// $routeProvider.when('/authorized', {redirectTo: '/private'});
// $routeProvider.when('/private', {templateUrl: 'resource/private.html', controller: 'UserController'});
//httpProvider.interceptors.push('authInterceptor');
}]);
//Constants
app.constant('AUTH_EVENTS', {
loginSuccess: 'auth-login-success',
loginFailed: 'auth-login-failed',
logoutSuccess: 'auth-logout-success',
logoutFailed: 'auth-logout-failed',
registrationSuccess: 'auth-registration-success',
registrationFailed: 'auth-registration-failed',
sessionTimeout: 'auth-session-timeout',
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized'
});
app.constant('USER_ROLES', {
all: '*',
admin: 'admin',
editor: 'editor',
guest: 'guest'
});
})();<file_sep>using MongoDB.Driver;
namespace PLM.CmsService.Data
{
public interface IDbConnection
{
IMongoDatabase Connect { get; }
}
}
<file_sep>using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
//ToDo:
// A generic repository can be made and reuse in other services.
// Collection name "contents" can be handled with naming convention or as a configuration value.
namespace PLM.CmsService.Data
{
public class CMSRepository : IRepository<CMSContent>,IDisposable
{
IMongoDatabase contentDatabase;
public CMSRepository(IDbConnection connection)
{
contentDatabase = connection.Connect;
}
public IEnumerable<CMSContent> List
{
get
{
var contents = contentDatabase.GetCollection<CMSContent>("contents");
var contentsCollection = contents.Find(new BsonDocument()).ToList();
return contentsCollection;
}
}
public void Add(CMSContent entity)
{
contentDatabase.GetCollection<CMSContent>("contents").InsertOne(entity);
}
public void Delete(CMSContent entity)
{
throw new NotImplementedException();
}
public void Dispose()
{
Console.WriteLine("Disposing.....");
}
public CMSContent FindById(int Id)
{
throw new NotImplementedException();
}
public void Update(CMSContent entity)
{
throw new NotImplementedException();
}
}
}
<file_sep>using PLM.CmsService.Data;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNet.Authentication.JwtBearer;
using System.IdentityModel.Tokens;
using System;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc.Filters;
using System.IdentityModel.Tokens.Jwt;
namespace CmsService.API
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddSingleton<IConfiguration>(sp => { return Configuration; });
services.AddSingleton<IDbConnection, MongoConnection>(); //ToDo: Consider to implement pooling singleton pattern
services.AddScoped<IRepository<CMSContent>, CMSRepository>();
var scopePolicy = new AuthorizationPolicyBuilder()
.RequireClaim("scope", "read")
.Build();
services.AddMvcCore(setup =>
{
setup.Filters.Add(new AuthorizeFilter(scopePolicy));
})
.AddJsonFormatters()
.AddAuthorization();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseMvcWithDefaultRoute();
app.UseMvc();
app.UseStatusCodePages();
app.UseDeveloperExceptionPage();
var certificate = new X509Certificate2(Convert.FromBase64String("MIIFFTCCAv2gAwIBAgIQJhSZrRi<KEY>"));
////oAuthorization
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
Authority = "http://localhost:64705",
Audience = "http://localhost:64705/resources",
RequireHttpsMetadata =false,
AutomaticAuthenticate = true,
TokenValidationParameters = new TokenValidationParameters
{
//ValidIssuer = "http://localhost:64705/",
//ValidAudience = "http://localhost:64705/resources",
//IssuerSigningKey = new X509SecurityKey(certificate),
NameClaimType = "name"
}
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
<file_sep>using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Configuration;
using PLM.CmsService.Data;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace CmsService.API.Controllers
{
[Route("api/[controller]")]
public class BaseController : Controller
{
protected IConfiguration Config { get; }
protected IRepository<CMSContent> CMSRepo { get; }
public BaseController()
{
}
protected BaseController(IConfiguration config, IRepository<CMSContent> repo)
{
this.Config = config;
this.CMSRepo = repo;
}
}
}
<file_sep>using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace PLM.CmsService.Data
{
public class CMSContent: IEntity
{
[BsonId]
public ObjectId id
{
get;set;
}
public ContentBlock content { get; set; }
}
public class ContentBlock
{
public int contentId { get; set; }
public string title { get; set; }
public string description { get; set; }
public string text { get; set; }
}
}
<file_sep>using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using PLM.CmsService.Data;
using System;
using Microsoft.AspNet.Authorization;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace CmsService.API.Controllers
{
public class ContentController : BaseController
{
//IRepository<CMSContent> repo;
public ContentController(IConfiguration config, IRepository<CMSContent> repo) : base(config,repo)
{
// this.repo = repo;
}
// GET: api/content
[HttpGet]
[Authorize]
public IEnumerable<CMSContent> Get()
{
var list = CMSRepo.List;
return list;
}
[HttpPost]
public void Post([FromBody]CMSContent value)
{
CMSContent values = new CMSContent() { content = new ContentBlock() { contentId = new Random().Next(100, 1000), description = "Sample description " + DateTime.Now, text = "Sample text " + DateTime.Now, title = "Sample title " + DateTime.Now } };
CMSRepo.Add(values);
}
}
}
<file_sep>(function() {
'use strict';
angular.module('PLM.Services.Configuration', [])
.service('ConfigService',[function(){
var apiUrl = 'http://localhost:10073/';
var authSrvrBaseUrl = 'http://localhost:64705/';
var publicApiUrl = 'http://localhost:14117/'
var api = {
accountUri: apiUrl + 'api/account/',
connectUri: authSrvrBaseUrl + 'connect/authorize',
resourceUri : publicApiUrl + 'resource/'
};
var getOAuthConfig =
{
client_id: "socialnetwork_implicit",
scope: "read",
response_type: "token",
redirect_uri: "http://localhost:8000/index.html/private",
state: Date.now() + "" + Math.random(),
nonce: "N" + Math.random() + "" + Date.now()
};
return{
appErrorPrefix: '[ABS Error] ', //Configure the exceptionHandler decorator
docTitle: 'Identity',
apiUrl: apiUrl,
getOAuthConfig: getOAuthConfig,
api: api,
version: '0.1'
}
}])
})();<file_sep>using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Configuration;
using PLM.CmsService.Data;
namespace CmsService.API.Controllers
{
public class ValuesController : BaseController
{
public ValuesController(IConfiguration config, IRepository<CMSContent> repo) : base(config, repo)
{
}
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
//MongoConnection con = new MongoConnection(config);
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
<file_sep># plm-poc
POC for PLM - basic framework with latest development in community
Test description will go here
<file_sep>(function() {
'use strict';
angular
.module('PLM.Controllers.Authorization',[])
.controller('AuthorizeController', AuthorizeController);
AuthorizeController.$inject = [
"$log",
"$scope",
"AuthService"];
function AuthorizeController($log,$scope,authService) {
$log.info("AuthorizeController called");
$scope.message = "redirecting to signle sign on";
authService.authorize();
}
})();
<file_sep>using MongoDB.Driver;
using Microsoft.Extensions.Configuration;
namespace PLM.CmsService.Data
{
public class MongoConnection : IDbConnection
{
IConfiguration config;
public MongoConnection(IConfiguration config)
{
this.config = config;
}
public IMongoDatabase Connect
{
get
{
string connectionString = config["AppSettings:mongoDbConnection"];
string dbName = config["AppSettings:databaseName"];
var client = new MongoClient(connectionString);
var database = client.GetDatabase(dbName);
return database;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
using IdentityServer4;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using Microsoft.Extensions.PlatformAbstractions;
using IdentityServer4.Core.Validation;
using IdentityServer4.Core.Configuration;
using PLM.Authorization.UI.Login;
using PLM.Authorization.UI;
using Microsoft.Extensions.Logging;
namespace PLM.Authorization
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) {
var policy = new Microsoft.AspNet.Cors.Infrastructure.CorsPolicy();
services.AddCors();
policy.Headers.Add("*");
policy.Methods.Add("*");
policy.Origins.Add("*");
policy.SupportsCredentials = true;
services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));
var inMemoryManager = new InMemoryManager();
var builder = services.AddIdentityServer(options =>
{
options.SigningCertificate = Certificate.Get();
options.Endpoints.EnableEndSessionEndpoint = true;
options.AuthenticationOptions = new AuthenticationOptions
{
EnableSignOutPrompt = false
};
});
builder.AddInMemoryClients(inMemoryManager.GetClients());
builder.AddInMemoryScopes(inMemoryManager.GetScopes());
builder.AddInMemoryUsers(inMemoryManager.GetUsers());
// for the UI
services
.AddMvc()
.AddRazorOptions(razor =>
{
razor.ViewLocationExpanders.Add(new CustomViewLocationExpander());
});
services.AddTransient<LoginService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseCors("corsGlobalPolicy");
loggerFactory.AddConsole(LogLevel.Verbose);
loggerFactory.AddDebug(LogLevel.Verbose);
app.UseDeveloperExceptionPage();
app.UseIISPlatformHandler(); // ToDo: Do we really need this now or in future?
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
//app.Run(async (context) =>
//{
// await context.Response.WriteAsync("PM Authorization services are up and running.");
//});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
| d2a6a955e4cb68589fa34b697d09cb8485365774 | [
"JavaScript",
"C#",
"Markdown"
] | 16 | C# | akajains/plm-poc | 0af98e00b4efb745b6d475c7a39763930fd9195b | 27fda190f66670cfe4e3ca6633a461f63aee5e80 |
refs/heads/master | <repo_name>anuloo/crud-react-redux-app<file_sep>/app/components/Home.js
import React from 'react';
import Navbar from './Navbar';
const Home = React.createClass({
render() {
return (
<div className="container-fluid">
<div className="page-header">
<h2>React Redux Contacts</h2>
</div>
<Navbar />
{React.cloneElement({...this.props}.children, {...this.props})}
</div>
)
}
});
export default Home;<file_sep>/app/components/ContactsList.js
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
class ContactsList extends Component {
constructor(props){
super(props)
}
static contextTypes = {
router: PropTypes.object
};
componentWillMount() {
this.props.fetchContacts();
this.props.resetAllState();
}
handleViewClick(id, e){
this.context.router.push(`/contacts/view/${id}`);
}
handleDeleteClick(id, e){
this.props.deleteContact(id);
this.props.fetchContacts();
}
handleEditClick(id, e){
this.context.router.push(`/contacts/addedit/${id}`);
}
renderContacts(contacts) {
return contacts.map((contact) => {
return (
<li className="list-group-item" key={contact.id}>
<div className="row">
<div className="col-xs-3 col-sm-2"><h6>{contact.firstName}</h6></div>
<div className="col-xs-3 col-sm-1"><button onClick={this.handleViewClick.bind(this, contact.id)} type="button" className="btn btn-primary">View</button></div>
<div className="col-xs-3 col-sm-1"><button onClick={this.handleEditClick.bind(this, contact.id)} type="button" className="btn btn-warning">Edit</button></div>
<div className="col-xs-3 col-sm-8"><button onClick={this.handleDeleteClick.bind(this, contact.id)} type="button" className="btn btn-danger">Delete</button></div>
</div>
</li>
);
});
}
render() {
const { contacts, loading, error } = this.props.contacts;
if(loading) {
return <div className="container"><h1>Posts</h1><h3>Loading...</h3></div>
} else if(error) {
return <div className="alert alert-danger">Error: {error.message}</div>
}
return (
<div className="container-fluid">
<div className="subheader">
<h3>Contacts</h3>
<span className="pull-right"><Link to="/contacts/addedit">Add new</Link></span>
</div>
<ul className="list-group clear-fix">
{this.renderContacts(contacts)}
</ul>
</div>
);
}
}
export default ContactsList;<file_sep>/app/store.js
import {createStore, applyMiddleware, compose} from 'redux';
import rootReducer from './reducers'
import thunk from 'redux-thunk';
import promise from 'redux-promise';
import {createLogger} from 'redux-logger';
const composeEnhancers = window.devToolsExtension ? window.devToolsExtension() : f => f
const middleWare = applyMiddleware(createLogger(), thunk, promise);
export default function configureStore() {
return createStore(
rootReducer,
compose(
middleWare,
composeEnhancers
)
);
}<file_sep>/app/containers/ViewContactContainer.js
import { connect } from 'react-redux';
import ViewContact from '../components/ViewContact';
/*import { fetchContact, fetchContactFulfilled, fetchContactRejected } from '../actions/actionCreators'
function mapStateToProps(state, ownProps) {
console.log('----mapStateToProps'+ ownProps.params.id);
return {
contact: state.contacts.selectedContact,
id: ownProps.params.id
}
}*/
/*const mapDispatchToProps = (dispatch) => {
return {
fetchContact: (id) => {
dispatch(fetchContact(id)).then((response) => {
!response.error ? dispatch(fetchContactFulfilled(response.payload.data)) : dispatch(fetchContactRejected(response.payload.data));
});
}
}
}*/
const ViewContactContainer = connect()(ViewContact);
export default ViewContactContainer;<file_sep>/app/components/App.js
import { connect } from 'react-redux';
import Home from './Home';
import { fetchContacts, fetchContactsFulfilled, fetchContactsRejected, fetchContactsReset,
deleteContact, deleteContactFulfilled, deleteContactRejected, deleteContactReset,
fetchContact, fetchContactFulfilled, fetchContactRejected, fetchContactReset,
updateContact, updateContactFulfilled, updateContactRejected, updateContactReset} from '../actions/actionCreators'
function mapStateToProps(state, ownProps) {
return {
contacts: state.contacts.contactsList,
selectedContact: state.contacts.selectedContact,
id: ownProps.params.id,
deletedContact: state.contacts.deletedContact,
updatedContact: state.contacts.updatedContact
}
}
const mapDispatchToProps = (dispatch) => {
return {
fetchContacts: () => {
dispatch(fetchContacts()).then((response) => {
!response.error ? dispatch(fetchContactsFulfilled(response.payload.data)) : dispatch(fetchContactsRejected(response.payload));
});
},
deleteContact: (id) => {
dispatch(deleteContact(id)).then((response) => {
!response.error ? dispatch(deleteContactFulfilled(response.payload.data)) : dispatch(deleteContactRejected(response.payload));
});
},
fetchContact: (id) => {
dispatch(fetchContact(id)).then((response) => {
!response.error ? dispatch(fetchContactFulfilled(response.payload.data)) : dispatch(fetchContactRejected(response.payload.data));
});
},
updateContact: (id, props) => {
dispatch(updateContact(id, props)).then((response) => {
!response.error ? dispatch(updateContactFulfilled(response.payload.data)) : dispatch(updateContactRejected(response.payload.data));
});
},
resetAllState: () => {
dispatch(updateContactReset());
dispatch(deleteContactReset());
dispatch(fetchContactReset());
},
fetchContactsReset: () => {
dispatch(fetchContactsReset())
}
}
}
const App = connect(mapStateToProps, mapDispatchToProps)(Home);
export default App;<file_sep>/app/actions/actionCreators.js
import axios from "axios";
//Contacts list
export const FETCH_CONTACTS = 'FETCH_CONTACTS';
export const FETCH_CONTACTS_SUCCESS = 'FETCH_CONTACTS_SUCCESS';
export const FETCH_CONTACTS_FAILED = 'FETCH_CONTACTS_FAILED';
export const FETCH_CONTACTS_RESET = 'FETCH_CONTACTS_RESET';
//Single contact
export const FETCH_CONTACT = 'FETCH_CONTACT';
export const FETCH_CONTACT_SUCCESS = 'FETCH_CONTACT_SUCCESS';
export const FETCH_CONTACT_FAILED = 'FETCH_CONTACT_FAILED';
export const FETCH_CONTACT_RESET = 'FETCH_CONTACT_RESET';
//Add new contact
export const ADD_CONTACT = 'ADD_CONTACT';
export const ADD_CONTACT_SUCCESS = 'ADD_CONTACT_SUCCESS';
export const ADD_CONTACT_FAILED = 'ADD_CONTACT_FAILED';
export const ADD_CONTACT_RESET = 'ADD_CONTACT_RESET';
//Delete a contact
export const DELETE_CONTACT = 'DELETE_CONTACT';
export const DELETE_CONTACT_SUCCESS = 'DELETE_CONTACT_SUCCESS';
export const DELETE_CONTACT_FAILED = 'DELETE_CONTACT_FAILED';
export const DELETE_CONTACT_RESET = 'DELETE_CONTACT_RESET';
//Update a contact
export const UPDATE_CONTACT = 'UPDATE_CONTACT';
export const UPDATE_CONTACT_SUCCESS = 'UPDATE_CONTACT_SUCCESS';
export const UPDATE_CONTACT_FAILED = 'UPDATE_CONTACT_FAILED';
export const UPDATE_CONTACT_RESET = 'UPDATE_CONTACT_RESET';
const API_URL = 'http://rest.learncode.academy/api/anuloo/contacts';
//list -----------------------------
// fetch the full list of contacts
export function fetchContacts() {
const request = axios.get(API_URL);
return {
type: FETCH_CONTACTS,
payload: request
};
}
// return the list
export function fetchContactsFulfilled(contacts) {
return {
type: FETCH_CONTACTS_SUCCESS,
payload: contacts
};
}
// handle error
export function fetchContactsRejected(error) {
return {
type: FETCH_CONTACTS_FAILED,
payload: error
};
}
// reset
export function fetchContactsReset() {
return {
type: FETCH_CONTACTS_RESET,
};
}
//Single contact ----------------------------
// fetch a contacts
export function fetchContact(id) {
const request = axios.get(API_URL+"/"+id);
return {
type: FETCH_CONTACT,
payload: request
};
}
// return a contact
export function fetchContactFulfilled(selectedContact) {
return {
type: FETCH_CONTACT_SUCCESS,
payload: selectedContact
};
}
// handle error
export function fetchContactRejected(error) {
return {
type: FETCH_CONTACT_FAILED,
payload: error
};
}
// reset
export function fetchContactReset() {
return {
type: FETCH_CONTACT_RESET,
};
}
//Add new contact ----------------------------
// start adding a contact
export function addContact(props) {
const request = axios({
method :'post',
data: props,
url: API_URL
});
return {
type: ADD_CONTACT,
payload: request
};
}
// return the newly added contact
export function addContactFulfilled(newContact) {
return {
type: ADD_CONTACT_SUCCESS,
payload: newContact
};
}
// handle error
export function addContactRejected(error) {
return {
type: ADD_CONTACT_FAILED,
payload: error
};
}
// reset
export function addContactReset() {
return {
type: ADD_CONTACT_RESET,
};
}
//Delete a contact ----------------------------
export function deleteContact(id) {
const request = axios.delete(API_URL+"/"+id);
return {
type: DELETE_CONTACT,
payload: request
};
}
// return a contact
export function deleteContactFulfilled(deletedContact) {
return {
type: DELETE_CONTACT_SUCCESS,
payload: deletedContact
};
}
// handle error
export function deleteContactRejected(error) {
return {
type: DELETE_CONTACT_FAILED,
payload: error
};
}
// reset
export function deleteContactReset() {
return {
type: DELETE_CONTACT_RESET,
};
}
//Update selected contact ----------------------------
// update contact
export function updateContact(id, props) {
const request = axios({
method :'put',
data: props,
url: API_URL+"/"+id
});
return {
type: UPDATE_CONTACT,
payload: request
};
}
// return updated contact
export function updateContactFulfilled(updatedContact) {
return {
type: UPDATE_CONTACT_SUCCESS,
payload: updatedContact
};
}
// handle error
export function updateContactRejected(error) {
return {
type: UPDATE_CONTACT_FAILED,
payload: error
};
}
// reset
export function updateContactReset() {
return {
type: UPDATE_CONTACT_RESET,
};
}
<file_sep>/README.md
# crud-react-redux-app
My first experiment with react and redux for a test project
<file_sep>/app/main.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { syncHistoryWithStore} from 'react-router-redux';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import configureStore from './store';
import App from "./components/App";
import ContactsList from "./components/ContactsList";
import ViewContactContainer from "./containers/ViewContactContainer";
import FormContactContainer from "./containers/FormContactContainer";
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={ContactsList}></IndexRoute>
<Route path="/contacts/view/:id" component={ViewContactContainer}></Route>
<Route path="/contacts/addedit" component={FormContactContainer}></Route>
<Route path="/contacts/addedit/:id" component={FormContactContainer}></Route>
</Route>
</Router>
</Provider>
, document.body.appendChild(document.createElement('div'))
);<file_sep>/app/reducers/contacts.js
import {FETCH_CONTACTS, FETCH_CONTACTS_SUCCESS, FETCH_CONTACTS_FAILED, FETCH_CONTACTS_RESET,
FETCH_CONTACT, FETCH_CONTACT_SUCCESS, FETCH_CONTACT_FAILED, FETCH_CONTACT_RESET,
ADD_CONTACT, ADD_CONTACT_SUCCESS, ADD_CONTACT_FAILED, ADD_CONTACT_RESET,
DELETE_CONTACT, DELETE_CONTACT_SUCCESS, DELETE_CONTACT_FAILED, DELETE_CONTACT_RESET,
UPDATE_CONTACT, UPDATE_CONTACT_SUCCESS, UPDATE_CONTACT_FAILED, UPDATE_CONTACT_RESET} from '../actions/actionCreators';
const INITIAL_STATE = { contactsList: {contacts: [], error:null, loading: false},
newContact:{contact:null, error: null, loading: false},
selectedContact:{contact:null, error:null, loading: false},
deletedContact: {contact:null, error:null, loading: false},
updatedContact: {contact:null, error:null, loading: false}
};
function contacts(state = INITIAL_STATE, action) {
switch(action.type) {
case FETCH_CONTACTS: // start fetching contacts set the loading = true
return {...state, contactsList: {contacts:[], error: null, loading: true}};
case FETCH_CONTACTS_SUCCESS: // return the contacts list set the loading = false
return {...state, contactsList: {contacts:action.payload, error: null, loading: false}};
case FETCH_CONTACTS_FAILED: // return an error the loading = false
return {...state, contactsList: {contacts:[], error: null, loading: false}};
case FETCH_CONTACTS_RESET: // reset everything
return {...state, contactsList: {contacts:[], error: null, loading: false}};
case FETCH_CONTACT: // start fetching a contact set the loading = true
return {...state, selectedContact: {...state.contact, error: null, loading: true}};
case FETCH_CONTACT_SUCCESS: // return a contacts set the loading = false
return {...state, selectedContact: {contact:action.payload, error: null, loading: false}};
case FETCH_CONTACT_FAILED: // return an error the loading = false
return {...state, selectedContact: {contact:null, error: null, loading: false}};
case FETCH_CONTACT_RESET: // reset everything
return {...state, selectedContact: {contact:null, error: null, loading: false}};
case ADD_CONTACT: // start fetching a contact set the loading = true
return {...state, newContact: {...state.contact, error: null, loading: true}};
case ADD_CONTACT_SUCCESS: // return a contacts set the loading = false
return {...state, newContact: {contact:action.payload, error: null, loading: false}};
case ADD_CONTACT_FAILED: // return an error the loading = false
return {...state, newContact: {contact:null, error: null, loading: false}};
case ADD_CONTACT_RESET: // reset everything
return {...state, newContact: {contact:null, error: null, loading: false}};
case DELETE_CONTACT: // start deleting a contact set the loading = true
return {...state, deletedContact: {...state.contact, error: null, loading: true}};
case DELETE_CONTACT_SUCCESS: // return the deleted contact set the loading = false
return {...state, deletedContact: {contact:action.payload, error: null, loading: false}};
case DELETE_CONTACT_FAILED: // return an error the loading = false
return {...state, deletedContact: {contact:null, error: null, loading: false}};
case DELETE_CONTACT_RESET: // reset everything
return {...state, deletedContact: {contact:null, error: null, loading: false}};
case UPDATE_CONTACT: // start updating contact set the loading = true
return {...state, updatedContact: {contact:null, error: null, loading: true}};
case UPDATE_CONTACT_SUCCESS: // loading = false
return {...state, updatedContact: {contact:action.payload, error: null, loading: false}};
case UPDATE_CONTACT_FAILED: // return an error the loading = false
return {...state, updatedContact: {contact:null, error: null, loading: false}};
case UPDATE_CONTACT_RESET: // reset everything
return {...state, updatedContact: {contact:null, error: null, loading: false}};
default:
return state;
}
}
export default contacts;<file_sep>/app/components/FormContact.js
import React, { Component, PropTypes } from 'react';
class FormContact extends Component{
constructor(props){
super(props);
this.updateFlag = false;
this.handleSubmit = this.handleSubmit.bind(this);
}
static contextTypes = {
router: PropTypes.object
};
componentDidMount() {
if(this.props.id){
this.props.fetchContact(this.props.id);
}
}
componentWillMount(){
this.props.fetchContactsReset();
}
componentWillReceiveProps(nextProps) {
if(this.updateFlag){
this.context.router.push('/');
this.updateFlag = false;
}
}
handleSubmit(e) {
e.preventDefault();
if (this.firstname.value || !this.firstname.value.trim() === '') {
let newContact = {};
newContact.firstName = this.firstname.value;
newContact.lastName = this.lastname.value;
newContact.email = this.email.value;
if(this.props.id){
this.props.updateContact(this.props.id, newContact);
}else{
this.props.addContact(newContact);
}
this.updateFlag = true;
this.contactForm.reset();
}
}
handleCancelClick(e) {
e.preventDefault();
this.context.router.push('/');
}
render() {
const { contact, loading, error ,updated} = this.props.selectedContact;
if (loading && this.props.id) {
return <div className="container">Loading...</div>;
} else if(error) {
return <div className="alert alert-danger">{error.message}</div>
} else if(!contact && this.props.id) {
return <span />
}
return (
<div className="container-fluid">
<div className="panel panel-primary">
<div className="panel-heading"><h4>{this.props.id?'Edit contact':'Add new contact'}</h4></div>
<div className="panel-body">
<form ref={(form) => this.contactForm = form} className="contact-form form-horizontal" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="inputFirstname" className="col-sm-2 control-label">First name</label>
<div className="col-sm-10">
<input type="text" defaultValue={this.props.id?contact.firstName:''} className="form-control" id="inputFirstname" ref={(input) => this.firstname = input} placeholder="First name"/>
</div>
</div>
<div className="form-group">
<label htmlFor="inputLastname" className="col-sm-2 control-label">Last name</label>
<div className="col-sm-10">
<input type="text" defaultValue={this.props.id?contact.lastName:''} className="form-control" id="inputLastname" ref={(input) => this.lastname = input} placeholder="Last name"/>
</div>
</div>
<div className="form-group">
<label htmlFor="inputEmail" className="col-sm-2 control-label">Email</label>
<div className="col-sm-10">
<input type="email" defaultValue={this.props.id?contact.email:''} className="form-control" id="inputEmail" ref={(input) => this.email = input} placeholder="Email"/>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button type="submit" value="submit" className="btn btn-primary">Submit</button>
<button onClick={this.handleCancelClick.bind(this)} type="button" className="btn btn-warning">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
);
}
}
export default FormContact;<file_sep>/__tests__/reducers/contacts.react-test.js
import request from '../../app/reducers/contacts';
const INITIAL_STATE = { contactsList: {contacts: [], error:null, loading: true},
newContact:{contact:null, error: null, loading: false},
selectedContact:{contact:null, error:null, loading: false},
deletedContact: {contact:null, error:null, loading: false},
updatedContact: {contact:null, error:null, loading: false}
};
describe('Contacts Reducer', () => {
it('has default state', () => {
expect(request(undefined, {type: 'unexpected'}))
.toEqual({
INITIAL_STATE
});
});
it('can handle FETCH_CONTACTS', () => {
expect(request(undefined, {
type: 'FETCH_CONTACTS',
}))
.toEqual(INITIAL_STATE);
});
}); | 43cf2d1cc4736443ae6410397464223480bb7fcb | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | anuloo/crud-react-redux-app | f4e76951be2fcc9e11d026513a71805ba3d7bafc | f3acef321911247e4bba30396ab4fc005fc7570b |
refs/heads/master | <file_sep>import { Injectable } from '@angular/core';
import {HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class InformationsMondialesService {
private key = '&apiKey=cb61f5e046d7449dadec5c4c58e1c981';
private country = 'fr';
private url = 'https://newsapi.org/v2/top-headlines?country=';
currently: any;
constructor(private http: HttpClient) {
}
gettingData() {
return this.http.get(this.url + this.country + this.key);
}
}
<file_sep>import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CulturellesPage } from './culturelles.page';
describe('CulturellesPage', () => {
let component: CulturellesPage;
let fixture: ComponentFixture<CulturellesPage>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CulturellesPage ],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CulturellesPage);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-culturelle',
templateUrl: './culturelle.page.html',
styleUrls: ['./culturelle.page.scss'],
})
export class CulturellePage implements OnInit {
constructor() { }
ngOnInit() {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-list',
templateUrl: 'list.page.html',
styleUrls: ['list.page.scss']
})
export class ListPage implements OnInit {
private selectedItem: any;
private icons = [
'wifi',
'basketball',
'paper-plane',
'boat'
];
private activities = [
'Le monde',
'La finance',
'La culture',
'le sport'
];
private descriptions = [
'',
'',
'',
''
];
public items: Array<{ title: string; note: string; icon: string }> = [];
constructor(private router: Router) {
for (let i = 0; i < 4; i++) {
this.items.push({
title: this.activities[i],
note: this.descriptions[i],
icon: this.icons[i]
});
}
}
ngOnInit() {
}
// add back when alpha.4 is out
// navigate(item) {
// this.router.navigate(['/list', JSON.stringify(item)]);
// }
voirInformation(conserned) {
if(conserned== 'Le monde'){
this.router.navigate(['mondiales']);
}
else
if(conserned == 'La finance'){
this.router.navigate(['financieres']);
}
else
if(conserned== 'La culture'){
this.router.navigate(['culturelles']);
}
}
}
<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
images=["1.jpg","2.jpg","3.jpg","4.jpg","lipson.jpg"];
constructor() { }
ngOnInit() {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { InformationsFinancieresService } from '../informations-financieres.service';
@Component({
selector: 'app-financieres',
templateUrl: './financieres.page.html',
styleUrls: ['./financieres.page.scss'],
})
export class FinancieresPage implements OnInit {
donnees: any;
constructor(private service: InformationsFinancieresService) { }
ngOnInit() {
this.service.gettingData().subscribe(
data => {
this.donnees = data;
console.log(data);
}
);
}
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { InformationsFinancieresService } from './informations-financieres.service';
describe('InformationsFinancieresService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: InformationsFinancieresService = TestBed.get(InformationsFinancieresService);
expect(service).toBeTruthy();
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-financiere',
templateUrl: './financiere.page.html',
styleUrls: ['./financiere.page.scss'],
})
export class FinancierePage implements OnInit {
constructor( ) { }
ngOnInit() {
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class InformationsFinancieresService {
private key = '';
private url = 'https://api.coindesk.com/v1/bpi/historical/close.json';
currently: any;
constructor(private http: HttpClient) { }
gettingData() {
return this.http.get(this.url + this.key);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { InformationsMondialesService } from '../informations-mondiales.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-mondiales',
templateUrl: './mondiales.page.html',
styleUrls: ['./mondiales.page.scss'],
})
export class MondialesPage implements OnInit {
donnees: any;
constructor(private info: InformationsMondialesService, private router: Router) { }
ngOnInit() {
this.info.gettingData().subscribe(
data => {
this.donnees = data;
}
);
}
description(article) {
this.info.currently = article;
this.router.navigate(['mondiale']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { InformationsMondialesService } from '../informations-mondiales.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-mondiale',
templateUrl: './mondiale.page.html',
styleUrls: ['./mondiale.page.scss'],
})
export class MondialePage implements OnInit {
article: any;
constructor(private service: InformationsMondialesService, private router: Router) { }
ngOnInit() {
this.article = this.service.currently;
}
retourner(){
this.router.navigate(['mondiales']);
}
}
<file_sep>import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MondialePage } from './mondiale.page';
describe('MondialePage', () => {
let component: MondialePage;
let fixture: ComponentFixture<MondialePage>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MondialePage ],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MondialePage);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Injectable } from '@angular/core';
import {HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class InformationsCulturellesService {
currently: any;
private key = '';
private url = '';
constructor(private port: HttpClient) { }
gettingData() {
return this.port.get('');
}
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { InformationsMondialesService } from './informations-mondiales.service';
describe('InformationsMondialesService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: InformationsMondialesService = TestBed.get(InformationsMondialesService);
expect(service).toBeTruthy();
});
});
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
loadChildren: './home/home.module#HomePageModule'
},
{
path: 'list',
loadChildren: './list/list.module#ListPageModule'
},
{ path: 'mondiales', loadChildren: './mondiales/mondiales.module#MondialesPageModule' },
{ path: 'mondiale', loadChildren: './mondiale/mondiale.module#MondialePageModule' },
{ path: 'financieres', loadChildren: './financieres/financieres.module#FinancieresPageModule' },
{ path: 'financiere', loadChildren: './financiere/financiere.module#FinancierePageModule' },
{ path: 'culturelles', loadChildren: './culturelles/culturelles.module#CulturellesPageModule' },
{ path: 'culturelle', loadChildren: './culturelle/culturelle.module#CulturellePageModule' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
| 0c45eb14badcc9beb262e2cf249473658851bc4d | [
"TypeScript"
] | 15 | TypeScript | isoume/information | 21569a715b9142bdd041b7e8eea74377253914d0 | de87725652c5fb22b2a6e561dce59243ab28471c |
refs/heads/master | <repo_name>haoSeven/copy_requests<file_sep>/requests/main.py
# -*- coding: utf-8 -*-
"""
学习requests
"""
import urllib
import urllib2
AUTOAUTHS = []
class _Request(urllib2.Request):
def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None):
urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)
self.method = method
def get_method(self):
if self.method:
return self.method
return urllib2.Request.get_method(self)
class Request(object):
_METHODS = ('GET', 'PUT', 'DELETE', 'HEAD', 'POST')
def __init__(self):
self.url = None
self.headers = dict()
self.method = None
self.params = dict()
self.data = dict()
self.response = Response()
self.auth = None
self.sent = False
def __repr__(self):
try:
repr = '<Response [%s]>' % self.method
except:
repr = '<Response object>'
return repr
def __setattr__(self, name, value):
if name == 'method' and value:
if value not in self._METHODS:
raise InvalidMethod()
object.__setattr__(self, name, value)
def _checks(self):
if not self.url:
raise UrlRequired
def _get_opener(self):
"""为urllib2创建适当的开启对象"""
if self.auth:
author = urllib2.HTTPPasswordMgrWithDefaultRealm()
author.add_password(None, self.url, self.auth.username, self.auth.password)
handler = urllib2.HTTPBasicAuthHandler(author)
opener = urllib2.build_opener(handler)
return opener.open
else:
return urllib2.urlopen
def send(self, anyway=False):
"""发送请求 返回True的successfull,如果不是,则返回false。
如果传输过程中出现HTTPError,
self.response.status_code将包含HTTPError代码。
一旦请求成功发送,`sent`将等于True。
:param anyway:如果为True,请求将被发送,即使它
已经发送
"""
self._checks()
success = False
if self.method in ('GET', 'HEAD', 'DELETE'):
if (not self.sent) or anyway:
# url encode GET params if it's a dict
if isinstance(self.params, dict):
params = urllib.urlencode(self.params)
else:
params = self.params
req = _Request(("%s?%s" % (self.url, params)), method=self.method)
if self.headers:
req.headers = self.headers
opener = self._get_opener()
try:
resp = opener(req)
self.response.status_code = resp.code
self.response.headers = resp.info().dict
if self.method.lower() == 'get':
self.response.content = resp.read()
success = True
except urllib2.HTTPError as why:
self.response.status_code = why.code
elif self.method == 'POST':
if (not self.sent) or anyway:
req = _Request(self.url, method='POST')
if self.headers:
req.headers = self.headers
if isinstance(self.data, dict):
req.data = urllib.urlencode(self.data)
else:
req.data = self.data
try:
opener = self._get_opener()
resp = opener(req)
self.response.status_code = resp.code
self.response.headers = resp.info().dict
self.response.content = resp.read()
success = True
except urllib2.HTTPError as why:
self.response.status_code = why.code
self.sent = True if success else False
return success
class Response(object):
def __init__(self):
self.content = None
self.status_code = None
self.headers = dict()
def __repr__(self):
try:
repr = '<Response [%s]>' % self.status_code
except:
repr = '<Response object>'
return repr
def get(url, params={}, headers={}, auth=None):
"""
发送GET请求, 返回Response 对象
:param url:
:param params:(可选)GET字符串要发送的参数:class:`Request`。
:param headers:
:param auth:(可选)AuthObject启用基本HTTP验证
:return:返回Response 对象
"""
r = Request()
r.method = 'GET'
r.url = url
r.params = params
r.headers = headers
r.auth = _detect_auth(url, auth)
r.send()
return r.response
def post(url, params={}, headers={}, auth=None):
r = Request()
r.url = url
r.params = params
r.headers = headers
r.auth = _detect_auth(url, auth)
r.send()
return r.response
def _detect_auth(url, auth):
"""返回给定URL的注册AuthObject(如果可用),默认为给定的AuthObject。"""
return _get_autoauth(url) if not auth else auth
def _get_autoauth(url):
for autoauth_url, auth in AUTOAUTHS:
if autoauth_url in url:
return auth
return None
class RequestException(Exception):
"""处理您的请求时发生了一个模糊异常。"""
class UrlRequired(RequestException):
"""需要一个有效的URL才能发出请求"""
class InvalidMethod(RequestException):
"""尝试了不适当的方法。"""
| 4a47ae38498194aa37986043f4c355d2d410b28c | [
"Python"
] | 1 | Python | haoSeven/copy_requests | 35b3130e3405730dbbcc8094fe198051717715ba | 19ac8f00764196f774274710b3732410e0b81bac |
refs/heads/master | <repo_name>alenad/killbill-paypal-express-plugin<file_sep>/spec/paypal_express/base_plugin_spec.rb
require 'spec_helper'
describe Killbill::PaypalExpress::PaymentPlugin do
include ::Killbill::Plugin::ActiveMerchant::RSpec
before(:each) do
Dir.mktmpdir do |dir|
file = File.new(File.join(dir, 'paypal_express.yml'), 'w+')
file.write(<<-eos)
:paypal_express:
:signature: 'signature'
:login: 'login'
:password: '<PASSWORD>'
:test: true
# As defined by spec_helper.rb
:database:
:adapter: 'sqlite3'
:database: 'test.db'
eos
file.close
@plugin = build_plugin(::Killbill::PaypalExpress::PaymentPlugin, 'paypal_express', File.dirname(file))
# Start the plugin here - since the config file will be deleted
@plugin.start_plugin
end
end
it 'should start and stop correctly' do
@plugin.stop_plugin
end
it 'should receive notifications correctly' do
description = 'description'
kb_tenant_id = SecureRandom.uuid
context = @plugin.kb_apis.create_context(kb_tenant_id)
properties = @plugin.hash_to_properties({ :description => description })
notification = ''
gw_notification = @plugin.process_notification notification, properties, context
end
it 'should correctly add and filter optional parameters' do
# Basic option test
options = { :amount => 9900,
:some_property => true}
amount = 99.99
amount_in_cents = 9999
property_hash = { :noShipping => true,
:max_amount => amount
}
@plugin.send(:add_optional_parameters, options, property_hash, 'USD')
expected_options = { :amount => 9900,
:some_property => true,
:no_shipping => true,
:max_amount => amount_in_cents
}
options.should == expected_options
# Test with correct option format and unwanted property, e.g., fakeKey and unlimited
options = { :amount => 9900,
:some_property => true}
amount = 99.99
amount_in_cents = 9999
property_hash = { :noShipping => true,
:max_amount => amount,
:subtotal => amount,
:shipping => amount,
:handling => amount,
:tax => amount,
:fakeKey => 'unlimited',
:insuranceTotal => amount,
:shipping_discount => amount,
:shipping_options => [{:default => false, :name => 'jack', :amount => amount, :unlimited => true}].to_json,
:items => [{:name => 'john', :number => 111, :quantity => 12, :amount => amount, :description => 'jacket', :url => 'test', :category => 'unknown', :unlimited => true}].to_json,
:shipping_address => {:name => 'john', :address1 => '111', :address2 => '12', :city => 'palo alto', :state => 'ca', :country => 'jacket', :phone => 'test', :zip => 'unknown', :family => 'unknown'}.to_json,
:address => {:name => 'john', :address1 => '111', :address2 => '12', :city => 'palo alto', :state => 'ca', :country => 'jacket', :phone => 'test', :zip => 'unknown', :family => 'unknown'}.to_json,
:funding_sources => {:source => 'unknown'}.to_json
}
@plugin.send(:add_optional_parameters, options, property_hash, 'USD')
expected_options = { :amount => 9900,
:some_property => true,
:no_shipping => true,
:max_amount => amount_in_cents,
:subtotal => amount_in_cents,
:shipping => amount_in_cents,
:handling => amount_in_cents,
:tax => amount_in_cents,
:insurance_total => amount_in_cents,
:shipping_discount => amount_in_cents,
:shipping_options => [{:default => false, :name => 'jack', :amount => amount_in_cents}],
:items => [{:name => 'john', :number => 111, :quantity => 12, :amount => amount_in_cents, :description => 'jacket', :url => 'test', :category => 'unknown'}],
:shipping_address => {:name => 'john', :address1 => '111', :address2 => '12', :state => 'ca', :city => 'palo alto', :country => 'jacket', :phone => 'test', :zip => 'unknown'},
:address => {:name => 'john', :address1 => '111', :address2 => '12', :state => 'ca', :city => 'palo alto', :country => 'jacket', :phone => 'test', :zip => 'unknown'},
:funding_sources => {:source => 'unknown'}
}
options.should == expected_options
# Test with incorrect option format and invalid json format
options = {}
property_hash = { :no_shipping => true,
:max_amount => amount,
:subtotal => amount,
:shipping => amount,
:handling => amount,
:tax => amount,
:fakeKey => 'unlimited',
:insurance_total => amount,
:shipping_discount => amount,
:shipping_options => "{\"default\":\"false\", [name]:\"jack\", \"amount\":12}",
:items => {:name => 'john', :number => 111, :quantity => 12, :amount => amount, :description => 'jacket', :url => 'test', :category => 'unknown', :unlimited => true}.to_json,
:shipping_address => [{:name => 'john', :address1 => '111', :address2 => '12', :city => 'amount', :country => 'jacket', :phone => 'test', :zip => 'unknown'}].to_json,
:address => [{:name => 'john', :address1 => '111', :address2 => '12', :city => 'amount', :country => 'jacket', :phone => 'test', :zip => 'unknown'}].to_json
}
@plugin.send(:add_optional_parameters, options, property_hash, 'USD')
expected_options = { :no_shipping => true,
:max_amount => amount_in_cents,
:subtotal => amount_in_cents,
:shipping => amount_in_cents,
:handling => amount_in_cents,
:tax => amount_in_cents,
:insurance_total => amount_in_cents,
:shipping_discount => amount_in_cents,
:items => nil,
:shipping_options => nil,
:shipping_address => nil,
:address => nil
}
options.should == expected_options
end
end
<file_sep>/spec/paypal_express/remote/browser_helpers.rb
require 'selenium-webdriver'
module Killbill
module PaypalExpress
module BrowserHelpers
def login_and_confirm(url)
if ENV['BUYER_USERNAME'].blank? || ENV['BUYER_PASSWORD'].blank?
print "\nPlease go to #{url} to proceed and press any key to continue... Note: you need to log-in with a paypal sandbox account (create one here: https://developer.paypal.com/webapps/developer/applications/accounts)\n"
$stdin.gets
else
driver = Selenium::WebDriver.for :firefox
# Login page
driver.get url
wait = Selenium::WebDriver::Wait.new(:timeout => 15)
wait.until {
driver.switch_to.frame('injectedUl') rescue nil
}
email_element, pwd_element, login_element = wait.until {
email_element = driver.find_element(:id, 'email') rescue nil
pwd_element = driver.find_element(:id, 'password') rescue nil
login_element = driver.find_element(:id, 'btnLogin') rescue nil
if ready?(email_element, pwd_element, login_element)
[email_element, pwd_element, login_element]
else
# Find the element ids from the old UI
old_email_element = driver.find_element(:id, 'login_email') rescue nil
old_pwd_element = driver.find_element(:id, 'login_password') rescue nil
old_login_element = driver.find_element(:id, 'submitLogin') rescue nil
if ready?(old_email_element, old_pwd_element, old_login_element)
[old_email_element, old_pwd_element, old_login_element]
else
false
end
end
}
email_element.send_keys(ENV['BUYER_USERNAME'])
pwd_element.send_keys(ENV['BUYER_PASSWORD'])
login_element.click
# Confirmation page
driver.switch_to.default_content
confirm_element = wait.until {
confirm_element = driver.find_element(:id, 'confirmButtonTop') rescue nil
if ready?(confirm_element)
confirm_element
else
old_confirm_element = driver.find_element(:id, 'continue_abovefold') rescue nil
ready?(old_confirm_element) ? old_confirm_element : false
end
}
# Wait for page to load. Even if it is displayed and enabled, sometimes the element is still not clickable.
sleep 2
confirm_element.click
driver.quit
end
end
private
def ready?(*elements)
elements.each do |element|
return false unless element && element.displayed? && element.enabled?
end
true
end
end
end
end
<file_sep>/spec/paypal_express/response_spec.rb
require 'spec_helper'
require 'nokogiri'
describe Killbill::PaypalExpress::PaypalExpressResponse do
def load_paypal_response(action, suffix)
@spec_root ||= File.expand_path(File.join(File.dirname(__FILE__), ".."))
xml = IO.read(File.join(@spec_root, "fixtures", action + "-" + suffix + ".xml"))
ActiveMerchant::Billing::PaypalGateway.any_instance.stub(:build_request).and_return(nil)
ActiveMerchant::Billing::PaypalGateway.any_instance.stub(:ssl_post).and_return(xml)
api = ActiveMerchant::Billing::PaypalGateway.new(:login => "dummy", :password => "<PASSWORD>", :signature => "dummy")
api.send(:commit, action, nil)
end
it 'should read a successful GetExpressCheckoutDetails response correctly' do
action = "GetExpressCheckoutDetails"
response = ::Killbill::PaypalExpress::PaypalExpressResponse.from_response(
action, # api_call
"account1", # kb_account_id
"payment1", # kb_payment_id
nil, # kb_payment_transaction_id
nil, # transaction_type
"account2", # payment_processor_account_id
"tenant1", # kb_tenant_id
load_paypal_response(action, "success")
)
expect(response.api_call).to eq(action)
expect(response.kb_account_id).to eq("account1")
expect(response.kb_payment_id).to eq("payment1")
expect(response.kb_payment_transaction_id).to be_nil
expect(response.transaction_type).to be_nil
expect(response.payment_processor_account_id).to eq("account2")
expect(response.kb_tenant_id).to eq("tenant1")
# data from the fixture as parsed by PaypalCommonAPI and PaypalExpressResponse
expect(response.message).to eq("Success")
expect(response.authorization).to be_nil
expect(response.fraud_review).to eq(false)
expect(response.success).to eq(true)
expect(response.token).to eq("EC-MY_TOKEN")
expect(response.payer_id).to eq("MY_PAYER_ID")
expect(response.payment_info_reasoncode).to be_nil
expect(response.gateway_error_code).to be_nil
end
it 'should read a DoExpressCheckoutPayment response with an error code correctly' do
action = "DoExpressCheckoutPayment"
response = ::Killbill::PaypalExpress::PaypalExpressResponse.from_response(
action, # api_call
"account1", # kb_account_id
"payment1", # kb_payment_id
"transaction1", # kb_payment_transaction_id
:purchase, # transaction_type
"account2", # payment_processor_account_id
"tenant1", # kb_tenant_id
load_paypal_response(action, "duplicate")
)
expect(response.api_call).to eq(action)
expect(response.kb_account_id).to eq("account1")
expect(response.kb_payment_id).to eq("payment1")
expect(response.kb_payment_transaction_id).to eq("transaction1")
expect(response.transaction_type).to eq(:purchase)
expect(response.payment_processor_account_id).to eq("account2")
expect(response.kb_tenant_id).to eq("tenant1")
# data from the fixture as parsed by PaypalCommonAPI and PaypalExpressResponse
expect(response.message).to eq("A successful transaction has already been completed for this token.")
expect(response.authorization).to eq("<KEY>")
expect(response.fraud_review).to eq(false)
expect(response.success).to eq(false)
expect(response.token).to eq("EC-MY_TOKEN")
expect(response.payer_id).to be_nil
expect(response.payment_info_reasoncode).to eq("11607")
expect(response.gateway_error_code).to eq("11607")
end
end
<file_sep>/lib/paypal_express/models/response.rb
module Killbill #:nodoc:
module PaypalExpress #:nodoc:
class PaypalExpressResponse < ::Killbill::Plugin::ActiveMerchant::ActiveRecord::Response
self.table_name = 'paypal_express_responses'
has_one :paypal_express_transaction
def self.ignore_none(value)
value == 'none' ? nil : value
end
def self.from_response(api_call, kb_account_id, kb_payment_id, kb_payment_transaction_id, transaction_type, payment_processor_account_id, kb_tenant_id, response, extra_params = {}, model = ::Killbill::PaypalExpress::PaypalExpressResponse)
super(api_call,
kb_account_id,
kb_payment_id,
kb_payment_transaction_id,
transaction_type,
payment_processor_account_id,
kb_tenant_id,
response,
{
:token => extract(response, 'Token'),
:payer_id => extract(response, 'PayerInfo', 'PayerID'),
:billing_agreement_id => extract(response, 'billing_agreement_id'),
:payer_name => [extract(response, 'PayerInfo', 'PayerName', 'FirstName'), extract(response, 'PayerInfo', 'PayerName', 'MiddleName'), extract(response, 'PayerInfo', 'PayerName', 'LastName')].compact.join(' '),
:payer_email => extract(response, 'PayerInfo', 'Payer'),
:payer_country => extract(response, 'PayerInfo', 'PayerCountry'),
:contact_phone => extract(response, 'ContactPhone'),
:ship_to_address_name => extract(response, 'ShipToAddress', 'Name'),
:ship_to_address_company => extract(response, 'PayerInfo', 'PayerBusiness'),
:ship_to_address_address1 => extract(response, 'ShipToAddress', 'Street1'),
:ship_to_address_address2 => extract(response, 'ShipToAddress', 'Street2'),
:ship_to_address_city => extract(response, 'ShipToAddress', 'CityName'),
:ship_to_address_state => extract(response, 'ShipToAddress', 'StateOrProvince'),
:ship_to_address_country => extract(response, 'ShipToAddress', 'Country'),
:ship_to_address_zip => extract(response, 'ShipToAddress', 'PostalCode'),
:ship_to_address_phone => (extract(response, 'ContactPhone') || extract(response, 'ShipToAddress', 'Phone')),
:receiver_info_business => (extract(response, 'ReceiverInfo', 'Business') || extract(response, 'PaymentTransactionDetails', 'ReceiverInfo', 'Business')),
:receiver_info_receiver => (extract(response, 'ReceiverInfo', 'Receiver') || extract(response, 'PaymentTransactionDetails', 'ReceiverInfo', 'Receiver')),
:receiver_info_receiverid => (extract(response, 'ReceiverInfo', 'ReceiverID') || extract(response, 'PaymentTransactionDetails', 'ReceiverInfo', 'ReceiverID')),
:payment_info_transactionid => (extract(response, 'PaymentInfo', 'TransactionID') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'TransactionID')),
:payment_info_parenttransactionid => (extract(response, 'PaymentInfo', 'ParentTransactionID') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'ParentTransactionID')),
:payment_info_receiptid => (extract(response, 'PaymentInfo', 'ReceiptID') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'ReceiptID')),
:payment_info_transactiontype => (extract(response, 'PaymentInfo', 'TransactionType') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'TransactionType')),
:payment_info_paymenttype => (extract(response, 'PaymentInfo', 'PaymentType') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'PaymentType')),
:payment_info_paymentdate => (extract(response, 'PaymentInfo', 'PaymentDate') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'PaymentDate')),
:payment_info_grossamount => (extract(response, 'PaymentInfo', 'GrossAmount') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'GrossAmount')),
:payment_info_feeamount => (extract(response, 'PaymentInfo', 'FeeAmount') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'FeeAmount')),
:payment_info_taxamount => (extract(response, 'PaymentInfo', 'TaxAmount') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'TaxAmount')),
:payment_info_exchangerate => (extract(response, 'PaymentInfo', 'ExchangeRate') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'ExchangeRate')),
:payment_info_paymentstatus => (extract(response, 'PaymentInfo', 'PaymentStatus') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'PaymentStatus')),
:payment_info_pendingreason => (extract(response, 'PaymentInfo', 'PendingReason') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'PendingReason')),
:payment_info_reasoncode => (ignore_none(extract(response, 'PaymentInfo', 'ReasonCode')) || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'ReasonCode') || extract(response, 'error_codes')),
:payment_info_protectioneligibility => (extract(response, 'PaymentInfo', 'ProtectionEligibility') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'ProtectionEligibility')),
:payment_info_protectioneligibilitytype => (extract(response, 'PaymentInfo', 'ProtectionEligibilityType') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'ProtectionEligibilityType')),
:payment_info_shipamount => (extract(response, 'PaymentInfo', 'ShipAmount') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'ShipAmount')),
:payment_info_shiphandleamount => (extract(response, 'PaymentInfo', 'ShipHandleAmount') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'ShipHandleAmount')),
:payment_info_shipdiscount => (extract(response, 'PaymentInfo', 'ShipDiscount') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'ShipDiscount')),
:payment_info_insuranceamount => (extract(response, 'PaymentInfo', 'InsuranceAmount') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'InsuranceAmount')),
:payment_info_subject => (extract(response, 'PaymentInfo', 'Subject') || extract(response, 'PaymentTransactionDetails', 'PaymentInfo', 'Subject'))
}.merge!(extra_params),
model)
end
def self.last_token(kb_account_id, kb_tenant_id)
response = where(:api_call => 'initiate_express_checkout',
:success => true,
:kb_account_id => kb_account_id,
:kb_tenant_id => kb_tenant_id).last
response.nil? ? nil : response.token
end
def self.initial_payment_account_processor_id(kb_account_id, kb_tenant_id, token)
return nil if token.blank?
response = where(:api_call => 'initiate_express_checkout',
:success => true,
:kb_account_id => kb_account_id,
:kb_tenant_id => kb_tenant_id,
:token => token).last
response.nil? ? nil : response.payment_processor_account_id
end
def self.cancel_pending_payment(transaction_plugin_info)
where( :api_call => 'build_form_descriptor',
:kb_payment_id => transaction_plugin_info.kb_payment_id,
:kb_payment_transaction_id => transaction_plugin_info.kb_transaction_payment_id).update_all( :success => false,
:updated_at => Time.now.utc,
:message => { :payment_plugin_status => :CANCELED, :exception_message => 'Token expired. Payment Canceled by Janitor.' }.to_json)
end
def gateway_error_code
payment_info_reasoncode
end
def to_transaction_info_plugin(transaction=nil)
t_info_plugin = super(transaction)
t_info_plugin.properties << create_plugin_property('message', token)
t_info_plugin.properties << create_plugin_property('payerId', payer_id)
t_info_plugin.properties << create_plugin_property('baid', billing_agreement_id)
t_info_plugin.properties << create_plugin_property('payerName', payer_name)
t_info_plugin.properties << create_plugin_property('payerEmail', payer_email)
t_info_plugin.properties << create_plugin_property('payerCountry', payer_country)
t_info_plugin.properties << create_plugin_property('contactPhone', contact_phone)
t_info_plugin.properties << create_plugin_property('shipToAddressName', ship_to_address_name)
t_info_plugin.properties << create_plugin_property('shipToAddressPayerBusiness', ship_to_address_company)
t_info_plugin.properties << create_plugin_property('shipToAddressStreet1', ship_to_address_address1)
t_info_plugin.properties << create_plugin_property('shipToAddressStreet2', ship_to_address_address2)
t_info_plugin.properties << create_plugin_property('shipToAddressCityName', ship_to_address_city)
t_info_plugin.properties << create_plugin_property('shipToAddressStateOrProvince', ship_to_address_state)
t_info_plugin.properties << create_plugin_property('shipToAddressCountry', ship_to_address_country)
t_info_plugin.properties << create_plugin_property('shipToAddressPostalCode', ship_to_address_zip)
t_info_plugin.properties << create_plugin_property('shipToAddressContactPhone', ship_to_address_phone)
t_info_plugin.properties << create_plugin_property('receiverInfoBusiness', receiver_info_business)
t_info_plugin.properties << create_plugin_property('receiverInfoReceiver', receiver_info_receiver)
t_info_plugin.properties << create_plugin_property('receiverInfoReceiverID', receiver_info_receiverid)
t_info_plugin.properties << create_plugin_property('paymentInfoTransactionID', payment_info_transactionid)
t_info_plugin.properties << create_plugin_property('paymentInfoParentTransactionID', payment_info_parenttransactionid)
t_info_plugin.properties << create_plugin_property('paymentInfoReceiptID', payment_info_receiptid)
t_info_plugin.properties << create_plugin_property('paymentInfoTransactionType', payment_info_transactiontype)
t_info_plugin.properties << create_plugin_property('paymentInfoPaymentType', payment_info_paymenttype)
t_info_plugin.properties << create_plugin_property('paymentInfoPaymentDate', payment_info_paymentdate)
t_info_plugin.properties << create_plugin_property('paymentInfoGrossAmount', payment_info_grossamount)
t_info_plugin.properties << create_plugin_property('paymentInfoFeeAmount', payment_info_feeamount)
t_info_plugin.properties << create_plugin_property('paymentInfoTaxAmount', payment_info_taxamount)
t_info_plugin.properties << create_plugin_property('paymentInfoExchangeRate', payment_info_exchangerate)
t_info_plugin.properties << create_plugin_property('paymentInfoPaymentStatus', payment_info_paymentstatus)
t_info_plugin.properties << create_plugin_property('paymentInfoPendingReason', payment_info_pendingreason)
t_info_plugin.properties << create_plugin_property('paymentInfoReasonCode', payment_info_reasoncode)
t_info_plugin.properties << create_plugin_property('paymentInfoProtectionEligibility', payment_info_protectioneligibility)
t_info_plugin.properties << create_plugin_property('paymentInfoProtectionEligibilityType', payment_info_protectioneligibilitytype)
t_info_plugin.properties << create_plugin_property('paymentInfoShipAmount', payment_info_shipamount)
t_info_plugin.properties << create_plugin_property('paymentInfoShipHandleAmount', payment_info_shiphandleamount)
t_info_plugin.properties << create_plugin_property('paymentInfoShipDiscount', payment_info_shipdiscount)
t_info_plugin.properties << create_plugin_property('paymentInfoInsuranceAmount', payment_info_insuranceamount)
t_info_plugin.properties << create_plugin_property('paymentInfoSubject', payment_info_subject)
t_info_plugin.properties << create_plugin_property('paypalExpressResponseId', id)
t_info_plugin
end
end
end
end
<file_sep>/spec/paypal_express/remote/hpp_spec.rb
require 'spec_helper'
require_relative 'hpp_spec_helpers'
require_relative 'build_plugin_helpers'
ActiveMerchant::Billing::Base.mode = :test
shared_examples 'hpp_spec_common' do
before(:each) do
::Killbill::PaypalExpress::PaypalExpressTransaction.delete_all
::Killbill::PaypalExpress::PaypalExpressResponse.delete_all
# clean the payments before each spec to avoid one influences each other
@plugin.kb_apis.proxied_services[:payment_api].delete_all_payments
end
it 'should generate forms correctly' do
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 0
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 0
# Verify the payment cannot go through without the token
purchase_with_missing_token
# Verify multiple payments can be triggered for the same payment method
n = 2
1.upto(n) do
form = @plugin.build_form_descriptor(@pm.kb_account_id, @form_fields, [], @call_context)
validate_form(form)
validate_nil_form_property(form, 'kb_payment_id')
validate_nil_form_property(form, 'kb_transaction_external_key')
token = validate_form_property(form, 'token')
# Verify no payment was created in Kill Bill
@plugin.kb_apis.proxied_services[:payment_api].payments.should be_empty
properties = []
properties << build_property('token', token)
# Verify the payment cannot go through until the token is validated
purchase_with_invalid_token(properties)
validate_token(form)
purchase_and_refund(SecureRandom.uuid, SecureRandom.uuid, properties)
# Verify no extra payment was created in Kill Bill by the plugin
@plugin.kb_apis.proxied_services[:payment_api].payments.should be_empty
# Verify the token cannot be re-used
subsequent_purchase(properties)
# Verify no token/baid was stored
verify_payment_method
end
# Each loop triggers one successful purchase and one successful refund
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 2 * n
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 1 + 8 * n
end
it 'should generate forms with pending payments correctly' do
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 0
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 0
# Verify the payment cannot go through without the token
purchase_with_missing_token
# Verify multiple payments can be triggered for the same payment method
n = 2
1.upto(n) do |i|
payment_external_key = SecureRandom.uuid
properties = @plugin.hash_to_properties(
:transaction_external_key => payment_external_key,
:create_pending_payment => true
)
form = @plugin.build_form_descriptor(@pm.kb_account_id, @form_fields, properties, @call_context)
validate_form(form)
kb_payment_id = validate_form_property(form, 'kb_payment_id')
validate_form_property(form, 'kb_transaction_external_key', payment_external_key)
token = validate_form_property(form, 'token')
# Verify the payment was created in Kill Bill
@plugin.kb_apis.proxied_services[:payment_api].payments.size.should == i
@plugin.kb_apis.proxied_services[:payment_api].get_payment(kb_payment_id).transactions.first.external_key.should == payment_external_key
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, [], @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :PURCHASE
payment_infos[0].amount.should be_nil
payment_infos[0].currency.should be_nil
payment_infos[0].status.should == :PENDING
payment_infos[0].gateway_error.should == {:payment_plugin_status => 'PENDING',
:token_expiration_period => @plugin.class.const_get(:THREE_HOURS_AGO).to_s}.to_json
payment_infos[0].gateway_error_code.should be_nil
properties = []
properties << build_property('token', token)
# Verify the payment cannot go through until the token is validated
purchase_with_invalid_token(properties)
validate_token(form)
purchase_and_refund(kb_payment_id, payment_external_key, properties)
# Verify no extra payment was created in Kill Bill by the plugin
@plugin.kb_apis.proxied_services[:payment_api].payments.size.should == i
# Verify the token cannot be re-used
subsequent_purchase(properties)
# Verify no token/baid was stored
verify_payment_method
end
# Each loop triggers one successful purchase and one successful refund
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 2 * n
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 1 + 9 * n
end
it 'should generate forms and perform auth, capture and refund correctly' do
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 0
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 0
# Verify the authorization cannot go through without the token
authorize_with_missing_token
# Verify multiple payments can be triggered for the same payment method
n = 2
1.upto(n) do |i|
payment_external_key = SecureRandom.uuid
is_pending_payment_test = i % 2 == 1 ? false : true
properties = @plugin.hash_to_properties(
:transaction_external_key => payment_external_key,
# test both with and without pending payments
:create_pending_payment => is_pending_payment_test,
:payment_processor_account_id => @payment_processor_account_id,
:auth_mode => true
)
form = @plugin.build_form_descriptor(@pm.kb_account_id, @form_fields, properties, @call_context)
validate_form(form)
token = validate_form_property(form, 'token')
# Verify payments were created when create_pending_payment is true
@plugin.kb_apis.proxied_services[:payment_api].payments.size.should == i / 2
if is_pending_payment_test
kb_payment_id = validate_form_property(form, 'kb_payment_id')
validate_form_property(form, 'kb_transaction_external_key', payment_external_key)
@plugin.kb_apis.proxied_services[:payment_api].get_payment(kb_payment_id).transactions.first.external_key.should == payment_external_key
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should be_nil
payment_infos[0].currency.should be_nil
payment_infos[0].status.should == :PENDING
payment_infos[0].gateway_error.should == {:payment_plugin_status => 'PENDING',
:token_expiration_period => @plugin.class.const_get(:THREE_HOURS_AGO).to_s}.to_json
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, :payment_processor_account_id).should == @payment_processor_account_id
else
kb_payment_id = SecureRandom.uuid
validate_nil_form_property(form, 'kb_payment_id')
validate_nil_form_property(form, 'kb_transaction_external_key')
end
properties = []
properties << build_property(:token, token)
# Verify the payment cannot be authorized without the token being validated
authorize_with_invalid_token(properties)
# Go to PayPal to validate the token
validate_token(form)
# Verify auth, capture and refund
authorize_capture_and_refund(kb_payment_id, payment_external_key, properties, @payment_processor_account_id)
# Verify no extra payment was created in Kill Bill by the plugin
@plugin.kb_apis.proxied_services[:payment_api].payments.size.should == (i / 2)
# Verify no token/baid was stored
verify_payment_method
end
# Each loop triggers one successful auth, one successful capture and one successful refund
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 3 * n
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 1 + 15 * n / 2 + 7 * n % 2
end
it 'should perform auth and void correctly' do
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 0
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 0
# Verify multiple payments can be triggered for the same payment method
n = 2
1.upto(n) do |i|
payment_external_key = SecureRandom.uuid
is_pending_payment_test = i % 2 == 1 ? false : true
properties = @plugin.hash_to_properties(
:transaction_external_key => payment_external_key,
:create_pending_payment => is_pending_payment_test,
:auth_mode => true,
:payment_processor_account_id => @payment_processor_account_id
)
form = @plugin.build_form_descriptor(@pm.kb_account_id, @form_fields, properties, @call_context)
validate_form(form)
token = validate_form_property(form, 'token')
if is_pending_payment_test
kb_payment_id = validate_form_property(form, 'kb_payment_id')
else
kb_payment_id = SecureRandom.uuid
end
# Go to PayPal to validate the token
validate_token(form)
properties = []
properties << build_property('token', token)
authorize_and_void(kb_payment_id, payment_external_key, properties, @payment_processor_account_id)
# Verify no extra payment was created in Kill Bill by the plugin
@plugin.kb_apis.proxied_services[:payment_api].payments.size.should == i / 2
end
# Each loop triggers one successful authorize and one successful void
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 2 * n
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 9 * n / 2 + 5 * n % 2
end
it 'should not capture the same transaction twice with full amount' do
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 0
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 0
payment_external_key = SecureRandom.uuid
properties = @plugin.hash_to_properties(
:transaction_external_key => payment_external_key,
:create_pending_payment => true,
:auth_mode => true
)
form = @plugin.build_form_descriptor(@pm.kb_account_id, @form_fields, properties, @call_context)
validate_form(form)
kb_payment_id = validate_form_property(form, 'kb_payment_id')
validate_form_property(form, 'kb_transaction_external_key', payment_external_key)
token = validate_form_property(form, 'token')
properties = []
properties << build_property('token', token)
properties << build_property('auth_mode', 'true')
validate_token(form)
authorize_and_double_capture(kb_payment_id, payment_external_key, properties)
end
it 'should find the payment processor id from the initial_express_call' do
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 0
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 0
properties = @plugin.hash_to_properties(
:transaction_external_key => SecureRandom.uuid,
:create_pending_payment => true,
:auth_mode => true,
:payment_processor_account_id => @payment_processor_account_id
)
form = @plugin.build_form_descriptor(@pm.kb_account_id, @form_fields, properties, @call_context)
token = validate_form_property(form, 'token')
@plugin.send(:find_payment_processor_id_from_initial_call, @pm.kb_account_id, @call_context.tenant_id, token).should == @payment_processor_account_id
properties = @plugin.hash_to_properties(
:transaction_external_key => SecureRandom.uuid,
:auth_mode => true,
:payment_processor_account_id => @payment_processor_account_id
)
form = @plugin.build_form_descriptor(@pm.kb_account_id, @form_fields, properties, @call_context)
token = validate_form_property(form, 'token')
@plugin.send(:find_payment_processor_id_from_initial_call, @pm.kb_account_id, @call_context.tenant_id, token).should == @payment_processor_account_id
properties = @plugin.hash_to_properties(
:transaction_external_key => SecureRandom.uuid,
:create_pending_payment => true,
:payment_processor_account_id => @payment_processor_account_id
)
form = @plugin.build_form_descriptor(@pm.kb_account_id, @form_fields, properties, @call_context)
token = validate_form_property(form, 'token')
@plugin.send(:find_payment_processor_id_from_initial_call, @pm.kb_account_id, @call_context.tenant_id, token).should == @payment_processor_account_id
properties = @plugin.hash_to_properties(
:transaction_external_key => SecureRandom.uuid,
:payment_processor_account_id => @payment_processor_account_id
)
form = @plugin.build_form_descriptor(@pm.kb_account_id, @form_fields, properties, @call_context)
token = validate_form_property(form, 'token')
@plugin.send(:find_payment_processor_id_from_initial_call, @pm.kb_account_id, @call_context.tenant_id, token).should == @payment_processor_account_id
end
it 'should cancel the pending payment if the token expires' do
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 0
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 0
expiration_period = 5
payment_external_key = SecureRandom.uuid
properties = @plugin.hash_to_properties(
:transaction_external_key => payment_external_key,
:create_pending_payment => true,
:token_expiration_period => expiration_period
)
form = @plugin.build_form_descriptor(@pm.kb_account_id, @form_fields, properties, @call_context)
kb_payment_id = validate_form_property(form, 'kb_payment_id')
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].amount.should be_nil
payment_infos[0].currency.should be_nil
payment_infos[0].status.should == :PENDING
payment_infos[0].gateway_error.should == {:payment_plugin_status => 'PENDING',
:token_expiration_period => expiration_period.to_s}.to_json
payment_infos[0].gateway_error_code.should be_nil
sleep payment_infos[0].created_date + expiration_period - Time.parse(@plugin.clock.get_clock.get_utc_now.to_s) + 1
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
# Make sure no extra response is created
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].amount.should be_nil
payment_infos[0].currency.should be_nil
payment_infos[0].status.should == :CANCELED
payment_infos[0].gateway_error.should == 'Token expired. Payment Canceled by Janitor.'
payment_infos[0].gateway_error_code.should be_nil
end
it 'should cancel the pending payment if the token expires without passing property' do
::Killbill::PaypalExpress::PaypalExpressTransaction.count.should == 0
::Killbill::PaypalExpress::PaypalExpressResponse.count.should == 0
expiration_period = 5
@plugin.class.const_set(:THREE_HOURS_AGO, expiration_period)
payment_external_key = SecureRandom.uuid
properties = @plugin.hash_to_properties(
:transaction_external_key => payment_external_key,
:create_pending_payment => true
)
form = @plugin.build_form_descriptor(@pm.kb_account_id, @form_fields, properties, @call_context)
kb_payment_id = validate_form_property(form, 'kb_payment_id')
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].amount.should be_nil
payment_infos[0].currency.should be_nil
payment_infos[0].status.should == :PENDING
payment_infos[0].gateway_error.should == {:payment_plugin_status => 'PENDING',
:token_expiration_period => expiration_period.to_s}.to_json
payment_infos[0].gateway_error_code.should be_nil
sleep payment_infos[0].created_date + expiration_period - Time.parse(@plugin.clock.get_clock.get_utc_now.to_s) + 1
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
# Make sure no extra response is created
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].amount.should be_nil
payment_infos[0].currency.should be_nil
payment_infos[0].status.should == :CANCELED
payment_infos[0].gateway_error.should == 'Token expired. Payment Canceled by Janitor.'
payment_infos[0].gateway_error_code.should be_nil
end
end
describe Killbill::PaypalExpress::PaymentPlugin do
include ::Killbill::Plugin::ActiveMerchant::RSpec
include ::Killbill::PaypalExpress::BuildPluginHelpers
include ::Killbill::PaypalExpress::HppSpecHelpers
context 'hpp test with a single account' do
before(:all) do
@payment_processor_account_id = 'default'
@plugin = build_start_paypal_plugin
hpp_setup
end
include_examples 'hpp_spec_common'
end
context 'hpp test with multiple accounts' do
before(:all) do
@payment_processor_account_id = 'paypal_test_account'
@plugin = build_start_paypal_plugin @payment_processor_account_id
hpp_setup
end
include_examples 'hpp_spec_common'
end
end
<file_sep>/spec/paypal_express/remote/baid_spec_helpers.rb
require_relative 'browser_helpers'
module Killbill
module PaypalExpress
module BaidSpecHelpers
include ::Killbill::PaypalExpress::BrowserHelpers
def baid_setup(payment_processor_account_id = nil)
@call_context = build_call_context
options = {:payment_processor_account_id => payment_processor_account_id}
@amount = BigDecimal.new('100')
@currency = 'USD'
kb_account_id = SecureRandom.uuid
external_key, kb_account_id = create_kb_account(kb_account_id, @plugin.kb_apis.proxied_services[:account_user_api])
# Initiate the setup process
response = create_token(kb_account_id, @call_context.tenant_id, options)
token = response.token
login_and_confirm @plugin.to_express_checkout_url(response, @call_context.tenant_id)
# Complete the setup process
@properties = []
@properties << build_property('token', token)
@pm = create_payment_method(::Killbill::PaypalExpress::PaypalExpressPaymentMethod, kb_account_id, @call_context.tenant_id, @properties)
verify_payment_method kb_account_id
end
private
def create_token(kb_account_id, kb_tenant_id, options)
private_plugin = ::Killbill::PaypalExpress::PrivatePaymentPlugin.new
response = private_plugin.initiate_express_checkout(kb_account_id, kb_tenant_id, @amount, @currency, true, options)
response.success.should be_true
response
end
def verify_payment_method(kb_account_id)
# Verify our table directly. Note that @pm.token is the baid
payment_methods = ::Killbill::PaypalExpress::PaypalExpressPaymentMethod.from_kb_account_id_and_token(@pm.token, kb_account_id, @call_context.tenant_id)
payment_methods.size.should == 1
payment_method = payment_methods.first
payment_method.should_not be_nil
payment_method.paypal_express_payer_id.should_not be_nil
payment_method.token.should == @pm.token
payment_method.kb_payment_method_id.should == @pm.kb_payment_method_id
end
end
end
end
<file_sep>/README.md
killbill-paypal-express-plugin
==============================
Plugin to use [PayPal Express Checkout](https://www.paypal.com/webapps/mpp/express-checkout) as a gateway.
Release builds are available on [Maven Central](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.kill-bill.billing.plugin.ruby%22%20AND%20a%3A%22paypal-express-plugin%22) with coordinates `org.kill-bill.billing.plugin.ruby:paypal-express-plugin`.
A full end-to-end integration demo is available [here](https://github.com/killbill/killbill-paypal-demo).
Kill Bill compatibility
-----------------------
| Plugin version | Kill Bill version |
| -------------: | ----------------: |
| 2.x.y | 0.14.z |
| 4.x.y | 0.16.z |
| 5.x.y | 0.18.z |
Requirements
------------
The plugin needs a database. The latest version of the schema can be found [here](https://github.com/killbill/killbill-paypal-express-plugin/blob/master/db/ddl.sql).
Configuration
-------------
```
curl -v \
-X POST \
-u admin:password \
-H 'X-Killbill-ApiKey: bob' \
-H 'X-Killbill-ApiSecret: lazar' \
-H 'X-Killbill-CreatedBy: admin' \
-H 'Content-Type: text/plain' \
-d ':paypal_express:
:signature: "your-paypal-signature"
:login: "your-username-facilitator.something.com"
:password: "<PASSWORD>"' \
http://127.0.0.1:8080/1.0/kb/tenants/uploadPluginConfig/killbill-paypal-express
```
To go to production, create a `paypal_express.yml` configuration file under `/var/tmp/bundles/plugins/ruby/killbill-paypal-express/x.y.z/` containing the following:
```
:paypal_express:
:test: false
```
Usage
-----
### One-off payments
Create a payment method for the account:
```
curl -v \
-X POST \
-u admin:password \
-H 'X-Killbill-ApiKey: bob' \
-H 'X-Killbill-ApiSecret: l<PASSWORD>' \
-H 'X-Killbill-CreatedBy: admin' \
-H 'Content-Type: application/json' \
-d '{
"pluginName": "killbill-paypal-express",
"pluginInfo": {}
}' \
"http://127.0.0.1:8080/1.0/kb/accounts/<ACCOUNT_ID>/paymentMethods?isDefault=true"
```
#### Without a pending payment
Generate the redirect URL using buildFormDescriptor (this will invoke `SetExpressCheckout`):
```
curl -v \
-X POST \
-u admin:password \
-H 'X-Killbill-ApiKey: bob' \
-H 'X-Killbill-ApiSecret: l<PASSWORD>' \
-H 'X-Killbill-CreatedBy: admin' \
-H 'Content-Type: application/json' \
-d '{
"formFields": [{
"key": "amount",
"value": 10
},{
"key": "currency",
"value": "USD"
}]
}' \
"http://127.0.0.1:8080/1.0/kb/paymentGateways/hosted/form/<ACCOUNT_ID>"
```
The customer should be redirected to the url specified in the `formUrl` entry of the response, e.g. https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=<KEY>.
Once the customer comes back from the PayPal flow, trigger the payment:
```
curl -v \
-X POST \
-u admin:password \
-H 'X-Killbill-ApiKey: bob' \
-H 'X-Killbill-ApiSecret: l<PASSWORD>' \
-H 'X-Killbill-CreatedBy: admin' \
-H 'Content-Type: application/json' \
-d '{
"transactionType": "PURCHASE",
"amount": "10",
"currency": "USD"
}' \
"http://127.0.0.1:8080/1.0/kb/accounts/<ACCOUNT_ID>/payments"
```
#### With a pending payment
Generate the redirect URL using buildFormDescriptor (this will invoke `SetExpressCheckout`):
```
curl -v \
-X POST \
-u admin:password \
-H 'X-Killbill-ApiKey: bob' \
-H 'X-Killbill-ApiSecret: lazar' \
-H 'X-Killbill-CreatedBy: admin' \
-H 'Content-Type: application/json' \
-d '{
"formFields": [{
"key": "amount",
"value": 10
},{
"key": "currency",
"value": "USD"
}]
}' \
"http://127.0.0.1:8080/1.0/kb/paymentGateways/hosted/form/<ACCOUNT_ID>?pluginProperty=create_pending_payment=true"
```
The customer should be redirected to the url specified in the `formUrl` entry of the response, e.g. https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-<PASSWORD>.
Once the customer comes back from the PayPal flow, complete the payment (the payment id and external key are returned as part of the buildFormDescriptor call):
```
curl -v \
-X PUT \
-u admin:password \
-H 'X-Killbill-ApiKey: bob' \
-H 'X-Killbill-ApiSecret: lazar' \
-H 'X-Killbill-CreatedBy: admin' \
-H 'Content-Type: application/json' \
"http://127.0.0.1:8080/1.0/kb/payments/<PAYMENT_ID>"
```
### Recurring payments via a billing agreement ID (BAID)
Issue the following call to generate a Paypal token:
```
curl -v \
-X POST \
-u admin:password \
-H 'X-Killbill-ApiKey: bob' \
-H 'X-Killbill-ApiSecret: lazar' \
-H 'X-Killbill-CreatedBy: admin' \
-H 'Content-Type: application/json' \
-d '{
"kb_account_id": "13d26090-b8d7-11e2-9e96-0800200c9a66",
"currency": "USD",
"options": {
"return_url": "http://www.google.com/?q=SUCCESS",
"cancel_return_url": "http://www.google.com/?q=FAILURE",
"billing_agreement": {
"description": "Your subscription"
}
}
}' \
http://127.0.0.1:8080/plugins/killbill-paypal-express/1.0/setup-checkout
```
Kill Bill will return a 302 Found on success. The customer should be redirected to the url specified in the Location header, e.g. https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=<KEY>.
Once the customer comes back from the PayPal flow, save the BAID in Kill Bill:
```
curl -v \
-X POST \
-u admin:password \
-H 'X-Killbill-ApiKey: bob' \
-H 'X-Killbill-ApiSecret: lazar' \
-H 'X-Killbill-CreatedBy: admin' \
-H 'Content-Type: application/json' \
-d '{
"pluginName": "killbill-paypal-express",
"pluginInfo": {
"properties": [{
"key": "token",
"value": "<PASSWORD>"
}]
}
}' \
"http://127.0.0.1:8080/1.0/kb/accounts/13d26090-b8d7-11e2-9e96-0800200c9a66/paymentMethods?isDefault=true"
```
Plugin properties
-----------------
| Key | Description |
| ---------------------------: | ----------------------------------------------------------------- |
| skip_gw | If true, skip the call to PayPal |
| token | PayPal token to use |
| payer_id | PayPal Payer id to use |
| create_pending_payment | Create pending payment during buildFormDescriptor call |
| payment_processor_account_id | Config entry name of the merchant account to use |
| external_key_as_order_id | If true, set the payment external key as the PayPal order id |
| email | Purchaser email |
| address1 | Billing address first line |
| address2 | Billing address second line |
| city | Billing address city |
| zip | Billing address zip code |
| state | Billing address state |
| country | Billing address country |
Below is a list of optional parameters for build_form_descriptor call. More details can be found on PayPal [manual](https://developer.paypal.com/docs/classic/api/merchant/SetExpressCheckout_API_Operation_SOAP/)
| Key | Description |
| ---------------------------: | ----------------------------------------------------------------- |
| max_amount | Maximum amount parameter |
| auth_mode | If true, [Authorization Payment Action](https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECRelatedAPIOps/) is adopted. Otherwise, Sale Payment Action is used.|
| no_shipping | Whether or not to show shipping address on PayPal checkout page |
| req_billing_address | Is 1 or 0. The value 1 indicates that you require that the buyer’s billing address on file with PayPal be returned. Setting this element will return `BILLTONAME`, `STREET`, `STREET2`, `CITY`, `STATE`, `ZIP`, and `COUNTRYCODE`. |
| address_override | Determines whether or not the PayPal pages should display the shipping address set by you in this SetExpressCheckout request, not the shipping address on file with PayPal for this buyer.|
| locale | Locale of pages displayed by PayPal during Express Checkout. It is either a two-letter country code or five-character locale code supported by PayPal. |
| brand_name | A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.|
| page_style | Name of the Custom Payment Page Style for payment pages associated with this button or link. It corresponds to the HTML variable page_style for customizing payment pages. |
| logo_image | A URL to your logo image. Use a valid graphics format, such as .gif, .jpg, or .png. Limit the image to 190 pixels wide by 60 pixels high. |
| header_image | URL for the image you want to appear at the top left of the payment page. The image has a maximum size of 750 pixels wide by 90 pixels high. |
| header_border_color | Sets the border color around the header of the payment page. The border is a 2-pixel perimeter around the header space, which is 750 pixels wide by 90 pixels high. By default, the color is black. |
| header_background_color | Sets the background color for the header of the payment page. By default, the color is white. |
| background_color | Sets the background color for the payment page. By default, the color is white.|
| allow_guest_checkout | If set to true, then the SolutionType is Sole and buyer does not need to create a PayPal account to check out. |
| landing_page | Type of PayPal page to display. It is one of the following values: Billing for Non-PayPal account and Login — PayPal account login. |
| email | Email address of the buyer as entered during checkout. PayPal uses this value to pre-fill the PayPal membership sign-up portion on the PayPal pages. |
| allow_note | Enables the buyer to enter a note to the merchant on the PayPal page during checkout.|
| callback_url | URL to which the callback request from PayPal is sent. It must start with HTTPS for production integration. |
| callback_timeout | An override for you to request more or less time to be able to process the callback request and respond. |
| allow_buyer_optin | Enables the buyer to provide their email address on the PayPal pages to be notified of promotions or special events. |
| shipping_address | Address to which the order is shipped. This parameter must be a JSON Hash with keys of `name`, `address1`, `address2`, `state`, `city`, `country`, `phone`, `zip` and `phone`. |
| address | Address to which the order is shipped if shipping_address is not set. This parameter must be a JSON Hash with keys of `name`, `address1`, `address2`, `state`, `city`, `country`, `phone`, `zip` and `phone`. |
| total_type | Type declaration for the label to be displayed in MiniCart for UX. It is one of the following values: Total or EstimatedTotal. |
| funding_sources | This parameter must be in a JSON hash format with a key being `source`. This element could be used to specify the preferred funding option for a guest user. However, the `landing_page` element must also be set to `Billing`. Otherwise, it is ignored.|
| shipping_options | This parameter must be in a JSON hash format with keys of `default`, `amount`, and `name`. This corresponds to the `ShippingOptionsType` in the SetupExpressCheckout call. |
| subtotal | Sum of cost of all items in this order. For digital goods, this field is required. |
| shipping | Total shipping costs for this order. |
| handling | Total handling costs for this order. |
| tax | Sum of tax for all items in this order. |
| insurance_total | Total shipping insurance costs for this order. The value must be a non-negative currency amount or null if you offer insurance options. |
| shipping_discount | Shipping discount for this order, specified as a negative number. |
| insurance_option_offered | Indicates whether insurance is available as an option the buyer can choose on the PayPal Review page. |
| description | Description of items the buyer is purchasing. |
| custom | A free-form field for your own use. |
| order_id | Your own invoice or tracking number. |
| invoice_id | Your own invoice or tracking number. This will be overridden by order_id. |
| notify_url | Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists.|
| items | This parameter must be a JSON Array that contains a list of Hashes with keys of `name`, `number`, `quantity`, `amount`, `description`, `url` and `category`. |
<file_sep>/spec/paypal_express/remote/hpp_spec_helpers.rb
require_relative 'browser_helpers'
module Killbill
module PaypalExpress
module HppSpecHelpers
include ::Killbill::PaypalExpress::BrowserHelpers
def hpp_setup
@call_context = build_call_context
@amount = BigDecimal.new('100')
@currency = 'USD'
@form_fields = @plugin.hash_to_properties(
:order_id => '1234',
:amount => @amount,
:currency => @currency
)
kb_account_id = SecureRandom.uuid
create_kb_account(kb_account_id, @plugin.kb_apis.proxied_services[:account_user_api])
@pm = create_payment_method(::Killbill::PaypalExpress::PaypalExpressPaymentMethod, kb_account_id, @call_context.tenant_id)
verify_payment_method kb_account_id
end
def validate_form(form)
form.kb_account_id.should == @pm.kb_account_id
form.form_url.should start_with('https://www.sandbox.paypal.com/cgi-bin/webscr')
form.form_method.should == 'GET'
end
def validate_nil_form_property(form, key)
key_properties = form.properties.select { |prop| prop.key == key }
key_properties.size.should == 0
end
def validate_form_property(form, key, value=nil)
key_properties = form.properties.select { |prop| prop.key == key }
key_properties.size.should == 1
key = key_properties.first.value
value.nil? ? key.should_not(be_nil) : key.should == value
key
end
def validate_token(form)
login_and_confirm form.form_url
end
def purchase_and_refund(kb_payment_id, purchase_payment_external_key, purchase_properties)
# Trigger the purchase
payment_response = @plugin.purchase_payment(@pm.kb_account_id, kb_payment_id, purchase_payment_external_key, @pm.kb_payment_method_id, @amount, @currency, purchase_properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == @amount
payment_response.transaction_type.should == :PURCHASE
payer_id = find_value_from_properties(payment_response.properties, 'payerId')
payer_id.should_not be_nil
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, [], @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :PURCHASE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payerId').should == payer_id
# Try a full refund
refund_response = @plugin.refund_payment(@pm.kb_account_id, kb_payment_id, SecureRandom.uuid, @pm.kb_payment_method_id, @amount, @currency, [], @call_context)
refund_response.status.should eq(:PROCESSED), refund_response.gateway_error
refund_response.amount.should == @amount
refund_response.transaction_type.should == :REFUND
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, [], @call_context)
payment_infos.size.should == 2
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :PURCHASE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
payment_infos[1].kb_payment_id.should.should == kb_payment_id
payment_infos[1].transaction_type.should == :REFUND
payment_infos[1].amount.should == @amount
payment_infos[1].currency.should == @currency
payment_infos[1].status.should == :PROCESSED
payment_infos[1].gateway_error.should == 'Success'
payment_infos[1].gateway_error_code.should be_nil
end
def authorize_capture_and_refund(kb_payment_id, payment_external_key, properties, payment_processor_account_id)
# Trigger the authorize
payment_response = @plugin.authorize_payment(@pm.kb_account_id, kb_payment_id, payment_external_key, @pm.kb_payment_method_id, @amount, @currency, properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == @amount
payment_response.transaction_type.should == :AUTHORIZE
payer_id = find_value_from_properties(payment_response.properties, 'payerId')
payer_id.should_not be_nil
# Verify GET AUTHORIZED PAYMENT
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payerId').should == payer_id
find_value_from_properties(payment_infos[0].properties, 'paymentInfoPaymentStatus').should == 'Pending'
find_value_from_properties(payment_infos[0].properties, 'paymentInfoPendingReason').should == 'authorization'
find_value_from_properties(payment_infos[0].properties, 'payment_processor_account_id').should == payment_processor_account_id
# Trigger the capture
payment_response = @plugin.capture_payment(@pm.kb_account_id, kb_payment_id, payment_external_key, @pm.kb_payment_method_id, @amount, @currency, properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == @amount
payment_response.transaction_type.should == :CAPTURE
# Verify GET CAPTURED PAYMENT
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
# Two expected transactions: one auth and one capture
payment_infos.size.should == 2
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payment_processor_account_id').should == payment_processor_account_id
payment_infos[1].kb_payment_id.should == kb_payment_id
payment_infos[1].transaction_type.should == :CAPTURE
payment_infos[1].amount.should == @amount
payment_infos[1].currency.should == @currency
payment_infos[1].status.should == :PROCESSED
payment_infos[1].gateway_error.should == 'Success'
payment_infos[1].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[1].properties, 'paymentInfoPaymentStatus').should == 'Completed'
find_value_from_properties(payment_infos[1].properties, 'payment_processor_account_id').should == payment_processor_account_id
# Try a full refund
refund_response = @plugin.refund_payment(@pm.kb_account_id, kb_payment_id, SecureRandom.uuid, @pm.kb_payment_method_id, @amount, @currency, [], @call_context)
refund_response.status.should eq(:PROCESSED), refund_response.gateway_error
refund_response.amount.should == @amount
refund_response.transaction_type.should == :REFUND
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
payment_infos.size.should == 3
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payment_processor_account_id').should == payment_processor_account_id
payment_infos[1].kb_payment_id.should == kb_payment_id
payment_infos[1].transaction_type.should == :CAPTURE
payment_infos[1].amount.should == @amount
payment_infos[1].currency.should == @currency
payment_infos[1].status.should == :PROCESSED
payment_infos[1].gateway_error.should == 'Success'
payment_infos[1].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[1].properties, 'payment_processor_account_id').should == payment_processor_account_id
payment_infos[2].kb_payment_id.should.should == kb_payment_id
payment_infos[2].transaction_type.should == :REFUND
payment_infos[2].amount.should == @amount
payment_infos[2].currency.should == @currency
payment_infos[2].status.should == :PROCESSED
payment_infos[2].gateway_error.should == 'Success'
payment_infos[2].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[2].properties, 'payment_processor_account_id').should == payment_processor_account_id
end
def authorize_and_double_capture(kb_payment_id, payment_external_key, properties)
# Trigger the authorize
payment_response = @plugin.authorize_payment(@pm.kb_account_id, kb_payment_id, payment_external_key, @pm.kb_payment_method_id, @amount, @currency, properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == @amount
payment_response.transaction_type.should == :AUTHORIZE
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
# Trigger the capture
payment_response = @plugin.capture_payment(@pm.kb_account_id, kb_payment_id, payment_external_key, @pm.kb_payment_method_id, @amount, @currency, properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == @amount
payment_response.transaction_type.should == :CAPTURE
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
payment_infos.size.should == 2
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
payment_infos[1].kb_payment_id.should == kb_payment_id
payment_infos[1].transaction_type.should == :CAPTURE
payment_infos[1].amount.should == @amount
payment_infos[1].currency.should == @currency
payment_infos[1].status.should == :PROCESSED
payment_infos[1].gateway_error.should == 'Success'
payment_infos[1].gateway_error_code.should be_nil
# Trigger a capture again with full amount
payment_response = @plugin.capture_payment(@pm.kb_account_id, kb_payment_id, payment_external_key, @pm.kb_payment_method_id, @amount, @currency, properties, @call_context)
payment_response.status.should eq(:ERROR), payment_response.gateway_error
payment_response.amount.should == nil
payment_response.transaction_type.should == :CAPTURE
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
payment_infos.size.should == 3
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
payment_infos[1].kb_payment_id.should == kb_payment_id
payment_infos[1].transaction_type.should == :CAPTURE
payment_infos[1].amount.should == @amount
payment_infos[1].currency.should == @currency
payment_infos[1].status.should == :PROCESSED
payment_infos[1].gateway_error.should == 'Success'
payment_infos[1].gateway_error_code.should be_nil
payment_infos[2].kb_payment_id.should.should == kb_payment_id
payment_infos[2].transaction_type.should == :CAPTURE
payment_infos[2].amount.should be_nil
payment_infos[2].currency.should be_nil
payment_infos[2].status.should == :ERROR
payment_infos[2].gateway_error.should == 'Authorization has already been completed.'
payment_infos[2].gateway_error_code.should == "10602"
end
def authorize_and_void(kb_payment_id, payment_external_key, properties, payment_processor_account_id)
# Trigger the authorize
payment_response = @plugin.authorize_payment(@pm.kb_account_id, kb_payment_id, payment_external_key, @pm.kb_payment_method_id, @amount, @currency, properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == @amount
payment_response.transaction_type.should == :AUTHORIZE
# Verify get_payment_info
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payment_processor_account_id').should == payment_processor_account_id
# Trigger the void
payment_response = @plugin.void_payment(@pm.kb_account_id, kb_payment_id, payment_external_key, @pm.kb_payment_method_id, properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.transaction_type.should == :VOID
# Verify get_payment_info
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, properties, @call_context)
# Two expected transactions: one auth and one capture
payment_infos.size.should == 2
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payment_processor_account_id').should == payment_processor_account_id
payment_infos[1].kb_payment_id.should == kb_payment_id
payment_infos[1].transaction_type.should == :VOID
payment_infos[1].status.should == :PROCESSED
payment_infos[1].gateway_error.should == 'Success'
payment_infos[1].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[1].properties, 'payment_processor_account_id').should == payment_processor_account_id
end
def purchase_with_missing_token
failed_purchase([], :CANCELED, 'Could not find the payer_id: the token is missing', 'RuntimeError')
end
def authorize_with_missing_token
failed_authorize([], :CANCELED, 'Could not find the payer_id: the token is missing', 'RuntimeError')
end
def purchase_with_invalid_token(purchase_properties)
failed_purchase(purchase_properties, :CANCELED, "Could not find the payer_id for token #{properties_to_hash(purchase_properties)[:token]}", 'RuntimeError')
end
def authorize_with_invalid_token(authorize_properties)
failed_authorize(authorize_properties, :CANCELED, "Could not find the payer_id for token #{properties_to_hash(authorize_properties)[:token]}", 'RuntimeError')
end
def subsequent_purchase(purchase_properties)
failed_purchase(purchase_properties, :ERROR, 'A successful transaction has already been completed for this token.', '11607')
end
def failed_authorize(authorize_properties, status, msg, gateway_error_code=nil)
kb_payment_id = SecureRandom.uuid
payment_response = @plugin.authorize_payment(@pm.kb_account_id, kb_payment_id, SecureRandom.uuid, @pm.kb_payment_method_id, @amount, @currency, authorize_properties, @call_context)
payment_response.status.should eq(status), payment_response.gateway_error
payment_response.amount.should be_nil
payment_response.transaction_type.should == :AUTHORIZE
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, [], @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should be_nil
payment_infos[0].currency.should be_nil
payment_infos[0].status.should == status
payment_infos[0].gateway_error.should == msg
payment_infos[0].gateway_error_code.should == gateway_error_code
end
def failed_purchase(purchase_properties, status, msg, gateway_error_code=nil)
kb_payment_id = SecureRandom.uuid
payment_response = @plugin.purchase_payment(@pm.kb_account_id, kb_payment_id, SecureRandom.uuid, @pm.kb_payment_method_id, @amount, @currency, purchase_properties, @call_context)
payment_response.status.should eq(status), payment_response.gateway_error
payment_response.amount.should be_nil
payment_response.transaction_type.should == :PURCHASE
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, kb_payment_id, [], @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == kb_payment_id
payment_infos[0].transaction_type.should == :PURCHASE
payment_infos[0].amount.should be_nil
payment_infos[0].currency.should be_nil
payment_infos[0].status.should == status
payment_infos[0].gateway_error.should == msg
payment_infos[0].gateway_error_code.should == gateway_error_code
end
private
def verify_payment_method(kb_account_id = nil)
# Verify our table directly
kb_account_id = @pm.kb_account_id if kb_account_id.nil?
payment_methods = ::Killbill::PaypalExpress::PaypalExpressPaymentMethod.from_kb_account_id(kb_account_id, @call_context.tenant_id)
payment_methods.size.should == 1
payment_method = payment_methods.first
payment_method.should_not be_nil
payment_method.paypal_express_payer_id.should be_nil
payment_method.token.should be_nil
payment_method.kb_payment_method_id.should == @pm.kb_payment_method_id
end
end
end
end
<file_sep>/spec/paypal_express/remote/baid_spec.rb
require 'spec_helper'
require_relative 'build_plugin_helpers'
require_relative 'baid_spec_helpers'
ActiveMerchant::Billing::Base.mode = :test
shared_examples 'baid_spec_common' do
before(:each) do
::Killbill::PaypalExpress::PaypalExpressTransaction.delete_all
kb_payment_id = SecureRandom.uuid
1.upto(6) do
@kb_payment = @plugin.kb_apis.proxied_services[:payment_api].add_payment(kb_payment_id)
end
end
it 'should be able to charge and refund' do
payment_response = @plugin.purchase_payment(@pm.kb_account_id, @kb_payment.id, @kb_payment.transactions[0].id, @pm.kb_payment_method_id, @amount, @currency, @properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == @amount
payment_response.transaction_type.should == :PURCHASE
payer_id = find_value_from_properties(payment_response.properties, 'payerId')
payer_id.should_not be_nil
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, @kb_payment.id, [], @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == @kb_payment.id
payment_infos[0].transaction_type.should == :PURCHASE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payment_processor_account_id').should == @payment_processor_account_id
find_value_from_properties(payment_infos[0].properties, 'payerId').should == payer_id
# Try a full refund
refund_response = @plugin.refund_payment(@pm.kb_account_id, @kb_payment.id, @kb_payment.transactions[1].id, @pm.kb_payment_method_id, @amount, @currency, @properties, @call_context)
refund_response.status.should eq(:PROCESSED), refund_response.gateway_error
refund_response.amount.should == @amount
refund_response.transaction_type.should == :REFUND
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, @kb_payment.id, [], @call_context)
payment_infos.size.should == 2
payment_infos[0].kb_payment_id.should == @kb_payment.id
payment_infos[0].transaction_type.should == :PURCHASE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payment_processor_account_id').should == @payment_processor_account_id
payment_infos[1].kb_payment_id.should == @kb_payment.id
payment_infos[1].transaction_type.should == :REFUND
payment_infos[1].amount.should == @amount
payment_infos[1].currency.should == @currency
payment_infos[1].status.should == :PROCESSED
payment_infos[1].gateway_error.should == 'Success'
payment_infos[1].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[1].properties, 'payment_processor_account_id').should == @payment_processor_account_id
end
it 'should be able to auth, capture and refund' do
payment_response = @plugin.authorize_payment(@pm.kb_account_id, @kb_payment.id, @kb_payment.transactions[0].id, @pm.kb_payment_method_id, @amount, @currency, @properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == @amount
payment_response.transaction_type.should == :AUTHORIZE
payer_id = find_value_from_properties(payment_response.properties, 'payerId')
payer_id.should_not be_nil
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, @kb_payment.id, [], @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == @kb_payment.id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payment_processor_account_id').should == @payment_processor_account_id
find_value_from_properties(payment_infos[0].properties, 'payerId').should == payer_id
# Try multiple partial captures
partial_capture_amount = BigDecimal.new('10')
1.upto(3) do |i|
payment_response = @plugin.capture_payment(@pm.kb_account_id, @kb_payment.id, @kb_payment.transactions[i].id, @pm.kb_payment_method_id, partial_capture_amount, @currency, @properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == partial_capture_amount
payment_response.transaction_type.should == :CAPTURE
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, @kb_payment.id, [], @call_context)
payment_infos.size.should == 1 + i
payment_infos[i].kb_payment_id.should == @kb_payment.id
payment_infos[i].transaction_type.should == :CAPTURE
payment_infos[i].amount.should == partial_capture_amount
payment_infos[i].currency.should == @currency
payment_infos[i].status.should == :PROCESSED
payment_infos[i].gateway_error.should == 'Success'
payment_infos[i].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[i].properties, 'payment_processor_account_id').should == @payment_processor_account_id
end
# Try a partial refund
refund_response = @plugin.refund_payment(@pm.kb_account_id, @kb_payment.id, @kb_payment.transactions[4].id, @pm.kb_payment_method_id, partial_capture_amount, @currency, @properties, @call_context)
refund_response.status.should eq(:PROCESSED), refund_response.gateway_error
refund_response.amount.should == partial_capture_amount
refund_response.transaction_type.should == :REFUND
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, @kb_payment.id, [], @call_context)
payment_infos.size.should == 5
payment_infos[4].kb_payment_id.should == @kb_payment.id
payment_infos[4].transaction_type.should == :REFUND
payment_infos[4].amount.should == partial_capture_amount
payment_infos[4].currency.should == @currency
payment_infos[4].status.should == :PROCESSED
payment_infos[4].gateway_error.should == 'Success'
payment_infos[4].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[4].properties, 'payment_processor_account_id').should == @payment_processor_account_id
# Try to capture again
payment_response = @plugin.capture_payment(@pm.kb_account_id, @kb_payment.id, @kb_payment.transactions[5].id, @pm.kb_payment_method_id, partial_capture_amount, @currency, @properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == partial_capture_amount
payment_response.transaction_type.should == :CAPTURE
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, @kb_payment.id, [], @call_context)
payment_infos.size.should == 6
payment_infos[5].kb_payment_id.should == @kb_payment.id
payment_infos[5].transaction_type.should == :CAPTURE
payment_infos[5].amount.should == partial_capture_amount
payment_infos[5].currency.should == @currency
payment_infos[5].status.should == :PROCESSED
payment_infos[5].gateway_error.should == 'Success'
payment_infos[5].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[5].properties, 'payment_processor_account_id').should == @payment_processor_account_id
end
it 'should be able to auth and void' do
payment_response = @plugin.authorize_payment(@pm.kb_account_id, @kb_payment.id, @kb_payment.transactions[0].id, @pm.kb_payment_method_id, @amount, @currency, @properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == @amount
payment_response.transaction_type.should == :AUTHORIZE
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, @kb_payment.id, [], @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == @kb_payment.id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payment_processor_account_id').should == @payment_processor_account_id
payment_response = @plugin.void_payment(@pm.kb_account_id, @kb_payment.id, @kb_payment.transactions[1].id, @pm.kb_payment_method_id, @properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.transaction_type.should == :VOID
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, @kb_payment.id, [], @call_context)
payment_infos.size.should == 2
payment_infos[0].kb_payment_id.should == @kb_payment.id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payment_processor_account_id').should == @payment_processor_account_id
payment_infos[1].kb_payment_id.should == @kb_payment.id
payment_infos[1].transaction_type.should == :VOID
payment_infos[1].amount.should be_nil
payment_infos[1].currency.should be_nil
payment_infos[1].status.should == :PROCESSED
payment_infos[1].gateway_error.should == 'Success'
payment_infos[1].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[1].properties, 'payment_processor_account_id').should == @payment_processor_account_id
end
it 'should be able to auth, partial capture and void' do
payment_response = @plugin.authorize_payment(@pm.kb_account_id, @kb_payment.id, @kb_payment.transactions[0].id, @pm.kb_payment_method_id, @amount, @currency, @properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == @amount
payment_response.transaction_type.should == :AUTHORIZE
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, @kb_payment.id, [], @call_context)
payment_infos.size.should == 1
payment_infos[0].kb_payment_id.should == @kb_payment.id
payment_infos[0].transaction_type.should == :AUTHORIZE
payment_infos[0].amount.should == @amount
payment_infos[0].currency.should == @currency
payment_infos[0].status.should == :PROCESSED
payment_infos[0].gateway_error.should == 'Success'
payment_infos[0].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[0].properties, 'payment_processor_account_id').should == @payment_processor_account_id
partial_capture_amount = BigDecimal.new('10')
payment_response = @plugin.capture_payment(@pm.kb_account_id, @kb_payment.id, @kb_payment.transactions[1].id, @pm.kb_payment_method_id, partial_capture_amount, @currency, @properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.amount.should == partial_capture_amount
payment_response.transaction_type.should == :CAPTURE
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, @kb_payment.id, [], @call_context)
payment_infos.size.should == 2
payment_infos[1].kb_payment_id.should == @kb_payment.id
payment_infos[1].transaction_type.should == :CAPTURE
payment_infos[1].amount.should == partial_capture_amount
payment_infos[1].currency.should == @currency
payment_infos[1].status.should == :PROCESSED
payment_infos[1].gateway_error.should == 'Success'
payment_infos[1].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[1].properties, 'payment_processor_account_id').should == @payment_processor_account_id
payment_response = @plugin.void_payment(@pm.kb_account_id, @kb_payment.id, @kb_payment.transactions[2].id, @pm.kb_payment_method_id, @properties, @call_context)
payment_response.status.should eq(:PROCESSED), payment_response.gateway_error
payment_response.transaction_type.should == :VOID
# Verify GET API
payment_infos = @plugin.get_payment_info(@pm.kb_account_id, @kb_payment.id, [], @call_context)
payment_infos.size.should == 3
payment_infos[2].kb_payment_id.should == @kb_payment.id
payment_infos[2].transaction_type.should == :VOID
payment_infos[2].amount.should be_nil
payment_infos[2].currency.should be_nil
payment_infos[2].status.should == :PROCESSED
payment_infos[2].gateway_error.should == 'Success'
payment_infos[2].gateway_error_code.should be_nil
find_value_from_properties(payment_infos[2].properties, 'payment_processor_account_id').should == @payment_processor_account_id
end
it 'should generate forms correctly' do
context = @plugin.kb_apis.create_context(@call_context.tenant_id)
fields = @plugin.hash_to_properties(
:order_id => '1234',
:amount => 12
)
properties = @plugin.hash_to_properties(
:create_pending_payment => false
)
form = @plugin.build_form_descriptor(@pm.kb_account_id, fields, properties, context)
form.kb_account_id.should == @pm.kb_account_id
form.form_method.should == 'GET'
form.form_url.should start_with('https://www.sandbox.paypal.com/cgi-bin/webscr')
end
end
describe Killbill::PaypalExpress::PaymentPlugin do
include ::Killbill::Plugin::ActiveMerchant::RSpec
include ::Killbill::PaypalExpress::BuildPluginHelpers
include ::Killbill::PaypalExpress::BaidSpecHelpers
context 'baid test with a single account' do
# Share the BAID
before(:all) do
# delete once here because we need to keep the initial response for later tests to find the payment processor account id
::Killbill::PaypalExpress::PaypalExpressResponse.delete_all
@payment_processor_account_id = 'default'
@plugin = build_start_paypal_plugin
baid_setup
end
include_examples 'baid_spec_common'
end
context 'baid tests with multiple accounts' do
# Share the BAID
before(:all) do
# delete once here because we need to keep the initial response for later tests to find the payment processor account id
::Killbill::PaypalExpress::PaypalExpressResponse.delete_all
@payment_processor_account_id = 'paypal_test_account'
@plugin = build_start_paypal_plugin @payment_processor_account_id
baid_setup @payment_processor_account_id
end
include_examples 'baid_spec_common'
end
end
<file_sep>/lib/paypal_express/api.rb
module Killbill #:nodoc:
module PaypalExpress #:nodoc:
class PaymentPlugin < ::Killbill::Plugin::ActiveMerchant::PaymentPlugin
THREE_HOURS_AGO = (3*3600)
def initialize
gateway_builder = Proc.new do |config|
::ActiveMerchant::Billing::PaypalExpressGateway.application_id = config[:button_source] || 'killbill_SP'
::ActiveMerchant::Billing::PaypalExpressGateway.new :signature => config[:signature],
:login => config[:login],
:password => config[:password]
end
super(gateway_builder,
:paypal_express,
::Killbill::PaypalExpress::PaypalExpressPaymentMethod,
::Killbill::PaypalExpress::PaypalExpressTransaction,
::Killbill::PaypalExpress::PaypalExpressResponse)
@ip = ::Killbill::Plugin::ActiveMerchant::Utils.ip
@private_api = ::Killbill::PaypalExpress::PrivatePaymentPlugin.new
end
def on_event(event)
# Require to deal with per tenant configuration invalidation
super(event)
#
# Custom event logic could be added below...
#
end
def authorize_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
authorize_or_purchase_payment kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context, true
end
def capture_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
# Pass extra parameters for the gateway here
options = {
# NotComplete to allow for partial captures.
# If Complete, any remaining amount of the original authorized transaction is automatically voided and all remaining open authorizations are voided.
:complete_type => 'NotComplete'
}
properties = merge_properties(properties, options)
super(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
end
def purchase_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
# by default, this call will purchase a payment
authorize_or_purchase_payment kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context
end
def void_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, properties, context)
# Pass extra parameters for the gateway here
options = {
# Void the original authorization
:linked_transaction_type => :authorize
}
properties = merge_properties(properties, options)
super(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, properties, context)
end
def credit_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
# Pass extra parameters for the gateway here
options = {}
properties = merge_properties(properties, options)
super(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
end
def refund_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
# Cannot refund based on authorizations (default behavior)
linked_transaction_type = @transaction_model.purchases_from_kb_payment_id(kb_payment_id, context.tenant_id).size > 0 ? :PURCHASE : :CAPTURE
# Pass extra parameters for the gateway here
options = {
:linked_transaction_type => linked_transaction_type
}
properties = merge_properties(properties, options)
super(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context)
end
def get_payment_info(kb_account_id, kb_payment_id, properties, context)
t_info_plugins = super(kb_account_id, kb_payment_id, properties, context)
# Should never happen...
return [] if t_info_plugins.nil?
# Completed purchases/authorizations will have two rows in the responses table (one for api_call 'build_form_descriptor', one for api_call 'purchase/authorize')
# Other transaction types don't support the :PENDING state
target_transaction_types = [:PURCHASE, :AUTHORIZE]
only_pending_transaction = t_info_plugins.find { |t_info_plugin| target_transaction_types.include?(t_info_plugin.transaction_type) && t_info_plugin.status != :PENDING }.nil?
t_info_plugins_without_pending = t_info_plugins.reject { |t_info_plugin| target_transaction_types.include?(t_info_plugin.transaction_type) && t_info_plugin.status == :PENDING }
# If its token has expired, cancel the payment and update the response row.
if only_pending_transaction
return t_info_plugins unless token_expired(t_info_plugins.last)
begin
cancel_pending_transaction(t_info_plugins.last).nil?
logger.info("Cancel pending kb_payment_id='#{t_info_plugins.last.kb_payment_id}', kb_payment_transaction_id='#{t_info_plugins.last.kb_transaction_payment_id}'")
super(kb_account_id, kb_payment_id, properties, context)
rescue => e
logger.warn("Unexpected exception while canceling pending kb_payment_id='#{t_info_plugins.last.kb_payment_id}', kb_payment_transaction_id='#{t_info_plugins.last.kb_transaction_payment_id}': #{e.message}\n#{e.backtrace.join("\n")}")
t_info_plugins
end
else
t_info_plugins_without_pending
end
end
def search_payments(search_key, offset, limit, properties, context)
# Pass extra parameters for the gateway here
options = {}
properties = merge_properties(properties, options)
super(search_key, offset, limit, properties, context)
end
def add_payment_method(kb_account_id, kb_payment_method_id, payment_method_props, set_default, properties, context)
all_properties = (payment_method_props.nil? || payment_method_props.properties.nil? ? [] : payment_method_props.properties) + properties
token = find_value_from_properties(all_properties, 'token')
if token.nil?
# HPP flow
options = {
:skip_gw => true
}
else
# Go to Paypal to get the Payer id (GetExpressCheckoutDetails call)
payment_processor_account_id = find_value_from_properties(properties, :payment_processor_account_id)
payment_processor_account_id ||= find_payment_processor_id_from_initial_call(kb_account_id, context.tenant_id, token)
payer_id = find_payer_id(token, kb_account_id, context.tenant_id, payment_processor_account_id)
options = {
:paypal_express_token => token,
:paypal_express_payer_id => payer_id,
:payment_processor_account_id => payment_processor_account_id
}
end
properties = merge_properties(properties, options)
super(kb_account_id, kb_payment_method_id, payment_method_props, set_default, properties, context)
end
def delete_payment_method(kb_account_id, kb_payment_method_id, properties, context)
# Pass extra parameters for the gateway here
options = {}
properties = merge_properties(properties, options)
super(kb_account_id, kb_payment_method_id, properties, context)
end
def get_payment_method_detail(kb_account_id, kb_payment_method_id, properties, context)
# Pass extra parameters for the gateway here
options = {}
properties = merge_properties(properties, options)
super(kb_account_id, kb_payment_method_id, properties, context)
end
def set_default_payment_method(kb_account_id, kb_payment_method_id, properties, context)
# TODO
end
def get_payment_methods(kb_account_id, refresh_from_gateway, properties, context)
# Pass extra parameters for the gateway here
options = {}
properties = merge_properties(properties, options)
super(kb_account_id, refresh_from_gateway, properties, context)
end
def search_payment_methods(search_key, offset, limit, properties, context)
# Pass extra parameters for the gateway here
options = {}
properties = merge_properties(properties, options)
super(search_key, offset, limit, properties, context)
end
def reset_payment_methods(kb_account_id, payment_methods, properties, context)
super
end
def build_form_descriptor(kb_account_id, descriptor_fields, properties, context)
jcontext = @kb_apis.create_context(context.tenant_id)
all_properties = descriptor_fields + properties
options = properties_to_hash(all_properties)
kb_account = ::Killbill::Plugin::ActiveMerchant::Utils::LazyEvaluator.new { @kb_apis.account_user_api.get_account_by_id(kb_account_id, jcontext) }
amount = (options[:amount] || '0').to_f
currency = options[:currency] || kb_account.currency
response = initiate_express_checkout(kb_account_id, amount, currency, all_properties, context)
descriptor = super(kb_account_id, descriptor_fields, properties, context)
descriptor.form_url = @private_api.to_express_checkout_url(response, context.tenant_id, options)
descriptor.form_method = 'GET'
descriptor.properties << build_property('token', response.token)
# By default, pending payments are not created for HPP
create_pending_payment = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(options, :create_pending_payment)
if create_pending_payment
payment_processor_account_id = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(options, :payment_processor_account_id)
token_expiration_period = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(options, :token_expiration_period)
custom_props = hash_to_properties(:from_hpp => true,
:token => response.token,
:payment_processor_account_id => payment_processor_account_id,
:token_expiration_period => token_expiration_period)
payment_external_key = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(options, :payment_external_key)
transaction_external_key = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(options, :transaction_external_key)
kb_payment_method = (@kb_apis.payment_api.get_account_payment_methods(kb_account_id, false, [], jcontext).find { |pm| pm.plugin_name == 'killbill-paypal-express' })
auth_mode = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(options, :auth_mode)
# By default, the SALE mode is used.
if auth_mode
payment = @kb_apis.payment_api
.create_authorization(kb_account.send(:__instance_object__),
kb_payment_method.id,
nil,
amount,
currency,
payment_external_key,
transaction_external_key,
custom_props,
jcontext)
else
payment = @kb_apis.payment_api
.create_purchase(kb_account.send(:__instance_object__),
kb_payment_method.id,
nil,
amount,
currency,
payment_external_key,
transaction_external_key,
custom_props,
jcontext)
end
descriptor.properties << build_property('kb_payment_id', payment.id)
descriptor.properties << build_property('kb_payment_external_key', payment.external_key)
descriptor.properties << build_property('kb_transaction_id', payment.transactions.first.id)
descriptor.properties << build_property('kb_transaction_external_key', payment.transactions.first.external_key)
end
descriptor
end
def process_notification(notification, properties, context)
# Pass extra parameters for the gateway here
options = {}
properties = merge_properties(properties, options)
super(notification, properties, context) do |gw_notification, service|
# Retrieve the payment
# gw_notification.kb_payment_id =
#
# Set the response body
# gw_notification.entity =
end
end
def to_express_checkout_url(response, kb_tenant_id, options = {})
payment_processor_account_id = options[:payment_processor_account_id] || :default
gateway = lookup_gateway(payment_processor_account_id, kb_tenant_id)
gateway.redirect_url_for(response.token)
end
protected
def get_active_merchant_module
::OffsitePayments.integration(:paypal)
end
private
def find_last_token(kb_account_id, kb_tenant_id)
@response_model.last_token(kb_account_id, kb_tenant_id)
end
def find_payer_id(token, kb_account_id, kb_tenant_id, payment_processor_account_id)
raise 'Could not find the payer_id: the token is missing' if token.blank?
# Go to Paypal to get the Payer id (GetExpressCheckoutDetails call)
payment_processor_account_id = payment_processor_account_id || :default
gateway = lookup_gateway(payment_processor_account_id, kb_tenant_id)
gw_response = gateway.details_for(token)
response, transaction = save_response_and_transaction(gw_response, :details_for, kb_account_id, kb_tenant_id, payment_processor_account_id)
raise response.message unless response.success?
raise "Could not find the payer_id for token #{token}" if response.payer_id.blank?
response.payer_id
end
def add_required_options(kb_payment_transaction_id, kb_payment_method_id, context, options)
payment_method = @payment_method_model.from_kb_payment_method_id(kb_payment_method_id, context.tenant_id)
options[:payer_id] ||= payment_method.paypal_express_payer_id.presence
options[:token] ||= payment_method.paypal_express_token.presence
options[:reference_id] ||= payment_method.token.presence # baid
options[:payment_type] ||= 'Any'
options[:invoice_id] ||= kb_payment_transaction_id
options[:ip] ||= @ip
end
def initiate_express_checkout(kb_account_id, amount, currency, properties, context)
properties_hash = properties_to_hash(properties)
with_baid = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(properties_hash, :with_baid)
options = {}
options[:return_url] = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(properties_hash, :return_url)
options[:cancel_return_url] = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(properties_hash, :cancel_return_url)
options[:payment_processor_account_id] = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(properties_hash, :payment_processor_account_id)
add_optional_parameters options, properties_hash, currency
amount_in_cents = amount.nil? ? nil : to_cents(amount, currency)
response = @private_api.initiate_express_checkout(kb_account_id,
context.tenant_id.to_s,
amount_in_cents,
currency,
with_baid,
options)
unless response.success?
raise "Unable to initiate paypal express checkout: #{response.message}"
end
response
end
def authorize_or_purchase_payment(kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context, is_authorize = false)
properties_hash = properties_to_hash properties
payment_processor_account_id = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(properties_hash, :payment_processor_account_id)
transaction_type = is_authorize ? :AUTHORIZE : :PURCHASE
api_call_type = is_authorize ? :authorize : :purchase
# Callback from the plugin itself (HPP flow)
if ::Killbill::Plugin::ActiveMerchant::Utils.normalized(properties_hash, :from_hpp)
token = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(properties_hash, :token)
message = {:payment_plugin_status => :PENDING,
:token_expiration_period => ::Killbill::Plugin::ActiveMerchant::Utils.normalized(properties_hash, :token_expiration_period) || THREE_HOURS_AGO.to_s}
response = @response_model.create(:api_call => :build_form_descriptor,
:kb_account_id => kb_account_id,
:kb_payment_id => kb_payment_id,
:kb_payment_transaction_id => kb_payment_transaction_id,
:transaction_type => transaction_type,
:authorization => token,
:payment_processor_account_id => payment_processor_account_id,
:kb_tenant_id => context.tenant_id,
:success => true,
:created_at => Time.now.utc,
:updated_at => Time.now.utc,
:message => message.to_json)
transaction = response.to_transaction_info_plugin(nil)
transaction.amount = amount
transaction.currency = currency
transaction
else
options = {}
add_required_options(kb_payment_transaction_id, kb_payment_method_id, context, options)
# We have a baid on file
if options[:token]
if is_authorize
gateway_call_proc = Proc.new do |gateway, linked_transaction, payment_source, amount_in_cents, options|
# Can't use default implementation: the purchase signature is for one-off payments only
gateway.authorize_reference_transaction(amount_in_cents, options)
end
else
gateway_call_proc = Proc.new do |gateway, linked_transaction, payment_source, amount_in_cents, options|
# Can't use default implementation: the purchase signature is for one-off payments only
gateway.reference_transaction(amount_in_cents, options)
end
end
else
# One-off payment
options[:token] = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(properties_hash, :token) || find_last_token(kb_account_id, context.tenant_id)
if is_authorize
gateway_call_proc = Proc.new do |gateway, linked_transaction, payment_source, amount_in_cents, options|
gateway.authorize(amount_in_cents, options)
end
else
gateway_call_proc = Proc.new do |gateway, linked_transaction, payment_source, amount_in_cents, options|
gateway.purchase(amount_in_cents, options)
end
end
end
# Find the payment_processor_id if not provided
payment_processor_account_id ||= find_payment_processor_id_from_initial_call(kb_account_id, context.tenant_id, options[:token])
options[:payment_processor_account_id] = payment_processor_account_id
# Populate the Payer id if missing
options[:payer_id] = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(properties_hash, :payer_id)
begin
options[:payer_id] ||= find_payer_id(options[:token],
kb_account_id,
context.tenant_id,
payment_processor_account_id)
rescue => e
# Maybe invalid token?
response = @response_model.create(:api_call => api_call_type,
:kb_account_id => kb_account_id,
:kb_payment_id => kb_payment_id,
:kb_payment_transaction_id => kb_payment_transaction_id,
:transaction_type => transaction_type,
:authorization => nil,
:payment_processor_account_id => payment_processor_account_id,
:kb_tenant_id => context.tenant_id,
:success => false,
:created_at => Time.now.utc,
:updated_at => Time.now.utc,
:message => { :payment_plugin_status => :CANCELED, :exception_class => e.class.to_s, :exception_message => e.message }.to_json)
return response.to_transaction_info_plugin(nil)
end
properties = merge_properties(properties, options)
dispatch_to_gateways(api_call_type, kb_account_id, kb_payment_id, kb_payment_transaction_id, kb_payment_method_id, amount, currency, properties, context, gateway_call_proc, nil, {:payer_id => options[:payer_id]})
end
end
def find_payment_processor_id_from_initial_call(kb_account_id, kb_tenant_id, token)
@response_model.initial_payment_account_processor_id kb_account_id, kb_tenant_id, token
end
def token_expired(transaction_plugin_info)
paypal_response_id = find_value_from_properties(transaction_plugin_info.properties, 'paypalExpressResponseId')
response = PaypalExpressResponse.find_by(:id => paypal_response_id)
begin
message_details = JSON.parse response.message
expiration_period = (message_details['token_expiration_period'] || THREE_HOURS_AGO).to_i
rescue
expiration_period = THREE_HOURS_AGO.to_i
end
now = Time.parse(@clock.get_clock.get_utc_now.to_s)
(now - transaction_plugin_info.created_date) >= expiration_period
end
def cancel_pending_transaction(transaction_plugin_info)
@response_model.cancel_pending_payment transaction_plugin_info
end
def add_optional_parameters(options, properties_hash, currency)
[:max_amount,
:req_billing_address,
:no_shipping,
:address_override,
:locale,
:brand_name,
:page_style,
:logo_image,
:header_image,
:header_border_color,
:header_background_color,
:background_color,
:allow_guest_checkout,
:landing_page,
:email,
:allow_note,
:callback_url,
:callback_timeout,
:allow_buyer_optin,
:callback_version,
:address,
:shipping_address,
:total_type,
:funding_sources,
:shipping_options,
# Below are options for payment details
:subtotal,
:shipping,
:handling,
:tax,
:insurance_total,
:shipping_discount,
:insurance_option_offered,
:description,
:custom,
:order_id,
:invoice_id,
:notify_url,
:items].each do |sym|
option_val = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(properties_hash, sym)
options[sym] = option_val unless option_val.nil?
end
# Special consideration for amount related options
[:max_amount,
:subtotal,
:shipping,
:handling,
:tax,
:insurance_total,
:shipping_discount].each do |sym|
if options[sym]
options[sym] = to_cents((options[sym] || '0').to_f, currency)
end
end
# Parse JSON based options including funding_source, items, shipping_options, address and shipping_address
[:funding_sources, :shipping_options, :items, :shipping_address, :address].each do |sym|
begin
options[sym] = JSON.parse options[sym] unless options[sym].nil?
rescue => e
logger.warn("Unexpected exception while parsing JSON option #{sym}: #{e.message}\n#{e.backtrace.join("\n")}")
options[sym] = nil
end
end
# Filter the options that has second level options including funding_source, items, shipping_options, address and shipping_address
[:shipping_address, :address].each do |key|
options[key] = filter_hash_options options[key], [:name, :address1, :address2, :city, :state, :country, :phone, :zip] unless options[key].nil?
end
options[:funding_sources] = filter_hash_options options[:funding_sources], [:source] unless options[:funding_sources].nil?
options[:shipping_options] = filter_array_options options[:shipping_options], [:default, :amount, :name], [:amount], currency unless options[:shipping_options].nil?
options[:items] = filter_array_options options[:items], [:name, :number, :quantity, :amount, :description, :url, :category], [:amount], currency unless options[:items].nil?
end
def filter_array_options(option, allowed_keys, amount_keys = [], currency = nil)
return nil if option.nil? || !option.is_a?(Array)
sub_options = []
option.each do |item|
next unless item.is_a?(Hash)
sub_hash = filter_hash_options item, allowed_keys, amount_keys, currency
sub_options << sub_hash unless sub_hash.nil?
end
sub_options.empty? ? nil : sub_options
end
def filter_hash_options(option, allowed_keys, amount_keys = [], currency = nil)
return nil if option.nil? || !option.is_a?(Hash)
# Because option is parsed from JSON, we need to convert to symbol keys to be used in ::Killbill::Plugin::ActiveMerchant::Utils.normalized
option.symbolize_keys!
sub_hash = {}
allowed_keys.each do |key|
sub_hash[key] = ::Killbill::Plugin::ActiveMerchant::Utils.normalized(option, key)
sub_hash[key] = to_cents((sub_hash[key] || '0').to_f, currency) if amount_keys.include?(key) && !sub_hash[key].nil?
end
sub_hash.empty? ? nil : sub_hash
end
end
end
end
<file_sep>/lib/paypal_express/private_api.rb
module Killbill #:nodoc:
module PaypalExpress #:nodoc:
class PrivatePaymentPlugin < ::Killbill::Plugin::ActiveMerchant::PrivatePaymentPlugin
def initialize(session = {})
super(:paypal_express,
::Killbill::PaypalExpress::PaypalExpressPaymentMethod,
::Killbill::PaypalExpress::PaypalExpressTransaction,
::Killbill::PaypalExpress::PaypalExpressResponse,
session)
end
# See https://cms.paypal.com/uk/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECReferenceTxns
def initiate_express_checkout(kb_account_id, kb_tenant_id, amount_in_cents=0, currency='USD', with_baid=true, options = {})
options[:currency] ||= currency
# Required arguments
options[:return_url] ||= 'http://www.example.com/success'
options[:cancel_return_url] ||= 'http://www.example.com/sad_panda'
if with_baid
options[:billing_agreement] ||= {}
options[:billing_agreement][:type] ||= 'MerchantInitiatedBilling'
options[:billing_agreement][:description] ||= 'Kill Bill billing agreement'
end
# Go to Paypal (SetExpressCheckout call)
payment_processor_account_id = options[:payment_processor_account_id] || :default
paypal_express_response = gateway(payment_processor_account_id, kb_tenant_id).setup_authorization(amount_in_cents, options)
response, transaction = save_response_and_transaction(paypal_express_response, :initiate_express_checkout, kb_account_id, kb_tenant_id, payment_processor_account_id)
response
end
def to_express_checkout_url(response, kb_tenant_id = nil, options = {})
payment_processor_account_id = options[:payment_processor_account_id] || :default
gateway = gateway(payment_processor_account_id, kb_tenant_id)
gateway.redirect_url_for(response.token)
end
end
end
end
<file_sep>/spec/spec_helper.rb
require 'bundler'
require 'paypal_express'
require 'killbill/helpers/active_merchant/killbill_spec_helper'
require 'logger'
require 'rspec'
RSpec.configure do |config|
config.color_enabled = true
config.tty = true
config.formatter = 'documentation'
end
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => 'test.db'
)
# For debugging
# ActiveRecord::Base.logger = Logger.new(STDOUT)
# Create the schema
require File.expand_path(File.dirname(__FILE__) + '../../db/schema.rb')
class PaypalExpressJavaPaymentApi < ::Killbill::Plugin::ActiveMerchant::RSpec::FakeJavaPaymentApi
def initialize(plugin)
super()
@plugin = plugin
end
def get_account_payment_methods(kb_account_id, plugin_info, properties, context)
[OpenStruct.new(:plugin_name => 'killbill-paypal-express', :id => SecureRandom.uuid)]
end
def create_purchase(kb_account, kb_payment_method_id, kb_payment_id, amount, currency, payment_external_key, payment_transaction_external_key, properties, context)
kb_payment = add_payment(kb_payment_id || SecureRandom.uuid, SecureRandom.uuid, payment_transaction_external_key, :PURCHASE)
rcontext = context.to_ruby(context)
@plugin.purchase_payment(kb_account.id, kb_payment.id, kb_payment.transactions.last.id, kb_payment_method_id, amount, currency, properties, rcontext)
kb_payment
end
def create_authorization(kb_account, kb_payment_method_id, kb_payment_id, amount, currency, payment_external_key, payment_transaction_external_key, properties, context)
kb_payment = add_payment(kb_payment_id || SecureRandom.uuid, SecureRandom.uuid, payment_transaction_external_key, :AUTHORIZE)
rcontext = context.to_ruby(context)
@plugin.authorize_payment(kb_account.id, kb_payment.id, kb_payment.transactions.last.id, kb_payment_method_id, amount, currency, properties, rcontext)
kb_payment
end
def delete_all_payments
@payments = []
end
end
| 0a6cee973bfd5eda5917a062c42b5bb67688cdea | [
"Markdown",
"Ruby"
] | 12 | Ruby | alenad/killbill-paypal-express-plugin | 2e3980e75b74720bd9e41552b36e12ddc1e7c4ba | 5a438a3e6269c4a472e2dfd1139a38527b5cca96 |
refs/heads/master | <file_sep>class NoExamples(Exception):
def __str__(self):
return 'No examples provided'
class MissingContent(Exception):
description = 'Expected content missing on the page'
def __init__(self, description=None):
if not description:
self.description = description
def __str__(self):
return self.description
<file_sep>const example = Vue.component('Example', {
template: '#example-template',
delimiters: ['[[', ']]'],
props: ['provider', 'url', 'examples', 'term'],
});
const messages = Vue.component('Messages', {
template: '#messages-template',
delimiters: ['[[', ']]'],
props: ['messages'],
});
const searchForm = Vue.component('SearchForm', {
template: '#search-form-template',
delimiters: ['[[', ']]'],
props: ['providers', 'query', 'isBusy', 'autoSearch'],
data() {
return {
term: this.query,
}
},
computed: {
enabledProviders() {
return this.providers.filter(p => p.enabled);
},
canSearch() {
return !this.isBusy
&& this.term
&& this.enabledProviders.length > 0;
}
},
watch: {
query(now, then) {
this.term = now;
}
},
methods: {
onSubmit() {
this.$emit('search', this.term, this.enabledProviders)
},
focusSearch() {
let input = document.querySelector('[name=query]');
input.focus();
input.select();
},
bindKeyboard() {
window.addEventListener('keydown', function (e) {
if (e.key === 'Escape') {
this.focusSearch();
}
}.bind(this))
},
bindPaste() {
document.addEventListener('paste', function (e) {
this.term = (e.clipboardData || window.clipboardData).getData('text').trim();
if (this.autoSearch && this.canSearch) {
this.$emit('search', this.term, this.enabledProviders);
}
}.bind(this));
},
},
mounted() {
this.bindKeyboard();
this.bindPaste();
this.focusSearch();
}
});
const examples = Vue.component('Examples', {
template: '#examples-template',
delimiters: ['[[', ']]'],
props: ['examples'],
data() {
return {
availableExamples: this.examples.map(e => ({
picked: e.examples.length > 0,
...e
}))
}
},
watch: {
examples(now, then) {
this.availableExamples = now.map(e => ({
picked: e.examples.length > 0,
...e
}))
}
},
computed: {
pickedExamples() {
return this.availableExamples.filter(ex => ex.picked)
},
},
methods: {
flattenExamples() {
return this.pickedExamples
.filter(ex => ex.examples.length)
.reduce((carry, ex) => carry.concat(ex.examples), [])
.join('\n')
.trim();
},
copyExamples() {
this.copyTextToClipboard(this.flattenExamples());
},
copyTextToClipboard(text) {
if (window.clipboardData && window.clipboardData.setData) {
// IE specific code path to prevent textarea being shown while dialog is visible.
return clipboardData.setData("Text", text);
} else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge.
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand("copy"); // Security exception may be thrown by some browsers.
} catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return false;
} finally {
document.body.removeChild(textarea);
}
}
},
onKeyDown(e) {
if (e.altKey && e.key === 'c') {
if (!this.pickedExamples.length) return;
this.copyExamples();
}
}
},
mounted() {
window.addEventListener('keydown', this.onKeyDown);
},
beforeDestroy() {
window.removeEventListener('keydown', this.onKeyDown);
}
});
const app = new Vue({
el: '#app',
delimiters: ['[[', ']]'],
data: {
providers: providers.map(name => ({name, enabled: true})),
query: '',
autoSearch: true,
isBusy: false,
examples: [],
messages: [],
timeout: null
},
computed: {
hasMessages() {
return this.messages.length > 0;
},
hasExamples() {
return this.examples.filter(ex => ex.examples.length).length > 0;
},
enabledProviders() {
return this.providers.filter(p => p.enabled);
},
},
methods: {
onSearch(term, providers) {
this.search(term, providers)
},
search: function (term, providers) {
if (!term) return;
if (!providers) return;
this.examples = [];
this.messages = [];
this.isBusy = true;
Promise.all(
providers.map(p => this.fetchExamples(p.name, term)
.then(response => {
if (response.status !== 'success') {
throw new Error(response.message);
}
this.processExamples(response.data);
})
.catch(error => {
this.processError(p.name, error.message);
}))
)
.then(() => this.isBusy = false);
},
fetchExamples(provider, term) {
return fetch(`/examples/${provider}/${term}`)
.then(res => res.json());
},
processExamples(data) {
this.examples.unshift(data);
},
processError(provider, message) {
this.messages.push({provider, message});
if (this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(() => this.messages = [], 5000);
},
bindKeyboard() {
window.addEventListener('keydown', function (e) {
if (e.altKey && e.key === 'n') {
this.$el.classList.toggle('night');
}
}.bind(this));
},
},
created() {
this.bindKeyboard();
},
});<file_sep>from requests import Response, post
from werkzeug.exceptions import ServiceUnavailable
from errors import MissingContent
def get_translations(phrase: str) -> list:
url = 'https://www2.deepl.com/jsonrpc'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0',
'Referer': 'https://www.deepl.com/translator',
}
try:
response: Response = post(url, headers=headers, json={
'jsonrpc': 2.0,
'method': 'LMT_handle_jobs',
'params': {
'jobs': [
{
'kind': 'default',
'raw_en_sentence': phrase
}
],
'lang': {
# 'user_preferred_langs': [
# 'EN',
# 'DE'
# ],
'source_lang_user_selected': 'DE',
'target_lang': 'EN'
},
# 'priority': -1
},
# 'id': 10
})
data = response.json()
translations = data['result']['translations'][0]['beams']
translations = [t['postprocessed_sentence']
for t in sorted(translations, key=lambda a: -a['score'])]
return translations
except KeyError:
raise MissingContent
except:
raise ServiceUnavailable
if __name__ == '__main__':
print(get_translations('Ich will weg'))
<file_sep>from bs4 import BeautifulSoup, Tag
from errors import NoExamples, MissingContent
import re
class WiktionaryDeutschParser:
name = '<NAME>'
def __init__(self, html: str):
self.page = BeautifulSoup(html, 'html.parser')
@property
def term(self):
title = self.page.find('h1')
if title:
return title.text
raise MissingContent('No term on the page')
@property
def examples(self):
try:
examples_title: Tag = self.page.find(title='Verwendungsbeispielsätze')
example_list = examples_title.find_next_siblings('dl')[0]
examples = example_list.text.split('\n')
return self.__clean_examples(examples)
except:
raise NoExamples
def __clean_examples(self, examples: list):
# remove [#] from examples
examples = [re.sub('(\[[^\]]+\]|)', '', e) for e in examples]
# remove quotes
examples = [re.sub('[„“]', '', e) for e in examples]
return [e.strip() for e in examples if not e.isspace()]
class DudenParser:
name = 'Duden.de'
def __init__(self, html: str):
self.page = BeautifulSoup(html, 'html.parser')
@property
def term(self):
title = self.page.find('h1')
lexem = self.page.select_one('.entry .lexem')
if not title or not lexem:
raise MissingContent('No term on the page')
return f'{title.text} ({lexem.text})'
@property
def examples(self):
try:
example_title = self.page.find('h3', string=re.compile('Beispiel'))
example_section = example_title.find_parent('section', class_='block')
example_titles = example_section.find_all('h3',
text=re.compile('(Beispiel|Wendungen|Redensarten|Sprichwörter)'))
example_wrappers = [t.next_sibling for t in example_titles if t.next_siblings]
except:
raise NoExamples
examples = []
for w in example_wrappers:
examples += self.__extract_examples_from_tag(w)
return examples
def __extract_examples_from_tag(self, w: Tag):
try:
if w.name == 'ul':
return [li.text.strip() for li in w.find_all('li')]
else:
return [w.text.strip()]
except:
return []
class LingueeParser:
name = 'Linguee'
def __init__(self, html: str):
self.page = BeautifulSoup(html, 'html.parser')
@property
def term(self):
featured_lemma = self.page.select_one('.lemma.featured .dictLink')
lemma_type = self.page.select_one('.lemma.featured .tag_wordtype')
if not featured_lemma or not lemma_type:
raise MissingContent('No term on the page')
return f'{featured_lemma.text} ({lemma_type.text})'
@property
def examples(self):
try:
examples = self.page.select('.isMainTerm .exact .example')
examples = [e.text.replace(' — ', '\n').strip()
for e in examples]
if not examples:
raise NoExamples
return examples
except:
raise NoExamples
class VerbFormenParser:
name = 'VerbFormen'
def __init__(self, html: str):
self.page = BeautifulSoup(html, 'html.parser')
@property
def term(self):
title = self.page.find('h1')
return title.text
@property
def examples(self):
examples = self.page.select('.rLst')
examples_text = [ex.text for ex in examples]
# unicode sequence is for superscript digits for footnotes
examples_text = [self.remove_non_words(ex)
for ex in examples_text]
return examples_text
@staticmethod
def remove_non_words(text: str):
# remove unicode superscript digits
return re.sub('(^\W+|\W+$|[\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079])', '', text)
class VerbFormenConjugationParser:
name = 'VerbFormen Conjugation'
def __init__(self, html: str):
self.page = BeautifulSoup(html, 'html.parser')
@property
def conjugation(self):
base_forms = self.page.select_one('#stammformen')
forms = [self.remove_non_words(f) for f in base_forms.text.strip().split('\n')]
return forms
@staticmethod
def remove_non_words(text: str):
# remove unicode superscript digits
return re.sub('(^\W+|\W+$|·|[\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079])', '', text)
class ReversoContextParser:
name = 'Reverso Context'
def __init__(self, html: str):
self.page = BeautifulSoup(html, 'html.parser')
@property
def term(self):
title = self.page.find('h1')
if title:
return title.text
raise MissingContent('No term on the page')
@property
def examples(self):
examples_list = self.page.select('#examples-content .example')
examples = []
for ex in examples_list:
try:
german = ex.select_one('.src').text.strip()
translation = ex.select_one('.trg').text.strip()
examples += [f'{german}\n{translation}']
except:
continue
return examples
class CollinsParser:
name = 'Collins Dictionary'
def __init__(self, html: str):
self.page = BeautifulSoup(html, 'html.parser')
@property
def term(self):
try:
return self.page.select_one('.h2_entry').text
except AttributeError:
raise MissingContent('No term on the page')
@property
def examples(self):
quotes = self.page.select('.content-box-examples blockquote')
examples = []
for q in quotes:
try:
text = q.text.strip()
except (KeyError, AttributeError):
continue
if text:
examples.append(text)
return examples
<file_sep>from parsers import *
from urllib.parse import quote
from slugify import slugify_de
from bs4 import BeautifulSoup
from werkzeug.exceptions import NotFound, ServiceUnavailable
from requests import get, Response
import re
def get_providers_list():
return [
'linguee',
'duden',
'wiktionary',
'verbformen',
'reverso',
'collins',
]
def get_html(url: str, headers=None):
if not headers:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3496.0 Safari/537.36'
}
response: Response = get(url, headers=headers)
if 400 <= response.status_code < 500:
raise NotFound
elif 500 <= response.status_code:
raise ServiceUnavailable
return response.content
def get_wiktionary(term):
url = f'https://de.wiktionary.org/wiki/{quote(term)}'
return WiktionaryDeutschParser(get_html(url)), url
def get_duden(term):
url = f'https://www.duden.de/rechtschreibung/{slugify_de(term)}'
search_url = f'https://www.duden.de/suchen/dudenonline/{quote(term)}'
try:
html = get_html(url)
except NotFound:
html = get_html(search_url)
search_page = BeautifulSoup(html, 'html.parser')
first_link = search_page.find('a', href=re.compile('rechtschreibung'))
if not first_link:
raise NotFound
url = first_link.attrs['href']
html = get_html(url)
return DudenParser(html), url
def get_linguee(term):
url = f'https://www.linguee.de/deutsch-englisch/uebersetzung/{quote(term)}.html'
html = get_html(url)
page = BeautifulSoup(html, 'html.parser')
main_term = page.select_one('.isMainTerm')
if not main_term:
raise NotFound
return LingueeParser(html), url
def get_verbformen(term: str):
if not term.endswith('n'):
raise NotFound('Not a verb')
url = f'https://www.verbformen.com/conjugation/examples/{quote(term)}.htm'
return VerbFormenParser(get_html(url)), url
def get_verbformen_conjugation(term: str):
if not term.endswith('n'):
raise NotFound('Not a verb')
url = f'https://www.verbformen.de/konjugation/?w={quote(term)}'
return VerbFormenConjugationParser(get_html(url)), url
def get_reverso(term: str):
url = f'http://context.reverso.net/translation/german-english/{quote(term)}'
html = get_html(url)
return ReversoContextParser(html), url
def get_collins(term: str):
url = f'https://www.collinsdictionary.com/de/worterbuch/deutsch-englisch/{quote(term)}'
html = get_html(url)
return CollinsParser(html), url
<file_sep>from flask import Flask, render_template, abort, redirect, request, url_for, jsonify
import providers
from werkzeug.exceptions import NotFound, ServiceUnavailable, BadRequest
from errors import NoExamples, MissingContent
import deepl
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html', providers=providers.get_providers_list())
@app.route('/examples/<provider_name>/<term>')
def examples_json(provider_name, term):
try:
term = term.strip()
assert term
provider_name = provider_name.strip()
for p in providers.get_providers_list():
if provider_name == p:
provider, url = getattr(providers, f'get_{p}')(term)
break
return jsonify(status='success', data={
'term': provider.term,
'url': url,
'provider': provider.name,
'examples': provider.examples
})
except NotFound:
raise NotFound(f'No relevant results for „{term}“')
@app.route('/conjugation/<verb>')
def declension(verb: str):
provider, url = providers.get_verbformen_conjugation(verb)
return jsonify(status='success', data={
'conjugation': provider.conjugation,
'conjugation_str': ', '.join(provider.conjugation),
'provider': provider.name
})
@app.route('/translate/<phrase>')
def translate(phrase: str):
phrase = phrase.strip()
assert phrase
translations = deepl.get_translations(phrase)
return jsonify(status='success', data=translations)
@app.errorhandler(AssertionError)
def handle_validation_error(error):
return jsonify(status='fail', message=str(error)), 400
@app.errorhandler(ServiceUnavailable)
def handle_service_error(error):
return jsonify(status='fail', message=str(error)), 503
@app.errorhandler(NoExamples)
@app.errorhandler(NotFound)
@app.errorhandler(MissingContent)
def handle_not_found_error(error):
return jsonify(status='fail', message=str(error) or error.description), 404
if __name__ == '__main__':
app.run(debug=True)
| cf931a82575d1308da9ec800c9315664f04a38c9 | [
"JavaScript",
"Python"
] | 6 | Python | abdusco/german-helper | 7b71029aa27e56e21420da07598da2ace168c65a | 1d6d833aaf9c112460fe3fc0329e8316e140b959 |
refs/heads/master | <repo_name>KLS-Gogte-Institute-of-Technology-bgm/sd-lab-project-5thsem_sd_lab_incognito<file_sep>/README.md
[](https://classroom.github.com/online_ide?assignment_repo_id=293093&assignment_repo_type=GroupAssignmentRepo)
<h1><b>Parking Lot Management System </b></h1>
<p>As we know, due to increase in number of cars and limited spots ,parking the cars is getting difficult. In metropolitan cities, car parking has become a major concern in all busy areas, and a good traffic system need a good parking system. In this project ,we have made a system where it is possible to reserve a parking spot ahead in time as to reduce the need to search parking spots and the unnecessary rush. This parking lot does not require a parking attendant. It will save a lot our time and it keeps all the records properly.The system has backup files and the system is secured.
<h3><b>Built with</b></h3>
PHP<br>
CSS<br>
Javascript<br>
MySQL
<h3>Authors</h3>
<NAME> -2GI18CS009<br>
<NAME> - 2GI18CS010<br>
<NAME> - 2GI18CS016<br>
<file_sep>/inc/footer.php
<footer>
<p>Car Park Management | Copyright 2020</p>
</footer>
| 25d1eea1b9f1d8fa40e5d329b0ef521185193112 | [
"Markdown",
"PHP"
] | 2 | Markdown | KLS-Gogte-Institute-of-Technology-bgm/sd-lab-project-5thsem_sd_lab_incognito | b14c5b6430cc607822b1e8322aa33758e238e83b | 4bec59a9addc62ef5e2116f4aadb99cf1d632eae |
refs/heads/master | <repo_name>yoovin/OhMyPolice<file_sep>/README.md
## 군대가요...
대한민국 남성 화이팅...<file_sep>/src/App.js
import React, { Component } from 'react'
import './App.css'
import Main from './components/Main'
// import seafrog from './Img/seafrog.png'
// import seafrog from './Img/wseafrog.png'
export default class App extends Component {
render() {
return (
<div className="out">
<div className="in">
<Main/>
{/* <img className="seafrog" src={seafrog} width="100px" alt="frog"/> */}
{/* <span className="nextButton">다음</span> */}
</div>
</div>
)
}
}
| e28a7a2ac7cd6729f5626ab7fce784e7271d8329 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | yoovin/OhMyPolice | 1c15eff92cf3e4c2bd237f70236dfa8b4e9b2e61 | 012eff35943a24d34e74305a7769b92e7a8d8449 |
refs/heads/master | <file_sep>def ask_age
puts "age?"
age gets.to_i
end
def ticket_price(age:)
if age < 17
puts "10kr"
elsif age > 64
puts "15kr"
else puts "20kr"
end
end
| 45e028cb8aa3eb73189985eeeea7401ebd5f5dc6 | [
"Ruby"
] | 1 | Ruby | itgsod-Alexander-Iglebk/Biljettautomat-1 | 858a3f806c6917440f0bae9706dfaad25ddeaa15 | be5240e0a3ef1977f2d91dc7468e78bb2187d23b |
refs/heads/main | <file_sep># Calorie-Tracker-BE
Solo Project 2 (Backend)
## Calorie Tracker App
**Calorie tracker is an app that helps users to keep track of their daily calorie intake.**
## About this app
How much you eat matters more than what you eat when it comes to losing weight or building muscles. It is vital to keep track of daily calorie intake and macro nutrients(Carbs, Fat, Protein). With this app, tracking food is fast and easy with this app.
## Wireframes
<details>
<summary>Click to see wireframes</summary>





</details>
## User Story
- When user loads the first page, user sees login, signup buttons
- User creates profile with name, email, password, username, sex, height, and weight.
- When user logs in, dashboard(account editor, calorie log), signout link are shown, user is redirected to a new page where they can search, create, save meals(breakfast, lunch, dinner).
- User can edit/delete account in account editor tab.
- User can search food for nutrition information – nutrition information will be shown.
- User can save nutrition information and, create and save meals.
- User can edit/delete their saved meals
## ERD

## HTTP Routes
[Users]
| Method | Path | Purpose |
|--------|------------------------|-----------------------------|
| GET | /users/:id | Get user profile info |
| GET | /users/:userId/getfood | Get saved food from user |
| POST | /users | Sign-up |
| POST | /users/login | Log-in |
| PUT | /users/:id/edit | Edit user profile info |
| DELETE | /users/:id | Delete user account |
| DELETE | /users/:userId/delete | Delete saved food from user |
[Foods]
| Method | Path | Purpose |
|--------|------------------------|---------------------------------|
| GET | /food/search/:foodname | Get food info from external api |
| POST | /food/:userId/save | User can save food |
## MVP checklist
- Can user sign up, sign in and sing out?
- Can user get nutrition information?
- Can user save and delete nutrition info?
- Can user see saved nutrition info?
## Stretch goals
- User can delete their account.
- User can see their daily calorie goals and the remainder of it.
- User can create meals with saved food.
## Work flow
<details>
<summary>Click to see </summary>
1. Work on backend and frontend synchronously<
2. Framework with frontend HTML, CSS
3. Setup (npm i, sequelize i, etc)
4. Make database(sequelize db:create, sequelize db:migrate), add constraints/validations, associations
5. Set server.js and run servers in both frontend and backend.
6. Controllers and Routers
7. CRUD
<p>[Create]</p>
- Signup
- Signin
- Save food info
<p>[Read]</p>
- User profile info
- Saved food from user
- axios request
<p>[Update]</p>
- user profile info edit
<p>[Delete]</p>
- Delete user account
- Delete saved food
8. Signout functionality
9. Styling up browser with HTML, CSS
</details>
## API resourse
[Edamam]
https://developer.edamam.com/food-database-api-docs<file_sep>const userController = require('../controllers/userController')
const express = require('express')
const userRoutes = express.Router()
///////////////////////////////////////////////
userRoutes.get('/:id', userController.getUser) //get user
userRoutes.get('/:userId/getfood', userController.getFood) //pull saved food from user
userRoutes.post('/', userController.createUser) //signup
userRoutes.post('/login', userController.login) //login
userRoutes.put('/:id/edit', userController.update)
userRoutes.delete('/:id', userController.delete) //Delete user account
userRoutes.delete('/:userId/delete', userController.deleteFood) //Delete saved food from user
//////////////////////////////////////////////
module.exports = userRoutes;<file_sep>const express = require('express')
const app = express()
const rowdy = require ('rowdy-logger')
const routesReport = rowdy.begin(app)
app.use(express.json())
app.use(require('cors')())
const morgan = require('morgan')//morgan is like console.log(on terminal)
app.use(morgan('tiny'))
//////////////////////////////write code below///////////////////////////////
const userRoutes = require('./routes/userRoutes')
const foodRoutes = require('./routes/foodRoutes')
//userRoutes
app.use('/users', userRoutes) //need to use just one app.use per route!
//foodRoutes
app.use('/food', foodRoutes)
//////////////////////////////write code above///////////////////////////////
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log(`backend server running on ${PORT}!`);
routesReport.print()
})
<file_sep>const models = require('../models')
const userController = {}
//signup
userController.createUser = async (req, res) => {
try {
const user = await models.user.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: <PASSWORD>,
height: req.body.height,
weight: req.body.weight
})
res.json({message: 'New user created', user})
} catch (error) {
//Validation error messages
if (error.errors[0].path === 'firstName') {
res.json({error: 'First name is required'})
}else if(error.errors[0].path === 'lastName') {
res.json({error: 'Last name is required'})
}else if(error.errors[0].path === 'password') {
res.json({error: 'Password is required'})
}else if(error.errors[0].path === 'height') {
res.json({error: 'Height is required'})
}else if(error.errors[0].path === 'weight') {
res.json({error: 'weight is required'})
}else{
res.status(400)
res.json({error: 'Email is already used by someone'})
}
}
}
//signin
userController.login = async (req, res) => {
try {
const user = await models.user.findOne({
where:{
email: req.body.email
}
})
// console.log(user)
if(user.password === req.body.<PASSWORD>){
res.json({message: 'login successful', user: user})
}else{
res.status(401)
res.json({error:'incorrect password'})
}
} catch (error) {
res.status(400)
res.json({error: 'login failed'})
}
}
//Get user info
userController.getUser = async (req, res) => {
try {
let user = await models.user.findOne({
where:{
id: req.params.id
}
})
res.json({user})
} catch (error) {
res.json({error})
}
}
// Find saved food from user
userController.getFood = async (req, res) => {
try {
let user = await models.user.findOne({
where:{
id: req.params.userId
}
})
let food = await user.getFood()
// console.log('savedFood', food)
res.json(food)
} catch (error) {
res.json({error})
}
}
//Delete user account
userController.delete = async (req, res) => {
try {
let user = await models.user.findOne({
where: {
id: req.params.id
}
})
await user.destroy()
res.json({user, message: 'Account deleted'})
} catch (error) {
res.json({error})
}
}
//Delete saved food
userController.deleteFood = async (req, res) => {
try {
let user = await models.user.findOne({
where:{
id: req.params.userId
}
})
let food = await user.getFood()
await user.removeFood(food)
// console.log(food)
res.json({user, food})
} catch (error) {
res.json({error})
}
}
//user info update
userController.update = async (req, res) => {
try {
let updates = req.body
let user = await models.user.findOne({
where:{
id: req.params.id
}
})
let finalStep = await user.update(updates)
res.json({finalStep})
} catch (error) {
res.json.error
}
}
module.exports = userController;<file_sep>const foodController = require('../controllers/foodController')
const express = require('express');
const foodRoutes = express.Router()
foodRoutes.get('/search/:foodname', foodController.search) //food search
foodRoutes.post('/:userId/save', foodController.save) //save food to users
foodRoutes.get('/search/foodId', foodController.searchOne)
module.exports = foodRoutes; | ae93b3c93bfb47cb8195391f63312ee3ab40efec | [
"Markdown",
"JavaScript"
] | 5 | Markdown | Chul0/Calorie-Tracker-BE | 39fe0cdf5c299b40fbf0a5c1704052445c661491 | 939ab7b0ea351e668f0266dc34747f9c22deb5e6 |
refs/heads/master | <file_sep>package exercises;
import java.util.ArrayList;
import java.util.Scanner;
import jdk.nashorn.api.tree.WhileLoopTree;
public class Prezzi {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Double> al = new ArrayList<>();
int z = 0;
do {
System.out.println("1. Nuevo precio");
System.out.println("2. Precio medio");
System.out.println("3. Precio maximo");
System.out.println("4. Precio minimo");
System.out.println("5. Mostrar los precios");
System.out.println("6. Salir");
System.out.print("Dame opcion: ");
Scanner sc = new Scanner(System.in);
z = sc.nextInt();
switch (z) {
case 1:
nuevoPrecio(al);
break;
case 2:
precioMedio(al);
break;
case 3:
precioMax(al);
break;
case 4:
precioMin(al);
break;
case 5:
showPrecios(al);
break;
case 6:
System.out.println("Saliendo...");
z=7;
break;
default:
System.out.println("Opcion errada");
}
}while (z <= 6);
}
public static void nuevoPrecio(ArrayList<Double> a) {
Scanner sc = new Scanner(System.in);
System.out.print("Dame nuevo precio: ");
double precio = sc.nextDouble();
a.add(precio);
}
public static void precioMedio(ArrayList<Double> a) {
double suma = 0;
for (Double d : a) {
suma += d;
}
System.out.printf("Prezzo medio: %.2f\n", suma / a.size());
}
public static void precioMax(ArrayList<Double> a) {
Double arr[] = new Double[a.size()];
arr = a.toArray(arr);
int i, j; double max =0;
for (i = 0; i < arr.length; i++) {
for (j = 1; j < arr.length; j++) {
if (arr[i] < arr[j])
arr[i] = arr[j];
max = arr[i];
}
}
System.out.println("Max: "+max);
}
public static void precioMin(ArrayList<Double> a) {
Double arr[] = new Double[a.size()];
arr = a.toArray(arr);
int i, j; double min = 0;
for (i = 0; i < arr.length; i++) {
for (j = 1; j < arr.length; j++) {
if (arr[i] < arr[j])
arr[j] = arr[i];
min = arr[j];
}
}
System.out.println("Min: "+min);
}
public static void showPrecios(ArrayList<Double> a) {
for (Double d : a) {
System.out.println("Todos los precios: " + d);
}
}
}
| 4bd323812079e443182cd9b426ba1c54985ae730 | [
"Java"
] | 1 | Java | Andreolo69/Varios | 6845b93960c53794d68abd3a5bfa8330d7a9abde | be0246c5f4228e91a22a46eb6cdeab4f0a91989c |
refs/heads/master | <repo_name>justinhschaaf/JusaonvsCraftingTweaks<file_sep>/src/main/java/net/jusanov/jusanovscraftingtweaks/common/Reference.java
package net.jusanov.jusanovscraftingtweaks.common;
public class Reference {
public static final String MODID = "dmscraftingtweaks";
public static final String NAME = "DragonMouth's Crafting Tweaks";
public static final String VERSION = "1.10.2-1.0.0.0-beta";
public static final String ACCEPTED_VERSIONS = "[1.10,1.10.2]";
public static final String CLIENT_PROXY_CLASS = "net.dragonmouth.dmscraftingtweaks.proxy.ClientProxy";
public static final String SERVER_PROXY_CLASS = "net.dragonmouth.dmscraftingtweaks.proxy.ServerProxy";
}
<file_sep>/src/main/java/net/jusanov/jusanovscraftingtweaks/handlers/LogHandler.java
package net.jusanov.jusanovscraftingtweaks.handlers;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.jusanov.jusanovscraftingtweaks.common.Reference;
public class LogHandler {
public static final Logger logHandler = LogManager.getLogger(Reference.NAME);
}
<file_sep>/src/main/java/net/jusanov/jusanovscraftingtweaks/handlers/ConfigHandler.java
package net.jusanov.jusanovscraftingtweaks.handlers;
import java.io.File;
import net.minecraft.init.Items;
import net.minecraftforge.common.config.Configuration;
public class ConfigHandler {
public static Configuration config;
// Create the variables for the config settings
public static boolean horseArmorCraftingRecipesEnabled;
public static boolean horseArmorCraftingUsesSaddle;
public static boolean saddleCraftingRecipeEnabled;
public static boolean alternateCarrotOnAStickCrafting;
public static boolean nametagCraftingRecipeEnabled;
public static boolean endCrystalCraftingRecipeEnabled;
public static boolean endCrystalCraftingUsesEmeralds;
public static boolean endCrystalCraftingUsesEnderPearls;
public static boolean dragonsBreathCraftingRecipesEnabled;
public static boolean dragonEggCraftingRecipeEnabled;
public static boolean dragonEggCraftingUsesMoreObsidian;
public static boolean dragonEggDuplicationEnabled;
public static boolean recordCraftingRecipesEnabled;
// Not working properly
//public static String recordMaterial;
// To work on later
/*public static boolean recordCraftingUsesCoalBlocks;
public static boolean recordCraftingUsesCoal;
public static boolean recordCraftingUsesObsidian;
public static boolean recordCraftingUsesClay;
public static boolean recordCraftingUsesWool;
public static boolean recordCraftingUsesCarpet;*/
public static boolean skullSkeletonCraftingRecipeEnabled;
public static boolean skullSkeletonCraftingUsesDiamond;
public static boolean skullWitherSkeletonCraftingRecipeEnabled;
public static boolean skullCreeperCraftingRecipeEnabled;
public static boolean skullZombieCraftingRecipeEnabled;
public static boolean skullDragonCraftingRecipeEnabled;
public static boolean rottenFleshToLeatherSmelting;
public static boolean boneToBoneMealSmelting;
public static boolean wheatToBreadSmelting;
public static boolean slimeballToMagmaCreamSmelting;
public static boolean enderEyeToEnderPearlSmelting;
public static void init(File file) {
LogHandler.logHandler.info("Beginning config initialization!");
config = new Configuration(file);
syncConfig();
LogHandler.logHandler.info("Config initialization complete!");
}
public static void syncConfig() {
String category;
LogHandler.logHandler.info("Creating and registering the Horse/Animals category for the config!");
category = "Horses/Animals";
config.addCustomCategoryComment(category, "Horses/Animals");
horseArmorCraftingRecipesEnabled = config.getBoolean("EnableHorseArmorCraftingRecipes", category, true, "Enable or disable the crafting recipes for horse armor.");
horseArmorCraftingUsesSaddle = config.getBoolean("HorseArmorCraftingUsesSaddle", category, false, "Instead of wool, the horse armor crafting recipes will use a saddle.");
saddleCraftingRecipeEnabled = config.getBoolean("EnableSaddleCraftingRecipe", category, true, "Enable or disable the crafting recipes for saddles.");
alternateCarrotOnAStickCrafting = config.getBoolean("AlternateCarrotOnAStickCrafting", category, true, "Allows a carrot on a stick to also be crafted by using a carrot in the fishing rod recipe. NOTE: DOES NOT REPLACE THE OLD RECIPE!");
nametagCraftingRecipeEnabled = config.getBoolean("NametagCraftingRecipeEnabled", category, true, "Enable or disable the crafting recipes for name tags.");
LogHandler.logHandler.info("Creating and registering the Dragon category for the config!");
category = "Dragon";
config.addCustomCategoryComment(category, "Dragon");
endCrystalCraftingRecipeEnabled = config.getBoolean("EndCrystalCraftingRecipeEnabled", category, true, "Enable or disable the crafting recipe for the End Crystals.");
endCrystalCraftingUsesEmeralds = config.getBoolean("EndCrystalCraftingUsesEmeralds", category, false, "Instead of diamonds, the End Crystal crafting recipe will use emeralds.");
endCrystalCraftingUsesEnderPearls = config.getBoolean("EndCrystalCraftingUsesEnderPearls", category, true, "Instead of diamonds, the End Crystal crafting recipe will use ender pearls.");
dragonsBreathCraftingRecipesEnabled = config.getBoolean("DragonsBreathCraftingRecipesEnabled", category, true, "Enable or disable the crafting recipes for the Dragon's Breath.");
dragonEggCraftingRecipeEnabled = config.getBoolean("DragonEggCraftingRecipeEnabled", category, true, "Enable or disable the crafting recipe for the Dragon Egg");
dragonEggCraftingUsesMoreObsidian = config.getBoolean("DragonEggCraftingUsesMoreObsidian", category, true, "Instead of 5 obsidian, 7 obsidian will be used in the Dragon Egg crafting recipe.");
dragonEggDuplicationEnabled = config.getBoolean("DragonEggDuplicationEnabled", category, false, "Enable or disable a crafting recipe that allows the Dragon Egg to be duplicated.");
LogHandler.logHandler.info("Creating and registering the Records category for the config!");
category = "Records";
config.addCustomCategoryComment(category, "Records");
recordCraftingRecipesEnabled = config.getBoolean("RecordCraftingRecipesEnabled", category, true, "Enable or disable the crafting recipes for records.");
// Not working properly
//recordMaterial = config.getString("RecordMaterial", category, "Items.FLINT", "Change the material used to craft the record material (e.g. Blocks.COAL_BLOCK, Items.FLINT).");
// To work on later
/*recordCraftingUsesCoalBlocks = config.getBoolean("RecordCraftingUsesCoalBlocks", category, false, "Instead of flint, use coal blocks for the record crafting recipes.");
recordCraftingUsesCoal = config.getBoolean("RecordCraftingUsesCoal", category, false, "Instead of flint, use coal for the record crafting recipes.");
recordCraftingUsesObsidian = config.getBoolean("RecordCraftingUsesObsidian", category, false, "Instead of flint, use obsidian for the record crafting recipes.");
recordCraftingUsesClay = config.getBoolean("RecordCraftingUsesClay", category, false, "Instead of flint, use obsidian for the record crafting recipes.");
recordCraftingUsesWool = config.getBoolean("RecordCraftingUsesWool", category, false, "Instead of flint, use black wool for the record crafting recipes.");
recordCraftingUsesCarpet = config.getBoolean("RecordCraftingUsesCarpet", category, false, "Instead of flint, use black carpet for the record crafting recipes.");*/
LogHandler.logHandler.info("Creating and registering the Skulls category for the config!");
category = "Skulls";
config.addCustomCategoryComment(category, "Skulls");
skullSkeletonCraftingRecipeEnabled = config.getBoolean("SkeletonSkullCraftingRecipeEnabled", category, true, "Enable or disable the crafting recipe for the skeleton skull.");
skullSkeletonCraftingUsesDiamond = config.getBoolean("SkeletonSkullCraftingUsesDiamond", category, false, "Instead of a nether star, a diamond will be used in the skeleton skull crafting recipe.");
skullWitherSkeletonCraftingRecipeEnabled = config.getBoolean("WitherSkeletonSkullCraftingRecipeEnabled", category, true, "Enable or disable the crafting recipe for the wither skeleton skull.");
skullCreeperCraftingRecipeEnabled = config.getBoolean("CreeperSkullCraftingRecipeEnabled", category, true, "Enable or disable the crafting recipe for the creeper head.");
skullZombieCraftingRecipeEnabled = config.getBoolean("ZombieSkullCraftingRecipeEnabled", category, true, "Enable or disable the crafting recipe for the zombie head.");
skullDragonCraftingRecipeEnabled = config.getBoolean("DragonSkullCraftingRecipeEnabled", category, true, "Enable or disable the crafting recipe for the dragon head.");
LogHandler.logHandler.info("Creating and registering the Smelting category for the config!");
category = "Smelting";
config.addCustomCategoryComment(category, "Smelting");
rottenFleshToLeatherSmelting = config.getBoolean("RottenFleshToLeatherSmelting", category, true, "Enable or disable the smelting of rotten flesh into leather.");
boneToBoneMealSmelting = config.getBoolean("BoneToBoneMealSmelting", category, true, "Enable or disable the smelting of bones into bone meal.");
wheatToBreadSmelting = config.getBoolean("WheatToBreadSmelting", category, true, "Enable or disable the smelting of 3 wheat into bread.");
slimeballToMagmaCreamSmelting = config.getBoolean("SlimeballToMagmaCreamSmelting", category, true, "Enable or disable the smelting of a slime ball into magma cream.");
enderEyeToEnderPearlSmelting = config.getBoolean("EyeOfEnderToEnderPearlSmelting", category, true, "Enable or disable the smelting of eyes of ender into ender pearls.");
config.save();
LogHandler.logHandler.info("Saved the config.");
}
}
<file_sep>/README.md
# JusanovsCraftingTweaks <img src="https://img.shields.io/badge/status-discontinued-red.svg">
A mod that makes a few additions and subtractions to the crafting of Minecraft.
<file_sep>/src/main/java/net/jusanov/jusanovscraftingtweaks/proxy/CommonProxy.java
package net.jusanov.jusanovscraftingtweaks.proxy;
public class CommonProxy {
public void init() {
// Nothing here yet!
}
}
<file_sep>/src/main/java/net/jusanov/jusanovscraftingtweaks/crafting/CraftingManager.java
package net.jusanov.jusanovscraftingtweaks.crafting;
import net.jusanov.jusanovscraftingtweaks.handlers.ConfigHandler;
import net.jusanov.jusanovscraftingtweaks.handlers.LogHandler;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.ShapelessOreRecipe;
public class CraftingManager {
public static void register() {
LogHandler.logHandler.info("Starting to register Crafting Recipes!");
/*
* HORSE/ANIMAL CRAFTING RECIPES
*/
// Horse Armor Recipes
if (ConfigHandler.horseArmorCraftingRecipesEnabled == true) {
if (ConfigHandler.horseArmorCraftingUsesSaddle == true) {
LogHandler.logHandler.info("Starting to register Horse Armor Recipes using a saddle!");
GameRegistry.addShapedRecipe(new ItemStack(Items.IRON_HORSE_ARMOR, 1, 0), " I", "ISI", "ILI", 'I', Items.IRON_INGOT, 'L', Items.LEATHER, 'S', Items.SADDLE);
GameRegistry.addShapedRecipe(new ItemStack(Items.GOLDEN_HORSE_ARMOR, 1, 0), " G", "GSG", "GLG", 'G', Items.GOLD_INGOT, 'L', Items.LEATHER, 'S', Items.SADDLE);
GameRegistry.addShapedRecipe(new ItemStack(Items.DIAMOND_HORSE_ARMOR, 1, 0), " D", "DSD", "DLD", 'D', Items.DIAMOND, 'L', Items.LEATHER, 'S', Items.SADDLE);
LogHandler.logHandler.info("Finished registering Horse Armor Recipes using a saddle!");
}
else {
LogHandler.logHandler.info("Starting to register Horse Armor Recipes!");
GameRegistry.addShapedRecipe(new ItemStack(Items.IRON_HORSE_ARMOR, 1, 0), " I", "IWI", "ILI", 'I', Items.IRON_INGOT, 'L', Items.LEATHER, 'W', Blocks.WOOL);
GameRegistry.addShapedRecipe(new ItemStack(Items.GOLDEN_HORSE_ARMOR, 1, 0), " G", "GWG", "GLG", 'G', Items.GOLD_INGOT, 'L', Items.LEATHER, 'W', Blocks.WOOL);
GameRegistry.addShapedRecipe(new ItemStack(Items.DIAMOND_HORSE_ARMOR, 1, 0), " D", "DWD", "DLD", 'D', Items.DIAMOND, 'L', Items.LEATHER, 'W', Blocks.WOOL);
LogHandler.logHandler.info("Finished registering Horse Armor Recipes!");
}
}
else {
LogHandler.logHandler.info("Horse Armor Crafting Recipes are DISABLED in the config! Moving on!");
}
// Saddle Recipe
if (ConfigHandler.saddleCraftingRecipeEnabled == true) {
LogHandler.logHandler.info("Started to register the Saddle recipe!");
GameRegistry.addShapedRecipe(new ItemStack(Items.SADDLE, 1, 0), "LCL", "LWL", "I I", 'L', Items.LEATHER, 'C', Blocks.CARPET, 'W', Blocks.WOOL, 'I', Items.IRON_INGOT);
LogHandler.logHandler.info("Finished registering the Saddle recipe!");
}
else {
LogHandler.logHandler.info("Saddle Crafting Recipes are DISABLED in the config! Moving on!");
}
// Carrot on a Stick Recipe
if (ConfigHandler.alternateCarrotOnAStickCrafting == true) {
LogHandler.logHandler.info("Started to register the Alternate Carrot on a Stick recipe!");
GameRegistry.addShapedRecipe(new ItemStack(Items.CARROT_ON_A_STICK, 1, 0), " S", " ST", "S C", 'S', Items.STICK, 'C', Items.CARROT, 'T', Items.STRING);
LogHandler.logHandler.info("Finished registering the Alternate Carrot on a Stick recipe!");
}
else {
LogHandler.logHandler.info("Alternate Carrot on a Stick recipe is DISABLED in the config! Moving on!");
}
// Nametag Recipe
if (ConfigHandler.nametagCraftingRecipeEnabled == true) {
LogHandler.logHandler.info("Started to register the Nametag recipe!");
GameRegistry.addShapedRecipe(new ItemStack(Items.NAME_TAG, 1, 0), " S", " P ", "P ", 'S', Items.STRING, 'P', Items.PAPER);
LogHandler.logHandler.info("Finished registering the Nametag recipe!");
}
else {
LogHandler.logHandler.info("Nametag Crafting Recipe is DISABLED in the config! Moving on!");
}
/*
* DRAGON CRAFTING RECIPES
*/
// Ender Crystal Recipe
if (ConfigHandler.endCrystalCraftingRecipeEnabled == true) {
if (ConfigHandler.endCrystalCraftingUsesEmeralds == true) {
LogHandler.logHandler.info("Starting to register the Ender Crystal recipe using emeralds!");
GameRegistry.addShapedRecipe(new ItemStack(Items.END_CRYSTAL, 1, 0), "GEG", "ESE", "GEG", 'G', Blocks.GLASS, 'E', Items.EMERALD, 'S', Items.NETHER_STAR);
LogHandler.logHandler.info("Finished registering the Ender Crystal recipe using emeralds!");
}
if (ConfigHandler.endCrystalCraftingUsesEnderPearls == true) {
LogHandler.logHandler.info("Starting to register the Ender Crystal recipe using ender pearls!");
GameRegistry.addShapedRecipe(new ItemStack(Items.END_CRYSTAL, 1, 0), "GEG", "ESE", "GEG", 'G', Blocks.GLASS, 'E', Items.ENDER_PEARL, 'S', Items.NETHER_STAR);
LogHandler.logHandler.info("Finished registering the Ender Crystal recipe using ender pearls!");
}
else {
LogHandler.logHandler.info("Starting to register the Ender Crystal recipe!");
GameRegistry.addShapedRecipe(new ItemStack(Items.END_CRYSTAL, 1, 0), "GDG", "DSD", "GDG", 'G', Blocks.GLASS, 'D', Items.DIAMOND, 'S', Items.NETHER_STAR);
LogHandler.logHandler.info("Finished registering the Ender Crystal recipe!");
}
}
else {
LogHandler.logHandler.info("The Ender Crystal crafting recipe is DISABLED in the config! Moving on!");
}
// Dragon's Breath recipe
if (ConfigHandler.dragonsBreathCraftingRecipesEnabled == true) {
LogHandler.logHandler.info("Starting to register the Dragon's Breath recipes!");
GameRegistry.addShapedRecipe(new ItemStack(Items.DRAGON_BREATH, 1, 0), " W ", "GEG", "GGG", 'G', Blocks.GLASS, 'W', Blocks.LOG, 'E', Items.END_CRYSTAL);
GameRegistry.addShapelessRecipe(new ItemStack(Items.DRAGON_BREATH, 1, 0), new ItemStack(Items.GLASS_BOTTLE, 1, 0), new ItemStack(Items.END_CRYSTAL, 1, 0));
LogHandler.logHandler.info("Finished registering the Dragon's Breath recipes!");
}
else {
LogHandler.logHandler.info("The Dragon's Breath crafting recipes are DISABLED in the config! Moving on!");
}
// Dragon Egg Recipe
if (ConfigHandler.dragonEggCraftingRecipeEnabled == true) {
if (ConfigHandler.dragonEggCraftingUsesMoreObsidian == true) {
LogHandler.logHandler.info("Starting to register the DragonEgg recipe using more obsidian!");
GameRegistry.addShapedRecipe(new ItemStack(Blocks.DRAGON_EGG, 1, 0), "OOO", "OCO", "OEO", 'O', Blocks.OBSIDIAN, 'C', Items.END_CRYSTAL, 'E', Items.EGG);
LogHandler.logHandler.info("Finished registering the DragonEgg recipe using more obsidian!");
}
else {
LogHandler.logHandler.info("Starting to register the DragonEgg recipe!");
GameRegistry.addShapedRecipe(new ItemStack(Blocks.DRAGON_EGG, 1, 0), " O ", "OCO", "OEO", 'O', Blocks.OBSIDIAN, 'C', Items.END_CRYSTAL, 'E', Items.EGG);
LogHandler.logHandler.info("Finished registering the DragonEgg recipe!");
}
}
else {
LogHandler.logHandler.info("The Dragon Egg crafting recipe is DISABLED in the config! Moving on!");
}
// Dragon Egg Duplication Recipe
if (ConfigHandler.dragonEggDuplicationEnabled == true) {
LogHandler.logHandler.info("Starting to register the DragonEgg Duplication recipe!");
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.DRAGON_EGG, 2, 0), new ItemStack(Blocks.DRAGON_EGG, 1, 0));
LogHandler.logHandler.info("Finished registering the DragonEgg Duplication recipe!");
}
else {
LogHandler.logHandler.info("The Dragon Egg Duplication recipe is DISABLED in the config! Moving on!");
}
/*
* RECORD CRAFTING RECIPES
*/
if (ConfigHandler.recordCraftingRecipesEnabled == true) {
LogHandler.logHandler.info("Starting to register the Record crafting recipes!");
// Shaped Recipe
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_11, 1, 0), "VDV", "VVV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 0));
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_13, 1, 0), "VDV", "VVV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 11));
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_BLOCKS, 1, 0), "VDV", "VVV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 14));
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_CAT, 1, 0), "VDV", "VVV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 10));
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_CHIRP, 1, 0), "VDV", "VVV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 1));
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_FAR, 1, 0), "VDV", "VEV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 10), 'E', new ItemStack(Items.DYE, 1, 11));
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_MALL, 1, 0), "VDV", "VVV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 5));
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_MELLOHI, 1, 0), "VDV", "VVV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 13));
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_STAL, 1, 0), "VDV", "VVV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 8));
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_STRAD, 1, 0), "VDV", "VVV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 15));
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_WAIT, 1, 0), "VDV", "VVV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 12));
GameRegistry.addShapedRecipe(new ItemStack(Items.RECORD_WARD, 1, 0), "VDV", "VVV", 'V', Items.FLINT, 'D', new ItemStack(Items.DYE, 1, 2));
// Shapeless Recipes
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_11, 1, 0), "record", "dyeBlack"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_13, 1, 0), "record", "dyeYellow"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_BLOCKS, 1, 0), "record", "dyeOrange"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_CAT, 1, 0), "record", "dyeLime"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_CHIRP, 1, 0), "record", "dyeRed"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_FAR, 1, 0), "record", "dyeLime", "dyeYellow"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_MALL, 1, 0), "record", "dyePurple"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_MELLOHI, 1, 0), "record", "dyeMagenta"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_STAL, 1, 0), "record", "dyeGray"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_STRAD, 1, 0), "record", "dyeWhite"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_WAIT, 1, 0), "record", "dyeLightBlue"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Items.RECORD_WARD, 1, 0), "record", "dyeGreen"));
LogHandler.logHandler.info("Finished registering the Record crafting recipes!");
}
else {
LogHandler.logHandler.info("The Record crafting recipes are DISABLED in the config! Moving on!");
}
/*
* SKULL CRAFTING RECIPES
*/
if (ConfigHandler.skullSkeletonCraftingRecipeEnabled == true) {
if (ConfigHandler.skullSkeletonCraftingUsesDiamond == true) {
LogHandler.logHandler.info("Started to register the Skeleton Skull crafting recipe using a diamond!");
GameRegistry.addShapedRecipe(new ItemStack(Items.SKULL, 1, 0), "BBB", "BDB", "CCC", 'B', Blocks.BONE_BLOCK, 'D', Items.DIAMOND, 'C', Items.BONE);
LogHandler.logHandler.info("Finished registering the Skeleton Skull crafting recipe using a diamond!");
}
else {
LogHandler.logHandler.info("Started to register the Skeleton Skull crafting recipe!");
GameRegistry.addShapedRecipe(new ItemStack(Items.SKULL, 1, 0), "BBB", "BSB", "CCC", 'B', Blocks.BONE_BLOCK, 'S', Items.NETHER_STAR, 'C', Items.BONE);
LogHandler.logHandler.info("Finished registering the Skeleton Skull crafting recipe!");
}
}
else {
LogHandler.logHandler.info("The Skeleton Skull crafting recipe is DISABLED in the config! Moving on!");
}
if (ConfigHandler.skullWitherSkeletonCraftingRecipeEnabled == true) {
LogHandler.logHandler.info("Started to register the Wither Skeleton Skull crafting recipe!");
GameRegistry.addShapedRecipe(new ItemStack(Items.SKULL, 1, 1), "BCB", "CSC", "BCB", 'B', Blocks.COAL_BLOCK, 'C', Items.COAL, 'S', new ItemStack(Items.SKULL, 1, 0));
LogHandler.logHandler.info("Finished registering the Wither Skeleton Skull crafting recipe!");
}
else {
LogHandler.logHandler.info("The Wither Skeleton Skull crafting recipe is DISABLED in the config! Moving on!");
}
if (ConfigHandler.skullCreeperCraftingRecipeEnabled == true) {
LogHandler.logHandler.info("Started to register the Creeper Skull crafting recipe!");
GameRegistry.addShapedRecipe(new ItemStack(Items.SKULL, 1, 4), "TGT", "GSG", "TGT", 'T', Blocks.TNT, 'G', Items.GUNPOWDER, 'S', new ItemStack(Items.SKULL, 1, 0));
LogHandler.logHandler.info("Finished registering the Creeper Skull crafting recipe!");
}
else {
LogHandler.logHandler.info("The Creeper Skull crafting recipe is DISABLED in the config! Moving on!");
}
if (ConfigHandler.skullZombieCraftingRecipeEnabled == true) {
LogHandler.logHandler.info("Started to register the Zombie Skull crafting recipe!");
GameRegistry.addShapedRecipe(new ItemStack(Items.SKULL, 1, 2), "FFF", "FSF", "FFF", 'F', Items.ROTTEN_FLESH, 'S', new ItemStack(Items.SKULL, 1, 0));
LogHandler.logHandler.info("Finished registering the Zombie Skull crafting recipe!");
}
else {
LogHandler.logHandler.info("The Zombie Skull crafting recipe is DISABLED in the config! Moving on!");
}
if (ConfigHandler.skullDragonCraftingRecipeEnabled == true) {
LogHandler.logHandler.info("Started to register the Dragon Skull crafting recipe!");
GameRegistry.addShapedRecipe(new ItemStack(Items.SKULL, 1, 5), "ECE", "CSC", "ECE", 'E', Blocks.DRAGON_EGG, 'C', Items.END_CRYSTAL, 'S', new ItemStack(Items.SKULL, 1, 0));
LogHandler.logHandler.info("Finished registering the Dragon Skull crafting recipe!");
}
else {
LogHandler.logHandler.info("The Dragon Skull crafting recipe is DISABLED in the config! Moving on!");
}
/*
* SMELTING RECIPES
*/
if (ConfigHandler.rottenFleshToLeatherSmelting == true) {
LogHandler.logHandler.info("Started to register the Rotten Flesh to Leather smelting recipe!");
GameRegistry.addSmelting(new ItemStack(Items.ROTTEN_FLESH, 1, 0), new ItemStack(Items.LEATHER, 1, 0), 5);
LogHandler.logHandler.info("Finished registering the Rotten Flesh to Leather smelting recipe!");
}
else {
LogHandler.logHandler.info("The Rotten Flesh to Leather smelting recipe is DISABLED in the config! Moving on!");
}
if (ConfigHandler.boneToBoneMealSmelting == true) {
LogHandler.logHandler.info("Started to register the Bone to Bone Meal smelting recipe!");
GameRegistry.addSmelting(new ItemStack(Items.BONE, 1, 0), new ItemStack(Items.DYE, 4, 15), 5);
LogHandler.logHandler.info("Finished registering the Bone to Bone Meal smelting recipe!");
}
else {
LogHandler.logHandler.info("The Bone to Bone Meal smelting recipe is DISABLED in the config! Moving on!");
}
if (ConfigHandler.wheatToBreadSmelting == true) {
LogHandler.logHandler.info("Started to register the Wheat to Bread smelting recipe!");
GameRegistry.addSmelting(new ItemStack(Items.WHEAT, 3, 0), new ItemStack(Items.BREAD, 1, 0), 25);
LogHandler.logHandler.info("Finished registering the Wheat to Bread smelting recipe!");
}
else {
LogHandler.logHandler.info("The Wheat to Bread smelting recipe is DISABLED in the config! Moving on!");
}
if (ConfigHandler.slimeballToMagmaCreamSmelting == true) {
LogHandler.logHandler.info("Started to register the Slime Ball to Magma Cream smelting recipe!");
GameRegistry.addSmelting(new ItemStack(Items.SLIME_BALL, 1, 0), new ItemStack(Items.MAGMA_CREAM, 1, 0), 15);
LogHandler.logHandler.info("Finished registering the Slime Ball to Magma Cream smelting recipe!");
}
else {
LogHandler.logHandler.info("The Slime Ball to Magma Cream smelting recipe is DISABLED in the config! Moving on!");
}
if (ConfigHandler.enderEyeToEnderPearlSmelting == true) {
LogHandler.logHandler.info("Started to register the Ender Eye to Ender Pearl smelting recipe!");
GameRegistry.addSmelting(new ItemStack(Items.ENDER_EYE, 1, 0), new ItemStack(Items.ENDER_PEARL, 1, 0), 5);
LogHandler.logHandler.info("Finished registering the Ender Eye to Ender Pearl smelting recipe!");
}
else {
LogHandler.logHandler.info("The Ender Eye to Ender Pearl smelting recipe is DISABLED in the config! Moving on!");
}
LogHandler.logHandler.info("Finished registering Crafting Recipes!");
}
}
| 23b39a2674222aae2b4502c0f7c63548df2e253b | [
"Markdown",
"Java"
] | 6 | Java | justinhschaaf/JusaonvsCraftingTweaks | 297f7478bc8731b1acb41c59bbd1c12bad43fda5 | dfdee58495a42dc516eab5b5a53a3a266fe7b286 |
refs/heads/master | <repo_name>harmannd/TestWebsite24<file_sep>/TestWebsite24/Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(TestWebsite24.Startup))]
namespace TestWebsite24
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
| efad4cc4a13850d6b5a78b564dbc9e67cc5a4ebb | [
"C#"
] | 1 | C# | harmannd/TestWebsite24 | 599027c0857a5168791763b43cfb2c36c2269ac3 | ab677e9f374182d1b0b98138627f86465265cdd2 |
refs/heads/master | <repo_name>Galadrielz/Inori-LineBot<file_sep>/README.md
# Inori-LineBot
Inori line chat bot
<file_sep>/server.js
const fs = require('fs'); //read or write or even it can append(update) file hehe
const util = require('util'); // setTimeout ,etc check documentation nodejs
const upfile = require('formidable'); //upload file etc check documentation nodejs
const line = require('@line/bot-sdk'); // from line
const express = require('express');
const axios = require('axios');
const config = {
channelAccessToken: "<YOUR CHANNEL ACCESS TOKEN>",
channelSecret: "<YOUR CHANNEL SECRET>",
};
const ai = require("./AI.js");
const func = require('./func.js');
// LINE sdk client
const client = new line.Client(config);
const os = require("os");
const app = express();
const XMLHttpRequest = require("xhr2");
app.post('/callback', line.middleware(config), (req, res) => {
Promise
.all(req.body.events.map(handleEvent))
.then((result) => res.json(result))
.catch((err)=>{
console.log(err);
});
});
var gis = require('g-i-s');
//const translateg = require('google-translate-api'); // this proxy got banned, fck -__-"
const translateg = require('@k3rn31p4nic/google-translate-api');
// NOTE:API ETC ADA DI mylongData.js, export menggunakan node.js
//globaltunnel
var start = Date.now();
//============================================================================VARIABEL
var inoriLeaveImg = "https://i.pinimg.com/736x/bb/32/5b/bb325b37fdf18d3b9ebcff8a762d0a76--crowns-anime-pictures.jpg"
var inoriAndMeImg = "https://i.pinimg.com/736x/f7/e1/a4/f7e1a482a7131af71a4dbc61a640c458.jpg"
let eventMsgText;
let hasil = 1;
var url = "myData.json" // REGEXP (space included \s)
const regexSpace = /[\s]/g;
const regExp = /[a-zA-Z0-9!#%*•,-/\:;$\&\n\s\+\(\)\"\'~\`\|√π÷×∆£¢€¥\^°\=©®™\℅\<\>?@\[-\]_\{\}]/g;
const date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let tanggal = date.getDate();
let offset = date.getDay();
let jam = date.getHours() + 7; if(jam > 24){
jam -= 24;
tanggal += 1;
offset += 1;
if(offset > 6){
offset -= 7;
}
};
let menit = date.getMinutes(); if(menit < 10){
menit = "0" + menit;
};
var hari = ["Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu"];
let outputHari = hari[offset];
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!FUNCTION!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
function replyText(rtext) {
return {
type: "text",
text: rtext
};
}
function replyImg(originalContent, thumbnail) {
return {
type: "image",
originalContentUrl: originalContent,
previewImageUrl: thumbnail
};
}
function replyKeyword() {
return {
"type": "template",
"altText": "Keyword",
"template": {
"type": "buttons",
"title": "Keyword",
"text": "KEYWORD INORIBOT",
"actions": [
{
"type": "message",
"label": "Keyword",
"text": "Inori keyword"
},
{
"type":"message",
"label":"PERKENALAN",
"text":"Inori perkenalkan dirimu"
},
{
"type": "uri",
"label": "Developer",
"uri": "http://line.me/ti/p/~gy76vtr"
}
]
}
};
}
//-------------------------------------------------------------LINE EVENT------------------------------------------------------------------------------------------------------------
function handleEvent(event) {
//~~~~~~~~~>>>SETUP<<~~~~~~~~~~~~~~~~~~~~~
var source = event.source.type;
const reqProfile = {
"userId": event.source.userId,
"groupId": event.source.groupId || null,
"roomId": event.source.roomId || null
}
var userProfile = client.getProfile(reqProfile.userId);
// ~~~~~~~~~~~~~~~~>>>handle event ^^<<<~~~~~~~~~~~~~~~~~~~~
if(event.type == 'join'){
return client.replyMessage(event.replyToken, replyText("Terima kasih telah mengundang bot ini ^^\n\silahkan ketik \"inori keyword list\" untuk melihat keyword dan perkenalan"));
}else{
let msg = event.message.text;
eventMsgText = msg.toLowerCase();
let clearspace = msg.replace(/\s+/g, '');
let spacelength = msg.length - clearspace.length;
let match;
let transdatOffset;
if(!eventMsgText.includes("inori")){ //translate
let readDataObj = JSON.parse(fs.readFileSync("dataNote.json","utf8"));
if(readDataObj.transdat.length == 0){
transdatOffset = 0;
}else{
for(let i = 0; i < readDataObj.transdat.length; i++){
if(readDataObj.transdat[i].user == reqProfile.userId){
translateg(msg, {to:"id"}).then( res =>{/* translate i only accept japan and english for this*/
var language = res.from.language.iso;
if(language == 'ja' || language == 'en'){
return client.replyMessage(event.replyToken, replyText(res.text));
}
transdatOffset = 0;
}).catch(err => {
console.log(err);
return client.replyMessage(event.replyToken, replyText("Sorry, translate API is under maintenance, please wait and use again later :v"));
});
break;
}
}
}
}
if(eventMsgText.includes("inori")){
if(reqProfile.userId !== ("U89fbd2cbd5f0ba51d0f320346796249b")){
let keyword = event.message.text;
let input = "";
let offsetData;
let subj = reqProfile.userId;
let i;
let readData = fs.readFileSync("keylog.json","utf8");
let readDataObj = JSON.parse(readData);
readData = JSON.stringify(readDataObj);
offsetData = readData.slice(0,readData.indexOf("]}"));
if(readDataObj.data.length == 0){
input = offsetData + "{ \"user\" : "+JSON.stringify(subj)+",\n \"isi\":"+JSON.stringify(keyword)+"\n}]}";
}else{
input = offsetData + ",{ \"user\" : "+JSON.stringify(subj)+",\n \"isi\":"+JSON.stringify(keyword)+"\n}]}";
}
fs.writeFileSync('./keylog.json',input,'utf8');
}
}
//======================================================================================================================================================================================
if(eventMsgText == ("afk")){
if(reqProfile.userId == ("U89fbd2cbd5f0ba51d0f320346796249b")){
hasil = 0;
return client.replyMessage(event.replyToken, replyText("Oke darling"));
}
}
else if(eventMsgText == ("im back")){
if(reqProfile.userId == ("U89fbd2cbd5f0ba51d0f320346796249b")){
hasil = 1;
return client.replyMessage(event.replyToken, replyText("Welcome back my Dearest!!^^"));
}
}
//==========================================================================================================================================================================================
if(eventMsgText == ("dar")){
if (hasil == 0){
return client.replyMessage(event.replyToken, replyText("Gomen nee, my darling lagi sibuk, mungkin lagi tidur, main game atau coli mungkin :v, klo penting nanti aja ya, ty^^"));
}
}
else if(eventMsgText.includes("darta")){
if (hasil == 0){
return client.replyMessage(event.replyToken, replyText("Gomen nee, my darling lagi sibuk, mungkin lagi tidur, main game atau coli mungkin :v, klo penting nanti aja ya, ty^^"));
}
}
//===================================================================================================================================================================================
if(eventMsgText == ("inori tanggal brp skrg?")){
return client.replyMessage(event.replyToken, replyText( year + " - " + month + " - " + tanggal + " / " + jam + ":" + menit +"\n Hari = " + outputHari +" \n ~> GMT+7.00 ^^ "));
}
if(eventMsgText.includes("inori my permission msg")){
return client.replyMessage(event.replyToken, replyText("Hi, I really like your art, I am actually a programmer and I am making my own site, I am impressed with your art, I will be very happy if you allow me to use this image on my site. thank you"));
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>INTRO/KEYWORD<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
else if(eventMsgText == ("hai inori")){
if(reqProfile.userId == ("U<KEY>")){
return client.replyMessage(event.replyToken, replyText("Hai Sayangkuuuuuu^^\n\Boku no Darling :3"))
}else {
return userProfile.then(profile => client.replyMessage(event.replyToken, replyText("Hai.." + profile.displayName + "^.^")))
}
}
else if(eventMsgText == ("inori")) {
if (reqProfile.userId !== ("U8<KEY>0ba51d0f320346796249b")){
let echo = ["N-nani ", "Ya ", "Ada apa " , "Yes, sir "];
let resultEcho = Math.floor(Math.random() * echo.length);
return userProfile.then(profile => client.replyMessage(event.replyToken, replyText(echo[resultEcho] + profile.displayName + "??")));
}
if (reqProfile.userId == ("U8<KEY>f0ba5<KEY>")){
let echo = ["Yes, darling?", "N-nani, darling?", "Ada apa Sayangku?", "Iya, my Dearest?"];
let resultEcho = Math.floor(Math.random() * echo.length);
return client.replyMessage(event.replyToken, replyText(echo[resultEcho]))
}
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
else if(eventMsgText ===("inori keyword list")){
return client.replyMessage(event.replyToken, replyKeyword());
}
//NOTE{KEYWORD ADA DI DEVELOPER LINE, BELUM DIGANTI}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> HIBURAN, {DADU, BAKA, SPAM, RAMAL DLL.}
else if(eventMsgText.includes("darling, cari gambar kita") || eventMsgText.includes("inori cari gambar kita") || eventMsgText.includes("darling cari gambar kita")){
if(reqProfile.userId == ("U89fbd<KEY>f320346796249b")){
return client.replyMessage(event.replyToken,[replyText("Okay Darling hehe^^"), replyImg(inoriAndMeImg, inoriAndMeImg)]);
}
else if(reqProfile.userId !== ("U89fbd2cbd5f0ba51d0f320346796249b")){
return client.replyMessage(event.replyToken, replyText("Who are u?"));
}
}
//----------------------------------------------------------------------------------------------------------------------------------
else if(eventMsgText == ("inori kocok dadu")){
var dadu = ["1 !!","2 !!",
"3 !!","4 !!",
"5 !!","6 !!"
];
let myRandom = Math.floor(Math.random() * dadu.length);
return client.replyMessage(event.replyToken, replyText("OK ^.^, Hasilnya adalaahhh: " + dadu[myRandom]));
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
else if (eventMsgText.includes ("inori spam")){
let echo = {type:'text', text:"Spam"};
let keyword = event.message.text.substring(12);
return client.replyMessage(event.replyToken, [echo,echo,echo,echo,echo]);
}
else if(eventMsgText.includes ("inori medium spam")){
let echo = {type:'text', text:"Spam\n\Spam\n\Spam\n\Spam\n\Spam\n\Spam\n\Spam\n\Spam\n\Spam\n\Spam"};
let keyword = event.message.text.substring(12);
return client.replyMessage(event.replyToken, [echo,echo,echo,echo,echo]);
}
else if(eventMsgText==("inori max spam")){
if(reqProfile.groupId == ("Caa294118593cca4a1ed633ec86189f8a")){
return client.replyMessage(event.replyToken, replyText("Hus saru, gaboleh spam banyak2 :v"))
}
else if(reqProfile.groupId !== ("Caa294118593cca4a1ed633ec86189f8a")){
let echo = {type:'text', text:"s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m\n\s\n\p\n\a\n\m"}
let keyword = event.message.text.substring(12);
return client.replyMessage(event.replyToken, [echo,echo,echo,echo,echo]);
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
else if(eventMsgText == ("inori ramal")){
let ramal = [
"Hari ini adalah hari tersial mu!",
"Nanti pasti kamu akan tidur",
"Hari ini mungkin kamu akan bertemu jodohmu",
"Tiada yang lebih baik dari hari ini bagimu",
"Hari ini mungkin hari adalah hari terindahmu",
"Hari ini mungkin hari terakhirmu",
"Hari ini adalah hari terburukmu"
];
let ramalRand = Math.round(Math.random() * ramal.length);
return client.replyMessage(event.replyToken, replyText(ramal[ramalRand]));
}
else if(eventMsgText == ("inori ramal buat besok")){
let ramal = [
"Besok adalah hari tersial mu! ^^ ",
"Besok malam pasti kamu akan tidur",
"Besok mungkin kamu akan bertemu jodohmu",
"Tiada yang lebih baik dari hari esok bagimu",
"Besok mungkin hari terakhirmu ^.^",
"Besok mungkin hari terakhirmu ^.^",
"Besok adalah hari terburukmu",
"Besok adalahh hari yang baik untukmu",
"Besok adalah hari terindah mu ^.^"
];
let ramalRand = Math.round(Math.random() * ramal.length);
let echo = { type: 'text', text: ramal[ramalRand] }
return client.replyMessage(event.replyToken, echo);
}
//- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
else if(eventMsgText == ("inori anime quote")){
return func.animeQuote(client, replyText, event);
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
else if(eventMsgText.includes ("inori baka") || eventMsgText.includes ("inori goblok") || eventMsgText.includes ("inori tolol")) {
return client.replyMessage(event.replyToken, replyText("Evernest yang goblok :v"));
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>FUNCTION,{STRING, DLL}<<<
else if(eventMsgText.includes ("inori cek id group")) {
return client.replyMessage(event.replyToken, replyText(reqProfile.groupId));
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
else if(eventMsgText.includes("inori unlink")){
if(reqProfile.userId == "<KEY>" ){
let input = "{\"data\":[]}";
fs.writeFile("./keylog.json",input,'utf8',function(err){
if(err){
return client.replyMessage(event.replyToken, replyText(err.toString()));
}else{
return client.replyMessage(event.replyToken, replyText("Success"));
}
});
}else{
return client.replyMessage(event.replyToken, replyText("Only Admin Ty"));
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
else if(eventMsgText == "inori read"){
if(reqProfile.userId == "<KEY>" ){
let readData = fs.readFileSync("dataNote.json","utf8");
let readDataObj = JSON.parse(readData);
readData = JSON.stringify(readDataObj);
readData = readData.substring(readData.indexOf("}],") + 3);
return client.replyMessage(event.replyToken, replyText(readData));
}else{
return client.replyMessage(event.replyToken, replyText("Only Admin Ty"));
}
}
else if(eventMsgText == "inori read keyword"){
if(reqProfile.userId == "<KEY>" ){
let readData = fs.readFileSync("keylog.json","utf8");
let readDataObj = JSON.parse(readData);
readData = JSON.stringify(readDataObj);
return client.replyMessage(event.replyToken, replyText(readData));
}else{
return client.replyMessage(event.replyToken, replyText("Only Admin Ty"));
}
}
else if(eventMsgText == "inori read translate"){
if(reqProfile.userId == "<KEY>" ){
let readData = fs.readFileSync("dataNote.json","utf8");
let readDataObj = JSON.parse(readData);
readData = JSON.stringify(readDataObj);
return client.replyMessage(event.replyToken, replyText(JSON.stringify(readDataObj.transdat)));
}else{
return client.replyMessage(event.replyToken, replyText("Only Admin Ty"));
}
}
else if(eventMsgText == "inori liat note"){
let adPr = "~>~>~>Your Note: <~<~<~\n\n";
let offset1;
let readData = fs.readFileSync("dataNote.json","utf8");
let readDataObj = JSON.parse(readData);
readData = JSON.stringify(readDataObj);
var subj = reqProfile.userId;
for(let i = 0; i < readDataObj.data.length; i++){
if(readDataObj.data[i].user == subj){
if(readDataObj.data[i].isi.indexOf("pr") < 3 && readDataObj.data[i].isi.indexOf("pr") !== -1){
adPr += "Adha PR, ~> "+ readDataObj.data[i].isi +"\n";
offset1 = 1;
}
else if(readDataObj.data[i].isi.indexOf("ulangan") < 8 && readDataObj.data[i].isi.indexOf("ulangan") !== -1){
adPr += "Adha Ulangan, ~> " + readDataObj.data[i].isi + "\n";
offset1 = 1;
}else{
adPr += "Adha Note, ~> " + readDataObj.data[i].isi + "\n";
offset1 = 1;
}
}else{
offset1 = 0;
}
}
if(offset1 == 0)adPr += "Your ID's note is empty, Thanks for using my Bot ^_^";
adPr += "\t\t\t^\t3\t^";
return client.replyMessage(event.replyToken, replyText(adPr));
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
else if(eventMsgText.includes("inori test length")) {
if(reqProfile.userId == ("<KEY>")){
let keyword = event.message.text.substring(18);
let echo = ["Yes, Sayangkuu^^", "Okay Darling^^", "I love U darling^^"];
let resultEcho = Math.floor(Math.random() * echo.length);
let echo1 = "Result length = " + keyword.length;
return client.replyMessage(event.replyToken, replyText(echo[resultEcho] +"\n" + echo1));
}
else if(reqProfile.userId !== ("U<KEY>")){
let echo = ["Gomen nee anata nee not my Darling ^^", "You're not my DARLING!", "Just for my DARLING", "Gomen nee"];
let resultEcho = Math.floor(Math.random() * echo.length);
return client.replyMessage(event.replyToken, replyText(echo[resultEcho]));
}
}
else if(eventMsgText.includes("inori bilang")){
let keyword = event.message.text.substring(13);
let echo3 = ["Evernest Sayangkuu ^.^", "Darta Sayangkuu ^.^"];
let myRand = Math.floor(Math.random() * echo3.length);
if(keyword.length <= 0) {
return client.replyMessage(event.replyToken, replyText("Bilang apa??"));
}
else if(keyword.includes("cinta")||keyword.includes("love")||keyword.includes("suka")||keyword.includes("sayang")||keyword.includes("syg")){
return client.replyMessage(event.replyToken, replyText(echo3[myRand]));
}
else if(keyword.includes("o cen")||keyword.includes("husband")||keyword.includes("suami")||keyword.includes("darta")||keyword.includes("waifu")||keyword.includes("evernest")) {
return client.replyMessage(event.replyToken, replyText(echo3[myRand]));
}else{
return client.replyMessage(event.replyToken, replyText(keyword));
}
}
else if(eventMsgText.includes("inori balikkan")){
let keyword = event.message.text.substring(15);
if (keyword.length <= 0){
return client.replyMessage(event.replyToken, replyText("Balikkan apa?"));
}
var resultKeyword = "" ;
for (let i = 0; i <= keyword.length; i++){
resultKeyword += keyword.charAt(keyword.length - i);
}
return client.replyMessage(event.replyToken, replyText(resultKeyword));
}
//--------------
else if(eventMsgText.includes("inori replace")){
let keyword = event.message.text.substring(13) ;
let reqKeyword = keyword.slice(1, keyword.indexOf("=>") -1);
let keyword2 = keyword.substring(keyword.indexOf("dalam") + 6);
let jadi = keyword.slice(keyword.indexOf("=>") +3, keyword.indexOf("dalam")-1);
let reqKeywordfin = new RegExp(reqKeyword, 'g');
let resKeyword = keyword2.replace(reqKeywordfin , jadi);
return client.replyMessage(event.replyToken, replyText(resKeyword));
}
//----------------
else if(eventMsgText.includes("inori translate")){
func.googleTranslate(eventMsgText,event,client,translateg,replyText);
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
else if(eventMsgText.includes("inori cari gambar")){
let keyword = event.message.text.substring(18);
function logResults(error, results) {
if (error) {
return client.replyMessage(event.replyToken, replyText("Image terlalu besar, silahkan coba lagi"));
}else{
let randomRes = Math.round(Math.random() * results.length);
let reshasil = results[randomRes];
let reshasilu = reshasil.url;
return client.replyMessage(event.replyToken,replyImg(reshasilu,reshasilu));
}
}
gis({searchTerm:keyword,
queryStringAddition: '&safe=active&tbs=isz:m',
filterOutDomains: ['google.com','i.redd.it','cloudfront.net','narvii.com','akamaihd.net',
'wattpad.com','img.fireden.net','vignette.wikia.nocookie.net',
'drawfolio.com','pbs.twimg.com','sirtaptap.com','static.tvtropes.org',
'tumblr.com','paigeeworld.com','photobucket.com','kontek.net','pinimg.com']
}, logResults);
}
else if(eventMsgText.includes("inori mapel")){
func.jadwalMapel(eventMsgText,event,client,reqProfile,replyText,offset,hari,outputHari);
}
else if(eventMsgText.includes("inori note")){
func.masukPR(eventMsgText,event,client,reqProfile,replyText);
}
else if(eventMsgText.includes("inori hapus note")){
func.hpsNote(eventMsgText,event,client,reqProfile,replyText);
}
else if(eventMsgText.includes("inori on translate")){
func.ontranslate(eventMsgText,event,client,reqProfile,replyText);
}
else if(eventMsgText == ("inori off translate")){
func.offtranslate(eventMsgText,event,client,reqProfile,replyText);
}
else if(eventMsgText.includes("inori browse")){
func.gSearch(eventMsgText,event,client,reqProfile,replyText);
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>evLibr.js copas high
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>STUDY AI<<<
else if(eventMsgText.includes("inori") && eventMsgText.includes("gunting batu kertas")){
let i = 1;
new Promise((resolve,reject) => {
client.replyMessage(event.replyToken, replyText("Ok ^^, pada hitungan ketiga chat gunting/batu/kertas yaa.."));
resolve(replyFirst);
});
function replyFirst(){
if(i <= 2){
setTimeout(replyFirst,1000);
}
client.replyMessage(event.replyToken, replyText(i));
return i++;
}
if(i == 3){
ai.RockScissorPaper(eventMsgText,event,client,reqProfile,replyText);
}
}
//==============================================================================================================================================================================================
else if(eventMsgText === ("bye inori")) {
let echo = ["Ok..", "Bye - bye ", "Cya"];
let resultEcho = Math.floor(Math.random() * echo.length);
return client.replyMessage(event.replyToken, [replyText(echo[resultEcho]), replyImg(inoriLeaveImg, inoriLeaveImg)]).then(result => {
if (source === "room") {
client.leaveRoom(reqProfile.roomId);
}
else if (source === "group") {
client.leaveGroup(reqProfile.groupId);
}
}).catch(err => {
return client.replyMessage(event.replyToken, replyText("Leave keyword = ERROR \n\Silahkan kick bot melalui setting grup"));
})
}
}
}
// listen on port
const port = 8080;
app.listen(port, () => {
console.log(`listening on ${port}`);// ECMASCRIPT 7
}); | 45791d0b57784daa9acbfbdb9040fb102dd3c6f7 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Galadrielz/Inori-LineBot | 0abf2e006745a3c64bea8f96fcc24805a9baed24 | ccedf17220283bcc1fb32f8d7737a98f5f87e589 |
refs/heads/master | <file_sep>/**
* Visualize data
*
* @module data-visualizer
*/
;(function () {
'use strict'
/* imports */
var typeCheck = require('type-check').typeCheck
var barChart = require('./js/chart')
/* exports */
module.exports = visualize
/**
*
* @function visualize
*
* @param {Object} options all function parameters
* @param {Function} callback handle results
*/
function visualize (options, callback) {
var error = invalidOptions(options)
if (error) {
callback(error)
console.error(error)
return
}
barChart(options, callback)
}
/**
* Validate options
*
* @param {Object} options that were passed to visualize
* @return {Error} if options are invalid
*/
function invalidOptions (options) {
if (!typeCheck('Object', options)) {
var message = 'options should be an object'
return new Error(message)
}
return null
}
})()
<file_sep>## Change Log
All notable changes to this project will be documented in this section. This
project adheres to [Semantic Versioning](http://semver.org/).
Please use: Added, Changed, Deprecated, Removed, Fixed, or Security as labels.
<br>
#### 0.3.0 - (Unreleased)
##### Added
* ...
##### Changed
* ...
##### Deprecated
* ...
##### Removed
* ...
##### Fixed
* ...
##### Security
* ...
#### 0.2.0 - (2016-08-16)
##### Added
* support for line charts
#### 0.1.0 - (2016-06-21)
##### Added
* All files from bagrounds/template-spa v0.2.0
* bar-chart module from my external project
##### Changed
* relevant files from template to suit this project
* CHANGELOG (this) to suit this project
* dependencies as appropriate
##### Removed
* irrelevant files
<file_sep># data-visualizer
[![GitHub Downloads][github-img]][github-url]
[![Travis-CI][travis-img]][travis-url]
[![Coveralls][coveralls-img]][coveralls-url]
[![Code Climate][codeclimate-img]][codeclimate-url]
[![Code Climate][codeclimate-issues-img]][codeclimate-issues-url]
[![js-standard-style][standard-img]][standard-url]
Visualize data
## Installation
``` bash
$ npm install 'bagrounds/data-visualizer'
```
## [Documentation][gh-pages-url]
## Usage
...
## Tests
``` bash
$ npm test
```
## [Changelog][changelog-url]
## License
[MIT][license-url]
[changelog-url]: CHANGELOG.md
[license-url]: LICENSE
[standard-img]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
[standard-url]: http://standardjs.com/
[github-img]: https://img.shields.io/github/downloads/bagrounds/data-visualizer/total.svg
[github-url]: https://github.com/bagrounds/data-visualizer
[travis-img]: https://img.shields.io/travis/bagrounds/data-visualizer/master.svg
[travis-url]: https://travis-ci.org/bagrounds/data-visualizer
[coveralls-img]: https://coveralls.io/repos/github/bagrounds/data-visualizer/badge.svg?branch=master
[coveralls-url]: https://coveralls.io/github/bagrounds/data-visualizer?branch=master
[codeclimate-img]: https://codeclimate.com/github/bagrounds/data-visualizer/badges/gpa.svg
[codeclimate-url]: https://codeclimate.com/github/bagrounds/data-visualizer
[codeclimate-issues-img]: https://codeclimate.com/github/bagrounds/data-visualizer/badges/issue_count.svg
[codeclimate-issues-url]: https://codeclimate.com/github/bagrounds/data-visualizer/issues
[gh-pages-url]: http://bagrounds.github.io/data-visualizer
<file_sep>/**
* Tests for data-visualizer
*/
;(function () {
/* global describe, it */
'use strict'
/* Imports */
var expect = require('chai').expect
var dataVisualizer = require('../data-visualizer')
/* Tests */
describe('data-visualizer', function () {
describe('stub', function () {
it('should pass', function () {
expect(true).to.be.true
expect(dataVisualizer).to.be.a.function
})
})
})
})()
| d164f267711414ea93c63b26c4e2f8e32ce37311 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | bagrounds/data-visualizer | fd0af19f794fc88e9182018b3b34c4fa110c8358 | a69b06c1a7aaf1d3bb83e0d12aaf07efd9a191d3 |
refs/heads/master | <file_sep>package com.company;
import javafx.beans.binding.DoubleExpression;
import java.util.Scanner;
public class Main {
int userHeight, userWeight;
public static void main(String[] args) {
// write your code here
//p1
Scanner keyboard;
keyboard = new Scanner(System.in);
String feet;
Double inches;
String name;
Double weight;
int imp;
//p2
System.out.println("Hello,What is your name");
name= keyboard.nextLine();
System.out.print("Hello "+ name);
System.out.println(",Welcome to your BMI calculator");
System.out.println("What is your height in inches");
inches= keyboard.nextDouble();
System.out.println("What is your weight in pounds");
weight= keyboard.nextDouble();
imp= 703;
System.out.println(" " );
System.out.println(imp*weight/(inches*inches));
}
}
| 4ff5a5c46d6a3e265fdd2864838ad50b6567a918 | [
"Java"
] | 1 | Java | Dominicthedon/BMIProject | 844ec6fda3c1b9515e56498dd6a74f09ba492967 | a3164a91616833a834389b666274db3f93e87d49 |
refs/heads/master | <repo_name>tocisz/git_bomb<file_sep>/src/main.rs
use git2::{Error, Repository, Signature};
fn doit() -> Result<(), Error> {
let repo = Repository::init("tmp")?;
let mut b = repo.treebuilder(None)?;
let mut t = b.write()?;
println!("tree is {}", t.to_string());
for _ in 0..10 {
let mut b = repo.treebuilder(None)?;
for i in 0..10 {
let _entry = b.insert(format!("d{}", i), t, 0o040000)?;
}
t = b.write()?;
println!("tree is {}", t.to_string());
}
let root = repo.find_tree(t)?;
let signature = Signature::now("Tomasz", "<EMAIL>")?;
let commit = repo.commit(None, &signature, &signature, "test", &root, &[])?;
println!("commit is {}", commit.to_string());
let c = repo.find_commit(commit)?;
repo.branch("master", &c, false)?;
// repo.set_head("refs/heads/master")?;
// let mut head = repo.head()?;
// head.set_target(commit, "Commit");
Result::Ok(())
}
fn main() {
// std::fs::remove_dir_all("./tmp").unwrap();
match doit() {
Ok(_) => {}
Err(e) => eprintln!("{}", e),
}
}
| c957c7d232773c5c723f31844e843ab2a10186ec | [
"Rust"
] | 1 | Rust | tocisz/git_bomb | b8ecf8fa25e103edeb4e29bbad5875220cf4dab5 | 2d49e88d427d1242e58c03f824a09f08b98261a1 |
refs/heads/master | <file_sep>FROM ubuntu:latest
MAINTAINER <NAME> "<EMAIL>"
RUN apt-get update -y
RUN apt-get install -y python-pip python-dev build-essential
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["python"]
CMD ["myorg/common/sample/run.py"]<file_sep>import codecs
from setuptools import setup, find_packages
# Get the long description from the relevant file
with codecs.open('README.md', encoding='utf-8') as f:
long_description = f.read()
__version__ = '1.0.0'
setup(name='myorg.common.sample',
namespace_packages=['myorg', 'myorg.common'],
version=__version__,
python_requires='>3.6',
description="Sample python application with Makefile and Docker file",
long_description=long_description,
classifiers=[],
keywords='',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/sillyfatcat/python-skeleton',
license='None',
packages=find_packages(exclude=[]),
include_package_data=True,
zip_safe=False,
install_requires=[
],
entry_points={
'console_scripts': ['sample=myorg.common.sample.run:main'],
}
)
<file_sep>import unittest
class TestImport(unittest.TestCase):
def test_import(self):
"""
General import test to make sure all the critical dependencies are working fine
:return:
"""
try:
from myorg.common.sample.run import main
except:
self.fail('Failed import')
if __name__ == '__main__':
unittest.main()
<file_sep># sample Makefile
# 2019
PYTHON = python3
SETUP = setup.py
DIRECTORY = "myorg/contrib/sample"
OS = $(shell uname -a | cut -f 1 -d " " | tr '[:upper:]' '[:lower:]')
NAME = $(shell $(PYTHON) $(SETUP) --name)
COMMON_NAME = $(shell $(PYTHON) $(SETUP) --name | awk '{n=split($$1,A,"."); print A[n]}')
VERSION = $(shell $(PYTHON) $(SETUP) --version)
WHEEL = $(NAME)-$(VERSION)-py3-none-any.whl
DIST = ./dist
run:
$(PYTHON) -m myorg.contrib.sample.run
wheel:
$(PYTHON) $(SETUP) bdist_wheel -d $(DIST)
clean:
$(PYTHON) $(SETUP) clean --all
find . -name "*~" -exec $(RM) {} \;
find . -name "*.pyc" -exec $(RM) {} \;
$(RM) -r .tox
$(RM) -r build
$(RM) -r dist
$(RM) -r $(NAME).egg-info
<file_sep>#Introduction
TODO
##Building and Deploying
TODO
###Building Wheel
TODO
```bash
TODO
```
TODO
###Building Docker Image
TODO
```bash
TODO
```
| a119c56efc7c5500d0f3eb4e3fb323d0f0b6c095 | [
"Markdown",
"Python",
"Makefile",
"Dockerfile"
] | 5 | Dockerfile | sillyfatcat/python-skeleton | cc5659decabfd083f34c504212319c96f4a51c98 | afa1f07a70bff3689b25f66f4a069dbf77255578 |
refs/heads/master | <repo_name>lazystitan/actix_practice<file_sep>/src/main.rs
use actix_web::{HttpResponse, Responder, HttpServer, App, web};
fn index1() -> impl Responder {
HttpResponse::Ok().body("Hello world")
}
fn index2() -> impl Responder {
HttpResponse::Ok().body("Hello world again")
}
fn main() {
HttpServer::new(|| {
App::new()
.route("/", web::get().to(index1))
.route("/again", web::get().to(index2))
})
.bind("127.0.0.1:8088")
.unwrap()
.run()
.unwrap();
}
| 36dd2190a3fc16eefdebc35aed1aac9b6e2050e0 | [
"Rust"
] | 1 | Rust | lazystitan/actix_practice | 3d8c375ffbf9cb97f6f5d3cb1591b63fb1c7b448 | 2fb3ca700af8944c0c730535dd00c0259dedde8a |
refs/heads/master | <file_sep>NewsPublisher Extra for MODx Revolution
=======================================
**Original Author:** <NAME>
**Revolution Author:** <NAME> [Bob's Guides](http://bobsguides.com)
**Major Contributor** <NAME> -Invaluable fixes, improvements, and feature additions were created and tested by Markus
NewsPublisher is a front-end resource editing and creation tool for MODX Revolution.
Documentation is available at [Bob's Guides] (http://bobsguides.com/newspublisher-tutorial.html)
NewsPublisher is based on the NewsPublisher snippet for MODx
Evolution but has been completely refactored from the ground up for
MODx Revolution. It includes rich text editing
for the content and summary (introtext) fields and also for any
rich text TVs.
The rich text editing function does not work with older versions
of TinyMCE, but should work with the current release.
Here's a fix for the TinyMCE problem in older versions (Thanks to Bruno17!):
Change line 170 of /assets/components/tinymce/tiny.js from this:
Ext.getCmp('modx-panel-resource').markDirty();
To this:
var pr = Ext.getCmp('modx-panel-resource');
if (pr) pr.markDirty();
<file_sep><?php
/**
* NewsPublisher File Browser modAction
*
* @package newspublisher
*/
$browserAction= $modx->newObject('modAction');
$browserAction->fromArray(array(
'id' => 1,
'namespace' => 'newspublisher',
'controller' => 'filebrowser',
'haslayout' => false,
'parent' => 0,
'lang_topics' => '',
'assets' => '',
), '', true, true);
return $browserAction;
<file_sep><?php
/**
* NewsPublisher Build Script
*
* Copyright 2011-2015 <NAME>
*
* NewsPublisher is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version.
*
* NewsPublisher is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NewsPublisher; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*
* @package newspublisher
*/
/**
* Build NewsPublisher Package
*
* Description: Build script for NewsPublisher package
* @package newspublisher
* @subpackage build
*/
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$tstart = $mtime;
set_time_limit(0);
define('MODX_BASE_URL','http://localhost/addons/');
define('MODX_MANAGER_URL','http://localhost/addons/manager/');
define('MODX_ASSETS_URL','http://localhost/addons/assets/');
define('MODX_CONNECTORS_URL','http://localhost/addons/connectors/');
/* define sources */
$root = dirname(dirname(__FILE__)) . '/';
$sources= array (
'root' => $root,
'build' => $root . '_build/',
'source_core' => $root . 'core/components/newspublisher',
'source_assets' => $root . 'assets/components/newspublisher',
'data' => $root . '_build/data/',
'docs' => $root . 'core/components/newspublisher/docs/',
'resolvers' => $root . '_build/resolvers/',
);
unset($root);
/* instantiate MODx */
require_once $sources['build'].'build.config.php';
require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
$modx= new modX();
$modx->initialize('mgr');
$modx->setLogLevel(xPDO::LOG_LEVEL_INFO);
$modx->setLogTarget(XPDO_CLI_MODE ? 'ECHO' : 'HTML');
/* set package info */
define('PKG_NAME','newspublisher');
define('PKG_VERSION','2.1.0');
define('PKG_RELEASE','pl');
/* load builder */
$modx->loadClass('transport.modPackageBuilder','',false, true);
$builder = new modPackageBuilder($modx);
$builder->createPackage(PKG_NAME, PKG_VERSION, PKG_RELEASE);
$builder->registerNamespace('newspublisher',false,true,'{core_path}components/newspublisher/');
/* create snippet objects */
/* create category */
/* @var $category modCategory */
$category= $modx->newObject('modCategory');
$category->set('id',1);
$category->set('category','NewsPublisher');
/* add snippets */
$modx->log(modX::LOG_LEVEL_INFO,'Adding in snippets.');
$snippets = include $sources['data'].'newspublisher/transport.snippets.php';
if (is_array($snippets)) {
$category->addMany($snippets);
} else { $modx->log(modX::LOG_LEVEL_FATAL,'Adding snippets failed.'); }
/* add chunks */
$modx->log(modX::LOG_LEVEL_INFO,'Adding in chunks.');
$chunks = include $sources['data'].'newspublisher/transport.chunks.php';
if (is_array($chunks)) {
$category->addMany($chunks);
} else { $modx->log(modX::LOG_LEVEL_FATAL,'Adding chunks failed.'); }
/* create category vehicle */
$attr = array(
xPDOTransport::UNIQUE_KEY => 'category',
xPDOTransport::PRESERVE_KEYS => false,
xPDOTransport::UPDATE_OBJECT => true,
xPDOTransport::RELATED_OBJECTS => true,
xPDOTransport::RELATED_OBJECT_ATTRIBUTES => array (
'Snippets' => array(
xPDOTransport::PRESERVE_KEYS => false,
xPDOTransport::UPDATE_OBJECT => true,
xPDOTransport::UNIQUE_KEY => 'name',
),
'Chunks' => array(
xPDOTransport::PRESERVE_KEYS => false,
xPDOTransport::UPDATE_OBJECT => true,
xPDOTransport::UNIQUE_KEY => 'name',
),
)
);
$vehicle = $builder->createVehicle($category,$attr);
$vehicle->resolve('file',array(
'source' => $sources['source_core'],
'target' => "return MODX_CORE_PATH . 'components/';",
));
$vehicle->resolve('file',array(
'source' => $sources['source_assets'],
'target' => "return MODX_ASSETS_PATH . 'components/';",
));
$builder->putVehicle($vehicle);
/* Add filebrowser action */
$modx->log(modX::LOG_LEVEL_INFO,'Adding filebrowser action.');
$browserAction = include $sources['data'].'transport.browseraction.php';
$vehicle= $builder->createVehicle($browserAction,array (
xPDOTransport::PRESERVE_KEYS => false,
xPDOTransport::UPDATE_OBJECT => true,
xPDOTransport::UNIQUE_KEY => array ('namespace','controller'),
));
$builder->putVehicle($vehicle);
/* NewsPublisher access policy template */
$modx->log(modX::LOG_LEVEL_INFO,'Adding access policy template.');
$template = include $sources['data'].'transport.accesspolicytemplate.php';
$vehicle= $builder->createVehicle($template,array (
xPDOTransport::PRESERVE_KEYS => false,
xPDOTransport::UPDATE_OBJECT => true,
xPDOTransport::UNIQUE_KEY => 'name',
));
$modx->log(modX::LOG_LEVEL_INFO, 'Adding access policy template resolver.');
$vehicle->resolve('php',array(
'source' => $sources['resolvers'] . 'accesspolicytemplate.resolver.php',
));
$builder->putVehicle($vehicle);
/* NewsPublisher access policy */
$modx->log(modX::LOG_LEVEL_INFO,'Adding access policy.');
$policy = include $sources['data'].'transport.accesspolicy.php';
$vehicle= $builder->createVehicle($policy,array (
xPDOTransport::PRESERVE_KEYS => false,
xPDOTransport::UPDATE_OBJECT => true,
xPDOTransport::UNIQUE_KEY => 'name',
));
$modx->log(modX::LOG_LEVEL_INFO, 'Adding access policy resolver.');
$vehicle->resolve('php',array(
'source' => $sources['resolvers'] . 'accesspolicy.resolver.php',
));
$modx->log(modX::LOG_LEVEL_INFO, 'Adding filemove resolver.');
$vehicle->resolve('php',array(
'source' => $sources['resolvers'] . 'filemove.resolver.php',
));
$builder->putVehicle($vehicle);
unset($vehicle,$template,$policy,$browserAction);
/* now pack in the license file, readme.txt and setup options */
$builder->setPackageAttributes(array(
'license' => file_get_contents($sources['source_core'] . '/docs/license.txt'),
'readme' => file_get_contents($sources['source_core'] . '/docs/readme.txt'),
'changelog' => file_get_contents($sources['docs'] . 'changelog.txt'),
));
/* zip up the package */
$builder->pack();
$mtime= microtime();
$mtime= explode(" ", $mtime);
$mtime= $mtime[1] + $mtime[0];
$tend= $mtime;
$totalTime= ($tend - $tstart);
$totalTime= sprintf("%2.4f s", $totalTime);
$modx->log(xPDO::LOG_LEVEL_INFO, "Package Built.");
$modx->log(xPDO::LOG_LEVEL_INFO, "Execution time: {$totalTime}");
exit();
| f922d2a437b822d779e04a63a4cb17be07b114e5 | [
"Markdown",
"PHP"
] | 3 | Markdown | donShakespeare/newspublisher | c4bdd72017f6e275fbb748e49d9b26ce6aa663e9 | a504fe9478d11ff91447b87e231aea0922121a0f |
refs/heads/master | <file_sep>class Hotel:
def __init__(self, start, rooms, room_bats):
self._estrella = start #atributo
self._cuartos = rooms
self._cuartos_bano = room_bats
self._CUARTOS_MAX = rooms #datofijo
self._CUARTOS_BANO_MAX = room_bats #dato fijo
def _actualizar_datos(self, accion, cuartos, cuarto_bano): #metodo
if accion == 'alquilar' or accion == 'reservar': #al alquilar y reservar, restamos y calculamos la disponibilidad
if self._cuartos - cuartos < 0: #verificamos que el usuario no reserve lo que no se dispone
print(f'No se dispone de {cuartos} cuartos, solo quedan disponibles {self._cuartos} cuartos')
else: #si todo es conforme, actualizamos la data
self._cuartos -= cuartos
if self._cuartos_bano - cuartos_bano < 0:
print(f'No se dispone de {cuartos_bano} cuartos con baño, solo se dispone de {self._cuartos_bano} cuartos con baño')
else:
self._cuartos_bano -= cuarto_bano
elif accion == 'cancelar reserva': #al cancelar la reserva sumamos y calculamos
if self._cuartos += cuartos > self._CUARTOS_MAX:
print(f'No se puede ejecutar la accion, solo se dispone de {self._cuartos} cuartos')
else:
self._cuartos += cuartos
if self._cuartos_bano + cuarto_bano > self._CUARTOS_BANO_MAX:
print(f'No se puede ejecutar la accion, solo se dispone de {self._CUARTOS_BANO_MAX} cuartos con baño')
else:
self._cuartos_bano += cuarto_bano #Actualizamos los atributos
def alquilar(self, cuartos, cuartos_bano):
self._actualizar_datos('alquilar', cuartos, cuartos_bano)
print(f'Quedan {self._cuartos} cuartos y {self._cuarto_bano} cuartos con baño disponibles')
def reservar(self, cuartos, cuartos_bano):
self._actualizar_datos('reservar', cuartos, cuartos_bano)
print(f'Quedan {self._cuartos} cuartos y {self._cuarto_bano} cuartos con baño disponible')
def cancelar_reserva(self, cuartos, cuartos_bano):
self._actualizar_datos('Cancelar_reserva', cuartos, cuarto_bano)
print(f'Quedan {self._cuartos} cuartos y {self._cuartos_bano}')
def llamar_asistente(self):
print("""
--- El asistente esta en camino ---
""")
def menu(self):
opcion = int(input(f"""
------------------------ WELCOME TO HOTEL ASSISTANT----------------------------
Este es el asistente para trabajar con los hoteles
Diponibilidad de:
- {self._cuartos} cuartos
- {self._cuarto_bano} cuartos con baño
_______________________________________
¿que es lo que desea hacer?
1.- Alquilar
2.- Reservar
3.- Cancelar reserva
4.- Llamar a asistente
5.- Salir del programa
Elija una opcion ------> """))
return opcion
def preguntar():
cuartos = int(input('Cuantos cuartos: '))
cuantos_banos =int(input('Cuantos cuartos con baño: '))
return cuartos, cuantos_banos
def run():
hotel_cielo = Hotel(3, 20, 15)
while True:
opcion = hotel_cielo()
if opcion == 1:
cuartos, cuartos baño = preguntar()
hotel_cielo.alquilar(cuartos, cuartos_bano)
elif opcion == 2:
cuartos, cuartos baño = preguntar()
hotel_cielo.reservar(cuartos, cuartos_bano)
elif opcion == 3:
cuartos, cuartos baño = preguntar()
hotel_cielo.cancelar_reserva(cuartos, cuartos_bano)
else:
break
if __name__ == '__main__':
run()
<file_sep>""" def funcion_decoradora(funcion):
def wrapper():
print('Este es el ultimo mensaje')
funcion()
print('Este es el primer mensaje')
return wrapper()
def zumbido():
print('buzzzz')
zumbido = funcion_decoradora(zumbido) """
#Clases whitout getters and setters
""" class Millas:
def __init__(self, distancia = 0):
self.distancia = distancia
def convertir_a_kilometros(self):
return (self.distancia * 1.609344)
#Metodo getter
def obtener_distancia(self):
return self._distancia
#Metodo Setter
def definir_distancia(self, valor):
if valor < 0:
raise ValueError('No es posible convertir distancias menores a 0')
self.distancia = valor
"""
class Millas:
def __init__(self):
self._distancia = 0
#getter
@property
def distancia(self):
print('Llamando a guetter')
print(self.distancia)
return self._distancia
#setter
@distancia.setter
def distancia(self, valor):
#validacion si no ingresa un numero
if False is isinstance(valor, (int, float)):
raise TypeError('Ingrese un numero entero valido')
if valor < 0:
raise ValueError('No es posible convertir distancias menores a 0')
print('Llamada al setter')
self._distancia = valor
print(self._distancia)
#funcion que convierte de km a millas
def convertir_a_km(self):
conversion = self.distancia * 1.609344
print(f'{self._distancia} millas convertidas a km son {conversion} km')
if __name__ == '__main__':
avion = Millas()
avion.distancia #el getter muestra cero ya que no le pasamos ningun dato
avion.distancia = 45
avion.convertir_a_km() #se transforma la funcion
<file_sep>class CasillaVotacion:
def __init__(self, identificador, pais):
self._identificador = identificador
self._pais = pais
self._region = None
@property
def region(self):
return self._region
@region.setter
def region(self, reg):
if reg in self._pais:
self._region = reg
else:
raise ValueError(f'La region {reg} no es valida en {self._pais}')
casilla = CasillaVotacion(123, ['Bogota', 'Medellin'])
print(casilla.region)
casilla.region = 'Bogota'
print(casilla.region)<file_sep>from library import Biblioteca
from libro_library import Libro
if __name__ == '__main__':
ejecutar = True
while(ejecutar):
print('-------------BIBLIOTECA----------------')
opcion = int(input('¿que vas a hacer?: \n1- Crear Biblioteca\n2- Agregar libro\n3- Ver catalogo\n4- Quitar libro\n5- Salir\n: '))
if opcion == 1:
nombre = input('Nombre de la biblioteca: ')
biblioteca = Biblioteca(nombre)
print(f'Se creo la biblioteca {biblioteca}'.format(biblioteca.consultar_nombre_biblioteca))
elif opcion == 2:
titulo = input('Titulo: ')
autor = input('Autor: ')
cantidad_de_paginas = input('Paginas: ')
genero = input('Genero: ')
sinopsis = input('Sinopsis: ')
libro = Libro(titulo, autor, cantidad_de_paginas, genero. sinopsis)
Biblioteca.agregar_libro(libro)
elif opcion == 3:
print('catalogo de libros: ')
for i in Biblioteca.consultar_libros()
print(i)
elif opcion == 4:
indice == input('Id del libro a eliminar: ')
biblioteca.quitar_libro(indice)
elif opcion == 5:
ejecutar = False
else:
print('Opcion incorrecta')
| d083aaad9c4f732185d6ee369296c3002c0eda5a | [
"Python"
] | 4 | Python | obemauricio/Prog_Orientada_Objetos_2021 | 60474371c70c0dcff0a465dda2957f0e0c578ac7 | 66895c4a8455f5091c2dbec493c0f1814910fcbd |
refs/heads/master | <file_sep>require 'net/ssh'
host = 'beret.cs.brandeis.edu'
user = 'hadoop07'
password = '<PASSWORD>'
Net::SSH.start(host, user, :password => password) do |ssh|
output = ssh.exec!("ls")
puts output
end
<file_sep>
class Document
attr_accessor :id
attr_accessor :score
attr_accessor :positions
attr_accessor :info
def initialize
@positions = Hash.new
end
def deserialize line, keyword
line = line[1, line.length - 2]
@id = line[0, line.index(',')].to_i
line = line[line.index(' ') + 1, line.length]
deserialize_positions line, keyword
end
def deserialize_positions line, keyword
first_positions = Array.new
line.split(' ').each { |pos| first_positions.push pos.to_i }
@score = first_positions.length
@positions.store keyword, first_positions
end
def serialize
st = "#{@id},#{@score}"
@positions.values[0].each { |pos| st += " #{pos}"}
st = '(' + st + ')'
st
end
# return new obj
def execute_and other
new_obj = Document.new
new_obj.id = @id
new_obj.score = @score + other.score
new_obj.positions = @positions.merge other.positions
new_obj
end
# return new obj
def execute_or other
new_obj = Document.new
new_obj.id = @id
new_obj.score = @score + other.score
new_obj.positions = @positions.merge other.positions
new_obj
end
# get
def get_info
info = DocumentUtil::get_document_by_id @id
summary = ""
@positions.keys.each do |keyword|
index = info["content"].index /#{keyword}/i
key_len = keyword.length
summary += "...#{info["content"][index - 20, 20]}<b>#{info["content"][index, key_len]}</b>#{info["content"][index + key_len, 20]}..."
end
@info = {}
@info.store "id", info["id"]
@info.store "name", info["name"]
@info.store "summary", summary.gsub("\n", " ")
end
def to_json_obj
obj = {}
obj["id"] = @id
obj["score"] = @score
obj["positions"] = @positions
obj["info"] = @info if @info != nil
obj
end
end<file_sep>source "https://rubygems.org"
ruby "2.3.1"
gem "sinatra"
gem "redis"
gem "bunny"
gem "algorithms"
gem "byebug"<file_sep>require.config({
baseUrl: "/",
paths: {
underscore: "js/underscore-1.8.3",
Backbone: "js/backbone",
jquery: "js/jquery.min-2.1.4",
TEXT: "js/text-2.0.14",
Document: "js/model/document.model",
DocumentList: "js/model/documents.collection",
ResultView: "js/index/result.view"
},
waitSeconds: 10
})
require(['ResultView'], function(ResultView) {
var result_view = new ResultView();
$("#search_main").click(function() {
result_view.search($("#input_main").val());
});
$("#search_global").click(function() {
result_view.search($("#input_global").val());
$("#input_global").val("");
});
});
<file_sep>require 'sinatra'
require 'redis'
require 'algorithms'
require 'json'
require './lib/commander'
require './lib/indexcaching'
require './lib/util'
require './lib/models/document'
require './lib/models/documentlist'
require './lib/models/operator'
# valid operators: "and", "or", "and not", "()"
# there must be a "and" before "not"
include DocumentUtil
get '/' do
"Hello World"
end
# parameters: command, start, number
get '/search' do
@command = params[:command]
start = params[:start].to_i
number = params[:number].to_i
document_list = Commander.instance.exec @command
document_list.sort_documents_by_score 0, document_list.length - 1 if document_list.length > 0
document_list.keep_part start, number
document_list.get_document_infos
@list = document_list.to_json_obj
erb :search
end
get '/documents/:id' do
id = params[:id].to_i
keyword_list = params[:keywords]
document = DocumentUtil::get_document_by_id id
# st = exec "docker exec -it big_cray /usr/local/hadoop/bin/hadoop jar /usr/local/hadoop/testCloud9-0.0.1-SNAPSHOT.jar testCloud9.testCloud9 10002"
document["content"] = DocumentUtil::mark_on_document document["content"], keyword_list
document["content"] = DocumentUtil::mark_enter_on_document document["content"]
@document = document
erb :document
end<file_sep>require 'redis'
require 'singleton'
class IndexManager
include Singleton
attr_accessor :redis
def initialize
@redis = Redis.new
end
def get key
@redis.get key
end
def set key, value
@redis.set key, value
end
end<file_sep>module DocumentUtil
def get_requestids document_list, start, number
id_list = []
document_list.documents[start, number].each { |document| id_list.push document.id }
id_list
end
def load_documents id_list
threads = []
id_list.each do |id|
threads << Thread.new {exec("docker exec -it big_cray /usr/local/hadoop/bin/hadoop jar /usr/local/hadoop/testCloud9-0.0.1-SNAPSHOT.jar testCloud9.testCloud9 10002 >> #{id}.txt") }
end
threads.each {|thread| thread.join}
end
def get_document_by_id id
document = `docker exec -it big_cray /usr/local/hadoop/bin/hadoop jar /usr/local/hadoop/testCloud9-0.0.1-SNAPSHOT.jar testCloud9.testCloud9 #{id}`
i1 = document.index "====="
document = document[i1 + 7, document.length]
i2 = document.index ":"
document_id = document[0, i2].to_i
i3 = document.index "\n"
document_name = document[i2 + 2, i3 - i2 - 2]
document_content = document[i3 + 1, document.length]
result = {}
result.store "id", document_id
result.store "name", document_name
result.store "content", document_content
result
end
def mark_on_document document, keyword_list
keyword_list.each do |keyword|
document = document.gsub(/(?<foo>#{keyword})/i, '<b>\k<foo></b>')
end
document
end
def mark_enter_on_document document
document = document.gsub("\n", "</br>")
end
end<file_sep># consumer
require 'redis'
require 'bunny'
require 'json'
require 'byebug'
connection_config = ENV["RABBITMQ_BIGWIG_URL"]
conn = Bunny.new(connection_config)
conn.start
ch = conn.create_channel
q = ch.queue("wikipedia")
redis = Redis.new
begin
q.subscribe(:block => true) do |delivery_info, properties, body|
# body is the string sent by producer.
request = JSON.parse body
key = request["key"]
value = request["value"]
puts key
redis.set key, value
end
rescue Interrupt => _
puts "Interrupt "
conn.close
exit(0)
end
<file_sep>
class Operator
attr_accessor :op_text
def initialize str
@op_text = str
end
def equal_to op
@op_text == op.op_text
end
def to_method
"execute_#{@op_text.gsub(' ', '_')}"
end
end<file_sep># producer
require 'redis'
require 'bunny'
require 'json'
require './lib/util'
require './lib/models/document'
require './lib/models/documentlist'
require 'byebug'
redis = Redis.new
conn = Bunny.new(ENV["RABBITMQ_BIGWIG_URL"])
conn.start
ch = conn.create_channel
q = ch.queue "wikipedia"
# path name generation
base_path = 'index/'
file_names = []
(97..122).each do |i|
c = i.chr
file_names.push base_path + c
end
file_names.push base_path + 'other'
arr = []
t_start = Time.now.to_f
file_names.each do |filename|
if File.exist? filename
t_filestart = Time.now.to_f
File.open(filename, 'r') do |file|
while line = file.gets
document_list = DocumentList.new
document_list.deserialize line, true
obj = {key: document_list.keyword, value: document_list.serialize_list}
q.publish JSON.generate obj
end
end
t_fileend = Time.now.to_f
puts "#{filename} time: #{t_fileend - t_filestart}s"
arr.push t_fileend - t_filestart
end
end
sum = 0
arr.each { |ele| sum += ele }
sum2 = 0
arr.each { |ele| sum2 += ele*ele }
puts "average expect of the worst case: #{sum2/sum}s"<file_sep>require 'algorithms'
require 'singleton'
require 'byebug'
# valid operators: "and", "or"
# all words are in down case
# 因为not操作不好做。 不可能把所有其他id都纳入进来
class Commander
include Singleton
attr_accessor :op_priority
def initialize
@op_priority = {"and" => 2, "and not" => 2, "or" => 1, "(" => 0}
end
def exec command
@workflow = Array.new
@op_stack = Containers::Stack.new
generate_workflow command
exec_workflow
end
private
def exec_workflow
document_list1 = DocumentList.build_from_redis @workflow[0]
document_list2 = nil
len = @workflow.length
(1 .. @workflow.length - 1).each do |i|
if @workflow[i].class == Operator.itself
document_list1 = document_list1.operate(@workflow[i], document_list2) # command pattern
else
document_list2 = DocumentList.build_from_redis @workflow[i]
end
end
document_list1
end
def generate_workflow command
len = command.length
st = ""
i = 0
while i < len
ch = command[i]
if (ch >= 'a' and ch <= 'z')
st += ch
p command
if (i == command.length - 1)
i = check_string st, command, i
st = ""
end
else
if !st.empty?
i = check_string st, command, i
st = ""
end
@op_stack.push(Operator.new('(')) if ch == '('
if (ch == ')')
while (op = @op_stack.pop).op_text != '('
@workflow.push op
end
end
end
i += 1
end
while @op_stack.next != nil
@workflow.push @op_stack.pop
end
end
# whether it is a value or an operator
# if it is an "and", check whether there is a not behind
def check_string str, command, index
if (str != "and" && str != "or") # a value
@workflow.push str
else
# if there is "not" behind an "and"
if str == "and" && index + 1 < command.length && command[index + 1, 3] == "not"
str = "and not"
index += 3
end
if @op_stack.empty? || @op_priority[str] > @op_priority[@op_stack.next.op_text]
@op_stack.push Operator.new(str)
else
@workflow.push @op_stack.pop #output top
@op_stack.push Operator.new(str)
end
end
index
end
end<file_sep># wikipedia
course project 02/2017
This is the online part of the project.
<file_sep>define(['Backbone', 'Document'], function(Backbone, Document) {
var DocumentList = Backbone.Collection.extend({
url: function() {
return '/api/v1/search'
},
model: Document,
});
});<file_sep>require 'byebug'
require 'set'
class DocumentList
attr_accessor :keyword
attr_accessor :documents
attr_accessor :length
def self.build_from_redis key
document_list = DocumentList.new
document_list.keyword = [key]
document_list.deserialize_list IndexManager.instance.get key
document_list
end
def deserialize line, sort = false
@keyword = [line[0, line.index("\t")]]
deserialize_list line, sort
end
def deserialize_list line, sort = false
if (line == nil)
@length = 0
@documents = Array.new
return
end
arr = line.scan /[(][0-9\s,]+[)]/
@documents = Array.new
arr.each do |str|
document = Document.new
document.deserialize str, @keyword[0]
@documents.push document
end
sort_documents_by_id 0, arr.length - 1 if sort
@length = arr.length
end
def serialize_list
str = String.new
@documents.each { |document| str += document.serialize }
str
end
# execute operation #{op} with #{other}
# op.class == Operator
# other.class == DocumentList
# execute_and_not, execute_and, execute_or
# return a new object
def operate op, other
instance_eval("#{op.to_method}(other)")
end
def sort_documents_by_score left, right
mid = left + (right - left) / 2;
pivot = @documents[mid] # a document
pivot_score = pivot.score
i = left
j = right
while (i <= j)
while (@documents[i].score > pivot_score)
i += 1
end
while (@documents[j].score < pivot_score)
j -= 1
end
if (i <= j)
tmp = @documents[i]
@documents[i] = @documents[j]
@documents[j] = tmp
i += 1
j -= 1
end
end
sort_documents_by_score left, j if j > left
sort_documents_by_score i, right if right > i
end
def keep_part start, number
if start >= @length
@documents = Array.new
@length = 0
else
@length = @length - start
@length = number if number < @length
@documents = @documents[start, @length]
end
end
def to_json_obj
obj = {}
obj["keyword"] = @keyword
obj["length"] = @length
obj["documents"] = Array.new
@documents.each { |document| obj["documents"].push document.to_json_obj }
obj
end
def get_document_infos
threads = []
@documents.each do |document|
threads << Thread.new { document.get_info }
end
threads.each { |thread| thread.join }
# @documents.each do |document|
# document.get_info
# end
end
private
def execute_and_not other
otherid_set = Set.new
other.documents.each { |document| otherid_set.add document.id }
new_obj = DocumentList.new
new_obj.keyword = @keyword - other.keyword
new_obj.documents = Array.new
@documents.each { |document| new_obj.documents.push document if !otherid_set.include? document.id }
new_obj.length = new_obj.documents.length
new_obj
end
def execute_and other
new_obj = DocumentList.new
new_obj.keyword = @keyword | other.keyword
new_obj.documents = Array.new
i = 0
j = 0
# two pointer
while i < @documents.length && j < other.documents.length
if @documents[i].id < other.documents[j].id
i += 1
elsif @documents[i].id > other.documents[j].id
j += 1
else
new_obj.documents.push @documents[i].execute_and(other.documents[j])
i += 1
j += 1
end
end
new_obj.length = new_obj.documents.length
new_obj
end
def execute_or other
new_obj = DocumentList.new
new_obj.keyword = @keyword | other.keyword
new_obj.documents = Array.new
i = 0
j = 0
while i < @documents.length || j < other.documents.length
if (i >= @documents.length || @documents[i].id > other.documents[j].id)
new_obj.documents.push other.documents[j]
j += 1
elsif (j >= other.documents.length || @documents[i].id < other.documents[j].id)
new_obj.documents.push @documents[i]
i += 1
else
new_obj.documents.push @documents[i].execute_or(other.documents[j])
i += 1
j += 1
end
end
new_obj.length = new_obj.documents.length
new_obj
end
def sort_documents_by_id left, right
mid = left + (right - left) / 2;
pivot = @documents[mid] # a document
pivot_id = pivot.id
i = left
j = right
while (i <= j)
while (@documents[i].id < pivot_id)
i += 1
end
while (@documents[j].id > pivot_id)
j -= 1
end
if (i <= j)
tmp = @documents[i]
@documents[i] = @documents[j]
@documents[j] = tmp
i += 1
j -= 1
end
end
sort_documents_by_id left, j if j > left
sort_documents_by_id i, right if right > i
end
end | 00860272fc08575a64ae20a972002e4a47ad7244 | [
"JavaScript",
"Ruby",
"Markdown"
] | 14 | Ruby | hongjic/wikipedia | 50bc3abbff23fe1813d9f8e3cbb5aa0310504eb6 | 2637be216bd20aecdf0ca54790bd33c9ef96b202 |
refs/heads/master | <file_sep>Rails.application.routes.draw do
root 'home#index'
get 'home/index'
get 'home/budderorder'
get 'home/kellykustom'
get 'home/membership'
get 'home/survey'
resources :charges
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| 433bd834a789bf4457d1602b1482b36493916cc7 | [
"Ruby"
] | 1 | Ruby | vedabrat/jerzjane | 23cc3ca2b41ab5d31c9e43809030db561d2971da | 1d6989136271a5a556b5ca38f786ed2062fb5476 |
refs/heads/master | <file_sep>1.Install python
2.Install ffmpeg
3.Create a file called .env inside the same folder as BenzBot V2.py, copy the following inside and get the token from #coding
# .env
DISCORD_TOKEN=Token Comes Here!
4.Install the chromium webdriver with sudo apt-get install chromium-chromedriver
5.pip install all necessary dependencies
6.then run this line:
python "BenzBot V2.py"
<file_sep>from discord.ext import commands
class Talk(commands.Cog):
@commands.Cog.listener()
async def on_message(self, message):
if message.content.startswith('Secret '):
await message.channel.send('Ja, aber zuerst müssen sie die Projektdokumentation schreiben')
def setup(bot):
bot.add_cog(Talk(bot))<file_sep>import discord
from discord.ext import commands
from discord_slash import cog_ext
from Functions.Music.MusicExtensions import VoiceChannelExtensions
class Join(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def join(self, ctx, channel):
voice_client = VoiceChannelExtensions.get_voice_client(self.bot, ctx)
if voice_client is not None:
return await voice_client.move_to(channel)
await channel.connect()
await ctx.send(f'Joining {channel}')
@commands.command(name = "join")
async def command_join(self, ctx, *, channel: discord.VoiceChannel):
await self.join(ctx, channel)
@cog_ext.cog_slash(name = "join", description = "Join a channel")
async def slash_join(self, ctx, channel: discord.VoiceChannel):
await self.join(ctx, channel)
def setup(bot):
bot.add_cog(Join(bot))<file_sep>from discord.ext import commands
from discord_slash import cog_ext
from Functions.Music.MusicExtensions import VoiceChannelExtensions
class Stop(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name = "stop")
async def command_stop(self, ctx):
await ctx.voice_client.disconnect()
await ctx.send("Leaving")
@cog_ext.cog_slash(name = "stop", description = "Leave channel")
async def slash_stop(self, ctx):
voice_client = VoiceChannelExtensions.get_voice_client(self.bot, ctx)
await voice_client.disconnect()
await ctx.send("Leaving")
def setup(bot):
bot.add_cog(Stop(bot))<file_sep>from discord.ext import commands
from discord_slash import cog_ext
description_string = "I suck your dick and play music " \
"\n-**join** <channel name> " \
"\n-**play** <local file name> " \
"\n-**stream** <video link or youtube query> " \
"\n-**volume** <0-100> " \
"\n-**stop** to stop the music and leave the channel" \
"\n-**bereso** i'll check if bereso is done " \
"\n-**<NAME>** when you want to talk with me " \
"\nI also react to @mentions"
class Base(commands.Cog):
@commands.Cog.listener()
async def on_ready(self):
print(f'Succesfully logged in!')
print('------')
@commands.command(name = "help")
async def command_help(self, ctx):
await ctx.send(description_string)
@cog_ext.cog_slash(name = "help", description = "fucking help me pls")
async def slash_help(self, ctx):
await ctx.send(description_string)
def setup(bot):
bot.add_cog(Base(bot))<file_sep>import json
from json.decoder import JSONDecodeError
import requests
import re
from discord.ext import commands
error_message = "An error has occurred, if this issue persists contact my master"
class CleverBotChat(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if message.content.startswith('<NAME> ') or self.client.user.mentioned_in(message):
message_string = message.content.replace('<NAME> ', '')
message_string = re.sub(r'<@.*>\W?','', message_string )
print(message_string)
try:
async with message.channel.typing():
reply = requests.get("", params = { 'message': message_string })
reply_text = json.loads(reply.text)
except requests.ConnectionError:
await message.channel.send(error_message)
await message.channel.send(reply_text)
def setup(bot):
bot.add_cog(CleverBotChat(bot))<file_sep>from discord.ext import commands
from discord_slash import cog_ext
from Functions.Music.MusicExtensions import VoiceChannelExtensions
class Volume(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def volume(self, ctx, volume):
voice_client = VoiceChannelExtensions.get_voice_client(self.bot, ctx)
if voice_client is None:
return await ctx.send("Not connected to a voice channel.")
if voice_client.source is None:
return await ctx.send("No Audio Playing")
voice_client.source.volume = volume / 100
await ctx.send(f"Changed volume to {volume}%")
@commands.command(name = "volume")
async def command_volume(self, ctx, volume: int):
await self.volume(ctx, volume)
@cog_ext.cog_slash(name = "volume", description = "Change volume")
async def slash_volume(self, ctx, volume: int):
await self.volume(ctx, volume)
def setup(bot):
bot.add_cog(Volume(bot))<file_sep>from discord.ext import commands
class VoiceChannelExtensions(commands.Cog):
@classmethod
async def ensure_voice(cls, bot, ctx):
voice_client = cls.get_voice_client(bot, ctx)
if voice_client is None:
if ctx.author.voice:
voice_client = await ctx.author.voice.channel.connect()
return voice_client
else:
await ctx.send("You are not connected to a voice channel.")
raise commands.CommandError("Author not connected to a voice channel.")
elif voice_client.is_playing():
voice_client.stop()
return voice_client
elif voice_client.is_connected():
return voice_client
@classmethod
def get_voice_client(cls, bot, ctx):
if type(ctx) is commands.context.Context:
return ctx.voice_client
else:
guild = bot.get_guild(ctx.guild_id)
return guild.voice_client<file_sep>import discord.errors
from discord.ext import commands
from discord_slash import cog_ext
from Functions.Music.YTDL import Source
from Functions.Music.MusicExtensions import VoiceChannelExtensions
class Stream(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def stream(self, ctx, url):
voice_client = await VoiceChannelExtensions.ensure_voice(self.bot, ctx)
if type(ctx) is commands.context.Context:
text_channel = ctx.message.channel
else:
text_channel = self.bot.get_channel(ctx.channel_id)
try:
async with text_channel.typing():
player = await Source.from_url(url, loop=self.bot.loop, stream=True)
voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)
await ctx.send(f'Now playing: {player.title}')
except discord.errors.NotFound:
ctx.send("Playing audio with unknown or unreadable title")
@commands.command(name = "stream")
async def command_stream(self, ctx, *, url):
await self.stream(ctx, url)
@cog_ext.cog_slash(name = "stream", description = "Stream audio from URL")
async def slash_stream(self, ctx, url):
await self.stream(ctx, url)
def setup(bot):
bot.add_cog(Stream(bot))
<file_sep>import discord
from discord.ext import commands
from discord_slash import cog_ext
from Functions.Music.MusicExtensions import VoiceChannelExtensions
class Play(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def play(self, ctx, url):
voice_client = await VoiceChannelExtensions.ensure_voice(self.bot, ctx)
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url))
voice_client.play(source, after=lambda e: print(f'Player error: {e}') if e else None)
@commands.command(name = "play")
async def command_play(self, ctx, *, url):
await self.play(ctx, url)
@cog_ext.cog_slash(name = "play", description = "Play a file from the local system")
async def slash_play(self, ctx, url):
await self.play(ctx, url)
def setup(bot):
bot.add_cog(Play(bot))
<file_sep>from flask import Flask, json
from flask.globals import request
import cleverbotfree
from gevent import monkey
monkey.patch_all()
api = Flask(__name__)
p_w = cleverbotfree.sync_playwright().__enter__()
c_b = cleverbotfree.Cleverbot(p_w)
p_w.stop
@api.route('/chat', methods = ['GET'])
def GetReply():
message = request.args.get('message', default=0, type = str)
reply = c_b.single_exchange(message)
if reply:
return json.dumps(reply)
else:
return json.dumps("something went wrong try again")
if __name__ == '__main__':
api.run(host='0.0.0.0', threaded = True)
<file_sep>import os
from discord.ext import commands
from discord_slash import SlashCommand
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix=commands.when_mentioned_or("Benz "),
help_command=None)
slash = SlashCommand(bot, sync_commands=True)
bot.load_extension("Functions.Base")
bot.load_extension("Functions.Talk")
bot.load_extension("Functions.CleverBotChat.CleverBotChat")
bot.load_extension("Functions.Music.Join")
bot.load_extension("Functions.Music.Play")
bot.load_extension("Functions.Music.Stream")
bot.load_extension("Functions.Music.Volume")
bot.load_extension("Functions.Music.Stop")
bot.load_extension("Functions.Selenium.BeresoCrawler")
bot.run(TOKEN)
<file_sep>from discord.ext import commands
from discord_slash import cog_ext
from selenium.webdriver.common.by import By
from selenium import webdriver
class BeresoCrawler(commands.Cog):
def __init__(self, bot):
self.driver = webdriver.Chrome(executable_path='C:/ChromeDriver/chromedriver.exe')
@commands.command(name="bereso")
async def command_help(self, ctx):
await self.crawl(self, ctx)
@cog_ext.cog_slash(name="bereso", description="i'll check if bereso is done")
async def slash_help(self, ctx):
await self.crawl(self, ctx)
@staticmethod
async def crawl(self, ctx):
self.driver.get('https://bereso.com')
assert r"Bereso" in self.driver.title
if self.driver.find_element(By.XPATH, "//*[contains(text(), 'Meine Webseite wird zurzeit vollständig überarbeitet und demnächst aufgeschaltet')]"):
await ctx.send('Bereso still is not done')
else:
await ctx.send('Bereso under construction page is no more!')
def setup(bot):
bot.add_cog(BeresoCrawler(bot))
| 395da5993f7bde0f5d7387914325eef5fe1a6484 | [
"Python",
"Text"
] | 13 | Text | FastGiove/Benz-Bot | 1822e5f0070a75c258be491fe7148815fbb54106 | 0c5ee850789f97f192c65f60d004558ad719c0e0 |
refs/heads/master | <repo_name>karnkm/NT203_62130500010_groupwork_5<file_sep>/62130500010_groupwork_5/Components/PhotoView.js
app.component('photo-view', {
props : {
zoom : Object,
},
template:
/*html*/
`
<div id="bigPicture" class="h-96 max-w-xl bg-black flex justify-center" >
<img :src="zoom.bigPictureSrc">
<div @click="zoomOut" class="w-10 h-10 absolute bg-red-400 mt-3.5 ml-28 -mr-96"></div>
</div>
`,
methods: {
zoomOut(){
this.$emit("zoom-out")
},
},
})
<file_sep>/62130500010_groupwork_5/main.js
const app = Vue.createApp({
data() {
return {
photos: [
{ picNo: "1", image: '/images/leng.png', title: 'Leng', liked: false },
{ picNo: "2", image: '/images/guy.png', title: 'Guy', liked: false },
{ picNo: "3", image: '/images/pizza.jpg', title: 'Pizza', liked: false },
{ picNo: "4", image: '/images/cake.jpg', title: 'Cake', liked: false }
],
message: '',
form: { searchText: '' },
zoom: { bigPictureSrc: '' },
isBigPicture: false,
}
},
methods: {
toggleLiked(photos) {
for (let index = 0; index < this.photos.length; index++) {
if (photos.picNo == this.photos[index].picNo) {
this.photos[index].liked = !this.photos[index].liked;
}
}
},
search() {
this.message = this.form.searchText;
},
bigPic(photos) {
for (let index = 0; index < this.photos.length; index++) {
if (photos.picNo == this.photos[index].picNo) {
this.zoom.bigPictureSrc = this.photos[index].image;
}
}
this.isBigPicture = true;
},
zoomOut() {
this.isBigPicture = false;
}
},
computed: {
countUnliked() {
return this.photos.filter(t => !t.liked).length
},
searching() {
return this.photos.filter((member) => {
return member.title.toLowerCase().includes(this.message.toLowerCase());
});
}
}
})
<file_sep>/62130500010_groupwork_5/Components/PhotoSearch.js
app.component('photo-search', {
props : {
form : Object,
},
template:
/*html*/
`
<span class="material-icons text-5xl cursor-pointer" v-show="!searchbutton" @click="searchBarToggle">search </span>
<div v-show="searchbutton"><input type="text" placeholder="Searching photos:" v-model="form.searchText"
@keyup.enter="search" class="border border-black">
<p>{{message}}</p>
<button @click="searchBarToggle" class="bg-green-500 text-white py-1 px-2 rounded">Cancel</button>
</div>
`,
methods: {
searchBarToggle() {
this.searchbutton = !this.searchbutton
},
search(){
this.$emit("search")
}
},
data() {
return {
searchbutton: false,
searchText:'',
}
},
}) | 716b7c56b3b1e8ff3a23703100e8286b6e271bbb | [
"JavaScript"
] | 3 | JavaScript | karnkm/NT203_62130500010_groupwork_5 | 04c400c380605043e452cb58bc32bb8f4b115638 | 3d0069e77886710af4256dd3c0a4720b63cdff72 |
refs/heads/main | <repo_name>luism3861/Recyclerlistview-with-RNN<file_sep>/README.md
Example call API with Recycler List View and React Native Navigation
install App:
- npm install or yarn install
<file_sep>/src/utils/LayoutUtil.js
import { LayoutProvider } from 'recyclerlistview';
import { Dimensions } from 'react-native';
export const getLayoutProvider = (type) => {
const getWindowWidth = Math.round(Dimensions.get('window').width * 1000) / 1000 - 6;
switch (type) {
case 0:
return new LayoutProvider(
() => {
return 'VSEL';
},
(type, dim, index) => {
const columnWidth = getWindowWidth / 3;
switch (type) {
case 'VSEL':
if (index % 3 === 0) {
dim.width = 3 * columnWidth;
dim.height = 300;
}
break;
default:
dim.width = 0;
dim.heigh = 0;
}
}
);
}
}<file_sep>/src/components/ImageRenderer.js
import React from 'react';
import {Image, View} from 'react-native';
export const ImageRenderer = ({imageUrl}) => {
return (
<View style={{marginBottom: 20}}>
<Image
style={{
width: '100%',
height: '100%',
}}
source={{uri: imageUrl}}
/>
</View>
);
};
| a9411e088639dc9a250d9c6104bd7b07fa975c18 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | luism3861/Recyclerlistview-with-RNN | dbc083627c8e551d44d1f000de03c4c6a870399b | de8bc2300df9aa558e2c861962bc3d09b9e5b43f |
refs/heads/main | <repo_name>by777/Pytorch--<file_sep>/CH04_两阶段经典检测器FasterRCNN/RCNN系列发展历程.md
> RCNN(Regions with CNN Features)
# 开山之作:RCNN3
+ 发表于:CVPR 2014
+ 检测率(PASCAL VOC):从35.1% 提升到了 53.7%
具体流程:
1. **候选区域生成**。采用Region Proposal提取候选区域,例如Selective Search。先将候选区域分割成小区域,然后合并包含同一物体可能性高的区域,并输出。这一步需要提取约2000个候选区域。在提取完后,还需要对每一个区域归一化。得到固定大小的图像。
2. **CNN特征提取**。利用CNN得到固定维度的特征输出。
3. **SVM分类器**。利用线性二分类器对输出的特征分类,得到是否属于此类的结果,并且采用**难样本挖掘**来平衡正负样本的不平衡。
4. **位置精修**。通过一个回归器,对特征边界回归得到更精确的目标区域。
# 端到端:Fast RCNN
在RCNN后,SPPNet解决了重复卷积计算与固定输出尺度的两个问题。
在2015年,提出了端到端的Fast RCNN,基于VGG16,训练速度上比RCNN快了近9倍,测试速度上快了213倍,在VOC 2012上达到了68.4%的准确率。
相比于RCNN,Fast RCNN主要有以下改进:
+ **共享卷积**。将整幅图送到CNN进行区域生成,而不是像RCNN那样一个个的候选区域,虽然仍采用Selective Search方法,但共享卷积使得计算量大大减少。
+ **RoI Pooling**。利用特征池化(RoI Pooling)的方法进行特征尺度变换,这种方法可以有任意大小的输入,使得训练过程更加灵活准确。
+ **多任务损失**。将分类和回归任务放到一起训练,并且为了避免SVM分类器带来的单独训练与速度慢的缺点,使用了softmax函数分类。
**缺点**:Seective Search消耗了2~3秒,远大于特征提取的0.2秒。
# 走向实时:Faster RCNN
+ 发表于 NIPS 2015
+ 创新点:提出了RPN(Region Proposal Network)
+ Anchor-base
+ 速度:17 FPS
+ 在VOC 2012测试集上准确率:70.4%
# Anchor
Anchor可以看作图像上许多固定大小与宽高的方框,由于需要检测的物体本身也都是一个个宽高不同的方框,因此Faster RCNN将Anchor动作强先验的知识,接下来只需要将Anchor与真实物体匹配,进行分类与位置的微调而已。相比于没有Anchor的物体检测算法,这样无疑降低了网络收敛的难度。
<file_sep>/CH03_网络骨架:Backbone/densenet调用.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/11 16:55
# @AUTHOR : <NAME>
# @FILE : densenet调用.py
# @DESCRIPTION :
import torch
from densenet_block import Denseblock
# 包含6个bottleneck
denseblock = Denseblock(64, 32, 6)
print(denseblock)
print('第1个输bottleneck的输入通道为64,输出固定为32')
print('第2个输bottleneck的输入通道为96,输出固定为32')
print('第3个输bottleneck的输入通道为128,输出固定为32')
print('第4个输bottleneck的输入通道为160,输出固定为32')
print('第5个输bottleneck的输入通道为192,输出固定为32')
print('第6个输bottleneck的输入通道为224,输出固定为32')
input = torch.randn(1, 64, 256, 256)
output = denseblock(input)
print('输出通道数为:224 + 32 = 64 + 32 x 6 = 256')
print(output.shape)
<file_sep>/CH03_网络骨架:Backbone/densenet介绍.md
# DenseNet
ResNet缓解了梯度消失。DenseNet将前后层Shortcuts前后层交流,通过建立前面所有层与后面层的密集连接,实现了通道维度上的复用。使其**可以在参数参与计算量更小的情况下实现比ResNet更优的性能。**
DenseNet的网络架构,由多个Dense Block与中间的卷积层池化组成。核心就在Dense Block中。DenseBlock中的黑点代表一个卷积层,其中的多条黑线代表数据的流动,每一层的输入都由前面所有的卷积层输出组成。注意这里使用了通道拼接Concatate操作,而非ResNet逐元素相加。
# DenseNet的特性
+ 神经网络一般需要池化等操作缩小特征图尺寸来提取语义特征,而Dense Block需要保持每一个Block内的特征图尺寸一致来进行Concatenate操作,因此DenseNet被分成了多个Block,一般4个。
+ 两个相邻的Dense Block之间的部分被称为Transition层,具体包括BN,ReLU,1x1卷积,2x2平均池化。1x1卷积为了降维,起到压缩模型的作用,而平均池化则是降低特征图尺寸。

# 关于Block,有4个特性需要注意
+ 每一个Bottleneck输出的特征通道数是一致的,例如上面的32,。同时可以看到,通过concatenate操作后通道数是按32的增长量来计算的,因此32也称为GrowthRate。
+ 这里1x1卷积的作用是固定输出通道数,达到降维的作用。当几十个bottlenek相连接时,Concatnate后的通道数会增加到上千,如果不增加1x1卷积来降维,后续3x3卷积所需的参数量会急剧增加。1x1卷积的通道数通常是GrowthRate的4倍。
+ Block采用了激活函数在前、卷积层在后的顺序,这与一般的网络是不同的。
# 优势
+ 密集连接的网络,使得每一层都会接受到其后所有层的梯度,而不是像普通卷积链式的反传,因此一定程度上解决了梯度消失的问题
+ 通过Concatenate使得大量特征被复用,每个层独有的特征图的通道数是少的,因此相比Resnet,它的参数量更少
# 不足
多次的concatenate使得数据被复制多次,显存增加的很快,需要一定的显存优化技术。另外Resnet应用更广泛一些。
<file_sep>/CH03_网络骨架:Backbone/inception介绍.md
# Inception v1
一般来说,增加网络的深度与宽度可以增加网络的性能。但是这样也会增加网络的参数量,同时较深的网络需要较多的数据,否则容易出现过拟合。除此之外,还有可能梯度消失。
Inception v1是一个精心设计的22层网络结构,并提出了具有良好局部特征结构的Inception模块,即对特征并行的执行多个大小不同的卷积运算和池化。最后**拼接**到一起。
由于1 x 1、3 x 3、5 x 5的卷积运算对应不同的特征图区域,因此可以得到更好的图像表征信息。

Inception模块如图所示,使用了3个大小不同的卷积核进行卷积运算,同时还有一个最大池化。然后将这4部分级联起来(通道拼接)送入下一层。
在上述基础上,为了进一步降低网络藏书量,Inception增加了多个 1 x 1卷积。这种1 x 1卷积块可以先将特征图降维,再送入 3 x 3和5 x 5的卷积核,由于通道数降低,参数量也显著减少。

<u>Inceptionv1是AlexNet的1/12,VGG的1/3,适合处理大规模数据,尤其是计算资源有限的平台。</u>
# Inception v2
Inception v2通过卷积分解与正则化实现更高效的计算,增加了BN层,同时利用两个级联的3 x 3卷积取代了Inception v1的 5 x 5卷积。这种方式即减少了卷积参数量,又增加了网络的非线性能力。

# Inception v3
Inception v3在v2的基础上使用了RMSProp优化器,在辅助的分类器部分增加了 7 x 7的卷积,并且使用了标签平滑技术。
# Inception v4
Inception v4将inception的思想与残差网络结合。
<file_sep>/CH03_网络骨架:Backbone/densenet_block.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/11 16:43
# @AUTHOR : <NAME>
# @FILE : densenet_block.py
# @DESCRIPTION :
import torch
import torch.nn.functional as F
from torch import nn
# 实现一个Bottleneck的类,初始化需要输入通道数与GrowhRate这两个参数
class Bottleneck(nn.Module):
def __init__(self, nChannels, growthRate):
super(Bottleneck, self).__init__()
# 通常1x1卷积的通道数为GrowthRate的4倍
interChannels = 4 * growthRate
self.bn1 = nn.BatchNorm2d(nChannels)
self.conv1 = nn.Conv2d(nChannels, interChannels, kernel_size=1, bias=False)
self.bn2 = nn.BatchNorm2d(interChannels)
self.conv2 = nn.Conv2d(interChannels, growthRate, kernel_size=3, padding=1, bias=False)
def forward(self, x):
out = self.conv1(F.relu(self.bn1(x)))
out = self.conv2(F.relu(self.bn2(out)))
# 将输入与计算的结果out拼接
out = torch.cat((x, out), 1)
return out
class Denseblock(nn.Module):
def __init__(self, nChannels, growthRate, nDenseBlocks):
super(Denseblock, self).__init__()
layers = []
# 将每一个Bottleneck利用Sequential整合起来,输入通道数需要线性增长
for i in range(int(nDenseBlocks)):
layers.append(Bottleneck(nChannels, growthRate))
nChannels += growthRate
self.denseblock = nn.Sequential(*layers)
def forward(self, x):
return self.denseblock(x)
<file_sep>/CH03_网络骨架:Backbone/resnet介绍.md
# ResNet
ResNet的思想在于引入了一个**深度残差框架**来解决梯度消失问题。<u>即让CNN去学习残差映射,而不是期望每一个堆叠层都能完整地拟合潜在的映射(拟合函数)</u>。
对于神经网络,如果我们期望的网络最终映射为H(x),左侧的网络需要直接拟合输出H(x),而右侧由ResNet提出的子模块、通过引入一个shortcut分支,把需要拟合的映射变为残差F(x):H(x)-x。ResNet给出的假设是:
相较于直接优化潜在映射,优化残差映射F(x)是更容易的。

<file_sep>/CH03_网络骨架:Backbone/detnet调用.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/14 16:30
# @AUTHOR : <NAME>
# @FILE : detnet调用.py
# @DESCRIPTION :
import torch
from torch import nn
from detnet_bottkeneck import DetBottleneck
# 完成一个stage 5,即B-A-A结构,Stage 4输出通道数为1024
bottleneck_b = DetBottleneck(1024, 256, 1, True)
print(bottleneck_b)
bottleneck_a1 = DetBottleneck(256, 256)
bottleneck_a2 = DetBottleneck(256, 256)
input = torch.randn(1, 1024, 14, 14)
output1 = bottleneck_b(input)
output2 = bottleneck_a1(output1)
output3 = bottleneck_a2(output2)
print(output1.shape, output2.shape, output3.shape)
<file_sep>/CH03_网络骨架:Backbone/特征金字塔FPN.md
# 多尺度问题
为了增强语义性,传统的特征检测模型只在CNN的最后一个特征图上进行后续操作,而这一层对应的下采样率(缩小的倍数)又通常比较大,如16、32。造成小物体的检测性能较低。
# 图像金字塔(Image Pyramid)
主要思路在于提取多尺度特征,通过将输入图片做成多个尺度,不同尺度的图像对应生成不同尺度的特征。这样做简单高效,也耗时。
# FPN(Feature Pyramid Network)
主要包含:自下而上网络、自上而下网络、横向连接与卷积融合4个部分。

+ **自下而上**:最左侧代表普通的卷积网络,默认使用ResNet结构,用作提取语义信息。C1代表了ResNet的前几个卷积层与池化层,而C2~C5分别为不同的ResNet卷积组,这些卷积组包含了多个Bottleneck结构,组内特征图大小相同,组件大小递减。
+ **自上而下**:首先对C5进行1x1卷积降低通道数得到P5,然后依次进行**上采样**得到P4、P3和P2,目的是得到与C4、C3、C2长宽相同的特征。以方便下一步的逐元素相加。这里采用2倍最邻近上采样,即直接对临近元素进行复制,而非线性插值。
+ **横向连接(Lateral Connection)**:目的是将**上采样后的高语义特征与浅层的定位细节特征**进行融合。高语义特征经过上采样后,其长宽与对应的浅层特征相同,其通道数固定为256,因此需要对底层特征C2~C4进行1x1卷积使得通道数变为256,然后两者进行逐元素相加得到P4、P3、P2。由于C1特征图尺寸较大且语义信息不足,因此没有把C1放到横向连接中。
+ **卷积融合**:在得到相加的特征后,利用3x3卷积再对生成的P2至P4再进行融合。目的是消除上采样过程中带来的重叠效应,以此生成最终的特征图。
> 自下而上指的是金字塔从下到上
# RoI(Region of Interests)
对于实际的目标检测算法,需要对特征图上进行RoI提取。而FPN有4个输出的特征图,选择哪一个特征图上的特征也是个问题。FPN给出的解决方法是。对于不同大小的RoI,使用不同的特征图,大尺度的RoI再深层的特征图上进行提取,如P5,小尺度的RoI在浅层的特征图上提取,如P2。<file_sep>/CH03_网络骨架:Backbone/resnet_bottleneck.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/7 17:08
# @AUTHOR : <NAME>
# @FILE : resnet_bottleneck.py
# @DESCRIPTION :
import torch.nn as nn
class Bottleneck(nn.Module):
def __init__(self, in_dim, out_dim, stride=1):
super(Bottleneck, self).__init__()
# 网络堆叠层是由 1x1 3x3 1x1 这3个卷积组成的,中间包含BN层
self.bottleneck = nn.Sequential(
nn.Conv2d(in_dim, in_dim, 1, bias=False),
nn.BatchNorm2d(in_dim),
nn.Conv2d(in_dim, in_dim, 3, stride, 1, bias=False),
nn.BatchNorm2d(in_dim),
nn.Conv2d(in_dim, out_dim, 1, bias=False),
nn.BatchNorm2d(out_dim)
)
self.relu = nn.ReLU(inplace=True)
# 利用下采样结构把恒等映射的通道数映射为与卷积堆叠层相同,保证可以相加
self.downsample = nn.Sequential(
nn.Conv2d(in_dim, out_dim, 1, 1),
nn.BatchNorm2d(out_dim)
)
def forward(self, x):
identity = x
out = self.bottleneck(x)
identity = self.downsample(x)
########################################################
# 将identity(恒等映射)与网络堆叠层输出相加,并经过ReLU后输出 #
########################################################
out = out + identity
out = self.relu(out)
return out
<file_sep>/CH03_网络骨架:Backbone/fpn调用.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/12 20:41
# @AUTHOR : <NAME>
# @FILE : fpn调用.py
# @DESCRIPTION :
from fpn import FPN
import torch
net_fpn = FPN([3, 4, 6, 3])
print('FPN的第一个卷积层:')
print(net_fpn.conv1)
print('FPN的第一个BN层:')
print(net_fpn.bn1)
print('FPN的第一个relu层:')
print(net_fpn.relu)
print('FPN的第一个池化层:')
print(net_fpn.maxpool)
print('\n')
print('FPN的第一个layer,即前面的C2,包含了3个Bottleneck')
print(net_fpn.layer1)
print('\n')
print('FPN的第二个layer,即前面的C3,包含了4个Bottleneck')
print(net_fpn.layer2)
print('\n')
print('FPN的第三个layer,即前面的C4,包含了6个Bottleneck')
print(net_fpn.layer3)
print('\n')
print('1x1卷积,用以得到P5')
print(net_fpn.toplayer)
print('\n')
print('对P4平滑处理的卷积层')
print(net_fpn.smooth1)
print('\n')
print('对C4横向处理的卷积层')
print(net_fpn.latlayer1)
input = torch.randn(1, 3, 224, 224)
output = net_fpn(input)
print('\n')
print('返回的P2、P3、P4、P5,这四个特征图通道数相同,但是特征图尺寸递减')
print(output[0].shape, output[1].shape, output[2].shape, output[3].shape)
<file_sep>/CH03_网络骨架:Backbone/detnet介绍.md
# DetNet
如VGG和ResNet等,究其根本是为了图像分类任务而设计的。但图像分类和检测任务天然存在落差,分类任务侧重于全图特征的提取,深层的特征图分辨率较低,而目标检测特征图分辨率不宜过低,因此造成了以下两种缺陷:
+ 大物体难以定位:FPN的采样率较大,边缘难以精确预测
+ 小物体难以检测:小物体在浅层的语义信息较弱,几乎不可见
DetNet选用ResNet作为基础结构,*旷视科技*引入了空洞卷积。
DetNet仍选择性能卓越的ResNet-50作为基础结构。并且保持前4个stage与Resnet-50相同,具体的结构细节有以下3点:
1. 引入了一个新的Stage 6,用于物体检测。Stage 5和Stage 6使用了DetNet提出的Bottleneck结构,最大的特点是利用空洞数为2的3x3卷积取代了步长为2的3x3卷积。
2. Stage 5与Stage 6的每一个Bottlneck输出的特征图尺寸都为原图的1/16。通道数都为256,而传统的Backbone通常是特征图尺寸递减,通道数递增。
3. 在组成特征金字塔时,由于特征图大小完全相同,因此可以直接从右往左传递相加,避免了上采样。为了进一步融合各通道的特征,需要对每一阶段的输出进行1x1卷积后再与后一Stage传回的特征相加。
DetNet这种精心设计的结构,在增加感受野的同时,获得了极大的特征图尺寸,有利于物体的定位。与此同时,由于各Stage的特征图尺寸相同,避免了上采样,降低了计算量,又有利于小物体的检测。

<file_sep>/CH02_PyTorch基础/2.4_模型处理.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/7 10:50
# @AUTHOR : <NAME>
# @FILE : 2.4_模型处理.py
# @DESCRIPTION :
from torch import nn
from torchvision import models
vgg = models.vgg16()
print(len(vgg.features),len(vgg.classifier))
print(vgg.classifier[-1])<file_sep>/CH04_两阶段经典检测器FasterRCNN/FasterRCNN总览.md
# Faster RCNN
主要分为:
+ 特征提取网络
+ RPN模块
+ RoI Pooling
+ RCNN模块
# 特征提取网络Backbone
输入图像首先经过Backbone得到特征图,在此以VGGNet为例,假设输入的图像为3 x 600 x 800,由于VGGNet下采样率为16,因此输出的feature map的维度为512 x 37 x 50。
# RPN模块
**区域生成模块。其作用是生成较好的建议框,即Proposal**,这里用到了强先验的Anchor。RPN包括了5个子模块:
1. **Anchor生成**。RPN对**feature map上的每一个点都对应了9个Anchor**,这9个Anchor的大小宽高不同,对应到原图基本可以覆盖所有可能出现的物体。因此,有了数量庞大的Anchor,RPN的接下来任务就是从中筛选,并调整更好的位置,得到Proposal。
2. **RPN网络**。与上面的Anchor对应,由于feature map上每个点都对应了9个anchor,因此可以利用1 x 1卷积再feature map上**得到每一个Anchor的预测得分与预测偏移值**。
3. **计算RPN Loss**。这一步旨在训练中,将所有的Anchors与标签匹配,匹配程度较好的赋予正样本,较差的赋予负样本,得到分类与偏移的真值,与第二步中的预测得分与预测偏移值进行loss的计算。
4. **生成Proposal**。利用第二步中每一个Anchor的预测得分与偏移量,可以进一步得到一组较好的Proposal,送到后续网络中。
5. **筛选Proposal得到RoI**。在训练时,由于Proposal的数量还是太多(默认是2000),需要进一步筛选得到RoI(默认256个)。在测试阶段,则不需要该模块,Proposal可以直接作为RoI,默认数量是300。
6. **RoI模块**。这部分承上启下,接受CNN提取的feature map和RPN的RoI。输出送到RCNN网络中。由于RCNN模块采用了全连接网络,要求特征的维度固定,而每一个RoI对应的特征大小各不相同,无法送入全连接网络,因此**RoI Pooling将RoI的特征池化到固定的维度,方便送到全连接网络中**。
7. **RCNN模块**。将RoI得到的特征送入全连接网络,预测每一个RoI的分类,并预测偏移量以精修边框位置,并计算损失,完成整个Faster RCNN过程。主要包含3个部分:
- **RCNN全连接网络**。将得到的固定维度的RoI特征接到全连接网络中,输出为RCNN部分的预测得分与预测回归偏移量。
- **计算RCNN的真值**。对应筛选出的RoI,需要确定是正样本还是负样本,同时 计算真实物体的偏移量。在实际实现时,为实现方便,这一步往往与RPN最后实现RoI那一步放到一起。
- **RCNN Loss**。通过RCNN的预测值与RoI部分的真值,计算分类与回归Loss。
通过整个过程可以看出,Faster RCNN是一个两阶段的算法,即RPN与RCNN,这两步都需要计算损失,只不过前者还要为后者提供较好的感兴趣区域。
```python
# RPN
# 输入:feature map、物体标签,即训练集中所有物体的类别和标签位置
# 输出:Proposal、分类Loss、回归Loss、其中,Proposal作为生成的区域,供后续模块分类# 和回归。两部分损失用作优化网络。
def forward(self, im_data, im_info, gt_boxes, num_boxes):
# 输入数据的第一维是batch数
batch_size = im_data.size()
im_info = im_info.data
gt_boxes = gt_boxes.data
num_boxes = num_boxes.data
# 从VGGNet的backbone获取feature map
base_feat = self.RCNN_base(im_data)
# 将feature map送入RPN得到Proposal与分类与回归Loss
rois, rpn_loss_cls, rpn_loss_bbox = self.RCNN_rpn(base_feat, im_info, gt_boxes, num_boxes)
...
```
# 理解Anchor
Anchor的本质是在原图大小上的一系列的矩形框,但Faster RCNN将这一系列的矩形框与feature map进行了关联。具体做法是,首先对feature map进行3 x 3卷积,得到每一个点的维度是512维,这512维的数据对应原始图像上的很多不同的大小与宽高区域的特征,这些区域的中心点都相同。如果下采样率维默认的16,则每一个点的而坐标乘以16即可得到对应的原始坐标。
为了适应不同物体的宽高,在作者的论文中,默认每一个点上抽取了9种Anchors,具体Scale为{8,16,32},Ratio为{0.5,1,2},将9种Anchors的大小反算到原图上,即得到不同原始Proposal。由于feature map的大小为37 x 50,因此一共有37 x 50 x 9 = 16650个Anchors。而后通过分类网络与回归网络得到每一个Anchor的前景背景概率和偏移量,前景背景概率原来判断Anchor是前景的概率,回归网络则将预测偏移量作用到Anchor使得Anchor更接近真实物体坐标。

```python
def generate_anchors(base_size=16,ratios=[0.5,1,2],scales=2**np.arange(3,6)):
# 首先创建一个基本anchor为[0,0,15,15]
base_anchor = np.arange([1,1,base_size,base_size]) - 1
# 将基本anchor进行宽高变换,生成3种宽高比的s:Anchor
ratio_anchor = _ratio_enum(base_anchor,ratio)
# 将上述anchor尺度变换,得到最终9种Anchors
anchors = np.vstack([_scale_enum(ratio_anchors[i,:],scales) for i in xrange(ratio_anchors.shape[0])])
# 返回对应于feature map大小的anchors
return anchors
```
# RPN的真值与预测值
对于物体检测任务来说,模型需要预测物体的类别与出现的位置。即类别、中心点坐标x和y、w和h,5个量。由于有了anchor先验框,RPN可以预测Anchor的类别作为预测边框的类别,并且可以预测真实的边框相对于anchor的偏移量,而不是直接预测边框的中心点坐标和宽高(x,y,w,h)。
举个例子,输入图像中有3个Anchors与两个标签,从位置来看,Anchor A,C分别于标签M、N有一定的重叠,而Anchor B的位置更像是背景。

+ 首先介绍**模型的真值**。
对于类别的真值,由于RPN只负责区域生成,保证Recall,而没必要细分每一个区域属于哪一个类别,因此只需要前景与背景两个类别,前景即有物体,背景则没有物体。
RPN通过计算Anchor与标签的IoU来判断Anchor是属于前景还是背景,**当IoU大于一定值时,该Anchor的真值为前景**,低于一定值时,该Anchor的真值为背景。
+ 然后是**偏移量的真值**。
仍以上图的Anchor A与label M为例,假设Anchor A中心坐标为X_a与Y_a,宽和高为W_a和H_a,label M的中心坐标为x和y,宽高为w和h,则对应的偏移真值计算公式如下:
$$
t_x = (x - x_a) / w_a \\
t_y = (y - y_a) / h_a \\
t_w = log(\frac{w}{w_a}) \\
t_h = log(\frac{h}{h_a}) \\
$$
从上式中可以看出,**位置偏移t_x与t_y利用宽高进行了归一化,而宽高偏移t_w和t_h进行了对数处理**,这样做的好处在于进一步限制了偏移量的范围,便于预测。
有了上述的真值,为了求取损失,RPN通过CNN分别得到了类别与偏移量的预测值。具体来讲,RPN需要预测每一个Anchor属于前景后景概率,同时还需要预测真实物体相对于Anchor的偏移量,记为
$$
t_x^*、t_y^*、t_w^*、t_h^*
$$
另外,在得到预测偏移量后,可以使用下面的公式讲预测偏移量作用到对应的Anchor上,得到预测框的实际位置
$$
x^*、y^*、w^*、h^*
$$
$$ \begin{aligned}
t_x^* = (x - x_a) / w_a
t_y^* = (y - y_a) / h_a
t_w^* = log(\frac{w}{w_a})
t_h^* = log(\frac{h}{h_a})
\end{aligned}
$$
<file_sep>/CH03_网络骨架:Backbone/resnet调用.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/7 15:54
# @AUTHOR : <NAME>
# @FILE : resnet调用.py
# @DESCRIPTION :
import torch
from resnet_bottleneck import Bottleneck
bottleneck_1_1 = Bottleneck(64, 256)
print(bottleneck_1_1)
input = torch.randn(1, 64, 56, 56)
output = bottleneck_1_1(input)
print(input.shape)
print(output.shape)
print('相比输入,输出的特征图的分辨率没变,而通道数变为4倍')
<file_sep>/README.md
"# Pytorch--"
"# Pytorch--"
<file_sep>/CH03_网络骨架:Backbone/vgg调用.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/6 20:55
# @AUTHOR : <NAME>
# @FILE : vgg_调用.py
# @DESCRIPTION :
import torch
from vgg import VGG
vgg = VGG(21)
input = torch.randn(1, 3, 224, 224)
print(input.shape)
scores = vgg(input)
print(scores)
print(scores.shape)
print(vgg.features)<file_sep>/CH01_物体检测基本知识/基础补充.md
# 发展历程
在利用深度学习做物体检测之前。传统算法对物体的检测通常分为`区域选取` `特征提取` `特征分类`这3个阶段。
1. 区域选取:如Sliding Windows
2. 特征提取:如SIFT和HOG等
3. 特征分类:如SVM、AdaBoost等
# 评价指标
IoU的计算:
```python
def iou(boxA, boxB):
# 计算重合部分的上、下、左、右4个边的值,注意最大最小函数的使用
left_max = max(boxA[0], boxB[0])
top_max = max(boxA[1], boxB[1])
right_min = min(boxA[2], boxB[2])
bottom_min = min(boxA[3], boxB[3])
# 计算重合部分的面积
inter = max(0, (right_min-left_max)) * max(0,(bottom_min-top_max))
Sa = (boxA[2]-boxA[0]) * (boxA[3] - boxA[1])
Sb = (boxB[2]-boxB[0]) * (boxB[3] - boxB[1])
union = Sa + Sb - inter
iou = inter / union
return iou
```
对于IoU而言,大于0.5时通常才认为是一个有效的检测。

由于图像中存在背景与物品两种标签,预测框也分为正确与错误,因此在评测时会产生以下4中样本:
+ 正确检测框TP(True Positive):正确的,如图
+ 误检框FP(False Positive):将背景预测成了物体
+ 漏检框FN(False Negative):本来需要检测出的物体没有检测出
+ 正确背景TN(True Negative):本身是背景,模型也没有检测出来
# mAP(Mean Average Precision)
AP指的是一个类别的检测精度,mAP是多个类别的平均精度
+ 预测值(Dets):物体类别、边框位置的4个预测值、该物体的得分
+ 标签值(GTs):物体类别,边框位置的4个真值
# Recall, R
当前一共检测出的标签框与所有标签框的比值
# Precision, P
当前遍历过的预测框中,属于正确预测框的比值
# P-R Curve
遍历到每一个预测框时,都可以生成一个对应的P和R,将所有的点绘制成曲线,就成了P-R曲线。

但如果直接选取曲线上的点,召回率高的时候准确率很低,准确率高的时候召回率很低。这时使用
$$
AP = ∫^1_0PdR
$$
# 常用工具
+ apt install terminator
+ apt install screen
| 操作 | 含义 |
| :-------------- | :------------------------- |
| screen -S name | 新建一个叫name的窗口 |
| ctrl+a->ctrl+d | 关闭当前的Screen窗口 |
| ctrl+a->k->y | 永久性删除当前的Screen窗口 |
| screen -ls | 列举所有当前的Screen窗口 |
| screen - r name | 回到name窗口 |
<file_sep>/CH03_网络骨架:Backbone/inceptionv1.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/7 15:28
# @AUTHOR : <NAME>
# @FILE : inceptionv1.py
# @DESCRIPTION :
import torch
from torch import nn
from torch.nn import functional as F
# 定义基础卷积类
class BasicConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, padding=0):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, padding=padding)
def forward(self, x):
x = self.conv(x)
return F.relu(x, inplace=True)
class Inceptionv1(nn.Module):
def __init__(self, in_dim, hide_1_1, hide_2_1, hide_2_3, hide_3_1, out_3_5, out_4_1):
super(Inceptionv1, self).__init__()
# 下面是4个子模块各自的网络定义
self.branch1x1 = BasicConv2d(in_dim, hide_1_1, 1)
self.branch3x3 = nn.Sequential(
BasicConv2d(in_dim, hide_2_1, 1),
BasicConv2d(hide_2_1, hide_2_3, 3, padding=1)
)
self.branch5x5 = nn.Sequential(
BasicConv2d(in_dim, hide_3_1, 1),
BasicConv2d(hide_3_1, out_3_5, 5, padding=2)
)
self.branch_pool = nn.Sequential(
nn.MaxPool2d(3, stride=1, padding=1),
BasicConv2d(in_dim, out_4_1, 1)
)
def forward(self, x):
b1 = self.branch1x1(x)
b2 = self.branch3x3(x)
b3 = self.branch5x5(x)
b4 = self.branch_pool(x)
# 将这3个子模块沿着通道方向拼接
output = torch.cat((b1, b2, b3, b4), dim=1)
return output
<file_sep>/CH03_网络骨架:Backbone/空洞卷积_backbone_neck_head介绍.md
[参考连接]: https://www.zhihu.com/zvideo/1356732245315805184
# 空洞卷积(Dilated Convolution)
空洞卷积最初是为解决图像分割问题而提出的。常见的图像分割算法通常使用池化层来增大感受野。同时也缩小了特征图尺寸,然后利用上采样还原图像尺寸。特征图缩小再放大造成了精度上的损失,因此需要一种操作能够在增加感受野的同时特征图的尺寸不变,从而代替池化和上采样操作。因此,空洞卷积就诞生了。
**空洞卷积**,卷积核中带有一些洞,跳过一些元素进行卷积。在代码实现时,空洞卷积有一个额外的超参数dilation rate默认为1,表示空洞数。
# Backbone、neck和head
在One-Stage Anchor free的检测器中,我们习惯性的将整个网络划分为3个部分:`backbone` 、`neck`和`head`。
## backbone: VGG\ResNet\ResNeXt\EfficientNet
当前物体检测算法各不相同,但第一步通常是利用CNN处理图像,生成特征图,然后再利用各种算法完成区域生成和损失计算,这部分CNN是整个检测算法的“骨架”,也称为Backbone。
每一个被选择特征图都有内在固有的语义表达能力。即:使用这个特征图做后面的预测,它到底能学什么、能学多好,可能就已经内定了。
特征图上每个位置上的感受野已经确定了,也就是它看到了什么区域已经非常明确了,让它去预测超过这个区域的目标,其实就不合理了。看到了但是能不能学好又是另一回事了。这个就和backbone的结构设计就有很大关系了。
**总结:backbone能为检测提供若干种感受野大小和中心步长的组合,以满足对不同尺度和类别的目标检测。**
## neck:Naiveneck\FPN\BiFPN\PANet\NAS-FPN
neck接受来自backbone的若干个特征图,处理后再输出给head。NaiveNeck:其实也就是没有neck,如SSD。
neck的第一要务就是进行特征融合:具有不同感受野大小的特征图进行了耦合,从而增强了特征图的表达能力。neck决定了head的数量,不同尺度的目标被分配到不同的Head学习,即:学习的负担被分散到了多个层级的特征图上。此外,进行宽带对齐,便于后续使用。
## head:RetinaNet-Head\FCOS-Head
划分方式1:有无Anchor:RetinaNet就是anchor-based,同时没有quality分支
划分方式2:有无quality分支:FCOS:anchor-free的,同时有quality分支
head通常会分为分类分支和回归分支,且两个分支独立不共享权重(但不一定)。

<file_sep>/CH03_网络骨架:Backbone/vgg.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/6 20:40
# @AUTHOR : <NAME>
# @FILE : vgg.py
# @DESCRIPTION : VGG16
from torch import nn
class VGG(nn.Module):
def __init__(self, num_classes=1000):
super(VGG, self).__init__()
layers = []
in_dim = 3
out_dim = 64
# 循环构建卷积层,一共有13个卷积层
for i in range(13):
layers += [nn.Conv2d(in_dim, out_dim, 3, 1, 1), nn.ReLU(inplace=True)]
in_dim = out_dim
# 在第2,4,7,10,13个卷积层后增加池化层
if i == 1 or i == 3 or i == 6 or i == 9 or i == 12:
layers += [nn.MaxPool2d(2, 2)]
# 第10个卷积后保持与前边的通道数一致,都为512,其余加倍
if i != 9:
out_dim *= 2
self.features = nn.Sequential(*layers)
# VGG的3个全连接层,中间有ReLU和Dropout层
self.classifier = nn.Sequential(
nn.Linear(512 * 7 * 7, 4096),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(4096, num_classes)
)
def forward(self, x):
x = self.features(x)
# 将特征图从[1,512,7,7]变到[1,512*7*7] #
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
<file_sep>/CH03_网络骨架:Backbone/inceptionv2调用.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/7 16:07
# @AUTHOR : <NAME>
# @FILE : inceptionv2调用.py
# @DESCRIPTION :
import torch
from inceptionv2 import Inceptionv2
net = Inceptionv2()
input = torch.randn(2, 192, 32, 32)
out = net(input)
print(out)
<file_sep>/CH03_网络骨架:Backbone/inceptionv1调用.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/7 15:46
# @AUTHOR : <NAME>
# @FILE : inceptionv1调用.py
# @DESCRIPTION :
import torch
from inceptionv1 import Inceptionv1
net_inceptionv1 = Inceptionv1(3, 64, 32, 64, 64, 96, 32)
print(net_inceptionv1)
input = torch.rand(2,3,256,256)
# print(input)
output = net_inceptionv1(input)
print(output.shape)<file_sep>/CH03_网络骨架:Backbone/detnet_bottkeneck.py
# -*- coding: utf-8 -*-
# @TIME : 2021/7/13 21:41
# @AUTHOR : <NAME>
# @FILE : detnet_bottkeneck.py
# @DESCRIPTION :
import torch
from torch import nn
class DetBottleneck(nn.Module):
# 初始化时extra为False时为Bottleneck A, 为B时为Bottleneck B
def __init__(self, inplanes, planes, stride=1, extra=False):
super(DetBottleneck, self).__init__()
# 构建连续3个卷积层的Bottleneck
self.bottleneck = nn.Sequential(
nn.Conv2d(inplanes, planes, 1, bias=False),
nn.BatchNorm2d(planes),
nn.ReLU(inplace=True),
nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=2, dilation=2, bias=False),
nn.BatchNorm2d(planes),
nn.ReLU(inplace=True),
nn.Conv2d(planes, planes, kernel_size=1, bias=False),
nn.BatchNorm2d(planes)
)
self.relu = nn.ReLU(inplace=True)
self.extra = extra
# Bottleneck B为1x1卷积
if self.extra:
self.extra_conv = nn.Sequential(
nn.Conv2d(inplanes, planes, 1, bias=False),
nn.BatchNorm2d(planes)
)
def forward(self, x):
if self.extra:
identity = self.extra_conv(x)
else:
identity = x
out = self.bottleneck(x)
out += identity
out = self.relu(out)
return out
<file_sep>/CH06_单阶段经典检测器YOLO/YOLOv1.md
# YOLO v1
+ 时间:2015
YOLO v1将输入图像划分为7 x 7的区域,每一区域对应最后特征图上的一个点,该点的通道数为30,代表了预测的30个特征。
YOLO v1在每一个区域预测了两个框,这样整个图上一共预测7 x 7 x 2 = 98个框,这些框的大小与位置各不相同,基本可以覆盖整个图上可能出现的物体。

如果一个物体的中心点落在了某个区域内,就由该区域负责检测该物体。如图,真实物体框的中心点在当前区域内,该区域就负责检测该物体,具体做法是将该区域的两个框与真实物体框相匹配,IoU更大的框负责回归该真实物体框,在此A框更接近真实物体。
最终的预测特征由类别概率、边框的置信度及边框的位置组成。如图,这3者的含义如下:
+ 类别概率。由于PASCAL VOC数据集一共有20个物体类别,因此这里预测的是物体属于哪一类别。
+ 置信度。由于有两个框,因此会存在两个置信度预测值。
+ 边框位置。对每一个边框需要预测其中心坐标及w、h。两个框共计8个预测值。

注意:YOLO v1采用了物体类别与置信度分开的预测方法,这点与Faster RCNN不同,Faster RCNN将背景也当作了一个类别,共计21种,在类别预测种包含了置信度的预测。
# 损失计算
通过CNN得到每个边框的预测值后为了进一步计算网络训练的损失,还需要确定每一个边框对应的是真实物体还是背景框,即区分正、负样本。YOLO v1在确定正负样本时,有以下两个原则:
+
| 57522d5837105a9c6d27a8a3cf32711c9e8dc2f8 | [
"Markdown",
"Python"
] | 24 | Markdown | by777/Pytorch-- | aaf8c64cba2661587b2a23e75a0fe17e21a525ce | 0d2583efe3ff5a6e3c80d9a07c3a13bf9593b487 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ConditionController : MonoBehaviour
{
void Start()
{
// a の値によって異なる処理をする
int a = 10;
Debug.Log("a の中身は " + a.ToString());
if (a == 5)
{
Debug.Log("a は 5 である");
}
else if (a > 5)
{
Debug.Log("a は 5 より大きい");
}
else
{
Debug.Log("a は 5 ではなく、5 より大きくもない");
}
// b が整数か奇数かを判断する
int b = 17;
Debug.Log("b の中身は " + b.ToString());
if (b % 2 == 1)
{
Debug.Log(b.ToString() + " は奇数です。");
}
else
{
Debug.Log(b.ToString() + " は偶数です。");
}
// 課題1: 9 行目で変数 a を初期化しているが、ここで a に代入する値を変更して 20 行目が実行されるようにせよ。
// 課題2: 変数 c (int 型) を宣言し、適当な整数を代入せよ。その c が「2 の倍数か」「3 の倍数か」「6 の倍数か」「それらのどれでもないか」を判定し、結果を出力せよ。
}
void Update()
{
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReturnValueController : MonoBehaviour
{
void Start()
{
// 関数の引数・戻り値の例
int a = Mathf.Max(1, 3); // 与えた引数の内、最大のものを返す関数。Mathf は色々な数学の関数が呼べる「クラス(静的クラス)」です。
Debug.Log(a);
float b = Mathf.Min(1.5f, 0.8f); // 最小のものを返す関数
Debug.Log(b);
}
void Update()
{
float t = Time.time; // Time.time は現在時刻を float で表現したもの。Time は時間に関係した情報が得られる「クラス(静的クラス)」です。
Vector2 p = Vector2.zero; // p は position の p。座標をこれから設定する。
p.x = Mathf.Sin(t); // x 座標を計算する
p.y = Mathf.Cos(t); // y 座標を計算する
this.transform.position = p; // このスクリプトコンポーネントがアタッチされたオブジェクトの座標を設定している。
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddForceController : MonoBehaviour
{
void Start()
{
}
void Update()
{
Rigidbody2D rb = this.gameObject.GetComponent<Rigidbody2D>(); // こうすると、「このオブジェクトがアタッチされている GameObject に同じようにアタッチされているコンポーネント」を取ってくることができる。
rb.AddForce((Vector2.left + Vector2.up) * 2); // これは「関数」を呼んでいる。関数の機能は「指定された方向に力を加える」である。
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpinController : MonoBehaviour
{
void Start()
{
Debug.Log(Vector3.forward.ToString()); // Update() 内で使っている Vector3.forward が何なのか出力する
}
void Update()
{
Transform t = this.gameObject.transform; // このオブジェクトが追加されているオブジェクトのトランスフォームを取得する
t.Rotate(Vector3.forward, 0.1f); // Z軸を中心に 0.1 ずつ回転させる。これは関数を呼んでいる。
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WarpController : MonoBehaviour
{
void Start()
{
Vector2 v2 = Vector2.zero; // v2 = (0, 0) である。zero は Vector2 のプロパティであり、Vector2.zero は (0, 0) を表す。
Debug.Log(v2.ToString()); // v2 が何か出力する
Transform t = this.gameObject.transform; // このオブジェクトが追加されているオブジェクトのトランスフォームを取得する
t.position = v2; // position(= 位置/座標)を書き変える。position は Transform 型の変数 t のプロパティで、オブジェクトの位置(座標)を表す。型は Vector2 または Vector3 である。
}
void Update()
{
}
}
<file_sep>using UnityEngine;
public class ScopeController : MonoBehaviour
{
public int m_counter;
void Start()
{
string[] a = { "apple", "orange", "banana", "kiwi" };
for (int i = 0; i < a.Length; i++)
{
Debug.Log(a[i]);
}
}
void Update()
{
int n = 0;
if (Input.GetKeyDown(KeyCode.Space))
{
m_counter += 1;
n += 1;
Debug.LogFormat("m_counter は {0}, n は {1}", m_counter, n);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseInputController : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonUp(0))
{
Debug.Log("左クリックを離した");
}
if (Input.GetMouseButtonDown(1))
{
Debug.Log("右クリック");
}
if (Input.GetMouseButtonDown(2))
{
Debug.Log("中(ホイール)クリック");
}
// 左ボタンを押している間はマウスの位置を Console に出力する
if (Input.GetMouseButton(0))
{
Debug.Log(Input.mousePosition.ToString());
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KeyboardInputController : MonoBehaviour
{
void Update()
{
// 押されたタイミングで検出する
if (Input.GetKeyDown(KeyCode.Q))
{
Debug.Log("Qが今押された");
}
// 離されたタイミングで検出する
if (Input.GetKeyUp(KeyCode.W))
{
Debug.Log("Wが今離された");
}
// 押しっぱなしを検出する
if (Input.GetKey(KeyCode.E))
{
Debug.Log("Eが押されている");
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LoopController : MonoBehaviour
{
string[] strArray = { "Apple", "Orange", "Banana", "Grape", "Kiwi" };
void Start()
{
Loop1();
Loop2();
Loop3();
Loop4();
}
void Loop1()
{
Debug.Log("Loop1 ==========");
for (int i = 0; i < 10; i++)
{
Debug.Log(i);
}
}
void Loop2()
{
Debug.Log("Loop2 ==========");
int[] intArray = { 5, 3, 7, 8, 9 };
for (int i = 0; i < intArray.Length; i++)
{
int x = intArray[i] * 2;
Debug.Log(x);
}
}
void Loop3()
{
Debug.Log("Loop3 ==========");
for (int i = 0; i < strArray.Length; i++)
{
Debug.Log(strArray[i]);
}
}
void Loop4()
{
Debug.Log("Loop4 ==========");
foreach (string s in strArray)
{
Debug.Log(s);
}
}
}
| 2cf170b71af19583da6f9222907601e2566c8025 | [
"C#"
] | 9 | C# | dsuz/unity-programming-exercise-1st-term-2020 | a4a9aa525dceebd5d0a3a7405006c8ac7575efee | 7bad2a1e12bdd652afb700eb11e208e58bd8cea6 |
refs/heads/master | <file_sep># python_convenience_functions
[](https://zenodo.org/badge/latestdoi/106049281)
Some tools of the trade.
<file_sep>import numpy as np
def lat_lon_to_position_angle(latitude, longitude):
"""Function to translate heliocentric coordinates (latitude, longitude) into position angle
Written by <NAME> and <NAME>.
Inputs:
longitude [float]: The east/west coordinate
latitude [float]: The north/south coordinate
Optional Inputs:
None
Outputs:
position_angle [float]: The converted position angle measured in degrees from solar north, counter clockwise
Optional Outputs:
None
Example:
position_angle = lat_lon_to_position_angle(35, -40)
"""
x = longitude * 1.0
y = latitude * 1.0
if y != 0:
pa = np.arctan(-np.sin(x) / np.tan(y))
else:
pa = 3.1415926 / 2. # limit of arctan(infinity)
pa = pa * 180.0 / 3.1415926
if y < 0:
pa += 180
if x == 90 and y == 0:
pa += 180
if pa < 0:
pa += 360
if x == 0 and y == 0:
pa = -1
return pa
<file_sep># Standard modules
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
# Custom modules
__author__ = '<NAME>'
__contact__ = '<EMAIL>'
def function_name():
"""Convert seconds of day to 'hh:mm:ss'
Inputs:
sod [np.array]: The array of seconds of day to convert.
Optional Inputs:
None
Outputs:
hhmmss [np chararray]: Array of strings of the form 'hh:mm:ss'
Optional Outputs:
None
Example:
hhmmss = sod_to_hhmmss(sod)
"""
return 1
| ba9de88db4b4757cbe259f616e53e021cf1c42c8 | [
"Markdown",
"Python"
] | 3 | Markdown | jmason86/python_convenience_functions | 809bc562d01df5b5655bdc12f65d873d3eb7977b | 01d6456bd669c4eacfbaba843155df43802fb032 |
refs/heads/master | <repo_name>Padmanabha18/Face_detection_project<file_sep>/Face_detection.py
import cv2 as cv
#Reading image
img = cv.imread('/Users/padmanab/Desktop/Pycharm/Face_detection_project/group 1.jpg.jpg')
#cv.imshow('Padmanab', img)
#Covertig to gray image
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
#cv.imshow('Gray', gray)
#Haarcascading
haar_cascade = cv.CascadeClassifier('haar_face.xml')
#Comparing image with Haar cascade
faces_rect = haar_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
#Drawing rectangle over the detected face
for (x, y, w, h) in faces_rect:
cv.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), thickness=2)
cv.imshow('Detected faces', img)
print(f'Number of faces found:= {len(faces_rect)}')
cv.waitKey(0)<file_sep>/README.md
Hi,
The required files and codeing details are mentioned and attached in the project folder,
as this a first project and basic one, it will be updated in coming days.
Thanks.
| 376d8f896e26bc3209ada22e8be69052e866e843 | [
"Markdown",
"Python"
] | 2 | Python | Padmanabha18/Face_detection_project | 4147d6655880b28d63c774ca7f50b04937f949bb | 6bfe7ea5b7dc55b44f9c42662d270251836818ce |
refs/heads/master | <repo_name>zYoma/demo_aiohttp<file_sep>/demo/static/js/ws.js
var sock = new WebSocket('ws://' + window.location.host + WS_URL);
const header = document.querySelector('#header')
const main = document.querySelector('#main')
function showMessage(message) {
/* Append message to chat area */
var data = jQuery.parseJSON(message.data);
let user = data.user
let text = data.text
if (text.includes('подключился')) {
text = `<font color="blue">${text}</font>`
}
if (text.includes('Вышел из чата')) {
text = `<font color="red">${text}</font>`
}
html = `<p><b>${user}</b>: ${text}</p>`
let new_elem = document.createElement('div')
new_elem.innerHTML = html
main.appendChild(new_elem)
}
// ...
$('#send').on('submit', function (event) {
event.preventDefault();
var $message = $(event.target).find('input[name="text"]');
sock.send($message.val());
$message.val('').focus();
});
sock.onopen = function (event) {
console.log('Connection to server started');
};
sock.onclose = function (event) {
console.log(event);
if(event.wasClean){
console.log('Clean connection end');
} else {
console.log('Connection broken');
}
// window.location.assign('/');
};
sock.onerror = function (error) {
console.log(error);
};
sock.onmessage = showMessage;<file_sep>/demo/views/frontend.py
import aiohttp
import peewee
from aiohttp_jinja2 import template
from ..db import Post, Role, User
from .. utils import login_required, gen_hash, redirect
class Index(aiohttp.web.View):
#@login_required
@template('index.html')
async def get(self):
ip = self.request.remote
return {'ip': ip}
@template('add.html')
async def add_post(request):
if request.method == 'POST':
app = request.app
data = await request.post()
title = data['title']
body = data['text']
await app.objects.create(Post, title=title, body=body)
raise aiohttp.web.HTTPFound('post')
return {}
async def del_post(request):
if request.method == 'POST':
app = request.app
post_id = request.match_info['id']
post = await app.objects.get(Post, id=post_id)
await app.objects.delete(post)
raise aiohttp.web.HTTPFound('/post')
class PostPage(aiohttp.web.View):
@template('post.html')
async def get(self):
app = self.request.app
# result = await Post.all_posts(self.request.app.objects)
result = await app.objects.execute(Post.select())
return {'result': result}
class LogIn(aiohttp.web.View):
@template('login.html')
async def get(self):
return {}
async def post(self):
""" Проверяем email """
user = await self.is_valid()
if not user:
redirect(self.request, 'login')
await self.login_user(user)
async def login_user(self, user):
""" Заносим id пользователя в сессию """
self.request.session['user'] = str(user.id)
redirect(self.request, 'post')
async def is_valid(self):
""" Проверяем пользователя и пароль """
app = self.request.app
data = await self.request.post()
email = data.get('email', '')
password = data.get('password', '')
pass_hash = gen_hash(password)
try:
user = await app.objects.get(User, email=email, password=pass_hash)
except peewee.DoesNotExist:
return False
return user
class Registration(aiohttp.web.View):
@template('reg.html')
async def get(self):
return {}
async def post(self):
""" Делаем валидацию """
user = await self.is_valid()
if not user:
redirect(self.request, 'registration')
await self.create_user(user)
async def create_user(self, data):
""" Создаем пользователя. """
app = self.request.app
email = data.get('email', '')
password = data.get('<PASSWORD>', '')
pass_hash = gen_hash(password)
role = await app.objects.get(Role, name='user')
new_user = await app.objects.create(User, email=email, password=pass_hash, role=role)
redirect(self.request, 'login')
async def is_valid(self):
""" Валидируем данные """
app = self.request.app
data = await self.request.post()
email = data.get('email', '')
password1 = data.get('password1', '')
password2 = data.get('password2', '')
if password1 != password2:
return False
try:
user = await app.objects.get(User, email=email)
except peewee.DoesNotExist:
return data
else:
return False
class CreateRoles(aiohttp.web.View):
async def get(self):
app = self.request.app
roles = [('admin', 'Админ'), ('user', 'Пользователь')]
for role in roles:
await app.objects.create_or_get(Role, name=role[0], description=role[1])
redirect(self.request, 'post')
<file_sep>/demo/test_ws.py
import websockets # pip install websockets
import asyncio
import time
async def test_url(url, data=""):
await asyncio.sleep(1)
async with websockets.connect(url) as websocket:
await websocket.send(data)
await asyncio.sleep(1)
async def main():
await asyncio.gather(*[test_url(f"ws://10.130.0.33:1234/ws/Tester-{n}", "это тест") for n,i in enumerate(range(100))])
if __name__ == "__main__":
asyncio.run(main())<file_sep>/demo/routes.py
from .views import frontend, websocket
from settings import STATIC_DIR
def setup_routes(app):
app.router.add_route('GET', '/', frontend.Index, name='index')
app.router.add_route('GET', '/post', frontend.PostPage, name='post')
app.router.add_route('GET', '/add-roles',
frontend.CreateRoles, name='create_roles')
app.router.add_route(method='*', path='/login',
handler=frontend.LogIn, name='login')
app.router.add_route(method='*', path='/reg',
handler=frontend.Registration, name='registration')
app.router.add_route('GET', '/add', frontend.add_post, name='add_post')
app.router.add_route('POST', '/add', frontend.add_post, name='add_post')
app.router.add_route(
'POST', r'/del/{id}', frontend.del_post, name='del_post')
app.router.add_route(
method='GET', path='/ws/{user}', handler=websocket.WebSocket, name='ws')
app.router.add_static('/static', STATIC_DIR, name='static')
<file_sep>/entry.py
import argparse
import asyncio
import uvloop # pip install uvloop
import aiohttp
from demo import create_app
from demo.settings import load_conf
# asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
parser = argparse.ArgumentParser(description="Demo project")
parser.add_argument('--host', help='Хост', default='10.130.0.33')
parser.add_argument('--port', help='Порт', default=1234)
parser.add_argument('--reload', action='store_true', help='Автоперезапуск')
parser.add_argument(
'-c', '--config', type=argparse.FileType('r'), help='Путь к файлу конфига')
args = parser.parse_args()
app = create_app(config=load_conf(args.config))
if args.reload:
print('Поддержка перезапуска активна')
import aioreloader # pip install aioreloader
aioreloader.start()
if __name__ == '__main__':
aiohttp.web.run_app(app, host=args.host, port=args.port)
<file_sep>/demo/settings.py
import os
from pathlib import Path
import yaml # pip install pyyaml
__all__ = ('load_conf')
BASE_DIR = Path(__file__).resolve().parent
STATIC_DIR = os.path.join(BASE_DIR, 'static')
DEBUG = True
REDIS_CON = 'localhost', 6379
DATABASE = {
'database': 'demo_aiohttp',
'password': '<PASSWORD>',
'user': 'aiohttp_user',
'host': 'localhost',
}
def load_conf(config_file=None):
default_file = Path(__file__).parent / 'config.yaml'
print(default_file)
with open(default_file, 'r') as f:
config = yaml.safe_load(f)
cf_dict = {}
if config_file:
cf_dict = yaml.safe_load(config_file)
config.update(**cf_dict)
return config
<file_sep>/demo/views/websocket.py
import json
from aiohttp import web, WSMsgType
class WebSocket(web.View):
async def get(self):
self.user = self.request.match_info['user']
app = self.request.app
ws = web.WebSocketResponse()
await ws.prepare(self.request)
app.wslist[self.user] = ws
await self.broadcast({'text': 'подключился', 'user': self.user})
async for msg in ws:
if msg.type == WSMsgType.text:
if msg.data == 'close':
await ws.close()
else:
text = msg.data.strip()
await self.broadcast({'text': f'{text}', 'user': self.user})
elif msg.type == WSMsgType.error:
print(f'Ошибка {ws.exception()}')
await self.disconnect(self.user, ws)
return ws
# async def command(self, cmd):
# """ Run chat command """
# app = self.request.app
# if cmd.startswith('/kill'):
# pass
# else:
# return {'text': f'{cmd}', 'user':self.user}
async def broadcast(self, message):
""" Отправка сообщений всем. """
for peer in self.request.app.wslist.values():
await peer.send_json(message)
async def disconnect(self, user, socket, silent=False):
""" Закрываем соединение и отправлем сообщение о выходе. """
app = self.request.app
app.wslist.pop(user, None)
if not socket.closed:
await socket.close()
if silent:
return
await self.broadcast({'text': 'Вышел из чата', 'user': self.user})
<file_sep>/demo/utils.py
import hashlib
from aiohttp import web
def redirect(request, router_name, *, permanent=False, **kwargs):
""" Redirect to given URL name """
url = request.app.router[router_name].url_for(**kwargs)
if permanent:
raise web.HTTPMovedPermanently(url)
raise web.HTTPFound(url)
def login_required(func):
""" Allow only auth users """
async def wrapped(self, *args, **kwargs):
if self.request.user is None:
redirect(self.request, 'login')
return await func(self, *args, **kwargs)
return wrapped
def gen_hash(password: str):
salt = '<PASSWORD>'
str2hash = password + salt
result = hashlib.md5(str2hash.encode())
return result.hexdigest()
<file_sep>/demo/app.py
import aioredis # pip install aioredis
import jinja2
import aiohttp_jinja2 # pip install aiohttp-jinja2
import aiohttp_debugtoolbar # pip install aiohttp_debugtoolbar
# import asyncpgsa # pip install asyncpg asyncpgsa
import peewee_async # pip install peewee-async aiopg
from aiohttp import web
from aiohttp_session import session_middleware # pip install aiohttp-session
from aiohttp_session.redis_storage import RedisStorage
from .routes import setup_routes
from middlewares import request_user_middleware
import settings
from db import database
async def create_app(config: dict):
""" Подключаем сесии, для хранения используем redis. """
redis_pool = await aioredis.create_pool(settings.REDIS_CON)
middlewares = [session_middleware(
RedisStorage(redis_pool)), request_user_middleware]
""" Подключаем debugtoolbar. """
if settings.DEBUG:
middlewares.append(aiohttp_debugtoolbar.middleware)
app = web.Application(middlewares=middlewares)
app.redis_pool = redis_pool
app.wslist = {} # для вебсокета
app['config'] = config
aiohttp_jinja2.setup(
app,
loader=jinja2.PackageLoader('demo', 'templates')
)
if settings.DEBUG:
aiohttp_debugtoolbar.setup(app, intercept_redirects=False)
setup_routes(app)
app.on_startup.append(on_start)
app.on_cleanup.append(on_shutdown)
return app
async def on_start(app):
config = app['config']
# app['db'] = await asyncpgsa.create_pool(dsn=config['database_uri'])
# db conn
database.init(**settings.DATABASE)
app.database = database
app.database.set_allow_sync(False)
app.objects = peewee_async.Manager(app.database)
async def on_shutdown(app):
await app.objects.close() # Закрываем соедиение с БД
app.redis_pool.close()
await app.redis_pool.wait_closed()
await app.shutdown()
<file_sep>/demo/db.py
# pip install peewee-async aiopg
import peewee
import peewee_async
from datetime import datetime
import peeweedbevolve # pip install peewee-db-evolve
import settings
database = peewee_async.PostgresqlDatabase(None)
class BaseModel(peewee.Model):
class Meta:
database = database
class Post(BaseModel):
title = peewee.CharField(max_length=50, verbose_name='Заголовок')
body = peewee.TextField(verbose_name='Текст поста')
created_at = peewee.DateTimeField(default=datetime.now)
@classmethod
async def all_posts(cls, objects):
return await objects.execute(cls.select())
def __str__(self):
return self.title
class Meta:
order_by = ('created_at', )
class Role(BaseModel):
name = peewee.CharField(max_length=50, unique=True, verbose_name='Имя')
description = peewee.CharField(max_length=100, verbose_name='Описание')
def __str__(self):
return self.name
class User(BaseModel):
email = peewee.CharField(max_length=50, verbose_name='Почта')
password = peewee.CharField(max_length=100, verbose_name='Пароль')
active = peewee.BooleanField(default=True, verbose_name='Статус')
#roles = peewee.ManyToManyField(Role, backref='users')
role = peewee.ForeignKeyField(Role, null=True, related_name='users')
def __str__(self):
return self.email
if __name__ == '__main__':
database.init(**settings.DATABASE)
database.evolve()
<file_sep>/README.md
# demo_aiohttp
### Изучаю асинхронное программирование.
### Стек
- aiohttp
- PostgreSQL
- peewee_async
- aiohttp_jinja2
- websockets
<file_sep>/http_request.py
import asyncio
import aiohttp
from bs4 import BeautifulSoup
def soup(html):
soup = BeautifulSoup(html, 'lxml')
title = soup.find('title').text.strip()
return title
async def task(name, work_queue):
async with aiohttp.ClientSession() as session:
while not work_queue.empty():
url = await work_queue.get()
print(f"{name} URL: {url}")
async with session.get(url) as response:
html = await response.read()
print(f"{name} выполнена")
print(soup(html))
async def main():
"""
This is the main entry point for the program.
"""
# Create the queue of 'work'
work_queue = asyncio.Queue()
# Put some 'work' in the queue
for url in [
"http://google.com",
"http://yahoo.com",
"http://linkedin.com",
"http://apple.com",
"http://microsoft.com",
"http://facebook.com",
]:
await work_queue.put(url)
# Run the tasks
await asyncio.gather(
asyncio.create_task(task('Задача-1', work_queue)),
asyncio.create_task(task('Задача-2', work_queue)),
)
if __name__ == "__main__":
asyncio.run(main())
| fc0529fcae7dba07415106a16b2fabadc42a274b | [
"JavaScript",
"Python",
"Markdown"
] | 12 | JavaScript | zYoma/demo_aiohttp | 3661026de2a7e4efa583cb87cb3343dda557765d | c7bc8192c6b0823989fe89a344f70f43db9b7964 |
refs/heads/master | <file_sep>import store from '@/store/index'
import axios from 'axios'
import jquery from "jquery"
import { Message, MessageBox } from 'element-ui'
// 创建一个axios实例
const service = axios.create({
baseURL: process.env.BASE_API, // api的base_url,在config下的dev.evn.js和prod.env.js中配置
timeout: 60000
})
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 请求拦截器
service.interceptors.request.use(function(config) {
// console.log("----request----")
// if(!!!store.state.epmToken){
//
// //store.commit("setEpmToken",'<PASSWORD>');
// jquery.ajax({
// headers: {
// 'X-Requested-With':'XMLHttpRequest'
// },
// type: 'post',
// url: process.env.TOKEN_API_URL,
// xhrFields: {
// withCredentials: true
// },
// async:false,
// beforeSend:null,
// success:(data)=>{
// let token = data;
// //此处需要判断是否正确生成
// if(!!token && token.result){
// store.commit("setEpmToken",token.data);
// }else{
// console.log("请求token时,返回不正确>>>>>>>>>>>>>>>>>>>>");
// window.location.href = process.env.PORTAL_URL;
// }
// },
// error:(result, status)=>{
// console.log("请求token时发生错误>>>>>>>>>>>>>>>>>>>>",result);//发生错误时执行的代码
// window.location.href = process.env.PORTAL_URL;
// }
// });
// }
// config.headers['e-user-token'] = store.state.dataset.epmToken;
return config;
}, function(error) {
return Promise.reject(error);
});
// 响应拦截器
service.interceptors.response.use((res) => {
if (res.status === 654) {
Message({
message: "请求超时",
type: 'error',
duration: 5 * 1000
})
}
if (res.status !== 200) {
Message({
message: "数据返回有误",
type: 'error',
duration: 5 * 1000
})
return Promise.reject(res);
}
return res;
}, (error) => {
console.log('promise error:' + error);
return Promise.reject(error);
});
export default service
<file_sep>module.exports = {
NODE_ENV: '"production"',
ENV_CONFIG: '"prod"',
BASE_API: '"http://localhost:8888/epm-databroker-system"',
TOKEN_API_URL:'"http://localhost:8888/epm-databroker-system/api/single/token/"',//token服务端api地址
PORTAL_URL:'"http://localhost:8888/api/epm-databroker-system/api/single/access/?url=http://localhost:9999/#/"',
}
<file_sep>const menuObj = {
menus: [
{
menuName: 'prismx',
path: '/prismx/prismx'
},
{
menuName: '测试目录',
sub: [
{
menuName: '普通测试',
path: '/test/test'
},
{
menuName: '测试数据集列表',
path: '/test/testDataset'
},
{
menuName: '测试form',
path: '/test/testForm'
},
{
menuName: '测试tree',
path: '/test/testTree'
},
{
menuName: '测试select',
path: '/test/testSelect'
},
{
menuName: '测试分档',
path: '/test/bracket'
},
{
menuName: '测试table',
path: '/test/table'
},
{
menuName: '测试luckywheel',
path: '/test/luckywheel'
},
{
menuName: '测试ninesquare',
path: '/test/ninesquare'
}
]
}
]
}
export default menuObj
<file_sep>import jquery from "jquery"
import store from '@/store/index'
const Util = {
uuid(){
var len=32;//32长度
var radix=16;//16进制
var chars='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var uuid=[],i;
radix=radix||chars.length;
for(i=0;i<len;i++){
uuid[i]=chars[0|Math.random()*radix];
}
return 'UUID'+uuid.join('');
},
getIdWithTypeAndUuid(type){
let newType = type.toUpperCase()+"";
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
if (month < 10) {
month = "0" + month;
}
if (day < 10) {
day = "0" + day;
}
var uuid8 = Util.uuid().substring(4, 12);
var nowDate = year +""+ month +""+ day+"";
return newType+nowDate+uuid8;
},
getNameWithDateAndUuid(prefix){
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
if (month < 10) {
month = "0" + month;
}
if (day < 10) {
day = "0" + day;
}
var uuid8 = Util.uuid().substring(4, 12);
var nowDate = year +""+ month +""+ day;
return prefix+"_"+nowDate+"_"+uuid8;
},
formatDate (date, fmt){
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
};
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + '';
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : this.padLeftZero(str));
}
}
return fmt;
},
padLeftZero (str) {
return ('00' + str).substr(str.length);
},
compareDate(start, end) {
var startDate;
var endDate;
if(start.indexOf(":")!=-1){
var startDatePart = start.split(" ")[0].split("-");
var startTimePart = start.split(" ")[1].split(":");
startDate = new Date(parseInt(startDatePart[0]),parseInt(startDatePart[1])-1,parseInt(startDatePart[2]),parseInt(startTimePart[0]),parseInt(startTimePart[1]),parseInt(startTimePart[2]));
var endDatePart = end.split(" ")[0].split("-");
var endTimePart = end.split(" ")[1].split(":");
endDate = new Date(parseInt(endDatePart[0]),parseInt(endDatePart[1])-1,parseInt(endDatePart[2]),parseInt(endTimePart[0]),parseInt(endTimePart[1]),parseInt(endTimePart[2]));
}else{
var startDatePart = start.split(" ")[0].split("-");
startDate = new Date(parseInt(startDatePart[0]),parseInt(startDatePart[1])-1,parseInt(startDatePart[2]));
var endDatePart = end.split(" ")[0].split("-");
endDate = new Date(parseInt(endDatePart[0]),parseInt(endDatePart[1])-1,parseInt(endDatePart[2]));
}
if (startDate > endDate) {
return true;
} else {
return false;
}
},
getEpmToken(){
jquery.ajaxSetup({
beforeSend: function(request) {
// if(!!!store.state.epmToken){
// jquery.ajax({
// headers: {
// 'X-Requested-With':'XMLHttpRequest'
// },
// beforeSend:null,
// type: 'get',
// url: process.env.TOKEN_API_URL,
// async:false,
// success:(data)=>{
// let token = data;
// if(!!token && token.result){
// store.commit("setEpmToken",token.data);
// }else{
// console.log("请求token时,返回不正确>>>>>>>>>>>>>>>>>>>>");
// window.location.href = process.env.PORTAL_URL;
// }
// },
// error:(result, status)=>{
// console.log("请求token时发生错误>>>>>>>>>>>>>>>>>>>>");//发生错误时执行的代码
// console.log(result);//发生错误时执行的代码
// console.log(">>获取token时报错,status="+status);
// window.location.href = process.env.PORTAL_URL;
// }
// });
// }
// request.setRequestHeader("e-user-token", store.state.dataset.epmToken);
},
});
}
}
export default Util
<file_sep>import jquery from "jquery"
import store from '@/store/index'
jquery.ajaxSetup({
beforeSend: function(request) {
// console.log("----ajax----")
// if(!!!store.state.epmToken){
// jquery.ajax({
// headers: {
// 'X-Requested-With':'XMLHttpRequest'
// },
// beforeSend:null,
// type: 'post',
// xhrFields: {
// withCredentials: true
// },
// url: process.env.TOKEN_API_URL,
// async:false,
// success:(data)=>{
// let token = data;
// if(!!token && token.result){
// store.commit("setEpmToken",token.data);
// }else{
// console.log("请求token时,返回不正确>>>>>>>>>>>>>>>>>>>>");
// window.location.href = process.env.PORTAL_URL;
// }
// },
// error:(result, status)=>{
// console.log("请求token时发生错误>>>>>>>>>>>>>>>>>>>>",result);//发生错误时执行的代码
// window.location.href = process.env.PORTAL_URL;
// }
// });
// }
// request.setRequestHeader("e-user-token", store.state.dataset.epmToken);
},
});
export default jquery
<file_sep>import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
import dataset from './modules/dataset'
import prismx from './modules/prismx'
Vue.use(Vuex)
const store = new Vuex.Store({
// 初始化的数据
state: {
newConnect: null
},
// 改变state里面的值得方法
mutations: {
newConnect(state, data) {
state.newConnect = data
}
},
modules: {
app,
dataset,
prismx
},
})
export default store
<file_sep>import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
base: '/prismx/',
routes: [
{ path: '/prismx/prismx', component: () => import('@/views/prismx/prismx'), name: 'prismx' },
{ path: '/dataset/components/list', component: () => import('@/views/dataset/components/list'), name: 'datasetList' },
{ path: '/dataset/components/create', component: () => import('@/views/dataset/components/create'), name: 'datasetCreate' },
{ path: '/test/testDataset', component: () => import('@/views/test/testDataset'), name: 'testDataset' },
{ path: '/test/testForm', component: () => import('@/views/test/testForm'), name: 'testForm' },
{ path: '/test/testTree', component: () => import('@/views/test/testTree'), name: 'testTree' },
{ path: '/test/testSelect', component: () => import('@/views/test/testSelect'), name: 'testSelect' },
{ path: '/test/table', component: () => import('@/views/test/table'), name: 'table' },
{ path: '/test/bracket', component: () => import('@/views/test/bracket'), name: 'bracket' },
{ path: '/test/luckywheel', component: () => import('@/views/test/luckywheel'), name: 'luckywheel' },
{ path: '/test/ninesquare', component: () => import('@/views/test/ninesquare'), name: 'ninesquare' },
{ path: '/test/test', component: () => import('@/views/test/test'), name: 'test' }
]
})
<file_sep>import request from '@/utils/request'
import jquery from '@/utils/JqueryAjax'
const DatasetService = {
/**
* 获取所有数据
* @param model
*/
getDataListByAjax: function(model) {
return jquery.ajax({
type: 'post',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
url: process.env.BASE_API + '/api/query/data/' + model.version
})
},
/**
* 获取数据集目录列表
* @param model
*/
getDataList: function(model) {
return request({
url: '/api/dataset/getDataList',
method: 'post',
params: model
})
}
}
export default DatasetService
<file_sep>module.exports = {
NODE_ENV: '"development"',
ENV_CONFIG: '"dev"',
BASE_API: '""',//ajax请求url的前缀,配置为java后台项目访问根路径http://ip:port/项目名
TOKEN_API_URL:'"/api/single/token/"',//token服务端api地址
PORTAL_URL:'"http://localhost:8888/api/epm-databroker-system/api/single/access/?url=http://localhost:9999/#/"',
}
| 4700165be6dfa64f312ea59bdc867f3a7e28aa4b | [
"JavaScript"
] | 9 | JavaScript | songzhikai/prismx | a461ac4041643a8d9b7b138e345054285823f170 | e5cf821b53346b2d0c9f064dc0854257af64c0ef |
refs/heads/master | <file_sep>
void setup(){
Serial.begin(9600);
}
void loop(){
if (Serial.available()) {
byte nr = Serial.read();
Serial.print("Folgender char wurde empfangen: ");
Serial.println(nr, DEC);
}
}
<file_sep>from tkinter import *
import tkinter as tk
import serial
import cv2
import time
value1 = 0
def sendValues(selected):
if selected == 0:
print("Data written: 0")
# serPC.write('0')
elif selected == 1:
# serPC.write('1')
print("Data written: 1")
class GUI:
def __init__(self,root,*args, **kwargs):
self.setPnt = tk.Label(root, text="Set point ")
self.setPnt.pack(side=LEFT)
self.spinBoxZ = tk.Spinbox(root, from_ =-24, to=24,textvariable = var ,command = self.printValues)
self.spinBoxZ.pack(side=LEFT)
self.setBtn = tk.Button(root, text = "Set", command = self.printValues)
self.setBtn.pack(side=LEFT)
self.setConn = tk.Button(root, text = "Connect", command = self.ArduinoConnection)
self.setConn.pack(side=LEFT)
self.setBtnUp = tk.Button(root, text = "Up", command = self.btnUp)
self.setBtnUp.pack()
self.setBtnDown = tk.Button(root, text = "Down", command = self.btnDown)
self.setBtnDown.pack()
# self.setBtn1 = tk.Button(root, text = "Close", command = root.quit)
# self.setBtn1.pack()
def btnUp(self):
print("Data written: 1")
serPC.write('1'.encode())
def btnDown(self):
print("Data written: 0")
serPC.write('0'.encode())
def printValues(self):
# global value1
# changeValue(self)
# while 1:
# inputData = input()
# print("You entered: ", inputData)
# print("Written: {}".format(self.spinBoxZ.get()))
print(self.spinBoxZ.get())
# value1 = int(self.spinBoxZ.get())
# try:
# serPC.read(size=100)
# serialcmd = input(self.spinBoxZ.get())
if int(self.spinBoxZ.get()) >= int(value1):
print("Data written: 1")
# serPC.write('0')
# print("Data written: 0")
elif int(self.spinBoxZ.get())-int(value1) < int(value1):
# serPC.write('1')
print("Data written: 0")
# value1 = int(self.spinBoxZ.get())
def ArduinoConnection(self):
global serPC
print("Establishing serial connection between Computer and Arduino ...")
try:
serPC = serial.Serial('/dev/ttyACM0',115200,timeout =0,parity = serial.PARITY_EVEN,rtscts=1)
print("Connection established!")
return serPC
except:
print("Connection to Arduino failed")
def changeValue(self):
global selected
selected = format(self.spinBoxZ.get())
sendValues(selected)
print("selected is assigned ...")
# return selected
#def printSelected(selected):
#if selected == 0:
# print("selected 0")
#
#elif selected == 1:
# print("selected 1")
root = tk.Tk()
var = tk.StringVar(root)
var.set("0")
var1 = tk.StringVar()
var2 = tk.StringVar()
root.title("Z Position")
root.geometry('500x100')
var1.set(0)
var2.set(0)
guiOpen = GUI(root)
root.mainloop()<file_sep>void setup() {
Serial.begin(9600);
}
unsigned int integerValue=0; // Max value is 65535
char incomingByte;
void loop() {
if (Serial.available() > 0) { // something came across serial
integerValue = 0; // throw away previous integerValue
while(1) { // force into a loop until 'n' is received
incomingByte = Serial.read();
if (incomingByte == '\n') break; // exit the while(1), we're done receiving
if (incomingByte == -1) continue; // if no characters are in the buffer read() returns -1
integerValue *= 10; // shift left 1 decimal place
// convert ASCII to integer, add, and shift left 1 decimal place
integerValue = ((incomingByte - 48) + integerValue);
}
Serial.println(integerValue); // Do something with the value
}
}
| 6cd76ac7d469f10afae95a44ff430c60b0db5c4d | [
"Python",
"C++"
] | 3 | C++ | christianburkard/ArduinoControl | 3f33c54c22fd296d883b938a12886462bd951cf6 | b9ab450cba8974267a84c63d4c3b95cbea79f19b |
refs/heads/master | <file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
counter = 100 # 赋值整型变量
miles = 1000.0 # 浮点型
name = "John" # 字符串
print(counter);
print(miles);
print(name);
list = ['runoob', 786, 2.23, 'john', 70.2]
tinylist = [123, 'john']
print (list); # 输出完整列表
print (list[0]); # 输出列表的第一个元素
print(list[1:3]); # 输出第二个至第三个的元素
print (list[2:]) # 输出从第三个开始至列表末尾的所有元素
print (tinylist * 2); # 输出列表两次
print (list + tinylist); # 打印组合的列表
print(int(123.5));<file_sep># PythonWorkSpace
PythonWorkSpace
| e095f9f5980795a738296c929e11892038723299 | [
"Markdown",
"Python"
] | 2 | Python | huihui4045/PythonWorkSpace | 298da60b479d8321defb740f84270823dcb0d285 | 9b45ba54055ece90f9f6fa259dc222f5e38ef141 |
refs/heads/master | <file_sep>/**
* ActionPlacement, utilisé dans le patron stratégie
*
*/
package bataillenavale;
import bataillenavale.AbstractPartieLive.ExceptionCoupImpossible;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author jaylesr
*/
public class ActionPlacement extends AbstractAction{
private int positionX;
private int positionY;
/**
* Constructeur
* @param positionX
* @param positionY
* @param bateau
*/
public ActionPlacement(int positionX, int positionY, AbstractBateau bateau){
super(bateau);
this.positionX = positionX;
this.positionY = positionY;
}
/**
* Enregistrement de l'action spécifique au placement
* @param partie
* @param joueur
* @param numTour
* @param numAction
* @throws bataillenavale.AbstractPartieLive.ExceptionCoupImpossible
*/
@Override
public void enregistrerAction(AbstractPartieLive partie, Joueur joueur, int numTour, int numAction) throws ExceptionCoupImpossible{
try {
super.enregistrerAction(partie, joueur, numTour, numAction);
} catch (ExceptionBateauTouche ex) {
Logger.getLogger(ActionPlacement.class.getName()).log(Level.SEVERE, null, ex);
}
int idAction = 0;
try {
//on récupère l'idAction en cours
PreparedStatement stt = BDManager.getInstance().prepareStatement("SELECT sequence_action.currval FROM Action");
ResultSet resultat = stt.executeQuery();
resultat.next();
idAction = resultat.getInt(1);
stt.close();
resultat.close();
//on insère le tuple dans la base de donnée
stt = BDManager.getInstance().prepareStatement("INSERT INTO Etat VALUES(sequence_etat.nextval,?,?,?,?,?,?,?,?)");
stt.setInt(1, this.getPositionX());
stt.setInt(2, this.getPositionY());
stt.setString(3, this.getBateau().getDirection().toString());
stt.setInt(4, this.getBateau().getVie());
stt.setInt(5, idAction);
stt.setInt(6, numAction);
stt.setInt(7, this.getBateau().getIdBateau());
stt.setInt(8, this.getBateau().taille);
stt.executeQuery();
stt.close();
} catch (SQLException ex) {
Logger.getLogger(ActionPlacement.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Accesseur positionX
* @return
*/
public int getPositionX() {
return this.positionX;
}
/**
* Accesseur positionY
* @return
*/
public int getPositionY() {
return this.positionY;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controleur;
import InterfaceGraphique.Interface;
import InterfaceGraphique.PageAccueil;
import bataillenavale.ConcreteFabriqueJoueur;
import bataillenavale.FabriqueJoueur;
import bataillenavale.Joueur;
/**
*
* @author gounonj
*/
public class CtrlAccueil {
public CtrlAccueil(){
}
public void inscription() {
Interface.getInstance().setPageInscription();
}
public void connexion(PageAccueil page) {
Joueur joueur = null;
try {
joueur = ConcreteFabriqueJoueur.getInstance().getJoueur(page.getPseudo().getText());
Controleur.getInstance().setJoueur(joueur);
} catch (FabriqueJoueur.pseudoInexistantException ex) {
System.out.println("Pseudo Introuvable");
Interface.getInstance().afficherMessageErreur("Pseudo Introuvable");
return;
}
//TODO Passer les pages en singleton
Interface.getInstance().setPageJoueur();
}
}
<file_sep>
package bataillenavale;
/**
*
* @author thomas
*/
public class BateauDestroyer extends AbstractBateau {
/**
* Constructeur
* @param idBateau
* @param coordX
* @param coordY
*/
public BateauDestroyer(int idBateau, int coordX, int coordY){
super(idBateau, 3);
this.coordX = coordX;
this.coordY = coordY;
}
/**
* Constructeur
* @param idBateau
* @param coordX
* @param coordY
* @param direction
*/
public BateauDestroyer(int idBateau, int coordX, int coordY, Direction direction){
super(idBateau, 3, direction, 3);
this.coordX = coordX;
this.coordY = coordY;
}
public BateauDestroyer(BateauDestroyer copy)
{
super(copy.idBateau, 3, copy.direction, 3);
this.coordX = copy.coordX;
this.coordY = copy.coordY;
}
/**
* Constructeur
* @param idBateau
*/
public BateauDestroyer(int idBateau) {
super(idBateau, 3);
}
@Override
public AbstractBateau copy() {
return new BateauDestroyer(this);
}
}<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controleur;
import InterfaceGraphique.Interface;
import InterfaceGraphique.PageInscription;
import bataillenavale.ConcreteFabriqueJoueur;
import bataillenavale.FabriqueJoueur;
import bataillenavale.Joueur;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author gounonj
*/
public class CtrlInscription {
public void annuler() {
Interface.getInstance().setPageAccueil();
}
public void inscription(PageInscription page) {
Joueur joueur = null;
try {
joueur = ConcreteFabriqueJoueur.getInstance().getJoueur(page.getPseudo().getText(),
page.getPrenom().getText(),page.getNom().getText(),page.getEmail().getText(),
null,0,page.getVille().getText());
} catch (FabriqueJoueur.pseudoExistantException ex) {
Logger.getLogger(PageInscription.class.getName()).log(Level.SEVERE, null, ex);
Interface.getInstance().afficherMessageErreur("Pseudo déjà existant.");
return;
}
Controleur.getInstance().setJoueur(joueur);
Interface.getInstance().setPageJoueur();
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package InterfaceGraphique;
import Controleur.Controleur;
import bataillenavale.ConcreteFabriquePartie;
import bataillenavale.FabriquePartie;
import bataillenavale.PartieEnReplay;
import bataillenavale.PartieLive;
import java.util.LinkedList;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* JPanel page joueur
* @author ngankafr
*/
public class PageJoueur extends javax.swing.JPanel {
/**
* Creates new form PageJoeur
*/
public PageJoueur() {
//La metode auto genere par l'outil netbeans
initComponents();
//On initialise les tableaux des paties replay
initTableauReplay();
//on initialise les tableaux des parties en cours
initTableauPartieEnCours();
}
/**
* Créer le tableau qui liste les parties en cours
*/
private void initTableauPartieEnCours() {
Set<PartieLive> listeLive;
// On recupere la liste des parties que le joueur peut continuer a jouer
listeLive = ConcreteFabriquePartie.getInstance().getPartieEnCours(Controleur.getInstance().getJoueur());
Object[][] data = new Object[listeLive.size()][3];
int i = 0;
//On defini le modele que l'on veut représenter dans le tableau
for (PartieLive element : listeLive) {
data[i][0] = element.getIdPartie();
data[i][1] = element.getAdversaire(Controleur.getInstance().getJoueur()).getPseudo();
if(element.monTour(Controleur.getInstance().getJoueur())){
data[i][2]="Oui";
}
else{
data[i][2] ="Non";
}
i++;
}
tablePartieEnCours.setModel(new javax.swing.table.DefaultTableModel(data, new String[]{"Id Partie", "Adversaire", "A vous de jouer ?"}));
}
/**
* Créer le tableau qui liste les parties en cours
*/
private void initTableauReplay() {
try {
LinkedList<PartieEnReplay> listePartie;
//On recupere la liste des parties que le joueur peut observer en replay
listePartie = ConcreteFabriquePartie.getInstance().getListePartieAObserver(Controleur.getInstance().getJoueur());
Object[][] data = new Object[listePartie.size()][3];
int i = 0;
//On defini le modele que l'on veut représenter dans le tableau
for (PartieEnReplay element : listePartie) {
data[i][0] = element.getIdPartie();
data[i][1] = element.getJoueur1();
data[i][2] = element.getJoueur2();
i++;
}
tablePartieReplay.setModel(new javax.swing.table.DefaultTableModel(data, new String[]{"Id Partie", "Nom joueur 1", "Nom joueur 2"}));
} catch (FabriquePartie.ExceptionPartieInexistante ex) {
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
nouvellePartie = new javax.swing.JButton();
quitter = new javax.swing.JButton();
scrollPaneReplay = new javax.swing.JScrollPane();
tablePartieReplay = new javax.swing.JTable();
scrollPanePartieEnCours = new javax.swing.JScrollPane();
tablePartieEnCours = new javax.swing.JTable();
labelPartiesReplay = new javax.swing.JLabel();
labelPartieEnCours = new javax.swing.JLabel();
setPreferredSize(new java.awt.Dimension(800, 600));
setLayout(null);
nouvellePartie.setText("Commencer une Nouvelle Partie");
nouvellePartie.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nouvellePartieActionPerformed(evt);
}
});
add(nouvellePartie);
nouvellePartie.setBounds(40, 10, 260, 29);
quitter.setText("Quitter");
quitter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
quitterActionPerformed(evt);
}
});
add(quitter);
quitter.setBounds(610, 10, 80, 29);
tablePartieReplay.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tablePartieReplay.setColumnSelectionAllowed(true);
tablePartieReplay.getTableHeader().setReorderingAllowed(false);
tablePartieReplay.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tablePartieReplayMouseClicked(evt);
}
});
scrollPaneReplay.setViewportView(tablePartieReplay);
tablePartieReplay.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
if (tablePartieReplay.getColumnModel().getColumnCount() > 0) {
tablePartieReplay.getColumnModel().getColumn(0).setResizable(false);
tablePartieReplay.getColumnModel().getColumn(1).setResizable(false);
tablePartieReplay.getColumnModel().getColumn(2).setResizable(false);
tablePartieReplay.getColumnModel().getColumn(3).setResizable(false);
}
add(scrollPaneReplay);
scrollPaneReplay.setBounds(410, 100, 360, 390);
tablePartieEnCours.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tablePartieEnCours.setColumnSelectionAllowed(true);
tablePartieEnCours.getTableHeader().setReorderingAllowed(false);
tablePartieEnCours.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tablePartieEnCoursMouseClicked(evt);
}
});
scrollPanePartieEnCours.setViewportView(tablePartieEnCours);
tablePartieEnCours.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
if (tablePartieEnCours.getColumnModel().getColumnCount() > 0) {
tablePartieEnCours.getColumnModel().getColumn(0).setResizable(false);
tablePartieEnCours.getColumnModel().getColumn(1).setResizable(false);
tablePartieEnCours.getColumnModel().getColumn(2).setResizable(false);
tablePartieEnCours.getColumnModel().getColumn(3).setResizable(false);
}
add(scrollPanePartieEnCours);
scrollPanePartieEnCours.setBounds(20, 100, 360, 390);
labelPartiesReplay.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N
labelPartiesReplay.setText("Parties Replay");
add(labelPartiesReplay);
labelPartiesReplay.setBounds(530, 60, 140, 40);
labelPartieEnCours.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N
labelPartieEnCours.setText("Vos parties en cours ");
add(labelPartieEnCours);
labelPartieEnCours.setBounds(110, 60, 200, 40);
}// </editor-fold>//GEN-END:initComponents
/**
* Recupere l'action sur le bouton nouvelle partie et envoie l'information au controleur
* @param evt
*/
private void nouvellePartieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nouvellePartieActionPerformed
Controleur.getInstance().getCtrlJoueur().nouvellePartie();
}//GEN-LAST:event_nouvellePartieActionPerformed
/**
* Recupere l'action sur le bouton quitter et envoie l'information au controleur
* @param evt
*/
private void quitterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitterActionPerformed
Controleur.getInstance().getCtrlJoueur().quitterPageJoueur();
}//GEN-LAST:event_quitterActionPerformed
/**
* Recupere l'action sur le tableau et envoie la ligne selectionner au controleur
* @param evt
*/
private void tablePartieReplayMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablePartieReplayMouseClicked
Controleur.getInstance().getCtrlJoueur().partieReplay((Integer)tablePartieReplay.getValueAt(tablePartieReplay.getSelectedRow(),0));
}//GEN-LAST:event_tablePartieReplayMouseClicked
/**
* Recupere l'action sur le tableau et envoie la ligne selectionner au controleur
* @param evt
*/
private void tablePartieEnCoursMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablePartieEnCoursMouseClicked
Controleur.getInstance().getCtrlJoueur().partieEnCours((String) tablePartieEnCours.getValueAt(tablePartieEnCours.getSelectedRow(),1));
}//GEN-LAST:event_tablePartieEnCoursMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel labelPartieEnCours;
private javax.swing.JLabel labelPartiesReplay;
private javax.swing.JButton nouvellePartie;
private javax.swing.JButton quitter;
private javax.swing.JScrollPane scrollPanePartieEnCours;
private javax.swing.JScrollPane scrollPaneReplay;
private javax.swing.JTable tablePartieEnCours;
private javax.swing.JTable tablePartieReplay;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controleur;
import InterfaceGraphique.*;
import bataillenavale.*;
import bataillenavale.FabriqueEtat.ExceptionPartiePerdue;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
/**
*
* @author gounonj
*/
public class CtrlPartieEnCours {
/**
* en 0 : le destroyer
* en 1 : l'escorteur
* en 2 : le 2ème escorteur
*/
private boolean tirerSelection = false;
private boolean monTour;
private AbstractBateau[] tabBateau = new AbstractBateau[3];
private boolean[] tabBateauTouche = new boolean[3];
private int[] actionRestante = new int[3];
private AbstractBateau bateau;
private int indexBateau;
VerificationDeplacement verification;
private LinkedList<AbstractAction> listeAction;
public CtrlPartieEnCours(){
this.listeAction = new LinkedList<AbstractAction>();
}
private void init()
{
tirerSelection = false;
tabBateau = new AbstractBateau[3];
tabBateauTouche = new boolean[3];
actionRestante = new int[3];
}
public LinkedList<Etat> rafraichirEtat() throws ExceptionPartiePerdue{
this.listeAction = new LinkedList<AbstractAction>();
int indexEscorteur = 1;
Joueur joueur = Controleur.getInstance().getJoueur();
AbstractPartieLive partie = (AbstractPartieLive) Controleur.getInstance().getPartie();
LinkedList<Etat> listeBateau = ConcreteFabriqueEtat.getInstance().getEtatEncours(partie, joueur);
for (Etat e : listeBateau) {
if (e.getTaille() == 3) {
tabBateau[0] = e.getBateau();
actionRestante[0] = tabBateau[0].getVie();
} else {
tabBateau[indexEscorteur] = e.getBateau();
actionRestante[indexEscorteur] = tabBateau[indexEscorteur].getVie();
indexEscorteur++;
}
}
verification = new VerificationDeplacement(tabBateau);
if(!partie.monTour(joueur)){
Interface.getInstance().afficherMessageInfo("Ce n'est pas à vous de jouer");
Interface.getInstance().getPagePartieEnCours().enableBouton(false);
Interface.getInstance().getPagePartieEnCours().enableRafraichir(true);
}else{
int numTour = (partie.getNumeroTourSuivant(joueur));
affichageActionAdverse(numTour);
Interface.getInstance().getPagePartieEnCours().enableBouton(true);
Interface.getInstance().getPagePartieEnCours().enableRafraichir(false);
}
return listeBateau;
//afficherVieBateau();
}
public void rafraichirAffichageEtatBateau(){
init();
try {
LinkedList<Etat> listeBateau = rafraichirEtat();
Interface.getInstance().getPagePartieEnCours().afficherGrille(listeBateau);
/*if(!partie.monTour(joueur)){
Interface.getInstance().afficherMessageInfo("Ce n'est pas à vous de jouer");
int numTour = (partie.getNumeroTourSuivant(joueur));//partie.getAdversaire(joueur)));
affichageDeplacementAdverse(numTour);
}
/*
if(partie.monTour(joueur)){
affichageResultatTirsAdverse();
}*/
afficherVieBateau();
} catch (FabriqueEtat.ExceptionPartiePerdue ex) {
Interface.getInstance().afficherMessageInfo("Partie perdue :( jjj");
Interface.getInstance().setPageJoueur();
}
}
public void decompterActionBateau(){
this.actionRestante[indexBateau]--;
}
public void deplacement (PagePartieEnCours page,Deplacement deplacement)
{
if(tirerSelection){
tirerSelection=false;
Interface.getInstance().getPagePartieEnCours().initialiserTirer();
}
if(this.actionRestante[indexBateau] > 0){
if(verification.verifier(indexBateau,deplacement)){
listeAction.add(new ActionDeplacement(bateau, deplacement));
this.decompterActionBateau();
}
else{
Interface.getInstance().afficherMessageInfo("Deplacement impossible");
}
}else{
Interface.getInstance().afficherMessageInfo("Plus assez de points d'action pour ce bateau");
}
}
public void tournerDroite(PagePartieEnCours page) {
deplacement(page, Deplacement.DROITE);
}
public void tournerGauche(PagePartieEnCours page) {
deplacement(page, Deplacement.GAUCHE);
}
public void reculer(PagePartieEnCours page) {
deplacement(page, Deplacement.ARRIERE);
}
public void avancer(PagePartieEnCours page) {
deplacement(page, Deplacement.AVANT);
}
public void afficherCoupRestant(){
Interface.getInstance().getPagePartieEnCours().afficherCoupRestant(actionRestante[indexBateau]);
}
public void selectionEscorteur2(PagePartieEnCours page) {
System.out.println("selection escorteur");
Interface.getInstance().getPagePartieEnCours().selectionnerEscorteur2();
if(tabBateau[2] == null){
Interface.getInstance().afficherMessageInfo("Vous n'avez qu'un escorteur");
}else{
bateau = tabBateau[2];
this.indexBateau = 2;
afficherCoupRestant();
afficherVieBateau();
}
}
public void selectionEscorteur1(PagePartieEnCours page) {
System.out.println("selection escorteur1");
Interface.getInstance().getPagePartieEnCours().selectionnerEscorteur1();
bateau = tabBateau[1];
this.indexBateau = 1;
afficherCoupRestant();
}
public void selectionDestroyer(PagePartieEnCours page) {
System.out.println("selection destroyeur");
Interface.getInstance().getPagePartieEnCours().selectionnerDestroyer();
bateau = tabBateau[0];
this.indexBateau = 0;
afficherCoupRestant();
afficherVieBateau();
}
public void afficherVieBateau(){
int vieDestroyeur=0;
int vieEscorteur1=0;
int vieEscorteur2=0;
vieDestroyeur = tabBateau[0].getVie();
vieEscorteur1 = tabBateau[1].getVie();
if(tabBateau[2] != null){
vieEscorteur2 = tabBateau[2].getVie();
}
Interface.getInstance().getPagePartieEnCours().
afficherVie(vieDestroyeur, vieEscorteur1, vieEscorteur2);
}
public void tirer(PagePartieEnCours page) {
this.tirerSelection=true;
Interface.getInstance().getPagePartieEnCours().afficherTirer();
}
public void retourPageJoueur() {
Interface.getInstance().setPageJoueur();
}
public void selectionCase(JPanel jPanelTabAdversaire, int j) {
if (this.actionRestante[indexBateau] > 0) {
if (tirerSelection) {
tirerSelection = false;
Interface.getInstance().getPagePartieEnCours().afficherCase(j);
Interface.getInstance().getPagePartieEnCours().initialiserTirer();
decompterActionBateau();
System.out.println("Le bateau" + bateau.getIdBateau() + " a tiré sur la case : x : " + (j % 10 + 1) + ", y : " + (j / 10 + 1) + " :) 77RPZ ");
listeAction.add(new ActionTir(bateau, j % 10 + 1, j / 10 + 1));
}
} else {
Interface.getInstance().afficherMessageInfo("Plus assez de points d'action pour ce bateau");
}
}
/*public void rafraichirPartie() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}*/
public void validerActions() {
AbstractPartieLive partie = (AbstractPartieLive) Controleur.getInstance().getPartie();
Joueur joueur = Controleur.getInstance().getJoueur();
if(!partie.monTour(joueur)){
Interface.getInstance().afficherMessageInfo("Ce n'est pas à vous de jouer");
return;
}
try {
LinkedList<int[]> coordBateauxTouches = partie.JouerCoup(listeAction, Controleur.getInstance().getJoueur(), partie.getNumeroTourSuivant(Controleur.getInstance().getJoueur()));
affichageResultatTirs(coordBateauxTouches);
rafraichirAffichageEtatBateau();
}catch (AbstractPartieLive.ExceptionCoupImpossible ex) {
Interface.getInstance().afficherMessageInfo("Coups Impossible, veuillez rejouer");
rafraichirAffichageEtatBateau();
}
catch(FabriqueEtat.ExceptionPartiePerdue ex){
partie.finPartie(joueur);
Interface.getInstance().afficherMessageInfo("Partie gagnée !!");
Interface.getInstance().setPageJoueur();
}
this.listeAction = new LinkedList<AbstractAction>();
}
/**
* Affiche le resultat des tirs du joueur
* @param coordBateauxTouches
*/
private void affichageResultatTirs(LinkedList<int[]> coordBateauxTouches){
String message = null;
if (coordBateauxTouches.isEmpty()) {
message = "Aucun bateau touché";
} else {
message = "Resutat des tirs : \n ";
for (int[] a : coordBateauxTouches) {
message += "x = " + a[0] + " y = " + a[1] + "\n";
}
}
Interface.getInstance().afficherMessageInfo(message);
}
/**
* Affiche le resultat des deplacements adverses
*/
private String afficheDeplacementAdverse(int numTour){
String message = "";
int idPartie = Controleur.getInstance().getPartie().getIdPartie();
LinkedList<AbstractAction> listAction = ConcreteFabriqueAction.getInstance().getActionDeplacement(idPartie, numTour);
for(AbstractAction a : listAction){
message+= " un bateau a effectué un deplacement "+((ActionDeplacement)a).getDeplacement().toString()+'\n';
}
if (message.equals("")){
message = "Aucun Deplacement ennemi \n";
}else{
message="Deplacement(s) Adverse :\n" + message;
}
return message;
//Interface.getInstance().afficherMessageInfo(message);
}
private String afficheTirAdverse(int numTour){
String message = "";
int idPartie = Controleur.getInstance().getPartie().getIdPartie();
LinkedList<AbstractAction> listAction = ConcreteFabriqueAction.getInstance().getActionTir(idPartie, numTour);
for(AbstractAction a : listAction){
message+= " x = "+ ((ActionTir)a).getCoordX() +"y = "+((ActionTir)a).getCoordY()+"\n";
}
if (message.equals("")){
message = "\nAucun tir ennemi\n";
}else{
message="\ntir(s) Adverse\n" + message;
}
return message;
//Interface.getInstance().afficherMessageInfo(message);
}
private void setTabBateauTouche(int index){
int nouvelleVie = tabBateau[index].getVie();
if (actionRestante[index] != nouvelleVie) {
tabBateauTouche[index] = true;
}
}
private void affichageActionAdverse(int numTour) {
String message = afficheDeplacementAdverse(numTour-1);
message += afficheTirAdverse(numTour-1);
Interface.getInstance().afficherMessageInfo(message);
}
/**
*
* @param x la position x du pivot
* @param y la position y du pivot
* @param direction
* @return renvoie vrai si aucun bateau ne se superpose
*/
private class VerificationDeplacement{
private AbstractBateau[] tabBateau2 = new AbstractBateau[3];
public VerificationDeplacement(AbstractBateau[] tabBateau) {
for(int i=0;i<3;i++){
if(tabBateau[i]!=null)
this.tabBateau2[i]= tabBateau[i].copy();
}
}
public boolean verifier(int bateauIndex,Deplacement deplacement) {
AbstractPartie partie = Controleur.getInstance().getPartie();
Joueur joueur = Controleur.getInstance().getJoueur();
boolean grille[][] = new boolean[11][11];
for (int ibateau=0;ibateau<3;ibateau++) {
AbstractBateau bateau_tmp=this.tabBateau2[ibateau];
if(bateau_tmp!=null && ibateau!=bateauIndex){
try {
for (Integer[] coord : bateau_tmp.getCoordonees()) {
grille[coord[0]][coord[1]] = true;
}
} catch (AbstractPartieLive.ExceptionCoupImpossible ex) {
Logger.getLogger(CtrlPartieEnCours.class.getName()).
log(Level.SEVERE, null, ex);
}
}
}
AbstractBateau bateau_tmp = this.tabBateau2[bateauIndex].copy();
try {
bateau_tmp.deplacer(deplacement);
} catch (AbstractPartieLive.ExceptionCoupImpossible ex) {
return false;
}
try {
for (Integer[] coord : bateau_tmp.getCoordonees()) {
if (grille[coord[0]][coord[1]]) {
return false;
}
}
} catch (AbstractPartieLive.ExceptionCoupImpossible ex) {
return false;
}
this.tabBateau2[bateauIndex]=bateau_tmp;
return true;
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bataillenavale;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author thomas
*/
public class ConcreteFabriqueBateau implements FabriqueBateau{
private static ConcreteFabriqueBateau instance = null;
public static ConcreteFabriqueBateau getInstance(){
if(instance == null){
instance = new ConcreteFabriqueBateau();
}
return instance;
}
/**
* Permet d'obtenir la liste des bateaux d'un joueur pour une partie donnée
* @param idPartie
* @param joueur
* @return
*/
@Override
public LinkedList<AbstractBateau> getBateau(int idPartie, Joueur joueur){
int id=1;
LinkedList<AbstractBateau> listeBateau = new LinkedList<AbstractBateau>();
try {
// reccuperation du numero de tour relatif au placement des bateaux au début de la partie
String requete = "SELECT MIN(numTour) FROM Tour t WHERE t.pseudo = ? AND t.idPartie= ?";
ResultSet reponse = null;
PreparedStatement stt1;
ResultSet reponse2 = null;
PreparedStatement stt2 = null;
stt1 = BDManager.getInstance().prepareStatement(requete);
stt1.setString(1, joueur.getPseudo());
stt1.setInt(2, idPartie);
reponse = stt1.executeQuery();
if (reponse.next()) {
// reccuperation des idBateaux
try {
requete = "SELECT DISTINCT idBateau FROM Action WHERE idPartie =? "
+ " AND numTour = ?";
stt2 = BDManager.getInstance().prepareStatement(requete);
stt2.setInt(1, idPartie);
stt2.setInt(2, reponse.getInt(1));
reponse2 = stt2.executeQuery();
} catch (Exception ex) {
Logger.getLogger(ConcreteFabriqueBateau.class.getName()).log(Level.SEVERE, "reccuperation des idBateau impossible", ex);
}
// creation des bateaux
try {
while (reponse2.next()) {
id = reponse2.getInt("idBateau");
listeBateau.add(NewBateau(id));
}
} catch (Exception ex) {
Logger.getLogger(ConcreteFabriqueBateau.class.getName()).log(Level.SEVERE, null, ex);
}
reponse.close();
reponse2.close();
stt1.close();
stt2.close();
}
} catch (SQLException ex) {
Logger.getLogger(ConcreteFabriqueBateau.class.getName()).log(Level.SEVERE, null, ex);
}
return listeBateau;
}
/**
* Pour récuperer un bateau en base de donnée
* @param idBateau
* @return
*/
public AbstractBateau NewBateau(int idBateau) throws SQLException{
String requete = "SELECT Type FROM Bateau b where b.idBateau = ? ";
PreparedStatement stt = BDManager.getInstance().prepareStatement(requete);
stt.setInt(1, idBateau);
ResultSet reponse = stt.executeQuery();
reponse.next();
if(reponse.getString(1).equals("destroyer")){
reponse.close();
stt.close();
return new BateauDestroyer(idBateau);
}else{
reponse.close();
stt.close();
return new BateauEscorteur(idBateau);
}
}
/**
* Pour créer un bateau en base de donnée
* @param joueur
* @return
*/
@Override
public BateauDestroyer getDestroyer(Joueur joueur) {
int idBateau = 0;
String requete = "INSERT INTO Bateau values (sequence_bateau.nextval,'destroyer',?)";
try {
PreparedStatement stt = BDManager.getInstance().prepareStatement(requete);
stt.setString(1, joueur.getPseudo());
stt.executeQuery();
stt.close();
requete = "SELECT sequence_bateau.currval from Bateau";
stt = BDManager.getInstance().prepareStatement(requete);
ResultSet resultat = stt.executeQuery();
resultat.next();
idBateau=resultat.getInt(1);
resultat.close();
stt.close();
} catch (SQLException ex) {
Logger.getLogger(ConcreteFabriqueBateau.class.getName()).log(Level.SEVERE, "Erreur lors de la creation d'un destroyer", ex);
}
return new BateauDestroyer(idBateau);
}
@Override
public BateauEscorteur getEscorteur(Joueur joueur) {
int idBateau = 0;
String requete = "INSERT INTO Bateau values (sequence_bateau.nextval,'escorteur',?)";
try {
PreparedStatement stt = BDManager.getInstance().prepareStatement(requete);
stt.setString(1,joueur.getPseudo() );
stt.executeQuery();
stt.close();
requete = "SELECT sequence_bateau.currval from Bateau";
stt = BDManager.getInstance().prepareStatement(requete);
ResultSet resultat = stt.executeQuery();
resultat.next();
idBateau=resultat.getInt(1);
resultat.close();
stt.close();
} catch (SQLException ex) {
Logger.getLogger(ConcreteFabriqueBateau.class.getName()).log(Level.SEVERE, "Erreur lors de la creation d'un destroyer", ex);
}
return new BateauEscorteur(idBateau);
}
/**
* Permet de créer le bateau mais aussi l'acion qui correspond au placement de ce batea
* @param joueur
* @param x
* @param y
* @param direction
* @return l'action à effectuer en base de donnée pour placer le bateau
*/
@Override
public ActionPlacement placerDestroyer(Joueur joueur, int x, int y, Direction direction) {
BateauDestroyer bateau = getDestroyer(joueur);
bateau.setCoordX(x);
bateau.setCoordY(y);
bateau.setTaille(3);
bateau.setDirection(direction);
return new ActionPlacement(x,y, bateau);
}
@Override
public ActionPlacement placerEscorteur(Joueur joueur, int x, int y, Direction direction) {
BateauEscorteur bateau = getEscorteur(joueur);
bateau.setCoordX(x);
bateau.setCoordY(y);
bateau.setDirection(direction);
bateau.setTaille(2);
return new ActionPlacement(x,y, bateau);
}
}<file_sep>/**
*
* Action déplacement, avec un enregistrerActionspécifique (Patron stratégie)
*
*
*/
package bataillenavale;
import bataillenavale.AbstractPartieLive.ExceptionCoupImpossible;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author thomas
*/
public class ActionDeplacement extends AbstractAction{
/**
* Attributs
*/
Deplacement deplacement;
public Deplacement getDeplacement() {
return deplacement;
}
/**
* Constructeur
* @param bateau
* @param deplacement
*/
public ActionDeplacement(AbstractBateau bateau,Deplacement deplacement) {
super(bateau);
this.deplacement=deplacement;
}
/**
* Cree le tuple dans la table ActionDeplacement et execute l'action
* @param partie
* @param joueur
* @param numTour
* @param numAction
* @throws bataillenavale.AbstractPartieLive.ExceptionCoupImpossible
* @throws bataillenavale.FabriqueEtat.ExceptionPartiePerdue
*/
@Override
public void enregistrerAction(AbstractPartieLive partie, Joueur joueur, int numTour, int numAction) throws ExceptionCoupImpossible{
try {
super.enregistrerAction(partie, joueur, numTour, numAction);
} catch (ExceptionBateauTouche ex) {
Logger.getLogger(ActionDeplacement.class.getName()).log(Level.SEVERE, null, ex);
}
try {
// recuperation de idAction
int idAction = 0;
PreparedStatement stt = BDManager.getInstance().prepareStatement("SELECT sequence_action.currval FROM Action");
ResultSet resultat = stt.executeQuery();
resultat.next();
idAction = resultat.getInt(1);
// creation du tuple ActionDeplacement
stt = BDManager.getInstance().prepareStatement("INSERT INTO ActionDeplacement VALUES (?,?)");
stt.setInt(1, idAction);
stt.setString(2, deplacement.toString());
stt.executeQuery();
stt.close();
this.getBateau().deplacer(deplacement);
// creation du tuple etat
stt = BDManager.getInstance().prepareStatement("INSERT INTO Etat VALUES(sequence_etat.nextval,?,?,?,?,?,?,?,?)");
stt.setInt(1, this.getBateau().getCoordX());
stt.setInt(2,this.getBateau().getCoordY());
stt.setString(3, this.getBateau().getDirection().toString());
stt.setInt(4,this.getBateau().getVie());
stt.setInt(5, idAction);
stt.setInt(6,numAction);
stt.setInt(7,this.getBateau().getIdBateau());
stt.setInt(8, this.getBateau().taille);
stt.executeQuery();
stt.close();
} catch (SQLException ex){
throw new ExceptionCoupImpossible();
}
}
}
<file_sep>/**
* Acion spécifique au tir, utilisé pour la patron stratégie
*
*/
package bataillenavale;
import bataillenavale.AbstractAction.*;
import bataillenavale.AbstractPartieLive.ExceptionCoupImpossible;
import bataillenavale.FabriqueEtat.ExceptionPartiePerdue;
import java.awt.PageAttributes;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author thomas
*/
public class ActionTir extends AbstractAction{
int coordX;
public int getCoordX() {
return coordX;
}
public int getCoordY() {
return coordY;
}
int coordY;
public ActionTir(AbstractBateau bateau, int coordX, int coordY) {
super(bateau);
this.coordX=coordX;
this.coordY=coordY;
}
/**
* Pour enregistrer l'action et le nouvel état en base de donnée
* @param partie
* @param joueur
* @param numTour
* @param numAction
* @throws bataillenavale.AbstractPartieLive.ExceptionCoupImpossible
* @throws bataillenavale.AbstractAction.ExceptionBateauTouche
*/
@Override
public void enregistrerAction(AbstractPartieLive partie, Joueur joueur, int numTour, int numAction) throws ExceptionCoupImpossible,ExceptionBateauTouche{
//création du tir dans la base de donnée
try {
super.enregistrerAction(partie, joueur, numTour, numAction);
int idAction = 0;
ResultSet resultat;
PreparedStatement stt;
String requete;
try {
requete = "SELECT sequence_action.currval FROM Action";
stt = BDManager.getInstance().prepareStatement(requete);
resultat = stt.executeQuery();
resultat.next();
idAction = resultat.getInt(1);
resultat.close();
stt.close();
} catch (SQLException ex) {
Logger.getLogger(ActionTir.class.getName()).log(Level.SEVERE, "La recuperation de idAction a echoué", ex);
}
// creation du tuple ActionTir
try {
requete = "INSERT INTO ActionTir VALUES ("+idAction+","+coordX+","+coordY+")";
stt = BDManager.getInstance().prepareStatement(requete);
stt.executeQuery(requete);
stt.close();
} catch (SQLException ex) {
Logger.getLogger(ActionTir.class.getName()).log(Level.SEVERE, "La creation de ActionTir a echoué", ex);
}
// Recherche si un bateau adverse est present sur cette case
// list bateau du joueur adverse :
LinkedList<Etat> listEtatBateau=null;
listEtatBateau = ConcreteFabriqueEtat.getInstance().getEtatEncours(partie, partie.getAdversaire(joueur));
/**
* Si le bateau est touché, on enregistre un nouvel état dans la base de donnée, et on lève l'exception pour informer que le coup a touché
*/
AbstractBateau bateauAdverse;
for(Etat e: listEtatBateau){
if(e.estVivant()){
if(e.estTouche(coordX, coordY)){
// TODO MAJ etat bateau touché
e.getBateau().afficheEtat();
bateauAdverse = e.getBateau();
bateauAdverse.setVie(bateauAdverse.getVie()-1);
e.setVie(e.getVie()-1);
stt = BDManager.getInstance().prepareStatement("INSERT INTO Etat VALUES(sequence_etat.nextval,?,?,?,?,?,?,?,?)");
stt.setInt(1, bateauAdverse.getCoordX());
stt.setInt(2, bateauAdverse.getCoordY());
stt.setString(3, bateauAdverse.getDirection().toString());
stt.setInt(4, bateauAdverse.getVie());
stt.setInt(5, idAction);
stt.setInt(6,numAction);
stt.setInt(7,bateauAdverse.getIdBateau());
stt.setInt(8, bateauAdverse.getTaille());
stt.executeQuery();
stt.close();
throw new ExceptionBateauTouche(coordX,coordY);
}
}
}
} catch (SQLException ex) {
Logger.getLogger(ActionTir.class.getName()).log(Level.SEVERE, "action tir failed", ex);
} catch (ExceptionPartiePerdue ex) {
Logger.getLogger(ActionTir.class.getName()).log(Level.FINE, "Partie Perdue", ex);
partie.finPartie(joueur);
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package InterfaceGraphique;
import Controleur.Controleur;
import javax.swing.JInternalFrame;
import javax.swing.JTextField;
/**
* JPanel page accueil
* @author gounonj
*/
public class PageAccueil extends javax.swing.JPanel {
/**
* Creates new form PageAccueil
*/
public PageAccueil() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
pseudo = new javax.swing.JTextField();
inscription = new javax.swing.JButton();
connexion = new javax.swing.JButton();
labelPseudo = new javax.swing.JLabel();
setPreferredSize(new java.awt.Dimension(800, 600));
inscription.setText("Inscription");
inscription.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
inscriptionActionPerformed(evt);
}
});
connexion.setText("Connexion");
connexion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
connexionActionPerformed(evt);
}
});
labelPseudo.setText("Pseudo :");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(313, 313, 313)
.addComponent(labelPseudo)
.addGap(12, 12, 12)
.addComponent(pseudo, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(connexion)
.addGap(18, 18, 18)
.addComponent(inscription)
.addGap(180, 180, 180))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(labelPseudo))
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(pseudo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(connexion)
.addComponent(inscription))
.addGap(550, 550, 550))
);
}// </editor-fold>//GEN-END:initComponents
/**
* Recupere l'action sur le bouton inscription et envoie l'information au controleur
* @param evt
*/
private void inscriptionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inscriptionActionPerformed
Controleur.getInstance().getCtrlAccueil().inscription();
}//GEN-LAST:event_inscriptionActionPerformed
/**
* Recupere l'action sur le bouton connexion et envoie l'information au controleur
* @param evt
*/
private void connexionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connexionActionPerformed
Controleur.getInstance().getCtrlAccueil().connexion(this);
}//GEN-LAST:event_connexionActionPerformed
/**
* On recupere le pseudo renseigné dans le JTextField
* @return
*/
public JTextField getPseudo(){
return this.pseudo;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton connexion;
private javax.swing.JButton inscription;
private javax.swing.JLabel labelPseudo;
private javax.swing.JTextField pseudo;
// End of variables declaration//GEN-END:variables
}
<file_sep>DROP TABLE ActionTir;
DROP TABLE ActionDeplacement;
DROP TABLE ActionPlacement;
DROP TABLE AGagne;
DROP TABLE Etat;
DROP TABLE Action;
DROP TABLE Bateau;
DROP TABLE Tour;
DROP TABLE Participe;
DROP TABLE Parties;
DROP TABLE Joueur ;
DROP SEQUENCE sequence_parties;
DROP SEQUENCE sequence_bateau;
DROP SEQUENCE sequence_action;
DROP SEQUENCE sequence_etat;
CREATE SEQUENCE sequence_parties;
CREATE SEQUENCE sequence_bateau;
CREATE SEQUENCE sequence_action;
CREATE SEQUENCE sequence_etat;
CREATE TABLE Joueur
(
pseudo VARCHAR(20) PRIMARY KEY,
nom VARCHAR(100),
prenom VARCHAR(100),
email VARCHAR(255),
dateNaissance DATE,
numRue INT,
ville VARCHAR(255),
check (NumRue >= 0)
);
CREATE TABLE Parties
(
idPartie INT PRIMARY KEY,
dateDebut DATE
);
CREATE TABLE Participe
(
pseudo VARCHAR(20),
idPartie INT references Parties (idPartie),
PRIMARY KEY(pseudo, idPartie)
);
CREATE TABLE Tour
(
numTour INT,
idPartie INT references Parties(idPartie),
pseudo VARCHAR(20) references Joueur(pseudo),
PRIMARY KEY(NumTour,idPartie)
);
CREATE TABLE Bateau
(
idBateau INT,
type VARCHAR(20),
-- ('destroyer', 'escorteur'),
pseudo VARCHAR(20),
FOREIGN key(pseudo) references Joueur(pseudo),
CONSTRAINT type_check CHECK(type IN ('destroyer','escorteur')),
PRIMARY KEY (idBateau)
);
CREATE TABLE Action
(
idAction INT,
numTour INT ,
numAction INT,
idPartie INT ,
idBateau INT references Bateau(idBateau),
PRIMARY KEY(idAction),
FOREIGN KEY (idPartie,numTour) references Tour(idPartie,numTour)
);
CREATE TABLE Etat (
idEtat INT,
X INT,
Y INT,
direction VARCHAR(20),
vie INT,
idAction INT ,
numAction INT ,
idBateau INT references Bateau(idBateau),
taille INT,
PRIMARY KEY(idEtat),
FOREIGN KEY (idAction) references Action(idAction),
CHECK (taille BETWEEN 2 and 3),
CHECK (vie BETWEEN 0 and 3),
CONSTRAINT check_pivot CHECK (X BETWEEN 1 and 10 and Y BETWEEN 1 and 10),
CONSTRAINT direction_check CHECK(direction IN ('NORD','SUD','EST','OUEST')),
check ((direction = 'NORD' and Y - taille >= 0) or
(direction = 'SUD' and Y + taille <= 11) or
(direction = 'OUEST' and X - taille >= 0) or
(direction = 'EST' and X + taille <= 11))
);
CREATE TABLE AGagne(
pseudo VARCHAR(20) references Joueur(pseudo),
idPartie INT references Parties(idPartie),
PRIMARY KEY(pseudo,idPartie)
);
CREATE TABLE ActionDeplacement(
idAction INT references Action(idAction),
sens VARCHAR(7),
-- ('gauche','droite'),
CONSTRAINT sens_check CHECK(sens IN ('GAUCHE','DROITE','AVANT','ARRIERE')),
PRIMARY KEY (idAction)
);
CREATE TABLE ActionPlacement(
idAction INT references Action(idAction),
--sens VARCHAR(7),
-- ('gauche','droite'),
CONSTRAINT sens_check_placement CHECK(sens IN ('GAUCHE','DROITE','AVANT','ARRIERE')),
PRIMARY KEY (idAction)
);
CREATE TABLE ActionTir(
idAction INT references Action(idAction),
X INT,
Y INT,
PRIMARY KEY (idAction),
CHECK (X BETWEEN 1 and 10 and Y BETWEEN 1 and 10 )
);
<file_sep>
changer l'endroit où se trouve la fonction estTouche (la modifier également)
vérifier que les déplacements sont les bons (avec le repère)
rajouter la contrainte sur les déplacements
--- Detecter escorteur 1 et 2 ---> fait
--- Afficher tire de l'ennemi ---> fait
--- Quand c'est pas ton tour , bouton enabled(false)--> fait
--- Changer label partie en cours ---> fait
--- bouton revenir pagejoueur(quand on est dans pagepartieencours ---> fait
Faire une passe sur tout le code
Se souvenir de ou on a tirer sur la carte ennemi aprés une co reco
Faire un champ pour partie terminé dans page partie joueur
enlever le champ 'selection partie en cours'
--- A faire valider gagner ---> fait
ABSTRACT Joueur
Action placement bateaux carte
Partie replay que l'on a joué peuvent etre vu si elles sont terminées
rafraichir les pts de vies et pts actions
//// BUG //////
Inscription
placement bateau premiere ligne(verifier placement)
//option
(bouton rafraichir pagejoueur)
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author jocelyn
*/
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
public class Bouton extends JButton{
private String name;
private Image img;
public Bouton(String str){
super(str);
this.name = str;
try {
img = ImageIO.read(new File("fondBouton.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D)g;
GradientPaint gp = new GradientPaint(0, 0, Color.blue, 0, 20, Color.cyan, true);
g2d.setPaint(gp);
g2d.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
g2d.setColor(Color.black);
g2d.drawString(this.name, this.getWidth() / 2 - (this.getWidth() / 2 /4), (this.getHeight() / 2) + 5);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controleur;
import InterfaceGraphique.Interface;
import bataillenavale.BDManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author gounonj
*/
public class CtrlInterface {
public void fermerConnexion() {
try {
BDManager.getInstance().closeConnection();
} catch (SQLException ex) {
Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void ouvrirConnexion() {
try {
System.out.println("Connexion ouverte");
BDManager.getInstance().openConnection();
} catch (SQLException ex) {
Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<file_sep>/**
*
* classe abstraite de l'Etat, est utilisée par les programmeurs des couches supérieures
*
*/
package bataillenavale;
/**
*
* @author pierre
*/
public abstract class AbstractEtat {
/**
* detect si un bateau est touche par un tir
* @param e
* @param coordX
* @param coordY
* @return
*/
public abstract boolean estTouche(int coordX, int coordY);
public abstract boolean estVivant();
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package InterfaceGraphique;
import Controleur.Controleur;
import Controleur.CtrlInterface;
import bataillenavale.BDManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* Classe Interface est un singleton qui contient les informations sur l'interface graphique
*
* @author gounonj
*/
public final class Interface extends javax.swing.JFrame {
private static volatile Interface instance = null;
/**
* Contient les differentes pages que l'on peut afficher
*/
private PageAccueil pageAccueil;
private PageInscription pageInscription;
private PageJoueur pageJoueur;
private PageNouvellePartie pageNouvellePartie;
private PagePartieEnCours pagePartieEnCours;
private PagePartieReplay pagePartieReplay;
/**
* Créer la JFrame principale qui va contenir les JPanel nommés PageXXX
*/
private Interface() {
super();
initComponents();
fixRootPane();
}
/**
* Retourne l'instance de l'interface, et la créer si elle n'existe pas deja
*
* @return Interface
*/
public final static Interface getInstance() {
if (Interface.instance == null) {
synchronized(Interface.class) {
if (Interface.instance == null) {
Interface.instance = new Interface();
}
}
}
return Interface.instance;
}
/**
* Methode autogenere grace a l'outil netbeans
*
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(800, 600));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 281, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* Fixe la panel racine de la frame
*/
private void fixRootPane() {
this.setRootPane(rootPane);
}
/**
* Permet de fermer la connexion lors de la fermeture de la fenetre.
* @param evt
*/
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
Controleur.getInstance().getCtrlInterface().fermerConnexion();
}//GEN-LAST:event_formWindowClosing
/**
* Oouvre la connexion lors de l'ouveture de la fenetre
* @param evt
*/
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
Controleur.getInstance().getCtrlInterface().ouvrirConnexion();
}//GEN-LAST:event_formWindowOpened
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Interface.getInstance().setVisible(true);
Interface.getInstance().setPageAccueil();
}
});
}
/**
* Affiche un message d'erreur
*
* @param message Sring
*/
public void afficherMessageErreur(String message) {
JOptionPane jop3 = new JOptionPane();
jop3.showMessageDialog(null, message, "Erreur", JOptionPane.ERROR_MESSAGE);
jop3.setVisible(true);
this.revalidate();
}
/**
* Affiche un message d'information
* @param message
*/
public void afficherMessageInfo(String message) {
JOptionPane jop3 = new JOptionPane();
jop3.showMessageDialog(null, message, "Attention", JOptionPane.INFORMATION_MESSAGE);
jop3.setVisible(true);
this.revalidate();
}
/**
* Retourne la page accueil
* @return Jpanel
*/
public PageAccueil getPageAccueil() {
return pageAccueil;
}
/**
* Retourne la page d'inscription
* @return Jpanel
*/
public PageInscription getPageInscription() {
return pageInscription;
}
/**
* Retourne la page du joueur
* @return Jpanel
*/
public PageJoueur getPageJoueur() {
return pageJoueur;
}
/**
* Retourne la page nouvelle partie
* @return Jpanel
*/
public PageNouvellePartie getPageNouvellePartie() {
return pageNouvellePartie;
}
/**
* Retourne la page pour les parties en cours
* @return Jpanel
*/
public PagePartieEnCours getPagePartieEnCours() {
return pagePartieEnCours;
}
/**
* Retourne la page pour les parties en replay
* @return Jpanel
*/
public PagePartieReplay getPagePartieReplay() {
return pagePartieReplay;
}
/**
* Fixe la JPanel courante a la page nouvelle partie
*/
public void setPageNouvellePartie(){
this.pageNouvellePartie = new PageNouvellePartie();
Interface.getInstance().setContentPane(this.pageNouvellePartie);
Interface.getInstance().revalidate();
}
/**
* Fixe la JPanel courante a la page accueil
*/
public void setPageAccueil(){
this.pageAccueil = new PageAccueil();
Interface.getInstance().setContentPane(this.pageAccueil);
Interface.getInstance().revalidate();
}
/**
* Fixe la JPanel courante a la page inscription
*/
public void setPageInscription(){
this.pageInscription = new PageInscription();
Interface.getInstance().setContentPane(this.pageInscription);
Interface.getInstance().revalidate();
}
/**
* Fixe la JPanel courante a la page joueur
*/
public void setPageJoueur(){
this.pageJoueur = new PageJoueur();
Interface.getInstance().setContentPane(this.pageJoueur);
Interface.getInstance().revalidate();
}
/**
* Fixe la JPanel courante a la page partie en cours
*/
public void setPagePartieEnCours(){
this.pagePartieEnCours = new PagePartieEnCours();
Interface.getInstance().setContentPane(this.pagePartieEnCours);
Interface.getInstance().revalidate();
Controleur.getInstance().getCtrlPartieEnCours().rafraichirAffichageEtatBateau();
}
/**
* Fixe la JPanel courante a la page des parties replay
*/
public void setPagePartieReplay(){
this.pagePartieReplay = new PagePartieReplay();
Interface.getInstance().setContentPane(this.pagePartieReplay);
Interface.getInstance().revalidate();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
<file_sep>/**
*
* Classe mère des Action. Le patron appliqué est le patron stratégie, avec la fonction enregistrer action
*
*
*/
package bataillenavale;
import bataillenavale.AbstractPartieLive.ExceptionCoupImpossible;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class AbstractAction {
/**
* Le bateau qui execute l'action
*/
private AbstractBateau bateau;
public AbstractAction(AbstractBateau bateau){
this.bateau = bateau;
}
/**
* Pour enregistrer une action en base de donnée
* creer le tuple dans la table action
* @param idPartie
*/
public void enregistrerAction(AbstractPartieLive partie, Joueur joueur, int numTour, int numAction) throws ExceptionCoupImpossible,ExceptionBateauTouche{
PreparedStatement stt;
try {
stt = BDManager.getInstance().prepareStatement("INSERT INTO Action VALUES(sequence_action.nextval,?,?,?,?)");
stt.setInt(1, numTour);
stt.setInt(2, numAction);
stt.setInt(3, partie.getIdPartie());
stt.setInt(4,this.getBateau().getIdBateau());
stt.executeQuery();
stt.close();
} catch (SQLException ex) {
Logger.getLogger(AbstractAction.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @return the bateau
*/
public AbstractBateau getBateau() {
return bateau;
}
/**
* Exception levée si lors de notre action on touche un bateau adverse
*/
public static class ExceptionBateauTouche extends Exception {
int coordX;
int coordY;
public int getCoordX() {
return coordX;
}
public int getCoordY() {
return coordY;
}
public ExceptionBateauTouche(int x,int y) {
this.coordX=x;
this.coordY=y;
}
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bataillenavale;
import java.sql.*;
import java.util.LinkedList;
import java.util.logging.*;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Patron de conception fabrique
*
* @author jaylesr
*/
public class ConcreteFabriqueJoueur implements FabriqueJoueur {
/**
* une ConcreteFabriqueJoueur est un singleton
*/
private static ConcreteFabriqueJoueur instance = null;
private ConcreteFabriqueJoueur() {
super();
}
/**
* une ConcreteFabriqueJoueur est un singleton
*/
public static FabriqueJoueur getInstance() {
//si il faut créer une nouvelle instance
if (ConcreteFabriqueJoueur.instance == null) {
ConcreteFabriqueJoueur.instance = new ConcreteFabriqueJoueur();
}
return ConcreteFabriqueJoueur.instance;
}
/**
* recherche dans la base le tuple joueur avec son pseudo
*
* @param pseudo
* @return
* @throws bataillenavale.FabriqueJoueur.pseudoInexistantException
*/
@Override
public Joueur getJoueur(String pseudo) throws pseudoInexistantException {
String requete = "SELECT * FROM Joueur j WHERE j.pseudo = '" + pseudo + "'";
try {
PreparedStatement stt = BDManager.getInstance().prepareStatement(requete);
ResultSet resultat = stt.executeQuery();
if (!resultat.next()) {
throw new pseudoInexistantException();
}
stt.close();
resultat.close();
} catch (SQLException ex) {
Logger.getLogger(ConcreteFabriqueJoueur.class.getName()).log(Level.SEVERE, null, ex);
}
return new Joueur(pseudo);
}
/**
* Creer un joueur lors de l'incription
*
* @param pseudo
* @param nom
* @param prenom
* @param email
* @param date
* @param NumRue
* @param nomVille
* @return un nouvelle objet joueur
* @throws bataillenavale.FabriqueJoueur.pseudoExistantException
*/
@Override
public Joueur getJoueur(String pseudo, String nom, String prenom, String email, Date date, int NumRue, String nomVille) throws pseudoExistantException {
PreparedStatement statement;
try {
statement = BDManager.getInstance().prepareStatement("INSERT INTO joueur VALUES(?,?,?,?,?,?,?)");
statement.setString(1, pseudo);
statement.setString(2, nom);
statement.setString(3, prenom);
statement.setString(4, email);
statement.setDate(5, date);
statement.setInt(6, NumRue);
statement.setString(7, nomVille);
statement.executeQuery();
statement.close();
} catch (SQLException ex) {
if (ex.getErrorCode() == 1) {
throw new pseudoExistantException();
} else {
Logger.getLogger(ConcreteFabriqueJoueur.class.getName()).log(Level.SEVERE, null, ex);
}
}
return new Joueur(pseudo);
}
/**
* Trouver tout les participants potentiels lors d'une creation de partie
*
* @param joueur
* @return
*/
@Override
public ArrayList<Joueur> getParticipationJoueur(Joueur joueur) {
ResultSet resultat;
PreparedStatement stt;
ArrayList<Joueur> listeJoueur = new ArrayList<Joueur>();
try {
//on commence par récuperer les joueurs qui n'ont jamais joués une seule partie
String requete = "SELECT pseudo FROM joueur WHERE NOT EXISTS (SELECT DISTINCT pseudo FROM participe WHERE joueur.pseudo = participe.pseudo) AND joueur.pseudo != ?";
stt = BDManager.getInstance().prepareStatement(requete);
stt.setString(1, joueur.getPseudo());
resultat = stt.executeQuery();
while (resultat.next()) {
listeJoueur.add(new Joueur(resultat.getString(1), 0));
}
stt.close();
resultat.close();;
//ensuite on ajoute les joueurs qui ont déjà participé à une partie
//TODO enlevé ceux qui ne participent pas
requete = "SELECT pseudo, COUNT(idPartie) FROM participe part WHERE NOT EXISTS(SELECT p1.pseudo "
+ "FROM participe p1 CROSS JOIN participe p2 WHERE p1.IDPARTIE=p2.IDPARTIE "
+ "AND p1.pseudo != p2.pseudo AND p1.pseudo != ? "
+ "AND p2.pseudo = ? AND part.pseudo = p1.pseudo ) "
+ "AND pseudo != ? GROUP BY(pseudo)";
stt = BDManager.getInstance().prepareStatement(requete);
stt.setString(1, joueur.getPseudo());
stt.setString(2, joueur.getPseudo());
stt.setString(3, joueur.getPseudo());
resultat = stt.executeQuery();
while (resultat.next()) {
listeJoueur.add(new Joueur(resultat.getString(1), resultat.getInt(2)));
}
stt.close();
resultat.close();
} catch (SQLException ex) {
Logger.getLogger(ConcreteFabriqueJoueur.class.getName()).log(Level.SEVERE, null, ex);
}
return listeJoueur;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bataillenavale;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
/**
*
* @author jaylesr
*/
public interface FabriqueJoueur {
/**
* Permet de tester l'existance du joueur
* @param pseudo du joueur
* @return un joueur existant
* @throws pseudoInexistantException si le joueur n'existe
*/
abstract Joueur getJoueur(String pseudo) throws pseudoInexistantException;
/**
* Requete utilisée pour l'inscription d'un joueur dans la base de données
* @param pseudo
* @param nom
* @param prenom
* @param email
* @param date
* @param NumRue
* @param nomVille
* @return
* @throws pseudoExistantException is jamais ce pseudo existe déjà dans la base
*/
abstract Joueur getJoueur(String pseudo, String nom, String prenom, String email, Date date, int NumRue, String nomVille) throws pseudoExistantException;
/**
* Permet d'aller chercher dans la base de donnée l'ensemble des joueurs avec le nombre de parties jouées
* @param joueur
* @return
*/
abstract ArrayList<Joueur> getParticipationJoueur(Joueur joueur);
public static class pseudoExistantException extends Exception {
public pseudoExistantException() {
}
}
public static class pseudoInexistantException extends Exception {
public pseudoInexistantException() {
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package InterfaceGraphique;
import Controleur.Controleur;
import Controleur.CtrlInscription;
import bataillenavale.ConcreteFabriqueJoueur;
import bataillenavale.FabriqueJoueur;
import bataillenavale.Joueur;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* JPanel page inscription
* @author gounonj
*/
public class PageInscription extends javax.swing.JPanel {
public PageInscription() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
annuler = new javax.swing.JButton();
inscription = new javax.swing.JButton();
pseudo = new javax.swing.JTextField();
jSeparator1 = new javax.swing.JSeparator();
jLabel1 = new javax.swing.JLabel();
prenom = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
nom = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
email = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
ville = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
nRue = new javax.swing.JTextField();
dateN = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
jInternalFrame1 = new javax.swing.JInternalFrame();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
setPreferredSize(new java.awt.Dimension(800, 600));
annuler.setText("Annuler");
annuler.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
annulerActionPerformed(evt);
}
});
inscription.setText("Inscription");
inscription.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
inscriptionActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
jLabel1.setText("Pseudonyme");
jLabel4.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
jLabel4.setText("Prénom");
jLabel5.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
jLabel5.setText("Nom");
jLabel6.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
jLabel6.setText("E-Mail");
jLabel7.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
jLabel7.setText("Numero de rue");
jLabel8.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
jLabel8.setText("Date de naissance");
jLabel9.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
jLabel9.setText("Ville");
jInternalFrame1.setClosable(true);
jInternalFrame1.setMaximumSize(new java.awt.Dimension(200, 100));
jInternalFrame1.setMinimumSize(new java.awt.Dimension(200, 100));
jInternalFrame1.setPreferredSize(new java.awt.Dimension(200, 100));
try {
jInternalFrame1.setSelected(true);
} catch (java.beans.PropertyVetoException e1) {
e1.printStackTrace();
}
jInternalFrame1.setVisible(false);
jInternalFrame1.getContentPane().setLayout(null);
jLabel2.setText("Pseudo déjà existant.");
jInternalFrame1.getContentPane().add(jLabel2);
jLabel2.setBounds(20, 20, 160, 20);
jLabel3.setFont(new java.awt.Font("DejaVu Sans", 1, 36)); // NOI18N
jLabel3.setText("Inscription");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(145, 145, 145)
.addComponent(jLabel1)
.addGap(114, 114, 114)
.addComponent(pseudo, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(145, 145, 145)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jLabel8))
.addGap(55, 55, 55)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(prenom, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(dateN, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(nom, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(layout.createSequentialGroup()
.addGap(145, 145, 145)
.addComponent(jLabel7)
.addGap(100, 100, 100)
.addComponent(nRue, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(145, 145, 145)
.addComponent(jLabel9)
.addGap(174, 174, 174)
.addComponent(ville, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(580, 580, 580)
.addComponent(inscription)
.addGap(9, 9, 9)
.addComponent(annuler))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 1217, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(61, 61, 61)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(75, 75, 75)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(jLabel1))
.addComponent(pseudo, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(jLabel4)
.addGap(24, 24, 24)
.addComponent(jLabel5)
.addGap(21, 21, 21)
.addComponent(jLabel6)
.addGap(21, 21, 21)
.addComponent(jLabel8))
.addComponent(prenom, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(117, 117, 117)
.addComponent(dateN, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(79, 79, 79)
.addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(nom, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(jLabel7))
.addComponent(nRue, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(jLabel9))
.addComponent(ville, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(69, 69, 69)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(inscription)
.addComponent(annuler)))
);
}// </editor-fold>//GEN-END:initComponents
/**
* Recupere l'action sur le bouton annuler et envoie l'information au controleur
* @param evt
*/
private void annulerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_annulerActionPerformed
Controleur.getInstance().getCtrlInscription().annuler();
}//GEN-LAST:event_annulerActionPerformed
/**
* Recupere l'action sur le bouton inscription et envoie l'information au controleur
* @param evt
*/
private void inscriptionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inscriptionActionPerformed
Controleur.getInstance().getCtrlInscription().inscription(this);
}//GEN-LAST:event_inscriptionActionPerformed
public JTextField getPseudo(){
return this.pseudo;
}
public JTextField getPrenom(){
return this.prenom;
}
public JTextField getNom(){
return this.nom;
}
public JTextField getdateN(){
return this.dateN;
}
public JTextField getEmail(){
return this.email;
}
public JTextField getVille(){
return this.ville;
}
public JTextField getNRue(){
return this.nRue;
}
public JInternalFrame getJInternalFrame1(){
return this.jInternalFrame1;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton annuler;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.JTextField dateN;
private javax.swing.JTextField email;
private javax.swing.JButton inscription;
private javax.swing.JInternalFrame jInternalFrame1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextField nRue;
private javax.swing.JTextField nom;
private javax.swing.JTextField prenom;
private javax.swing.JTextField pseudo;
private javax.swing.JTextField ville;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bataillenavale;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author pierre
*/
public class ConcreteFabriqueEtat implements FabriqueEtat {
private static ConcreteFabriqueEtat instance = null;
/**
* Constructeur
*/
private ConcreteFabriqueEtat() {
super();
}
/**
* getInstance
* @return
*/
public static ConcreteFabriqueEtat getInstance() {
if (ConcreteFabriqueEtat.instance == null) {
ConcreteFabriqueEtat.instance = new ConcreteFabriqueEtat();
}
return ConcreteFabriqueEtat.instance;
}
/**
*
* @param partie
* @param joueur
* @return
* @throws bataillenavale.FabriqueEtat.ExceptionPartiePerdue
*/
public LinkedList<Etat> getEtatEncours(AbstractPartie partie, Joueur joueur) throws ExceptionPartiePerdue{
//TODO
Etat etatBateau;
int vieTotale = 0;
LinkedList<Etat> listeEtat = new LinkedList<Etat>();
LinkedList<AbstractBateau> listeBateau = ConcreteFabriqueBateau.getInstance().getBateau(partie.getIdPartie(), joueur);
for(AbstractBateau b : listeBateau){
etatBateau = ConcreteFabriqueEtat.getInstance().getEtatBateau(partie,b);
listeEtat.add(etatBateau);
vieTotale = vieTotale + etatBateau.getVie();
}
if(vieTotale == 0){
throw new ExceptionPartiePerdue();
}
return listeEtat;
}
/**
*
* @param partie
* @param bateau
* @return
*/
public Etat getEtatBateau(AbstractPartie partie, AbstractBateau bateau) {
try {
int idLastAction = 0;
PreparedStatement stt = BDManager.getInstance().prepareStatement("SELECT e.x, e.y, e.vie, e.direction, e.taille FROM Etat e CROSS JOIN Action a WHERE e.idAction = a.idAction AND e.numAction = a.numAction AND e.idBateau = ? ORDER BY a.numTour DESC, a.numAction DESC");
stt.setInt(1, bateau.getIdBateau());
ResultSet resultat = stt.executeQuery();
if(resultat.first()){
int x = resultat.getInt(1);
int y = resultat.getInt(2);
int vie =resultat.getInt(3);
String direction = resultat.getString(4);
int taille = resultat.getInt(5);
System.out.println("Etat pour bateau : " + bateau.getIdBateau() + "x : " + x + " y : " + y + " Direction : " + Direction.valueOf(direction)+" vie= "+ vie);
bateau.setDirection(Direction.valueOf(direction));
bateau.setCoordX(x);
bateau.setCoordY(y);
bateau.setVie(vie);
bateau.setTaille(taille);
stt.close();
resultat.close();
return new Etat(bateau,x,y,vie,Direction.valueOf(direction),taille);
}
stt.close();
resultat.close();
} catch (SQLException ex) {
Logger.getLogger(ConcreteFabriqueEtat.class.getName()).log(Level.SEVERE, "getEtatBateau failed", ex);
}
return null;
}
/**
* Permet de remplir les etats de la PartieEnReplay avec les états initiaux de la BD
* @param partie
*/
public void getEtatInitiaux(PartieEnReplay partie){
try {
Joueur j1 = partie.getJoueur1();
Joueur j2 = partie.getJoueur2();
PreparedStatement stt = BDManager.getInstance().prepareStatement("SELECT numTour, pseudo FROM Tour WHERE idPartie=? ORDER BY NumTour");
stt.setInt(1, partie.getIdPartie());
ResultSet resultat = stt.executeQuery();
resultat.next();
j1.setPseudo(resultat.getString(2));
resultat.next();
j2.setPseudo(resultat.getString(2));
/*<AbstractBateau> listeBateau1 = ConcreteFabriqueBateau.getInstance().getBateau(partie.getIdPartie(), j1);
LinkedList<AbstractBateau> listeBateau2 = ConcreteFabriqueBateau.getInstance().getBateau(partie.getIdPartie(), j2);*/
partie.setEtatJoueur1(getEtatInitial(0, partie.getIdPartie()));
partie.setEtatJoueur2(getEtatInitial(1, partie.getIdPartie()));
stt.close();
resultat.close();
} catch (SQLException ex) {
Logger.getLogger(ConcreteFabriqueEtat.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Permet d'obtenir les état initiaux des bateaux pour le joueur qui a joué le tour (le numéro de tour doit être 0 ou 1)
*/
private LinkedList<Etat> getEtatInitial(int tour, int idPartie){
LinkedList<Etat> listeEtat = new LinkedList<Etat>();
try {
PreparedStatement stt = BDManager.getInstance().prepareStatement("SELECT e.idBateau, x,y,taille,direction,vie FROM Action a CROSS JOIN Etat e WHERE idPartie=? AND numTour=? AND a.idAction = e.idAction ORDER BY e.numAction");
stt.setInt(1, idPartie);
stt.setInt(2, tour);
ResultSet resultat = stt.executeQuery();
//on va épuiser les résultats
AbstractBateau bateau;
Etat etat;
int idBateau;
int taille;
int x;
int y;
int vie;
Direction direction;
while (resultat.next()) {
idBateau = resultat.getInt(1);
x = resultat.getInt(2);
y = resultat.getInt(3);
taille = resultat.getInt(4);
direction = Direction.valueOf(resultat.getString(5));
vie = resultat.getInt(6);
if (taille == 3) {
bateau = new BateauDestroyer(idBateau, x, y, direction);
bateau.setVie(vie);
} else {
bateau = new BateauEscorteur(idBateau, x, y, direction);
}
etat = new Etat(bateau, x, y, y, direction, taille);
etat.setVie(vie);
listeEtat.add(etat);
}
stt.close();
resultat.close();
return listeEtat;
} catch (SQLException ex) {
Logger.getLogger(ConcreteFabriqueEtat.class.getName()).log(Level.SEVERE, null, ex);
}
return listeEtat;
}
/**
* Permet d'avoir les état crées lors d'un tour. Attention ces états peuvent appartenir à des bateaux des deux camps
* @param numTour
* @return
*/
public LinkedList<Etat> getEtatCrees(int idPartie, int tour){
LinkedList<Etat> listeEtat = new LinkedList<Etat>();
try {
PreparedStatement stt = BDManager.getInstance().prepareStatement("SELECT e.idBateau, x,y,taille,direction,vie FROM Action a CROSS JOIN Etat e WHERE idPartie=? AND numTour=? AND a.idAction = e.idAction ORDER BY e.numAction");
stt.setInt(1, idPartie);
stt.setInt(2, tour);
ResultSet resultat = stt.executeQuery();
//on va épuiser les résultats
AbstractBateau bateau;
Etat etat;
int idBateau;
int taille;
int x;
int y;
int vie;
Direction direction;
while (resultat.next()) {
idBateau = resultat.getInt(1);
x = resultat.getInt(2);
y = resultat.getInt(3);
taille = resultat.getInt(4);
direction = Direction.valueOf(resultat.getString(5));
vie = resultat.getInt(6);
if (taille == 3) {
bateau = new BateauDestroyer(idBateau, x, y, direction);
bateau.setVie(vie);
} else {
bateau = new BateauEscorteur(idBateau, x, y, direction);
}
etat = new Etat(bateau, x, y, y, direction, taille);
etat.setVie(vie);
listeEtat.add(etat);
}
return listeEtat;
} catch (SQLException ex) {
Logger.getLogger(ConcreteFabriqueEtat.class.getName()).log(Level.SEVERE, null, ex);
}
return listeEtat;
}
} | 4cda67eaa4aa379ba179b35ebd0706caeb818c76 | [
"Java",
"Text",
"SQL"
] | 21 | Java | ngnnpgn/battleship | 65046fd9c6f963de286ff6c5d612df7a0168b492 | 55d5393151698bf26e5d95d081ec8ec77a3f4618 |
refs/heads/master | <file_sep>import fetch from 'isomorphic-fetch';
import { HOST_URL } from './';
import { playerPeers } from '../reducers';
const url = (playerId, numPeers) => `/api/players/${playerId}/peers${numPeers ? `?limit=${numPeers}` : ''}`;
const REQUEST = 'yasp/playerPeers/REQUEST';
const OK = 'yasp/playerPeers/OK';
const ERROR = 'yasp/playerPeers/ERROR';
const SORT = 'yasp/playerPeers/SORT';
export const playerPeersActions = {
REQUEST,
OK,
ERROR,
SORT,
};
export const setPlayerPeersSort = (sortField, sortState, sortFn, id) => ({
type: SORT,
sortField,
sortState,
sortFn,
id,
});
export const getPlayerPeersRequest = (id) => ({ type: REQUEST, id });
export const getPlayerPeersOk = (payload, id) => ({
type: OK,
payload,
id,
});
export const getPlayerPeersError = (payload, id) => ({
type: ERROR,
payload,
id,
});
export const getPlayerPeers = (playerId, numPeers, host = HOST_URL) => (dispatch, getState) => {
if (playerPeers.isLoaded(getState(), playerId)) {
dispatch(getPlayerPeersOk(playerPeers.getPeerList(getState(), playerId), playerId));
} else {
dispatch(getPlayerPeersRequest(playerId));
}
return fetch(`${host}${url(playerId, numPeers)}`, { credentials: 'include' })
.then(response => response.json())
.then(json => dispatch(getPlayerPeersOk(json, playerId)))
.catch(error => dispatch(getPlayerPeersError(error, playerId)));
};
<file_sep>import React from 'react';
// import YaspBadge from './YaspBadge';
import PlayerPicture from './PlayerPicture';
import Error from '../Error';
import Spinner from '../Spinner';
import { connect } from 'react-redux';
import { player } from '../../reducers';
import styles from './PlayerHeader.css';
const PlayerName = ({ playerName, registered, loading, error, playerId }) => {
const getPlayerName = () => {
if (error) return <Error />;
if (loading) return <Spinner />;
return (
<div className={styles.nameContainer}>
<div className={styles.pictureContainer}>
<PlayerPicture registered={registered} playerId={playerId} />
</div>
<div className={styles.playerName}>{playerName}</div>
</div>
);
};
return <div>{getPlayerName()}</div>;
};
export { PlayerName };
// metadata.getUserId(state)
// TODO - why is the player picture not showing up at all? that's whack
const mapStateToProps = (state, ownProps) => ({
loading: player.getLoading(state, ownProps.playerId),
error: player.getError(state, ownProps.playerId),
playerName: player.getPlayerName(state, ownProps.playerId),
registered: player.getLastLogin(state, ownProps.playerId),
playerId: ownProps.playerId,
});
export default connect(mapStateToProps)(PlayerName);
<file_sep>import React from 'react';
import { createTable } from '../Table';
import PlayerHeader from './PlayerHeader';
import Error from '../Error';
import {
getPlayer,
getPlayerMatches,
setPlayerMatchesSort,
getPlayerHeroes,
setPlayerHeroesSort,
getPlayerWinLoss,
} from '../../actions';
import { connect } from 'react-redux';
import styles from './Player.css';
import {
playerMatchesColumns,
playerHeroesColumns,
playerHeroesOverviewColumns,
} from '../Table/columnDefinitions';
import {
sortPlayerMatches,
transformPlayerMatchesById,
sortPlayerHeroes,
transformPlayerHeroes,
} from '../../selectors';
import { PeersPage } from './Pages';
import { Text } from '../Text';
import { Card } from 'material-ui/Card';
import { playerMatches, REDUCER_KEY } from '../../reducers';
const playerHeroes = (state) => state[REDUCER_KEY].gotPlayer.heroes;
const PlayerMatchesTable = createTable(
playerMatches.getPlayerMatchesById,
(state, sortState, playerId) => (sortState ? sortPlayerMatches(playerId)(state) : transformPlayerMatchesById(playerId)(state)),
setPlayerMatchesSort
);
const PlayerHeroesTable = createTable(
playerHeroes,
(state, sortState) => (sortState ? sortPlayerHeroes(state) : transformPlayerHeroes(state)),
setPlayerHeroesSort
);
const getOverviewTab = playerId => (
<div className={styles.overviewContainer}>
<div className={styles.overviewMatches}>
<Text className={styles.tableHeading}>RECENT MATCHES</Text>
<Card className={styles.card}>
<PlayerMatchesTable columns={playerMatchesColumns} id={playerId} />
</Card>
</div>
<div className={styles.overviewHeroes}>
<div className={styles.heroesContainer}>
<Text className={styles.tableHeading}>HERO STATS</Text>
<Card className={styles.card}>
<PlayerHeroesTable columns={playerHeroesOverviewColumns} id={playerId} numRows={20} />
</Card>
</div>
</div>
</div>
);
const getPlayerSubroute = (info, playerId) => {
switch (info) {
case 'overview':
return getOverviewTab(playerId);
case 'matches':
return <PlayerMatchesTable columns={playerMatchesColumns} id={playerId} />;
case 'heroes':
return <PlayerHeroesTable columns={playerHeroesColumns} id={playerId} />;
case 'peers':
return <PeersPage playerId={playerId} />;
default:
return getOverviewTab(playerId);
}
};
const Player = ({ playerId, info }) => {
if (!playerId) {
return <Error />;
}
return (
<div>
<div className={styles.header}>
<PlayerHeader playerId={playerId} />
</div>
{getPlayerSubroute(info, playerId)}
</div>
);
};
const mapStateToProps = (state, { params }) => ({ playerId: params.account_id, info: params.info });
const mapDispatchToProps = (dispatch) => ({
getPlayer: (playerId) => dispatch(getPlayer(playerId)),
getPlayerMatches: (playerId, numMatches) => dispatch(getPlayerMatches(playerId, numMatches)),
getPlayerHeroes: (playerId) => dispatch(getPlayerHeroes(playerId)),
getPlayerWinLoss: (playerId) => dispatch(getPlayerWinLoss(playerId)),
});
const getData = props => {
props.getPlayer(props.playerId);
props.getPlayerMatches(props.playerId, 20);
props.getPlayerHeroes(props.playerId);
props.getPlayerWinLoss(props.playerId);
};
class RequestLayer extends React.Component {
componentDidMount() {
getData(this.props);
}
componentWillUpdate(nextProps) {
if (this.props.playerId !== nextProps.playerId) {
getData(nextProps);
}
}
render() {
return <Player {...this.props} />;
}
}
export default connect(mapStateToProps, mapDispatchToProps)(RequestLayer);
<file_sep>import React from 'react';
import PiePercent from '../../PiePercent';
import styles from './PercentContainer.css';
const getPercentWin = (wins, games) => (games ? Math.ceil(1000 * (wins / games)) / 10 : 0);
export default ({ wins, games }) => (
<div className={styles.percentContainer}>
<span className={styles.textContainer}>{getPercentWin(wins, games).toFixed(1)}</span>
<span>
<PiePercent percent={getPercentWin(wins, games)} />
</span>
</div>
);
<file_sep>import React from 'react';
import styles from './WinLoss.css';
const getColor = result => {
if (result.toLowerCase() === 'w') return styles.win;
if (result.toLowerCase() === 'l') return styles.loss;
return styles.notScored;
};
export default ({ result }) => (
<div className={getColor(result)}>
{result}
</div>
);
| e62b1396e1a5703d2281ed0c26803cdcc1720dee | [
"JavaScript"
] | 5 | JavaScript | pcollinsmusic/ui | aee8982b5ac8332dc3c028161a10d0f36832f01e | 0fb5e6e69064e127cd42d17ebe72d4353adf76f4 |
refs/heads/master | <file_sep>import discord
client = discord.Client()
f = open("tokenfile.txt", 'r')
token = f.read()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message: discord.Message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
if message.content.startswith('$react'):
await message.add_reaction("😎")
if message.content.startswith('$echo'):
await message.channel.send(message.content.split(' ', 1)[1])
client.run(token)<file_sep># Setup
1) Bot registration
Go to [Discord's Developer page](https://discordapp.com/developers) and create a new application, and give it the name that you want your bot to have. Once that's created, go to the "Bot" tab and make sure that a bot is created as well. Take note of the "Token" field on the page, and the long string of letters and numbers that you can reveal. You'll need this later.
2) Add bot to your server
On the "OAuth2" tab on your bot page, at the bottom of the page, there should be an array of checkmarks. Check the "bot" option. When you do that, another separate array of checkmarks will appear below the first one. Check the "Administrator" option. Go back up to the first checkboxes, and click the "Copy" button next to the URL. Paste that into your address bar, login to your Discord account, and choose a Discord server that you want to add your bot too. WARNING: by giving your bot the Administrator permission, it has the ability to delete your server. I highly recommend adding your bot to a test server before a more established server, in case there's a bug with catastrophic consequences.
3) Install Discord.py
In your terminal (Terminal on MacOS and Linux, Command Prompt or cmd on Windows) enter the command `python3 -m pip install -U discord.py`. If this command doesn't function, you can also try `py -3 -m pip install -U discord.py`. This should show a message about installing the discord.py library.
4) Create a tokenfile
The Bot token that I mentioned earlier is like a password for your bot. If someone has it, they can just login as your bot and make it do things. This is especially bad, given that we've given the bot the Administrator permission. You should take steps to make sure no one can get it, including that you don't accidentally put the token on GitHub (if you're using it). This project loads the token from a file called "tokenfile.txt", but for obvious reasons I've removed it from this repository. In order for this example program to function, you need to create a file called "tokenfile.txt" and paste your Bot's Token into it, and save it.
5) Run the file
With all of this setup, it *should* just work. Try running the script with the command `python3 main.py` or `py main.py`. To see which commands the bot has by default, just take a look at the source code! ;) | 3a1468af4c3ffb6c6ea458d13f370cc9bb720abb | [
"Markdown",
"Python"
] | 2 | Python | jmalexan/DiscordBotExample | b6b66b592fbd7c701b6642206a36276f6084d942 | ee97dea5d460ebe8bb4ccfe2a1c0a9468f02d001 |
refs/heads/main | <file_sep>import { MnistData } from './data.js';
let model;
let data;
let isModelTrained = false;
let ctx;
const canvasSize = 200;
// Last position of the mouse
let lastPosition = { x: 0, y: 0 };
let drawing = false;
// Image size is [28, 28]
const IMAGE_SIZE = 28;
// 1 because it is a grayscale image
const IMAGE_CHANNELS = 1;
// tfjs-vis visor surface
const dataSurface = { name: 'Sample', tab: 'Data' };
function defineModel() {
model = tf.sequential();
// The output of this layer is of shape [24, 24, 8]
model.add(tf.layers.conv2d({
inputShape: [IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS],
kernelSize: [5, 5],
filters: 8,
strides: 1,
activation: 'relu',
padding: 'valid',
}));
// The output of this layer is of shape [12, 12, 8]
model.add(tf.layers.maxPooling2d({
poolSize: [2, 2],
strides: 2,
}));
// The output of this layer is of shape [8, 8, 16]
model.add(tf.layers.conv2d({
kernelSize: [5, 5],
filters: 16,
strides: 1,
activation: 'relu',
padding: 'valid',
}));
// The output of this layer is of shape [4, 4, 16]
model.add(tf.layers.maxPooling2d({
poolSize: [2, 2],
strides: 2,
}));
model.add(tf.layers.dropout({ rate: 0.3 }));
// The output of this layer is of shape [256]
model.add(tf.layers.flatten());
// The last layer has 10 outputs; one for each class.
model.add(tf.layers.dense({
units: 10,
activation: 'softmax',
}));
model.compile({
optimizer: tf.train.adam(),
loss: 'categoricalCrossentropy',
metrics: ['accuracy'],
});
model.summary();
}
async function train() {
// Make sure the tfjs-vis visor is open before starting the training.
tfvis.visor().open();
const BATCH_SIZE = 512;
const TRAIN_DATA_SIZE = 5500;
const TEST_DATA_SIZE = 1000;
// Get a batch of training data
const [xTrain, yTrain] = tf.tidy(() => {
const d = data.nextTrainBatch(TRAIN_DATA_SIZE);
return [
d.xs.reshape([TRAIN_DATA_SIZE, IMAGE_SIZE, IMAGE_SIZE, 1]),
d.labels,
];
});
// Get a batch of test data
const [xTest, yTest] = tf.tidy(() => {
const d = data.nextTestBatch(TEST_DATA_SIZE);
return [
d.xs.reshape([TEST_DATA_SIZE, IMAGE_SIZE, IMAGE_SIZE, 1]),
d.labels,
];
});
await model.fit(xTrain, yTrain, {
batchSize: BATCH_SIZE,
epochs: 30,
validationData: [xTest, yTest],
shuffle: true,
callbacks: tfvis.show.fitCallbacks(
{ name: 'Loss and Accuracy', tab: 'Training' },
['loss', 'val_loss', 'acc', 'val_acc'],
),
});
isModelTrained = true;
}
function prepareCanvas() {
const canvas = document.getElementById('draw-canvas');
canvas.width = canvasSize;
canvas.height = canvasSize;
ctx = canvas.getContext('2d');
// Set the canvas style
ctx.strokeStyle = 'white';
ctx.fillStyle = 'white';
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.lineWidth = 15;
// Add the canvas event listeners for mouse events
canvas.addEventListener('mousedown', (e) => {
drawing = true;
lastPosition = { x: e.offsetX, y: e.offsetY };
});
canvas.addEventListener('mouseout', () => {
drawing = false;
});
canvas.addEventListener('mousemove', (e) => {
if (!drawing) {
return;
}
ctx.beginPath();
ctx.moveTo(lastPosition.x, lastPosition.y);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
lastPosition = { x: e.offsetX, y: e.offsetY };
});
canvas.addEventListener('mouseup', () => {
drawing = false;
if (!isModelTrained) {
return;
}
// Convert the canvas to a tensor
// and modify it.
const toPredict = tf.browser.fromPixels(canvas)
.resizeBilinear([IMAGE_SIZE, IMAGE_SIZE])
.mean(2)
.expandDims()
.expandDims(3)
.toFloat()
.div(255.0);
const prediction = model.predict(toPredict).dataSync();
// Use argMax to get the label.
const p = document
.getElementById('predict-output');
p.innerHTML = `O numero desenhado é : ${tf.argMax(prediction).dataSync()}`;
});
}
function createButton(innerText, selector, id, listener, disabled = false) {
const btn = document.createElement('BUTTON');
btn.innerText = innerText;
btn.id = id;
btn.disabled = disabled;
// Listener that waits for clicks.
// Once a click is done, it will execute the function.
btn.addEventListener('click', listener);
document.querySelector(selector).appendChild(btn);
}
// This function draws a sample of the data
// with tfjs-vis
async function drawData() {
// Add surface to visor
const surface = tfvis.visor().surface(dataSurface);
const results = [];
const numSamples = 26;
let digit;
// Get a sample of N images
const sample = data.nextTestBatch(numSamples);
// Create a canvas and add the images
for (let i = 0; i < numSamples; i += 1) {
// Cleanup all the allocated tensors
digit = tf.tidy(() => sample.xs
.slice([i, 0], [1, sample.xs.shape[1]])
.reshape([IMAGE_SIZE, IMAGE_SIZE, 1]));
const visCanvas = document.createElement('canvas');
visCanvas.width = IMAGE_SIZE;
visCanvas.height = IMAGE_SIZE;
visCanvas.style = 'margin: 5px;';
results.push(tf.browser.toPixels(digit, visCanvas));
surface.drawArea.appendChild(visCanvas);
}
await Promise.all(results);
digit.dispose();
}
function enableButton(selector) {
document.getElementById(selector).disabled = false;
}
function init() {
prepareCanvas();
createButton('Load data', '#pipeline', 'load-btn',
async () => {
data = new MnistData();
await data.load();
drawData();
enableButton('train-btn');
});
createButton('Train', '#pipeline', 'train-btn',
async () => {
defineModel();
train();
}, true);
createButton('Clear', '#pipeline', 'clear-btn',
() => {
ctx.clearRect(0, 0, canvasSize, canvasSize);
});
}
init(); | bebdbbb17e7e6b046dc3ad34c895168915560938 | [
"JavaScript"
] | 1 | JavaScript | rhaymisonbetini/CNN-Numbers-Javascript | 7f97a66f2bf1bec604f218a9d5d34a4ba5e7908b | 44c9240c62cca0965a528a682c416f8e1978065d |
refs/heads/master | <file_sep>import { ActionKey } from './actions/action-keys.enum';
import { MainBoard } from './main-board.class';
import { Player } from './player.class';
import { ResourceType } from './resource-type.enum';
describe('Player Class', () => {
it('should create', () => {
const mainBoard = new MainBoard(4);
const player = new Player(mainBoard, [], [], () => null);
expect(player).toBeDefined();
expect(player instanceof Player).toBeTruthy();
});
it('return the number of used farmers for the turn', () => {
const mainBoard = new MainBoard(4);
const player = new Player(mainBoard, [], [], () => null);
expect(player.usedFarmers).toBe(0);
player.takeAction(mainBoard.findAvailableActionByKey(ActionKey.CLAY_PIT));
expect(player.usedFarmers).toBe(1);
player.takeAction(mainBoard.findAvailableActionByKey(ActionKey.FOREST));
expect(player.usedFarmers).toBe(2);
});
it('should take the action and apply its effect on the player', () => {
const mainBoard = new MainBoard(4);
const player = new Player(mainBoard, [], [], () => null);
mainBoard.accumulate();
expect(player.takeAction(mainBoard.findAvailableActionByKey(ActionKey.CLAY_PIT))).toBe(true);
expect(player.resources).toEqual({
[ResourceType.FOOD]: 0,
[ResourceType.SHEEP]: 0,
[ResourceType.CATTLE]: 0,
[ResourceType.PIG]: 0,
[ResourceType.REED]: 0,
[ResourceType.CLAY]: 1,
[ResourceType.WOOD]: 0,
[ResourceType.STONE]: 0,
[ResourceType.CEREAL]: 0,
[ResourceType.VEGETABLE]: 0,
});
});
it('should cook one resource', () => {
// TODO
});
it('should discard the resources from the player\'s storage', () => {
const mainBoard = new MainBoard(4);
const player = new Player(mainBoard, [], [], () => null);
mainBoard.accumulate();
mainBoard.accumulate();
mainBoard.accumulate();
expect(player.takeAction(mainBoard.findAvailableActionByKey(ActionKey.CLAY_PIT))).toBe(true);
player.discardResources([{ type: ResourceType.CLAY, amount: 2 }]);
expect(player.resources).toEqual({
[ResourceType.FOOD]: 0,
[ResourceType.SHEEP]: 0,
[ResourceType.CATTLE]: 0,
[ResourceType.PIG]: 0,
[ResourceType.REED]: 0,
[ResourceType.CLAY]: 1,
[ResourceType.WOOD]: 0,
[ResourceType.STONE]: 0,
[ResourceType.CEREAL]: 0,
[ResourceType.VEGETABLE]: 0,
});
});
});
<file_sep>import { ResourceType } from '../../resource-type.enum';
import { AccumulationAction } from '../accumulation-action.class';
import { ActionKey } from '../action-keys.enum';
export class FishingAction extends AccumulationAction {
public readonly key = ActionKey.FISHING;
public readonly type = ResourceType.FOOD;
}
<file_sep>import { Player } from '../../player.class';
import { ResourceType } from '../../resource-type.enum';
import { ActionKey } from '../action-keys.enum';
import { IActionParams } from '../action-params.interface';
import { Action } from '../action.class';
export class FarmExpansionAction extends Action {
public readonly key = ActionKey.FARM_EXPANSION;
private readonly roomReedCost = 2;
private readonly roomResourceCost = 5;
private readonly stableWoodCost = 2;
protected applyEffects(player: Player, params: IActionParams): boolean {
if (params.rooms) {
if (!this.buildRooms(player, params.rooms)) {
return false;
}
}
if (params.stablePositions) {
if (!this.buildStables(player, params.stablePositions)) {
return false;
}
}
return false;
}
private buildRooms(
player: Player,
rooms: { type: ResourceType.WOOD | ResourceType.CLAY | ResourceType.STONE, positions: number[] },
): boolean {
const resourceCost = [
{ type: ResourceType.REED, amount: this.roomReedCost * rooms.positions.length },
{ type: rooms.type, amount: this.roomResourceCost * rooms.positions.length },
];
if (!player.hasResources(resourceCost)) {
return false;
}
if (!player.buildRooms(rooms.type, rooms.positions)) {
return false;
}
player.discardResources(resourceCost);
return true;
}
private buildStables(player: Player, stablePositions: number[]): boolean {
const resourceCost = [{ type: ResourceType.WOOD, amount: this.stableWoodCost * stablePositions.length }];
if (!player.hasResources(resourceCost)) {
return false;
}
if (!player.buildStables(stablePositions)) {
return false;
}
player.discardResources(resourceCost);
return true;
}
}
<file_sep>export class PlayerBoard {
}
<file_sep>import { ResourceType } from '../../resource-type.enum';
import { AccumulationAction } from '../accumulation-action.class';
import { ActionKey } from '../action-keys.enum';
export class SheepMarketAction extends AccumulationAction {
public readonly key = ActionKey.SHEEP_MARKET;
public readonly type = ResourceType.SHEEP;
}
<file_sep>import { ActionKey } from './actions/action-keys.enum';
import { Game } from './game.class';
const game = new Game(1);
// Turn 1
console.log(game.toString());
console.log(game.activePlayer.toString());
console.log('TAKE ACTION', ActionKey.CLAY_PIT);
game.activePlayer.takeAction(game.mainBoard.findAvailableActionByKey(ActionKey.CLAY_PIT));
console.log(game.toString());
console.log(game.activePlayer.toString());
console.log('TAKE ACTION', ActionKey.FOREST);
game.activePlayer.takeAction(game.mainBoard.findAvailableActionByKey(ActionKey.FOREST));
// Turn 2
console.log(game.toString());
console.log(game.activePlayer.toString());
console.log('TAKE ACTION', ActionKey.REED_BANK);
game.activePlayer.takeAction(game.mainBoard.findAvailableActionByKey(ActionKey.REED_BANK));
console.log(game.toString());
console.log(game.activePlayer.toString());
console.log('TAKE ACTION', ActionKey.CLAY_PIT);
game.activePlayer.takeAction(game.mainBoard.findAvailableActionByKey(ActionKey.CLAY_PIT));
// Turn 3
console.log(game.toString());
console.log(game.activePlayer.toString());
console.log('TAKE ACTION', ActionKey.FOREST);
game.activePlayer.takeAction(game.mainBoard.findAvailableActionByKey(ActionKey.FOREST));
console.log(game.toString());
console.log(game.activePlayer.toString());
console.log('TAKE ACTION', ActionKey.CLAY_PIT);
game.activePlayer.takeAction(game.mainBoard.findAvailableActionByKey(ActionKey.CLAY_PIT));
// Turn 4
console.log(game.toString());
console.log(game.activePlayer.toString());
console.log('TAKE ACTION', ActionKey.FOREST);
game.activePlayer.takeAction(game.mainBoard.findAvailableActionByKey(ActionKey.FOREST));
console.log(game.toString());
console.log(game.activePlayer.toString());
console.log('TAKE ACTION', ActionKey.SHEEP_MARKET);
game.activePlayer.takeAction(game.mainBoard.findAvailableActionByKey(ActionKey.SHEEP_MARKET));
// Turn 5
console.log(game.toString());
console.log(game.activePlayer.toString());
<file_sep>export class Occupation {}
<file_sep>export class MajorImprovement {}
<file_sep>import { ResourceType } from '../../resource-type.enum';
import { AccumulationAction } from '../accumulation-action.class';
import { ActionKey } from '../action-keys.enum';
export class CattleMarketAction extends AccumulationAction {
public readonly key = ActionKey.CATTLE_MARKET;
public readonly type = ResourceType.CATTLE;
}
<file_sep>import { Player } from '../player.class';
import { ActionKey } from './action-keys.enum';
import { IActionParams } from './action-params.interface';
export abstract class Action {
public abstract readonly key: ActionKey;
private player: Player;
public take(player: Player, params?: IActionParams): boolean {
if (this.occupied) {
return false;
}
const success = this.applyEffects(player, params);
if (success) {
this.player = player;
return true;
}
return false;
}
public get occupied(): boolean {
return !!this.player;
}
public get occupyingPlayer(): Player {
return this.player;
}
// TODO This shouldn't be public! Find another way to return the farmer
public clearPlayer() {
this.player = null;
}
protected abstract applyEffects(player: Player, params?: IActionParams): boolean;
}
<file_sep>import { MainBoard } from './main-board.class';
import { Player } from './player.class';
export class Game {
public readonly mainBoard: MainBoard;
private players: Player[];
private firstPlayer: number;
private activePlayerIndex: number;
private activeTurnIndex: number;
private harvestTurnIndexes = [3, 6, 8, 10, 12, 14];
get activePlayer(): Player {
return this.players[this.activePlayerIndex];
}
public constructor(playerCount: 1 | 2 | 3 | 4) {
this.mainBoard = new MainBoard(playerCount);
this.players = [];
for (let i = 0; i < playerCount; ++i) {
const occupations = []; // TODO build a random list from the deck
const minorImprovements = []; // TODO build a random list from the deck
const onPlayerTakeAction = (player) => this.onPlayerTakeAction(player);
this.players.push(new Player(this.mainBoard, occupations, minorImprovements, onPlayerTakeAction));
}
this.firstPlayer = Math.floor(Math.random() * playerCount);
this.activeTurnIndex = 0;
this.beginTurn();
}
public getPlayer(index: number): Player {
return this.players[index];
}
public toString(): string {
return `
GAME:
Current Turn: ${this.activeTurnIndex + 1}
Current Player: ${this.activePlayerIndex + 1}
`;
}
private onPlayerTakeAction(player: Player) {
this.activateNextPlayer();
}
private activateNextPlayer() {
const nextPlayerIndex = (this.activePlayerIndex + 1) % this.players.length;
const nextPlayer = this.players[nextPlayerIndex];
if (nextPlayer.hasFarmerAvailable) {
this.activePlayerIndex = nextPlayerIndex;
} else {
this.beginReturnFromWork();
}
}
private beginTurn() {
this.activePlayerIndex = this.firstPlayer;
this.mainBoard.addActionForTurn(this.activeTurnIndex);
this.mainBoard.accumulate();
}
private beginReturnFromWork() {
this.mainBoard.returnAllFarmers();
this.activeTurnIndex++;
this.beginTurn();
}
}
<file_sep>export enum ResourceType {
FOOD,
SHEEP,
CATTLE,
PIG,
REED,
CLAY,
WOOD,
STONE,
CEREAL,
VEGETABLE,
}
<file_sep>import { Player } from '../../player.class';
import { ResourceType } from '../../resource-type.enum';
import { ActionKey } from '../action-keys.enum';
import { Action } from '../action.class';
export class GrainSeedsAction extends Action {
public readonly key = ActionKey.GRAIN_SEEDS;
protected applyEffects(player: Player): boolean {
player.obtainResource(ResourceType.CEREAL, 1);
return true;
}
}
<file_sep>import { AccumulationAction } from './actions/accumulation-action.class';
import { ActionKey } from './actions/action-keys.enum';
import { MainBoard } from './main-board.class';
import { Player } from './player.class';
describe('MainBoard Class', () => {
it('should create', () => {
const mainBoard = new MainBoard(4);
expect(mainBoard).toBeDefined();
expect(mainBoard instanceof MainBoard).toBeTruthy();
});
it('should add a new random Action each call', () => {
// Mock the Math.random so the function always add the first action from the list
spyOn(Math, 'random').and.returnValue(0);
const mainBoard = new MainBoard(2);
// Period 1
expect(mainBoard.findAvailableActionByKey(ActionKey.MAJOR_IMPROVEMENT)).toBeFalsy();
mainBoard.addActionForTurn(0);
expect(mainBoard.findAvailableActionByKey(ActionKey.MAJOR_IMPROVEMENT)).toBeDefined('MAJOR_IMPROVEMENT not added');
expect(mainBoard.findAvailableActionByKey(ActionKey.FENCING)).toBeFalsy();
mainBoard.addActionForTurn(1);
expect(mainBoard.findAvailableActionByKey(ActionKey.FENCING)).toBeDefined('FENCING not added');
expect(mainBoard.findAvailableActionByKey(ActionKey.GRAIN_UTILIZATION)).toBeFalsy();
mainBoard.addActionForTurn(2);
expect(mainBoard.findAvailableActionByKey(ActionKey.GRAIN_UTILIZATION)).toBeDefined('GRAIN_UTILIZATION not added');
expect(mainBoard.findAvailableActionByKey(ActionKey.SHEEP_MARKET)).toBeFalsy();
mainBoard.addActionForTurn(3);
expect(mainBoard.findAvailableActionByKey(ActionKey.SHEEP_MARKET)).toBeDefined('SHEEP_MARKET not added');
// Period 2
expect(mainBoard.findAvailableActionByKey(ActionKey.BASIC_WISH_FOR_CHILDREN)).toBeFalsy();
mainBoard.addActionForTurn(4);
expect(mainBoard.findAvailableActionByKey(ActionKey.BASIC_WISH_FOR_CHILDREN))
.toBeDefined('BASIC_WISH_FOR_CHILDREN not added');
expect(mainBoard.findAvailableActionByKey(ActionKey.HOUSE_REDEVELOPMENT)).toBeFalsy();
mainBoard.addActionForTurn(5);
expect(mainBoard.findAvailableActionByKey(ActionKey.HOUSE_REDEVELOPMENT))
.toBeDefined('HOUSE_REDEVELOPMENT not added');
expect(mainBoard.findAvailableActionByKey(ActionKey.WESTERN_QUARRY)).toBeFalsy();
mainBoard.addActionForTurn(6);
expect(mainBoard.findAvailableActionByKey(ActionKey.WESTERN_QUARRY)).toBeDefined('WESTERN_QUARRY not added');
// Period 3
expect(mainBoard.findAvailableActionByKey(ActionKey.VEGETABLE_SEEDS)).toBeFalsy();
mainBoard.addActionForTurn(7);
expect(mainBoard.findAvailableActionByKey(ActionKey.VEGETABLE_SEEDS)).toBeDefined('VEGETABLE_SEEDS not added');
expect(mainBoard.findAvailableActionByKey(ActionKey.PIG_MARKET)).toBeFalsy();
mainBoard.addActionForTurn(8);
expect(mainBoard.findAvailableActionByKey(ActionKey.PIG_MARKET)).toBeDefined('PIG_MARKET not added');
// Period 4
expect(mainBoard.findAvailableActionByKey(ActionKey.CATTLE_MARKET)).toBeFalsy();
mainBoard.addActionForTurn(9);
expect(mainBoard.findAvailableActionByKey(ActionKey.CATTLE_MARKET)).toBeDefined('CATTLE_MARKET not added');
expect(mainBoard.findAvailableActionByKey(ActionKey.EASTERN_QUARRY)).toBeFalsy();
mainBoard.addActionForTurn(10);
expect(mainBoard.findAvailableActionByKey(ActionKey.EASTERN_QUARRY)).toBeDefined('EASTERN_QUARRY not added');
// Period 5
expect(mainBoard.findAvailableActionByKey(ActionKey.URGENT_WISH_FOR_CHILDREN)).toBeFalsy();
mainBoard.addActionForTurn(11);
expect(mainBoard.findAvailableActionByKey(ActionKey.URGENT_WISH_FOR_CHILDREN))
.toBeDefined('URGENT_WISH_FOR_CHILDREN not added');
expect(mainBoard.findAvailableActionByKey(ActionKey.CULTIVATION)).toBeFalsy();
mainBoard.addActionForTurn(12);
expect(mainBoard.findAvailableActionByKey(ActionKey.CULTIVATION)).toBeDefined('CULTIVATION not added');
// Period 6
expect(mainBoard.findAvailableActionByKey(ActionKey.FARM_REDEVELOPMENT)).toBeFalsy();
mainBoard.addActionForTurn(13);
expect(mainBoard.findAvailableActionByKey(ActionKey.FARM_REDEVELOPMENT))
.toBeDefined('FARM_REDEVELOPMENT not added');
});
it('should call accumulate() on all accumulation actions', () => {
const mainBoard = new MainBoard(4);
const action = mainBoard.findAvailableActionByKey(ActionKey.CLAY_PIT) as AccumulationAction;
spyOn(action, 'accumulate');
mainBoard.accumulate();
expect(action.accumulate).toHaveBeenCalledTimes(1);
});
it('should call clearPlayer() on all occupied actions', () => {
const mainBoard = new MainBoard(4);
const player = new Player(mainBoard, [], [], () => null);
const action = mainBoard.findAvailableActionByKey(ActionKey.FOREST);
player.takeAction(action, {});
spyOn(action, 'clearPlayer');
mainBoard.returnAllFarmers();
expect(action.clearPlayer).toHaveBeenCalledTimes(1);
});
it('should return the action if its not occupied', () => {
const mainBoard = new MainBoard(4);
const player = new Player(mainBoard, [], [], () => null);
const action = mainBoard.findAvailableActionByKey(ActionKey.FOREST);
expect(action).toBeDefined();
player.takeAction(action, {});
expect(mainBoard.findAvailableActionByKey(ActionKey.FOREST)).toBeFalsy();
});
it('should return a list of actions taken by the player', () => {
const mainBoard = new MainBoard(4);
const player = new Player(mainBoard, [], [], () => null);
const forestAction = mainBoard.findAvailableActionByKey(ActionKey.FOREST);
const clayPitAction = mainBoard.findAvailableActionByKey(ActionKey.CLAY_PIT);
player.takeAction(forestAction, {});
player.takeAction(clayPitAction, {});
const takenActions = mainBoard.getActionsTakenBy(player);
expect(takenActions.length).toBe(2);
expect(mainBoard.getActionsTakenBy(player)).toEqual([forestAction, clayPitAction]);
});
});
<file_sep>import { Player } from '../../player.class';
import { ResourceType } from '../../resource-type.enum';
import { ActionKey } from '../action-keys.enum';
import { Action } from '../action.class';
export class DayLaborerAction extends Action {
public readonly key = ActionKey.DAY_LABORER;
private readonly foodAmount = 2;
protected applyEffects(player: Player): boolean {
player.obtainResource(ResourceType.FOOD, this.foodAmount);
return true;
}
}
<file_sep>export class MinorImprovement {}
<file_sep>import { ResourceType } from '../../resource-type.enum';
import { AccumulationAction } from '../accumulation-action.class';
import { ActionKey } from '../action-keys.enum';
export class ForestAction extends AccumulationAction {
public readonly key = ActionKey.FOREST;
public readonly type = ResourceType.WOOD;
public accumulate() {
this.quantity += 3;
}
}
<file_sep>import { Player } from '../player.class';
import { ResourceType } from '../resource-type.enum';
import { Action } from './action.class';
export abstract class AccumulationAction extends Action {
public abstract readonly type: ResourceType;
protected quantity = 0;
public accumulate() {
this.quantity++;
}
protected applyEffects(player: Player): boolean {
player.obtainResource(this.type, this.quantity);
this.quantity = 0;
return true;
}
}
<file_sep>import { AccumulationAction } from './actions/accumulation-action.class';
import { ActionKey } from './actions/action-keys.enum';
import { Action } from './actions/action.class';
import { ClayPitAction } from './actions/board/clay-pit-action.class';
import { DayLaborerAction } from './actions/board/day-laborer-action.class';
import { FarmExpansionAction } from './actions/board/farm-expansion-action.class';
import { FarmlandAction } from './actions/board/farmland-action.class';
import { FishingAction } from './actions/board/fishing-action.class';
import { ForestAction } from './actions/board/forest-action.class';
import { GrainSeedsAction } from './actions/board/grain-seeds-action.class';
import { LessonsAction } from './actions/board/lessons-action.class';
import { MeetingPlaceAction } from './actions/board/meeting-place-action.class';
import { ReedBankAction } from './actions/board/reed-bank-action.class';
import { BasicWishForChildrenAction } from './actions/cards/basic-wish-for-children-action.class';
import { CattleMarketAction } from './actions/cards/cattle-market-action.class';
import { CultivationAction } from './actions/cards/cultivation-action.class';
import { EasternQuarryAction } from './actions/cards/eastern-quarry-action.class';
import { FarmRedevelopmentAction } from './actions/cards/farm-redevelopment-action.class';
import { FencingAction } from './actions/cards/fencing-action.class';
import { GrainUtilizationAction } from './actions/cards/grain-utilization-action.class';
import { HouseRedevelopmentAction } from './actions/cards/house-redevelopment-action.class';
import { MajorImprovementAction } from './actions/cards/major-improvement-action.class';
import { PigMarketAction } from './actions/cards/pig-market-action.class';
import { SheepMarketAction } from './actions/cards/sheep-market-action.class';
import { UrgentWishForChildrenAction } from './actions/cards/urgent-wish-for-children-action.class';
import { VegetableSeedsAction } from './actions/cards/vegetable-seeds-action.class';
import { WesternQuarryAction } from './actions/cards/western-quarry-action.class';
import { Player } from './player.class';
export class MainBoard {
private readonly actionPool = {
period1: [
new MajorImprovementAction(),
new FencingAction(),
new GrainUtilizationAction(),
new SheepMarketAction(),
],
period2: [
new BasicWishForChildrenAction(),
new HouseRedevelopmentAction(),
new WesternQuarryAction(),
],
period3: [
new VegetableSeedsAction(),
new PigMarketAction(),
],
period4: [
new CattleMarketAction(),
new EasternQuarryAction(),
],
period5: [
new UrgentWishForChildrenAction(),
new CultivationAction(),
],
period6: [
new FarmRedevelopmentAction(),
],
};
private actions: Action[];
constructor(playerCount: 1 | 2 | 3 | 4) {
this.actions = [
new FarmExpansionAction(),
new MeetingPlaceAction(),
new GrainSeedsAction(),
new FarmlandAction(),
new LessonsAction(),
new DayLaborerAction(),
new ForestAction(),
new ClayPitAction(),
new ReedBankAction(),
new FishingAction(),
];
}
public addActionForTurn(turnIndex: number) {
const nextAction = this.pickRandomActionForTurn(turnIndex);
if (nextAction) {
this.actions.push(nextAction);
}
}
public accumulate() {
this.actions
.filter((action) => action instanceof AccumulationAction)
.forEach((action: AccumulationAction) => action.accumulate());
}
public returnAllFarmers() {
this.actions.filter((action) => action.occupied).forEach((action) => {
action.clearPlayer();
});
}
public findAvailableActionByKey(key: ActionKey): Action {
return this.actions
.filter((action) => !action.occupied)
.find((action) => action.key === key);
}
public getActionsTakenBy(player: Player): Action[] {
return this.actions
.filter((action) => action.occupied)
.filter((action) => action.occupyingPlayer === player);
}
private pickRandomActionForTurn(turnIndex: number): Action | null {
if (turnIndex >= 0 && turnIndex <= 3) {
return pickRandomAction(this.actionPool.period1);
}
if (turnIndex >= 4 && turnIndex <= 6) {
return pickRandomAction(this.actionPool.period2);
}
if (turnIndex >= 7 && turnIndex <= 8) {
return pickRandomAction(this.actionPool.period3);
}
if (turnIndex >= 9 && turnIndex <= 10) {
return pickRandomAction(this.actionPool.period4);
}
if (turnIndex >= 11 && turnIndex <= 12) {
return pickRandomAction(this.actionPool.period5);
}
if (turnIndex === 13) {
return pickRandomAction(this.actionPool.period6);
}
return null;
}
}
function pickRandomAction(actions: Action[]): Action {
const actionIndex = Math.floor(Math.random() * actions.length);
const action = actions[actionIndex];
actions.splice(actionIndex, 1);
return action;
}
<file_sep>import { Player } from '../../player.class';
import { ActionKey } from '../action-keys.enum';
import { Action } from '../action.class';
export class VegetableSeedsAction extends Action {
public readonly key = ActionKey.VEGETABLE_SEEDS;
protected applyEffects(player: Player): boolean {
// TODO
return false;
}
}
<file_sep>import { ResourceType } from '../../resource-type.enum';
import { AccumulationAction } from '../accumulation-action.class';
import { ActionKey } from '../action-keys.enum';
export class ClayPitAction extends AccumulationAction {
public readonly key = ActionKey.CLAY_PIT;
public readonly type = ResourceType.CLAY;
}
<file_sep>import { MajorImprovement } from '../major-improvements/major-improvement.class';
import { MinorImprovement } from '../minor-improvements/minor-improvement.class';
import { Occupation } from '../occupations/occupation.class';
import { ResourceType } from '../resource-type.enum';
export interface IActionParams {
fieldPosition?: number;
rooms?: { type: ResourceType.WOOD | ResourceType.CLAY | ResourceType.STONE, positions: number[] };
stablePositions?: number[];
fencesPositions?: number[];
occupation?: Occupation;
minorImprovement?: MinorImprovement;
majorImprovement?: MajorImprovement;
getFirstPlayerToken?: boolean;
seeds?: Array<ResourceType.CEREAL | ResourceType.VEGETABLE>;
renovateTo?: ResourceType.CLAY | ResourceType.STONE;
}
<file_sep>import { Game } from './game.class';
describe('Game Class', () => {
it('should create', () => {
const game = new Game(1);
expect(game).toBeDefined();
expect(game instanceof Game).toBeTruthy();
});
});
<file_sep>export enum ActionKey {
BASIC_WISH_FOR_CHILDREN = 'basic-wish-for-children',
CATTLE_MARKET = 'cattle-market',
CULTIVATION = 'cultivation',
EASTERN_QUARRY = 'eastern-quarry',
FARM_REDEVELOPMENT = 'farm-redevelopment',
FENCING = 'fencing',
GRAIN_UTILIZATION = 'grain-utilization',
HOUSE_REDEVELOPMENT = 'house-redevelopment',
MAJOR_IMPROVEMENT = 'major-improvement',
PIG_MARKET = 'pig-market',
SHEEP_MARKET = 'sheep-market',
URGENT_WISH_FOR_CHILDREN = 'urgent-wish-for-children',
VEGETABLE_SEEDS = 'vegetable-seeds',
WESTERN_QUARRY = 'western-quarry',
CLAY_PIT = 'clay-pit',
DAY_LABORER = 'day-laborer',
FARM_EXPANSION = 'farm-expansion',
FARMLAND = 'farmland',
FISHING = 'fishing',
FOREST = 'forest',
GRAIN_SEEDS = 'grain-seeds',
LESSONS = 'lessons',
MEETING_PLACE = 'meeting-place',
REED_BANK = 'reed-bank',
}
<file_sep>import { IActionParams } from './actions/action-params.interface';
import { Action } from './actions/action.class';
import { MainBoard } from './main-board.class';
import { MinorImprovement } from './minor-improvements/minor-improvement.class';
import { Occupation } from './occupations/occupation.class';
import { ResourceType } from './resource-type.enum';
export class Player {
private resourceMap = new Map<ResourceType, number>();
private farmerCount = 2;
private mainBoard: MainBoard;
private actionTakenCallback: (Player) => void;
private occupations: Occupation[];
private minorImprovements: MinorImprovement[];
get hasFarmerAvailable(): boolean {
return this.usedFarmers < this.farmerCount;
}
get usedFarmers(): number {
return this.mainBoard.getActionsTakenBy(this).length;
}
get resources(): any {
return {
[ResourceType.FOOD]: this.resourceMap.get(ResourceType.FOOD) || 0,
[ResourceType.SHEEP]: this.resourceMap.get(ResourceType.SHEEP) || 0,
[ResourceType.CATTLE]: this.resourceMap.get(ResourceType.CATTLE) || 0,
[ResourceType.PIG]: this.resourceMap.get(ResourceType.PIG) || 0,
[ResourceType.REED]: this.resourceMap.get(ResourceType.REED) || 0,
[ResourceType.CLAY]: this.resourceMap.get(ResourceType.CLAY) || 0,
[ResourceType.WOOD]: this.resourceMap.get(ResourceType.WOOD) || 0,
[ResourceType.STONE]: this.resourceMap.get(ResourceType.STONE) || 0,
[ResourceType.CEREAL]: this.resourceMap.get(ResourceType.CEREAL) || 0,
[ResourceType.VEGETABLE]: this.resourceMap.get(ResourceType.VEGETABLE) || 0,
};
}
constructor(
mainBoard: MainBoard,
occupations: Occupation[],
minorImprovements: MinorImprovement[],
actionTakenCallback: (Player) => void,
) {
this.mainBoard = mainBoard;
this.occupations = occupations;
this.minorImprovements = minorImprovements;
this.actionTakenCallback = actionTakenCallback;
}
public takeAction(action: Action, params?: IActionParams): boolean {
if (this.usedFarmers >= this.farmerCount) {
return false;
}
const success = action.take(this, params);
if (success) {
this.actionTakenCallback(this);
return true;
}
return false;
}
public cookOneResource(
majorImprovement: any,
resourceType: ResourceType.VEGETABLE | ResourceType.SHEEP | ResourceType.PIG | ResourceType.CATTLE,
) {
// TODO
}
public obtainResource(type: ResourceType, amount: number): boolean {
const currentAmount = this.resourceMap.get(type) || 0;
this.resourceMap.set(type, currentAmount + amount);
return true;
}
public hasResources(resources: Array<{ type: ResourceType, amount: number }>): boolean {
return !resources.some((resource) => {
const resourceInStorage = this.resourceMap.get(resource.type);
if (!resourceInStorage || resourceInStorage < resource.amount) {
return true;
}
return false;
});
}
public discardResources(resources: Array<{ type: ResourceType, amount: number }>): boolean {
if (!this.hasResources(resources)) {
return false;
}
resources.forEach((resource) => {
const resourceInStorage = this.resourceMap.get(resource.type);
this.resourceMap.set(resource.type, resourceInStorage - resource.amount);
});
return true;
}
public plowField(position: number): boolean {
// TODO
return false;
}
public sow(resources: Array<ResourceType.CEREAL | ResourceType.VEGETABLE>): boolean {
// TODO
return false;
}
public playOccupationCard(card: any): boolean {
// TODO
return false;
}
public playMinorImprovementCard(card: any): boolean {
// TODO
return false;
}
public playMajorImprovementCard(card: any): boolean {
// TODO
return false;
}
public becomeFirstPlayer(): boolean {
// TODO
return false;
}
public makeAChild(): boolean {
// TODO
return false;
}
public buildRooms(type: ResourceType.WOOD | ResourceType.CLAY | ResourceType.STONE, positions: number[]): boolean {
// TODO
return false;
}
public renovateHouse(type: ResourceType.CLAY | ResourceType.STONE): boolean {
// TODO
return false;
}
public placeFences(positions: number[]): boolean {
// TODO
return false;
}
public buildStables(positions: number[]): boolean {
// TODO
return false;
}
public toString(): string {
return `
Resources:
FOOD: ${this.resourceMap.get(ResourceType.FOOD)}
SHEEP: ${this.resourceMap.get(ResourceType.SHEEP)}
CATTLE: ${this.resourceMap.get(ResourceType.CATTLE)}
PIG: ${this.resourceMap.get(ResourceType.PIG)}
REED: ${this.resourceMap.get(ResourceType.REED)}
CLAY: ${this.resourceMap.get(ResourceType.CLAY)}
WOOD: ${this.resourceMap.get(ResourceType.WOOD)}
STONE: ${this.resourceMap.get(ResourceType.STONE)}
CEREAL: ${this.resourceMap.get(ResourceType.CEREAL)}
VEGETABLE: ${this.resourceMap.get(ResourceType.VEGETABLE)}
`;
}
}
<file_sep>import { Player } from '../../player.class';
import { ActionKey } from '../action-keys.enum';
import { IActionParams } from '../action-params.interface';
import { Action } from '../action.class';
export class FarmlandAction extends Action {
public readonly key = ActionKey.FARMLAND;
protected applyEffects(player: Player, params: IActionParams): boolean {
return player.plowField(params.fieldPosition);
}
}
| cee09bfbb9ec95818ec877a23e210df8cdd59530 | [
"TypeScript"
] | 26 | TypeScript | pedrus16/agricola | fc375b490bfb965fb6881656c139db77c493d70b | b20ccdc682cfb2333f5fc5e6d22b64e5c044654e |
refs/heads/master | <repo_name>1085437068/hello_world<file_sep>/change_format.py
#!/usr/bin/env python3
#--coding:utf-8--
#出现IOError可能与图片保存的新路径有关,换个路径试试
#出现Keyeeror由于fmt_output处多加了双引号
#在调试过程中发现os.path下的函数引用路径必须要有双引号,此程序在函数get_imlist中返回的数列已带有双引号!
from PIL import Image
import os
def get_imlist(path1,fmt_input):
return[os.path.join(path1,f) for f in os.listdir(path1) if f.endswith(fmt_input)] #listdir显示所有文件名给f,返回所有输入格式的图片 f:文件名和path:路径
def convert_image_fmt(path1,path2,fmt_input,fmt_output):
im_list=get_imlist(path1,fmt_input)
for infile in im_list: #将文件列表名字赋予infile
file_name=os.path.basename(infile) #抽出文件名
outfile=path2+'/'+os.path.splitext(file_name)[0]+fmt_output #提取infile的名字赋予新的格式,fmt。。。不要用引号
if os.path.splitext(infile)[1] != os.path.splitext(outfile)[1]:
try:
Image.open(infile).save(outfile) #替换
except IOError:
print('cannot convert')
path1=input('Please enter path(original):')
path2=input('Please enter path(now):')
fmt_input=input('Please enter format(original):')
fmt_output=input('Please enter latter format(now):')
convert_image_fmt(path1,path2,fmt_input,fmt_output)
<file_sep>/scanning_simple.cpp
//文件扫描程序:能够对纸质文件进行扫描处理,即图像的信息区域的提取与矫正
//2019/9/18
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include<algorithm>
using namespace cv;
using namespace std;
//角点排序
bool x_sort(const Point2f & m1, const Point2f & m2)
{
return m1.x < m2.x;
}
//确定四个点的中心线
void sortCorners(vector<Point2f>& corners, Point2f center)
{
vector<Point2f> top, bot;
vector<Point2f> backup = corners;
sort(corners.begin(), corners.end(), x_sort); //注意先按x的大小给4个点排序
for (int i = 0; i < corners.size(); i++)
{
if (corners[i].y < center.y && top.size() < 2) //这里的小于2是为了避免三个顶点都在top的情况
top.push_back(corners[i]);
else
bot.push_back(corners[i]);
}
corners.clear();
if (top.size() == 2 && bot.size() == 2)
{
//cout << "log" << endl;
cv::Point2f tl = top[0].x > top[1].x ? top[1] : top[0];
cv::Point2f tr = top[0].x > top[1].x ? top[0] : top[1];
cv::Point2f bl = bot[0].x > bot[1].x ? bot[1] : bot[0];
cv::Point2f br = bot[0].x > bot[1].x ? bot[0] : bot[1];
corners.push_back(tl);
corners.push_back(tr);
corners.push_back(br);
corners.push_back(bl);
}
else
{
corners = backup;
}
}
//图像矫正后的高度与宽度计算
int CalcDstSize_height(const vector<cv::Point2f>& corners)
{
int dst_hight;
int h1 = sqrt((corners[0].x - corners[3].x)*(corners[0].x - corners[3].x) + (corners[0].y - corners[3].y)*(corners[0].y - corners[3].y));
int h2 = sqrt((corners[1].x - corners[2].x)*(corners[1].x - corners[2].x) + (corners[1].y - corners[2].y)*(corners[1].y - corners[2].y));
return dst_hight = MAX(h1, h2);
}
int CalcDstSize_width(const vector<cv::Point2f>& corners)
{
int dst_width;
int w1 = sqrt((corners[0].x - corners[1].x)*(corners[0].x - corners[1].x) + (corners[0].y - corners[1].y)*(corners[0].y - corners[1].y));
int w2 = sqrt((corners[2].x - corners[3].x)*(corners[2].x - corners[3].x) + (corners[2].y - corners[3].y)*(corners[2].y - corners[3].y));
return dst_width = MAX(w1, w2);
}
int main()
{
Mat src = imread("1-123029001-OCR-AH-A01_100.jpg");
Mat img = src.clone();
//储存轮廓的变量
vector<vector<Point> > contours;
vector<vector<Point> > f_contours;
Mat contour_dstimg = Mat::zeros(src.rows, src.cols, CV_8UC3);
//计算角点时使用的变量
Mat corner_img;
Mat bkup = src.clone();
vector<Point2f> corners;
int maxCornerNumber = 4;
int r = 4;
double qualityLevel = 0.01;
double minDistance = 10;
RNG rng(12345);
//矫正计算使用的变量
Mat source = src.clone();
int g_dst_hight;
int g_dst_width;
//图像太大,改变下尺寸
resize(src, src, Size(), 0.5, 0.5);
resize(source, source, Size(), 0.5, 0.5);
resize(img, img, Size(), 0.5, 0.5);
resize(bkup, bkup, Size(), 0.5, 0.5);
imshow("原图", src);
cvtColor(img, img, CV_RGB2GRAY); //二值化
GaussianBlur(img, img, Size(5, 5), 0, 0); //高斯滤波
Mat element = getStructuringElement(MORPH_RECT, Size(3, 3)); //获取自定义核,第一个参数MORPH_RECT表示矩形的卷积核,当然还可以选择椭圆形的、交叉型的 //膨胀操作
dilate(img, img, element); //实现过程中发现,适当的膨胀很重要
//选取信息区域轮廓
Canny(img, img, 30, 120, 3); //边缘提取
findContours(img, f_contours, RETR_EXTERNAL, CHAIN_APPROX_NONE); //找轮廓
//求出面积最大的轮廓
int max_area = 0;
int index;
for (int i = 0; i < f_contours.size(); i++)
{
double tmparea = fabs(contourArea(f_contours[i]));
if (tmparea > max_area)
{
index = i;
max_area = tmparea;
}
}
contours.push_back(f_contours[index]);
drawContours(contour_dstimg, contours, -1, Scalar(255, 255, 255));
//计算角点
cvtColor(contour_dstimg, contour_dstimg, CV_RGB2GRAY);
goodFeaturesToTrack(contour_dstimg, corners, maxCornerNumber, qualityLevel, minDistance);
//确定中心点
Point2f center;
double center_x = (corners[0].x + corners[1].x + corners[2].x + corners[3].x) / corners.size();
double center_y = (corners[0].y + corners[1].y + corners[2].y + corners[3].y) / corners.size();
center = (Point(center_x, center_y));
//角点排序
sortCorners(corners, center);
//矫正后图像的宽度和高度
g_dst_hight = CalcDstSize_height(corners); //最终图像的高度
g_dst_width = CalcDstSize_width(corners); //最终图像的宽度
//矫正变换
Mat quad = Mat::zeros(g_dst_hight, g_dst_width, CV_8UC3);
vector<Point2f> quad_pts;
quad_pts.push_back(Point2f(0, 0));
quad_pts.push_back(Point2f(quad.cols, 0));
quad_pts.push_back(Point2f(quad.cols, quad.rows));
quad_pts.push_back(Point2f(0, quad.rows));
Mat transmtx = getPerspectiveTransform(corners, quad_pts);
warpPerspective(source, quad, transmtx, quad.size());
imshow("quadrilateral", quad);
waitKey(0);
}
<file_sep>/README.md
# hello_world
这是在学习编程时,跟着练习做的一些小工具
| e6f46db96b8d6408dd447a48ac9963a05d42f906 | [
"Markdown",
"Python",
"C++"
] | 3 | Python | 1085437068/hello_world | e7472b01a44403c1a5a0765a04d2080d454decd4 | c6e95e1b9f0a44370446a07c57244688a30322a9 |
refs/heads/master | <repo_name>guorant/hexo-sup-footnote<file_sep>/index.js
var renderFootnotes = require('./src/footnotes');
util = require('hexo-util');
var hexo = hexo || {};
var config = hexo.config || {};
var footnoteConfig = config.sup_footnote || {};
// Register footnotes filter
hexo.extend.filter.register('before_post_render', function(data) {
data.content = renderFootnotes(data.content, footnoteConfig);
return data;
});<file_sep>/src/footnotes.js
'use strict';
var md = require('markdown-it')({
// allow HTML tags
html: true
});
var indexLabelList = [
'①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳',
'❶❷❸❹❺❻❼❽❾❿⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴',
'㊀㊁㊂㊃㊄㊅㊆㊇㊈㊉',
'㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩',
'⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇',
'⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛',
'ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ',
'ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹ',
'ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ',
'ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ',
'⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵',
];
/**
* Render markdown footnotes
* @param {String} text
* @returns {String} text
*/
function renderFootnotes(text, config) {
var footnotes = [];
var indexMap = {};
var indexLabel = ('⓪' + indexLabelList.join('')).split('').join("|");
var indexLabelMap = {'⓪': 0};
indexLabelList.forEach(function(item, index) {
item.split('').forEach(function (it, id) {
indexLabelMap[it] = id + 1;
});
});
var reFootnoteContent = new RegExp('('+ indexLabel
+ '|\\[\\d+\\])([\\S \\t]+?)(?::|:) ?([\\S\\s]+?)(?=\\n[\\S\\s]+?(?:'
+ indexLabel + '|\\[\\d+\\])(?:[\\S \\t]+?)(?::|:)|\n\n|$)', 'g');
// render (HTML) footnotes reference
text = text.replace(reFootnoteContent, function (match, index, original, content) {
var reIndex = original + '^' + index + '^';
var indexId = (undefined !== indexLabelMap[index]) ? indexLabelMap[index] : parseInt(index.substring(1));
if (-1 != text.indexOf(reIndex)) {
footnotes.push(indexMap[reIndex] = {
index: index,
indexId: indexId,
original: original,
reIndex: reIndex
});
// render footnote content
return '<span id="supfntxt:' + indexId +
(config.location_target_class ? '" class="' + config.location_target_class : '') +
'">' + index + original + '</span>: ' + md.renderInline(content.trim())
+ '<a href="#supfnref:' + indexId + '">↩</a>';
} else {
// with no footnot index
return match;
}
});
// render footnotes (HTML)
if (footnotes.length) {
var replaceStr = footnotes.map(function (item)
{ return item.reIndex.replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&'); }).join("|");
text = text.replace(new RegExp(replaceStr, 'gm'), function (match) {
var item = indexMap[match];
if (item) {
return '<a id="supfnref:' + item.indexId + '" href="#supfntxt:' + item.indexId +
(config.location_target_class ? '" class="' + config.location_target_class : '') +
'">' + item.original + '<sup>' + item.index + '</sup></a>';
} else {
return match;
}
});
}
return text;
}
module.exports = renderFootnotes;<file_sep>/README.md
# hexo-sup-footnote
[](https://www.npmjs.com/package/hexo-sup-footnote) [](https://travis-ci.org/guorant/hexo-sup-footnote) [](https://coveralls.io/github/guorant/hexo-sup-footnote?branch=master) [](https://david-dm.org/guorant/hexo-sup-footnote#info=dependencies&view=table) [](https://david-dm.org/guorant/hexo-sup-footnote#info=devDependencies&view=table)
A plugin to support markdown sup footnotes in your Hexo blog posts.
## Installation
```
npm install hexo-sup-footnote --save
```
If Hexo detect automatically all plugins, that's all.
If that is not the case, register the plugin in your `_config.yml` file :
```
plugins:
- hexo-sup-footnote
```
## Configuration
```
sup_footnote:
location_target_class: location-target
```
## Syntax
### Mardown
```
footnote with ①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳ first type No.^①^
another footnote with ❶❷❸❹❺❻❼❽❾❿⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴ second type No.^❷^
third type footnote with ㊀㊁㊂㊃㊄㊅㊆㊇㊈㊉ third type No.^㊂^
fourth type footnote with ㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩ fourth type No.^㈣^
fifth type footnote with ⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇ fifth type No.^⑸^
sixth type footnote with ⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛ sixth type No.^⒍^
seventh type footnote with ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ seventh type No.^Ⅶ^
eighth type footnote with ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹ eighth type No.^ⅷ^
ninth type footnote with ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ ninth type No.^Ⓘ^
tenth type footnote with ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ tenth type No.^ⓙ^
eleventh type footnote with ⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵ eleventh type No.^⒦^
twelfth type footnote with 1234567890 twelfth type No.^[12]^
test other type footnote [-[\]{}()*+!<=?.\\$|#\s,^[13]^
①first type No.: 第一类上标
❷second type No.: 第二类上标
㊂third type No.: 第三类上标
㈣fourth type No.: 第四类上标
⑸fifth type No.: 第五类上标
⒍sixth type No.: 第六类上标
Ⅶseventh type No.: 第七类上标
ⅷeighth type No.: 第八类上标
Ⓘninth type No.: 第九类上标
ⓙtenth type No.: 第十类上标
⒦eleventh type No.: 第十一类上标
[12]twelfth type No.: 第十二类上标
[13][-[\]{}()*+!<=?.\\$|#\s,: 测试上标
```
See [Demo](http://kchen.cc/2016/11/10/footnotes-in-hexo/) here.
### Output
 | dbfd2fc5ca6975bcf730c1ab8d3a7a0b18f50af8 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | guorant/hexo-sup-footnote | 3b15a153fc4b474084536317c9fef966035fe35c | 032d66a97f6aa64578f9c2ba978c455b99562be9 |
refs/heads/master | <repo_name>drafe1/bathroom<file_sep>/js.js
function closeAndOpen(elem){
var a,b;
if (elem.id == "cross1") {
a = document.getElementById('work1');
b = getComputedStyle(a,null);
if (b.visibility== 'visible') {
a.style.visibility = 'hidden';
elem.style.marginLeft = 0;
} else {
a.style.visibility = 'visible';
elem.style.marginLeft = 165;
}
}
else if (elem.id == "cross2") {
a = document.getElementById('work2');
b = getComputedStyle(a,null);
if (b.visibility== 'visible') {
a.style.visibility = 'hidden';
elem.style.marginLeft = 0;
} else {
a.style.visibility = 'visible';
elem.style.marginLeft = 165;
}
}
else if (elem.id == "cross3") {
a = document.getElementById('work3');
b = getComputedStyle(a,null);
if (b.visibility== 'visible') {
a.style.visibility = 'hidden';
elem.style.marginLeft = 0;
} else {
a.style.visibility = 'visible';
elem.style.marginLeft = 165;
}
}
}
function openPopUp(){
var a = document.getElementById("PopUp");
a.style.display = "block";
a.style.height = "100%";
a.style.width = "100%";
a.style.zIndex = 4;
a.style.position = "fixed";
a.style.backgroundColor = "rgba(0,0,0,0.5)";
var b = document.getElementById("childPopUp");
b.style.width = '40%';
b.style.height = '40%';
b.style.backgroundColor = "white";
b.style.display = "block";
b.style.marginLeft = "auto"
b.style.marginRight = "auto"
b.style.marginTop = "300px"
}
function closePopUp(){
var a = document.getElementById("PopUp");
a.style.display = "none";
} | 7712390dd5a4f60fc9acb6a61a88b6bd18fa835a | [
"JavaScript"
] | 1 | JavaScript | drafe1/bathroom | 6b3794fdd326723c583378c91f3c969e90a47a32 | b02ff2614e8d5ff8224fc9b40b8c5c26c767060a |
refs/heads/master | <repo_name>jonathan-kalechstain/shap<file_sep>/tests/maskers/test_fixed_composite.py
""" This file contains tests for the FixedComposite masker.
"""
import pytest
import numpy as np
import shap
@pytest.mark.skip(reason="fails on travis and I don't know why yet...Ryan might need to take a look since this API will change soon anyway")
def test_fixed_composite_masker_call():
""" Test to make sure the FixedComposite masker works when masking everything.
"""
AutoTokenizer = pytest.importorskip("transformers").AutoTokenizer
args = ("This is a test statement for fixed composite masker",)
tokenizer = AutoTokenizer.from_pretrained("gpt2")
masker = shap.maskers.Text(tokenizer)
mask = np.zeros(masker.shape(*args)[1], dtype=bool)
fixed_composite_masker = shap.maskers.FixedComposite(masker)
expected_fixed_composite_masked_output = (np.array(['']), np.array(["This is a test statement for fixed composite masker"]))
fixed_composite_masked_output = fixed_composite_masker(mask, *args)
assert fixed_composite_masked_output == expected_fixed_composite_masked_output
| 41a980563cb32b3f804ca34cf671f6c7cd89db68 | [
"Python"
] | 1 | Python | jonathan-kalechstain/shap | c99631bb0b0888ce9ca0c5c3c97a4288d24e4dd7 | 243344fbb149ba451c62e60822f7dd0a74e21ffc |
refs/heads/master | <file_sep><?php
//this function creates links to rss feeds
function rssfeed_links($items_array) {
$rsslinks = "";
for ($item = 0; $item < count($items_array); $item++) {
$item_name = $items_array[$item];
$item_name_url = urlencode($item_name);
$rsslinks .= "<p>
<a href='rssfeed.php?rssLink=$item_name_url' target='_blank'><img src='./images/rssicon.png' alt='$item_name RSS feed'></a>
<a href='rssfeed.php?rssLink=$item_name_url' target='_blank'>$item_name</a>
</p>";
}
return $rsslinks;
}
// this function builds navigational page links based on selection, current page, number of pages
function generate_page_links($selection, $cur_page, $num_pages) {
$links = "";
// if this page is not first page, generate previous "<" link
if ($cur_page > 1) {
$previous_link = $cur_page - 1;
$links .= "<a href='" . $_SERVER['PHP_SELF'] . "?productline=$selection&page=$previous_link'><</a>";
}
else {
$links .= "<";
}
// loop through pages generating page number links
for ($link = 1; $link <= $num_pages; $link++) {
if ($cur_page == $link) {
$links .= " $link";
}
else {
$links .= "<a href='" . $_SERVER['PHP_SELF'] . "?productline=$selection&page=$link'> $link</a>";
}
}
// if this page is not last page, generate next ">" link
if ($cur_page < $num_pages) {
$next_link = $cur_page + 1;
$links .= "<a href='" . $_SERVER['PHP_SELF'] . "?productline=$selection&page=$next_link'> ></a>";
}
else {
$links .= " >";
}
return $links;
}
// this function creates data set containing bar names and values
function fill_graph_array($array) {
$bar1 = $bar2 = $bar3 = $bar4 = $bar5 = 0;
foreach ($array as $values) {
if ($values == 0) {
$bar1++;
}
elseif ($values < 50001) {
$bar2++;
}
elseif ($values < 75001) {
$bar3++;
}
elseif ($values < 100001) {
$bar4++;
}
else {
$bar5++;
}
}
$filled_chart_array = array(
array(" $0", $bar1),
array(" $1 to $50,000", $bar2),
array(" $50,001 to $75,000", $bar3),
array(" $75,001 to $100,000", $bar4),
array(" Greater than $100,000", $bar5)
);
return $filled_chart_array;
}
// this function calculates maximum y-axis value
function make_graph_scale($array) {
$scale_max = round((count($array) / 5) + 15);
return $scale_max;
}
// this function draws bar graph given width, height, data set, max value, and image filename
function draw_bar_graph($width, $height, $data, $max_value, $filename) {
// create empty graph image
$img = imagecreatetruecolor($width, $height);
// set background, border, bar and text colors
$bg_color = imagecolorallocate($img, 228, 228, 228); // gray
$border_color = imagecolorallocate($img, 0, 0, 0); // black
$bar_color = imagecolorallocate($img, 51, 102, 102); // green
$text_color = imagecolorallocate($img, 255, 255, 255); // white
// fill graph background
imagefilledrectangle($img, 0, 0, $width, $height, $bg_color);
// draw graph bars
$bar_width = $width / ((count($data) * 2) + 1);
for ($i = 0; $i < count($data); $i++) {
imagefilledrectangle($img, ($i * $bar_width * 2) + $bar_width, $height,
($i * $bar_width * 2) + ($bar_width * 2), $height - (($height / $max_value) * $data[$i][1]), $bar_color);
imagestringup($img, 5, ($i * $bar_width * 2) + ($bar_width), $height - 5, $data[$i][0], $text_color);
}
// draw graph border
imagerectangle($img, 0, 0, $width - 1, $height - 1, $border_color);
// draw range on left side of graph
for ($i = 0; $i <= $max_value; $i+=5) {
imagestring($img, 5, 0, $height - ($i * ($height / $max_value)), $i, $border_color);
}
// write graph image to a file
imagepng($img, $filename, 5);
imagedestroy($img);
}
?><file_sep>A fictional Berkeley Classic Vehicles website created in PHP. Developing this website involves the creation of forms, storage of form data in the database, use of data from databases, and web application security.
<file_sep><?php
// start and check for valid session
require_once("./includes/redirectlogin.inc.php");
// database connection
require_once "./includes/connectvars.inc.php";
// functions for drawing bar graph
require_once("./includes/functions.inc.php");
// store credit limit data into array
$creditlimit = array();
$query = "SELECT creditLimit from customers";
$data = mysqli_query($dbc, $query)
or die("Error querying database - $query");
while ($row = mysqli_fetch_array($data)) {
array_push($creditlimit, $row['creditLimit']);
}
// draw bar graph based on credit limit data
$graph_array = fill_graph_array($creditlimit);
$graph_name = "./charts/bar-graph-report.png";
$graph_scale = make_graph_scale($creditlimit);
draw_bar_graph(600, 500, $graph_array, $graph_scale, $graph_name);
require_once("./includes/htmlhead.inc.php");
?>
<body>
<div id="bodycontainer">
<?php require_once("./includes/header.inc.php"); ?>
<?php require_once("./includes/navigation.inc.php"); ?>
<div id="content">
<h2>Credit Limits and Number of Customers</h2>
<p>Our past customers had a wide range of credit limits or financial capabilities. Please select the vehicles that will fit the customer's financial requirements.</p>
<p id="vertical-axis-title">Number of Customers</p>
<div id="bar-graph">
<p><img src="<?= $graph_name ?>" alt="Credit limits and customer number bar graph"></p>
<p id="horizontal-axis-title">Credit Limits in US Dollars</p>
</div>
</div>
<?php require_once("./includes/footer.inc.php"); ?>
</div>
</body>
</html>
<?php
// close database connection
mysqli_close($dbc);
?><file_sep><?php
require_once "./includes/connectvars.inc.php"; // database connection
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="utf-8"?>';
$builddate = gmdate(DATE_RSS, time()); // GMT date and time
if (isset($_GET['rssLink'])) { // $_GET variable is set
// get vehicle type from URL via GET
$vehicle_type = trim($_GET['rssLink']);
// select query
$query = "SELECT * FROM products WHERE productLine = '$vehicle_type' ORDER BY dateAdded DESC LIMIT 10";
// query result
$result = mysqli_query($dbc, $query)
or die("Error querying database - $query");
$num_rows = mysqli_num_rows($result);
if ($num_rows != 0) { // valid data provided to page via GET
?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title><?= $vehicle_type ?></title>
<atom:link href="http://<?= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?>" rel="self" type="application/rss+xml" />
<link>http://joahsu.com/berkeley-classic-vehicles/rssfeedlinks.php</link>
<description>RSS Feed for <?= $vehicle_type ?></description>
<lastBuildDate><?= $builddate ?></lastBuildDate>
<language>en-us</language>
<?
// loop through each data row
while ($newArray = mysqli_fetch_array($result)) {
$product_code = $newArray['productCode'];
$product_name = $newArray['productName'];
$product_line = $newArray['productLine'];
$product_scale = $newArray['productScale'];
$product_vendor = $newArray['productVendor'];
$product_description = $newArray['productDescription'];
$buy_price = $newArray['buyPrice'];
$date_added = $newArray['dateAdded'];
$usd_buy_price = "US$".number_format($buy_price,2);
$pubdate = date(DATE_RSS, strtotime($date_added));
$information = "Product Line - $product_line<br />
Product Scale - $product_scale<br />
Vendor - $product_vendor<br />
Description - $product_description<br />
Buy Price - $usd_buy_price";
?>
<item>
<title><?= $product_name ?></title>
<description><?= $information ?></description>
<link>http://joahsu.com/berkeley-classic-vehicles/product.php?productid=<?= $product_code ?></link>
<guid isPermaLink="false">http://joahsu.com/berkeley-classic-vehicles/product.php?productid=<?= $product_code ?></guid>
<pubDate><?= $pubdate ?></pubDate>
</item>
<?
}
} else { // invalid data provided to page via GET
require_once("./includes/xmlrss.inc.php");
}
} else { // $_GET variable is not set
require_once("./includes/xmlrss.inc.php");
}
?>
</channel>
</rss>
<?php
// close database connection
mysqli_close($dbc);
?><file_sep><?php
// start and check for valid session
require_once("./includes/redirectlogin.inc.php");
// set local employee name to say goodbye
$employee_name = $_SESSION['username'];
// destroy session, logout, redirect to login page
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 3600);
}
session_destroy();
header('Refresh: 8; login.php');
// HTML document
require_once("./includes/htmlhead.inc.php");
?>
<body>
<div id="bodycontainer">
<?php require_once("./includes/header.inc.php"); ?>
<?php require_once("./includes/navigation.inc.php"); ?>
<div id="content">
<h2>You have now logged out</h2>
<div>
<p>Thank you for visiting the website of Berkeley Classic Vehicles, <?= $employee_name ?>! Please come back soon.</p>
</div>
</div>
<?php require_once("./includes/footer.inc.php"); ?>
</div>
</body>
</html><file_sep><?php
// start and check for valid session
require_once("./includes/redirectlogin.inc.php");
// database connection
require_once "./includes/connectvars.inc.php";
// declare variables
$display_form = true;
$firstname = '';
$firstname_error_msg = '';
$valid_firstname = false;
$firstname_regex = '/^[a-zA-Z]{2,20}$/';
$lastname = '';
$lastname_error_msg = '';
$valid_lastname = false;
$lastname_regex = '/^[a-zA-Z]{2,20}$/';
$company = '';
$company_error_msg = '';
$valid_company = false;
$company_regex = "/^[0-9a-zA-Z\s\&]{2,40}$/";
$phone = '';
$digits_only_phone = '';
$phone_error_msg = '';
$valid_phone = false;
$phone_regex = '/^\d{3}\-\d{3}-\d{4}$/';
$address1 = '';
$address1_error_msg = '';
$valid_address1 = false;
$address1_regex = '/^[a-zA-Z0-9#,\.\s]{2,40}$/';
$address2 = '';
$address2_error_msg = '';
$valid_address2 = false;
$address2_regex = '/^[a-zA-Z0-9#,\.\s]{2,40}$/';
$city = '';
$city_error_msg = '';
$valid_city = false;
$city_regex = '/^[a-zA-Z\s]{3,20}$/';
$state = '';
$state_error_msg = '';
$valid_state = false;
$state_regex = '/^[a-zA-Z\s]{2,20}$/';
$postalcode = '';
$postalcode_error_msg = '';
$valid_postalcode = false;
$postalcode_regex = '/^[0-9]{5}(\-[0-9]{4})?$/';
$country = '';
$country_error_msg = '';
$valid_country = false;
$country_regex = '/^[a-zA-Z\s]{2,20}$/';
$salesrep = '1165';
$creditlimit = '';
$creditlimit_error_msg = '';
$valid_creditlimit = false;
$creditlimit_regex = '/^\d{1,6}$/';
// SELECT query
$query = "SELECT * FROM employees WHERE jobTitle = 'Sales Rep' ORDER BY employeeNumber ASC";
// result of query
$result = mysqli_query($dbc, $query)
or die ("Error querying database - $query");
// check if submit button has submitted form data
if (isset($_POST['submit'])) {
// get submitted form data
$firstname = mysqli_real_escape_string($dbc, trim($_POST['firstname']));
$lastname = mysqli_real_escape_string($dbc, trim($_POST['lastname']));
$company = mysqli_real_escape_string($dbc, trim($_POST['company']));
$phone = mysqli_real_escape_string($dbc, trim($_POST['phone']));
$address1 = mysqli_real_escape_string($dbc, trim($_POST['address1']));
$address2 = mysqli_real_escape_string($dbc, trim($_POST['address2']));
$city = mysqli_real_escape_string($dbc, trim($_POST['city']));
$state = mysqli_real_escape_string($dbc, trim($_POST['state']));
$postalcode = mysqli_real_escape_string($dbc, trim($_POST['postalcode']));
$country = mysqli_real_escape_string($dbc, trim($_POST['country']));
$salesrep = $_POST['salesrep'];
$creditlimit = mysqli_real_escape_string($dbc, trim($_POST['creditlimit']));
// validate first name
if (preg_match($firstname_regex, $firstname)) {
$valid_firstname = true;
} else {
$firstname_error_msg = '<span class="error">Enter from 2 to 20 alphabets</span>';
}
// validate last name
if (preg_match($lastname_regex, $lastname)) {
$valid_lastname = true;
} else {
$lastname_error_msg = '<span class="error">Enter from 2 to 20 alphabets</span>';
}
// validate company
if (preg_match($company_regex, $company)) {
$valid_company = true;
} else {
$company_error_msg = '<span class="error">Enter from 2 to 40 characters. Acceptable characters are alphabets, numbers, space, and &</span>';
}
// validate phone
if (preg_match($phone_regex, $phone)) {
$valid_phone = true;
} else {
$phone_error_msg = '<span class="error">Enter in xxx-xxx-xxxx format</span>';
}
// validate address line 1
if (preg_match($address1_regex, $address1)) {
$valid_address1 = true;
} else {
$address1_error_msg = '<span class="error">Enter from 2 to 40 characters. Acceptable characters are alphabets, numbers, period, space, comma, and #</span>';
}
// validate address line 2
if (strlen($address2) == 0) {
$valid_address2 = true;
}
else if (preg_match($address2_regex, $address2)){
$valid_address2 = true;
} else {
$address2_error_msg = '<span class="error">Enter from 2 to 40 characters. Acceptable characters are alphabets, numbers, period, space, comma, and #</span>';
}
// validate city
if (preg_match($city_regex, $city)) {
$valid_city = true;
} else {
$city_error_msg = '<span class="error">Enter from 3 to 20 characters. Acceptable characters are alphabets and space</span>';
}
// validate state
if (preg_match($state_regex, $state)) {
$valid_state = true;
} else {
$state_error_msg = '<span class="error">Enter from 2 to 20 characters. Acceptable characters are alphabets and space</span>';
}
// validate postal code
if (preg_match($postalcode_regex, $postalcode)) {
$valid_postalcode = true;
} else {
$postalcode_error_msg = '<span class="error">Enter in xxxxx or xxxxx-xxxx format</span>';
}
// validate country
if (preg_match($country_regex, $country)) {
$valid_country = true;
} else {
$country_error_msg = '<span class="error">Enter from 2 to 20 characters. Acceptable characters are alphabets and space</span>';
}
// validate credit limit
if (preg_match($creditlimit_regex, $creditlimit)) {
$valid_creditlimit = true;
} else {
$creditlimit_error_msg = '<span class="error">Enter from 1 to 6 digits only</span>';
}
if (!$valid_firstname || !$valid_lastname || !$valid_company || !$valid_phone || !$valid_address1 || !$valid_address2 || !$valid_postalcode || !$valid_city || !$valid_state || !$valid_country || !$valid_creditlimit) {
// one or more inputs are invalid
$display_form = true;
} else {
// all inputs are valid
$display_form = false;
$pattern = '/[\-]/';
$replacement = '';
$digits_only_phone = preg_replace($pattern, $replacement, $phone);
}
}
// HTML document
require_once("./includes/htmlhead.inc.php");
?>
<body>
<div id="bodycontainer">
<?php require_once("./includes/header.inc.php"); ?>
<?php require_once("./includes/navigation.inc.php"); ?>
<div id="content">
<?php
if ($display_form) {
?>
<h2>Customer Information Form</h2>
<p id="application">Please complete the form below to record the customer's information.</p>
<p>
All fields are required except Address Line 2. Phone is in xxx-xxx-xxxx format.<br>
Postal Code is 5 digits or 5 digits+4. Credit Limit is from 1 to 6 digits only.
</p>
<p>
Upon successful submission, the customer's information will be recorded in the database under your name.
</p>
<form action = "<?= $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data" name="customerform">
<table>
<tr>
<td><label for="firstname">First Name:</label></td>
<td><input type="text" name="firstname" id="firstname" size="25" value="<?= $firstname ?>"><?= $firstname_error_msg ?></td>
</tr>
<tr>
<td><label for="lastname">Last Name:</label></td>
<td><input type="text" name="lastname" id="lastname" size="25" value="<?= $lastname ?>"><?= $lastname_error_msg ?></td>
</tr>
<tr>
<td><label for="company">Company:</label></td>
<td><input type="text" name="company" id="company" size="25" value="<?= $company ?>"><?= $company_error_msg ?></td>
</tr>
<tr>
<td><label for="phone">Phone:</label></td>
<td><input type="text" name="phone" id="phone" size="25" value="<?= $phone ?>"><?= $phone_error_msg ?></td>
</tr>
<tr>
<td><label for="address1">Address Line 1:</label></td>
<td><input type="text" name="address1" id="address1" size="25" value="<?= $address1 ?>"><?= $address1_error_msg ?></td>
</tr>
<tr>
<td><label for="address2">Address Line 2:</label></td>
<td><input type="text" name="address2" id="address2" size="25" value="<?= $address2 ?>"><?= $address2_error_msg ?></td>
</tr>
<tr>
<td><label for="city">City:</label></td>
<td><input type="text" name="city" id="city" size="25" value="<?= $city ?>"><?= $city_error_msg ?></td>
</tr>
<tr>
<td><label for="state">State:</label></td>
<td><input type="text" name="state" id="state" size="25" value="<?= $state ?>"><?= $state_error_msg ?></td>
</tr>
<tr>
<td><label for="postalcode">Postal Code:</label></td>
<td><input type="text" name="postalcode" id="postalcode" size="25" value="<?= $postalcode ?>"><?= $postalcode_error_msg ?></td>
</tr>
<tr>
<td><label for="country">Country:</label></td>
<td><input type="text" name="country" id="country" size="25" value="<?= $country ?>"><?= $country_error_msg ?></td>
</tr>
<tr>
<td><label for="salesrep">Sales Rep:</label></td>
<td><select name="salesrep" id="salesrep">
<?php
while ($row = mysqli_fetch_array($result)) {
$emp_number = $row['employeeNumber'];
$emp_lastname = $row['lastName'];
$emp_firstname = $row['firstName'];
if ($salesrep == $emp_number) {
$selected = " selected";
} else {
$selected = "";
}
?>
<option value="<?= $emp_number ?>"<?= $selected ?>><?= "$emp_number - $emp_firstname $emp_lastname" ?></option>
<?php
}
?>
</select></td>
</tr>
<tr>
<td><label for="creditlimit">Credit Limit:</label></td>
<td><input type="text" name="creditlimit" id="creditlimit" size="25" value="<?= $creditlimit ?>"><?= $creditlimit_error_msg ?></td>
</tr>
</table>
<p><input type="submit" name="submit" id="submit" value="Submit"></p>
</form>
<?php
} else {
$insert_query = "INSERT INTO customers (customerName, contactLastName, contactFirstName, phone, addressLine1, addressLine2, city, state, postalCode, country, salesRepEmployeeNumber, creditLimit) VALUES ('$company','$lastname','$firstname','$digits_only_phone','$address1','$address2','$city','$state','$postalcode','$country', '$salesrep','$creditlimit')";
mysqli_query($dbc, $insert_query)
or die ("Error querying database - $insert_query");
$update_query = "UPDATE customers SET addressLine2 = NULL WHERE addressLine2 = ''";
mysqli_query($dbc, $update_query)
or die ("Error querying database - $update_query");
?>
<h2>You have successfully recorded the customer's information</h2>
<p>
Name: <?= "$firstname $lastname" ?><br>
Company: <?= $company ?><br>
Phone: <?= $phone ?><br>
Address 1: <?= $address1 ?><br>
Address 2: <?= $address2 ?><br>
City: <?= $city ?><br>
State: <?= $state ?><br>
Postal Code: <?= $postalcode ?><br>
Country: <?= $country ?><br>
Sales Representative's Number: <?= $salesrep ?><br>
Credit Limit: <?= $creditlimit ?>
</p>
<?php
}
?>
</div>
<?php require_once("./includes/footer.inc.php"); ?>
</div>
</body>
</html>
<?php
mysqli_close($dbc);
?><file_sep><?php
session_start();
// function for creating links to rss feeds
require_once("./includes/functions.inc.php");
//HTML document
require_once("./includes/htmlhead.inc.php");
?>
<body>
<div id="bodycontainer">
<?php require_once("./includes/header.inc.php"); ?>
<?php require_once("./includes/navigation.inc.php"); ?>
<div id="content">
<h2>RSS Feeds for Vehicles</h2>
<?php
$vehicle_types = array('Classic Cars', 'Motorcycles', 'Vintage Cars', 'Planes');
$rss_links = rssfeed_links($vehicle_types);
?>
<div id="rsslinks">
<?= $rss_links ?>
</div>
</div>
<?php require_once("./includes/footer.inc.php"); ?>
</div>
</body>
</html><file_sep><?php
session_start();
// database connection
require_once "./includes/connectvars.inc.php";
$output = 'No product information';
// check if $_GET variable is set
if (isset($_GET['productid'])) {
$product_id = trim($_GET['productid']); // get product id from URL via GET
$query = "SELECT * FROM products WHERE productCode = '$product_id'"; // select query
$result = mysqli_query($dbc, $query) // query result
or die ("Error querying database - $query");
$num_rows = mysqli_num_rows($result); // number of rows in result set
if ($num_rows != 0) { // valid data provided to page via GET
// loop through each data row
while ($row = mysqli_fetch_array($result)) {
$product_code = $row['productCode'];
$product_name = $row['productName'];
$product_line = $row['productLine'];
$product_scale = $row['productScale'];
$product_vendor = $row['productVendor'];
$product_quantity = number_format($row['quantityInStock']);
$product_description = $row['productDescription'];
$buy_price = $row['buyPrice'];
$msrp = $row['MSRP'];
$usd_buy_price = "US$".number_format($buy_price,2);
$usd_msrp = "US$".number_format($msrp,2);
$output = "<p>Product ID: $product_code</p>
<p>Product Line: $product_line</p>
<p>Product Scale: $product_scale</p>
<p>Vendor: $product_vendor</p>
<p>Quantity in Stock: $product_quantity</p>
<p>Description: $product_description</p>
<p>Buy Price: $usd_buy_price</p>
<p>MSRP: $usd_msrp</p>";
}
} else { // invalid data provided to page via GET
$output = 'No match found';
}
}
// HTML document
require_once("./includes/htmlhead.inc.php");
?>
<body>
<div id="bodycontainer">
<?php require_once("./includes/header.inc.php"); ?>
<?php require_once("./includes/navigation.inc.php"); ?>
<div id="content">
<h2><?= $product_name ?></h2>
<div>
<?= $output ?>
</div>
</div>
<?php require_once("./includes/footer.inc.php"); ?>
</div>
</body>
</html>
<?php
// close database connection
mysqli_close($dbc);
?><file_sep><?php
// start and check for valid session
require_once("./includes/redirectlogin.inc.php");
// HTML document
require_once("./includes/htmlhead.inc.php");
?>
<body>
<div id="bodycontainer">
<?php require_once("./includes/header.inc.php"); ?>
<?php require_once("./includes/navigation.inc.php"); ?>
<div id="content">
<h2>Welcome, <?= $_SESSION['username'] ?>!</h2>
<div id="welcome">
<p>Check out our inventory and select from the categories of cars, motorcycles, trucks and buses, planes, ships, and trains. We offer high quality products at competitive prices and attractive terms for customer finance.</p>
</div>
<div id="photos">
<p>A few photos of our classic vehicles</p>
<table>
<tr>
<td><img src="./images/chevrolet-napco.jpg" alt="Chevrolet Napco"></td>
<td><img src="./images/ford-thunderbird.jpg" alt="Ford Thunderbird"></td>
<td><img src="./images/classic-car.jpg" alt="Classic Car"></td>
</tr>
<tr>
<td><img src="./images/greyhound.jpg" alt="Greyhound"></td>
<td><img src="./images/motorcycle.jpg" alt="Motorcycle"></td>
<td><img src="./images/kenosha-trolley.jpg" alt="Kenosha Trolley"></td>
</tr>
</table>
</div>
</div>
<?php require_once("./includes/footer.inc.php"); ?>
</div>
</body>
</html><file_sep><?php
// start and check for valid session
require_once("./includes/redirectlogin.inc.php");
// database connection
require_once "./includes/connectvars.inc.php";
// function for creating navigational page links
require_once("./includes/functions.inc.php");
//declare variables
$error_msg = '';
$page_links = '';
// query to get all product lines
$query_productlines = "SELECT productLine FROM productlines ORDER BY productLine ASC";
$result = mysqli_query($dbc, $query_productlines)
or die ("Error querying database - $query_productlines");
// get first product line
$first_row = mysqli_fetch_array($result);
$first_productline = $first_row['productLine'];
$user_selection = $first_productline;
// check if $_GET variable is set
if (isset($_GET['productline'])) {
// get selected product line from URL via GET
$user_selection = trim($_GET['productline']);
}
$user_selection_url = urlencode($user_selection);
$current_page = 1;
// check if $_GET variable is set
if (isset($_GET['page'])) {
// get page from URL via GET
$current_page = trim($_GET['page']);
}
// query to get products of a product line
$query_products = "SELECT * FROM products WHERE productLine = '$user_selection' ORDER BY productName ASC";
$products = mysqli_query($dbc, $query_products)
or die ("Error querying database - $query_products");
$total_rows = mysqli_num_rows($products); // total product rows
$rows_per_page = 10; // number of products per page
$skip_rows = (($current_page - 1) * $rows_per_page); // rows to be skipped
$number_of_pages = ceil($total_rows / $rows_per_page); // total number of pages
// query to get ten products for each page
$query_subset = "$query_products LIMIT $skip_rows, $rows_per_page";
$subset = mysqli_query($dbc, $query_subset)
or die ("Error querying database - $query_subset");
// display navigational page links if we have more than one page
if ($number_of_pages > 1) {
$page_links = generate_page_links($user_selection_url, $current_page, $number_of_pages);
}
// display error message if invalid data provided via GET
if ($current_page < 1 || $current_page > $number_of_pages) {
$user_selection = '';
$page_links = '';
$error_msg = '<p>Sorry, there is no inventory list on this page.</p>';
}
// HTML document
require_once("./includes/htmlhead.inc.php");
?>
<body>
<div id="bodycontainer">
<?php require_once("./includes/header.inc.php"); ?>
<?php require_once("./includes/navigation.inc.php"); ?>
<div id="content">
<p id="product-line">Please select a product line to check the makes, models, features, quantities, base prices and MSRPs.</p>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="get" enctype="multipart/form-data" name="report">
<table>
<tr>
<td><label for="productline">Product Line:</label></td>
<td><select name="productline" id="productline">
<?php
// productline selection options
$productlines = mysqli_query($dbc, $query_productlines)
or die ("Error querying database - $query_productlines");
while ($row = mysqli_fetch_array($productlines)) {
$pline = $row['productLine'];
if ($user_selection == $pline) {
$selected = "selected";
} else {
$selected = "";
}
?>
<option value="<?= $pline ?>" <?= $selected ?>><?= $pline ?></option>
<?php
}
?>
</select></td>
<td><input type="submit" name="submit" id="submit" value="Submit"></td>
</tr>
</table>
</form>
<h2><?= $user_selection ?></h2>
<p id="pagelinks">
<?= $page_links ?>
</p>
<table id="inventory">
<tr>
<th class="cell">Product Line</th>
<th class="cell">Product ID</th>
<th class="cell">Product Name</th>
<th class="cell">Product Scale</th>
<th class="cell">Product Vendor</th>
<th class="description">Product Description</th>
<th class="cell">Quantity in Stock</th>
<th class="cell">Buy Price</th>
<th class="cell">MSRP</th>
</tr>
<?php
$row_count = 1; // keep track of row number
// loop through each data row
while ($row = mysqli_fetch_array($subset)) {
$product_line = $row['productLine'];
$product_code = $row['productCode'];
$product_name = $row['productName'];
$product_scale = $row['productScale'];
$product_vendor = $row['productVendor'];
$product_description = $row['productDescription'];
$quantity_stock = number_format($row['quantityInStock']);
$buy_price = $row['buyPrice'];
$msrp = $row['MSRP'];
$usd_buy_price = "US$".number_format($buy_price,2);
$usd_msrp = "US$".number_format($msrp,2);
$row_count++; // count row number
if ($row_count % 2 == 0) { // even row
echo "<tr class='even-row-color'>
<td class='cell'>$product_line</td>
<td class='cell'>$product_code</td>
<td class='cell'>$product_name</td>
<td class='cell'>$product_scale</td>
<td class='cell'>$product_vendor</td>
<td class='description'>$product_description</td>
<td class='cell'>$quantity_stock</td>
<td class='cell'>$usd_buy_price</td>
<td class='cell'>$usd_msrp</td>
</tr>";
} else { // odd row
echo "<tr class='odd-row-color'>
<td class='cell'>$product_line</td>
<td class='cell'>$product_code</td>
<td class='cell'>$product_name</td>
<td class='cell'>$product_scale</td>
<td class='cell'>$product_vendor</td>
<td class='description'>$product_description</td>
<td class='cell'>$quantity_stock</td>
<td class='cell'>$usd_buy_price</td>
<td class='cell'>$usd_msrp</td>
</tr>";
}
}
?>
</table>
<?= $error_msg ?>
</div>
<?php require_once("./includes/footer.inc.php"); ?>
</div>
</body>
</html>
<?php
// close database connection
mysqli_close($dbc);
?><file_sep><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>RSS Feed Not Available</title>
<atom:link href="http://<?= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?>" rel="self" type="application/rss+xml" />
<link>http://joahsu.com/berkeley-classic-vehicles/rssfeedlinks.php</link>
<description>Description not available</description>
<lastBuildDate><?= $builddate ?></lastBuildDate>
<language>en-us</language>
<item>
<title>Item Not Available</title>
<description>Description not available</description>
<link>http://<?= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']?></link>
<guid isPermaLink="false">http://<?= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?></guid>
<pubDate><?= $builddate ?></pubDate>
</item><file_sep><?php
// start and check for valid session
require_once("./includes/redirectindex.inc.php");
// database connection
require_once "./includes/connectvars.inc.php";
// declare variables
$display_form = true;
$error_msg = '';
$username = '';
$password = '';
// check if submit button has submitted form data
if (isset($_POST['submit'])) {
// get submitted form data
$username = mysqli_real_escape_string($dbc, trim($_POST['username']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if (strlen($username) == 0 || strlen($password) == 0) { // username or password field is blank
$error_msg = '<p class="error">Enter both password and username</p>';
$display_form = true;
} else {
// look up username and password in database
$select_query = "SELECT * FROM employees WHERE username = '$username' AND password = md5('<PASSWORD>')";
$data = mysqli_query($dbc, $select_query)
or die("Error querying database - $select_query");
if(mysqli_num_rows($data) == 1) { // valid username and password
$display_form = false;
$row = mysqli_fetch_array($data);
// set username and employee number as session variables and redirect to index page
$_SESSION['username'] = $row['username'];
$_SESSION['employeeNumber'] = $row['employeeNumber'];
header('Location: index.php');
}
else { // invalid username and/or password
$display_form = true;
$error_msg = '<p class="error">Invalid username and/or password.</p>';
}
}
}
// HTML document
require_once("./includes/htmlhead.inc.php");
?>
<body>
<div id="bodycontainer">
<?php require_once("./includes/header.inc.php"); ?>
<div id="content">
<?php
if ($display_form) { // display entry form
?>
<div id="block1">
<h2>Login</h2>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data" name="loginform">
<?= $error_msg ?>
<table>
<tr>
<td><label for="username">Username:</label></td>
<td><input type="text" name="username" id="username" size="20" value="<?= $username ?>"></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="<PASSWORD>" name="password" id="password" size="20" value="<?= $password ?>"></td>
</tr>
</table>
<p><input type="submit" name="submit" id="submit" value="Submit"></p>
</form>
<?php
}
?>
<p id="account"><a href="register.php">Create a User Account</a></p>
</div>
<div id="block2">
<p>Employees/sales representatives at Berkeley Classic Vehicles may use this website to help customers with their purchase of classical vehicle(s) they are interested in. Berkeley Classic Vehicles offers a great variety of classic vehicles from 18th century to early 2000's, including such cars as Porsche 356, BMW F650, and Ford Pickups as well as mortorcycles, buses, trains, planes, and ships. The range of vehicle prices is from US$40 to US$200.</p>
</div>
<div id="block3">
<p><img src="./images/porsche356.jpg" alt="1956 Porsche 356"></p>
</div>
</div>
<?php require_once("./includes/footer.inc.php"); ?>
</div>
</body>
</html>
<?php
// close database connection
mysqli_close($dbc);
?><file_sep><?php
// start and check for valid session
require_once("./includes/redirectindex.inc.php");
// database connection
require_once "./includes/connectvars.inc.php";
// declare variables
$display_form = true;
$error_msg = '';
$username = '';
$username_error_msg = '';
$valid_username = false;
$username_regex = '/^[a-zA-Z][a-zA-Z0-9_\-]{2,23}[a-zA-Z0-9]$/';
$password = '';
$password_error_msg = '';
$valid_password = false;
$password_regex = '/(?=.*\d)(?=.*[a-zA-Z])(?=.*[@!\?\^\$]).{6,}/';
// check if submit button has submitted form data
if (isset($_POST['submit'])) {
// get submitted form data
$username = mysqli_real_escape_string($dbc, trim($_POST['username']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
// validate username
if (preg_match($username_regex, $username)) {
$valid_username = true;
} else {
$username_error_msg = '<span class="error">Username is not acceptable</span>';
}
// validate password
if (preg_match($password_regex, $password)) {
$valid_password = true;
} else {
$password_error_msg = '<span class="error">Password is not acceptable</span>';
}
if (!$valid_username || !$valid_password) {
// one or more inputs are invalid
$display_form = true;
} else {
$display_form = false;
// look up username in database
$select_query = "SELECT * FROM employees WHERE username = '$username'";
$data = mysqli_query($dbc, $select_query)
or die("Error querying database - $select_query");
if (mysqli_num_rows($data) == 0) { // username is avaliable for registration
$display_form = false;
// look up last added employee number in database
$select_query_empnumber = "SELECT MAX(employeeNumber) from employees";
$rows = mysqli_query($dbc, $select_query_empnumber)
or die("Error querying database - $select_query_empnumber");
$row = mysqli_fetch_array($rows);
$employee_id = $row['MAX(employeeNumber)']; // set $employee_id to last added employee number
$employee_id++; // add one to $employee_id
// insert user information into database
$insert_query = "INSERT INTO employees (employeeNumber, lastName, firstName, extension, email, officeCode, reportsTo, jobTitle, username, password) VALUES ('$employee_id', NULL, NULL, NULL, NULL, 1, 1088, NULL, '$username', md5('$password'))";
mysqli_query($dbc, $insert_query)
or die("Error querying database - $insert_query");
// redirect to login page
header('Location: login.php');
} else { // username already taken
$display_form = true;
$username_error_msg = '<span class="error">Username is already taken</span>';
}
}
}
// HTML document
require_once("./includes/htmlhead.inc.php");
?>
<body>
<div id="bodycontainer">
<?php require_once("./includes/header.inc.php"); ?>
<?php require_once("./includes/navigation.inc.php"); ?>
<div id="content">
<?php
if ($display_form) { // display entry form
?>
<h2>Create a User Account</h2>
<p><span id="uname">Username</span> - Enter from 4 to 25 characters. Acceptable characters are letters, numbers, underscore, and hypen.<br>
First character must be a letter. Last character must be a letter or a number</p>
<p><span id="pwd">Password</span> - Enter at least 6 characters. Password must have at least one letter, one number, and one of<br>
these special characters @, !, ?, ^, and $.</p>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data" name="registerform">
<table>
<tr>
<td><label for="username">Username:</label></td>
<td><input type="text" name="username" id="username" size="20" value="<?= $username ?>"><?= $username_error_msg ?></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="<PASSWORD>" name="password" id="password" size="20" value="<?= $password ?>"><?= $password_error_msg ?></td>
</tr>
</table>
<p><input type="submit" name="submit" id="submit" value="Submit"></p>
</form>
<?php
}
?>
</div>
<?php require_once("./includes/footer.inc.php"); ?>
</div>
</body>
</html>
<?php
// close database connection
mysqli_close($dbc);
?><file_sep> <div id="navigation">
<?php
if (isset($_SESSION['username']) && isset($_SESSION['employeeNumber'])) {
// user is logged in
?>
<p class="nav"><a href="index.php" target="_self">Welcome</a></p>
<p class="nav"><a href="inventory.php" target="_self">Vehicle Inventory</a></p>
<p class="nav"><a href="bargraph.php" target="_self">Customers' Credit Limits</a></p>
<p class="nav"><a href="customerform.php" target="_self">Customer Information Form</a></p>
<p id="logout"><a href="logout.php" target="_self">Log Out</a></p>
<?php
} else { // user is not logged in
?>
<p id="phrase">Check Out Our Great Selection of Classic Vehicles</p>
<p id="login"><a href="login.php" target="_self">Log In</a></p>
<?php
}
?>
</div> | 10f8fec9105644a8f15217fd5657fa1e58647ab3 | [
"Markdown",
"PHP"
] | 14 | PHP | jhhsu8/classic-vehicles-website | 19bcca5aa5357348e734a8750d46884b480a009f | 96b186a081a778293b19103fdb6c1c23ffdf4cf0 |
refs/heads/master | <file_sep>require 'sinatra/base'
require 'data_mapper'
require 'rack-flash'
require 'byebug'
class ChitterWeb < Sinatra::Base
enable :sessions
set :session_secret, 'super secret'
use Rack::Flash
#This will allow us to use a new method in our server file, 'delete'
use Rack::MethodOverride
#tells you where your views are..
set :views, Proc.new { File.join(root, "", "views") }
env = ENV['RACK_ENV'] || 'dev'
DataMapper.setup(:default, "postgres://localhost/chitter_#{env}")
p "I'm connected to #{env} !!!!!!!!"
#require our classes/models
require './lib/user'
# After declaring your models, you should finalise them
DataMapper.finalize
# However, the database tables don't exist yet. Let's tell datamapper to create them
DataMapper.auto_upgrade!
get '/' do
@message = "If you would like to peep please register"
erb :index
end
post '/peep/new' do
@peep_msg = Peep.new(peep_msg: params[:peep_msg])
if Peep.save
@message = "Thank you for your thoughts"
redirect to('/')
else
flash.now[:errors] = ['Your peep is chit']
erb :index
end
end
get '/users/new' do
@user = User.new
erb :'users/new'
end
post '/users' do
@user = User.new(email: params[:email],
password: params[:password],
password_confirmation: params[:password_confirmation],
fullname: params[:fullname],
username:params[:username])
if @user.save
session[:user_id] = @user.id
@message = "Welcome to Chitter #{@user.username}"
redirect to('/')
else
flash.now[:errors] = @user.errors.full_messages
erb :'users/new'
end
end
delete '/sessions' do
flash.now[:errors] = ["You've just logged out"]
session[:user_id] = nil
redirect to('/')
end
get '/sessions/new' do
erb :'sessions/new'
end
post '/sessions' do
email, password = params[:email], params[:password]
user = User.authenticate(email, password)
if user
session[:user_id] = user.id
redirect to('/')
else
flash.now[:errors] = ['The email or password is incorrect']
erb :'sessions/new'
end
end
helpers do
def current_user
@current_user ||= User.get(session[:user_id]) if session[:user_id]
end
end
# start the server if ruby file executed directly
run! if app_file == $0
end
<file_sep># Generated by cucumber-sinatra. (2015-05-22 14:57:57 +0100)
ENV['RACK_ENV'] = 'test'
require File.join(File.dirname(__FILE__), '..', '..', 'app/server.rb')
require 'capybara'
require 'capybara/cucumber'
require 'rspec'
#require './features/support/database_cleaner_setup'
require_relative './database_cleaner_setup'
Capybara.app = ChitterWeb
class ChitterWebWorld
include Capybara::DSL
include RSpec::Expectations
include RSpec::Matchers
end
World do
ChitterWebWorld.new
end
<file_sep># move this to under models
require 'bcrypt' # bcrypt will generate the password hash
class User
include DataMapper::Resource
property :id, Serial
property :fullname, String
property :username, String, unique: true, message: 'This username is already taken'
property :email, String, unique: true, message: 'This email is already taken'
property :password_digest, Text
validates_confirmation_of :password, :message => "Sorry, your passwords do not match"
attr_reader :password
attr_accessor :password_confirmation
def password=(password)
@password = <PASSWORD>
self.password_digest = BCrypt::Password.create(password)
end
def self.authenticate(email, password)
user = first(email: email) # that's the user who is trying to sign in
if user && BCrypt::Password.new(user.password_digest) == password
# return this user
user
else
nil
end
end
end<file_sep>source 'https://rubygems.org'
ruby '2.2.1'
gem 'data_mapper' #datamapper
gem 'dm-postgres-adapter' #datamapper
gem 'bcrypt-ruby'
gem 'sinatra'
gem 'rack-flash3'
group :test do
gem 'byebug'
gem 'capybara'
gem 'rspec'
gem 'cucumber'
gem 'cucumber-sinatra'
gem 'coveralls', require: false
gem 'database_cleaner'
gem 'launchy'
gem 'rubocop-rspec'
gem 'rubocop'
end
<file_sep>When(/^I enter "([^"]*)" in "([^"]*)"$/) do |text, fieldname|
fill_in(fieldname, with: text)
end
When(/^I click "([^"]*)"$/) do |button|
click_button(button)
end
#doesn't use 'user'
Given(/^I signup as "([^"]*)"$/) do |user|
visit('/')
click_link("Register")
fill_in("fullname", with: "<NAME>")
fill_in("email", with: "<EMAIL>")
fill_in("username", with: "bobster")
fill_in("password", with: "<PASSWORD>")
fill_in("password_confirmation", with: "<PASSWORD>")
click_button("Sign up")
end
#doesn't use 'user'
Given(/^I log in as "([^"]*)"$/) do |user|
visit('/')
click_button("Sign in")
fill_in("email", with: "<EMAIL>")
fill_in("password", with: "<PASSWORD>")
click_button("Sign in")
end
<file_sep>class Link
include DataMapper::Resource
has n, :tags, through: Resource
property :id, Serial
property :peep_msg, Text
property :peep_time, DateTime
property :user_id, Serial
end | 49ecbdce0d435e30bb6a84151bb54e7c871f9b6f | [
"Ruby"
] | 6 | Ruby | timoxman/chitter-challenge | 1ae2f6f0c8288e2c56813648d9c5662daafa3c36 | c5b682f8cb82502b2d7012e2f72bb07b1e20c83d |
refs/heads/master | <repo_name>ilyaborodin/GitHomework<file_sep>/main.py
print('Enter your name:')
x = input()
print("Hello brave new " + x)
print('How is the weather today?')
| b20674382b062335e7781056cd13dcd46113f0dd | [
"Python"
] | 1 | Python | ilyaborodin/GitHomework | 0ea98e31608d5a6b62be065a1044348bee5410d4 | 02ad0fe6502448fc70ac06f6ac1bf4dce8619fca |
refs/heads/main | <file_sep>package mehmethy.todo.data
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
object DataBaseInfo {
const val NAME = "tododb"
const val VERSION = 1
const val TODO_GROUP_TABLE_NAME = "todo_group"
const val TODO_GROUP_COLUMN_ID_NAME = "id"
const val TODO_GROUP_COLUMN_TITLE_NAME = "title"
const val TODO_TABLE_NAME = "todo"
const val TODO_COLUMN_ID_NAME = "id"
const val TODO_COLUMN_GROUP_ID_NAME = "groupId"
const val TODO_COLUMN_TITLE_NAME = "title"
const val TODO_COLUMN_DESCRIPTION_NAME = "description"
const val TODO_COLUMN_STATE_NAME = "state"
}
class DataBaseHelper(context: Context) : SQLiteOpenHelper(context, DataBaseInfo.NAME, null, DataBaseInfo.VERSION) {
override fun onCreate(db: SQLiteDatabase?) {
val createTodoGroupTableStatement =
"CREATE TABLE ${DataBaseInfo.TODO_GROUP_TABLE_NAME} (" +
"${DataBaseInfo.TODO_GROUP_COLUMN_ID_NAME} INTEGER PRIMARY KEY AUTOINCREMENT," +
"${DataBaseInfo.TODO_GROUP_COLUMN_TITLE_NAME} TEXT NOT NULL" +
");"
val createTodoTableStatement =
"CREATE TABLE ${DataBaseInfo.TODO_TABLE_NAME} (" +
"${DataBaseInfo.TODO_COLUMN_ID_NAME} INTEGER PRIMARY KEY AUTOINCREMENT," +
"${DataBaseInfo.TODO_COLUMN_GROUP_ID_NAME} INTEGER NOT NULL," +
"${DataBaseInfo.TODO_COLUMN_TITLE_NAME} TEXT NOT NULL," +
"${DataBaseInfo.TODO_COLUMN_DESCRIPTION_NAME} TEXT," +
"${DataBaseInfo.TODO_COLUMN_STATE_NAME} INTEGER NOT NULL" +
");"
db?.execSQL(createTodoGroupTableStatement)
db?.execSQL(createTodoTableStatement)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
TODO("Not yet implemented")
}
}<file_sep>package mehmethy.todo
import android.content.ContentValues
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.LinearLayout
import mehmethy.todo.data.DataBaseHelper
import mehmethy.todo.data.DataBaseInfo
import mehmethy.todo.dialogs.TodoGroupEditDialog
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val todoGroupList: LinearLayout? = findViewById(R.id.todo_main_menu_list)
val todoManager = TodoManager()
val loadButton = findViewById<Button>(R.id.todo_main_menu_load)
loadButton.setOnClickListener {
if (todoManager.activeTodoGroup != null) {
val intent = Intent(this, TodoActivity::class.java)
TodoManager.activeTodoGroupId = todoManager.activeTodoGroup?.getId()
startActivity(intent)
}
}
val newButton: Button? = findViewById(R.id.todo_main_menu_new)
newButton?.setOnClickListener {
val dataBaseHelper = DataBaseHelper(this)
val db = dataBaseHelper.writableDatabase
val cv = ContentValues()
cv.put(DataBaseInfo.TODO_GROUP_COLUMN_TITLE_NAME, getString(R.string.todo_default_title))
val id = db.insert(DataBaseInfo.TODO_GROUP_TABLE_NAME, null, cv)
val newTodoGroup = TodoGroup(this, todoManager, id)
todoGroupList?.addView(newTodoGroup.getView())
TodoGroupEditDialog(this, newTodoGroup::handleTodoEditDialog).show()
}
val deleteButton: Button? = findViewById(R.id.todo_main_menu_delete)
deleteButton?.setOnClickListener {
if (todoManager.activeTodoGroup != null) {
val dataBaseHelper = DataBaseHelper(this)
val db = dataBaseHelper.writableDatabase
db.delete(DataBaseInfo.TODO_TABLE_NAME, "${DataBaseInfo.TODO_COLUMN_GROUP_ID_NAME} = ${todoManager.activeTodoGroup?.getId()}", null)
db.delete(DataBaseInfo.TODO_GROUP_TABLE_NAME, "${DataBaseInfo.TODO_GROUP_COLUMN_ID_NAME} = ${todoManager.activeTodoGroup?.getId()}", null)
todoGroupList?.removeView(todoManager.activeTodoGroup?.getView())
todoManager.activeTodoGroup = null
}
}
populateTodoGroupList(todoGroupList, todoManager)
}
private fun populateTodoGroupList(list: LinearLayout?, todoManager: TodoManager) {
val dataBaseHelper = DataBaseHelper(this)
val db = dataBaseHelper.readableDatabase
val todoGroupQueryString = "SELECT * FROM ${DataBaseInfo.TODO_GROUP_TABLE_NAME}"
val todoGroupCursor = db.rawQuery(todoGroupQueryString, null)
if (todoGroupCursor.moveToFirst()) {
do {
val todoGroupId = todoGroupCursor.getLong(0)
val todoGroupTitle = todoGroupCursor.getString(1)
val todoGroup = TodoGroup(this, todoManager, todoGroupId, todoGroupTitle)
list?.addView(todoGroup.getView())
} while (todoGroupCursor.moveToNext())
todoGroupCursor.close()
}
}
}<file_sep>package mehmethy.todo.dialogs
import android.content.Context
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatDialog
class TodoGroupEditDialog(context: Context, private val confirmCallback: (String) -> Unit, private val defaultText: String = "") : AppCompatDialog(context) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(mehmethy.todo.R.layout.dialog_todo_group_edit)
val inputText: EditText? = findViewById(mehmethy.todo.R.id.todoGroupNameInput)
inputText?.setText(defaultText)
inputText?.selectAll()
val okButton: Button? = findViewById(mehmethy.todo.R.id.todoGroupConfirmButton)
okButton?.setOnClickListener {
confirmCallback(inputText?.text.toString())
this.dismiss()
}
val cancelButton: Button? = findViewById(mehmethy.todo.R.id.todoGroupCancelButton)
cancelButton?.setOnClickListener {
this.cancel()
}
}
}<file_sep>package mehmethy.todo
import android.content.ContentValues
import android.content.Context
import android.view.ContextThemeWrapper
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import mehmethy.todo.data.DataBaseHelper
import mehmethy.todo.data.DataBaseInfo
import mehmethy.todo.dialogs.TodoGroupEditDialog
class TodoGroup(private val context: Context, private val todoManager: TodoManager, private val id: Long, private var title: String = "") {
private val view: TextView
init {
if (title == "") {
title = context.getString(R.string.todo_default_title)
}
view = TextView(ContextThemeWrapper(context, R.style.TodoCommon_UIButton))
val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
params.setMargins(0, 4, 0, 4)
view.layoutParams = params
view.text = title
view.textAlignment = View.TEXT_ALIGNMENT_TEXT_START
view.setPadding(24, 8, 24, 8)
view.setOnClickListener {
activate()
}
view.setOnLongClickListener {
activate()
TodoGroupEditDialog(context, this::handleTodoEditDialog, title).show()
true
}
activate()
}
fun handleTodoEditDialog(text: String) {
if (text.isBlank()) {
return
}
title = text
view.text = title
val dataBaseHelper = DataBaseHelper(context)
val db = dataBaseHelper.writableDatabase
val cv = ContentValues()
cv.put(DataBaseInfo.TODO_GROUP_COLUMN_TITLE_NAME, title)
db.update(DataBaseInfo.TODO_GROUP_TABLE_NAME, cv, "${DataBaseInfo.TODO_GROUP_COLUMN_ID_NAME} = $id", null)
}
private fun activate() {
if (todoManager.activeTodoGroup == this) {
return
}
if (todoManager.activeTodoGroup != null) {
todoManager.activeTodoGroup?.deactivate()
}
todoManager.activeTodoGroup = this
view.isSelected = true
}
private fun deactivate() {
view.isSelected = false
}
fun getId(): Long {
return id
}
fun getView(): TextView = view
}<file_sep>package mehmethy.todo.dialogs
import android.content.Context
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatDialog
class TodoDescriptionDialog(context: Context, private val title: String = "", private val description: String = "") : AppCompatDialog(context) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(mehmethy.todo.R.layout.dialog_todo_description)
val titleView: TextView? = findViewById(mehmethy.todo.R.id.todo_description_dialog_title)
titleView?.text = title
val descriptionView: TextView? = findViewById(mehmethy.todo.R.id.todo_description_dialog_text)
descriptionView?.text = description
val closeButton: Button? = findViewById(mehmethy.todo.R.id.todo_description_close)
closeButton?.setOnClickListener {
this.dismiss()
}
}
}<file_sep>package mehmethy.todo.widget
import android.content.ContentValues
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.LinearLayout
import androidx.appcompat.content.res.AppCompatResources
import mehmethy.todo.TodoManager
import mehmethy.todo.data.DataBaseHelper
import mehmethy.todo.data.DataBaseInfo
import mehmethy.todo.dialogs.TodoDescriptionDialog
import mehmethy.todo.dialogs.TodoEditDialog
class TodoWidget(
private val context: Context,
parent: LinearLayout,
private val todoManager: TodoManager,
private val id: Long,
private val groupId: Long,
private var _title: String,
private var description: String = "",
_state: TodoState = TodoState.IN_PROGRESS
) {
private val bg: LinearLayout
private val stateButton: ImageButton
private var todoState = TodoState.IN_PROGRESS
private val titleButton: Button
private val descriptionButton: ImageButton
init {
bg = buildContainer()
stateButton = buildStateButton()
descriptionButton = buildNoteButton()
titleButton = buildTitleButton()
bg.addView(stateButton)
bg.addView(descriptionButton)
bg.addView(titleButton)
parent.addView(bg)
if (_title.isBlank()) {
_title = context.getString(mehmethy.todo.R.string.todo_default_title)
}
titleButton.text = _title
setState(_state)
}
fun getView(): LinearLayout = bg
fun getTitleText() = titleButton.text.toString()
private fun getDescriptionText() = description
private fun setState(state: TodoState) {
val dataBaseHelper = DataBaseHelper(context)
val db = dataBaseHelper.writableDatabase
val cv = ContentValues()
val stateLong: Long =
when (state) {
TodoState.IN_PROGRESS -> 0
TodoState.COMPLETED -> 1
TodoState.NOT_STARTED -> 2
}
cv.put(DataBaseInfo.TODO_COLUMN_STATE_NAME, stateLong)
db.update(DataBaseInfo.TODO_TABLE_NAME, cv, "${DataBaseInfo.TODO_COLUMN_ID_NAME} = $id", null)
when (state) {
TodoState.IN_PROGRESS -> {
val id = mehmethy.todo.R.drawable.progress_icon
val drawable: Drawable? = AppCompatResources.getDrawable(context, id)
stateButton.setImageDrawable(drawable)
todoState = TodoState.IN_PROGRESS
}
TodoState.COMPLETED -> {
val id = mehmethy.todo.R.drawable.completed_icon
val drawable: Drawable? = AppCompatResources.getDrawable(context, id)
stateButton.setImageDrawable(drawable)
todoState = TodoState.COMPLETED
}
TodoState.NOT_STARTED -> {
val id = mehmethy.todo.R.drawable.not_started_icon
val drawable: Drawable? = AppCompatResources.getDrawable(context, id)
stateButton.setImageDrawable(drawable)
todoState = TodoState.NOT_STARTED
}
}
}
fun handleEditConfirm(title: String, _description: String) {
if (title.isBlank()) {
return
}
titleButton.text = title
description = _description
val dataBaseHelper = DataBaseHelper(context)
val db = dataBaseHelper.writableDatabase
val cv = ContentValues()
cv.put(DataBaseInfo.TODO_COLUMN_TITLE_NAME, title)
cv.put(DataBaseInfo.TODO_COLUMN_DESCRIPTION_NAME, description)
db.update(DataBaseInfo.TODO_TABLE_NAME, cv, "${DataBaseInfo.TODO_COLUMN_ID_NAME} = $id", null)
}
fun activate() {
if (todoManager.activeTodoWidget == this) {
return
}
bg.isSelected = true
todoManager.activeTodoWidget?.deactivate()
todoManager.activeTodoWidget = this
}
private fun deactivate() {
bg.isSelected = false
todoManager.activeTodoWidget = null
}
private fun changeState() {
when (todoState) {
TodoState.IN_PROGRESS -> {
setState(TodoState.COMPLETED)
}
TodoState.COMPLETED -> {
setState(TodoState.NOT_STARTED)
}
TodoState.NOT_STARTED -> {
setState(TodoState.IN_PROGRESS)
}
}
}
private fun buildContainer(): LinearLayout {
val params = LinearLayout.LayoutParams(
ViewGroup.MarginLayoutParams(
ViewGroup.MarginLayoutParams.MATCH_PARENT,
ViewGroup.MarginLayoutParams.WRAP_CONTENT
)
)
params.setMargins(16, 4, 16, 4)
val layout = LinearLayout(context)
layout.layoutParams = params
layout.setBackgroundResource(mehmethy.todo.R.drawable.todo_widget_bg)
layout.setPadding(8, 8, 8, 8)
return layout
}
private fun buildStateButton(): ImageButton {
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
params.setMargins(0, 0, 8, 0)
val button = ImageButton(context)
button.layoutParams = params
val id = mehmethy.todo.R.drawable.progress_icon
val drawable: Drawable? = AppCompatResources.getDrawable(context, id)
button.setImageDrawable(drawable)
button.setBackgroundResource(mehmethy.todo.R.drawable.todo_widget_button)
button.setPadding(16, 16, 16, 16)
button.setOnClickListener {
activate()
changeState()
}
return button
}
private fun buildNoteButton(): ImageButton {
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
params.setMargins(0, 0, 8, 0)
val button = ImageButton(context)
button.layoutParams = params
val id = mehmethy.todo.R.drawable.note_icon
val drawable: Drawable? = AppCompatResources.getDrawable(context, id)
button.setImageDrawable(drawable)
button.setBackgroundResource(mehmethy.todo.R.drawable.todo_widget_button)
button.setPadding(16, 16, 16, 16)
button.setOnClickListener {
activate()
TodoDescriptionDialog(context, titleButton.text.toString(), getDescriptionText()).show()
}
return button
}
private fun buildTitleButton(): Button {
val button = Button(context)
button.text = context.getString(mehmethy.todo.R.string.todo_title_label)
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
params.weight = 1.0f
button.layoutParams = params
button.setBackgroundResource(mehmethy.todo.R.drawable.todo_widget_button)
button.textAlignment = View.TEXT_ALIGNMENT_CENTER
button.setOnClickListener { activate() }
button.setOnLongClickListener {
TodoEditDialog(
context,
::handleEditConfirm,
getTitleText(),
getDescriptionText()
).show()
true
}
return button
}
fun getId() = id
fun getGroupId() = groupId
}
<file_sep>package mehmethy.todo.dialogs
import android.content.Context
import android.os.Bundle
import android.view.Window
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatDialog
class TodoEditDialog(
context: Context,
private val confirmCallback: (String, String) -> Unit,
private var initTitle: String = "",
private var initDescription: String = ""
) : AppCompatDialog(context) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_NO_TITLE)
setContentView(mehmethy.todo.R.layout.dialog_todo_edit)
val titleInput: EditText = findViewById(mehmethy.todo.R.id.todo_edit_title_input)!!
titleInput.setText(initTitle)
titleInput.setOnFocusChangeListener { _, _ -> titleInput.selectAll() }
val descriptionInput: EditText? =
findViewById(mehmethy.todo.R.id.todo_edit_description_input)
descriptionInput?.setText(initDescription)
val okButton: Button? = findViewById(mehmethy.todo.R.id.todo_edit_ok_button)
okButton?.setOnClickListener {
confirmCallback(titleInput.text.toString(), descriptionInput?.text.toString())
this.dismiss()
}
val cancelButton: Button? = findViewById(mehmethy.todo.R.id.todo_edit_cancel_button)
cancelButton?.setOnClickListener {
this.cancel()
}
setOnShowListener {
titleInput.requestFocus()
}
}
}<file_sep>package mehmethy.todo
import android.content.ContentValues
import android.os.Bundle
import android.widget.Button
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import mehmethy.todo.data.DataBaseHelper
import mehmethy.todo.data.DataBaseInfo
import mehmethy.todo.dialogs.TodoEditDialog
import mehmethy.todo.widget.TodoState
import mehmethy.todo.widget.TodoWidget
class TodoActivity : AppCompatActivity() {
private val todoContainer: LinearLayout by lazy(LazyThreadSafetyMode.NONE) { findViewById(R.id.todoContainer) }
private val todoList: MutableList<TodoWidget> = mutableListOf()
private val todoManager = TodoManager()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_todo)
val addButton = findViewById<Button>(R.id.addButton)
addButton.setOnClickListener {
val dataBaseHelper = DataBaseHelper(this)
val db = dataBaseHelper.writableDatabase
val cv = ContentValues()
cv.put(DataBaseInfo.TODO_COLUMN_GROUP_ID_NAME, TodoManager.activeTodoGroupId)
cv.put(DataBaseInfo.TODO_COLUMN_TITLE_NAME, getString(R.string.todo_default_title))
cv.put(DataBaseInfo.TODO_COLUMN_DESCRIPTION_NAME, "")
cv.put(DataBaseInfo.TODO_COLUMN_STATE_NAME, 0)
val newId = db.insert(DataBaseInfo.TODO_TABLE_NAME, null, cv)
val widget = TodoWidget(
this,
todoContainer,
todoManager,
newId,
TodoManager.activeTodoGroupId!!,
getString(R.string.todo_default_title)
)
widget.activate()
todoList.add(widget)
TodoEditDialog(this, widget::handleEditConfirm, widget.getTitleText()).show()
}
val deleteButton = findViewById<Button>(R.id.deleteButton)
deleteButton.setOnClickListener {
val dataBaseHelper = DataBaseHelper(this)
val db = dataBaseHelper.writableDatabase
db.delete(
DataBaseInfo.TODO_TABLE_NAME,
"${DataBaseInfo.TODO_COLUMN_ID_NAME} = ${todoManager.activeTodoWidget?.getId()}",
null
)
todoContainer.removeView(todoManager.activeTodoWidget?.getView())
}
populateContainer(todoContainer, todoManager)
}
private fun populateContainer(container: LinearLayout, todoManager: TodoManager) {
val dataBaseHelper = DataBaseHelper(this)
val db = dataBaseHelper.readableDatabase
val queryString =
"SELECT * FROM ${DataBaseInfo.TODO_TABLE_NAME} WHERE ${DataBaseInfo.TODO_COLUMN_GROUP_ID_NAME} = ${TodoManager.activeTodoGroupId}"
val cursor = db.rawQuery(queryString, null)
if (cursor.moveToFirst()) {
do {
val id = cursor.getLong(0)
val groupId = TodoManager.activeTodoGroupId
val title = cursor.getString(2)
val description = cursor.getString(3)
val state =
when (cursor.getInt(4)) {
1 -> TodoState.COMPLETED
2 -> TodoState.NOT_STARTED
else -> TodoState.IN_PROGRESS
}
TodoWidget(
this,
container,
todoManager,
id,
groupId!!,
title,
description,
state
)
} while (cursor.moveToNext())
cursor.close()
}
}
}<file_sep>package mehmethy.todo.widget
enum class TodoState {
IN_PROGRESS,
COMPLETED,
NOT_STARTED
}<file_sep>package mehmethy.todo
import mehmethy.todo.widget.TodoWidget
class TodoManager {
private var _activeTodoWidget: TodoWidget? = null
var activeTodoWidget: TodoWidget?
get() = _activeTodoWidget
set(value) {
_activeTodoWidget = value
}
var activeTodoGroup: TodoGroup? = null
companion object {
var activeTodoGroupId: Long? = null
}
}
<file_sep># Android Todo App
A simple todo app for Android 4.4.2 KitKat and above.
<br>
<span>
<img src="https://raw.githubusercontent.com/MehmetHY/AndroidToDoApp/screenshots/todo01.jpg" width="360">
<img src="https://raw.githubusercontent.com/MehmetHY/AndroidToDoApp/screenshots/todo02.jpg" width="360">
</span> | 79546a35d1b0e5dfeaf4169ce11e19a090c975c4 | [
"Markdown",
"Kotlin"
] | 11 | Kotlin | MehmetHY/AndroidToDoApp | 2ba02e828c5531bf744bda1c12e02e703a73301c | 62ab1ca0462668d5b00085157d630331af84493d |
refs/heads/main | <file_sep>{
console.log('10.1.Rozgrzewka');
{
console.log('Ćwiczenie 1.1');
{
const names = ['Kasia', 'Tomek', 'Amanda', 'Maja'];
const newNames = [];
for (const singlNameId in names) {
const singlNameLastLetter = names[singlNameId].charAt((names[singlNameId].length - 1));
if (singlNameLastLetter === "a") newNames.push(names[singlNameId]);
};
console.log('Wynik zadania to:', newNames);
}
//
//
console.log('Ćwiczenie 1.2');
{
const employees = {
john: {
name: '<NAME>',
salary: 3000
},
amanda: {
name: '<NAME>',
salary: 4000
},
}
let employeesNames = [];
let employeesSalaries = [];
for (const singlEmployee in employees) {
const singlName = employees[singlEmployee].name.split(" ", 1);
const singlSalary = employees[singlEmployee].salary;
employeesNames.push(singlName);
employeesSalaries.push(singlSalary);
}
console.log('names: ', employeesNames, 'salaries: ', employeesSalaries);
}
//
//
console.log('Ćwiczenie 1.3');
{
const salaries = [2000, 3000, 1500, 6000, 3000];
function sum(total, number) {
return total + number;
}
console.log('sum: ', salaries.reduce(sum));
console.log('max: ', Math.max(...salaries));
console.log('min: ', Math.min(...salaries));
}
//
//
console.log('Ćwiczenie 1.4');
{
const persons = {
john: 2000,
amanda: 3000,
thomas: 1500,
james: 6000,
claire: 3000
};
let sum = 0;
let max = 0;
for (const singlPerson in persons) {
sum += persons[singlPerson];
if (persons[singlPerson] > max) max = persons[singlPerson];
}
const min = Math.min(...Object.values(persons));
console.log('sum: ', sum);
console.log('max: ', max);
console.log('min: ', min);
}
//
//
console.log('Ćwiczenie 1.5');
{
const tags = ['news', 'code', 'news', 'sport', 'hot', 'news', 'code'];
const uniqueTags = {};
for (const singlTag of tags) {
if (!uniqueTags[singlTag]) uniqueTags[singlTag] = { appearance: 1 };
else uniqueTags[singlTag].appearance++;
};
console.log(uniqueTags);
}
}
{
console.log('Ćwiczenie 2.4');
const employees = [
{ name: '<NAME>', salary: 3000 },
{ name: '<NAME>', salary: 4000 },
{ name: '<NAME>', salary: 2000 },
{ name: '<NAME>', salary: 6000 },
{ name: '<NAME>', salary: 8200 }
];
function filterEmployees(allEmployees, minSalary, maxSalary) {
const filteredEmpl = [];
for (const singlEmployee of allEmployees) {
if (singlEmployee.salary > minSalary && singlEmployee.salary < maxSalary) {
filteredEmpl.push(singlEmployee);
}
}
console.log(filteredEmpl);
};
filterEmployees(employees, 2000, 8200);
}
{
console.log('Ćwiczenie 2.5');
const obj = {
firstName: 'John',
lastName: 'Doe'
}
const details = function (arg) {
for (const singlEl in obj) {
console.log(singlEl + ': ' + obj[singlEl]);
}
}
details(obj);
}
{
console.log('Ćwiczenie 2.6');
const forEach = function (arr, callback) {
for (const singlEl of arr) {
callback(singlEl);
}
};
const arrEx = ['John', 'Tom', 'Marry'];
forEach(arrEx, function (item) { console.log(item); });
}
{
console.log('Ćwiczenie 2.7');
const formatName = function (name) {
const givenName = name.split(" ");
const firstName = givenName[0];
const lastName = givenName[1];
const convertedFirstName = firstName.charAt(0).toUpperCase() + firstName.substring(1).toLowerCase();
const convertedLastName = lastName.charAt(0).toUpperCase() + lastName.substring(1).toLowerCase();
console.log(convertedFirstName + " " + convertedLastName);
}
formatName('<NAME>');
}
{
console.log('Ćwiczenie 2.8');
const getEvensInRange = function (checkStart, checkStop) {
const evens = [];
for (let i = 0; i <= checkStop; i++) {
if (checkStart + i % 2 == 0) evens.push(checkStart + i);
}
console.log(evens);
}
getEvensInRange(0, 5);
}
{
console.log('Ćwiczenie 2.9');
const filter = function (arr, call) {
let newArr = [];
for (const arrId of arr) {
if (call(arrId) == true) newArr.push(arrId);
}
console.log(newArr);
}
filter([5, 6, 7], function (item) { return item % 2 === 0 });
}
}
| 4904a4dd3f9babe5c6856bd27e5504b877100ae8 | [
"JavaScript"
] | 1 | JavaScript | MarcinZajecki/JS-Exercises | 9cfd33b974041f6ac9474b56f336be512f215c50 | ea6c197a4c17566c77151adc3cb49a31ebdad157 |
refs/heads/master | <repo_name>Michal-Atlas/DawnStorm-TextAdventure<file_sep>/dawnstorm-textfront/src/parser/sysexec.rs
use dawnstorm_core::{entity::Entity, syscall::SysCall, world::World};
pub fn sys_exec(call: SysCall, _player: &mut Entity, world: &mut World, current_node: &mut String) {
println!("{:?}", call);
match call {
SysCall::Move(target) => {
*current_node = target;
println!("{}", &world[current_node.as_str()]);
}
SysCall::Print(msg) => println!("{}", msg),
_ => {}
}
}
<file_sep>/dawnstorm-core/src/profession.rs
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Profession {
pub xp: u8,
pub tier: u8,
pub profession: ProfessionEnum,
}
impl Profession {}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProfessionEnum {
Fighter,
Recruit,
Squire,
Hunter,
Herbalist,
Noble,
Thief,
}
<file_sep>/dawnstorm-core/src/lib.rs
pub mod dataload;
pub mod entity;
pub mod item;
pub mod load_methods;
pub mod profession;
pub mod savegame;
pub mod syscall;
pub mod world;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
<file_sep>/dawnstorm-core/Cargo.toml
[package]
name = "dawnstorm-core"
version = "0.2.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
derive_more = "0.99.14"
lazy_static = "1.4.0"
phf = { version = "0.8.0", features = ["macros"] }
serde = { version = "1.0.126", features = ["derive"] }
serde_json = "1.0.64"
toml = "0.5.8"
<file_sep>/dawnstorm-core/src/savegame.rs
use crate::entity::Entity;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct SaveGame {
pub player: Entity,
}
<file_sep>/dawnstorm-core/src/dataload.rs
use crate::world::Node;
use lazy_static::lazy_static;
use serde_json::from_str;
use std::collections::HashMap;
use std::include_str;
/// Loads a list of Json Files containing Map Nodes into a HashMa
/// TODO: Find out how to use a PHF instead
macro_rules! load_map {
($($x:literal),+) => {
{let mut m = HashMap::new();
$(
m.insert($x, from_str(include_str!(concat!("../../data/map/",$x,".json"))).expect(format!("There was an issue in the '{}.json' file", $x).as_str()));
)+
m
}};
}
lazy_static! {
pub static ref WORLD_MAP: HashMap<&'static str, Node> = load_map! {
"main",
"castle_path"
};
}
<file_sep>/dawnstorm-core/src/entity.rs
use crate::item::Item;
use crate::profession::Profession;
use derive_more::Display;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Serialize, Deserialize)]
pub struct Entity {
pub body: Stat,
pub soul: Stat,
pub influence: Stat,
pub size: Size,
pub professions: Vec<Profession>,
pub flags: HashMap<String, bool>,
pub inventory: Vec<Item>,
pub abilities: Vec<Ability>,
}
impl Entity {
pub fn sleep(&mut self, hours: u8) {
self.body.sleep(hours);
self.soul.sleep(hours);
self.influence.sleep(hours);
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Stat {
pub max: u8,
pub spent: u8,
}
impl Stat {
pub fn new(max: u8) -> Self {
Self { max, spent: 0 }
}
pub fn sleep(&mut self, hours: u8) {
let divisor = match hours {
1..=3 => 4,
4..=7 => 2,
8..=255 => 1,
_ => return,
};
self.spent = self.spent.saturating_sub(self.max / divisor);
}
}
#[derive(Debug, Display, Serialize, Deserialize)]
pub enum Size {
Scrawny,
Tiny,
Small,
Normal,
Large,
Huge,
Giant,
Colossal,
Immense,
Primal,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum Ability {}
<file_sep>/dawnstorm-core/src/world.rs
use crate::syscall::{Command, SysCall};
use core::fmt;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::Display;
pub type World = HashMap<&'static str, Node>;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Node {
pub description: String,
pub aliases: Vec<String>,
pub children: Option<Vec<Node>>,
pub commands: HashMap<Command, SysCall>,
}
impl Display for Node {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.description.is_empty() {
write!(f, "{} ", self.description)?;
}
if self.children.is_some() {
for c in self.children.as_ref().unwrap() {
write!(f, "{}", c)?;
}
}
Ok(())
}
}
<file_sep>/dawnstorm-textfront/src/main.rs
mod create_character;
mod parser;
use colored::*;
use create_character::create_character;
use dawnstorm_core::dataload::WORLD_MAP;
use parser::parser;
use rustyline::{error::ReadlineError, Editor};
fn main() {
let mut world = WORLD_MAP.clone();
let mut current_room = String::from("main");
let player = create_character();
if player.is_none() {
return;
}
let mut player = player.unwrap();
let mut rl = Editor::<()>::new();
loop {
let line = rl.readline(">> ");
match line {
Ok(l) => {
rl.add_history_entry(l.as_str());
match l.as_str() {
"exit" => break,
"look around" => println!("{}", &world[current_room.as_str()]),
_ => {
parser(&mut player, &mut world, &mut current_room, &l);
}
}
}
Err(ReadlineError::Eof) => {
println!("{}", "Sorry to see you go".bright_red().bold());
break;
}
_ => {
panic!("Error in Parsing")
}
}
}
}
<file_sep>/dawnstorm-textfront/src/parser.rs
use dawnstorm_core::{entity::Entity, syscall::Command, world::World};
mod search;
mod sysexec;
use search::room_search;
use sysexec::sys_exec;
pub fn parser(player: &mut Entity, world: &mut World, current_node: &mut String, command: &str) {
let mut input = command.split_whitespace();
let command = input.next();
// Transform str to Command Enum
let command = match command {
Some(command) => {
if COMMAND_ALIASES.contains_key(command) {
COMMAND_ALIASES[command].clone()
} else {
println!("I don't know that verb");
return;
}
}
None => return,
};
// Search verb to apply verb on
match room_search(
&world[current_node.as_str()],
&input
.map(|x| x.to_string().to_lowercase())
.collect::<Vec<_>>()
.as_slice(),
) {
Some(s) => {
// If the object has the associated Action
if s.commands.contains_key(&command) {
// Execute it
sys_exec(s.commands[&command].clone(), player, world, current_node);
} else {
println!("I'm not sure how to do that");
}
}
None => println!("Can't find the object you were looking for."),
}
}
const COMMAND_ALIASES: phf::Map<&'static str, Command> = phf::phf_map! {
"move" => Command::Move,
"m" => Command::Move,
"walk" => Command::Move,
"talk" => Command::Talk,
"ask" => Command::Talk,
"look" => Command::Look,
"watch" => Command::Look,
};
<file_sep>/dawnstorm-textfront/Cargo.toml
[package]
name = "dawnstorm-textfront"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
colored = "2.0.0"
dawnstorm-core = { version = "0.2.0", path = "../dawnstorm-core" }
phf = "0.8.0"
rustyline = "8.0.0"
<file_sep>/dawnstorm-core/src/item.rs
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Item {
pub name: String,
pub r#type: ItemType,
pub major: bool,
pub makeshift: bool,
}
#[derive(Debug, Deserialize, Serialize)]
pub enum ItemType {
Misc,
Weapon(WeaponType),
}
#[derive(Debug, Deserialize, Serialize)]
pub enum WeaponType {
Slashing,
ShortSlashing,
Blunt,
Piercing,
Short,
Long,
Shield,
}
<file_sep>/dawnstorm-core/src/load_methods.rs
use crate::savegame::SaveGame;
use std::{fs::File, io::Write};
pub fn save_game(save_path: &str, save_game: SaveGame) -> Result<(), serde_json::Error> {
let mut f = File::open(save_path).expect("No Player Found in Data Directory");
f.write_all(serde_json::to_string(&save_game)?.as_bytes())
.unwrap();
Ok(())
}
<file_sep>/Cargo.toml
[workspace]
members = ["dawnstorm-textfront", "dawnstorm-core"]
<file_sep>/dawnstorm-textfront/src/parser/search.rs
use dawnstorm_core::world::Node;
/// Searches for the most relevant child of the given node
/// by the query.
/// Checks recursively if the returned result has a relevant child,
/// if yes, returns the child.
pub fn room_search<'a>(item: &'a Node, query: &[String]) -> Option<&'a Node> {
let mut acc_max = 0;
let mut ret = None;
for n in item.children.as_ref()? {
let mut curr_max = 0;
for q in query {
if n.aliases.contains(&q) {
curr_max += 1;
}
}
if curr_max > acc_max {
acc_max = curr_max;
ret = Some(n);
}
}
if let Some(s) = room_search(ret?, query) {
return Some(s);
}
ret
}
<file_sep>/dawnstorm-core/src/syscall.rs
use crate::profession::ProfessionEnum;
use serde::{Deserialize, Serialize};
/// An action that using a Verb on a Node causes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SysCall {
Move(String),
Call(Box<SysCall>, Box<SysCall>),
Print(String),
/// Contains a list of which professions give a bonus to the check
/// Then what to do on success and then on failure
SkillCheck(Vec<ProfessionEnum>, Box<SysCall>, Box<SysCall>),
}
/// The Verb of the player's Input
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum Command {
Move,
Look,
Talk,
}
<file_sep>/dawnstorm-textfront/src/create_character.rs
use dawnstorm_core::entity::{Entity, Size, Stat};
use std::collections::HashMap;
#[allow(unused_macros)]
macro_rules! get_stat {
($name:expr, $var:expr) => {
let mut rl = Editor::<()>::new();
loop {
match rl.readline(format!("{} > ", $name).as_str()) {
Ok(l) => {
let l = l.parse();
if l.is_err() {
continue;
}
$var = l.unwrap();
break;
}
Err(ReadlineError::Eof) => {
println!("{}", "Sorry to see you go".bright_red().bold());
return None;
}
_ => {}
}
}
};
}
pub fn create_character() -> Option<Entity> {
let player = Entity {
body: Stat::new(5),
soul: Stat::new(5),
influence: Stat::new(5),
size: Size::Normal,
professions: Vec::new(),
flags: HashMap::new(),
inventory: Vec::new(),
abilities: Vec::new(),
};
/*get_stat!("Strength", player.body.max);
get_stat!("Intelligence", player.soul.max);
get_stat!("Charisma", player.influence.max);
println!(
"Your power level is {}, the recommended level is between 15 and 20",
player.body.max + player.soul.max + player.influence.max
);*/
Some(player)
}
| cee5b09f879d345d908529f53fdb4fbf67c8c28e | [
"TOML",
"Rust"
] | 17 | Rust | Michal-Atlas/DawnStorm-TextAdventure | f18adab2efabd7ed9d957a3f4def16ef2ef4b0e3 | b5e46349610e3a351638dabb9937281d64abd438 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UIApp.Models
{
public class VehicleVM
{
private string _lat;
public string lat
{
get { return _lat; }
set { _lat = value; }
}
private string _lon;
public string lon
{
get { return _lon; }
set { _lon = value; }
}
private int _sd;
public int sd
{
get { return _sd; }
set { _sd = value; }
}
private string _hd;
public string hd
{
get { return _hd; }
set { _hd = value; }
}
private string _time;
public string time
{
get { return _time; }
set { _time = value; }
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using Newtonsoft.Json;
using System.Text;
using UIApp.Models;
namespace UIApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult ackSample()
{
return View();
}
public ActionResult Sample()
{
return View();
}
[HttpPost]
public ActionResult SamplePost()
{
string[] Vehicle = ConfigurationManager.AppSettings["VehicleLocation"].Split('~').Select(s => s.Trim()).ToArray();
for (int i = 0; i <= Vehicle.Length - 1; i++)
{
string vehicleparam = Vehicle[i].ToString();
var Client = new HttpClient();
//Client.BaseAddress = new Uri("http://localhost:64103/");
Client.BaseAddress = new Uri("http://postapitest.azurewebsites.net/");
string serurl = "api/Test/Insert?param=" + vehicleparam;
var conresponse = Client.PostAsync(serurl,
new StringContent(JsonConvert.SerializeObject(vehicleparam).ToString(),
Encoding.UTF8, "application/json"));
var res = conresponse.Result;
if (res.IsSuccessStatusCode)
{
dynamic concontent = JsonConvert.DeserializeObject(
res.Content.ReadAsStringAsync()
.Result);
TempData["content"] = concontent;
// Access variables from the returned JSON object
//var appHref = concontent.links.applications.href;
}
}
return RedirectToAction("ackSample");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UIApp.Models
{
public class Vehicle
{
private string _number;
public string vin
{
get { return _number; }
set { _number = value; }
}
public List<VehicleVM> fcd { get; set; }
}
} | a1617b7bc4a09579ee760b8aae6f2b73fdf7a16b | [
"C#"
] | 3 | C# | Saravanagopi/UIApp | 8ada5bd9a713f54fa9dbd68170d57e1d0953ac14 | 35a8137a969eb4fcba88301d804981a742913fea |
refs/heads/main | <file_sep>import React from "react";
import { useSelector } from "react-redux";
import FlightCard from "../FlightCards/FlightCard";
import styles from "./InfoBox.module.css";
const InfoBox = ({ flightData }) => {
const { data, isLoading } = useSelector((state) => state.search);
console.log(data);
return (
<div className={styles.mainContainer}>
<div className={styles.flightInfoBanner}>
<div className={styles.flightInfoBanner_destination}>
{flightData?.origin_city === undefined ||
flightData?.origin_city === "" ? (
<h2>Select Origin and Destination City</h2>
) : (
<>
{" "}
{flightData?.one_way ? (
<h2>{`${flightData?.origin_city} > ${flightData?.dest_city} > ${flightData?.origin_city}`}</h2>
) : (
<h2>{`${flightData?.origin_city} > ${flightData?.dest_city}`}</h2>
)}
</>
)}
</div>
<div className={styles.flightInfoBanner_date}>
{flightData?.start_date && (
<>
<p>{`Depart: ${flightData?.string_date}`}</p>
{flightData?.one_way && (
<p>{`Return: ${flightData?.e_str_date}`}</p>
)}
</>
)}
</div>
</div>
<div className={styles.cardContainer}>
{isLoading ? (
<div>
<img
src="https://media0.giphy.com/media/3oEjI6SIIHBdRxXI40/200.gif"
alt="Loadong"
/>
</div>
) : data == "" ? (
<strong className={styles.errorMsg}>
No Results Found. Please try another date...
</strong>
) : (
data?.map((el) => (
<FlightCard key={el.id} el={el} flightData={flightData} />
))
)}
</div>
</div>
);
};
export default InfoBox;
<file_sep>import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import "./style.css";
export default function App({
setStartDate,
setEndDate,
startDate,
endDate,
oneway,
}) {
return (
<>
<div>
<DatePicker
selected={startDate}
placeholderText="Departure Date"
calendarClassName="red-border"
dateFormat="dd/MM/yyyy"
selectsStart
startDate={startDate}
minDate={new Date()}
endDate={endDate}
onChange={(date) => setStartDate(date)}
/>
{!oneway && (
<DatePicker
selected={endDate}
placeholderText="Return Date"
calendarClassName="red-border"
dateFormat="dd/MM/yyyy"
selectsEnd
startDate={startDate}
endDate={endDate}
minDate={startDate}
onChange={(date) => setEndDate(date)}
/>
)}
</div>
</>
);
}
<file_sep>import {GET_SEARCH_REQUEST, GET_SEARCH_SUCCESS, GET_SEARCH_FAILURE} from "./actionType"
const initState = {
data: undefined,
isLoading: false,
isError: false
}
export const SearchReducer = (state=initState, action) => {
switch(action.type){
case GET_SEARCH_REQUEST:{
return{
...state,
isLoading: true,
isError: false
}
}
case GET_SEARCH_SUCCESS:{
return{
...state,
data: action.payload,
isLoading: false
}
}
case GET_SEARCH_FAILURE:{
return{
...state,
isLoading: false,
isError: true
}
}
default: return state
}
}<file_sep>export const GET_FILTER_SUCCESS = "GET_FILTER_SUCCESS"<file_sep>import {GET_SEARCH_REQUEST, GET_SEARCH_SUCCESS, GET_SEARCH_FAILURE} from "./actionType"
import axios from "axios"
const getSearch = (payload) => (dispatch) => {
if(payload !== undefined){
const search_req = search_request()
dispatch(search_req)
axios.get(`https://metta-social-assign.herokuapp.com/flights?Departure_Date=${payload.start_date}&Origin_City=${payload.origin_city}&Destination_City=${payload.dest_city}`)
.then(resp => {
const success_req = search_success(resp.data)
dispatch(success_req)
})
.catch(err => {
const failure_req = search_failure()
dispatch(failure_req)
})
}
}
const getReturnSearch = (payload) => (dispatch) => {
if(payload !== undefined){
const search_req = search_request()
dispatch(search_req)
axios.get(`https://metta-social-assign.herokuapp.com/flights?Departure_Date=${payload.start_date}&Return_Date=${payload.end_date}&Origin_City=${payload.origin_city}&Destination_City=${payload.dest_city}`)
.then(resp => {
const success_req = search_success(resp.data)
dispatch(success_req)
})
.catch(err => {
const failure_req = search_failure()
dispatch(failure_req)
})
}
}
const search_request = () => {
return{
type: GET_SEARCH_REQUEST
}
}
const search_success = (payload) => {
return{
type: GET_SEARCH_SUCCESS,
payload
}
}
const search_failure = () => {
return{
type: GET_SEARCH_FAILURE
}
}
export {getSearch, getReturnSearch}<file_sep>import React, { useState, useEffect } from "react";
import styles from "./Slider.module.css";
export default function Slider({ setPrice, price }) {
useEffect(() => {
const ele = document.querySelector(".buble");
if (ele) {
ele.style.left = `${Number(price / 4)}px`;
}
});
const handleChange = (e) => {
if (e.target.value === "") {
setPrice(1500);
}
setPrice(e.target.value);
};
return (
<div className={styles.slider_parent}>
<input
className={styles.slider_parent_slide}
type="range"
min="1500"
max="50000"
value={price}
onChange={({ target: { value: radius } }) => {
setPrice(radius);
}}
/>
<input type="number" placeholder={price} onChange={handleChange} />
</div>
);
}
<file_sep>import React from "react";
import styles from "./FlightCard.module.css";
const FlightCard = ({ el, flightData }) => {
return (
<div className={styles.card}>
<div className={styles.infoBox}>
<div className={styles.infoBox_amount}>
<span>
{flightData.one_way
? `RS. ${el.Price * flightData.passengers * 2}`
: `RS. ${el.Price * flightData.passengers}`}
</span>
</div>
<div className={styles.infoBox_bookDetails}>
<div className={styles.infoBox_bookDetails_left}>
<p>{el.Plane_code}</p>
<p>{`${el.City_Code_Origin} > ${el.City_Code_Destination}`}</p>
<p>{`Depart: ${el.Departure_Time}`}</p>
<p>{`Arrive: ${el.Arrival_Time}`}</p>
</div>
{flightData.one_way && (
<div className={styles.infoBox_bookDetails_right}>
<p>{el.Plane_code}</p>
<p>{`${el.City_Code_Destination} > ${el.City_Code_Origin}`}</p>
<p>{`Depart: ${el.Arrival_Time}`}</p>
<p>{`Arrive: ${el.Departure_Time}`}</p>
</div>
)}
</div>
</div>
<div className={styles.btnBox}>
<div className={styles.btnBox_img}>
<img className={styles.img} src={el.Image} alt="flight" />
</div>
<button className={styles.btnBox_btn}>Book this flight</button>
</div>
</div>
);
};
export default FlightCard;
<file_sep>export const GET_SEARCH_REQUEST = "GET_SEARCH_REQUEST"
export const GET_SEARCH_SUCCESS = "GET_SEARCH_SUCCESS"
export const GET_SEARCH_FAILURE = "GET_SEARCH_FAILURE"<file_sep>import React from "react";
import styles from "./FilterBox.module.css";
import { Tab, Tabs, TabList, TabPanel } from "react-tabs";
import "react-tabs/style/react-tabs.css";
import Slider from "../Slider/Slider";
import CalenderInput from "../CalenderInput/CalenderInput";
import { useDispatch } from "react-redux";
import { getFilter } from "../../Redux/Filter/action";
const FilterBox = () => {
const [oneway, setOneway] = React.useState(true);
let [returnway, setReturnway] = React.useState(false);
const [startDate, setStartDate] = React.useState(false);
const [endDate, setEndDate] = React.useState(false);
const [origin, setOrigin] = React.useState("");
const [destination, setDestination] = React.useState("");
const [pass, setPass] = React.useState(0);
const [price, setPrice] = React.useState(1500);
const dispatch = useDispatch();
const handleOChange = (e) => {
setOrigin(e.target.value);
};
const handleDChange = (e) => {
setDestination(e.target.value);
};
const handleDropChange = (e) => {
setPass(Number(e.target.value));
};
const handleSubmit = (e) => {
e.preventDefault();
setReturnway((returnway = false));
console.log(returnway + "t");
const sp = startDate.toString().trim().split(" ");
const ed = endDate.toString().trim().split(" ");
let start_num_month;
if (startDate) {
if (startDate.getMonth() <= 8) {
start_num_month = 0 + `${startDate.getMonth() + 1}`;
console.log(start_num_month);
} else {
start_num_month = startDate.getMonth() + 1;
}
}
let sDate = `${sp[2]}/${start_num_month}/${sp[3]}`;
let str_month = sp[1];
let StrDate = `${sp[2]} ${str_month} ${sp[3]}`;
let end_num_month;
if (endDate) {
if (endDate.getMonth() <= 8) {
end_num_month = 0 + `${endDate.getMonth() + 1}`;
} else {
end_num_month = endDate.getMonth() + 1;
}
}
let eDate = `${ed[2]}/${end_num_month}/${ed[3]}`;
let e_str_month = ed[1];
let e_StrDate = `${ed[2]} ${e_str_month} ${ed[3]}`;
const payload = {
origin_city: origin,
dest_city: destination,
passengers: pass,
start_date: sDate,
end_date: eDate,
price: price,
month_str: str_month,
string_date: StrDate,
e_month_str: e_str_month,
e_str_date: e_StrDate,
one_way: returnway,
};
console.log(returnway);
dispatch(getFilter(payload));
};
const handleSubmit2 = (e) => {
e.preventDefault();
setReturnway((returnway = true));
const sp = startDate.toString().trim().split(" ");
const ed = endDate.toString().trim().split(" ");
let start_num_month;
if (startDate) {
if (startDate.getMonth() <= 8) {
start_num_month = 0 + `${startDate.getMonth() + 1}`;
} else {
start_num_month = startDate.getMonth() + 1;
}
}
let sDate = `${sp[2]}/${start_num_month}/${sp[3]}`;
let str_month = sp[1];
let StrDate = `${sp[2]} ${str_month} ${sp[3]}`;
let end_num_month;
if (endDate) {
if (endDate.getMonth() <= 8) {
end_num_month = 0 + `${endDate.getMonth() + 1}`;
} else {
end_num_month = endDate.getMonth() + 1;
}
}
let eDate = `${ed[2]}/${end_num_month}/${ed[3]}`;
let e_str_month = ed[1];
let e_StrDate = `${ed[2]} ${e_str_month} ${ed[3]}`;
const payload = {
origin_city: origin,
dest_city: destination,
passengers: pass,
start_date: sDate,
end_date: eDate,
price: price,
month_str: str_month,
string_date: StrDate,
e_month_str: e_str_month,
e_str_date: e_StrDate,
one_way: returnway,
};
console.log(returnway);
dispatch(getFilter(payload));
};
return (
<div className={styles.mainContainer}>
<div className={styles.fromContainer}>
<Tabs style={{ marginTop: "10%" }}>
<TabList style={{ border: "none" }}>
<Tab>One-Way</Tab>
<Tab>Return</Tab>
</TabList>
<TabPanel
style={{
border: "1px solid #AAAAAA",
marginTop: "-2.5%",
padding: "10px",
}}
>
<form onSubmit={handleSubmit}>
<input
className={styles.inputBox}
placeholder="Enter Origin City"
onChange={handleOChange}
/>
<input
className={styles.inputBox}
placeholder="Enter Destination City"
onChange={handleDChange}
/>
<div className={styles.selectBox}>
<CalenderInput
oneway={oneway}
setStartDate={setStartDate}
setEndDate={setEndDate}
startDate={startDate}
endDate={endDate}
/>
</div>
<select
onChange={handleDropChange}
className={styles.selectBox_pass}
>
<option>Passengers</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<button className={styles.btn}>Search</button>
</form>
</TabPanel>
<TabPanel
style={{
border: "1px solid #AAAAAA",
marginTop: "-2.5%",
padding: "10px",
}}
>
<form onSubmit={handleSubmit2}>
<input
className={styles.inputBox}
placeholder="Enter Origin City"
onChange={handleOChange}
/>
<input
className={styles.inputBox}
placeholder="Enter Destination City"
onChange={handleDChange}
/>
<div className={styles.selectBox}>
<CalenderInput
setStartDate={setStartDate}
setEndDate={setEndDate}
startDate={startDate}
endDate={endDate}
/>
</div>
<select
onChange={handleDropChange}
className={styles.selectBox_pass}
>
<option>Passengers</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
<button className={styles.btn}>Search</button>
</form>
</TabPanel>
</Tabs>
<div className={styles.sliderContainer}>
<p>Refine flight search</p>
<Slider setPrice={setPrice} price={price} />
</div>
</div>
</div>
);
};
export default FilterBox;
<file_sep>import React from "react";
import FilterBox from "../FilterBox/FilterBox";
import InfoBox from "../InfoBox/InfoBox";
import styles from "./HomePage.module.css";
import { getSearch, getReturnSearch } from "../../Redux/Serach/action";
import { useSelector, useDispatch } from "react-redux";
const HomePage = () => {
const flightData = useSelector((state) => state.filter.data);
const dispatch = useDispatch();
dispatch(getSearch(flightData));
if (flightData?.returnway) {
dispatch(getReturnSearch(flightData));
}
return (
<>
<h2 className={styles.heading}>Flight Search Engine</h2>
<hr />
<div className={styles.mainContainer}>
<FilterBox />
<InfoBox flightData={flightData} />
</div>
</>
);
};
export default HomePage;
<file_sep># Metta Social Flight Booking Assignment
## Tech Stacks Used
- React for frontend
- Mock json server for backend
## Source
- React: [React](https://www.npmjs.com/package/react)
- Redux: [Redux](https://www.npmjs.com/package/redux)
- React-Redux: [React-Redux](https://www.npmjs.com/package/react-redux)
- Redux-thunks: [Redux-thunks](https://www.npmjs.com/package/thunks)
- Axios: [Axios](https://www.npmjs.com/package/axios)
## How to run the project 📑
## For Front-end
1.Clone the repo using https://github.com/Vinesh3124/Metta_Social_Assignment.git.
2.Open the front-end folder and run the command npm i and then npm run start in terminal to start the app.
3.Go to the browser you will land in the landing page just Register and login if you have signed up before or do the signup.
## Usage instruction
You can serach for flight for four cities (Pune, Delhi, Goa and Kochi). The flight date are available between 29/09/2021 till 30/10/2021.
## Limitations
- Responsiveness: App is responsive till 780px
- Payment Slider not yet implemented
Will be working on the project for adding the missing parts.
## Demo Link
React App: https://metta-social-assignment.vercel.app/
Mock Server Link: http://metta-social-assign.herokuapp.com/flights
## Sample Data to Search
### One-way
- Origin City: Goa
- Destination City: Pune
- Departure Date: 30/09/2021
## Return
- Origin City: Goa
- Destination City: Pune
- Departure Date: 29/09/2021
- Return Date: 01/10/2021
| 7dd37170bea937a849e6fd8069a656eddf04f152 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | Vinesh3124/Metta_Social_Assignment | 8964150e81d4c59484fa29490f8c02ff389e2c08 | 67758f102bad46f5c88eefaf89e459065d670d7f |
refs/heads/master | <file_sep>import pickle
from collections import Counter
from petapp.data_preprocess_util import dataArrange
from petapp import decision_tree_scratch, db
from petapp.models_db import Disease
def prediction(X_raw):
sympfile = open('symp_model','rb')
symp_list = pickle.load(sympfile)
infile = open('model','rb')
clf = pickle.load(infile)
encode_file = open('encode_model','rb')
encode = pickle.load(encode_file)
X = dataArrange(symp_list , X_raw)
X = [X]
pred_array = []
for count in range(10):
pred = (clf[count].predict(X))
pred = encode.inverse_transform(pred)
pred_array.append(pred[0])
counter = Counter(pred_array)
iterator = counter.most_common()
disease_prediction = []
for i in iterator:
probability = i[1]
probability/=10
probability *= 100
disease = Disease.query.filter_by(name=i[0]).first()
temp = { "disease" : disease.name,"id" : disease.id, "probability" : probability}
disease_prediction.append(temp)
return disease_prediction
infile.close
sympfile.close
encode_file.close
<file_sep>from flask import Flask
from flask_restful import Api
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
import petapp.decision_tree_scratch as decision_tree_scratch
app = Flask(__name__)
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
api = Api(app)
from petapp.routes import symptoms_return, predict
<file_sep>from petapp import db
from petapp.models_db import Disease
import pickle
from petapp.data_preprocess_util import del_duplicates_from_symptoms
def ini_db():
if (Disease.query.first() == None):
disease_obj_file = open('disease_obj_list','rb')
disease_obj_list = pickle.load(disease_obj_file)
for i in disease_obj_list:
symptom = del_duplicates_from_symptoms(i.selectionPool)
symptom_to_add = " ,".join(symptom)
to_add = Disease(name=i.name, symptoms=symptom_to_add)
db.session.add(to_add)
db.session.commit()
<file_sep>from flask import jsonify, request
from flask_restful import Resource
import pickle
from petapp.prediction import prediction
from petapp.data_preprocess_util import symp_process
from petapp import api, db
from petapp.models_db import Disease
sympfile = open('symp_list_to_send','rb')
symp_list = pickle.load(sympfile)
diction ={
"symptoms" : symp_list
}
class symptoms_return(Resource):
def get(self):
return jsonify(diction)
class predict(Resource):
def post(self):
symptoms = request.json['symptoms']
trainable_symptoms = []
for i in symptoms:
temp = symp_process(i)
trainable_symptoms.append(temp)
disease = prediction(trainable_symptoms)
predicted = {"prediction" : disease}
return jsonify(predicted)
class get_description(Resource):
def get(self, id):
disease = Disease.query.get(id)
description = {
"Name" : disease.name,
"Symptoms" : disease.symptoms,
"Description" : disease.description
}
return jsonify(description)
api.add_resource(symptoms_return, "/symptoms")
api.add_resource(predict, "/predict")
api.add_resource(get_description, "/description/<int:id>")<file_sep>from petapp import db
class Disease(db.Model):
id = db.Column(db.Integer , primary_key=True )
name = db.Column(db.String(20), unique=True, nullable=False)
description = db.Column(db.Text)
symptoms = db.Column(db.Text, nullable=False)
def __repr__(self):
return f"User('{self.name}','{self.symptoms}')" | f5b2dbf99a2692fdf19ba6d1627878f58496cca4 | [
"Python"
] | 5 | Python | petify-inout/petify-backend | 1fe96600ac426f46192ef32ad9f4cbf8788b3cea | 75859e85b77def5ae243a8b4ced0dfa43cf0c4ce |
refs/heads/main | <repo_name>AleksandrButakov/ip-calculator<file_sep>/src/ipcalcul/DecToBin.java
package ipcalcul;
// получим двоичный массив BitOrder байта DD0
public class DecToBin {
public boolean[] BitOrder = new boolean[8];
public int[] Degree = new int[]{1,2,4,8,16,32,64,128};
public DecToBin (int iByte0) {
float Residue;
for (int i=7; i>=0; i--){
Residue = (float) (iByte0/Degree[i]);
if (Residue>=1){
BitOrder[i]=true;
iByte0-=Degree[i];
} else {
BitOrder[i]=false;
}
}
}
}
<file_sep>/README.md
# IPCalculator
IP calculator calculates the subnet, the first address, the gateway in the range set by the mask. The functionality of sending a ping request to each address of the calculated range has been implemented to check the availability of all IP addresses.
<file_sep>/src/ipcalcul/BinToDec.java
package ipcalcul;
public class BinToDec {
public int AxiliaryDecByte0=0;
// полученный двумерный массив переведем в десятичный вид
public BinToDec (boolean[] Arr) {
boolean[] BitOrder = new boolean[8];
int[] Degree = new int[]{1,2,4,8,16,32,64,128};
for (int i=7; i>=0; i--) {
if (Arr[i]==true) {
AxiliaryDecByte0 += Degree[i];
}
}
}
}
| 5e84e7f655494126adc7f72d4f14421fe4a64e01 | [
"Markdown",
"Java"
] | 3 | Java | AleksandrButakov/ip-calculator | f1a861447cf0306a42a904414931b8d595110e75 | a0500f7b3f77aefdfeeb86392f0d81ce4fdac940 |
refs/heads/master | <file_sep>using System.Collections.Generic;
namespace HitsTesterWeb.ViewModels
{
public class TestPageViewModel
{
public TestPageViewModel(string text, string translatedText, List<string> hits)
{
Text = text;
TranslatedText = translatedText;
Hits = hits;
}
public string Text { get; }
public string TranslatedText { get; }
public List<string> Hits { get; }
}
}<file_sep>using System.Linq;
using Microsoft.AspNetCore.Mvc;
using HitsTesterWeb.Models;
using HitsTesterWeb.ViewModels;
namespace HitsTesterWeb.Controllers
{
public class HomeController : Controller
{
[HttpGet]
[Route("/")]
public IActionResult Index()
{
return View();
}
[HttpPost]
[Route("/")]
public IActionResult IndexPost(FormModel model)
{
var hits = HaagsTranslator.Translator.GetHits(model.Text).Where(h => h.Item2).Select(t => t.Item1).ToList();
return View("Index", new TestPageViewModel(model.Text, HaagsTranslator.Translator.Translate(model.Text), hits));
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace HaagsTranslator
{
/// <summary>
/// Translator for translating nl-NL to nl-DH
/// </summary>
public static class Translator
{
/// <summary>
/// list of replacement rules, ordered
/// </summary>
static readonly string[][] TranslationReplacements = {
new []{ "childerswijk", "childâhswijk"},
new [] { "eider", "èijâh" }, // 'projectleider'
new []{ "(?<![o])ei", "è"}, // moet voor 'scheveningen' en 'eithoeke', geen 'groeit'
new []{ "Ei", "È"}, // 'Eind'
new []{ "(B|b)roodje bal", "$1eschùitstùitâh"},
new []{ "koets", "patsâhbak"},
new []{ "kopje koffie", "bakkie pleuâh" },
new []{ "Kopje koffie", "Bakkie pleuâh" },
new []{ "koffie\\b", "pleuâh" },
new []{ "Koffie\\b", "Pleuâh" },
new []{ "Kurhaus", "Koeâhhâhs"}, // moet voor 'au' en 'ou'
new []{ "\\bMaurice\\b", "Mâhpie"}, // moet voor 'au' en 'ou'
new []{ "Hagenezen", "Hageneize"}, // moet na 'ei'
new []{ "toiletten", "pleis"},
new []{ "Toiletten", "Pleis"},
new []{ "toilet", "plei"},
new []{ "Toilet", "Plei"},
new []{ "(N|n)erd", "$1euâhd"},
new []{ "(L|l)unchroom", "$1unsroem" },
new []{ "\\bThis\\b", "Dis" },
new []{ "\\b(H|h)ighlights\\b", "$1aailaaits"},
new []{ "\\b(L|l)ast-minute\\b","$1asminnut" },
new []{"\\bAirport", "Èâhpogt" },
new []{ "\\bairport", "èâhpogt" },
new []{ "(A|a)dvertentie", "$1dvâhtensie" },
new []{ "\\b(B|b)eauty", "$1joetie" },
new []{ "\\bthe\\b", "de" },
new []{ "\\b(B|b)east\\b", "$1ies" },
new []{ "(B|b)each", "$1ietsj"},
new []{ "Bites", "Bèts" },
new []{ "Cuisine", "Kwiesien"},
new []{ "cuisine", "kwiesien"},
new []{ "Europese", "Euraipeise"},
new []{ "(?<![z])event(s|)", "ievent$1" }, // geen 'zeventig'
new []{ "Event(s|)", "Ievent$1" },
new []{ "(F|f)acebook", "$1eisboek" },
new []{ "(F|f)avorite", "$1avverietûh" },
new []{ "(F|f)avoriete", "$1avverietûh" },
new []{ "(F|f)lagship", "fleksjip" },
new []{ "Jazz", "Djes" },
new []{ "jazz", "djes" },
new []{ "(T|t)entoon", "$1etoon" },
new []{ "(C|c)abaret", "$1abberet" },
new []{ "(M|m)usical", "$1usikol" },
new []{ "kids", "kindâh" }, // 'kindertips'
new []{ "(M|m)ovies", "$1oevies" },
new []{ "(?<![Zz])(O|o)r(i|)g", "$1âhg" }, // 'originele', 'organisatie', geen 'zorg'
new []{ "chine", "sjine" }, // 'machine'
new []{ "(P|p)alace", "$1ellus"},
new []{ "(P|p)rivacy", "$1raaivesie" },
new []{ "policy", "pollesie" },
new []{ "\\b(R|r)oots\\b", "$1oets" },
new []{ "SEA LIFE", "SIELÈF" },
new []{ "(S|s)how", "$1jow" },
new []{ "(S|s)hoppen", "$1joppûh" },
new []{ "(S|s)kiën", "$1kieje"},
new []{ "(S|s)tores", "$1toâhs" },
new []{ "(T|t)ouchscreen", "$1atskrien" },
new []{ "(T|t)ouch", "$1ats" },
new []{ "that", "det" },
new []{ "(T|t)ripadvisor", "$1ripetfaaisoâh" },
new []{ "(V|v)andaag", "$1edaag" },
new []{ "\\b(V|v)erder\\b", "$1eâhdahs"},
new []{ "(V|v)intage", "$1intuts" },
new []{ "you(?![n])", "joe" }, // geen 'young'
new []{ "You(?![n])", "Joe" }, // geen 'young'
new []{ "(W|w)eekend", "$1iekend" },
new []{ "(W|w)ork", "$1urrek" },
new []{ "(B|b)ibliotheek", "$1iebeleteik" },
new []{ "(F|f)ood", "$1oet"},
new []{ "mondkapje", "bekbedekkâh"},
new []{ "Mondkapje", "Bekbedekkâh"},
new []{ "doe je het", "doejenut"},
new []{ "\\bsee\\b", "sie"}, // van 'must see'
new []{ "(M|n|R|r)ust(?![ai])", "$1us" }, // van 'must see', 'rustsignaal', geen 'rustig'
new []{ "(M|m)oeten", "$1otte"}, // moet voor '-en'
new []{ "(w|W)eleens", "$1elles"}, // 'weleens', moet voor 'hagenees'
new []{ "(g|G)ouv", "$1oev"}, // 'gouveneur'
new []{ "heeft", "hep"}, // 'heeft', moet voor 'heef'
new []{ "(on|i)der(?!e)", "$1dâh" }, // 'onder', 'Zuiderpark', geen 'bijzondere'
new []{ "iendel", "iendâhl" }, // 'vriendelijk'
new []{ "(?<![ao])ndere", "ndâhre" }, // 'bijzondere', geen 'andere'
new []{ "uier\\b", "uiâh" }, // 'sluier', moet voor 'ui'
new []{ "ui", "ùi"}, // moet voor 'ooi' zitte n
new []{ "Ui", "Ùi" },
new []{ "(?<![ieopfv])ert\\b", "egt" }, // 'gert', geen 'viert', 'expert', 'levert'
new []{ "pert\\b", "peâh" }, // 'expert'
new []{ "\\b(V|v)ert", "$1et"}, // 'vertegenwoordiger', moet voor '-ert'
new []{ "(?<![eo])erte", "egte" }, // 'concerten'
new []{ "(?<![eo])(a|o)r(|s)t(?!j)", "$1g$2t" }, // barst, martin etc., geen 'eerste', 'biertje', 'sport', 'voorstellingen'
new []{ " er aan", " d'ran"}, // 'er aan'
new []{ "(A|a)an het\\b", "$1nnut"}, // 'aan het', moet voor 'gaan'
new []{ "\\b(A|a)an", "$1n" }, // 'aan', 'aanrennen'
new []{ "\\b(G|g)aan\\b", "$1an" }, // 'gaan'
new []{ "(H|h)oud\\b", "$1ou"}, // 'houd', moet voor 'oud'
new []{ "(B|b|R|r|P|p)ou(l|t)", "$1oe$2"}, // 'boulevard', 'routes', 'poule'
new []{ "oele\\b", "oel"}, // 'poule'
new []{ "(au|ou)w(?!e)", "$1"}, // 'vrouw', ''flauw', maar zonder 'blauwe'
new []{ "oude", "ouwe"}, // 'goude'
new []{ "\\b(T|t)our\\b", "$1oeâh"},
new []{ "diner\\b", "dinei"},
new []{ "o(e|u)r\\b", "oeâh"}, // 'broer', 'retour', moet voor 'au|ou'
new []{ "oer(?![aieou])", "oeâh"}, // 'beroerd', 'hoer', geen 'toerist', 'stoere, moet voor 'au|ou'
new []{ "(?<![epYy])(au|ou)(?![v])", "âh" }, // 'oud', geen 'souvenirs', 'cadeau', 'bureau', 'routes', 'poule', 'young'
new []{ "Ou", "Âh" }, // 'Oud'
new []{ "aci", "assi"}, // 'racist'
new []{ "als een", "assun"}, // 'als een'
new []{ "a(t|l) ik", "a$1$1ik"}, // val ik, at ik
new []{ "alk\\b", "alluk"}, // 'valk'
new []{ "(?<![a])ars", "ags"}, // 'harses', geen 'Haagenaars'
new []{ "oor" , "oâh"},
new []{ "(A|a)ar(?![io])", "$1ah"}, // 'waar, 'aardappel, 'verjaardag', geen 'waarom', 'waarin'
new []{ "aar(?![i])", "ar" }, // wel 'waarom', geen 'waarin'
new []{ "patie", "petie"}, // 'sympatiek'
new []{ "aagd\\b", "aag"}, // 'ondervraagd'
new []{ "(am|at|ig|ig|it|kk|nn)en(?![ e,.?!])", "$1e"}, // 'en' in een woord, bijv. 'samenstelling', 'eigenlijk', 'buitenstaander', 'statenkwartier', 'dennenweg', 'klokkenluider', geen 'betrokkenen'
// woordcombinaties
new []{ "\\b(K|k)an er\\b", "$1andâh"},
new []{ "\\b(K|k)en ik\\b", "$1ennik"},
new []{ "\\b(K|k)en u\\b", "$1ennu"},
new []{ "\\b(K|k)en jij\\b", "$1ejjèh"},
new []{ "\\b(A|a)ls u", "$1ssu"},
new []{ "\\b(M|m)ag het\\b", "$1aggut"},
new []{ "\\bik dacht het\\b", "dachut"},
new []{ "\\b(V|v)an jâh\\b", "$1ajjâh"},
new []{ "\\b(K|k)ijk dan\\b", "$1èktan"},
new []{ "\\b(G|g)aat het\\b", "$1aat-ie"},
new []{ "\\b(M|m)et je\\b", "$1ejje"},
new []{ "\\b(V|v)ind je\\b", "$1ijje"},
new []{ "\\bmij het\\b", "mènnut"},
new []{ "\\b(A|a)ls er\\b", "$1stâh"},
new []{ "\\b(K|k)(u|a)n j(e|ij) er\\b", "$1ejjedâh"}, // 'ken je er'
new []{ "\\b(K|k)un je\\b", "$1ajje" },
new []{"\\bje ([^ ]+) je", "je $1 je ège" },
new []{ "<NAME>", "<NAME>"},
new []{ "ADO", "Adau"},
new []{ "(?<![i])atie(?![fkv])", "asie" }, // 'informatie', geen 'initiatief', 'kwalitatieve', 'automatiek'
new []{ "avil", "ave" }, // 'strandpaviljoen'
new []{ "sje\\b", "ssie"}, // 'huisje', moet voor 'asje'
new []{ "\\balleen\\b", "enkelt"},
new []{ "\\bAlleen\\b", "Enkelt"},
new []{ "(A|a)ls je", "$1sje"}, // moet voor 'als'
new []{ "athe", "atte"}, // 'kathedraal'
new []{ "(o|u)als\\b", "$1as"}, // als, zoals
new []{ "(b|k|w)ar\\b", "$1âh"},
new []{ "\\b(A|a)ls\\b", "$1s"},
new []{ " bent\\b", " ben"}, // 'ben', geen 'instrument'
new []{ "bote", "baute"}, // 'boterham'
new []{"(B|b)roc", "$1rauc" }, // 'brochure'
new []{ "bt\\b", "b"}, // 'hebt'
new []{ "cce", "kse"}, // 'accenten', geen 'account'
new []{ "cc", "kk"}, // 'account'
new []{ "chique", "sjieke" },
new []{ "(?<![s])chure", "sjure" }, // 'brochure', geen 'schuren'
new []{ "pact", "pekt"}, // 'impact'
new []{ "aca", "akke"}, // 'vacatures'
new []{ "c(a|o|t|r)", "k$1"}, // 'geactualiseerde', 'directie', 'crisis'
new []{ "C(a|o|t|r)", "K$1" }, // 'Concerten', 'Cadeau'
new []{ "(c|k)or\\b", "$1oâh" }, // 'decor'
new []{ "(?<![.])c(a|o)", "k$1" }, // 'concerten', 'cadeau', 'collectie', geen '.com'
new []{ "\\bkoro", "kerau"}, // 'corona'
new []{ "cu", "ku" }, // 'culturele'
new []{ "Cu", "Ku" }, // 'culturele'
new []{ "ci(ë|ee)l", "sjeil" }, // 'financieel', 'financiële'
new []{ "(ch|c|k)t\\b", "$1"}, // woorden eindigend op 'cht', 'ct', 'kt', of met een 's' erachter ('geslachts')
new []{ "(ch|c|k)t(?![aeiouâr])", "$1"}, // woorden eindigend op 'cht', 'ct', 'kt', of met een 's' erachter ('geslachts'), geen 'elektronische'
new []{ "(?<![Gg])(e|r)gt\\b", "$1g"}, // 'zorgt', 'legt'
new []{ "(d|D)at er", "$1attâh"}, // 'dat er'
new []{ "(d|D)at is ", "$1a's "}, // 'dat is'
new []{ "denst", "dest" },
new []{ "derb", "dâhb"},
new []{ "nderh", "ndâhh"}, // 'anderhalf', geen 'derhalve'
new []{ "derd\\b", "dâhd"}, // 'veranderd'
new []{ "(D|d)eze(?![l])", "$1eize"}, // 'deze', geen 'dezelfde'
new []{ "dt\\b", "d"}, // 'dt' op het einde van een woord
new []{"\\b(B|b)ied\\b", "$1iedt" }, // uitzondering, moet na '-dt'
new []{ "(D|d)y", "$1i"}, // dynamiek
new []{ "eaa", "eiaa"}, // 'ideaal'
new []{ "eau\\b", "o" }, // 'cadeau', 'bureau'
new []{ "ègent", "èget" }, // 'eigentijds', moet voor 'ee', geen 'dreigend'
new []{ "Eig", "Èg" }, // 'Eigenlijk', moet voor 'ee'
new []{ "eig", "èg" }, // 'eigenlijk', moet voor 'ee'
new []{ "uee\\b", "uwee"}, // 'prostituee', moet voor '-ee'
new []{ "ueel\\b", "eweil"}, // 'audiovisueel'
new []{ "uele\\b", "eweile" }, // 'actuele'
new []{ "(g|n|l|L|m|M)ee(n|s)" , "$1ei$2"}, // 'geen', 'hagenees', 'lees', 'burgemeester'
new []{ "ee\\b", "ei"}, // met '-ee' op het eind zoals 'daarmee', 'veel'
new []{ "eel", "eil"}, // met '-ee' op het eind zoals 'daarmee', 'veel'
new []{ " is een ", " issun "}, // moet voor ' een '
new []{ "(I|i)n een ", "$1nnun "}, // 'in een', voor ' een '
new []{ "één", "ein"}, // 'één'
new []{ " een ", " un "},
new []{ "Een ", "Un "},
new []{ " eens", " 'ns"}, // 'eens'
new []{ "(?<![eo])erd\\b", "egd"}, // 'werd', geen 'verkeerd', 'gefeliciteerd', 'beroerd
new []{ "eerd", "eâhd"}, // 'verkeerd'
new []{ "(?<![k])ee(d|f|g|k|l|m|n|p|s|t)", "ei$1"}, // 'bierfeest', 'kreeg', 'greep', geen 'keeper'
new []{ "(?<![l])ands\\b", "ens"}, // 'hands', moet voor 'ds', geen 'Nederlands'
new []{ "(?<![t])ain", "ein"}, // 'trainer', geen 'quarantaine'
new []{ "(?<![èijhmr])ds(?![ceèt])", "s" }, // moet na 'ee','godsdienstige', 'gebedsdienst', geen 'ahdste', 'boodschappen', 'beroemdste', 'eigentijds', 'weidsheid', 'reeds', 'strandseizoen', 'wedstrijd', 'nerds'
new []{ "(?<![eh])ens\\b", "es"}, // 'ergens', geen 'weleens', 'hands/hens'
new []{ "(D|d)ance", "$1ens" }, // moet na '-ens'
new []{ "(?<![ hi])eden\\b", "eije"}, // geen 'bieden'. 'bezienswaardigheden'
new []{ "(?<![ bgi])eden", "eide" }, // 'hedendaagse', geen 'bedenken'
new []{ "\\b(E|e)ve", "$1ive" }, // 'evenementen'
new []{ "(?<![a])(m|M|R|r)e(d|t|n)e(?![ei])", "$1ei$2e"}, // 'medeklinkers', 'rede', geen 'Hagenees', 'meneer', geen 'meteen'
new []{ "(G|g)ener", "$1einer"}, // 'generatie'
new []{ "(E|e)nerg", "$1inerg"}, // 'energie'
new []{ "eugd", "eug" }, // 'jeugd', 'jeugdprijs'
new []{ "(?<![o])epot\\b", "eipau"}, // 'depot'
new []{ "(e|E)rg\\b", "$1rrag"}, // 'erg', moet voor 'ergens'
new []{ "(?<![fnN])(a|o)rm","$1rrem" }, // 'platform', 'vormgeving', 'warm', geen 'normale', 'informatie'
new []{ "(f|N|n)orma", "$1oâhma" }, // 'normale', 'informatie', geen 'boorplatform'
new []{ "(i|I)nterna", "$1ntâhna" }, // 'internationale'
new []{ "elden", "elde"}, // 'zeeheldenkwartier'
new []{ "oeter", "oetâh" }, // 'Zoetermeer', moet voor 'kermis'
new []{ "erm\\b", "errum"}, // 'scherm', moet voor 'kermis'
new []{ "(?<![ieoptvV])er(m|n)", "erre$1"}, // kermis', geen 'vermeer', 'vermoeide', 'toernooi', 'externe', 'supermarkt', termijn, 'hierna'
new []{ "(?<![edktv])(e|E)rg(?!ez|i)", "$1rreg"}, // 'kermis', 'ergens', geen 'achtergelaten', 'neergelegd', 'overgebleven', 'ubergezellige', 'bekergoal', 'energie', 'rundergehakt'
new []{ "ber(?![eoiuaâè])", "bâh"}, // 'ubergezellige', moet na '-erg', geen 'beraden'
new []{ "(P|p)ers(?![l])", "$1egs"}, // 'pers', geen 'superslimme'
new []{ "(?<![e])(t|V|v)ers(?![clt])", "$1egs"}, // 'vers', 'personeel', 'versie', 'diverse', geen 'gevers', 'verscheen', 'eerste',
new []{ "(G|g)eve(r|n)", "$1eive$2" }, // 'Gevers', moet na 'vers', geen 'gevestigd'
new []{ "(t|w|W)ene", "$1eine" }, // 'stenen', 'wenen'
new []{ "renstr", "restr" }, // 'herenstraat' (voor koppelwoorden)
new []{ "(?<![eIio])eder", "eider" }, // 'Nederland', geen 'iedereen', 'bloederige', 'Iedere'
new []{ "(?<![eiop])ers\\b", "âhs"}, // 'klinkers', geen 'pers', 'personeel'
new []{ "(H|h)er(?![erp])", "$1eâh" }, // 'herzien', 'herstel', geen 'herenstraat', 'scherm', 'scherp', moet voor 'ers'
new []{ "(?<![vV])ers(c|t)", "âhs$1"}, // 'eerste', 'bezoekerscentrum', geen 'verschaffen', 'Verstappen'
new []{ "erwt", "erret" }, // 'erwtensoep'
new []{ "(?<![eo])eci", "eici" }, // 'speciaal'
new []{ "(?<![Bbg])ese", "eise" }, // 'reserveer', geen 'beseffen', 'geselecteerd'
new []{ "eiser", "eisâh"}, // 'reserveer'
new []{ "eur\\b", "euâh"}, // worden eindigend op 'eur', zoals 'deur', 'gouveneurlaan', geen 'kleuren'
new []{ "eur(?![eio])", "euâh"}, // worden eindigend op 'eur', zoals 'deur', 'gouveneurlaan', geen 'kleuren', 'goedkeuring', 'euro
new []{ "eur(i|o)", "euâhr$1"}, // 'goedkeuring', 'euro'
new []{ "eurl", "euâhl"}, // worden eindigend op 'eur', zoals 'deur', 'gouveneurlaan'
new []{ "eer", "eâh" }, // 'zweer', 'neer'
new []{ "elk\\b", "ellek"}, // 'elk'
new []{ "(?<![og])ega", "eige"}, // 'negatief', geen 'toegang', 'gegaan'
new []{ "(E|e)xt", "$1kst" }, // 'extra'
new []{ "(H|h|n)ele", "$1eile"}, // 'gehele', 'hele', 'originele'
new []{ "\\b(E|e)le", "$1ile"}, // 'elektronica'
new []{ "ffis", "ffes"}, // 'officiele'
new []{ "(G|g)ese", "$1esei"}, // 'geselecteerd'
new []{ "\\b(g|G|v|V)ele\\b", "$1eile" }, // 'vele', 'gele', 'hele'
new []{ "ebut", "eibut" }, // 'debuteren', geen 'debuut'
new []{ "\\b(D|d)elen", "$1eile"}, // 'delen', geen 'wandelen'
new []{ "sdelen", "sdeile"}, // 'geslachtsdelen', geen 'wandelen'
new []{ "(?<![diokrs])ele(n|m|r)", "eile$1"}, // 'helemaal', geen 'enkele', 'winkelen', 'wandelen', 'borrelen', 'beginselen'
new []{ "(B|b)eke(?![n])", "$1eike"}, // 'beker', geen 'bekende'
new []{ "(B|b)ene(?![v])", "$1eine" }, // 'benen', geen 'beneveld'
new []{ "(?<![ioBbg])eke", "eike"}, // geen 'aangekeken' op 'gek', wel 'kek'
new []{ "(?<![r])rege(?![r])", "reige" }, // 'gekregen', geen 'berrege', 'regeren'
new []{ "(T|t)ege(?![l])", "$1eige" }, // 'tegen', geen 'tegelijkertijd'
new []{ "(?<![bBIiort])e(g|v|p)e(l|n|m| )", "ei$1e$2" }, // aangegeven, 'leverde', geen 'geleden', 'uitspreken', 'geknepen', 'goeveneur', 'verdiepen', 'postzegels', 'begeleiding', 'berregen', 'tegelijkertijd'
new []{ "dige", "dege"}, // 'vertegenwoordiger', moet na 'ege'
new []{ "(L|l)ever", "$1eiver"}, // 'leverde'
new []{ "alve\\b", "alleve"}, // 'halve', moet na 'aangegeven'
new []{ "\\b(K|k)en\\b", "$1an"}, // moet voor -en
new []{ "(a|o)ien\\b", "$1ie"}, // 'uitwaaien', geen 'zien'
new []{ "(?<![ ieo])en([.?!])", "ûh$1"}, // einde van de zin, haal ' en ', 'doen', 'zien' en 'heen' eruit
new []{ "(?<![ bieohr])en\\b", "e"}, // haal '-en' eruit, geen 'verscheen', 'tien', 'indien', 'ben', 'doen', 'hen'
new []{ "(?<![r])ren\\b", "re"}, // oren, geen 'kerren'
new []{ "bben\\b", "bbe"}, // 'hebben'
new []{ "oien\\b", "oie"}, // 'weggooien'
new []{ "enso", "eso" }, // 'erwtensoep'
new []{ "eum", "eijum" }, // 'museum'
new []{ "(?<![eio])enm(?![e])", "em" }, // 'kinderboekenmuseum', geen 'kenmerken'
new []{ "(?<![eiorvV])en(b|h|j|l|p|r|v|w|z)", "e$1"}, // 'binnenhof', geen 'paviljoenhoeder', 'venlo', 'Bernhard'
new []{ "([Hh])eb je ", "$1ebbie "}, // voor '-eb'
new []{ "(H|h)eb (un|een)\\b", "$1ep'n"}, // voor '-eb'
new []{ "(?<![eu])eb\\b", "ep"},
new []{ "(E|e)x(c|k)", "$1ksk" }, // 'excursies'
new []{ "(?<![ s])teri", "tâhri" }, // 'karakteristieke'
new []{ "(?<![ sS])ter(?![aeirn])", "tâh"}, // 'achtergesteld', geen 'beluisteren', 'literatuur', 'sterren', 'externe', 'sterker', 'karakteristieke'
new []{ "feli", "feili" }, // 'gefeliciteerd'
new []{ "(I|i)ndeli", "$1ndeili" }, // 'indeling', geen 'eindelijk', 'wandelingen'
new []{ "(f|p)t\\b", "$1"}, // 'blijft', 'betrapt'
new []{ "\\b(N|n)iet\\b", "$1ie" }, // 'niet', geen 'geniet'
new []{ "fd(?![eo])", "f"}, // 'hoofd', 'hoofdtrainer', geen 'zelfde', 'verfdoos'
new []{ "(F|f)eb", "$1eib" }, // 'februari'
new []{ "ngt\\b", "nk"}, // 'hangt'
new []{ "e(k|v)ing", "ei$1ing"}, // 'omgeving', 'onderbreking'
new []{ "gje\\b", "ggie"}, // 'dagje'
new []{ "go(r)", "gau$1" }, // 'algoritme'
new []{ "gelegd\\b", "geleige"}, // 'neergelegd'
new []{ "([HhVvr])ee(l|n|t)", "$1ei$2"}, // 'verscheen', 'veel', 'overeenkomsten', 'heet'
new []{ "(I|i)n het", "$1nnut"}, // 'in het'
new []{ "\\b(E|e)te", "$1ite"}, // 'eten'
new []{ "(?<![ior])ete(?![il])", "eite" }, // 'hete', 'gegeten', geen 'bibliotheek','erretensoep', 'koffietentjes', 'genieten, 'roetes (routes)', 'vertelde'
new []{ "(d|h|l|m|r|t)ea(?![m])", "$1eija" }, // 'theater', geen 'team'
new []{ "\\bhet\\b", "ut"},
new []{ "Het\\b", "Ut"},
new []{ "(?<![eouù])i\\b", "ie" }, // 'januari'
new []{ "ieri(n|g)", "ieâhri$1"}, // 'plezierig', 'viering'
new []{ "emier", "emjei" }, // 'premier'
new []{ "(?<![uù])ier(?!(a|e|i|ony))", "ieâh" }, // 'bierfeest', 'hieronder', geen 'hieronymus', 'plezierig', 'dieren', 'sluier'
new []{ "iero(?!e|o|nd)", "ierau" }, // 'hieronymus', geen 'hieronder'
new []{ "ière", "ijerre"}, // 'barriere'
new []{ "ibu", "ibe"}, // 'tribunaal'
new []{ "icke", "ikke" }, // 'tickets'
new []{ "iti(a|o|au)", "isi$1" }, // 'initiatief', 'traditioneel'
new []{ "ijgt\\b", "ijg"}, // 'krijgt', moet voor 'ij\\b'
new []{ "(B|b)ijz", "$1iez" }, // 'bijzondere', moet voor 'bij'
new []{ "ij\\b", "è"}, // 'zij', 'bij'
new []{ "(?<![e])ije(?![ei])", "èje" }, // 'bijenkorf', 'blije', geen 'geleie', 'bijeenkomst'
new []{ "èjen", "èje" }, // 'bijenkorf'
new []{ "(B|b)ij", "$1è" }, // 'bijbehorende'
new []{ "\\blijk\\b", "lèk" }, // 'lijk' , geen 'eindelijk' ('-lijk')
new []{ "(D|d|K|k|p|R|r|W|w|Z|z)ijk", "$1èk"}, // 'wijk', geen '-lijk'
new []{ "ij([dgslmnftpvz])", "è$1"}, // 'knijp', 'vijver', 'stijl', 'vervoersbewijzen', geen '-lijk'
new []{ "(?<![euù])ig\\b", "ag"}, // geen 'kreig', 'vliegtuig'
new []{ "tigdù", "tagdù"}, // 'vijftigduizend'
new []{ "lige\\b", "lage"}, // 'gezellige'
new []{ "(?<![euù])igd\\b", "ag" }, // gevestigd
new []{ "\\bIJ", "È" }, // 'IJsselmeer'
new []{ "ilm", "illem" }, // 'film'
new []{ "ilieu", "ejui"}, // 'milieu'
new []{ "incia", "insja"}, // 'provinciale'
new []{ "inc(k|)(?![i])", "ink"}, // 'incontinentie', 'binckhorst', geen 'provinciale'
new []{ "io(?![oen])", "iau"}, // 'audio', geen 'viool', 'station'
new []{ "\\bin m'n\\b", "imme"},
new []{ "(n|r)atio", "$1asjau" }, // 'internationale'
new []{ "io\\b", "iau" }, // 'audio', geen 'viool', 'station', 'internationale'
new []{ "io(?![oen])", "iau" }, // 'audio', geen 'viool', 'station', 'internationale'
new []{ "ir(c|k)", "irrek" }, // 'circus'
new []{ "(?<![gr])ties\\b", "sies"}, // 'tradities', moet voor -isch, geen 'smarties'
new []{ "isch(|e)", "ies$1"},
new []{ "is er", "istâh"},
new []{ "ap je\\b", "appie" }, // 'stap je'
new []{ "(p) je\\b", "$1ie" }, // 'loop je', geen 'stap je'
new []{ "(g|k) je\\b", "$1$1ie" }, // 'zoek je'
new []{ "jene", "jenei"}, // 'jenever'
new []{ "jezelf", "je ège"}, // "jezelf"
new []{ "(?<![oe])kje\\b", "kkie"}, // 'bakje', moet voor algemeen regel op 'je', TODO, 'bekje'
new []{ "olg", "olleg"}, // 'volgens'
new []{ "(a|i|o)(k|p)je\\b", "$1$2$2ie"}, // 'kopje', 'gokje', 'tipje', 'stapje'
new []{ "(?<![ deèijstn])je\\b", "ie"}, // woorden eindigend op -je', zonder 'asje', 'rijtje', 'avondje', geen 'mejje' 'blèjje', 'skiën', 'oranje'
new []{ "(K|k)an\\b", "$1en"}, // 'kan', geen 'kans', 'kaneel'
new []{ "(K|k)unne", "$1enne"}, // 'kunnen', TODO, wisselen van u / e
new []{ "(K|k)unt", "$1en" },
new []{ "(K|k)led(?![d])", "$1leid"}, // 'kleding', geen 'kledder'
new []{ "\\bOra", "Aura" }, // 'Oranje'
new []{ "\\bora", "aura" }, // 'oranje'
new []{ "orf", "orref" },
new []{ "oro(?![eo])", "orau" }, // 'Corona'
new []{ "Oo([igkm])", "Au$1" }, // 'ook'
new []{ "oo([difgklmnpst])", "au$1"}, // 'hoog', 'dood'
new []{ "lo\\b", "lau"}, // 'venlo'
new []{ "([RrNn])ij", "$1è"}, // 'Nijhuis'
new []{ "tieg", "sieg" }, // 'vakantiegevoel'
new []{ "(?<![e])tie\\b", "sie"}, // 'directie', geen 'beauty'
new []{ "enties\\b", "ensies"}, // 'inconsequenties', geen 'romantisch'
new []{ "er(f|p)(?![a])", "erre$1"}, // 'modeontwerper', 'scherp', 'verf', geen 'verpakking'
new []{ "(b|B|k|K|m|L|l|M|p|P|t|T|w|W)erk", "$1errek" }, // 'kerk', 'werkdagen', geen 'verkeer'
new []{ "(f|k)jes\\b", "$1$1ies" }, // 'plekjes'
new []{ "(M|m)'n", "$1e"}, // 'm'n'
new []{ "(M|m)ong", "$1eg"}, // 'mongool'
new []{ "k mein(?![ut])", "k meint"}, // 'ik meen', moet na 'ee', geen 'menu', 'gemeentemuseum'
new []{ "mt\\b", "mp"}, // 'komt'
new []{ "(?<![oO])md(?![e])", "mp" }, // 'beroemdste', geen 'omdat', 'beroemde
new []{ "lair(?![e])", "lèh"}, // geen 'spectaculaire'
new []{ "ulaire", "elère"}, // 'spectaculaire'
new []{ "lein", "lèn"},
new []{ "\\bliggûh\\b", "leggûh"},
new []{ "\\b(L|l)igge\\b", "$1egge" },
new []{ "\\b(L|l)igt\\b", "$1eg" },
new []{ "(?<![p])(L|l)ez", "$1eiz"}, // 'lezer', geen 'plezierig'
new []{ "lf", "lluf"}, // 'zelfde'
new []{ "ll([ ,.])", "l$1" }, // 'till'
new []{ "(a|e|i|o|u)rk\\b", "$1rrek" }, // 'park', 'stork'
new []{ "(P|p)arke", "$1agke"}, // 'parkeervergunning', moet voor '-ark'
new []{ "ark(?![a])", "arrek" }, // 'markt', 'marktstraat', geen 'markante'
new []{ "ark", "agk"}, // 'markante', moet na -ark
new []{ "\\b(M|m)oet\\b", "$1ot"}, // 'moet', geen 'moeten'
new []{ "nair", "nèâh" }, // 'culinair'
new []{ "neme\\b", "neime" }, // 'nemen', geen 'evenementen'
new []{ "nemi", "neimi" }, // 'onderneming'
new []{ "nce", "nse"}, // 'nuance'
new []{ "\\b(N|n)u\\b", "$1âh"},
new []{ "ny", "ni" }, // 'hieronymus'
new []{ "\\bmad", "med"}, // 'madurodam'
new []{ "oeder", "oedâhr" }, // 'bloederigste'
new []{ "(?<![v])(a|o)(rdt|rd)(?![eû])", "$1gt"}, // wordt, word, hard, geen 'worden', 'wordûh', 'boulevard'
new []{ "ord(e|û)", "ogd$1"}, // 'worden'
new []{ "(N|n)(|o)od", "$1aud"}, // 'noodzakelijk'
new []{ "nirs\\b", "nieâhs" }, // 'souvenirs'
new []{ "l(f|k|m|p)(?![aeou])", "lle$1"}, // 'volkslied', 'behulp', geen 'elkaar', 'doelpunten', 'IJsselmeer', 'vuilcontainer'
new []{ "(e|o)lk(?![a])", "$1llek"}, // 'volkslied','elke', geen 'elkaar'
new []{ "(F|f)olleklore", "$1olklore" },
new []{ "o(c|k)a", "auka" }, // 'locaties'
new []{ "(?<![o])oms", "omps" }, // 'aankomsthal'
new []{ "one(e|i)", "aunei" }, // 'toneel'
new []{ "on(a|i)", "aun$1" }, // 'telefonische', 'gepersonaliseerde'
new []{ "hore", "hoâhre"}, // 'bijbehorende'
new []{ "org(?![i])", "orrag"}, // 'zorg', geen 'orgineel'
new []{ "orp", "orrep"}, // 'ontworpen'
new []{ "mor\\b", "moâh"}, // 'humor', geen 'humoristische'
new []{ "\\borg", "oâhg"}, // 'orgineel'
new []{ "Over(?![ei])", "Auvâh"}, // 'overgebleven', 'overnachten', geen 'overeenkomsten', 'overige'
new []{ "(?<![z])over(?![ei])", "auvâh"}, // 'overgebleven', geen 'overeenkomsten', 'overige', 'zover'
new []{ "o(v|z)e", "au$1e"},
new []{ "(?<![gz])o(b|d|g|k|l|m|n|p|s|t|v)(i|e|o|au)", "au$1$2"}, // 'komen', 'grote', 'over', 'olie', 'notie', geen 'gokje', 'foto', 'doneren', 'zone'
new []{ "O(b|d|g|k|l|m|p|s|t|v)(i|e)", "Au$1$2"}, // zelfde, maar dan met hoofdletter
new []{ "\\bout", "âht" }, // 'outdoor'
new []{ "\\bOut", "Âht" }, // 'Outdoor'
new []{ "\\b(V|v)er\\b", "$1eâh"}, // 'ver'
new []{ "(D|d)ert(?![u])","$1eâht"}, // 'dertig', geen 'ondertussen'
new []{ "\\b(D|d)er\\b","$1eâh"}, // 'der'
new []{ "der(?![dehianrouèt])", "dâh"},// 'moderne'/'moderrene', geen 'dertig', 'derde', 'derhalve'
new []{ "\\b(P|p|T|t)er\\b", "$1eâh" }, // 'per', 'ter'
new []{ "(Z|z)auver\\b", "$1auveâh" }, // 'zover'
new []{ "ergi", "egi" }, // 'energie'
new []{ "(?<![ io])er\\b", "âh" }, // 'kanker', geen 'hoer', 'er', 'per', 'hier' , moet voor 'over' na o(v)(e)
new []{ "eiker(g|h)", "eikâh$1" }, // 'bekergoal', 'bekerheld'
new []{ "orm", "orrum" }, // 'platform'
new []{ "(P|p)er(?![aeirt])", "$1âh"}, // 'supermarkt', geen 'periode', 'expert', 'beperkt/beperrekt', 'operaties', 'beperken/beperreken' moet na 'per'
new []{ "(P| p)o(^st)" , "$1au$2"}, // 'poltici'
new []{ "p ik\\b", "ppik"}, // 'hep ik'
new []{ "ppen", "ppe" }, // 'poppentheater'
new []{ "popu", "paupe"}, // 'populairste'
new []{"(p|P)ro(?![oefkns])", "$1rau" }, // 'probleem', geen 'prof', 'prostituee', 'instaprondleiding'
new []{ "(p|P)rofe", "$1raufe" }, // 'professor', 'professioneel'
new []{ "ersch", "esch"}, // 'verschijn'
new []{ "(A|a)rme", "$1rreme"}, // 'arme'
new []{ "re(s|tr)(e|o)", "rei$1$2"}, // 'resoluut', 'retro', 'reserveren'
new []{ "palè", "pelè"}, // voor Vredespaleis
new []{ "(R|r)elax", "$1ieleks" },
new []{ "(R|r)estâhrant", "$1esterant"},
new []{ "(R|r)esu", "$1eisu"}, // 'resultaat'
new []{ "rants\\b", "rans"}, // 'restaurants'
new []{ "rigste", "ragste"}, // 'bloederigste'
new []{ "rod", "raud"}, // 'madurodam'
new []{ "(r|R)ou", "$1oe"}, // 'routes'
new []{ "(a|o)rt", "$1gt"}, //'korte'
new []{ "([Rr])o(?=ma)" , "$1au"}, // voor romantisch, maar haal bijv. rommel eruit
new []{ "inds", "ins"}, // 'sinds'
new []{ "seque", "sekwe"}, // 'inconsequenties'
new []{ "sjes\\b", "ssies"}, // 'huisjes'
new []{ "(S|s)hop", "$1jop" }, // 'shop'
new []{ "stje\\b", "ssie"}, // 'beestje'
new []{ "st(b|d|g|h|j|k|l|m|n|p|v|w|z)", "s$1"}, // 'lastpakken', geen 'str'
new []{ "(S|s)ouv", "$1oev" }, // 'souvenirs'
new []{ "(?<![gr])st\\b", "s"}, // 'haast', 'troost', 'gebedsdienst', geen 'barst'
new []{ "tep\\b", "teppie"}, // 'step'
new []{ "té\\b", "tei"}, // 'satè'
new []{ "tion", "sion"}, // 'station'
new []{ "(d|t)je\\b", "$1sje"}, // 'biertje', 'mandje'
new []{ "\\b(T|t)o\\b", "$1oe"}, // to
new []{ "(p|t)o\\b", "$1au"}, // 'expo', moet na 'au'/'ou'
new []{ "toma", "tauma"}, // moet na 'au'/'ou', 'automatiek', geen 'tom'
new []{ "(T|t)ram", "$1rem"}, // 'tram'
new []{ "quaran", "karre" }, // 'quarantaine', moet voor 'ua'
new []{ "ua", "uwa"}, // 'nuance', 'menstruatie'
new []{ "(J|j)anu", "$1anne" }, // 'januari', moet na 'ua'
new []{ "ùite\\b", "ùitûh" }, // 'buiten'
new []{ "(u|ù)igt\\b", "$1ig"}, // 'zuigt'
new []{ "(U|u)ren", "$1re"}, // 'uren'
new []{ "ùidâh\\b", "ùiâh"}, // 'klokkenluider'
new []{ "unch", "uns" }, // 'lunch'
new []{ "anch", "ansj" }, // 'branch'
new []{ "(?<![u])urg", "urrag"}, // 'Voorburg', geen natuurgras
new []{ "(?<![u])urs", "ugs" }, // 'excursies', geen 'cultuurschatten'
new []{ "uur", "uâh" }, // 'literatuurfestival', moet voor '-urf'
new []{ "ur(f|k)", "urre$1"}, // 'Turk','snurkende','surf'
new []{ "(T|t)eam", "$1iem"},
new []{ "ntures", "ntjâhs"}, // 'ventures'
new []{ "ultur", "ulter"}, // 'culturele'
new []{ "(?<![Ss])tu(?![âfkurst])", "te"}, // 'culturele', geen 'tua', 'vintage', 'instituut', 'tussenletter', 'stuks', 'aansturing', 'vacatures'
new []{ "\\bvan je\\b", "vajje"},
new []{ "\\bvan (het|ut)\\b", "vannut"},
new []{ "\\b(V|v)ege(?![lz])", "$1eige"}, // 'vegetarisch', geen 'vergelijking', 'vergezeld' (moet voor 'ver -> ve')
new []{ "vert\\b", "vâht"}, // 'levert'
new []{ "([Vv])er(?![aeèfrious])", "$1e"}, // wel 'verkoop', geen 'verse', 'veranderd', 'overeenkomsten', 'overige', 'verf/verref', uitgeverij/è
new []{ "([Vv])er(sl|sta)", "$1e$2"}, // 'verslag', 'verstappen'
new []{ "vaka", "veka" }, // 'vakantie'
new []{ "vard", "vâh"}, // 'boulevard'
new []{ "voetbal", "foebal"},
new []{ "we er ", "we d'r "}, // 'we er'
new []{ "\\ber\\b", "d'r"},
new []{ "\\bEr\\b", "D'r"},
new []{ "(I|i)n je\\b", "$1jje"},
new []{ "wil hem\\b", "wil 'm"},
new []{ "(W|w|H|h)ee(t|l)", "$1ei$2"}, // 'heel', 'heet'
new []{ "Young", "Jong" }, // 'Young'
new []{ "young", "jong" }, // 'young'
new []{ "yo", "jau" }, // 'yoga'
new []{ "Yo", "Yau" }, // 'yoga'
new []{ "\\b(Z|z)ee", "$1ei"}, // 'zeeheldenkwartier'
new []{ "eep", "iep"}, // 'keeper'
new []{ "\\b(Z|z)ult\\b", "$1al"},
new []{ "z'n" , "ze"}, // 'z'n'
new []{ "\\bzich\\b", "ze ège"}, // 'zich'
new []{ "z(au|o)'n", "zaun"},
new []{ "\\bzegt\\b", "zeg"},
new []{ "(z|Z)(o|ó)(?![cenr])", "$1au"}, // 'zogenaamd', 'zó', geen 'zoeken', 'zondag', 'zorgen', 'zocht'
new []{ "'t", "ut"},
new []{ "derr", "dèrr" }, // 'moderne, moet na 'ern'/'ode'
new []{ "Nie-westegse", "Niet westagse" },
new []{ "us sie", "us-sie" }, // 'must see'
new []{ "\\bThe Hague\\b", "De Heek" }, // moet na 'ee -> ei'
new []{ "Krowne", "Kraun" },
new []{ "social media", "sausjel miedieja" }, // moet na 'au'
new []{ "sol", "saul" }, // 'resoluut'
new []{ "aine", "ène" }, // 'quarantaine'
new []{ "tain", "tein" }, // 'vuilcontainer'
new []{ "(?<![eèuoin])gel\\b", "sjel"}, // 'handgel', geen 'regel', 'pingel', 'vogel'
new []{ "ingel\\b", "ingol"}, // 'pingel'
new []{ "ign", "inj"}, // 'rustsignaal'
new []{ "down", "dâhn" }, // 'lockdown'
new []{ "lock", "lok"}, // 'lockdown'
new []{ "(?<![s])sis(?![i])", "sus"}, // 'crisis', geen 'rassis'van 'racist', 'positie'
new []{ "COVID", "KAUVID"}, // 'COVID-19'
//quick fixups
new [] { "stgong>", "strong>"}, //fixups for <strong tag>
new [] { "kute;", "cute;" }, // fixups for é tag
new [] { "&ksedil;", "ç" }, // fixups for ç tag
new [] { "lie>", "li>" } // fixups for <li> tag
};
/// <summary>
/// Verify that at least our regexe's fit in the cache of the regex lib
/// </summary>
static Translator()
{
Regex.CacheSize = Math.Max(Regex.CacheSize, TranslationReplacements.Length);
}
/// <summary>
/// Translate the given string from nl-NL to nl-DH
/// </summary>
/// <param name="dutch"></param>
/// <returns></returns>
public static string Translate(string dutch)
{
if (string.IsNullOrEmpty(dutch))
return dutch;
var copyValue = string.Copy(dutch);
return TranslationReplacements.Aggregate(copyValue, (current, replacement) => Regex.Replace(current, replacement[0], replacement[1], RegexOptions.CultureInvariant));
}
#if DEBUG
/// <summary>
/// retrieve all regexes and if they hit for the given string
/// </summary>
/// <param name="dutch"></param>
/// <returns></returns>
public static IEnumerable<Tuple<string, bool>> GetHits(string dutch)
{
if (string.IsNullOrEmpty(dutch))
return Enumerable.Empty<Tuple<string, bool>>();
var result = new List<Tuple<string, bool>>();
var haags = dutch;
foreach (var replacement in TranslationReplacements)
{
var original = haags;
haags = Regex.Replace(original, replacement[0], replacement[1], RegexOptions.CultureInvariant);
result.Add(Tuple.Create(replacement[0], !original.Equals(haags, StringComparison.InvariantCultureIgnoreCase)));
}
return result;
}
#endif
}
}
<file_sep># Vertaler Nederlands naar het Haags
Ontwikkeld speciaal voor de Haagse versie van DenHaag.com ter ere van de onthulling van het standbeeld van <NAME> op de Grote Markt in Den Haag.
Bekijk het op [DeHaag.com](http://www.dehaag.com)
# How to use
nuget `Install-Package HaagsTranslator`
`HaagsTranslator.Translator.Translate("Ontwikkeld speciaal voor de Haagse versie van DenHaag.com ter ere van de onthulling van het standbeeld van <NAME> op de Grote Markt in Den Haag.")`
=>
`Ontwikkeld speiciaal voâh de Haagse vegsie van DenHaag.com teâh ere van de onthulling vannut standbeild van <NAME> op de Graute Marrek in De Haag.`
Of gebruik [haags.nu](http://haags.nu) om live iets te vertalen.
# Disclaimer
Het algoritme is tot standgekomen met behulp van 'Ut groen geile boekie' door <NAME>, <NAME> en <NAME>. En met behulp van correcties door <NAME> en Robert-<NAME>. Uiteraard zou zonder Q42 en Den Haag marketing en in het bijzonder <NAME> dit nooit het levenslicht hebben gezien.
Het algoritme mag vrij gebruikt worden. Eventuele correcties of aanvullingen zijn welkom.
-
<NAME> (Q42) & <NAME> (Q42)
<file_sep>namespace HitsTesterWeb.Models
{
public class FormModel
{
public string Text { get; set; }
}
} | 986dc7dc2de799475957a2281ee584cc4ab4da51 | [
"Markdown",
"C#"
] | 5 | C# | Q42/HaagsTranslator | ff3e9aaa1b72be050e49997ec485a4e2b2703ebf | 1d85ec225d3f9333282511fe8d5eadc819c77cac |
refs/heads/master | <repo_name>apullenb/myBudget-api<file_sep>/Services/Bills/billsService.js
const BillServices = {
addNewBill(knex, newEntry){
return knex
.insert(newEntry)
.into('bills')
.returning('*')
.then(rows => {
return rows[0];
});
},
getById(knex, id) {
return knex
.from('bills')
.select('*')
.where('user_id', id);
},
updateBill(knex, id, newBillFields) {
return knex('bills')
.where('id', id)
.update(newBillFields);
},
deleteBill(knex, id) {
return knex('bills')
.where('id', id)
.delete();
},
};
module.exports = BillServices;<file_sep>/Services/Income/incomeRoutes.js
const express = require("express");
const path = require("path");
const Services = require("./incomeService");
const authorization = require("../../utils/authorization");
const jsonParser = express.json();
const incomeRouter = express.Router();
incomeRouter.get("/", authorization, async (req, res) => {
try {
const user = await Services.getById(req.app.get("db"), req.user);
res.json(user);
} catch (err) {
console.error(err.message);
res.status(500).json("server error");
}
});
incomeRouter.post("/", jsonParser, authorization, (req, res) => {
const { source, amount, date, month } = req.body;
const newIncome = { source, amount, date, month };
for (const [key, value] of Object.entries(newIncome))
if (value === null || undefined || "")
return res.status(400).json({
error: `Missing Value for '${key}' `,
});
newIncome.user_id = req.user;
Services.addNewIncome(req.app.get("db"), newIncome).then((entry) => {
res
.status(201)
.location(path.posix.join(req.originalUrl, `/${entry.id}`))
.json(entry);
});
});
incomeRouter.patch("/:id", authorization, (req, res, next) => {
const { id } = req.params;
const paid = req.body;
Services.updateIncome(req.app.get("db"), id, paid)
.then(() => {
res.status(204).end();
})
.catch(next);
});
incomeRouter.delete("/:id", authorization, (req, res, next) => {
const { id } = req.params;
Services.deleteIncome(req.app.get("db"), id)
.then(() => {
res.status(204).end();
})
.catch(next);
});
module.exports = incomeRouter;
<file_sep>/Services/Transactions/transactService.js
const transactService = {
addNewBill(knex, newEntry){
return knex
.insert(newEntry)
.into('transactions')
.returning('*')
.then(rows => {
return rows[0];
});
},
getById(knex, id) {
return knex
.from('transactions')
.select('*')
.where('user_id', id);
},
updateBill(knex, id, newTransact) {
return knex('transactions')
.where(id)
.update(newTransact);
},
deleteBill(knex, id) {
return knex('transactions')
.where(id)
.delete();
},
};
module.exports = transactService;<file_sep>/migrations/001.do.create_user.sql
CREATE TABLE IF NOT EXISTS "user"
(
user_id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY (
start 548264648
),
first_name text NOT NULL,
user_name character varying(150),
password character varying(150) NOT NULL,
CONSTRAINT PK_users PRIMARY KEY ( user_id )
);
<file_sep>/migrations/004.undo.create_debt.sql
DROP TABLE "debt";<file_sep>/README.md
# Divvy$
This app can be viewed live @ https://divvy.vercel.app/
## A QUICK AND EASY WAY TO MANAGE YOUR PERSONAL FINANCES!
### See Your Budget at a Glance, & Quickly Calculate Your Expenses
#### - Add Your Bills & Income for the Month!
#### - See How Much You Have Left Over!
#### - Plan Towards Paying Down Your Long Term Debt!
***
## API Documentation:
> ** In order to Access This Information, A User Must Be Authenticated **
#### GET /api/bills
Retrieves the user's bills that have been added for the current month. Returns a response like the following:
{
"id": 5,
"bill_name": "Mortgage",
"bill_amt": 5757,
"amt_paid": 586,
"month": "January",
"user_id": 548264648,
"year": 2021,
"date": null,
"paid": false
}
#### POST /api/bills
In order to post successfully, a user must be logged in. This POST method will retrieve your user information and authentication status before attempting to post.
See the example below:
method: "POST",
headers: { "content-type": "application/json", token: `${token}` },
body: {
"bill_name" : "<NAME>",
"bill_amt" : "500",
"amt_paid" : "0",
"month" : "january",
}
***
## Technology info:
### Backend:
<ul>
<li>Node for interacting with the file system</li>
<li>Express for handling API requests</li>
<li>Knex.js for interacting with the PostgreSQL database</li>
<li>Postgrator for database migration</li>
<li>Mocha, Chai, Supertest for testing</li>
<li>JSON Web Token and bcryptjs for user authentication / authorization</li>
</ul>
***
### Front End:
<ul>
<li>React</li>
<li>HTML5</li>
<li>CSS3</li>
<li>Jest/Enzyme</li>
</ul>
<file_sep>/Services/Income/incomeService.js
const IncomeServices = {
addNewIncome(knex, newEntry){
return knex
.insert(newEntry)
.into('income')
.returning('*')
.then(rows => {
return rows[0];
});
},
getById(knex, id) {
return knex
.from('income')
.select('*')
.where('user_id', id);
},
updateIncome(knex, id, newIncomeFields) {
return knex('income')
.where('id', id)
.update(newIncomeFields);
},
deleteIncome(knex, id) {
return knex('income')
.where('id', id)
.delete();
},
};
module.exports = IncomeServices;<file_sep>/migrations/003.undo.create_income.sql
DROP TABLE "income";<file_sep>/migrations/002.do.create_bills.sql
CREATE TABLE IF NOT EXISTS "bills"
(
id int NOT NULL GENERATED BY DEFAULT AS IDENTITY,
bill_name text NOT NULL,
bill_amt int NOT NULL,
amt_paid int NOT NULL DEFAULT 0,
month text NOT NULL,
user_id integer NOT NULL,
year integer NOT NULL DEFAULT 2021,
date date NULL,
paid boolean NOT NULL DEFAULT false,
CONSTRAINT PK_bills PRIMARY KEY ( "id" ),
CONSTRAINT FK_19 FOREIGN KEY ( user_id ) REFERENCES "user" ( user_id )
);
CREATE INDEX fkIdx_20 ON bills
(
user_id
);
<file_sep>/migrations/003.do.create_income.sql
CREATE TABLE IF NOT EXISTS income
(
"id" int NOT NULL GENERATED BY DEFAULT AS IDENTITY,
source text NOT NULL,
amount integer NOT NULL,
user_id integer NOT NULL,
month text NOT NULL,
year integer NOT NULL DEFAULT 2021,
received boolean NOT NULL DEFAULT false,
date date NULL,
CONSTRAINT PK_income PRIMARY KEY ( "id" ),
CONSTRAINT FK_28 FOREIGN KEY ( user_id ) REFERENCES "user" ( user_id )
);
CREATE INDEX fkIdx_29 ON income
(
user_id
);
<file_sep>/Services/Users/userService.js
const bcrypt = require('bcrypt');
const Services= {
getAllUsers(knex) {
return knex.select('*').from('user');
},
checkForUser(knex, user_name) {
return knex
.from('user')
.select('*')
.where('user_name', user_name)
.first();
},
insertUser(knex, first_name, user_name, password) {
return knex
.insert({first_name, user_name, password})
.into('user')
.returning('*')
.then(rows => {
return rows;
});
},
getById(knex, id) {
return knex
.select('*')
.from('user')
.where('user_id', id)
.first();
},
getUserWithUserName(db, user_name) {
return db('user')
.where({ user_name })
.first();
},
comparePasswords(password, hash) {
return bcrypt.compare(password, hash);
},
getUserDash(knex, id) {
return knex
.select('first_name')
.from('user')
.where('user_id', id)
.first();
}
};
module.exports = Services;<file_sep>/migrations/002.undo.create_bills.sql
DROP TABLE "bills";<file_sep>/migrations/004.do.create_debt.sql
CREATE TABLE IF NOT EXISTS debt
(
"id" int NOT NULL GENERATED BY DEFAULT AS IDENTITY,
name text NOT NULL,
start_bal int NOT NULL,
curr_bal int NOT NULL,
monthly_min int NOT NULL,
amt_paid int NOT NULL DEFAULT 0,
user_id integer NOT NULL,
month text NOT NULL,
year integer NOT NULL DEFAULT 2021,
paid boolean NOT NULL DEFAULT false,
date date NULL,
CONSTRAINT PK_debt PRIMARY KEY ( "id" ),
CONSTRAINT FK_39 FOREIGN KEY ( user_id ) REFERENCES "user" ( user_id )
);
CREATE INDEX fkIdx_40 ON debt
(
user_id
);
| 46ba475df68273b63fce77b5d2970924f1bc1da2 | [
"JavaScript",
"SQL",
"Markdown"
] | 13 | JavaScript | apullenb/myBudget-api | 1505cd1b331c8bc88399b54fcf1b92c457be1a7b | 5f6a0cded3f65316dc6a26adb3651817bd2f6d31 |
refs/heads/main | <repo_name>gitsans/Tic-Tac-Toe<file_sep>/src/Board.java
import java.util.*;
public class Board {
String userState;
String jvmState;
boolean winnerFlag;
int size = 0;
// Index VS Character
// X -> 1 && O -> 0
// false -> Player
HashMap<Integer, String> map = new HashMap<>();
public Board(String state) {
this.userState = state;
this.jvmState = (userState.equals("X")) ? "O" : "X";
}
public String getValue(int key) {
if(map.containsKey(key))
return " " + map.get(key) + " ";
return " ";
}
public void display() {
System.out.println(getValue(1) + "|" + getValue(2) + "|" + getValue(3));
System.out.println("---+---+---");
System.out.println(getValue(4) + "|" + getValue(5) + "|" + getValue(6));
System.out.println("---+---+---");
System.out.println(getValue(7) + "|" + getValue(8) + "|" + getValue(9));
}
public int getJVMMove() {
int temp = (int)Math.round(Math.random()*9);
return temp;
}
public void add(int index) {
if(map.containsKey(index) || index<1 || index>9) {
System.out.println("Invalid Choice!");
return;
}
else {
map.put(index, userState);
size++;
System.out.println(size);
if(size==9)
return;
int randomIndex = getJVMMove();
while(map.containsKey(randomIndex) || randomIndex==0)
randomIndex = getJVMMove();
map.put(randomIndex, jvmState);
size++;
}
}
public boolean firstRow() {
if(map.containsKey(1) && map.containsKey(2) && map.containsKey(3)) {
if(map.get(1).equals(userState)) {
if(map.get(2).equals(userState) && map.get(3).equals(userState)) {
winnerFlag = false;
return true;
}
}
else {
if(map.get(2).equals(jvmState) && map.get(3).equals(jvmState)) {
winnerFlag = true;
return true;
}
}
}
return false;
}
public boolean secondRow() {
if(map.containsKey(4) && map.containsKey(5) && map.containsKey(6)) {
if(map.get(4).equals(userState)) {
if(map.get(5).equals(userState) && map.get(6).equals(userState)) {
winnerFlag = false;
return true;
}
}
else {
if(map.get(6).equals(jvmState) && map.get(6).equals(jvmState)) {
winnerFlag = true;
return true;
}
}
}
return false;
}
public boolean thirdRow() {
if(map.containsKey(7) && map.containsKey(8) && map.containsKey(9)) {
if(map.get(7).equals(userState)) {
if(map.get(8).equals(userState) && map.get(9).equals(userState)) {
winnerFlag = false;
return true;
}
}
else {
if(map.get(8).equals(jvmState) && map.get(9).equals(jvmState)) {
winnerFlag = true;
return true;
}
}
}
return false;
}
public boolean firstCol() {
if(map.containsKey(1) && map.containsKey(4) && map.containsKey(7)) {
if(map.get(1).equals(userState)) {
if(map.get(4).equals(userState) && map.get(7).equals(userState)) {
winnerFlag = false;
return true;
}
}
else {
if(map.get(4).equals(jvmState) && map.get(7).equals(jvmState)) {
winnerFlag = true;
return true;
}
}
}
return false;
}
public boolean secondCol() {
if(map.containsKey(2) && map.containsKey(5) && map.containsKey(8)) {
if(map.get(2).equals(userState)) {
if(map.get(5).equals(userState) && map.get(8).equals(userState)) {
winnerFlag = false;
return true;
}
}
else {
if(map.get(5).equals(jvmState) && map.get(8).equals(jvmState)) {
winnerFlag = true;
return true;
}
}
}
return false;
}
public boolean thirdCol() {
if(map.containsKey(3) && map.containsKey(6) && map.containsKey(9)) {
if(map.get(3).equals(userState)) {
if(map.get(6).equals(userState) && map.get(9).equals(userState)) {
winnerFlag = false;
return true;
}
}
else {
if(map.get(6).equals(jvmState) && map.get(9).equals(jvmState)) {
winnerFlag = true;
return true;
}
}
}
return false;
}
public boolean firstDiagnol() {
if(map.containsKey(1) && map.containsKey(5) && map.containsKey(9)) {
if(map.get(1).equals(userState)) {
if(map.get(5).equals(userState) && map.get(9).equals(userState)) {
winnerFlag = false;
return true;
}
}
else {
if(map.get(5).equals(jvmState) && map.get(9).equals(jvmState)) {
winnerFlag = true;
return true;
}
}
}
return false;
}
public boolean secondDiagnol() {
if(map.containsKey(3) && map.containsKey(5) && map.containsKey(7)) {
if(map.get(3).equals(userState)) {
if(map.get(5).equals(userState) && map.get(7).equals(userState)) {
winnerFlag = false;
return true;
}
}
else {
if(map.get(5).equals(jvmState) && map.get(7).equals(jvmState)) {
winnerFlag = true;
return true;
}
}
}
return false;
}
public boolean getWinner() {
if(map.containsKey(1) && map.containsKey(2) && map.containsKey(3) && map.containsKey(4) && map.containsKey(5) && map.containsKey(6) && map.containsKey(7) && map.containsKey(8) && map.containsKey(9)) {
System.out.println("Draw!!!");
System.exit(1);
}
return firstRow() || secondRow() || thirdRow() || firstCol() || secondCol() || thirdCol() || firstDiagnol() || secondDiagnol();
}
}<file_sep>/README.md
Focused on semantic issues.<file_sep>/src/App.java
import java.io.*;
import java.util.*;
public class App {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("************ Tic Tac Toe ************");
System.out.println("Enter your choice \n1) X \n2) O");
String choice = sc.next();
choice = choice.toUpperCase();
Board tictactoe = new Board(choice);
System.out.println("Welcome Player!");
tictactoe.display();
do {
System.out.print("Enter your position: ");
int index = sc.nextInt();
tictactoe.add(index);
tictactoe.display();
} while(!tictactoe.getWinner());
if(tictactoe.winnerFlag)
System.out.println("JVM is the winner!!!");
else
System.out.println("Player is the winner!!!");
}
}
| af178eb0544b6e6d50c1c746a234d504d357e9cd | [
"Markdown",
"Java"
] | 3 | Java | gitsans/Tic-Tac-Toe | 861ae1e1c023ded94c2e50e683379ec492131a6c | fd3d1b6b32597a40dcde6bf9a3bc115a37549452 |
refs/heads/master | <repo_name>kelseyzzz/PlugIn-Homework<file_sep>/assets/js/main.js
console.log("Hello World from main.js!");
$.jInvertScroll(['.wedding']);
(function($) {
$.jInvertScroll(['.wedding'], // an array containing the selector(s) for the elements you want to animate
{
height: 9000, // optional: define the height the user can scroll, otherwise the overall length will be taken as scrollable height
onScroll: function(percent) { //optional: callback function that will be called when the user scrolls down, useful for animating other things on the page
console.log(percent);
}
})
}) | 44761aef48851c4c82ab56ed2251ce76192d49c4 | [
"JavaScript"
] | 1 | JavaScript | kelseyzzz/PlugIn-Homework | 0a1aab4ac16d30f3ed6227da9fbe113cbe07d040 | b9edfd2f5e7beff9e57e01fa19e81d641ca6b63e |
refs/heads/master | <repo_name>ArchimediaZerogroup/alchemy-ajax-form<file_sep>/config/initializer/assets.rb
Rails.application.config.assets.precompile << 'alchemy_ajax_form_manifest.js'<file_sep>/test/alchemy/ajax/form_test.rb
require 'test_helper'
class Alchemy::Ajax::Form::Test < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, Alchemy::Ajax::Form
end
end
<file_sep>/app/views/alchemy/ajax_forms/create.json.jbuilder
if @object.errors.empty?
json.messages t(:form_sended_succesfully)
else
json.messages @object.errors.full_messages
json.errors @object.errors
end<file_sep>/README.md
# Alchemy::Ajax::Form
A gem for semplify form creations in alchemy.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'alchemy-ajax-form', github: "ArchimediaZerogroup/alchemy-ajax-form"
```
And then execute:
```bash
$ bundle install
```
Or install it yourself as:
```bash
$ gem install alchemy-ajax-form
```
install mjml 4.1.0 with npm globally (with sudo if necessary)
```bash
$ npm install mjml@4.1.0 -g
```
## Usage
Launch the generator with this command:
```bash
$ bin/rails generate custom_form name_of_form param:type
```
example:
```bash
$ bin/rails generate custom_form contact_form email:string firstname:string lastname:string message:text
```
Ansawer to the questions step by step
Configure element in layoutpage
Restart Server
### How use without generator
If you don't wont use the generator you have to follow these steps:
Let's assume we want to create the form "ContactForm"
#### Create Admin Controller
Create Admin::ContactFormsController (/app/controllers/admin/contact_forms_controller.rb)
```ruby
class Admin::ContactFormsController < Alchemy::Admin::AjaxFormsController
end
```
#### Create Controller
Create ContactFormsController (/app/controllers/admin/contact_forms_controller.rb)
```ruby
class ContactFormsController < Alchemy::AjaxFormsController
end
```
#### Create Resource
Create ContactFormResource (app/lib/contact_form_resource.rb)
```ruby
class ContactFormResource < Alchemy::AjaxFormResource
end
```
#### Create Model
Create ContactForm (app/models/contact_form.rb)
```ruby
class ContactForm < Alchemy::AjaxForm
validates :check_privacy, inclusion: [true, '1']
def notify_subject
I18n.translate(:contact_form_notify, scope: [:ajax_form_mailer, :subjects])
end
def notify_user_subject
I18n.translate(:contact_form_user_notify, scope: [:ajax_form_mailer, :subjects])
end
end
```
#### Create Ability
Create ContactFormAbility (app/models/contact_form_ability.rb)
```ruby
class ContactFormAbility
include CanCan::Ability
def initialize(user)
if user.present? && user.is_admin?
can :manage, ContactForm
cannot :create, ContactForm
cannot :update, ContactForm
can :manage, :admin_contact_forms
cannot :create, :admin_contact_forms
cannot :update, :admin_contact_forms
end
end
end
```
#### Create Migration
Create CreateContactForm (db/migrate/%Y%m%d%H%M%Screate_contact_form.rb)
```ruby
class CreateContactForm < ActiveRecord::Migration[5.2]
def change
create_table :contact_forms do |t|
# insert all form fields
t.boolean :check_privacy
t.references :language, index: true
t.timestamps
end
end
end
```
#### Create Element Configuration
Insert into file "config/alchemy/elements.yml"
```yaml
- name: contact_form
hint: false
contents:
- name: privacy_page
type: EssenceText
settings:
linkable: true
- name: recipient_notification
type: EssenceText
default: "<EMAIL>"
- name: send_only
type: EssenceBoolean
- name: send_staff
type: EssenceBoolean
- name: send_user
type: EssenceBoolean\n
```
#### Create Element View
Create contact form view "app/views/alchemy/elements/_contact_form_view.html.erb"
```erbruby
<% cache(element) do %>
<%= element_view_for(element) do |el| -%>
<%
privacy_link = element.content_by_name(:privacy_page).essence.link
privacy_title = element.content_by_name(:privacy_page).essence.body
@contact_form = ContactForm.new
@contact_form.alcm_element = element.id
%>
<div class="messages"></div>
<%= form_for(@contact_form, url: main_app.contact_forms_path, method: :post, remote: true, multipart: true,html:{class: "ajax_forms"}) do |f| %>
<%= f.hidden_field :alcm_element %>
<div class="row">
#list of attributes
</div>
<% if !privacy_title.blank? %>
<div class="privacy">
<div class="single_privacy">
<%= f.check_box :check_privacy %>
<%= link_to privacy_link do %>
<label><%= privacy_title %></label>
<% end %>
</div>
</div>
<% else %>
<%= f.check_box :check_privacy %>
<% end %>
<div class="submit">
<%= f.submit t(:submit) %>
</div>
<% end %>
<%- end -%>
<%- end -%>
```
#### Create or add entry to initializer
Create or edit alchemy_ahax_forms initializer ( config/initializers/alchemy_ajax_forms.rb)
```ruby
Alchemy::Modules.register_module({
name: 'alchemy_ajax_forms',
order: 1,
navigation: {
name: 'modules.contact_forms',
controller: '/admin/contact_forms',
action: 'index',
image: 'alchemy/ajax_form.png',
sub_navigation: [
{
name: 'modules.contact_forms',
controller: '/admin/contact_forms',
action: 'index'
},
]
}
})
Alchemy.register_ability(ContactFormAbility)
module Alchemy
EMAIL_NOTIFY= "<EMAIL>"
EMAIL_NOTIFY_FROM = "<EMAIL>"
end
```
If you add multiple form add only:
```ruby
{
name: 'modules.contact_forms',
controller: '/admin/contact_forms',
action: 'index'
}
```
and ability
```ruby
Alchemy.register_ability(ContactFormAbility)
```
#### Create Mail Template
Create email template ()app/views/alchemy/ajax_forms_mailer/_contact_form.mjml)
Create email template for user notification ()app/views/alchemy/ajax_forms_mailer/_contact_form_user.mjml)
```ruby
<mj-column>
<mj-text align="left" color="#55575d" font-family="Arial, sans-serif" font-size="13px" line-height="22px" padding-bottom="0px" padding-top="5px" padding="10px 25px">
<p style="line-height: 16px; text-align: center; margin: 10px 0;font-size:12px;color:#000;font-family:'Times New Roman',Helvetica,Arial,sans-serif">
<span><b>attribute name:</b></span>
<span><%= rec.attribute_name %></span>
</p>
</mj-text>
</mj-column>
```
#### Add Routes
Add right routes
```ruby
namespace :admin do
resources :contact_forms
end
resources :contact_forms , only: [:create]
```
#### Require assets
Add to app/assets/javascripts/application.js
```ruby
//= require jquery3
//= require ajax_forms
```
Add to vendor/assets/stylesheets/alchemy/admin/all.css
```ruby
*= require alchemy/ajax/form/backend/custom_resource_show
```
Add to app/assets/stylesheets/application.css
```ruby
*= require alchemy/ajax/form/style
```
### Run Migration
Run migration with rake task
```bash
$ bin/rake db:migrate
```
Configure element in layoutpage
Restart Server
## Translations
Remember to check translations
## Disable MJML
If you don't want mjml, insert in an initializer
```ruby
Alchemy::Ajax::Form.enable_mjml= false
```
n.b. Disable mjml before launching the generator, otherwise email templates will be generated with mjml
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
<file_sep>/app/models/alchemy/ajax_form_ability.rb
module Alchemy
class AjaxFormAbility
include CanCan::Ability
def initialize(user)
if user.present? && user.is_admin?
# can :manage, ::UserSiteRegistration
# can :manage, :admin_user_site_registrations
can :manage, AjaxForm
cannot :create, AjaxForm
cannot :update, AjaxForm
can :manage, :admin_ahjax_forms
cannot :create, :admin_ajax_forms
cannot :update, :admin_ajax_forms
end
end
end
end<file_sep>/app/controllers/alchemy/ajax_forms_controller.rb
module Alchemy
class AjaxFormsController < Alchemy::BaseController
def create
@object = base_class.new permitted_resource_attributes
if verify_recaptcha(model: @object) && @object.valid?
#registro dati, invio email
unless @object.send_only?
@object.save
end
@object.mail_deliver
render formats: :json
else
render formats: :json, status: :not_acceptable
end
end
private
def permitted_resource_attributes
params.require(base_class.to_s.demodulize.underscore).permit!
end
def base_class
controller_name.classify.constantize
end
end
end<file_sep>/lib/alchemy/ajax/form.rb
require "alchemy_cms"
require "js-routes"
require "recaptcha/rails"
require "mjml-rails"
require "recaptcha"
require "alchemy/ajax/form/engine"
module Alchemy
module Ajax
module Form
# Your code goes here...
mattr_accessor :enable_mjml, :recaptcha_badge
@@enable_mjml = true
@@recaptcha_badge = 'inline'
end
end
end
<file_sep>/app/models/alchemy/ajax_form.rb
module Alchemy
class AjaxForm < ApplicationRecord
self.abstract_class = true
belongs_to :language, class_name: "Alchemy::Language", optional: true, required: false
def site
language.try(:site)
end
def notify_subject
I18n.translate(:default_notification_subject, scope: [:ajax_form_mailer, :subjects])
end
def notify_user_subject
I18n.translate(:default_notification_user_subject, scope: [:ajax_form_mailer, :subjects])
end
validates :email, :presence => {allow_blank: false}, if: -> {respond_to? :email}
validates_format_of :email, :with => /\A([-a-z0-9!\#$%&'*+\/=?^_`{|}~]+\.)*[-a-z0-9!\#$%&'*+\/=?^_`{|}~]+@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i,
if: -> {respond_to? :email and !self.email.blank?}
#with alchemy element can retrieve settings of form (ex. recipient_notification)
attr_accessor :alcm_element
before_save -> {self.language = Alchemy::Language.current}
def send_only?
element_alchemy.content_by_name(:send_only).essence.value
rescue
false
end
def send_to_staff?
element_alchemy.content_by_name(:send_staff).essence.value
rescue
false
end
def send_to_user?
element_alchemy.content_by_name(:send_user).essence.value and respond_to? :email
rescue
false
end
def mail_deliver
if send_to_staff?
AjaxFormsMailer.notify_message(self).deliver_now
end
if send_to_user?
AjaxFormsMailer.notify_message_user(self).deliver_now
end
end
def element_alchemy
Alchemy::Element.find(self.alcm_element)
end
def emails_recipient
element_alchemy.content_by_name(:recipient_notification).essence.body
rescue
Alchemy::EMAIL_NOTIFY
end
end
end<file_sep>/app/helpers/alchemy/admin/ajax_forms_helper.rb
module Alchemy
module Admin
module AjaxFormsHelper
def alchemy_body_class
[
"ajax_forms",
controller_name,
action_name,
content_for(:main_menu_style),
content_for(:alchemy_body_class)
].compact
end
def search_panel(options = {}, &block)
submit_button = options.fetch(:enable_submit, true)
klass = options.delete(:class) || []
content_tag(:div, class: "search_panel #{klass.join(" ")}", ** options) do
if @query
simple_form_for(@query, url: polymorphic_path([:admin, @query.klass]), method: :get) do |f|
sb = ActiveSupport::SafeBuffer.new
sb << content_tag(:div, class: "search_fields_group") do
search_fields = ActiveSupport::SafeBuffer.new
search_fields << f.input(resource_handler.search_field_name,
label: false,
input_html: {
class: 'search_input_field',
placeholder: Alchemy.t(:search)
},
wrapper_html: {
class: "full-width"
}
)
search_fields << capture do
block.call(f)
end
search_fields
end
if submit_button
sb << content_tag(:div, class: "action_buttons") do
f.submit(::I18n.t('alchemy_ajax_form.submit_search'))
end
end
sb
end
end
end
end
end
end
end<file_sep>/lib/generators/custom_form/custom_form_generator.rb
class CustomFormGenerator < Rails::Generators::NamedBase
include Rails::Generators::Migration
source_root File.expand_path('../templates', __FILE__)
argument :attributes, type: :array, required: false
attr_accessor :model_attributes
desc "Create amin controller"
def add_admin_cotroller
template "app/controllers/admin/generic_controller.rb.tt", "app/controllers/admin/#{name.underscore.pluralize}_controller.rb"
end
desc "Create controller"
def add_controller
template "app/controllers/generic_controller.rb.tt", "app/controllers/#{name.underscore.pluralize}_controller.rb"
end
desc "Create Resource"
def add_resource
template "app/lib/generic_resource.rb.tt", "app/lib/#{name.singularize.underscore}_resource.rb"
end
desc "Create model"
def add_model
# inserted_attributes = attributes
#
# self.attributes = ["gfgdfgdfg:skdkfjdkf"]
# parse_attributes!
#
# say self.attributes + inserted_attributes
#
inserted_attributes = []
if attributes.empty?
ask_attribute
else
inserted_attributes = attributes
self.attributes = []
ask_attribute "Do you want add attributes?"
end
parse_attributes!
self.attributes = inserted_attributes + self.attributes unless inserted_attributes.empty?
migration_template "db/migrate/generic_migration.rb.tt", "db/migrate/create_#{name.singularize.underscore}.rb"
template "app/model/generic_form.rb.tt", "app/models/#{name.singularize.underscore}.rb"
template "app/model/generic_ability.rb.tt", "app/models/#{name.singularize.underscore}_ability.rb"
end
desc "Create elements view"
def add_element_view
template "app/views/alchemy/elements/_generic_ajax_form_view.html.erb.tt",
"app/views/alchemy/elements/_#{name.underscore.singularize}_view.html.erb"
end
desc "Create initializer"
def add_initializer
#
file ="#{Rails.root}/config/initializers/alchemy_ajax_forms.rb"
if !File.exist? file
template "config/initializers/alchemy_ajax_forms.rb.tt","config/initializers/alchemy_ajax_forms.rb"
else
insert_into_file file, before: "]" do
<<-code
{
name: 'modules.#{name.underscore.pluralize}',
controller: '/admin/#{name.underscore.pluralize}',
action: 'index'
},
code
end
append_to_file file do
"\nAlchemy.register_ability(#{name.singularize.classify}Ability)\n"
end
end
end
desc "Add email template"
def add_mail_template
ext = "html.erb"
ext = "mjml" if Alchemy::Ajax::Form.enable_mjml
template "app/views/alchemy/ajax_forms_mailer/_generic_form.html.erb.tt",
"app/views/alchemy/ajax_forms_mailer/_#{name.underscore.singularize}.#{ext}"
template "app/views/alchemy/ajax_forms_mailer/_generic_user_form.html.erb.tt",
"app/views/alchemy/ajax_forms_mailer/_#{name.underscore.singularize}_user.#{ext}"
end
desc "Add element configuration"
def add_element_config
append_to_file "config/alchemy/elements.yml", <<-element
- name: #{name.singularize.underscore}
hint: false
contents:
- name: privacy_page
type: EssenceText
settings:
linkable: true
- name: recipient_notification
type: EssenceText
default: "<EMAIL>"
- name: send_only
type: EssenceBoolean
- name: send_staff
type: EssenceBoolean
- name: send_user
type: EssenceBoolean\n
element
end
desc "Add needed routes"
def add_routes
routes_path = Rails.root + "config/routes.rb"
if File.exist?(routes_path) and File.readlines(routes_path).grep(/namespace :admin do/).count > 0
insert_into_file routes_path, :after => "namespace :admin do\n" do
"\nresources :#{name.underscore.pluralize}\n"
end
route "\nresources :#{name.underscore.pluralize}\n"
else
route <<-route
\nnamespace :admin do
resources :#{name.underscore.pluralize}
end
resources :#{name.underscore.pluralize} , only: [:create]\n
route
end
end
desc "Require needed assets"
def add_assets
inject_into_file "app/assets/javascripts/application.js" , before: '//= require_tree .' do
"\n//= require jquery3\n//= require ajax_forms\n"
end
inject_into_file "vendor/assets/stylesheets/alchemy/admin/all.css" , before: '*= require_tree .' do
"\n*= require alchemy/ajax/form/backend/custom_resource_show\n"
end
# inject_into_file "app/assets/stylesheets/application.css", {} do
# "\n*= require alchemy/ajax/form/style\n"
# end
# inject_into_file "app/assets/stylesheets/application.*" , before: '*= require alchemy/ajax/form/style' do
# "\n*= require @fortawesome/fontawesome-free/css/all\n"
# end
# inject_into_file "app/assets/javascripts/application.js", {} do
# "\n//= @fortawesome/fontawesome-free/js/all\n"
# end
end
desc "Run migration and install mjml and create alchemy elements"
def run_scripts
rake("db:migrate")
#run "npm install mjml"
run "yarn add @fortawesome/fontawesome-free"
generate("alchemy:elements","--skip")
end
private
def ask_attribute mex = nil
if mex.nil?
response = ask "Insert an attribute name (q for exit)"
if response.downcase != "q"
self.attributes << response unless response.blank?
ask_attribute
end
else
response = ask mex, :limited_to => ["y", "n"]
if response.downcase == "y"
ask_attribute
end
end
end
def self.next_migration_number(dir)
Time.now.utc.strftime("%Y%m%d%H%M%S")
end
end
<file_sep>/app/controllers/alchemy/admin/ajax_forms_controller.rb
module Alchemy
module Admin
class AjaxFormsController < ResourcesController
def resource_handler
@_resource_handler ||= "::#{controller_name.classify}Resource".constantize.new(controller_path, alchemy_module)
end
def index
@query = resource_handler.model.joins(language: :site).ransack(search_filter_params[:q])
items = @query.result
items = items.order(created_at: :desc)
if contains_relations?
items = items.includes(*resource_relations_names)
end
if search_filter_params[:tagged_with].present?
items = items.tagged_with(search_filter_params[:tagged_with])
end
if search_filter_params[:filter].present?
items = items.public_send(sanitized_filter_params)
end
respond_to do |format|
format.html {
items = items.page(params[:page] || 1).per(items_per_page)
instance_variable_set("@#{resource_handler.resources_name}", items)
}
format.csv {
instance_variable_set("@#{resource_handler.resources_name}", items)
}
end
end
def show
end
protected
def common_search_filter_includes
[
# contrary to Rails' documentation passing an empty hash to permit all keys does not work
{options: options_from_params.keys},
{q: [resource_handler.search_field_name, :s].push(*permitted_ransack_attributes)},
:tagged_with,
:filter,
:page
].freeze
end
def permitted_ransack_attributes
[:language_id_eq, :language_site_id_eq]
end
def load_resource
@resource = resource_handler.model.find(params[:id])
instance_variable_set("@#{resource_handler.resource_name}", @resource)
end
end
end
end
<file_sep>/alchemy-ajax-form.gemspec
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "alchemy/ajax/form/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "alchemy-ajax-form"
s.version = Alchemy::Ajax::Form::VERSION
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = ""
s.summary = "Structure to implement the forms using ajax and management in the backend"
s.description = "Structure to implement the forms using ajax and management in the backend"
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
s.add_dependency "rails", "~> 5.0"
s.add_dependency "js-routes", "~>1.0"
s.add_dependency "sass-rails", "~> 5.0"
s.add_dependency 'alchemy_cms', '~> 4.0'
s.add_dependency 'recaptcha','~> 4.7'
s.add_dependency 'mjml-rails','~> 4.1'
s.add_dependency 'jquery-rails','~>4.0'
#s.add_development_dependency "sqlite3"
end
<file_sep>/app/mailers/alchemy/ajax_forms_mailer.rb
module Alchemy
class AjaxFormsMailer < ApplicationMailer
if Alchemy::Ajax::Form.enable_mjml
layout "alchemy/mjml_base_mailer"
else
layout "alchemy/base_mailer"
end
include Alchemy::ConfigurationMethods
add_template_helper(Alchemy::PagesHelper)
def notify_message(r)
@rec = r
reply_to = @rec.email if @rec.respond_to? :email
if Alchemy::Ajax::Form.enable_mjml
mail(from: Alchemy::EMAIL_NOTIFY_FROM, to: r.emails_recipient, subject: r.notify_subject, reply_to: reply_to) do |format|
format.mjml { render "mjml_notify_message", locals: {recipient: @rec} }
end
else
mail(from: Alchemy::EMAIL_NOTIFY_FROM, to: r.emails_recipient, subject: r.notify_subject, reply_to: reply_to)
end
end
def notify_message_user(r)
@rec = r
if Alchemy::Ajax::Form.enable_mjml
mail(to: @rec.email, from: Alchemy::EMAIL_NOTIFY_FROM, subject: @rec.notify_user_subject) do |format|
format.mjml { render "mjml_notify_user_message", locals: {recipient: @rec} }
end
else
mail(to: @rec.email, from: Alchemy::EMAIL_NOTIFY_FROM, subject: @rec.notify_user_subject) do |format|
format.html {render "notify_user_message"}
end
end
end
end
end
<file_sep>/lib/alchemy/ajax_form_resource.rb
module Alchemy
class AjaxFormResource < Resource
def attributes
attr = super.reject {|c| [:check_privacy,:language_id].include?(c[:name].to_sym)}
attr += [{
name: :language,
relation: {
name: :language,
model_association: Alchemy::Language,
attr_method: :name
}
},
{
name: :site,
relation: {
name: :site,
model_association: Alchemy::Site,
attr_method: :name
}
}]
end
def searchable_attribute_names
if model.column_names.include? "email"
[:email]
else
[]
end
end
def search_field_name
searchable_attribute_names.join("_or_") + "_cont"
end
end
end<file_sep>/lib/alchemy/ajax/form/version.rb
module Alchemy
module Ajax
module Form
VERSION = '1.2.1'
end
end
end
<file_sep>/lib/alchemy/ajax/form/engine.rb
module Alchemy
module Ajax
module Form
class Engine < ::Rails::Engine
isolate_namespace Alchemy::Ajax::Form
config.autoload_paths << config.root.join('lib')
initializer "alchemy_ajax_form.assets.precompile" do |app|
app.config.assets.precompile << 'alchemy_ajax_form_manifest.js'
end
# initializer "alchemy_ajax_form.assets.precompile" do |app|
# app.config.assets.precompile << %w(alchemy/ajax_form.png)
# end
end
end
end
end
| 9b1391730431fe49986a3019b581c82330ee62ad | [
"Markdown",
"Ruby"
] | 16 | Ruby | ArchimediaZerogroup/alchemy-ajax-form | bfa89fdff47c67a67b6881c848b4f03e63936fac | bdc7cfedfe157684f02ad5f58ffddee0345c3ba4 |
refs/heads/master | <file_sep>var MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
console.error('Missing MONGODB_URI environment variable.');
process.exit(1);
}
// Require express and mongoose
var express = require("express");
var mongoose = require("mongoose");
//require all models
var db = require("./models");
// Set up listening port
var PORT = process.env.PORT || 80;
var app = express();
// Setup public directory
app.use(express.static("public"));
// middleware to parse body as JSON
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Set Handlebars.
var exphbs = require("express-handlebars");
app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");
mongoose.connect(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
// Routes
require("./routes/apiRoutes")(app);
require("./routes/htmlRoutes")(app);
// Start the server
app.listen(PORT, function() {
console.log("App running on port http://localhost:" + PORT + "/");
});
<file_sep>// Save an Article => set saved to true
function scrapeArticles(){
$.ajax({
method: "GET",
url: "/scrape"
}).then(function() {
location.reload();
});
}
function saveArticle(){
var articleId = $(this).data("id");
console.log(articleId);
$.ajax({
method: "POST",
url: "/api/saved/" + articleId,
}).then(function () {
location.reload();
});
}
// Save Note
function saveNote(){
var articleId = $(this).attr("data-id-article");
var newNote = $("#" + articleId).val().trim();
console.log(articleId, newNote);
$.ajax({
method: "POST",
url: "/api/saved/notes/" + articleId,
data: {
body: newNote
}
}).then(function() {
location.reload();
});
}
function deleteNote(){
var noteId = $(this).attr("data-id-note");
console.log('clicked', noteId);
$.ajax({
method: "DELETE",
url: "/api/notes/" + noteId
}).then(function() {
location.reload();
});
}
function deleteArticle(){
var articleId = $(this).attr("data-id-article");
$.ajax({
method: "DELETE",
url: "/api/articles/" + articleId
}).then(function() {
location.reload();
});
}
function clearAll(){
$.ajax({
method: "DELETE",
url:"/api/articles"
}).then(function () {
location.reload();
});
}
$("#scrape-btn").on("click", scrapeArticles);
$("#clear-btn").on("click", clearAll);
$(".save-btn").on("click", saveArticle);
$(".save-note-btn").on("click", saveNote);
$(".delete-note-btn").on("click", deleteNote);
$(".delete-article-btn").on("click", deleteArticle);
<file_sep># Project Name
All-the-news
## Table of contents
* [General info](#general-info)
* [Technologies](#technologies)
* [Setup](#setup)
* [Features](#features)
* [Status](#status)
* [Contact](#contact)
## General info
All-the-news is a news scraper that displays articles about the current political climate.
## Technologies
* [Node](https://nodejs.org)
* [Mongo](https://www.mongodb.com/)
* [Mongoose](https://mongoosejs.com/)
* [Express](https://expressjs.com/)
* [Axios](https://www.npmjs.com/package/axios)
* [Bootstrap](https://www.mongodb.com/)
## Setup
Make a `.env` file in the root directory containing your MongoDB connection string.
```
MONGODB_URI=
```
Then run the following command to start the web server:
```console
npm start
```
You can check out the heroku deployed site here: https://all-the-news123.herokuapp.com/
## Features
List of features ready and TODOs for future development
* Feature: Ability to save articles for later reading
* To do: Ability to add a note onto the article
## Status
Project is: Finished
## Contact
Created by [@tlacy1000](https://www.lacytammy.com/) - feel free to contact me!
<file_sep>var db = require("../models");
module.exports = function (app) {
// Load index page
app.get("/", function (req, res) {
db.Article.find({ "saved": false }, function (error, data) {
var hbsObject = {
article: data
};
// console.log(hbsObject);
res.render("index", hbsObject);
});
});
app.get("/saved", function (req, res) {
db.Article.find({ saved: true }).populate("note").exec(function(error, data) {
var hbsObject = {
article: data
};
if(error){
res.send(error)
} else {
res.render("saved", hbsObject);
}
});
});
// Render 404 page for any unmatched routes
app.get("*", function (req, res) {
res.render("404");
});
};
<file_sep>// Axios and cheerio to query and scrape
var axios = require("axios");
var cheerio = require("cheerio");
var db = require("../models");
module.exports = function(app) {
app.get("/scrape", function(req, res) {
axios.get("https://fivethirtyeight.com/politics/").then(function(response) {
var $ = cheerio.load(response.data);
$(".fte_features").each(function(i, element) {
// Create an empty result object
var result = {};
// Add the text and href and image of every link, and save them as properties of the result object
result.title = $(element)
.find(".article-title")
.children("a")
.text()
.trim();
result.link = $(element)
.children("a")
.attr("href");
result.image = $(element)
.children("a")
.children("img")
.attr("src");
console.log(result);
// Create a new Article using the `result` object built from scraping if the title, link and image exist
if (result.title && result.link && result.image) {
db.Article.create(result)
.then(function(dbArticle) {
// View the added result in the console
console.log(dbArticle);
})
.catch(function(err) {
// If an error occurred, log it
console.log(err);
});
}
});
// Send a message to the client
res.redirect("/");
});
});
app.get("/api/articles", function(req, res) {
db.Article.find({})
.populate("note")
.then(function(data) {
res.json(data);
});
});
// // put route to updated the article to be saved:true
app.post("/api/saved/:id", function(req, res) {
// res.redirect("/")
db.Article.updateOne(
{ _id: req.params.id },
{ $set: { saved: true } },
function(err, doc) {
if (err) {
res.send(err);
} else {
// res.redirect("/");
}
}
);
});
// Save a note route
app.post("/api/saved/notes/:id", function(req, res) {
db.Note.create(req.body)
.then(function(dbNote) {
console.log(req.params.id, dbNote);
//update the Article and push the note id into the array
return db.Article.findOneAndUpdate(
{ _id: req.params.id },
{ $push: { note: dbNote._id } }
);
})
.then(function(dbArticle) {
res.json(dbArticle);
})
.catch(function(err) {
res.json(err);
});
});
// // Delete a note route
app.delete("/api/notes/:id", function(req, res) {
console.log(req.params.id);
db.Note.findOneAndDelete({ _id: req.params.id })
.then(function(dbNote) {
return db.Article.findOneAndUpdate(
{ note: req.params.id },
{ $pullAll: [{ note: req.params.id }] }
);
})
.then(function(dbArticle) {
res.json(dbArticle);
})
.catch(function(err) {
res.json(err);
});
});
//Delete Saved Article Route
app.delete("/api/articles/:id", function(req, res) {
db.Article.findOneAndDelete({ _id: req.params.id })
.then(function(dbArticle) {
res.json(dbArticle);
})
.catch(function(err) {
res.json(err);
});
});
// // Clear all Unsaved Articles
app.delete("/api/articles", function (req, res) {
db.Article.remove({saved: false})
.then(function (dbArticle) {
res.json(dbArticle);
})
.catch(function (err) {
res.json(err);
});
});
};
| 9dc8bbc0199ce07a32db1f6873a1ba9a0936e683 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | tlacy1000/all-the-news | a346fa8fe1ca17cf8220232d2b29107aa019e9ec | b993b46d8b5f03adfbb491b3900305cb3772e57b |
refs/heads/main | <file_sep># AAP1
Primer Proyecto del curso Análisis de Algoritmos
<file_sep>from Generator.dominoes import *
from timeit import default_timer as timer
import matplotlib.pyplot as plt
from math import log
#######################################################################
## Solucion del proyecto
#######################################################################
"""
A continuacion se presentan las funciones creadas para el desarrollo
del proyecto.
"""
# Visualizacion de datos
def graficar(lista_n, lista_y, titulo, color):
plt.plot(lista_n,lista_y,'-',linewidth=3,color=color)
plt.grid()
plt.xlabel('Cantidad de muestras')
plt.ylabel('Tiempo')
plt.title(titulo)
plt.show()
# Algoritmo generar matriz vacia
def generarMatriz(tamano):
a = -1
filas = tamano + 1
columnas = tamano + 2
matriz = [[a for filas in range(columnas)] for filas in range(filas)]
return matriz
# Funciones para el algoritmo de backtracking
def log(msg):
#if debug:
if False:
print(msg)
def gen_pos(n, result, current):
pos = random.randint(0,1)
if pos==0:
if current[1]+1 < n+2:
if current[0]!=0:
if result[current[0]-1][current[1]+1]!=1:
return pos
else:
log("Horizontal blocked by vertical")
if current[0]<n:
return abs(pos-1)
else:
return -1
else:
return pos
else:
log("Horizontal out of bounds")
if current[0]<n:
return abs(pos-1)
else:
return -1
else:
if current[0]<n:
return pos
else:
log("Vertical out of bounds")
if current[1]+1 < n+2:
if result[current[0]-1][current[1]+1]!=1:
return abs(pos-1)
else:
return -1
else:
return -1
def update_current(n, result, prev_pos, current): # Call at end of while, is recursive
if prev_pos == 0:
new_current = (current[0],current[1]+2)
elif prev_pos == 1:
new_current = (current[0],current[1]+1)
else:
new_current = (current[0],current[1])
if new_current[0]<n+1:
if new_current[1] < n+2:
if new_current[0]!=0:
if result[new_current[0]-1][new_current[1]]!=1:
return new_current
else:
log("New current blocked by vertical")
return update_current(n, result, 1, new_current)
else:
return new_current
else:
log("New current out of bounds")
return update_current(n, result, -1, (new_current[0]+1,0))
else:
log("End of board")
return (-1,-1)
def get_domino(board, current, pos):
if pos==0:
return (board[current[0]][current[1]], board[current[0]][current[1]+1])
else:
return (board[current[0]][current[1]], board[current[0]+1][current[1]])
def domino_to_string(domino, invert=False):
if invert:
return f"{domino[1]}|{domino[0]}"
return f"{domino[0]}|{domino[1]}"
def is_domino_valid(pieces, domino, pos):
to_insert = domino_to_string(domino)
inverted = domino_to_string(domino, True)
current_pieces = pieces.keys()
if (to_insert not in current_pieces) and (inverted not in current_pieces):
pieces[to_insert] = pos
return True
else:
return False
def is_pos_valid(n, result, current, pos):
if pos==0:
if current[1]+1 < n+2:
if current[0]!=0:
if result[current[0]-1][current[1]+1]!=1:
return True
else:
return False
else:
return True
else:
return False
else:
if current[0]<n:
return True
else:
if current[1]+1 < n+2:
if result[current[0]-1][current[1]+1]!=1:
return True
else:
return False
else:
return False
# Algoritmo de backtrscking
def backtracking(board):
start = timer()
n = len(board)-1
result = generarMatriz(n)
bt_times = generarMatriz(n)
hist = []
pieces = {}
log(f"N: {n}\nData: {board}")
latest_domino = None
current = (0,0)
not_at_end_of_board = True
while not_at_end_of_board:
log("__________________")
pos = gen_pos(n, result, current)
log(f"Pieces: {pieces}\nHist: {hist}\nResult: {result}\nBT_times: {bt_times}\nCurrent: {current}\nPos: {pos}\nLatest inserted domino: {latest_domino}")
if pos != -1:
domino = get_domino(board, current, pos)
else:
domino = latest_domino
trying_to_add_domino = True
while trying_to_add_domino:
if (is_domino_valid(pieces, domino, pos) == False):
log("--------------BACKTRACKING----------------")
validating_pos = True
while validating_pos and hist!=[]:
current = hist.pop()
old_pos = result[current[0]][current[1]]
result[current[0]][current[1]] = -1
del pieces[domino_to_string(get_domino(board, current, old_pos))]
pos = abs(old_pos-1)
log(f"$$$Hist: {hist}\nResult: {result}\nBT_times: {bt_times}\nCurrent: {current}\nInverted Pos: {pos}\nPieces: {pieces}")
if is_pos_valid(n, result, current,pos):
if bt_times[current[0]][current[1]] < 1:
validating_pos = False
if validating_pos:
bt_times[current[0]][current[1]] = -1
domino = get_domino(board, current, pos)
else:
latest_domino = domino
hist.append(current)
result[current[0]][current[1]] = pos
bt_times[current[0]][current[1]] += 1
trying_to_add_domino = False
current = update_current(n, result, pos, current)
if current == (-1,-1):
not_at_end_of_board = False
end = timer()
time_emp = (end-start)*1000000
time_an = ec_analitica_bac(n)
return result,hist,time_emp,time_an
# ecuacion de medicion analitica del back tracking
def ec_analitica_bac(n):
time = n*3
return time
#######################################################################
## MAIN
#######################################################################
# PARA MODO DEBUG
debug = False # Set True para ver prints de proceso,
# puzzle más de 4 puede crashear por el volumen de prints
"""
# Variables
lista_entrada = [1,2,4,2,5,3,4,1,3,5,4,5,5,2]
Medicion_Empirica = []
Medicion_Analitica = []
# Realizar las Pruebas
for n in lista_entrada:
board = create_puzzle(n)
lista_resultados = []
if board != False:
result,hist,time_emp,time_an = backtracking(board)
Medicion_Empirica.append(time_emp)
Medicion_Analitica.append(time_an)
for coord in hist:
lista_resultados.append(result[coord[0]][coord[1]])
print(lista_resultados)
# Imprimir resultados
print("Los resultados obtenidos de las mediciones: ")
print('- Empirico: ',Medicion_Empirica)
print('- Analitico: ',Medicion_Analitica)
# Graficar
#graficar(lista_entrada, Medicion_Empirica, 'Medicion Empirica Mediciones Empiricas', 'r')
#graficar(lista_entrada, Medicion_Analitica, 'Medicion Empirica Mediciones Analiticas', 'b')
"""<file_sep>
"""
Algoritmo que revisa todas las posibles soluciones para completar el tablero
"""
def fuerza_bruta(board,tiles,solut):
buscar = [] #Ficha que va buscar y verficar
#Condiciones de parada basicas
#1 todas las soluciones hechas y ya no hay fichas
if solut == [] and tiles == []:
return True
#2 Solucion invalida
elif solut == [] and tiles!=[]:
return False
#Recorrer toda la matriz
else:
for i in range(len(board)):
for j in range(len(board[i])):
#Podas
if board[i][j] != -1:
#Pruebas de posiciones, se utilizara valores binarios 0 = horizontal / 1 = vertical
if(solut[0] == 0):
#Para quitar validaciones de bordes utilizamos un try
try:
buscar.append(board[i][j])
buscar.append(board[i][j+1])
#Saber que no tengo que volver a pasar por ahí
board[i][j] = -1
board[i][j+1] = -1
except IndexError:
return False
#Repetir proceso para la funcion en vertical
elif(solut[0] == 1):
#Para quitar validaciones de bordes utilizamos un try
try:
buscar.append(board[i][j])
buscar.append(board[i+1][j])
#Saber que no tengo que volver a pasar por ahí
board[i][j] = -1
board[i+1][j] = -1
except IndexError:
return False
if(isIn(buscar,tiles)):
try:
tiles.remove(buscar)
except:
buscar[0],buscar[1] = buscar[1],buscar[0]
tiles.remove(buscar)
return fuerza_bruta(board,tiles,solut[1:])
else:
return False
#Tenemos que confirmar que la ficha esta entre todas las fichas posibles
#Tanto al derecho, como a la inversa
def isIn(ficha,Tfichas):
if(ficha in Tfichas):
return True
else:
#Se voltea la ficha para volver a verificar
ficha[0],ficha[1] = ficha[1],ficha[0]
if(ficha in Tfichas):
return True
else:
return False<file_sep>from Generator.dominoes import *
from FuerzaBruta import *
from BackTracking import *
import copy
#######################################
# Main principal #
#######################################
Tablero = []
Fichas = []
# PRIMERO CREAR EL TABLERO
#Este recibe un N con la cantidad a generar
def creacion(n):
global Tablero
global Fichas
board = True
while(type(board) == bool):
board = create_puzzle(n)
tiles = make_tiles(n)
Tablero = copy.deepcopy(board)
Fichas = copy.deepcopy(tiles)
#Recibie un n para saber cual algoritmo llamar 0 = Fuerza Bruta, 1 = Backtracking
def main(m):
if(m == 0):
print(main_FB(copy.deepcopy(Tablero),copy.deepcopy(Fichas)))
elif(m == 1):
main_btk(copy.deepcopy(Tablero))
#######################################
# Main para Fuerza Bruta #
#######################################
def main_FB(board,tiles):
num_solu = listaCero(len(tiles))
final = []
#Este ciclo es para probar todas las posiciones posibles x cada ficha
for i in range(2**len(tiles)):
if( fuerza_bruta(copy.deepcopy(board),copy.deepcopy(tiles),num_solu) ):
final.append(copy.deepcopy(num_solu))
#Sino funciono entonces hay que cambiar la lista de ceros, para probar otra posicion
cambio(num_solu)
return final
#Esto para tener una lista con el numero de fichas y de posiciones de cada una
def listaCero(n):
lista = []
for i in range(n):
lista.append(0)
return lista
#Este algoritmo es para cambiar los valores entre 0 y 1
#Esto para que el algortimos "se devuelva" y pruebe otra posicion
def cambio(lista):
for i in range(1,len(lista)+1):
if(lista[-i]) == 0:
lista[-i] = 1
return
else:
lista[-i] = 0
#######################################
# Main para Backtracking #
#######################################
def main_btk(board):
lista_resultados = []
Medicion_Analitica = []
Medicion_Empirica = []
result,hist,time_emp,time_an = backtracking(board)
Medicion_Empirica.append(time_emp)
Medicion_Analitica.append(time_an)
for coord in hist:
lista_resultados.append(result[coord[0]][coord[1]])
print(lista_resultados) | 02601600544e1c913060e3465fc94c8649f73d3c | [
"Markdown",
"Python"
] | 4 | Markdown | CNNunez/AAP1 | c5611319b2131228e74ae3b3717beafdc6ae03dd | 763a844f5f20300b68a375752ede2f296e76cf81 |
refs/heads/master | <file_sep><?php
namespace App\Modules\Transaksi\Controllers;
use App\Controllers\BaseController;
class Transaksi extends BaseController
{
protected $path = 'pages/transaksi/';
public function masuk()
{
$data = [
'user' => 'Tri',
'page_title' => 'Transaksi Masuk',
];
return view($this->path . '/transaksi_masuk', $data);
}
public function keluar()
{
$data = [
'user' => 'Tri',
'page_title' => 'Transaksi Keluar',
];
return view($this->path . '/transaksi_keluar', $data);
}
public function masuk_reseller()
{
$data = [
'user' => 'Tri',
'page_title' => 'Transaksi Masuk Reseller',
];
return view($this->path . '/transaksi_masuk_reseller', $data);
}
}
<file_sep>"use strict";
// Cicle Chart
Circles.create({
id: "circles-1",
radius: 45,
value: 60,
maxValue: 100,
width: 7,
text: 5,
colors: ["#f1f1f1", "#FF9E27"],
duration: 400,
wrpClass: "circles-wrp",
textClass: "circles-text",
styleWrapper: true,
styleText: true,
});
Circles.create({
id: "circles-2",
radius: 45,
value: 70,
maxValue: 100,
width: 7,
text: 36,
colors: ["#f1f1f1", "#2BB930"],
duration: 400,
wrpClass: "circles-wrp",
textClass: "circles-text",
styleWrapper: true,
styleText: true,
});
Circles.create({
id: "circles-3",
radius: 45,
value: 40,
maxValue: 100,
width: 7,
text: 12,
colors: ["#f1f1f1", "#F25961"],
duration: 400,
wrpClass: "circles-wrp",
textClass: "circles-text",
styleWrapper: true,
styleText: true,
});
//Notify
// $.notify({
// icon: 'flaticon-alarm-1',
// title: 'Atlantis Lite',
// message: 'Free Bootstrap 4 Admin Dashboard',
// },{
// type: 'info',
// placement: {
// from: "bottom",
// align: "right"
// },
// time: 1000,
// });
var totalIncomeChart = document
.getElementById("totalIncomeChart");
if (totalIncomeChart != null) {
totalIncomeChart.getContext("2d")
var mytotalIncomeChart = new Chart(totalIncomeChart, {
type: "bar",
data: {
labels: ["S", "M", "T", "W", "T", "F", "S", "S", "M", "T"],
datasets: [
{
label: "Total Income",
backgroundColor: "#ff9e27",
borderColor: "rgb(23, 125, 255)",
data: [6, 4, 9, 5, 4, 6, 4, 3, 8, 10],
},
],
},
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false,
},
scales: {
yAxes: [
{
ticks: {
display: false, //this will remove only the label
},
gridLines: {
drawBorder: false,
display: false,
},
},
],
xAxes: [
{
gridLines: {
drawBorder: false,
display: false,
},
},
],
},
},
});
}
$("#datatables-1").DataTable({});
/* Kategori */
// Add Row
$('#add-row').DataTable({
"pageLength": 5,
});
var action =
'<td> <div class="form-button-action"> <button type="button" data-toggle="tooltip" title="" class="btn btn-icon btn-primary btn-round" data-original-title="Edit Task"> <i class="fa fa-edit"></i> </button> <button type="button" data-toggle="tooltip" title="" class="btn btn-icon btn-danger btn-round" data-original-title="Remove"> <i class="fa fa-times"></i> </button> </div> </td>';
$('#addRowButton').click(function() {
});
$(".edit-kategori").click(function () {
// console.log(baseURL);
$("#content-modal-edit").load(baseURL + "/kategori/edit");
$("#EditRowModal").modal('show');
})
$(".delete-kategori").click(function (e) {
e.preventDefault()
let r = confirm("Yakin ingin menghapus kategori ini ?")
if (r == true) {
alert("Kategori berhasil di hapus")
}else{
alert("Kategori gagal di hapus")
}
})
/* Jenis */
$(".edit-jenis").click(function () {
// console.log(baseURL);
$("#content-modal-edit").load(baseURL + "/jenis/edit");
$("#EditRowModal").modal('show');
})
$(".delete-jenis").click(function (e) {
e.preventDefault()
let r = confirm("Yakin ingin menghapus jenis ini ?")
if (r == true) {
alert("Jenis berhasil di hapus")
}else{
alert("Jenis gagal di hapus")
}
})
/* Produk */
$(".edit-produk").click(function () {
// console.log(baseURL);
$("#content-modal-edit").load(baseURL + "/produk/edit");
$("#EditRowModal").modal('show');
})
$(".delete-produk").click(function (e) {
e.preventDefault();
let r = confirm("Yakin ingin menghapus produk ini ?");
if (r == true) {
alert("Produk berhasil di hapus");
} else {
alert("Produk gagal di hapus");
}
});
/* Reseller */
$(".edit-reseller").click(function () {
// console.log(baseURL);
$("#content-modal-edit").load(baseURL + "/reseller/edit");
$("#EditRowModal").modal('show');
})
$(".delete-reseller").click(function (e) {
e.preventDefault();
let r = confirm("Yakin ingin menghapus reseller ini ?");
if (r == true) {
alert("Reseller berhasil di hapus");
} else {
alert("Reseller gagal di hapus");
}
});<file_sep>run:
@php spark serve<file_sep><?= $this->extend('layouts/index'); ?>
<?= $this->section('content'); ?>
<div class="page-inner">
<div class="page-header">
<h4 class="page-title">Produk</h4>
<ul class="breadcrumbs">
<li class="nav-home">
<a href="#">
<i class="flaticon-home"></i>
</a>
</li>
<li class="separator">
<i class="flaticon-right-arrow"></i>
</li>
<li class="nav-item">
<a href="#">Master</a>
</li>
<li class="separator">
<i class="flaticon-right-arrow"></i>
</li>
<li class="nav-item">
<a href="#">Produk</a>
</li>
</ul>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<div class="d-flex align-items-center">
<h4 class="card-title">Daftar Produk</h4>
<button class="btn btn-primary btn-round ml-auto" data-toggle="modal" data-target="#addRowModal">
<i class="fa fa-plus"></i>
Tambah Produk
</button>
</div>
</div>
<div class="card-body">
<!-- Modal -->
<div class="modal fade" id="addRowModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header no-bd">
<h5 class="modal-title">
<span class="fw-mediumbold">
Produk Baru
</span>
</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="row">
<div class="col-sm-12">
<div class="form-group form-group-primary">
<label>Nama Produk</label>
<input id="addName" type="text" class="form-control" placeholder="Masukkan Nama Produk">
</div>
</div>
<div class="col-sm-12">
<div class="form-group form-group-primary">
<label for="jenis_produk">Jenis Produk</label>
<select name="jenis_produk" id="jenis_produk" class="form-control form-control">
<option selected disabled>-- Pilih Jenis Produk --</option>
<option value="">asdasd</option>
<option value="">asdasd</option>
<option value="">asdasd</option>
<option value="">asdasd</option>
</select>
</div>
</div>
<div class="col-sm-12">
<div class="form-group form-group-primary">
<label>Warna Produk</label>
<input name="warna_produk" id="warna_produk" type="text" class="form-control" placeholder="Masukkan Warna Produk">
</div>
</div>
<div class="col-sm-12">
<div class="form-group form-group-primary">
<label>Size Produk</label>
<input name="size_produk" id="size_produk" type="number" class="form-control" placeholder="Masukkan Size Produk">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer no-bd">
<button type="button" id="addRowButton" class="btn btn-primary bg-default-gradient">Tambah</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Batal</button>
</div>
</div>
</div>
</div>
<!-- Modal Edit -->
<div class="modal fade" id="EditRowModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content" id="content-modal-edit"></div>
</div>
</div>
<div class="table-responsive">
<table id="add-row" class="display table table-striped table-hover">
<thead>
<tr>
<th>Nama Produk</th>
<th style="width: 10%">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>System Architect</td>
<td>
<div class="form-button-action">
<button type="button" data-toggle="tooltip" title="" class="btn btn-icon btn-primary btn-round edit-produk" data-original-title="Detail Produk">
<i class="fa fa-eye"></i>
</button>
<button type="button" data-toggle="tooltip" title="" class="btn btn-icon btn-primary btn-round edit-produk" data-original-title="Ubah Produk">
<i class="fa fa-edit"></i>
</button>
<button type="button" data-toggle="tooltip" title="" class="btn btn-icon btn-danger btn-round delete-produk" data-original-title="Hapus Produk">
<i class="far fa-trash-alt"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?= $this->extend('layouts/index'); ?>+
<?= $this->section('content'); ?>
<div class="panel-header bg-primary-gradient">
<div class="page-inner py-5">
<div class="d-flex align-items-left align-items-md-center flex-column flex-md-row">
<div>
<h2 class="text-white pb-2 fw-bold">Dashboard</h2>
<h5 class="text-white op-7 mb-2">Free Bootstrap 4 Admin Dashboard</h5>
</div>
<div class="ml-md-auto py-2 py-md-0">
<a href="#" class="btn btn-white btn-border btn-round mr-2"><i class="fa fa-plus"></i> Tambah Reseller</a>
<a href="#" class="btn btn-secondary btn-round"><i class="fa fa-plus"></i> Tambah Transaksi</a>
</div>
</div>
</div>
</div>
<div class="page-inner mt--5">
<div class="row mt--2">
<div class="col-md-6">
<div class="card full-height">
<div class="card-body">
<div class="card-title">Overall statistics</div>
<div class="card-category">Daily information about statistics in system</div>
<div class="d-flex flex-wrap justify-content-around pb-2 pt-4">
<div class="px-2 pb-2 pb-md-0 text-center">
<div id="circles-1"></div>
<h6 class="fw-bold mt-3 mb-0">New Users</h6>
</div>
<div class="px-2 pb-2 pb-md-0 text-center">
<div id="circles-2"></div>
<h6 class="fw-bold mt-3 mb-0">Sales</h6>
</div>
<div class="px-2 pb-2 pb-md-0 text-center">
<div id="circles-3"></div>
<h6 class="fw-bold mt-3 mb-0">Subscribers</h6>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card full-height">
<div class="card-body">
<div class="card-title">Total income & spend statistics</div>
<div class="row py-3">
<div class="col-md-4 d-flex flex-column justify-content-around">
<div>
<h6 class="fw-bold text-uppercase text-success op-8">Total Income</h6>
<h3 class="fw-bold">$9.782</h3>
</div>
<div>
<h6 class="fw-bold text-uppercase text-danger op-8">Total Spend</h6>
<h3 class="fw-bold">$1,248</h3>
</div>
</div>
<div class="col-md-8">
<div id="chart-container">
<canvas id="totalIncomeChart"></canvas>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?php
namespace App\Modules\Home\Controllers;
use App\Controllers\BaseController;
class Home extends BaseController
{
public function index()
{
$data = [
'user' => 'Tri',
'page_title' => 'Home',
];
return view('pages/home/index', $data);
}
}
<file_sep><div class="sidebar sidebar-style-2">
<div class="sidebar-wrapper scrollbar scrollbar-inner">
<div class="sidebar-content">
<ul class="nav nav-primary">
<li class="nav-item active">
<a href="/">
<i class="fas fa-home"></i>
<p>Dashboard</p>
</a>
</li>
<li class="nav-section">
<span class="sidebar-mini-icon">
<i class="fa fa-ellipsis-h"></i>
</span>
<h4 class="text-section">Components</h4>
</li>
<li class="nav-item">
<a data-toggle="collapse" href="#base">
<i class="fas fa-layer-group"></i>
<p>Master</p>
<span class="caret"></span>
</a>
<div class="collapse" id="base">
<ul class="nav nav-collapse">
<li>
<a href="<?= route_to('kategori')?>">
<span class="sub-item">Kategori</span>
</a>
</li>
<li>
<a href="<?= route_to('jenis')?>">
<span class="sub-item">Jenis</span>
</a>
</li>
<li>
<a href="<?= route_to('produk')?>">
<span class="sub-item">Produk</span>
</a>
</li>
<li>
<a href="<?= route_to('reseller')?>">
<span class="sub-item">Reseller</span>
</a>
</li>
</ul>
</div>
</li>
<li class="nav-item">
<a data-toggle="collapse" href="#sidebarLayouts">
<i class="fas fa-th-list"></i>
<p>Transaksi</p>
<span class="caret"></span>
</a>
<div class="collapse" id="sidebarLayouts">
<ul class="nav nav-collapse">
<li>
<a href="<?= route_to('transaksi-in')?>">
<span class="sub-item">Transaksi Masuk</span>
</a>
</li>
<li>
<a href="<?= route_to('transaksi-out')?>">
<span class="sub-item">Transaksi Keluar</span>
</a>
</li>
<li>
<a href="<?= route_to('transaksi-in-reseller')?>">
<span class="sub-item">Transaksi Reseller</span>
</a>
</li>
</ul>
</div>
</li>
<li class="nav-item">
<a data-toggle="collapse" href="#forms">
<i class="fas fa-pen-square"></i>
<p>Laporan</p>
<span class="caret"></span>
</a>
<div class="collapse" id="forms">
<ul class="nav nav-collapse">
<li>
<a href="<?= route_to('report-sales')?>">
<span class="sub-item">Laporan Penjualan</span>
</a>
</li>
<li>
<a href="<?= route_to('report-stock')?>">
<span class="sub-item">Laporan Stock</span>
</a>
</li>
<li>
<a href="<?= route_to('report-rekap-sales')?>"> <span class="sub-item">Laporan Rekap Penjualan</span> </a>
</li>
</ul>
</div>
</li>
</ul>
</div>
</div>
</div><file_sep><?php namespace App\Modules\Jenis\Controllers;
use App\Controllers\BaseController;
class Jenis extends BaseController
{
private $path = 'pages/jenis';
public function index()
{
$data = [
'user' => 'Tri',
'page_title' => 'Jenis',
];
return view($this->path.'/list', $data);
}
public function edit_modal()
{
echo view($this->path.'/edit_modal');
}
}
<file_sep><?php namespace App\Modules\Reseller\Controllers;
use App\Controllers\BaseController;
class Reseller extends BaseController
{
private $path = 'pages/reseller';
public function index()
{
$data = [
'user' => 'Tri',
'page_title' => 'Reseller',
];
return view($this->path.'/list', $data);
}
public function edit_modal()
{
echo view($this->path.'/edit_modal');
}
}
<file_sep><?= $this->extend('layouts/index'); ?>
<?= $this->section('content'); ?>
<div class="page-inner">
<div class="page-header">
<h4 class="page-title">Transaksi</h4>
<ul class="breadcrumbs">
<li class="nav-home">
<a href="#">
<i class="flaticon-home"></i>
</a>
</li>
<li class="separator">
<i class="flaticon-right-arrow"></i>
</li>
<li class="nav-item">
<a href="#">Master</a>
</li>
<li class="separator">
<i class="flaticon-right-arrow"></i>
</li>
<li class="nav-item">
<a href="#">Transaksi Keluar</a>
</li>
</ul>
</div>
<div class="row">
<div class="col-md-12">
<div id="accordion">
<div class="card">
<div class="card-header" id="headingOne">
<div class="card-head-row" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<div class="card-title">
Form Transaksi Keluar
</div>
<div class="card-tools">
<button class="btn btn-sm btn-round mr-2" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
</div>
<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordion">
<div class="card-body">
<form action="">
<div class="row">
<div class="col-md-4 col-lg-4">
<div class="form-group">
<label for="no_resi">No. Resi</label>
<input type="text" name="no_resi" class="form-control">
</div>
<div class="form-group">
<label for="tgl_transaksi">Tanggal Transaksi</label>
<input type="date" name="tgl_transaksi" id="" class="form-control">
</div>
<div class="form-group">
<div class="input-icon">
<label for="reseller_name">Nama Reseller</label>
<input type="text" class="form-control pl-3" name="reseller_name" id="reseller_name" placeholder="Cari Reseller...">
<span class="input-icon-addon mt-3">
<i class="fa fa-search"></i>
</span>
</div>
</div>
<div class="form-group">
<div class="input-icon">
<label for="produk">Produk</label>
<input type="text" class="form-control pl-3" name="produk" placeholder="Cari produk...">
<span class="input-icon-addon mt-3">
<i class="fa fa-search"></i>
</span>
</div>
</div>
<div class="form-group">
<label for="qty">Qty</label>
<input type="number" name="qty" class="form-control" min="1">
</div>
</div>
<div class="col-md-4 col-lg-4">
<div class="form-group">
<label for="saldo_masuk">Saldo Masuk</label>
<input type="number" name="saldo_masuk" class="form-control">
</div>
<div class="form-group">
<label for="garansi">Garansi</label>
<input type="number" name="garansi" class="form-control">
</div>
<div class="form-group">
<label for="nama_penerima">Nama Penerima</label>
<input type="text" name="nama_penerima" class="form-control" placeholder="Masukkan Nama Penerima">
</div>
<div class="form-group">
<label for="nohp_penerima">No. HP Penerima</label>
<input type="text" name="nohp_penerima" class="form-control" placeholder="Masukkan No. HP Penerima">
</div>
<div class="form-group">
<label for="alamat_penerima">Alamat Penerima</label>
<textarea name="alamat_penerima" cols="30" rows="2" class="form-control"></textarea>
</div>
</div>
<div class="col-md-4 col-lg-4">
<div class="form-group">
<label for="pembayaran">Pembayaran Pembeli</label>
<input type="text" name="pembayaran" class="form-control">
</div>
</div>
</div>
<div class="card-action pl-3">
<button class="btn btn-success">Submit</button>
<button class="btn btn-danger">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Data Transaksi Keluar</h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="datatables-1" class="display table table-striped table-hover">
<thead>
<tr>
<th>Tanggal Transaksi</th>
<th>Produk</th>
<th>Reseller</th>
<th>Total Order</th>
<th>No Resi</th>
<th>Pembayaran</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<tr>
<td>2011/04/25</td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>61</td>
<td>Edinburgh2712379JS</td>
<td>$320,800</td>
<td>
<div class="row flex-nowrap">
<button type="button" data-toggle="tooltip" title="" class="btn btn-icon btn-primary btn-round edit-transout" data-original-title="Edit Task">
<i class="fa fa-edit"></i>
</button>
<button type="button" data-toggle="tooltip" title="" class="btn btn-icon btn-danger btn-round delete-transout d-inline" data-original-title="Remove">
<i class="far fa-trash-alt"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?php namespace App\Modules\Produk\Controllers;
use App\Controllers\BaseController;
class Produk extends BaseController
{
private $path = 'pages/produk';
public function index()
{
$data = [
'user' => 'Tri',
'page_title' => 'Produk',
];
return view($this->path.'/list', $data);
}
}
<file_sep><?= $this->extend('layouts/index'); ?>
<?= $this->section('content'); ?>
<div class="page-inner">
<div class="page-header">
<h4 class="page-title">Transaksi</h4>
<ul class="breadcrumbs">
<li class="nav-home">
<a href="#">
<i class="flaticon-home"></i>
</a>
</li>
<li class="separator">
<i class="flaticon-right-arrow"></i>
</li>
<li class="nav-item">
<a href="#">Master</a>
</li>
<li class="separator">
<i class="flaticon-right-arrow"></i>
</li>
<li class="nav-item">
<a href="#">Transaksi Masuk Reseller</a>
</li>
</ul>
</div>
<div class="row">
<div class="col-md-12">
<div id="accordion">
<div class="card">
<div class="card-header" id="headingOne">
<div class="card-head-row" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<div class="card-title">
Form Transaksi Masuk Reseller
</div>
<div class="card-tools">
<button class="btn btn-sm btn-round mr-2" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
</div>
<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordion">
<div class="card-body">
<form action="">
<div class="row">
<div class="col-md-4 col-lg-4">
<div class="form-group">
<label for="tgl_transaksi">Tanggal Transaksi</label>
<input type="date" name="tgl_transaksi" id="" class="form-control">
</div>
<div class="form-group">
<div class="input-icon">
<label for="produk">Produk</label>
<input type="text" class="form-control pl-3" name="produk" placeholder="Cari produk...">
<span class="input-icon-addon mt-3">
<i class="fa fa-search"></i>
</span>
</div>
</div>
<div class="form-group">
<label for="warna">Warna</label>
<select name="warna" id="warna" class="form-control">
<option selected disabled>-- Pilih Warna --</option>
</select>
</div>
<div class="form-group">
<label for="size">Size</label>
<select name="size" id="size" class="form-control">
<option selected disabled>-- Pilih Size --</option>
</select>
</div>
<div class="form-group">
<label for="qty">Qty</label>
<input type="number" name="qty" class="form-control" min="1">
</div>
</div>
<div class="col-md-4 col-lg-4">
<div class="form-group">
<label for="customer_name">Nama Pembeli</label>
<input type="text" class="form-control pl-3" name="customer_name" id="customer_name" placeholder="Masukkan Nama Pembeli">
</div>
<div class="form-group">
<label for="nohp_pembeli">No. HP Pembeli</label>
<input type="text" name="nohp_pembeli" class="form-control" placeholder="Masukkan No. HP Pembeli">
</div>
<div class="form-group">
<label for="alamat_penerima">Alamat Pembeli</label>
<textarea name="alamat_penerima" cols="30" rows="2" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="pembayaran">Pembayaran Pembeli</label>
<input type="text" name="pembayaran" class="form-control">
</div>
</div>
</div>
<div class="card-action pl-3">
<button class="btn btn-success">Submit</button>
<button class="btn btn-danger">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Data Transaksi</h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="datatables-1" class="display table table-striped table-hover">
<thead>
<tr>
<th>Tanggal Transaksi</th>
<th>Produk</th>
<th>Qty</th>
<th>Pembeli</th>
<th>Alamat</th>
<th>Pembayaran</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<tr>
<td>2011/04/25</td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>61</td>
<td>Edinburgh2712379JS</td>
<td>$320,800</td>
<td>
<div class="row flex-nowrap">
<button type="button" data-toggle="tooltip" title="" class="btn btn-icon btn-primary btn-round edit-transout" data-original-title="Edit Task">
<i class="fa fa-edit"></i>
</button>
<button type="button" data-toggle="tooltip" title="" class="btn btn-icon btn-danger btn-round delete-transout d-inline" data-original-title="Remove">
<i class="far fa-trash-alt"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?= $this->extend('layouts/index'); ?>
<?= $this->section('content'); ?>
<div class="page-inner">
<div class="page-header">
<h4 class="page-title">Transaksi</h4>
<ul class="breadcrumbs">
<li class="nav-home">
<a href="#">
<i class="flaticon-home"></i>
</a>
</li>
<li class="separator">
<i class="flaticon-right-arrow"></i>
</li>
<li class="nav-item">
<a href="#">Master</a>
</li>
<li class="separator">
<i class="flaticon-right-arrow"></i>
</li>
<li class="nav-item">
<a href="#">Transaksi Masuk</a>
</li>
</ul>
</div>
<div class="row">
<div class="col-md-12">
<div id="accordion">
<div class="card">
<div class="card-header" id="headingOne">
<div class="card-head-row" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<div class="card-title">
Form Transaksi Masuk
</div>
<div class="card-tools">
<button class="btn btn-sm btn-round mr-2" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
</div>
<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordion">
<div class="card-body">
<form action="">
<div class="row">
<div class="col-md-4 col-lg-4">
<div class="form-group">
<label for="no_po">No. PO</label>
<input type="text" name="no_po" class="form-control">
</div>
<div class="form-group">
<label for="tgl_transaksi">Tanggal Transaksi</label>
<input type="date" name="tgl_transaksi" id="" class="form-control">
</div>
</div>
<div class="col-md-4 col-lg-4">
<div class="form-group">
<div class="input-icon">
<label for="produk">Produk</label>
<input type="text" class="form-control pl-3" name="produk" placeholder="Cari produk...">
<span class="input-icon-addon mt-3">
<i class="fa fa-search"></i>
</span>
</div>
</div>
<div class="form-group">
<label for="qty">Qty</label>
<input type="number" name="qty" class="form-control" min="1">
</div>
</div>
<div class="col-md-4 col-lg-4">
<div class="form-group">
<label for="pembayaran">Tipe Pembayaran</label>
<select name="pembayaran" id="" class="form-control">
<option selected disabled>-- Pilih Tipe Pembayaran --</option>
<option value="">Tunai</option>
<option value="">Non Tunai</option>
</select>
</div>
</div>
</div>
<div class="card-action pl-3">
<button class="btn btn-success">Submit</button>
<button class="btn btn-danger">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Data Transaksi Masuk</h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="datatables-1" class="display table table-striped table-hover">
<thead>
<tr>
<th>Tanggal Transaksi</th>
<th>No. PO</th>
<th>Produk</th>
<th>Qty</th>
<th>Tipe Pembayaran</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<tr>
<td>2011/04/25</td>
<td><NAME></td>
<td>System Architect</td>
<td>61</td>
<td>Edinburgh2712379JS</td>
<td>
<div class="row flex-nowrap">
<button type="button" data-toggle="tooltip" title="" class="btn btn-icon btn-primary btn-round edit-transout" data-original-title="Edit Task">
<i class="fa fa-edit"></i>
</button>
<button type="button" data-toggle="tooltip" title="" class="btn btn-icon btn-danger btn-round delete-transout d-inline" data-original-title="Remove">
<i class="far fa-trash-alt"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?php namespace App\Modules\Kategori\Controllers;
use App\Controllers\BaseController;
class Kategori extends BaseController
{
private $path = 'pages/kategori';
public function index()
{
$data = [
'user' => 'Tri',
'page_title' => 'Kategori',
];
return view($this->path.'/list', $data);
}
public function edit_modal()
{
echo view($this->path.'/edit_modal');
}
}
| 03b77b831ecbdc4b961feede1e70213371feaa7b | [
"JavaScript",
"Makefile",
"PHP"
] | 14 | PHP | boombaw/parahiyanganstore | 920ffc9d1fb711fd6314b8b24ae8c323a607cfc9 | 7247ecda069aa427a186363259a68cc5735777ca |
refs/heads/master | <repo_name>dsilvers/Milwaukee-Alternative-Radio-Station-Spotify-Playlist-Creator<file_sep>/requirements.txt
certifi==2018.4.16
chardet==3.0.4
future==0.16.0
idna==2.6
oauthlib==2.1.0
python-twitter==3.4.1
requests==2.18.4
requests-oauthlib==0.8.0
spotipy==2.4.4
urllib3==1.22
wheel==0.26.0
<file_sep>/README.md
# Milwaukee-Alternative-Radio-Station-Spotify-Playlist-Creator
<file_sep>/spotify_setup.py
import spotipy
import spotipy.util as util
from settings_local import SPOTIFY_USERNAME, SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, \
SPOTIFY_REDIRECT_URI, SPOTIFY_PLAYLIST_ID, SPOTIFY_SCOPE
token = util.prompt_for_user_token(SPOTIFY_USERNAME, SPOTIFY_SCOPE,
client_id=SPOTIFY_CLIENT_ID, client_secret=SPOTIFY_CLIENT_SECRET,
redirect_uri=SPOTIFY_REDIRECT_URI)<file_sep>/create_sqlite.py
import sqlite3
# because using the same thing for the name for the file, table, and column is cool
con = sqlite3.connect("tracks.db")
con.execute("create table tracks (id integer primary key, tracks varchar unique)")
<file_sep>/playlister.py
import pprint
import sys
import json
import sqlite3
import spotipy
import spotipy.util as util
import twitter
from settings_local import SPOTIFY_USERNAME, SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, \
SPOTIFY_REDIRECT_URI, SPOTIFY_PLAYLIST_ID, SPOTIFY_SCOPE, TWITTER_CONSUMER_KEY, \
TWITTER_CONSUMER_SECRET, TWITTER_USER_TOKEN, TWITTER_USER_SECRET, TWITTER_FOLLOW
con = sqlite3.connect("tracks.db")
api = twitter.Api(consumer_key=TWITTER_CONSUMER_KEY,
consumer_secret=TWITTER_CONSUMER_SECRET,
access_token_key=TWITTER_USER_TOKEN,
access_token_secret=TWITTER_USER_SECRET)
stream = api.GetStreamFilter(follow=[TWITTER_FOLLOW])
for line in stream:
tweet = twitter.Status.NewFromJsonDict(line)
if tweet.text is None:
continue
#(artist, song) = tweet.text.split(' - ', 2)
song_title = tweet.text
track_ids = []
token = util.prompt_for_user_token(SPOTIFY_USERNAME, SPOTIFY_SCOPE,
client_id=SPOTIFY_CLIENT_ID, client_secret=SPOTIFY_CLIENT_SECRET,
redirect_uri=SPOTIFY_REDIRECT_URI)
if not token:
print("Can't get token")
sys.exit()
spotify = spotipy.Spotify(auth=token)
results = spotify.search(q='{}'.format(song_title), type='track', limit=1)
try:
track_id = results['tracks']['items'][0]['uri']
except:
continue
c = con.cursor()
t = (track_id,)
c.execute('SELECT * FROM tracks WHERE tracks=?', t)
if c.fetchone() is None:
track_ids.append(results['tracks']['items'][0]['uri'])
for track_id in track_ids:
results = spotify.user_playlist_add_tracks(SPOTIFY_USERNAME, SPOTIFY_PLAYLIST_ID, [track_id,])
c.execute('INSERT INTO tracks(tracks) VALUES (?)', (track_id,))
con.commit()
print("Added: {} - {}".format(artist, song))
| 6b194a9c08bc814660a4943e7797e1e1b0a0fef5 | [
"Markdown",
"Python",
"Text"
] | 5 | Text | dsilvers/Milwaukee-Alternative-Radio-Station-Spotify-Playlist-Creator | 0a93f998d8124b79c277efd04a0be76812490ffd | 6c14115569fa361ecc470e2b3934e5d515dd3c6a |
refs/heads/master | <file_sep># Generate forest plot for odds ratio.
# http://www.metafor-project.org/doku.php/plots:forest_plot_with_subgroups
library(metafor)
#library(forestplot)
# *************
# A simi-auto plot for forest plot.
# @<NAME>, <EMAIL>
# *************
#http://www.cookbook-r.com/Graphs/Output_to_a_file/
pdf("plots.pdf", width=6, height=3.2)
### decrease margins so the full space is used
par(mar=c(4,4,1,2))
data=read.table("data.txt",header = T,sep = '\t')
# Specify study group.
# slab optional vector with labels for the k studies.
# data is data.frame with header. author year tpos tneg cpos cneg ablat alloc
### fit random-effects model (use slab argument to define study labels)
#res <- rma(ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat.bcg, measure="RR",
# slab=paste(author, year, sep=", "), method="REML")
# we estimate the OR and its 95%CI based on 2x2 table.
#res <- rma(ai=t.case, bi=t.ctrl, ci=r.case, di=r.ctrl, data=data, measure="OR",
# slab=paste(percentile, '%', sep=""),
# method="REML")
#res$slab = paste(data$percentile, '%', sep="")
### set up forest plot (with 2x2 table counts added; rows argument is used
### to specify exactly in which rows the outcomes will be plotted)
# forest(res, xlim=c(-16, 6), at=log(c(0.05, 0.25, 1, 4)), atransf=exp,
# ilab=cbind(dat.bcg$tpos, dat.bcg$tneg, dat.bcg$cpos, dat.bcg$cneg),
# ilab.xpos=c(-9.5,-8,-6,-4.5), cex=0.75, ylim=c(-1, 27),
# order=order(dat.bcg$alloc), rows=c(3:4,9:15,20:23),
# xlab="Risk Ratio", mlab="", psize=1)
# https://www.rdocumentation.org/packages/metafor/versions/1.9-9/topics/forest.rma
# https://stackoverflow.com/questions/32655316/using-meta-metaprop-and-forest-to-create-forest-plot-graphics-in-r
# Data for each group on the Y. Num_data_entry + 3 (title + 2 empty line). Plot in reverse order
# we have 4 group, each has 4 data entries. + 2 empty lines for the sperator between groups.
# So we will put data at 1:4,7:10,13:16,19:22
# put title for each group at 5, 11, 17, 23
# Ylim top is the total lines: 22 + 4(extra lines) = 26.
# YLIM = #data_entries + (#group -1) * 2 + 4(extra_lines)
YLIM = dim(data)[1] + (length(unique(data$GROUP)) -1) *2 + 4
# Compute the location for put each row's text.
num_per_group = length(data$GROUP)/length(unique(data$GROUP))
num_of_group = length(unique(data$GROUP))
shift_num = num_per_group + 2
x = 1:num_per_group
yrows = x
k = num_per_group +1
ylables = c(k)
for (y in 1:(num_of_group-1)) {
x = x + shift_num
k = k + shift_num
yrows = c(yrows, x)
ylables = c(ylables, k)
}
# the y position for put each row's data entry.
yrows
# the y position for put each labels.
ylables
#col_pos_4data_cols = c(-7.5,-6,-3,-1.5)
# by is the length between columns, the last number is teh sift from 0
# ****** Control the column width behaviours here ******
col_width = 2.8
shift_left = 1.5
label_width = 4.8
XRIGHT = 6
# ************************
col_pos_4data_cols = rev( seq(0,by=col_width * - 1.0,length.out = 4) - shift_left )
XLEFT = col_pos_4data_cols[1] - label_width
# we use the Forest Plots (Default Method) for specify the size and variance(CI) by our self.
#forest(res,
forest(x=data[,6],ci.lb = data[,7], ci.ub = data[,8], slab= data[,1],
xlim=c(XLEFT, XRIGHT),
#at=log(c(0.5, 1, 3, 8)),
at = c(0,1,2),
#atransf=exp,
#atransf=log,
#The 4 columns for listing scores.
#ilab=cbind(data$t.case, data$t.ctrl, data$r.case, data$r.ctrl),
ilab = data[,2:5],
# important change ylim from ylim=c(-1, 20) to ylim=c(0.5, 20) to hidden the summary information.
#ilab.xpos=c(-7.5,-6,-3,-1.5), cex=0.75,
ilab.xpos=col_pos_4data_cols, cex=0.75,
#ylim=c(0.5, 26),
ylim=c(0.5, YLIM),
#rows, specify the position on Y for result to put.
#rows=c(1:4,7:10,13:16,19:22),
rows=rev(yrows),
#col=fpColors(box="royalblue",line="darkblue", summary="royalblue"),
xlab="Odds Ratio", psize=1)
op <- par(cex=0.75, font=3)
### add text for the subgroups, text, x y location.
#text(-13, c(23,17,11,5), pos=4, c("UK Biobank White","UK Biobank S.Asian",
# "Medgenome S.Asian",
# "BRAVE"))
# We put label data in reverse order.
text(XLEFT, rev(ylables), pos=4, unique(data$GROUP))
### switch to bold font
par(font=2)
### add column headings to the plot, top limit is 26.
#text(c(-7.5,-6,-3,-1.5), 25, c("Case", "Control", "Case", "Control"))
text(col_pos_4data_cols , YLIM-1, colnames(data)[2:5])
#GROUP NAMEs for the columns of 2:3, 4:5
#text(c(-6.65,-2.15), YLIM, c("Top percentile", "Remainder population"))
text(XLEFT, YLIM-1, colnames(data)[1], pos=4)
text(XRIGHT, YLIM-1, "Odds Ratio [95% CI]", pos=2)
dev.off()
<file_sep>cat test.txt | python3 Quantiles.py -c 1 -a 4
#80.000000
<file_sep>
zcat test1.vcf.gz | python3 VCFSetID.py | bgzip >out.vcf.gz
<file_sep>
cat in.txt | python3 ./ColumnTransformator.py -c 2 -t maf
#1 0.1000
#2 -2.0000
#3 0.2000
<file_sep>#!/usr/bin/env python3
"""
Convert N lines to a single one line, repeat until file end.
@Author: <EMAIL>
Usage:
N2OneLine.py -n int [-q text]
N2OneLine.py -h | --help | -v | --version | -f | --format
Notes:
1. Read data from stdin, and output to stdout.
2. See example by -f.
Options:
-n int Convert the number of 'int' lines to a single line.
Any int >= 0, 0 means convert the whole file as a single line.
-q text Quote each input line element by 'text'.
-h --help Show this screen.
-v --version Show version.
-f --format Show input/output file format example.
"""
import sys
from docopt import docopt
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE, SIG_DFL)
def ShowFormat():
'''Input File format example:'''
print('''
#input:
------------------------
1
2
3
4
5
#output: -n 0
------------------------
1 2 3 4 5
#output: -n 2 -q "'"
------------------------
'1' '2'
'3' '4'
'5'
''');
if __name__ == '__main__':
args = docopt(__doc__, version='1.0')
#print(args)
if(args['--format']):
ShowFormat()
sys.exit(-1)
NUM_LINE = int(args['-n'])
QUOTE = args['-q'] if args['-q'] else ''
out = []
for line in sys.stdin:
line = line.strip()
if line:
if QUOTE:
line = QUOTE + line + QUOTE
if NUM_LINE == 0:
out.append(line)
else:
out.append(line)
if len(out) == NUM_LINE:
sys.stdout.write('%s\n'%('\t'.join(out)))
out = []
#output the cached results in out.
if out:
sys.stdout.write('%s\n'%('\t'.join(out)))
sys.stdout.flush()
sys.stdout.close()
sys.stderr.flush()
sys.stderr.close()
<file_sep>
cat test.txt | Rscript MultipleLinearRegression.R
<file_sep>
cat test.txt | python3 SubsetByKey.py -v 3,1 -c 2 -k
##12 3
#A 1
#B 1
| 9cdbf4ca555f58f37a9ddc9f4affb222a1010fdb | [
"Python",
"R",
"Shell"
] | 7 | R | kbsssu/WallaceBroad | 72f36d24850e485ff5c5ef6e29742d7d39708e4d | 996de84c7d65cc15b58467f6d75f6d9c3acd0330 |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Cliente;
import java.io.DataInputStream;
import java.io.PrintStream;
import java.net.Socket;
import Servidor.server;
import java.io.IOException;
// Para cada conexión de cliente llamamos a esta clase
public class ClienteThread extends Thread {
private String clientName = null;
private DataInputStream is = null;
private PrintStream os = null;//para las operaciones de entrada y salida
private Socket clientSocket = null;//Se crea el Socket para establecer la comunicación
private final ClienteThread[] threads;
private int maxClientsCount;//Establece el maximo de clientes para conectarse
public ClienteThread(Socket clientSocket, ClienteThread[] threads) {
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
}
public void run() {
int maxClientsCount = this.maxClientsCount;
ClienteThread[] threads = this.threads;
try {
//Crea flujos de entrada y salida para clientes cliente.
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
String name;
while (true) {
os.println("Introduzca su nombre");
name = is.readLine().trim();
if (name.indexOf('@') == -1) {
break;
} else {
os.println("nombre invalido");
}
}
// Msg de bienvenida y envío de conversaciones anteriores
System.out.println("" + name + " Se unio al grupo");
System.out.print(server.mensagens);
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] == this) {
clientName = "@" + name;
break;
}
}
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this) {
threads[i].os.println("" + name + " Se unio al grupo");
}
}
}
/* Comienza la conversación*/
while (true) {
String line = is.readLine();
/*asigna nuevas conversaciones a la variable globo de msg */
server.mensagens += name + " dice: " + line + "\n";
if (line.startsWith("/quit")) {
break;
} else {
/* El mensaje es público y lo transmite a todos los demás clientes. */
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i].clientName != null) {
threads[i].os.println(name + " dice: " + line);
}
}
}
}
}
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this
&& threads[i].clientName != null) {
threads[i].os.println("*** El usuario " + name
+ " está saliendo de la sala de chat !!! ***");
}
}
}
os.println("*** Bye " + name + " ***");
// * Limpiar. Establezca la variable de subproceso actual en nulo para que un nuevo cliente
// * podría ser aceptado por el servidor.
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] == this) {
threads[i] = null;
}
}
}
/**
* Cierre la secuencia de salida, cierre la secuencia de entrada,
* cierre el socket.
*/
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
}
}
}
| 88bffebbaf58f7eb1e90dafa9483306726c10dfd | [
"Java"
] | 1 | Java | merinomerino/messenger | d75f5f27dd8a6315a0177bca37cd54d0493cf551 | 41f9bbaaef02c1d48fb92d6fd9014d419428267a |
refs/heads/master | <repo_name>youssefmohamed552/infinite-runner<file_sep>/src/gnd/Ground.java
package gnd;
import java.awt.Graphics;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
import game.Canvas;
import game.Game;
import game.GameObject;
public class Ground {
private int _x;
private int _y;
private int blocks_count;
private LinkedList<GroundBlock> blocks;
private final int initial_height = 4;
private Canvas canvas;
public enum Behaviour{
STAY,
LEFT,
DOWN;
}
public Ground(Game parent , int count){
_x = 0;
_y = Canvas.HEIGHT - (initial_height * GroundTile.HEIGHT);
blocks_count = count;
blocks = new LinkedList<>();
init_ground(parent);
}
private void init_ground(Game parent){
if(blocks == null) return;
int w = 5;
int x = _x;
int prev_h = 0;
int h = initial_height;
Random random = new Random();
//int h = random.nextInt(6)+1;
for(int i = 0; i < blocks_count;i++){
prev_h = h;
blocks.add(new GroundBlock(parent, x , Canvas.HEIGHT - ( h * GroundTile.HEIGHT ), h , w));
x += (GroundTile.WIDTH*w);
h = random.nextInt(6)+1;
while(Math.abs(h - prev_h) > 2){
h = random.nextInt(6)+1;
}
// System.out.println("dimensions : "+h + ":" + 5);
}
}
public void draw(Graphics g){
if(blocks == null) return;
for(GroundBlock block: blocks){
block.draw(g);
}
}
public void move(){
for(GroundBlock block : blocks){
block.move();
}
_x -= GroundTile.STEP;
}
public int getHeightAt(int pos){
int height = 0;
for(GroundBlock block: blocks){
if(block.getX() < pos) {
height = (int)block.getHeight() * GroundTile.HEIGHT;
}
else{
break;
}
}
return height;
}
public Behaviour collidesWith(GameObject other) {
Iterator<GroundBlock> it_b = blocks.iterator();
GroundBlock b_prev = it_b.next();
while(it_b.hasNext()){
GroundBlock b = it_b.next();
if(b_prev.collidesWith(other)){
if(b_prev.getHeight() != b.getHeight() && b.collidesWith(other)) {
// System.out.println("LEFT");
return Behaviour.LEFT;
}
// System.out.println("STAY");
return Behaviour.STAY;
}
b_prev = b;
}
// for(GroundBlock b : blocks){
// if(b.collidesWith(other)){
// return true;
// }
// }
// System.out.println("DOWN");
return Behaviour.DOWN;
}
}
| a8d859fbbe796b529e1bebf6a6f96af33a1c12d2 | [
"Java"
] | 1 | Java | youssefmohamed552/infinite-runner | 3f760c7abd48d339affd2a2bbc3d6122850ae98a | a8eb57de1fd69f1a26418171c8d74a748e812955 |
refs/heads/master | <file_sep>package algorithms.search;
import java.util.*;
public class DepthFirstSearch extends ASearchingAlgorithm {
private Stack<AState> stack;
public DepthFirstSearch() {
this.queue = new LinkedList<AState>();
this.visitedNodes = 0;
this.stack = new Stack<AState>();
}
@Override
public Solution solve(ISearchable Is) {
if (Is==null || Is.getStartState()==null || Is.getGoalState()==null)
return null;
Is.ClearVisited();
// ArrayList<AState> solArr = new ArrayList<AState>();
// Mark the start state as visited and add it to the queue
Is.getStartState().setVisited(true);
// visitedNodes++;
// solArr.add(Is.getStartState());
stack.push(Is.getStartState());
// boolean finish = false;
Solution sol = new Solution(null);
while (!stack.isEmpty())
{
// remove a random state from the queue and add it to the solution path
AState currState = stack.pop();
if (currState.equals(Is.getGoalState())) {
// solArr.add(neighbors.get(i));
// Is.getGoalState().setCameFrom(currState);
sol = new Solution(currState);
break;
}
// solArr.add(currState);
//get all the possible next states
ArrayList<AState> neighbors = Is.getAllPossibleStates(currState, getName());
// go over all the neighbors of the curr state
for (int i = 0; i < neighbors.size() ; i++) {
//if the neighbor is not visited yet, set visited and set parent
if (!neighbors.get(i).isVisited()){
neighbors.get(i).setVisited(true);
visitedNodes++;
neighbors.get(i).setCameFrom(currState);
//if we arrived to the end, exit
//////////////////////////////////////
//add the neighbor to the queue
stack.push(neighbors.get(i));
}
}
}
//if we arrived here there is no solution
return sol;
// ArrayList<AState> solArr = new ArrayList<AState>();
// recDFS(Is, Is.getStartState(), solArr);
// ArrayList<AState> solArrForReal = new ArrayList<AState>();
// AState stateToAdd = Is.getGoalState();
// for (int i = 0; i<getNumberOfNodesEvaluated(); i++) {
// if (stateToAdd.equals(Is.getStartState()))
// break;
// solArrForReal.add(stateToAdd);
// stateToAdd = stateToAdd.getCameFrom();
// }
// return new Solution(Is.getGoalState(), solArrForReal);
}
@Override
public String getName() {
return "Depth First Search";
}
// void recDFS(ISearchable Is, AState currStart, ArrayList<AState> solArr) {
// // Mark the start state as visited and add it to the queue
// currStart.setVisited(true);
// visitedNodes++;
// solArr.add(currStart);
//
// //get all the possible next states
// ArrayList<AState> neighbors = Is.getAllPossibleStates(currStart, getName());
//// while (neighbors.size()!=0) {
// // go over all the neighbors of the curr state
// for (int i = 0; i < neighbors.size(); i++) {
// //if the neighbor is not my parent
// if (neighbors.get(i).equals(currStart.getCameFrom())) {
//// neighbors.remove(neighbors.get(i));
// continue;
// }
// if (neighbors.get(i).isVisited())
// continue;
// //if the neighbor is not visited yet, set visited and set parent
// else {
// neighbors.get(i).setVisited(true);
// visitedNodes++;
// neighbors.get(i).setCameFrom(currStart);
// //if we arrived to the end, exit
// if (neighbors.get(i).equals(Is.getGoalState())) {
// solArr.add(neighbors.get(i));
// return;
// }
// }
// recDFS(Is, neighbors.get(i), solArr);
// }
//// }
//// return recDFS(Is, currStart.getCameFrom(), solArr);
// }
}<file_sep>package algorithms.mazeGenerators;
import java.util.Arrays;
public class Maze {
private int[][] mat;
private Position start;
private Position end;
public Maze(int[][] mat, Position start, Position end) {
this.mat = mat;
this.start = start;
this.end = end;
}
public int[][] getMat() {
return mat;
}
public int getNumOfRows() {
return mat.length;
}
public int getNumOfColumns() {
return mat[0].length;
}
public Position getStartPosition() {
return start;
}
public Position getGoalPosition() {
return end;
}
public void print(){ //TODO: Print or print
if (mat == null)
System.out.print("null"); //TODO: check if ok
int iMax = mat.length - 1;
if (iMax == -1)
System.out.print(""); //TODO: check if ok
for (int i = 0; i<mat.length ; i++) {
for (int j=0; j<mat[0].length; j++){
if (i==start.getRowIndex() && j==start.getColumnIndex()){
System.out.print('S');
}
else if (i==end.getRowIndex() && j==end.getColumnIndex()){
System.out.print('E');
}
//if it's the end of a row
else System.out.print(mat[i][j]);
if (j==mat[0].length-1){
System.out.print('\n');
}
}
}
}
@Override
public String toString() {
return "Maze{" +
"mat=" + Arrays.toString(mat) +
", start=" + start +
", end=" + end +
'}';
}
}
| 08347890e972f31f0e739f7b307458d1a7aa6a45 | [
"Java"
] | 2 | Java | oribena/Maze | f29b5ac6ded1eb1de9fc2f2ceadebd8603c1aee1 | 97cd12cb8d15453bf7c7776b131ed69817f9a1d4 |
refs/heads/main | <repo_name>QuentinAndre11/lecture-spring-2021<file_sep>/test_core.py
from core import *
def test_add():
"""Check that `add()` works as expected"""
assert add(2, 3) == 5
def test_add_z():
"""Check that `add()` works as expected"""
assert add(2, 3, 1) == 6
def test_add_2():
"""Check that `add()` works as expected"""
assert add_2(3) == 5<file_sep>/core.py
def add(x, y, z=0):
"""Add two (or three) objects"""
return x + y + z
def add_2(x):
"""Add two to a number"""
return x + 2 | 383eb397dfe04e24910013fc581d9b4b771d5069 | [
"Python"
] | 2 | Python | QuentinAndre11/lecture-spring-2021 | 2f2b563e91ea6e18fe6cd3e9087f2fd0b2e2beee | 3f58eba6ce123eb6dbd5dc5d52a3a5bbf7639923 |
refs/heads/master | <file_sep>package com.rzierfiz.peinit.Pein;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.hardware.TriggerEventListener;
import android.util.Log;
import android.widget.TextView;
import com.rzierfiz.pein.SensorAPI.Sensors;
import com.rzierfiz.peinit.R;
public class Pein{
private int Intensity;
public boolean isMove;
public boolean isFall;
private SensorManager manager;
private Sensors g;
private Sensors a;
private TriggerPein tpm;
private TriggerPein tpf;
private int gf;
private int gm;
public static enum kind{
Fall,
Move,
}
public Pein(SensorManager manager)
{
this.manager = manager;
Intensity = 0;
isMove = isFall = false;
tpf = new TriggerPein(kind.Fall);
tpm = new TriggerPein(kind.Move);
}
public void work() {
g = new Sensors(manager, 0) {
public void onSensorChanged(SensorEvent e) {
//G-Sensor
if(isMove)
{
calcIntensity(e.values);
tpm.ResponsePein(Intensity);
}
}
};
a = new Sensors(manager, 1) {
public void onSensorChanged(SensorEvent e) {
//Accelometer
if(isFall) {
new CollisionDetection(e.values) {
@Override
public void run() {
if (this.isCollision())
tpf.ResponsePein(100);
Log.e("ASensor","Works");
}
};
}
}
};
}
public void getf(int i)
{
Log.e("" + i + ":","Moe");
tpf.change(i);
}
public void getm(int i)
{
Log.e("" + i + ":","Moe");
tpm.change(i);
}
public void stop()
{
tpf.pause();
tpm.pause();
g.stop();
a.stop();
}
void calcIntensity(float[] gsen)
{
if((int)gsen[0] != 0 || (int)gsen[1] != 0)
this.Intensity = 100;
else
this.Intensity = 0;
}
}
<file_sep># Pein
App is Meant To Pull Pranks..<br/>
<a href="https://github.com/rmhg/Pein/raw/master/Android%20Packags%20(.apk)/Signed/Release/Pein.apk">Click To Download App</a>
## Working :
App Play Sound If phone Is Moved From A Horizontal Table,
Sound Can Be Fart, Cough etc.
And If It Falls It Plays A Sound Like Scream
## Permissions :
Not Require Any Explicit Permission
## Requirements :
1.Min Android Version Should Be : 4.0 <br/>
2.Gravity Sensor<br/>
3.Accelarometer<br/>
## SoundClip Source : freesoung.org
## This App Is NOT A Virus
<file_sep>package com.rzierfiz.peinit.Pein;
import android.util.Log;
abstract public class CollisionDetection {
private float[] vals;
public CollisionDetection(float[] e)
{
this.vals = e;
run();
}
boolean isCollision() {
for (int i = 0; i < vals.length; i++) {
float temp = vals[i];
if (temp >= 35) {
return true;
}
}
return false;
}
abstract void run();
}
| 0262294ba2807674b96c669824390792a52915f0 | [
"Markdown",
"Java"
] | 3 | Java | rmhg/Pein | 3f8863b14cb1caf5bb572590f1f30572a7a69622 | c1df31b4532e2f4be1d4e353f2f789116f4b5b6b |
refs/heads/master | <repo_name>doulos76/Python_Study<file_sep>/python_basic/section04-1.py
# Data Type
v_str1 = "Niceman"
v_bool = True
v_str2 = "Goodboy"
v_float = 10.3
v_int = 7
v_dict = {
"name" : "Kim",
"age" : 25
}
v_list = [3, 5, 7]
v_tuple = 3, 5, 7
v_set = {7, 8, 9}
print(type(v_tuple))
print(type(v_set))
print(type(v_float))
print(type(v_str1))
print(type(v_bool))
print(type(v_int))
print(type(v_dict))
print(type(v_list))
i1 = 39
i2 = 939
big_int1 = 999999999999999999999999999999999999999999999999999
big_int2 = 777777777777777777777777777777777777777777777777777
f1 = 1.234
f2 = 3.784
f3 = .5
f4 = 10.
print(i1 * i2)
print(big_int1 * big_int2)
print(f1 ** f2)
print(f3 + i2)
result = f3 + i2
print(result)
print(type(result))
a = 5
b = 4
print(type(a), type(b))
result2 = a + b
c = result2
print(result2)
# 형변환
# int, float, complex(복소수)
print(int(result2))
print(float(c))
print(complex(3))
print(int(True))
print(int(False))
print(int('3'))
print(complex(False))
print(complex(True))
y = 100
y *= 100
print(y)
# 수치 연산 함수
# https://docs.python.org/3/library/math.html
print(abs(-7))
n, m = divmod(100, 8)
print(n, m)
import math
print(math.ceil(5.1))
print(math.floor(3.874))
<file_sep>/section01.py
# -*- coding: utf-8 -*-
# Section01
# Python Introduction, Workspace Setting
# Basic print out 설정
print('Hello Python!')
<file_sep>/section02-1.py
# -*- coding: utf-8 -*-
# section02-1
# Python Basic Coding
# Understand of Print Syntax
# Reference : https://www.python-course.eu/python3_formatted_output.php
# Basic Print
print('Hello Python!')
print("Hello Python!")
print("""Hello Python!""")
print('''Hello Python!''')
print()
# Usage of Separator Option
print('T', 'E', 'S', 'T', sep='')
print('T', 'E', 'S', 'T', sep='-')
print('niceman', 'google.com', sep='@')
print('one', 'two', 'three', sep='')
# Usage of End Option
print('Welcom To', end=' ')
print('the black parade', end=' ')
print('piano notes')
# Usage of Format [], {}, ()
print('{} and {}'.format('You', 'Me'))
print("{0} and {1} and {0}".format('You', 'Me'))
print("{a} are {b}".format(a='You', b='Me'))
#%s : String, %d : Integer, %f : Float Number
print("%s's favorite number is %d" % ('EunJee', 7))
print("Test1: %5d, Price: %4.2f" %(776, 6534.123))
print("Test1: {0: 5d}, Price: {1: 4.2f}".format(776, 6534.123))
print("Test1: {a: 5d}, Price: {b: 4.2f}".format(a=776, b=6534.123))
# escape code
"""
\n : 개행
"""
print("'you'")
print('\'you\'')
print('"you"')
print("""'you'""")
print('\\you\\\n')
print('test')
print('\t\t\ttest')
<file_sep>/python_basic/section05-2.py
# section05-2
# 시퀀스(순서가 있는) 자료형 반복
# 문자열, 리스트, 튜플, 집합, 사전
# iterable 리턴 함수: range, reversed, enumerate, filter, map, zip
names = ["Kim", "Park", "Cho", "Choi", "Yoo"]
for v in names:
print("You are : ", v)
word = "dreams"
for s in word:
print("Word : ", s)
my_info = {
"name": "Kim",
"age": 33,
"city": "Seoul"
}
# 기본 값을 키
for key in my_info:
print("my_info", key)
# 값
for key in my_info.values():
print("my_info", key)
# 키
for key in my_info.keys():
print("my_info", key)
# 키 and 값
for k in my_info.items():
print("my_info", k, v)
name = "KennRY"
for n in name:
if n.isupper():
print(n.lower())
else:
print(n.upper())
# break
numbers = [14, 3, 4, 7, 10, 24, 17, 2, 37, 15, 34, 36, 38]
for num in numbers:
if num == 33:
print("found : 33!")
break
else:
print("not found : 33!")
# for - else 구문(반복문이 정상적으로 수행 된 경우 else 블럭 수행)
for num in numbers:
if num == 33:
print("found : 33!")
break
else:
print("not found : 33!")
else:
print("Not found 33......")
# continue
lt = ["1", 2, 5, True, 4.3, complex(4)]
for v in lt:
if type(v) is float:
continue
print("타입 : ", type(v))
name = "Niceman"
print(reversed(name))
print(list(reversed(name)))
<file_sep>/python_basic/section02-1.py
# Section 02-1
# Python Basic Coding
# Print
# Basic Print
print('Hello Python!')
print("Hello Python!")
print("""Hello Python!""")
print('''Hello Python!''')
print()
# Using Seperator Option
print('T', 'E', 'S', 'T', sep='')
print('2019', '02', '19', sep='-')
print('niceman', 'google.com', sep='@')
# Using End Option
print('Welcome To', end=' ')
print('the black paradise', end=' ')
print('piano notes')
print('testtest')
print()
# Using format [], {}, ()
print('{} and {}'.format('You', 'Me'))
print("{0} and {1} and {0}".format('You', 'Me'))
print("{a} are {b}".format(a='You', b='Me'))
print("%s's favorite number is %d" % ('Python', 3)) #%s : 문자, %d: 정수, %f : 실수
print("Test1: %5d, Price: %4.2f" % (776, 6534.123))
print("Test1: {0: 5d}, Price:{1: 4.2f}".format(776, 6534.123))
print("Test1: {a: 5d}, Price:{b: 4.2f}".format(a=776, b=6534.123))
# escape code
print("'you'")
print('\'you\'')
print('"you"')
print("""'you'""")
print('\\you\\\n')
print('\t\t\ttest')
<file_sep>/python_basic/section04-5.py
# Quiz
# Section04-5
# 파이썬 데이터 타입(자료형)
# 딕셔너리, 집합 자료형
# 데이터 타입 관련 퀴즈(정답은 영상)
# 1. 아래 문자열의 길이를 구해보세요.
q1 = "dk2jd923i1jdk2jd93jfd92jd918943jfd8923"
lengthOfQ1 = len(q1)
print(lengthOfQ1)
print("1. ", len(q1))
# 2. print 함수를 사용해서 아래와 같이 출력해보세요.
# apple;orange;banana;lemon
print('apple;orange;banana;lemon')
print("2. ", """apple;orange;banana;lemon""")
# 3. 화면에 * 기호 100개를 표시하세요.
print('*' * 100)
# 4. 문자열 "30" 을 각각 정수형, 실수형, 복소수형, 문자형으로 변환해보세요.
thirty = "30"
int(thirty)
print(int(thirty))
print(float(thirty))
print(complex(thirty))
print(str(30))
print(type(int(thirty)))
print(type(float(thirty)))
print(type(complex(thirty)))
# 5. 다음 문자열 "Niceman" 에서 "man" 문자열만 추출해보세요.
niceman = "Niceman"
print(niceman[4:7])
niceman_idx = niceman.index("man")
print(niceman[niceman_idx: niceman_idx + 3])
# 6. 다음 문자열을 거꾸로 출력해보세요. : "Strawberry"
strawberry = "Strawberry"
print(strawberry[::-1])
print(list(reversed(strawberry)))
# 7. 다음 문자열에서 '-'를 제거 후 출력하세요. : "010-7777-9999"
phoneNumber = "010-7777-9999"
number = phoneNumber.replace('-', '')
print(number)
q7 = "010-7777-9999"
print("7. ", q7[0:3] + q7[4:8] + q7[9:13])
# 정규표현식
import re
print("Q7. ", re.sub('[^0-9]', '', q7))
# 8. 다음 문자열(URL)에서 "http://" 부분을 제거 후 출력하세요. : "http://daum.net"
url = "http://daum.net"
removeHttp = url[7:]
print(removeHttp)
# 9. 다음 문자열을 모두 대문자, 소문자로 각각 출력해보세요. : "NiceMan"
niceman = "NiceMan"
upperNiceman = niceman.upper()
print(upperNiceman)
lowerNiceman = niceman.lower()
print(lowerNiceman)
# 10. 다음 문자열을 슬라이싱을 이용해서 "cde"만 출력하세요. : "abcdefghijklmn"
string10 = "abcdefghijklmn"
print(string10[2:5])
# 11. 다음 리스트에서 "Apple" 항목만 삭제하세요. : ["Banana", "Apple", "Orange"]
fruits = ["Banana", "Apple", "Orange"]
fruits.remove("Apple")
print(fruits)
# 12. 다음 튜플을 리스트로 변환하세요. : (1,2,3,4)
tuple12 = (1, 2, 3, 4)
list12 = list(tuple12)
print(list12)
print(type(list12))
# 13. 다음 항목을 딕셔너리(dict)으로 선언해보세요. : <성인 - 100000 , 청소년 - 70000 , 아동 - 30000>
dic = {"성인": 100000, "청소년": 70000, "아동": 30000}
print(type(dic))
print(dic)
q13_dic = {}
q13_dic['성인'] = 100000
q13_dic['청소년'] = 70000
q13_dic['아동'] = 30000
print(q13_dic)
# 14. 13번 에서 선언한 dict 항목에 <소아 - 0> 항목을 추가해보세요.
dic["소아"] = 0
print(dic)
# 15. 13번에서 선언한 딕셔너리(dict)에서 Key 항목만 출력해보세요.
print(dic.keys())
print(list(dic.keys()))
# 16. 13번에서 선언한 딕셔너리(dict)에서 value 항목만 출력해보세요.
print(dic.values())
print(list(dic.values()))
# *** 결과 값만 정확하게 출력되면 됩니다. ^^* 고생하셨습니다. ***
<file_sep>/SourceCode/section01.py
# Section01
# Python 소개 및 작업 환경 설정
# 기본 출력
print('Hello Python!')
print('안녕 파이썬!')<file_sep>/README.md
# Python_Study
## Python 설치
* [Python download site](https://www.python.org/downloads/)
* Python 3 권장
## 가상환경 설치
* 아래 예시와 같이 사용
```
➜ Python_Study git:(master) ✗ python3 -m venv python_basic
ls
➜ Python_Study git:(master) ✗ ls
README.md SourceCode python_basic section01.py section02-1.py section02-2.py
➜ Python_Study git:(master) ✗ cd python_basic
➜ python_basic git:(master) ✗ ls
bin include lib pyvenv.cfg
➜ python_basic git:(master) ✗ cd bin
➜ bin git:(master) ✗ ls
activate activate.fish easy_install-3.7 pip3 python
activate.csh easy_install pip pip3.7 python3
➜ bin git:(master) ✗ source ./activate
(python_basic) ➜ bin git:(master) ✗ deactivate
➜ bin git:(master) ✗ source ./activate
(python_basic) ➜ bin git:(master) ✗ deactivate
➜ bin git:(master) ✗ source ./activate
(python_basic) ➜ bin git:(master) ✗ code```
```
## VSCode 설치 및 설정
* 폴더 설정
* Python 설정
* Python: Select Interpreter
* tasks.json 설정 (단축키 설정)
## 가상환경 및 패키지
* [참고](https://docs.python.org/ko/3/tutorial/venv.html)
### pip로 package 관리하기
* 필요 package 검색 예제
```
(tutorial-env) $ pop search simplejson
```
* 설치
```
(tutorial-env) $ pop install simplejson
```
* 내용 확인
```
(tutorial-env) $ pop show simplejson
```
* 가상환경에 설치된 내용 확인
```
(tutorial-env) $ pop list
```
* 설치된 package 삭제
```
(tutorial-env) $ pop uninstall simplejson
``` | 6727f6f02ef8bf1403f02b0fc11c98f364a621b5 | [
"Markdown",
"Python"
] | 8 | Python | doulos76/Python_Study | cd978ec0f60fe16de575122f1dcf37bc5895aac6 | fdd73012ce9f1d61d1805e992a1c2893c5b77a45 |
refs/heads/master | <file_sep>import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Link } from "react-router-dom"
import {
Home,
Login,
Topic
} from 'view'
// const Topics = ({ match }) => (
// <div>
// <h2>Topics</h2>
// <ul>
// <li>
// <Link to={`${match.url}/rendering`}>Rendering with React</Link>
// </li>
// <li>
// <Link to={`${match.url}/components`}>Components</Link>
// </li>
// <li>
// <Link to={`${match.url}/props-v-state`}>Props v. State</Link>
// </li>
// </ul>
// <Route exact path={`${match.url}/:topicId`} component={Topic} />
// <Route
// path={match.url}
// render={() => <h3>Please select a topic.</h3>}
// />
// </div>
// );
// const Topic = ({ match }) => (
// <div>
// <h3>{match.params.topicId}</h3>
// </div>
// );
export default class App extends Component {
render(){
return (
<Router>
<div>
<header>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/login">Login</Link>
</li>
<li>
<Link to="/Topic">Topics</Link>
</li>
</ul>
</header>
<hr />
<main>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/Topic" component={Topic} />
</main>
<footer>脚部</footer>
</div>
</Router>
)
}
}<file_sep>import fetch from 'http'
import { Component } from 'react';
import { observable, action } from 'mobx'
class Topic extends Component {
@observable topics = []
/**
* 主题列表
* @memberof Topic
*/
@action topicList = async () => {
let { data } = await fetch({
api : 'topics',
method: 'get'
})
this.topics = data;
console.log(data);
}
/**
* 主题详情
* @memberof Topic
*/
@action topicDetail = () => {
}
/**
* 主题删除
* @memberof Topic
*/
@action topicDelete = () => this.topics.shift()
/**
* 主题新增
* @memberof Topic
*/
@action topicAdd = () => {
}
}
export default new Topic()<file_sep>import React, { Component } from 'react'
import { observer, inject } from 'mobx-react'
//注入状态
@inject(store => ({
topics : store.topic.topics, //主题
topicList : store.topic.topicList, //获取主题列表
topicDelete: store.topic.topicDelete
}))
//@inject('topic')
//组件监听
@observer
export class TopicList extends Component{
componentDidMount(){
this.props.topicList();
}
render(){
const { topics } = this.props
return(
<div>
<button onClick={ this.props.topicDelete }>更新数据</button>
<ul>
{
topics.map((item, index) =>
<li key={index}>
{ item.title }
</li>
)
}
</ul>
</div>
)
}
}<file_sep>export * from './topic'
export * from './login'
export * from './test'
export * from './home'<file_sep>import React, { Component } from 'react'
import { Route, Link } from "react-router-dom"
import {
TopicList,
TopicDetail
} from './index'
export class Topic extends Component {
render(){
return (
<div>
<h1>Topic</h1>
<ul>
<li><Link to='/topic/list'>全部</Link></li>
<li><Link to='/topic/detail'>精华</Link></li>
<li>分享</li>
<li>问答</li>
<li>招聘</li>
</ul>
<div>
<Route path='/topic/list' component={TopicList}></Route>
<Route path='/topic/detail' component={TopicDetail}></Route>
</div>
</div>
)
}
}
<file_sep>import BasicExample from './test'
export {
BasicExample
}<file_sep>import { user } from './user'
import { topic } from './topic'
/**
* sotre <object>
*/
export default {
user,
topic
}
<file_sep>import React, { Component } from 'react'
import { observer, inject } from 'mobx-react'
@inject(store => ({
detail:store.topic.detail
}))
@observer
export class TopicDetail extends Component {
render(){
return (
<div>详情页面</div>
)
}
}
<file_sep>export * from './topic'
export * from './topic-list'
export * from './topic-detail' | f735fafe706334bfc81a550d420e2b289adeead0 | [
"JavaScript"
] | 9 | JavaScript | yxbgithub1/react-cnode | d08e197c9a20725a4bb97df2f9e7afd8bead3590 | df5a0cef60e264cdb7faa56f71cd80d5b68b7eb0 |
refs/heads/master | <repo_name>kisaragui/Alkemy-React-Challenge<file_sep>/src/components/utils/useApiHeroes.js
import { useEffect, useState } from "react";
import apiHeroes from "./Api";
const useApiHeroes = (response) => {
const [state, setState] = useState({data: [], empty: true, response:"" });
useEffect(() => {
let {results} = response;
apiHeroes(results)
.then(res =>{
if (res.response ===undefined) {
setState({data: [], empty: true});
}else if(res.response ==="error"){
setState({data:[], empty: true, response:"error"});
}else if(res.response ==="success"){
setState({data:res.data, empty: false});
}
})
},[response]);
return state;
}
export default useApiHeroes;<file_sep>/src/components/utils/useEffectTeam.js
import { useEffect, useState } from "react";
import React from 'react'
const useEffectTeam = (hero) => {
const [state, setState] = useState({data: [], empty: true, selected:true });
return state;
}
export default useEffectTeam
<file_sep>/src/components/views/HeroItem.js
import React from "react";
const HeroItem = (hero) => {
return (
<div className="row no-gutters">
<div className="col-md-4">
<img src={hero.image.url} className="card-img" alt={hero.name}/>
</div>
<div className="col-md-8">
<div className="card-body">
<h5 className="card-title">{hero.name}</h5>
<div className="container">
<div className="row align-items">
<div className="col">
<p className="card-text"> intelligence: {hero.powerstats.intelligence}</p>
</div>
<div className="col">
<p className="card-text"> strength: {hero.powerstats.strength}</p>
</div>
</div>
<div className="row align-items">
<div className="col">
<p className="card-text"> durability: {hero.powerstats.durability}</p>
</div>
<div className="col">
<p className="card-text"> speed: {hero.powerstats.speed}</p>
</div>
</div>
<div className="row align-items">
<div className="col">
<p className="card-text"> power: {hero.powerstats.power}</p>
</div>
<div className="col">
<p className="card-text"> combat: {hero.powerstats.combat}</p>
</div>
</div>
</div>
<div className="card-body">
<button type="button" className="btn btn-primary btn-sm" >Agregar al Equipo</button>
<button type="button" className="btn btn-secondary btn-sm">Ver detalle</button>
</div>
</div>
</div>
</div>
)
}
export default HeroItem
<file_sep>/src/components/views/SearchForm.js
import React from 'react';
import { useFormik } from 'formik';
const Searchform= ({setHero}) => {
const formClean = (formValues) => {
let form={};
for (const key in formValues) {
form.hero = formValues[key].toLowerCase()
}
return form;
}
const formik = useFormik({
initialValues: {
hero: ""
},
onSubmit: (values) =>{
const form =formClean(values);
setHero(form)
formik.resetForm()
},
});
return (
<form onSubmit={formik.handleSubmit}>
<div className="container-fluid">
<p>Por favor ingrese un heroe: </p>
<label htmlFor="search" className="form-label">Buscador</label>
<input type="text" className="form-control" name="hero" onBlur={formik.handleBlur} onChange={formik.handleChange} value={ formik.values.hero }/>
<button className="btn btn-primary" type="submit">Buscar</button>
</div>
</form>
)
}
export default Searchform
<file_sep>/src/components/views/Containerbody.js
import SearchForm from "./SearchForm";
import HeroList from "./HeroList";
import React, { useState } from 'react'
const Containerbody = () => {
const [hero, setHero] = useState("");
return (
<div className="main">
<div class="container-fluid">
<div class="row">
<SearchForm setHero={setHero}/>
</div>
<div class="row row-cols">
<HeroList results={hero["hero"]}/>
</div>
</div>
</div>
)
}
export default Containerbody
<file_sep>/src/components/utils/Api.js
import Api from "./ConfigApi";
const tokenKey = "4058531047595511";
const apiHeroes = async (hero) => {
let results = {response: undefined, data: undefined}
const url = `/https://superheroapi.com/api/${tokenKey}/search/${hero}`;
if (hero){
const apiHeroes = await Api.get(url)
const data = await apiHeroes.data;
if(data.response === "success"){
results = {response: apiHeroes.data.response, data:apiHeroes.data.results}
return results
}else{
results = {response: apiHeroes.data.response, data:apiHeroes.data.error}
return results
}
}else{
return results
}
}
export default apiHeroes; | da2261c1b46b47552e523caee344517615f51ff6 | [
"JavaScript"
] | 6 | JavaScript | kisaragui/Alkemy-React-Challenge | 420e24bdb9d8152aeef941f8ce5e979e2bfce33f | 1a77a008c29337d4f0460212441e117f64b7f68a |
refs/heads/master | <file_sep>//! An experimental
//! [OSCORE](https://tools.ietf.org/html/rfc8613)
//! implementation with
//! [EDHOC](https://tools.ietf.org/html/draft-selander-ace-cose-ecdhe-14)
//! key exchange, intended for embedded devices.
//!
//! The EDHOC implementation is based on
//! [draft 14](https://tools.ietf.org/html/draft-selander-ace-cose-ecdhe-14)
//! of the EDHOC specification. It only does authentication with raw public
//! keys (RPK), so it covers the asymmetric authentication scenario, but not
//! the symmetric one using pre-shared keys (PSK).
//! On the OSCORE side, it does key derivation using the master secret and
//! master salt, which can be established with EDHOC.
//!
//! There is [documentation](https://martindisch.github.io/oscore/oscore/) as
//! well as a [demo implementation](https://github.com/martindisch/oscore-demo)
//! using this library, with a resource server on an STM32F3, a client on an
//! STM32F4 and a CoAP proxy running on a Raspberry Pi.
//!
//! ## Security
//! This should **not currently be used in production code**, use at your own
//! risk.
#![cfg_attr(not(feature = "std"), no_std)]
#[macro_use]
extern crate alloc;
mod cbor;
pub mod edhoc;
pub mod oscore;
| f0efd64c421148cdb7a63222a656689655faf061 | [
"Rust"
] | 1 | Rust | mcr/oscore | bfc184a1ba37c719358dfe0fac405724cf9cf3fe | 8dbd9a62f479cd419caae3baa00f8b9a3c3e68a9 |
refs/heads/master | <repo_name>os6sense/ruby-micro-benchmarks<file_sep>/spec/bm_record_spec.rb
require_relative '../bmstore'
describe BMRecord do
it "add_tms adds a tms record to the db" do
TMS = Struct.new(:user, :system, :total, :real)
tms = TMS.new(1.0, 2.0, 3.0, 4.0)
bm = BMRecord.new.add_tms("test", DateTime.now, tms)
end
end
<file_sep>/constants.rb
# Constants
MICRO = 100
SMALL = 1_000
MIDS = 10_000
MEDIUM = 100_000
LARGE = 1_000_000
XLARGE = 10_000_000
BIGNUM = 999_999_999_999_999_999_999
<file_sep>/app/models/bm_record.rb
class BMRecord < ActiveRecord::Base
has_one :ruby_version
has_one :test_date
has_one :test_name
attr_accessible :id,
:user,
:system,
:total,
:real
def add_tms(label, test_date, ruby_version, tms)
self.test_name_id ||= (tn = BMTestName.new(test_name: label)).save ? tn.id : BMTestName.find_by_test_name(label).id
self.test_date_id ||= (td = BMTestDate.new(run_date_time: test_date)).save ? td.id : BMTestDate.where("run_date_time=?", test_date).first.id
self.ruby_version_id ||= (rv = BMRubyVersion.new(ruby_version: ruby_version)).save ? rv.id : BMRubyVersion.find_by_ruby_version(ruby_version).id
self.user ||= tms.utime
self.system ||= tms.stime
self.total ||= tms.total
self.real ||= tms.real
save()
end
def compare(versions)
ResultTable.new(versions).tap do | table |
BMTestName.find(:all).each do | test |
ResultRow.new(test.test_name).tap do | row |
versions.each do | ruby_version |
BMRecord
.where(test_name_id: test.id, ruby_version_id: BMRubyVersion.find_by_ruby_version(ruby_version).id)
.tap { | result | row.add_result(ruby_version, result) }
end
table.add_row(row)
end
end
end
end
end
class ResultTable
attr_reader :versions,
:results
def initialize(versions)
@versions = versions
@results = {}
end
def add_row(result)
@results[result.name] = result
end
end
class ResultRow
attr_reader :name,
:results
def initialize(name)
@name = name
@results = {}
end
def add_result(ruby_version, result)
@results[ruby_version] = result
.inject(0.0) { | sum, r | sum + r.real } / result.size
end
end
<file_sep>/helpers.rb
#
# Print usage information
#
def usage
puts "Run this program using either:
ruby benchmark.rb
or
rake run_benchmark
Running as a rake task will allow for saving results for analysis using
the rails UI.
"
end
#
# Used to format a header for each "test section"
#
def header str
puts str
.upcase
end
#
# Very simple class to test class and accors
#
class Point
attr_accessor :x, :y
def initialize(x, y)
@x = x
@y = y
end
end
# ################################
# TESTS TO HELP IN TESTING RETURN
#
def ret i
return i
end
def ret_impl i
i
end
def yield_i i
yield i
end
# ################################
#
# Used to test Class vs Struct
#
Widget = Struct.new(:id)
point_s = Struct.new(:x, :y)
Point_s = point_s
#
# Used for testing class accessors
#
class TestClass
attr_reader :ar
attr_writer :aw
attr_accessor :aa
attr_accessor :i
class << self; attr_accessor :x end
@@x = 1
def self.sfoo; end
def foo; end
end
<file_sep>/benchmarks.rb
require "benchmark"
require_relative 'constants'
require_relative 'helpers'
# TODO:
# Save Section info so that it is easier to analyse the final result.
# Save source code line
# Retain checkboxes on UI
# Wrap the bmstore in an ugly begin end otherwise Rails will find SOMETHING
# to complain about if we just try running the benchmark via Ruby. Probably
# should attempt to initialise a connection but I'm already tired of hearing
# Rails opinion.
begin
require_relative 'bmstore'
$run_date = Time.zone.now # Monkey patched
rescue Exception
$run_date = Time.now
end
# Reopen the Benchmark::Report class, manually sending the
# item message (item is aliased to report). After running, store the result
# in the db. This is called ONCE after each benchmark has run.
class Benchmark::Report
@@warned = false
def report(label, *format, &block)
tms = item(label, format, &block)
SourceLine.new(caller[0])
begin
SourceLine.new(caller[0])
#BMStore.new(label, $run_date, $ruby_version,
#SourceLine.new(caller[0]), tms)
rescue Exception
unless @@warned
puts "** Sorry, could not save benchmark results to rails db."
puts "** Try running as a rake task. Further warnings suppressed."
end
@@warned = true
end
end
end
def method_calls x
tc = TestClass.new
header("method calls")
x.report("Static Call") { XLARGE.times { TestClass.sfoo }}
x.report("Instance Call") { XLARGE.times { tc.foo }}
x.report("Send (static)") { XLARGE.times { tc.send(:foo) }}
x.report("Send (instance)") { XLARGE.times { TestClass.send(:sfoo) }}
x.report("Instance Accessor") { XLARGE.times { tc.i}}
x.report("class variable") { XLARGE.times { TestClass.x}}
x.report("Accessor - r") { XLARGE.times { tc.ar }}
x.report("Accessor - rw") { XLARGE.times { tc.aa }}
x.report("Accessor - rw") { XLARGE.times { tc.aa=1 }}
x.report("Accessor - w") { XLARGE.times { tc.aw=1 }}
end
# Used to test global access
$global = 1
def comparisons x
bar = 1
baz = nil
header("Comparisons")
x.report("bool == bool") { XLARGE.times { |i| true == true } }
x.report("bool != bool") { XLARGE.times { |i| true != true } }
x.report("bool.eql? bool") { XLARGE.times { |i| true.eql? true } }
x.report("sym == sym") { XLARGE.times { |i| :a == :a } }
x.report("sym != sym") { XLARGE.times { |i| :a != :a } }
x.report("sym.eql? sym") { XLARGE.times { |i| :a.eql? :a } }
x.report("int == int (fix-global)") { XLARGE.times { |i| $global == $global } }
x.report("int != int (fix-global)") { XLARGE.times { |i| $global == $global } }
x.report("int.eql? int (fix-global)") { XLARGE.times { |i| $global.eql? $global } }
x.report("int == int (fix)") { XLARGE.times { |i| 1 == 1 } }
x.report("int != int (fix)") { XLARGE.times { |i| 1 == 1 } }
x.report("int.eql? int (fix)") { XLARGE.times { |i| 1.eql? 1 } }
x.report("int == int (big)") { XLARGE.times { |i| BIGNUM == BIGNUM } }
x.report("int != int (big)") { XLARGE.times { |i| BIGNUM != BIGNUM } }
x.report("int.eql? int (big)") { XLARGE.times { |i| BIGNUM.eql? BIGNUM } }
x.report("float == float") { XLARGE.times { |i| 1.0 == 1.0 } }
x.report("float != float") { XLARGE.times { |i| 1.0 != 1.0 } }
x.report("float eql float") { XLARGE.times { |i| 1.0.eql? 1.0 } }
x.report("char == char") { XLARGE.times { |i| 'a' == 'a' } }
x.report("str == str") { XLARGE.times { |i| "a" == "a" } }
x.report("str == char") { XLARGE.times { |i| "a" == 'a' } }
x.report("str == sym") { XLARGE.times { |i| :a == 'a' } }
x.report("var == nil") { XLARGE.times { |i| bar == nil } }
x.report("nil? (false)") { XLARGE.times { |i| bar.nil? } }
x.report("nil? (true)") { XLARGE.times { |i| baz.nil? } }
end
def exceptions x
header("Exceptions")
x.report("raise Exception") { LARGE.times { |i| begin raise Exception; rescue Exception; end } }
x.report("fail Exception") { LARGE.times { |i| begin fail Exception; rescue Exception; end } }
x.report("raise StandardError") { LARGE.times { |i| begin raise StandardError; rescue StandardError; end } }
x.report("fail StandardError") { LARGE.times { |i| begin fail StandardError; rescue StandardError; end } }
x.report("raise (str)") { LARGE.times { |i| begin raise "Exception"; rescue Exception; end } }
x.report("fail (str)") { LARGE.times { |i| begin fail "Exception"; rescue Exception; end } }
end
def containers_aa x
p1 = Point.new(10, 10)
p2 = {x: 10, y: 10}
p3 = Point_s.new(10, 10)
header("Containers, Accessors & Assignments")
x.report("class.new:") { LARGE.times { |i| Point.new(i, i) } }
x.report("hash {}:") { LARGE.times { |i| {x: i, y: i} } }
x.report("struct.new:") { LARGE.times { |i| Point_s.new(i, i) } }
header("Accessors")
x.report("class.x:") { XLARGE.times { |i| p1.x } }
x.report("hash[:x]:") { XLARGE.times { |i| p2[:x]} }
x.report("hash[\"x\"]:") { XLARGE.times { |i| p2["x"]} }
x.report("struct.x:") { XLARGE.times { |i| p3.x } }
x.report("struct[:x]:") { XLARGE.times { |i| p3[:x] } }
x.report("struct[\"x\"]:") { XLARGE.times { |i| p3["x"] } }
header("Assignments")
x.report("c.x=:") { XLARGE.times { |i| p1.x = 20 } }
x.report("h[:x]=:") { XLARGE.times { |i| p2[:x] = 20 } }
x.report("h[\"x\"]=:") { XLARGE.times { |i| p2["x"] = 20 } }
x.report("s.x=:") { XLARGE.times { |i| p3.x = 20 } }
x.report("foobar ||=:") { XLARGE.times { |i| foobar ||= 20 } }
x.report("foobar =:") { XLARGE.times { |i| foobar = 20 } }
end
def string_ops x
foo = "foo"
bar = 1
header("String Ops")
x.report("interpolation :") { ; LARGE.times { |i| " p1 #{foo} and p2 #{bar}" } }
x.report("concatination + ':") { LARGE.times { |i| 'p1 ' + foo + ' and p2 ' + bar.to_s } }
x.report("concatination + \":") { LARGE.times { |i| "p1 " + foo + " and p2 " + bar.to_s } }
x.report("<< concatination-':") { LARGE.times { |i| 'p1 ' << foo << ' and p2 ' << bar } }
x.report("<< concatination-\":"){ LARGE.times { |i| "p1 " << foo << " and p2 " << bar } }
header("String Ops, StringBuilder style (ONLY 20K)")
x.report("sb interpolation :") { tmp = ""; (1..20_000).each { |i| tmp = "#{tmp} p1 #{foo} and p2 #{bar}" } }
x.report("sb concatination +':") { tmp = ""; (1..20_000).each { |i| tmp += 'p1 ' + foo + ' and p2 ' + bar.to_s } }
x.report("sb concatination +\":") { tmp = ""; (1..20_000).each { |i| tmp += "p1 " + foo + " and p2 " + bar.to_s } }
x.report("sb concatination-':") { tmp = ""; (1..20_000).each { |i| tmp << 'p1 ' << foo << ' and p2 ' << bar } }
x.report("sb concatination-\":") { tmp = ""; (1..20_000).each { |i| tmp << "p1 " << foo << " and p2 " << bar } }
end
def enumerable x
widgets = [].tap { |w| 100.times { |i| w << Widget.new(i) } }
header("Enumerable")
x.report("map with to_proc") { MEDIUM.times { widgets.map(&:id) }}
x.report("inject") { MEDIUM.times { widgets.inject([]) {|w, a| w.push(a.id)} }}
x.report("collect") { MEDIUM.times { widgets.collect {|w| w.id }}}
x.report("map") { MEDIUM.times { widgets.map {|w| w.id } }}
x.report("unwound") { MEDIUM.times { i=0; a = []; while i < 100 do a << widgets[i].id; i+=1; end }}
end
# helper method so that we dont have to write the same loop 3 times
def loop_helper x, outer, inner
x.report("while (start) #{inner}:") { outer.times { |i| i=0; while i < inner do i+=1; end }}
x.report("while (tail) #{inner}:") { outer.times { |i| i=0; begin i+= 1 end while i < inner }}
x.report("until (tail): #{inner}:") { outer.times { |i| i=0; i+= 1 until i >= inner }}
x.report("until (start) #{inner}:") { outer.times { |i| i=0; until i > inner do i+=1 end }}
x.report("upto #{inner}:") { outer.times { |i| 0.upto(inner) {} }}
x.report("times #{inner}:") { outer.times { |i| inner.times {} }}
x.report("each #{inner}:") { outer.times { |i| (0..inner).each {} }}
x.report("for #{inner}:") { outer.times { |i| for i in 0..inner do ; end }}
end
def loops x
header("loops - #{MICRO} iterations")
loop_helper x, MEDIUM, MICRO
header("loops - #{SMALL} iterations")
loop_helper x, SMALL, MEDIUM
header("loops - #{LARGE} iterations")
loop_helper x, MICRO, LARGE
end
def return_vs_yield x
header("return vs yield")
x.report("return explicit:") { LARGE.times { |i| ret(i) }}
x.report("return implicit:") { LARGE.times { |i| ret_impl(i) }}
x.report("yield:") { LARGE.times { |i| yield_i(i) { } }}
end
def logic x
header("Logic")
x.report("if (1 term):") { XLARGE.times { |i| true if true }}
x.report("if-then-end (1 term):") { XLARGE.times { |i| if true then true end }}
x.report("if-then-else:") { XLARGE.times { |i| if true then 1 else 0 end }}
x.report("?:") { XLARGE.times { |i| true ? 1 : 0 }}
x.report("case:") { XLARGE.times { |i| case true when true;1 else;0 end }}
end
def misc x
header("Miscellanious")
x.report("mod:") { XLARGE.times { |i| i % 2 == 0 } }
x.report("even:") { XLARGE.times { |i| i.even? }}
end
# run the sweet (tee hee)
def run_benchmarks(ruby_version=nil)
if ruby_version
$ruby_version = ruby_version
else
$ruby_version = RUBY_VERSION
end
usage
Benchmark.bm(25) do |x|
containers_aa x
loops x
method_calls x
comparisons x
exceptions x
string_ops x
enumerable x
return_vs_yield x
logic x
# : vs =>
end
end
# Run the benchmarks if called directly
if __FILE__ == $0
run_benchmarks
end
<file_sep>/db/migrate/20140302091816_create_bm_records.rb
class CreateBmRecords < ActiveRecord::Migration
def change
create_table :bm_records do |t|
t.integer :ruby_version_id
t.integer :test_date_id
t.integer :test_name_id
t.float :user
t.float :system
t.float :total
t.float :real
t.timestamps
end
end
end
<file_sep>/app/controllers/bm_record_controller.rb
class BMRecordController < ApplicationController
def index
# list the available versions, accept in check box which to compare
@versions = BMRubyVersion.all
if params[:ruby_version].present?
@result_table = BMRecord.new.compare(params[:ruby_version][:versions])
end
_simple_response @versions
end
def _simple_response r_obj
respond_to do |format|
format.html
format.json { render json: r_obj }
end
end
end
class ResultTablePresenter
def initialize result_table
@rt = result_table
end
def open_table
"<table class=\"table table-bordered table-striped\">"
end
def headers(versions)
"".tap do | tmp |
tmp << "<tr><th>test name</th>"
versions.each do | version |
tmp << "<th>#{version}</th>"
end
tmp << "</tr>"
end
end
def results(versions, test_name, row)
"".tap do | tmp |
tmp << "<tr><td>#{test_name}</td>"
versions.each do | version |
tmp << "<td>#{'%.5f' % row.results[version]}</td>"
end
tmp << "</tr>"
end
end
def present
@tb = ""
@tb << open_table
@tb << headers(@rt.versions)
@rt.results.each do | test_name, row |
@tb << results(@rt.versions, test_name, row)
end
@tb << "</table>"
@tb.html_safe
end
end
<file_sep>/app/models/bm_ruby_version.rb
class BMRubyVersion < ActiveRecord::Base
belongs_to :bm_record
attr_accessible :ruby_version
validates_uniqueness_of :ruby_version
end
<file_sep>/test/unit/helpers/bm_record_helper_test.rb
require 'test_helper'
class BmRecordHelperTest < ActionView::TestCase
end
<file_sep>/app/models/bm_test_date.rb
class BMTestDate < ActiveRecord::Base
belongs_to :bm_record
attr_accessible :run_date_time
validates_uniqueness_of :run_date_time
end
<file_sep>/app/models/bm_test_name.rb
class BMTestName < ActiveRecord::Base
belongs_to :bm_record
attr_accessible :test_name
validates_uniqueness_of :test_name
end
<file_sep>/test/unit/bm_record_test.rb
require 'test_helper'
class BmRecordTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
test "add_tms adds a tms record to the db" do
TMS = Struct(:user, :system, :total, :real)
tms = TMS.new(1.0, 2.0, 3.0, 4.0)
bm = BMRecord.new.add_tms("test", DateTime.now, tms)
end
end
<file_sep>/README.md
A simple set of benchmarks for measuring specific Ruby statements and
operations.
<file_sep>/db/migrate/20140302091858_create_bm_test_names.rb
class CreateBmTestNames < ActiveRecord::Migration
def change
create_table :bm_test_names do |t|
#t.belongs_to :bm_record
t.string :test_name
t.timestamps
end
end
def up
end
def down
end
end
<file_sep>/lib/tasks/benchmark_run.rake
desc 'perform a run of the benchmark, storing the results in the db'
task :benchmark_run => :environment do
require_relative '../../benchmarks'
run_benchmarks
end
<file_sep>/bmstore.rb
require 'active_record'
require_relative 'app/models/bm_test_name'
require_relative 'app/models/bm_test_date'
require_relative 'app/models/bm_ruby_version'
require_relative 'app/models/bm_record'
class BMStore
# Attempts to save the record into a database as defined by the rails
# database. If is fails it silently fails.
#
# id concatination
# id 1.9.2
# id datetime - generated at start of tests
# id test_name_id, ruby: _version_id, test_run_id, user, system, total, real
def initialize(label, test_date, ruby_version, source_line, tms)
begin
BMRecord.new
.add_tms(label, test_date, ruby_version, source_line, tms)
rescue ActiveRecord::ConnectionNotEstablished
end
end
end
class SourceLine
def initialize(line)
# benchmarks.rb:122:in `containers_aa'
@filename = line[0..(i=line.index(':'))-1]
@line_no = line[i+1..(line.index(':', i+1)-1 )]
@method_name = line[line.index('`')+1..-2]
#@code =
puts @line
puts @filename
puts @line_no
puts @method_name
end
def get_line(filename, line_number)
File.open(filename, 'r')
end
end
<file_sep>/db/migrate/20140302091921_create_bm_test_dates.rb
class CreateBmTestDates < ActiveRecord::Migration
def change
create_table :bm_test_dates do |t|
#t.belongs_to :bm_record
t.time :run_date_time
t.timestamps
end
end
end
| ffe397096a0c5b153a6c5435a385bae4df0c7e24 | [
"Markdown",
"Ruby"
] | 17 | Ruby | os6sense/ruby-micro-benchmarks | b5c18c9b23d5936f50b5c57de4fc1d3f128fa1bf | 1576908906ea7b560733796b9cd2f25e4d0166f0 |
refs/heads/main | <file_sep>import $ from 'jquery';
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import './css/styles.css';
import convertToRoman from './scripts.js';
// UI Logic
$(document).ready(function () {
$("form#convert").submit(function (event) {
event.preventDefault();
const value = $("#number").val();
$("#result").html(convertToRoman(value));
});
});
// Additional way to convert:
// var romanNumeralConverter = [
// [1000, 'M'],
// [900, 'CM'],
// [500, 'D'],
// [400, 'CD'],
// [100, 'C'],
// [90, 'XC'],
// [50, 'L'],
// [40, 'XL'],
// [10, 'X'],
// [9, 'IX'],
// [5, 'V'],
// [4, 'IV'],
// [1, 'I']
// ];
// function convertToRoman(num) {
// if (num === 0) {
// return '';
// }
// for (var i = 0; i < romanNumeralConverter.length; i++) {
// if (num >= romanNumeralConverter[i][0]) {
// return romanNumeralConverter[i][1] + convertToRoman(num - romanNumeralConverter[i][0]);
// }
// }
// }<file_sep>import convertToRoman from './../src/scripts.js';
describe ('convertToRoman', () => {
test('should correctly convert a number to a roman numeral', () => {
expect(convertToRoman(4)).toEqual("IV");
});
});<file_sep>// Business Logic
export default function convertToRoman(num) {
var roman = "";
var values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
var numerals = [
"M",
"CM",
"D",
"CD",
"C",
"XC",
"L",
"XL",
"X",
"IX",
"V",
"IV",
"I",
];
for (let i = 0; i < values.length; i++) {
if (num >= values[i]) {
if (5 <= num && num <= 8) num -= 5;
else if (1 <= num && num <= 3) num -= 1;
else num -= values[i];
roman += numerals[i];
i--;
}
}
return roman;
}
<file_sep># Roman Numeral Converter
#### This is a site that converts to Roman Numerals
#### _By <NAME>_
## Technologies Used
* HTML
* CSS
* JavaScript
* JQuery
* Bootstrap
## Description
This simple HTML site uses Javascript loops to convert an inputted number to Roman Numerals.
## Setup/Installation Requirements
* _Clone this repository to your desktop_
* _Go to the top level of this directory_
* _Open index.html in your browser_
* _Type in the number you want to convert_
## Known Bugs
* _N/A_
## License
_[MIT](https://opensource.org/licenses/MIT)_
Copyright (c) 2021 <NAME>
## Contact Information
_<NAME> **<EMAIL>**_
<details>
<summary><h2>Tests</h2></summary>
Describe: convertToRoman()
Test: "It will convert one number to I"
Code: convertToRoman(1)
Expected Output: I
Test: "It will convert 4 to IV"
Code: convertToRoman(4)
Expected Output:IV
Test: "It will separate out ones, tens, hundreds, and thousands"
Code: convertToRoman(100)
Expected Output: C
Test: "It will return a Roman Numeral if user inputs any number less than 4000"
Code: convertToRoman(3,999)
Expected Output: MMMCMXCIX
</details>
| 43d92a0a6ccbdf28a44d338758b4b0c4dce6ea5e | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | paigetiedeman/Roman-Numerals | 818da6e38b1e372fb97a531dcf8592d5d417c22e | da932becf389b88ac51c2501ed44b72ef792988f |
refs/heads/master | <repo_name>franela/watch-docker<file_sep>/timeline/timeline.go
package timeline
import (
"fmt"
"os"
"time"
"github.com/google/go-github/github"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
var mongoSession *mgo.Session
func init() {
mongoUrl := "mongo"
if url, exists := os.LookupEnv("MONGO_URL"); exists {
mongoUrl = url
}
var err error
for {
mongoSession, err = mgo.Dial(mongoUrl)
if err == nil {
break
}
fmt.Printf("MongoDB not accessible, trying again in 5 seconds...")
time.Sleep(5 * time.Second)
}
mongoSession.SetMode(mgo.Monotonic, true)
indexes := []mgo.Index{
mgo.Index{
Key: []string{"base.repo.fullname"},
Background: true,
},
mgo.Index{
Key: []string{"mergedat"},
Background: true,
},
mgo.Index{
Key: []string{"comments"},
Background: true,
},
mgo.Index{
Key: []string{"number", "base.repo.fullname"},
Unique: true,
DropDups: true,
Background: true,
},
}
c := mongoSession.DB("github").C("pulls")
for _, index := range indexes {
c.EnsureIndex(index)
}
}
func GetProjectTimeline(nameQuery string, size int, importance int, skipToken string) ([]*github.PullRequest, error) {
c := mongoSession.DB("github").C("pulls")
format := "2006-01-02T15:04:05Z"
var skipTime time.Time
var err error
if skipToken != "" {
skipTime, err = time.Parse(format, skipToken)
if err != nil {
skipToken = ""
}
}
prs := []*github.PullRequest{}
var query bson.M
if skipToken != "" {
query = bson.M{
"comments": bson.M{"$gt": importance},
"mergedat": bson.M{"$lt": skipTime},
"base.repo.fullname": bson.M{"$regex": fmt.Sprintf(".*%s.*", nameQuery)},
}
} else {
query = bson.M{
"comments": bson.M{"$gt": importance},
"base.repo.fullname": bson.M{"$regex": fmt.Sprintf(".*%s.*", nameQuery)},
}
}
if err = c.Find(query).Sort("-mergedat").Limit(size).All(&prs); err != nil {
return nil, err
}
return prs, nil
}
func CleanUp() {
mongoSession.Close()
}
<file_sep>/api.go
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/franela/watch-docker/handlers"
"github.com/gorilla/mux"
"github.com/urfave/negroni"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/timeline", handlers.GetPulls).Methods("GET")
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./www")))
n := negroni.Classic()
n.UseHandler(r)
port, exists := os.LookupEnv("PORT")
if !exists {
port = "3000"
}
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), n))
}
<file_sep>/www/features/featuresFactory.js
appFactories
.factory('Features', function ($http) {
return {
getFeatures: function(searchParams) {
return $http.get("/timeline", {params: searchParams});
}
};
});
<file_sep>/handlers/pulls.go
package handlers
import (
"encoding/json"
"net/http"
"github.com/franela/watch-docker/timeline"
)
func GetPulls(rw http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("q")
skip := r.URL.Query().Get("skip")
prs, err := timeline.GetProjectTimeline(query, 21, 20, skip)
if err != nil {
return
}
rw.Header().Add("content-type", "application/json")
json.NewEncoder(rw).Encode(prs)
}
<file_sep>/history/history.go
package main
import (
"context"
"log"
"os"
mgo "gopkg.in/mgo.v2"
"golang.org/x/oauth2"
"github.com/google/go-github/github"
)
type Pull struct {
Id int64 `json:id`
}
func main() {
token := ""
mongo_url := "mongo"
if url, exists := os.LookupEnv("MONGO_URL"); exists {
mongo_url = url
}
session, err := mgo.Dial(mongo_url)
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("github").C("pulls")
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
opts := &github.PullRequestListOptions{State: "closed"}
for {
prs, resp, err := client.PullRequests.List(ctx, "moby", "moby", opts)
if err != nil {
log.Println(err)
continue
}
for _, pr := range prs {
if pr.MergedAt == nil {
continue
}
pr, _, err := client.PullRequests.Get(ctx, "moby", "moby", *pr.Number)
if err != nil {
log.Println(err)
continue
}
err = c.Insert(pr)
if err != nil {
log.Fatal(err)
}
log.Printf("Inserted PR [%d]\n", *pr.Number)
}
if resp.NextPage == 0 {
break
}
opts.ListOptions.Page = resp.NextPage
}
}
<file_sep>/handlers/subscribe.go
package handlers
import "net/http"
func Subscribe(rw http.ResponseWriter, r *http.Request) {
}
<file_sep>/Dockerfile
FROM golang:1.8
# Copy the code inside the container and set the workdir
COPY ./ /go/src/github.com/franela/watch-docker
WORKDIR /go/src/github.com/franela/watch-docker
# Build the binary
RUN go get ./...
CMD ["watch-docker"]
<file_sep>/www/app.js
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.features',
'ui.bootstrap',
'myApp.Factories',
'infinite-scroll'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({redirectTo: '/features'});
}]);
var appFactories = angular.module('myApp.Factories', []);
| 9d70552fcbd9ca51ca8f414163c49d581f83397d | [
"JavaScript",
"Go",
"Dockerfile"
] | 8 | Go | franela/watch-docker | 6e5f806a3743af8453cd717243ff71491401c757 | 6ae5d09dcd2886c66966d0c77bd1c277b33cf52f |
refs/heads/main | <file_sep>myNumber = 3
print(myNumber)
myNumber2 = 4.5
print(myNumber2)
myNumber ="hello world"
print(myNumber)
| d4573d349b69227f8a494f3dbddbf63bc7d8254e | [
"Python"
] | 1 | Python | LGHAR/hello | 7674430ca8cb33e825909934f47312d6d0d4633f | 7cf2f77cfa4b69307157e592d3b1d3e6aeb9f0da |
refs/heads/master | <repo_name>tommasoscocciolini/php-snacks-b1<file_sep>/snack1/index.php
<?php
$giornataX = [
[
'casa' => 'Cantù',
'punti_casa' => rand(50, 120),
'ospite' => 'Milano',
'punti_ospite' => rand(50, 120),
],
[
'casa' => 'Bari',
'punti_casa' => rand(50, 120),
'ospite' => 'Perugia',
'punti_ospite' => rand(50, 120),
],
[
'casa' => 'Siena',
'punti_casa' => rand(50, 120),
'ospite' => 'Pescara',
'punti_ospite' => rand(50, 120),
],
];
//var_dump($giornataX);
for ($i=0; $i < count($giornataX); $i++) { ?>
<div class="">
<?= $giornataX[$i]['casa'] ?> -
<?= $giornataX[$i]['ospite'] ?> |
<?= $giornataX[$i]['punti_casa'] ?> -
<?= $giornataX[$i]['punti_ospite'] ?>
</div>
<?php } ?>
<file_sep>/snack2/index.php
<?php
$name = $_GET['name'];
$mail = $_GET['mail'];
$age = $_GET['age'];
?>
<?php
$resEmail = filter_var($mail, FILTER_VALIDATE_EMAIL);
var_dump($name);
var_dump($mail);
var_dump($age);
?>
<?php if (strlen($name) > 3 && $resEmail && is_numeric($age)): ?>
<div class="">“Accesso riuscito”</div>
<?php else: ?>
<div class="">“Accesso negato”</div>
<?php endif; ?>
<file_sep>/snack4/index.php
<?php
$classe = [
'Pino Pineta' => [
[
'nome' => 'Pino',
'cognome' => 'Pineta',
'voti' => [ 5, 8, 4, 9, 6, 6, 7],
],
],
'<NAME>' => [
[
'nome' => 'Mario',
'cognome' => 'Rossi',
'voti' => [ 6, 7, 8, 9, 5, 3, 5, 8],
],
],
'<NAME>' => [
[
'nome' => 'Tommaso',
'cognome' => 'Scocciolini',
'voti' => [7, 7, 3, 5, 8, 4, 8],
],
],
];
?>
<?php //var_dump($classe)
echo ($classe['Pino Pineta'][0]['nome']) . '<br>';
echo ($classe['Pino Pineta'][0]['cognome']) . '<br>';
$mediaPino = 0;
for ($i=0; $i < count($classe['Pino Pineta'][0]['voti']); $i++) {
// code...
$mediaPino += $classe['Pino Pineta'][0]['voti'][$i];
}
$mediaPino = $mediaPino / count($classe['Pino Pineta'][0]['voti']);
echo "Media = " . round($mediaPino, 2) . '<br><br>';
?>
<?php //var_dump($classe)
echo ($classe['Mario Rossi'][0]['nome']) . '<br>';
echo ($classe['Mario Rossi'][0]['cognome']) . '<br>';
$mediaMario = 0;
for ($i=0; $i < count($classe['Mario Rossi'][0]['voti']); $i++) {
// code...
$mediaMario += $classe['Mario Rossi'][0]['voti'][$i];
}
$mediaMario = $mediaMario / count($classe['Mario Rossi'][0]['voti']);
echo "Media = " . round($mediaMario, 2) . '<br><br>';
?>
<?php //var_dump($classe)
echo ($classe['Tommaso Scocciolini'][0]['nome']) . '<br>';
echo ($classe['Tommaso Scocciolini'][0]['cognome']) . '<br>';
$mediaTom = 0;
for ($i=0; $i < count($classe['Tommaso Scocciolini'][0]['voti']); $i++) {
// code...
$mediaTom += $classe['Tommaso Scocciolini'][0]['voti'][$i];
}
$mediaTom = $mediaTom / count($classe['Tommaso Scocciolini'][0]['voti']);
echo "Media = " . round($mediaTom, 2) . '<br>';
?>
<file_sep>/snack3/index.php
<?php
$posts = [
'12/01/2021' => [
[
'title' => 'Post 1',
'author' => '<NAME>',
'text' => 'Testo post 1'
],
[
'title' => 'Post 2',
'author' => '<NAME>',
'text' => 'Testo post 2'
],
],
'10/05/2021' => [
[
'title' => 'Post 3',
'author' => '<NAME>',
'text' => 'Testo post 3'
]
],
'12/05/2021' => [
[
'title' => 'Post 4',
'author' => '<NAME>',
'text' => 'Testo post 4'
],
[
'title' => 'Post 5',
'author' => '<NAME>',
'text' => 'Testo post 5'
],
[
'title' => 'Post 6',
'author' => '<NAME>',
'text' => 'Testo post 6'
]
],
];
?>
<?= '12/01/2021' . '<br>'; ?>
<?php for($i=0; $i < count($posts['12/01/2021']); $i++) {
// code...
echo $posts['12/01/2021'][$i]['title'] . '<br>';
echo $posts['12/01/2021'][$i]['author'] . '<br>';
echo $posts['12/01/2021'][$i]['text'] . '<br>';
echo "<br>";
}
?>
<?= '10/05/2021' . '<br>'; ?>
<?php for($i=0; $i < count($posts['10/05/2021']); $i++) {
// code...
echo $posts['10/05/2021'][$i]['title'] . '<br>';
echo $posts['10/05/2021'][$i]['author'] . '<br>';
echo $posts['10/05/2021'][$i]['text'] . '<br>';
echo "<br>";
}
?>
<?= '12/05/2021' . '<br>'; ?>
<?php for($i=0; $i < count($posts['12/05/2021']); $i++) {
// code...
echo $posts['12/05/2021'][$i]['title'] . '<br>';
echo $posts['12/05/2021'][$i]['author'] . '<br>';
echo $posts['12/05/2021'][$i]['text'] . '<br>';
echo "<br>";
}
?>
| 02c0baa75daf05ff980bd9b8817fd308ae36c2b1 | [
"PHP"
] | 4 | PHP | tommasoscocciolini/php-snacks-b1 | 673c4ef88fd993b2db873a8558370517f74e367d | d52c9113e9ec0faaed1247a1a4f6160b703b5cc1 |
refs/heads/main | <file_sep>using UnityEngine;
using Zenject;
namespace Input
{
public class KeyInputInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind<IInputEvent>()
.To<KeyInput>()
.FromNewComponentOnNewGameObject()
.AsCached();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UniRx;
using Cysharp.Threading.Tasks;
using Pun2Task;
using System;
using Photon.Realtime;
using Photon.Pun;
namespace Sequence
{
/// <summary>
/// タイトルシーケンス
/// </summary>
public class TitleSequence : MonoBehaviour
{
/// <summary>
/// スタートボタン
/// </summary>
[SerializeField]
private Button startButton = null;
void Awake()
{
startButton.OnClickAsObservable()
.Subscribe(async _ =>
{
startButton.interactable = false;
var token = this.GetCancellationTokenOnDestroy();
try
{
await Pun2TaskNetwork.ConnectUsingSettingsAsync(token);
Debug.Log("Connect OK");
await Pun2TaskNetwork.JoinOrCreateRoomAsync("TestRoom", new RoomOptions()
{
CleanupCacheOnLeave = false
}, TypedLobby.Default, null, token);
Debug.Log("Room Join OK");
PhotonNetwork.LoadLevel("Game");
}
catch (Exception e)
{
startButton.interactable = true;
Debug.LogError(e.Message);
}
}).AddTo(gameObject);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Cysharp.Threading.Tasks;
using Pun2Task;
using Cysharp.Threading.Tasks.Linq;
namespace Player
{
/// <summary>
/// 切断されたプレイヤーのクリーンアップ監視
/// </summary>
[RequireComponent(typeof(PhotonView))]
public class PlayerCleanUp : MonoBehaviour
{
/// <summary>
/// 所有者
/// ※OnPlayerLeftRoomが走るタイミングではPhotonView.Ownerは既に書き換えられているため、
/// あらかじめキャッシュしておく
/// </summary>
private Photon.Realtime.Player owner = null;
void Start()
{
var photonView = GetComponent<PhotonView>();
owner = photonView.Owner;
Watch().Forget();
}
/// <summary>
/// 監視
/// </summary>
private async UniTaskVoid Watch()
{
await Pun2TaskCallback.OnPlayerLeftRoomAsyncEnumerable()
.ForEachAsync((player) =>
{
if (player == owner)
{
Destroy(gameObject);
}
}, this.GetCancellationTokenOnDestroy());
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;
using System;
namespace Input
{
/// <summary>
/// 入力イベントインタフェース
/// </summary>
public interface IInputEvent
{
/// <summary>
/// 移動
/// </summary>
IObservable<Vector2> OnMove { get; }
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
namespace Sequence
{
/// <summary>
/// ゲームシーケンス
/// </summary>
public class GameSequence : MonoBehaviour
{
/// <summary>
/// プレイヤーのPrefabのパス
/// </summary>
private static string PlayerPrefabPath = "Prefabs/Player";
/// <summary>
/// NPCのPrefabのパス
/// </summary>
private static string NPCPrefabPath = "Prefabs/NPC";
// ↓AwakeのタイミングだとZenAutoInjecterが上手く動作しない
//void Awake()
// ↓Startのタイミングで行う
void Start()
{
PhotonNetwork.Instantiate(PlayerPrefabPath, Vector3.zero, Quaternion.identity);
if (PhotonNetwork.IsMasterClient)
{
for (int i = 0; i < 3; i++)
{
Vector3 pos = new Vector3(Random.Range(-5.0f, 5.0f), 0.0f, Random.Range(-5.0f, 5.0f));
PhotonNetwork.Instantiate(NPCPrefabPath, pos, Quaternion.identity);
}
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
namespace NPC
{
/// <summary>
/// NPCの移動
/// </summary>
[RequireComponent(typeof(PhotonView))]
public class NPCMove : MonoBehaviour
{
/// <summary>
/// PhotonView
/// </summary>
private PhotonView photonView = null;
/// <summary>
/// 現在の座標
/// </summary>
private Vector3 currentPosition = Vector3.zero;
/// <summary>
/// 次の座標
/// </summary>
private Vector3 nextPosition = Vector3.zero;
/// <summary>
/// 移動時間
/// </summary>
private float moveTime = 1.0f;
void Awake()
{
photonView = GetComponent<PhotonView>();
currentPosition = transform.position;
nextPosition = currentPosition;
}
void Update()
{
if (!photonView.IsMine) { return; }
if (moveTime >= 1.0f)
{
currentPosition = transform.position;
nextPosition = currentPosition + new Vector3(Random.Range(-5.0f, 5.0f), 0.0f, Random.Range(-5.0f, 5.0f));
moveTime = 0.0f;
}
moveTime = Mathf.Min(moveTime + Time.deltaTime, 1.0f);
transform.position = Vector3.Lerp(currentPosition, nextPosition, moveTime);
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;
namespace Input
{
/// <summary>
/// キー入力
/// </summary>
public class KeyInput : MonoBehaviour, IInputEvent
{
/// <summary>
/// 移動プロパティ
/// </summary>
private ReactiveProperty<Vector2> onMoveProp = new ReactiveProperty<Vector2>(Vector2.zero);
/// <summary>
/// 移動した
/// </summary>
public IObservable<Vector2> OnMove => onMoveProp;
void Update()
{
Vector2 moveVec = Vector2.zero;
moveVec.x = UnityEngine.Input.GetAxisRaw("Horizontal");
moveVec.y = UnityEngine.Input.GetAxisRaw("Vertical");
onMoveProp.Value = moveVec;
}
}
}
<file_sep># PUN2NPCTest
PUN2でのNPCの挙動テスト
# LICENSE
- [UniRx](https://github.com/neuecc/UniRx)
- [UniTask](https://github.com/Cysharp/UniTask)
- [Pun2Task](https://github.com/TORISOUP/Pun2Task)
- [Zenject](https://github.com/modesttree/Zenject)
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Zenject;
using Input;
using UniRx;
namespace Player
{
/// <summary>
/// プレイヤー移動Component
/// </summary>
[RequireComponent(typeof(PhotonView))]
public class PlayerMove : MonoBehaviour
{
/// <summary>
/// 入力イベント
/// </summary>
private IInputEvent inputEvent = null;
/// <summary>
/// 移動ベクトル
/// </summary>
private Vector2 moveVec = Vector2.zero;
/// <summary>
/// RigidBody
/// </summary>
private Rigidbody rigidBody = null;
/// <summary>
/// PhotonView
/// </summary>
private PhotonView photonView = null;
void Awake()
{
rigidBody = GetComponent<Rigidbody>();
photonView = GetComponent<PhotonView>();
}
/// <summary>
/// InputEventの注入
/// </summary>
/// <param name="inputEvent">InputEventインタフェース</param>
[Inject]
public void InjectInputEvent(IInputEvent inputEvent)
{
inputEvent.OnMove
.Subscribe(vec =>
{
if (photonView.IsMine)
{
moveVec = vec;
}
}).AddTo(gameObject);
}
void FixedUpdate()
{
if (!photonView.IsMine) { return; }
rigidBody.velocity = new Vector3(moveVec.x, 0.0f, moveVec.y);
}
}
}
| dc58f50b11a261ccd1e9a99aacc0599378de3e51 | [
"Markdown",
"C#"
] | 9 | C# | YanaPIIDXer/PUN2NPCTest | 44a2b4cad4322772c66a91f8409475fa2c598abf | 7f8abaa5ba17074a0b7aff97fe9f886efe39a4fd |
refs/heads/master | <file_sep>from __future__ import unicode_literals
from django.apps import AppConfig
class FazbazConfig(AppConfig):
name = 'fazbaz'
<file_sep>from celery import shared_task
@shared_task
def say_hello(name):
print 'Hello, %s' % name<file_sep>amqp==2.1.4
appnope==0.1.0
backports.shutil-get-terminal-size==1.0.0
billiard==3.5.0.2
celery==4.0.2
decorator==4.0.10
Django==1.10.5
enum-compat==0.0.2
enum34==1.1.6
eventlet==0.20.1
greenlet==0.4.11
ipython==5.1.0
ipython-genutils==0.1.0
kombu==4.0.2
pathlib2==2.2.0
pexpect==4.2.1
pickleshare==0.7.4
prompt-toolkit==1.0.9
ptyprocess==0.5.1
Pygments==2.1.3
pytz==2016.10
redis==2.10.5
scandir==1.4
simplegeneric==0.8.1
six==1.10.0
traitlets==4.3.1
vine==1.1.3
wcwidth==0.1.7
| 6550f9f0d9d77ad7193eac4040f4368e05ae03c0 | [
"Python",
"Text"
] | 3 | Python | thongly/scaling-test-foobar | 8974eca466c3b4aba48956a630aba16b0732cbaa | 8957c4337706d9af332f1dfa536d20cb00f71d18 |
refs/heads/main | <repo_name>AlexCollin/goRangeDownloader<file_sep>/main.go
package main
import (
"flag"
"fmt"
"github.com/AlexCollin/goRangeDownloader/internal/downloader"
. "github.com/AlexCollin/goRangeDownloader/internal/errutil"
"github.com/AlexCollin/goRangeDownloader/internal/urlutil"
"log"
"time"
)
func main() {
var workerCount = flag.Int64("c", 5, "goroutines count")
var maxRepeats = flag.Int64("r", 1, "max repeats on net errors")
flag.Parse()
now := time.Now().UTC()
downloadUrl := "http://i.imgur.com/z4d4kWk.jpg"
log.Println("Url:", downloadUrl)
fileSize, err := urlutil.GetSizeAndCheckRangeSupport(downloadUrl)
log.Printf("Size: %d bytes\n", fileSize)
fName, err := urlutil.GetFileName(downloadUrl)
if err != nil {
log.Printf("Could not get file name. Using default")
fName = "default"
}
var filePath = fmt.Sprintf("./downloads/%s", fName)
if err == nil {
HandleError(downloader.AsyncDownload(filePath, downloadUrl, fileSize, workerCount, maxRepeats))
} else {
log.Fatalf("File is not support range header")
}
log.Println("Elapsed time:", time.Since(now))
log.Println("Finish!")
}
<file_sep>/internal/downloader/worker.go
package downloader
import (
"errors"
"fmt"
. "github.com/AlexCollin/goRangeDownloader/internal/errutil"
"io"
"log"
"net/http"
"os"
"strconv"
"sync"
"sync/atomic"
"time"
)
type worker struct {
Url string
File *os.File
Count int64
SyncWG sync.WaitGroup
TotalSize int64
writeCount *uint32
writeBytes *uint64
}
func (w *worker) writeSlice(sliceNum int64, start int64, end int64, repeat int64, maxRepeats int64) {
var written int64
body, size, err := w.getSliceData(start, end)
if err != nil {
log.Printf("Slice %d request error: %s\n", sliceNum, err.Error())
if maxRepeats > repeat {
repeat += 1
time.AfterFunc(5*time.Second, func() {
w.writeSlice(sliceNum, start, end, repeat, maxRepeats)
})
return
} else {
log.Fatalf("Error: %v\n", OneOrManyChunksDontLoaded)
}
}
defer body.Close()
defer w.SyncWG.Done()
// Write with 4096 bytes block size
bs := int64(4096)
log.Printf("Goroutine №%d: Set write block size %v ", sliceNum, bs)
buf := make([]byte, bs)
for {
nr, er := body.Read(buf)
if nr > 0 {
nw, err := w.File.WriteAt(buf[0:nr], start)
if err != nil {
log.Fatalf("Slice %d occured error: %s.\n", sliceNum, err.Error())
}
if nr != nw {
log.Fatalf("Slice %d occured error of short writing.\n", sliceNum)
}
start = int64(nw) + start
if nw > 0 {
written += int64(nw)
}
atomic.AddUint32(w.writeCount, 1)
atomic.AddUint64(w.writeBytes, uint64(nw))
log.Printf("Goroutine №%d: writing %v-%v bytes of file", sliceNum, start-bs, start)
}
if er != nil {
if er.Error() == "EOF" {
if size == written {
} else {
HandleError(errors.New(fmt.Sprintf("Slice write %d unfinished.\n", sliceNum)))
}
break
}
HandleError(errors.New(fmt.Sprintf("Slice %d occured error: %s\n", sliceNum, er.Error())))
}
}
}
func (w *worker) getSliceData(start int64, end int64) (io.ReadCloser, int64, error) {
var client http.Client
req, err := http.NewRequest("GET", w.Url, nil)
if err != nil {
return nil, 0, err
}
req.Header.Add("Range", fmt.Sprintf("bytes=%d-%d", start, end))
resp, err := client.Do(req)
if err != nil {
return nil, 0, err
}
size, err := strconv.ParseInt(resp.Header["Content-Length"][0], 10, 64)
return resp.Body, size, err
}
<file_sep>/internal/errutil/error.go
package errutil
import (
"errors"
"log"
"os"
)
var FileSizeIsNotEqualWrittenBytesError = errors.New("File size is not equal written bytes ")
var OneOrManyChunksDontLoaded = errors.New("One or many chunks dont loaded ")
func HandleError(err error) {
if err != nil {
log.Println("Error:", err)
os.Exit(1)
}
}
<file_sep>/go.mod
module github.com/AlexCollin/goRangeDownloader
go 1.14
<file_sep>/internal/urlutil/urlutil.go
package urlutil
import (
"errors"
"log"
"net/http"
"net/url"
"path/filepath"
"strconv"
)
func GetSizeAndCheckRangeSupport(url string) (size int64, err error) {
client := &http.Client{}
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
return
}
res, err := client.Do(req)
if err != nil {
return
}
header := res.Header
log.Printf("%v+", header)
acceptRanges, supported := header["Accept-Ranges"]
log.Printf("Response header range: %v\n", supported)
if !supported {
err = errors.New("Doesn't support header 'Accept-Ranges'. ")
} else if supported && acceptRanges[0] != "bytes" {
err = errors.New("Exists header 'Accept-Ranges', but value is not 'bytes'. ")
}
if _, ok := header["Content-Length"]; !ok {
err = errors.New("Header 'Content-Length' is empty. ")
} else {
size, err = strconv.ParseInt(header["Content-Length"][0], 10, 64)
}
return
}
func GetFileName(downloadUrl string) (string, error) {
urlStruct, err := url.Parse(downloadUrl)
if err != nil {
return "", err
}
return filepath.Base(urlStruct.Path), nil
}
<file_sep>/internal/downloader/async.go
package downloader
import (
"github.com/AlexCollin/goRangeDownloader/internal/cmd"
"github.com/AlexCollin/goRangeDownloader/internal/errutil"
"log"
"os"
"sync/atomic"
)
func AsyncDownload(filepath string, url string, size int64, worksCount *int64, maxRepeats *int64) (err error) {
log.Printf("Save to: %s\n", filepath)
f, err := os.OpenFile(filepath, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return
}
defer f.Close()
wc, wb := uint32(0), uint64(0)
var worker = worker{
Url: url,
File: f,
Count: *worksCount,
TotalSize: size,
writeCount: &wc,
writeBytes: &wb,
}
var start, end int64
var partialSize = size / *worksCount
log.Println("Part size on goroutine:", partialSize)
for num := int64(0); num < worker.Count; num++ {
start = num * partialSize
end += partialSize
if end >= size {
end = size
} else if start > 0 {
start += 1
}
// If surplus exists and division by worksCount != 0
if num == (worker.Count - 1) {
end += size % *worksCount
}
log.Printf("Goroutine №%d: Start download from '%d' to '%d' bytes of file", num, start, end)
worker.SyncWG.Add(1)
go worker.writeSlice(num, start, end, 0, *maxRepeats)
start = end
}
worker.SyncWG.Wait()
writesCount := atomic.LoadUint32(worker.writeCount)
log.Println("Writes count:", writesCount)
writesByte := atomic.LoadUint64(worker.writeBytes)
log.Println("Check write total bytes:", writesByte)
if uint64(size) != writesByte {
log.Printf("Error: %v", errutil.FileSizeIsNotEqualWrittenBytesError.Error())
if cmd.DownloadAgainQuestion() {
return AsyncDownload(filepath, url, size, worksCount, maxRepeats)
}
}
return
}
<file_sep>/internal/cmd/cmd.go
package cmd
import (
"fmt"
)
func DownloadAgainQuestion() bool {
var answer string
fmt.Print("Try download file again?[yn] ")
_, _ = fmt.Scan(&answer)
if answer == "y" {
return true
}
return false
}
<file_sep>/README.md
# goRangeDownloader
## Use
```shell
go run main.go [-c=15] [-r=1]
```
## Params
-c # Goroutines count
-r # Max repeats on net errors | 1d0891a864646e25894a5cdcbda2ede5115b59b6 | [
"Markdown",
"Go Module",
"Go"
] | 8 | Go | AlexCollin/goRangeDownloader | 8271db36ab6a7156c3c12849ee994c5481444211 | 03b60059b625baeb3f57e3963ee6b16000cebeab |
refs/heads/master | <file_sep>'use strict'
const express = require('express')
const SocketServer = require('ws').Server
const path = require('path')
const R = require('ramda')
var users = {}
const PORT = process.env.PORT || 8080
const INDEX = path.join(__dirname, 'index.html')
const server = express()
.use((req, res) => res.sendFile(INDEX) )
.listen(PORT, () => console.log(`Listening on ${ PORT }`))
const wss = new SocketServer({ server })
wss.on('connection', function(connection) {
connection.on('message', function(message) {
let data
// accepting only JSON messages
try {
data = JSON.parse(message)
} catch (e) {
// invalid JSON
data = {}
}
switch (data.type) {
case 'login': {
users = R.assocPath([data.wisId, data.name], connection, users)
// users[data.wisId][data.name] = connection
connection.name = data.name
sendTo(connection, {
type: 'login',
success: true
})
// send current users to user
sendTo(connection, {
type: 'newUser',
name: Object.keys(users[data.wisId]).filter(function (name) {
if (name === data.name) return false
return true
})
})
// send data name to others
Object.keys(users[data.wisId]).forEach(function (name) {
if (name !== data.name && R.path([data.wisId, name], users)) {
sendTo(users[data.wisId][name], {
type: 'newUser',
name: [data.name]
})
}
})
break
}
case 'offer': {
const conn = R.path([data.wisId, data.name])(users)
// users[data.wisId][data.name]
if(conn != null) {
connection.otherName = data.name
sendTo(conn, {
type: 'offer',
offer: data.offer,
name: connection.name
})
}
break
}
case 'answer': {
const conn = R.path([data.wisId, data.name])(users)
// users[data.wisId][data.name]
if(conn != null) {
connection.otherName = data.name
sendTo(conn, {
type: 'answer',
answer: data.answer
})
}
break
}
case 'candidate': {
const conn = R.path([data.wisId, data.name])(users)
// users[data.wisId][data.name]
if(conn != null) {
sendTo(conn, {
type: 'candidate',
candidate: data.candidate
})
}
break
}
case 'leave': {
const conn = R.path([data.wisId, data.name])(users)
// users[data.wisId][data.name]
conn.otherName = null
if(conn != null) {
sendTo(conn, {
type: 'leave'
})
}
break
}
default:
sendTo(connection, {
type: 'error',
message: 'Command not found: ' + data.type
})
break
}
})
// in case of closing browser tab
connection.on('close', function() {
if(connection.name) {
delete users[connection.name]
if(connection.otherName) {
const conn = users[connection.otherName]
if (conn) {
conn.otherName = null
}
if(conn != null) {
sendTo(conn, {
type: 'leave'
})
}
}
}
})
})
function sendTo(connection, message) {
connection.send(JSON.stringify(message))
}
// 'use strict'
//
// const express = require('express')
// const SocketServer = require('ws').Server
// const path = require('path')
//
// const users = {}
//
// const PORT = process.env.PORT || 8080
// const INDEX = path.join(__dirname, 'index.html')
//
// const server = express()
// .use((req, res) => res.sendFile(INDEX) )
// .listen(PORT, () => console.log(`Listening on ${ PORT }`))
//
// const wss = new SocketServer({ server })
//
//
// wss.on('connection', function(connection) {
//
// connection.on('message', function(message) {
//
// let data
//
// // accepting only JSON messages
// try {
// data = JSON.parse(message)
// } catch (e) {
// // invalid JSON
// data = {}
// }
//
// switch (data.type) {
// case 'login': {
// users[data.name] = connection
// connection.name = data.name
//
// sendTo(connection, {
// type: 'login',
// success: true
// })
//
// sendTo(connection, {
// type: 'newUser',
// name: Object.keys(users).filter(function (name) {
// if (name === data.name) return false
// return true
// })
// })
//
// // send data name to others
// Object.keys(users).forEach(function (name) {
// if (name !== data.name) {
// sendTo(users[name], {
// type: 'newUser',
// name: [data.name]
// })
// }
// })
//
// break
// }
//
// case 'offer': {
// const conn = users[data.name]
//
// if(conn != null) {
// connection.otherName = data.name
//
// sendTo(conn, {
// type: 'offer',
// offer: data.offer,
// name: connection.name
// })
// }
//
// break
// }
//
// case 'answer': {
// const conn = users[data.name]
//
// if(conn != null) {
// connection.otherName = data.name
// sendTo(conn, {
// type: 'answer',
// answer: data.answer
// })
// }
//
// break
// }
//
// case 'candidate': {
// const conn = users[data.name]
//
// if(conn != null) {
// sendTo(conn, {
// type: 'candidate',
// candidate: data.candidate
// })
// }
//
// break
// }
//
// case 'leave': {
// const conn = users[data.name]
// conn.otherName = null
//
// if(conn != null) {
// sendTo(conn, {
// type: 'leave'
// })
// }
//
// break
// }
//
// default:
// sendTo(connection, {
// type: 'error',
// message: 'Command not found: ' + data.type
// })
//
// break
// }
// })
//
// // in case of closing browser tab
// connection.on('close', function() {
//
// if(connection.name) {
// delete users[connection.name]
//
// if(connection.otherName) {
//
// const conn = users[connection.otherName]
// conn.otherName = null
//
// if(conn != null) {
// sendTo(conn, {
// type: 'leave'
// })
// }
// }
// }
// })
//
// })
//
// function sendTo(connection, message) {
// connection.send(JSON.stringify(message))
// }
| dc86990c9efca4dc5608b34b5000ae9150973cd6 | [
"JavaScript"
] | 1 | JavaScript | amiraliweblite/voicelite | 8243a88fc92f52f7dca24694044d47ae81bf9a7e | 2a1e8e6f048c2c0fd99aace99749d8eac1cf1e76 |
refs/heads/master | <repo_name>HaDaanCraft/mylovelifefamily<file_sep>/viewLists.php
<?php
include('private/DB.php');
if(isset($_POST['listItem'])) {
$listItem = $_POST['listItem'];
DB::query('INSERT INTO list'.$_GET['id'].' VALUES (0, :value, 0)', array(':value'=>$listItem));
}
$items = DB::query('SELECT * FROM list'.$_GET['id'].' ORDER BY value ASC');
if(isset($_POST['checkitem_x'])) {
$checked = DB::query('SELECT checked FROM list'.$_GET['id'].' WHERE id=:itemid', array(':itemid'=>$_GET['itemId']))[0]['checked'];
if($checked) {
DB::query('UPDATE list'.$_GET['id'].' SET checked=0 WHERE id=:itemId', array(':itemId'=>$_GET['itemId']));
header("Refresh:0");
} else {
DB::query('UPDATE list'.$_GET['id'].' SET checked=1 WHERE id=:itemId', array(':itemId'=>$_GET['itemId']));
header("Refresh:0");
}
}
if(isset($_POST['deleteitem_x'])) {
DB::query('DELETE FROM list'.$_GET['id'].' WHERE id=:itemId', array(':itemId'=>$_GET['itemId']));
header("Refresh:0");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyLoveLifeFamily</title>
<link rel="icon" href="./assets/pictures/family.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="navResponsive" id="navResponsive">
</div>
<div class="nav" id="nav">
</div>
<div class="list">
<div class="listWrapper">
<a href="lists.php"><img src="./assets/pictures/back.png" alt="Terug"></a><h3><?php echo DB::query('SELECT name FROM lists WHERE id=:id', array(':id'=>$_GET['id']))[0]['name'] ?></h3>
<div class="listDiv">
<div class="listAdd">
<form method="post" action="viewLists.php?id=<?php echo $_GET['id'] ?>">
<input type="text" name="listItem" value="" placeholder="Voeg iets toe aan de lijst" id="listItem">
<input type="image" name="createlist" src="./assets/pictures/add.png" alt="Maak lijst" height="50px">
</form>
</div>
<div class="listView">
<?php
foreach ($items as $item) {
if($item['checked']) {
echo '<p class="checked">'.$item['value'].'</p>';
} else {
echo '<p>'.$item['value'].'</p>';
}
echo '<form method=post action=?id='.$_GET['id'].'&itemId='.$item['id'].'>';
echo '<input type="image" name="checkitem" src="./assets/pictures/check.png" alt="Vink aan" height="30px" id="checkItem">';
echo '<input type="image" name="deleteitem" src="./assets/pictures/delete.png" alt="Verwijder" height="30px" id="deleteItem">';
echo '</form>';
}
?>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep>/classes/translate.php
<?php
class Translate {
public static function translateDate($date) {
$date = explode(" ", $date);
foreach ($date as $word) {
if ($word == "Monday") {
$n = array_search($word, $date);
$date[$n] = "Maandag";
} else if ($word == "Tuesday") {
$n = array_search($word, $date);
$date[$n] = "Dinsdag";
} else if ($word == "Wednesday") {
$n = array_search($word, $date);
$date[$n] = "Woensdag";
} else if ($word == "Thursday") {
$n = array_search($word, $date);
$date[$n] = "Donderdag";
} else if ($word == "Friday") {
$n = array_search($word, $date);
$date[$n] = "Vrijdag";
} else if ($word == "Saturday") {
$n = array_search($word, $date);
$date[$n] = "Zaterdag";
} else if ($word == "Sunday") {
$n = array_search($word, $date);
$date[$n] = "Zondag";
}
}
$newdate = implode(" ", $date);
return $newdate;
}
}<file_sep>/recipes.php
<?php
include('private/DB.php');
$recipes = DB::query('SELECT * FROM recipes');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyLoveLifeFamily</title>
<link rel="icon" href="./assets/pictures/family.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="navResponsive" id="navResponsive">
</div>
<div class="nav" id="nav">
</div>
<div class="recipes">
<div class="recipesWrapper">
<h3>Gerechten</h3>
<?php if($_COOKIE['loggedInUserType'] == 0 || $_COOKIE['loggedInUserType'] == 2){echo '<h4><a href="addrecipe.php">Voeg gerecht toe!</a></h4>';}?>
<div class="recipesDiv">
<?php
foreach ($recipes as $recipe) {
echo "<div class='recipe'>";
echo "<a href='viewrecipe.php?id=".$recipe['id']."'>";
echo "<center><img src='".$recipe['photo']."'/></center>";
echo "<hr />";
echo "<p class='name'>".$recipe['name']."</p>";
echo "</a>";
echo "</div>";
}
?>
</div>
</div>
</div>
</body>
</html>
<file_sep>/test/calendar.php
<!DOCTYPE html>
<html>
<head>
<?php include("./files/head.php"); ?>
</head>
<body>
<?php include("./files/navigation.php"); ?>
<div class="text">
<p>Wat staat er op het programma? ;)</p>
</div>
<iframe class="calendar" src="https://calendar.google.com/calendar/embed?title=MyLoveLifeFamily&height=600&wkst=2&bgcolor=%23FFFFFF&src=te22oshrg5qsnlj5jrfc3rf24g%40group.calendar.google.com&color=%23711616&ctz=Europe%2FBrussels"></iframe>
<footer>© All rights reserved</footer>
</body>
</html>
<file_sep>/viewrecipe.php
<?php
include('private/DB.php');
$recipe = DB::query('SELECT * FROM recipes WHERE id=:id', array('id'=>$_GET['id']))[0];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyLoveLifeFamily</title>
<link rel="icon" href="./assets/pictures/family.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="navResponsive" id="navResponsive">
</div>
<div class="nav" id="nav">
</div>
<div class="recipes">
<div class="recipesWrapper">
<a href="recipes.php"><img src="./assets/pictures/back.png" alt="Terug" id="back"></a>
<h3 id="viewName"><?php echo $recipe['name'];?></h3>
<div class="recipeDiv">
<div class="photo">
<img src="<?php echo $recipe['photo']; ?>" />
</div>
<div class="ingredients">
<p class="hltext"><underline>Ingediënten</underline></p>
<?php echo $recipe['ingredients']; ?>
</div>
<div class="preparation">
<p class="hltext"><underline>Recept</underline></p>
<?php echo $recipe['recipe']; ?>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep>/menuvdweekadd.php
<?php
include('private/DB.php');
include('classes/translate.php');
$currentdates = array();
$currentdatesdb = DB::query('SELECT date FROM menu');
$dates = array();
$time = time();
$format = "l d/m/Y";
foreach ($currentdatesdb as $currentdate) {
$newcurrentdate = date($format, $currentdate['date']);
array_push($currentdates, $newcurrentdate);
}
for ($i = 0; $i <= 31; $i++) {
$newtime = $time + 60 * 60 * 24 * $i;
$newtimeformat = date($format, $newtime);
if (!in_array($newtimeformat, $currentdates)) {
array_push($dates, $newtime);
}
}
if (isset($_POST['submit'])) {
if ($_POST['name']) {
$name = $_POST['name'];
$date = $_POST['date'];
DB::query('INSERT INTO menu VALUES (0, :date, :name)', array(':date' => $date, ':name' => $name));
} else {
echo ('Geen naam ingegeven');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyLoveLifeFamily</title>
<link rel="icon" href="./assets/pictures/family.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="navResponsive" id="navResponsive">
</div>
<div class="nav" id="nav">
</div>
<div class="menuw">
<div class="menuwWrapper">
<a href="menuvdweek.php"><img src="./assets/pictures/back.png" alt="Terug" id="back"></a>
<div class="form">
<form enctype="multipart/form-data" action="menuvdweekadd.php" method="POST">
<h5>Datum</h5>
<?php
echo '<select name="date">';
foreach ($dates as $date) {
echo '<option value="' . $date . '">' . Translate::translateDate(date($format, $date)) . '</option>';
}
echo '</select>';
?>
<h5>Gerecht</h5>
<input type="text" name="name" placeholder="<NAME>" class="input" id="name">
<p />
<input type="submit" id="submit" name="submit" value="Voeg toe!">
</div>
</div>
</div>
</body>
</html><file_sep>/testing.php
<?php
if(isset($_POST['testclick_x'])) {
$id = $_GET['deleteListId'];
echo $id;
echo 'Hello World';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyLoveLifeFamily Test Page</title>
<link rel="icon" href="./assets/pictures/family.ico">
</head>
<body>
<form method="post" action="testing.php?deleteListId=10">
<a href="?id=10">Test</a>
<input type="image" name="testclick" src="./assets/pictures/delete.png" alt="Verwijder lijst" height="30px">
</body>
</html>
<file_sep>/uploadfoto.php
<?php
include('classes/imageRotate/imageRotate.php');
$imageRotate = new imageRotate;
function reArrayFiles($file_post)
{
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i = 0; $i < $file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
if (isset($_GET['lastpage'])) {
if (isset($_GET['album'])) {
$album = rawurldecode($_GET['album']);
} else {
$album = "";
}
$lastpagecr = $_GET['lastpage'];
$lastpagedecr = str_replace("µ", "#", $lastpagecr);
if (isset($_GET['newFolder'])) {
$newfolder = $_GET['newFolder'];
} else {
$newfolder = "";
}
if (isset($_POST['uploadfoto'])) {
$photoarray = reArrayFiles($_FILES['photos']);
foreach ($photoarray as $photo) {
$filetype = $photo['type'];
$filetype = substr($filetype, 6);
$name = $photo['name'];
$targetdir = 'nano_photos_provider2/nano_photos_content/' . $album . '/';
$targetfile = $targetdir . $name . "." . $filetype;
move_uploaded_file($photo['tmp_name'], $targetfile);
$imageRotate->fixOrientation($targetfile);
}
echo "<script>
window.location.href = '".$lastpagedecr."';
</script>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyLoveLifeFamily</title>
<link rel="icon" href="./assets/pictures/family.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="navResponsive" id="navResponsive">
</div>
<div class="nav" id="nav">
</div>
<div class="photos">
<div class="photosWrapper">
<h3>Upload Foto's</h3>
<a href="<?php echo $lastpagedecr; ?>"><img src="./assets/pictures/back.png" alt="Terug" id="back"></a>
<div class="form">
<form enctype="multipart/form-data" action="<?php echo "uploadfoto.php?album=" . $album . "&lastpage=" . $lastpagecr . "&newFolder=" . $newfolder; ?>" method="POST">
<h5>Selecteer foto's:</h5>
<input type="file" name="photos[]" class="input" multiple>
<h5>Album:</h5>
<input type="text" name="name" value="<?php echo $album; ?>" class="input" id="name" disabled>
<input type="submit" value="Upload" name="uploadfoto" id="submit">
</form>
</div>
</div>
</div>
</body>
</html><file_sep>/photoalbum.php
<!-- <?php
require('classes/imageRotate/imageRotate.php');
$rotate = new imageRotate();
$rotate->fixOrientation("File");
?> -->
<?php
if (isset($_GET['nameNewFolder'])) {
$newfolder = rawurldecode($_GET['nameNewFolder']);
$location = rawurldecode($_GET['album']);
$lastpage = $_GET['lastPage'];
$album = $location . "/" . $newfolder;
if (!file_exists('nano_photos_provider2/nano_photos_content/' . $album)) {
mkdir('nano_photos_provider2/nano_photos_content/' . $album, 0777, true);
}
echo "<script>
window.location.href = 'uploadfoto.php?album=" . $album . "&lastpage=".$lastpage."&newFolder=".$newfolder."';
</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyLoveLifeFamily</title>
<link rel="icon" href="./assets/pictures/family.ico">
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1">
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.md5.js" type="text/javascript"></script>
<script src="js/main.js"></script>
<link href="https://unpkg.com/nanogallery2@2.4.2/dist/css/nanogallery2.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="https://unpkg.com/nanogallery2@2.4.2/dist/jquery.nanogallery2.min.js"></script>
</head>
<body>
<div class="navResponsive" id="navResponsive">
</div>
<div class="nav" id="nav">
</div>
<div class="menu">
<div class="menuWrapper">
<h3 id="albumMenuNewAlbum">Nieuw Album</h3>
<h3 id="albumMenuUploadFoto">Upload Foto's</h3>
</div>
</div>
<div id="my_nanogallery" data-nanogallery2='{
"kind": "nano_photos_provider2",
"dataProvider": "/mylovelifefamily/nano_photos_provider2/nano_photos_provider2.php",
"thumbnailWidth": "200",
"thumbnailAlignment": "center"
}'>
</div>
</body>
</html><file_sep>/lists.php
<?php
include('private/DB.php');
if(isset($_POST['namelist'])) {
$namelist = $_POST['namelist'];
DB::query('INSERT INTO lists VALUES (0, :name)', array(':name'=>$namelist));
$listid = DB::query('SELECT id FROM lists WHERE name=:name', array(':name'=>$namelist))[0]['id'];
DB::query('CREATE TABLE mylovelifefamily.list'.$listid.' ( id INT(64) NOT NULL AUTO_INCREMENT , value VARCHAR(100) NOT NULL , checked BOOLEAN NOT NULL , PRIMARY KEY (id))');
}
$lists = DB::query('SELECT * FROM lists ORDER BY name ASC');
if(isset($_POST['deletelist_x'])) {
$listid = $_GET['deleteListId'];
DB::query('DELETE FROM lists WHERE id=:id', array(':id'=>$listid));
DB::query('DROP TABLE list'.$listid);
header("Refresh:0");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyLoveLifeFamily</title>
<link rel="icon" href="./assets/pictures/family.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="navResponsive" id="navResponsive">
</div>
<div class="nav" id="nav">
</div>
<div class="list">
<div class="listWrapper">
<h3>Lijstjes</h3>
<div class="listDiv">
<div class="listAdd">
<form method="post" action="lists.php">
<input type="text" name="namelist" value="" placeholder="Maak een lijst" id="namelist">
<input type="image" name="createlist" src="./assets/pictures/add.png" alt="Maak lijst" height="50px" id="add">
</form>
</div>
<div class="listView">
<?php
foreach ($lists as $list) {
echo '<a href=viewLists.php?id='.$list['id'].'>'.$list['name'].'</a>';
echo '<form method="post" action="lists.php?deleteListId='.$list['id'].'">';
echo '<input type="image" name="deletelist" src="./assets/pictures/delete.png" alt="Verwijder lijst" height="30px" id="deleteList">';
echo '</form>';
}
?>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep>/test/index.php
<!DOCTYPE html>
<html>
<head>
<?php include("./files/head.php"); ?>
</head>
<body>
<?php include("./files/navigation.php"); ?>
<div class="timeline">
<img src="./assets/pictures/family_pic.jpg">
<p>Zeeland - 2018</p>
<p><NAME> in de familie - 11/01/2018</p>
<img src="./assets/pictures/tuur.jpg">
<img src="./assets/pictures/verjaardag-marie-2017.jpg">
<p><NAME> - 2017</p>
<p><NAME> - 2016</p>
<img src="./assets/pictures/verjaardag-eline-2016.jpg">
</div>
<footer>© All rights reserved</footer>
</body>
</html>
<file_sep>/addrecipe.php
<?php
include('private/DB.php');
if (isset($_POST['addrecipe'])) {
$name = $_POST['name'];
$ingredients = $_POST['ingredients'];
$ingredients = nl2br($ingredients);
$recipe = $_POST['recipe'];
$recipe = nl2br($recipe);
$photo = $_FILES['photo'];
$filetype = $photo['type'];
$filetype = substr($filetype, 6);
$targetdir = 'assets/pictures/recipes/';
$targetfile = $targetdir.$name.".".$filetype;
if ($name != "") {
if ($ingredients != "") {
if ($recipe != "") {
if (move_uploaded_file($photo['tmp_name'], $targetfile)) {
DB::query('INSERT INTO recipes VALUES (0, :name, :ingredients, :recipe, :photo)', array(':name'=>$name, ':ingredients'=>$ingredients, ':recipe'=>$recipe, ':photo'=>$targetfile));
} else {
echo 'Foto is niet geüpload!';
}
} else {
echo "Het gerecht is ongeldig!";
}
} else {
echo "Ingrediënten zijn ongeldig!";
}
} else {
echo "Naam is ongeldig!";
}
}
if (isset($_GET['nm'])) {
$nm = $_GET['nm'];
$ingr = $_GET['ingr'];
$rec = $_GET['rec'];
$phot = $_GET['phot'];
} else {
$nm = '';
$ingr = '';
$rec = '';
$phot = '';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyLoveLifeFamily</title>
<link rel="icon" href="./assets/pictures/family.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="navResponsive" id="navResponsive">
</div>
<div class="nav" id="nav">
</div>
<div class="recipes">
<div class="recipesWrapper">
<a href="recipes.php"><img src="./assets/pictures/back.png" alt="Terug" id="back"></a>
<div class="form">
<form enctype="multipart/form-data" action="addrecipe.php" method="POST">
<h5>Naam Gerecht:</h5>
<input type="text" name="name" placeholder="Naam gerecht" class="input" id="name">
<h5>Ingrediënten:</h5>
<textarea name="ingredients" placeholder="Ingrediënten" rows="30" cols="70" class="input" style="z-index: 0;"></textarea>
<h5>Recept</h5>
<textarea name="recipe" placeholder="Recept" rows="30" cols="80" class="input" style="z-index: 0;"></textarea>
<h5>Foto</h5>
<input type="file" name="photo" class="input">
<input type="submit" value="Voeg toe" name="addrecipe" id="submit">
</form>
</div>
</div>
</div>
</body>
</html>
<file_sep>/login.php
<?php
include('private/DB.php');
if (isset($_POST['login'])) {
$pin = $_POST['pin'];
if (DB::query('SELECT * FROM users WHERE pin=:pin', array(':pin'=>$pin))) {
$userType = DB::query('SELECT userType FROM users WHERE pin=:pin', array(':pin'=>$pin))[0]['userType'];
echo '<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>';
echo '<script type="text/javascript">',
'Cookies.set("loggedInUserType", "'.$userType.'", { expires: 1 });',
'</script>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyLoveLifeFamily</title>
<link rel="icon" href="./assets/pictures/family.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="js/main.js"></script>
</head>
<body class="loginFile">
<div class="nav">
<div class="navWrapper">
<img src="./assets/pictures/family.ico" alt="Family Icon">
</div>
</div>
<div class="login">
<div class="loginWrapper">
<h3>Login</h3>
<form action="login.php" method="post">
<input type="number" name="pin" placeholder="Pin..." id="pin"> <p />
<input type="submit" name="login" value="Login" id="button">
</form>
</div>
</div>
<!-- 8973 -->
</html>
<file_sep>/js/main.js
$(document).ready(() => {
// Logged In Checking
var loggedCookie = Cookies.get('loggedInUserType');
if (loggedCookie == null && $(location).attr('pathname') != '/mylovelifefamily/login.php') {
localStorage.link = $(location).attr('pathname');
$(location).attr('href', 'login.php');
} else if (loggedCookie != null && $(location).attr('pathname') == '/mylovelifefamily/login.php') {
$(location).attr('href', localStorage.link);
}
// Navigation Bar
$('#header').load('files/header.php');
$('#nav').load('files/nav.php');
$('#navResponsive').load('files/navresponsive.php');
setTimeout(function () {
// Animations
$("h1").addClass("animated fadeIn");
// Smooth Scrolling
// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
// Responsive Nav
$(".open").click(function(){
$(this).css("display", "none");
$(".navResponsive").css("width", "100%");
$("#my_nanogallery").attr("id", "photo");
});
$(".close").click(function(){
$(".navResponsive").css("width", "0");
$(".open").css("display", "block");
$("#photo").attr("id", "my_nanogallery");
});
// Sticky Nav Bar
var num = 0; //number of pixels before modifying styles
$(window).bind('scroll', function () {
if ($(window).scrollTop() > num) {
$('.nav').addClass('sticky');
$('.headerWrapper h1').addClass('heads');
$('.list').addClass('pageMargin');
$('.calendar').addClass('pageMargin');
$('.recipes').addClass('pageMargin');
$('.menuw').addClass('pageMargin');
} else {
$('.nav').removeClass('sticky');
$('.headerWrapper h1').removeClass('heads');
$('.list').removeClass('pageMargin');
$('.calendar').removeClass('pageMargin');
$('.recipes').removeClass('pageMargin');
$('.menuw').removeClass('pageMargin');
}
});
// Photo Album
$("#albumMenuNewAlbum").click(function() {
var name = prompt("Naam voor het nieuwe album?");
var url = window.location.href;
var sendurl = url.replace("#", "µ")
var regExp = new RegExp("(?<=my_nanogallery\/).*($)");
if (regExp.test(url)) {
album = regExp.exec(url)[0];
} else {
album = "";
}
$(location).attr('href', "photoalbum.php?nameNewFolder="+name+"&album="+album+"&lastPage="+sendurl);
});
$("#albumMenuUploadFoto").click(function () {
var url = window.location.href;
var sendurl = url.replace("#", "µ")
var regExp = new RegExp("(?<=my_nanogallery\/).*($)");
if (regExp.test(url)) {
album = regExp.exec(url)[0];
} else {
album = "";
}
$(location).attr('href', "uploadfoto.php?album="+album+"&lastpage="+sendurl);
});
// End File
}, 1000);
});
<file_sep>/menuvdweek.php
<?php
include('private/DB.php');
include('classes/translate.php');
$recipes = DB::query('SELECT menu.date, menu.name FROM menu ORDER BY menu.date ASC');
$format = "l d/m/Y";
if (isset($_POST['delete'])) {
$date = $_GET['gerechtdate'];
DB::query('DELETE FROM menu WHERE date=:date', array(':date'=>$date));
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyLoveLifeFamily</title>
<link rel="icon" href="./assets/pictures/family.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="navResponsive" id="navResponsive">
</div>
<div class="nav" id="nav">
</div>
<div class="menuw">
<div class="menuwWrapper">
<h3>Menu Van De Week</h3>
<?php if ($_COOKIE['loggedInUserType'] == 0 || $_COOKIE['loggedInUserType'] == 2) {
echo '<h4><a href="menuvdweekadd.php">Verander de menu!</a></h4>';
} ?>
<div class="menuwDiv">
<?php
foreach ($recipes as $recipe) {
echo '<div class="day">
<div class="date">
<p class="datep">' . Translate::translateDate(date($format, $recipe['date'])) . '</p>
</div>
<div class="gerecht">
<p class="gerechtp">' . $recipe['name'] . '<p />';
if ( $_COOKIE['loggedInUserType'] == 0 || $_COOKIE['loggedInUserType'] == 2){
echo '<form class="form" action="menuvdweek.php?gerechtdate='.$recipe['date'].'" method="POST">
<input type="submit" id="delete" name="delete" value="Delete">
</form>';
}
echo '</div>
</div>
<hr />';
}
?>
</div>
</div>
</div>
</body>
</html> | 716ec5636ff060237a4c392fba6e2c1fff5ef676 | [
"JavaScript",
"PHP"
] | 15 | PHP | HaDaanCraft/mylovelifefamily | cae1cdda2b552478ad5a069fba89102b63378643 | 70937e78198fed55af383cc7e62577cc9ca16bc2 |
refs/heads/master | <repo_name>kabragaurav/Blockchain-With-Js<file_sep>/README.md
# Blockchain-With-Js
Very basic functions of Blockchain, implemented in Typescript
# Author
> <NAME>
# Installation
In VS Code, open terminal and type : <br>
```
npm install --save crypto-js
```
This will provide cryptographic libraries.
# Running
In VS Code, open terminal and type : <br>
```
node main.js
```
# Live Demonstration
[Here](https://andersbrownworth.com/blockchain/blockchain)
# Sample ScreenSave
<file_sep>/main.js
// AUTHOR - <NAME>
// <EMAIL>
/**
* This program does not consider communication in a peer-to-peer n/w
* Also does not check if enough funds for transaction
* THIS PROGRAM IS ONLY INTENDED TO DEMONSTRATE A VERY BASIC OF HOW A BLOCKCHAIN WORKS
*/
SHA256 = require('crypto-js/sha256');
class Block{
// index : position of block on chain
// timestamp : when block was created
// data : content of block
// prevHash : avoid fraudulence
// nounce : difficulty (# of 0's that hash should start with)
constructor(data, prevHash = ''){
this.index = Block.index++;
this.timestamp = this.getTimestamp();
this.data = data;
this. prevHash = prevHash;
this.hash = this.calculateHash();
this.nounce = 0;
}
calculateHash(){
let temp = this.index + this.timestamp + this.prevHash + JSON.stringify(this.data) + this.nounce;
// convert object 'temp' to string
return SHA256(temp).toString();
}
getTimestamp(){
let currentDate = new Date();
let date = currentDate.getDate();
let month = currentDate.getMonth();
let year = currentDate.getFullYear();
let dateString = date + "/" +(month + 1) + "/" + year; // added 1 bcz January is 0 not 1
return dateString;
}
// proof of work (aka mining) is used so only certain number of blocks may be added to chain
// hash of a block must start with a certain amount of zeros
// difficulty is reqd so that as machines get faster, difficulty may be raised
mineBlock(difficulty){
while(this.hash.substring(0, difficulty) != Array(difficulty+1).join('0')){
this.nounce++;
this.hash = this.calculateHash();
}
}
}
// static variable
Block.index = 0
class Blockchain{
constructor(){
// first block is called genesis block and must be added manually
this.chain = [this.createGenesisBlock()];
this.difficulty = 5;
}
createGenesisBlock(){
return new Block("Genesis Block", "0");
}
addBlock(newBlock){
newBlock.prevHash = this.getLastBlock().hash;
newBlock.mineBlock(this.difficulty);
this.chain.push(newBlock);
}
getLastBlock(){
return this.chain[this.chain.length - 1];
}
// chain may become invalid if temper block data
isChainValid(){
for(let i=1; i<this.chain.length; i++){
let currentBlock = this.chain[i];
let prevBlock = this.chain[i-1];
if(currentBlock.hash != currentBlock.calculateHash() || currentBlock.prevHash != prevBlock.hash)
return false;
return true;
}
}
}
class Main{
runner(){
let gaurav = new Blockchain();
console.log("Mining Blk 1");
let sdate = new Date();
gaurav.addBlock(new Block({amount : 1001}));
let edate = new Date();
console.log("Time in sec :" + (edate-sdate)/1000);
console.log(gaurav);
console.log("Mining Blk 2");
sdate = new Date();
gaurav.addBlock(new Block({price : 499}));
edate = new Date();
console.log("Time in sec :" + (edate-sdate)/1000);
console.log(gaurav);
}
}
let m = new Main();
m.runner(); | f7bf4e9b01a93a4532716d400cefdd3d8089069f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | kabragaurav/Blockchain-With-Js | 535919180526c275f42c6d733b161751da91c66d | 86c4cbead43a09636e7a2ff338ecfc174f649939 |
refs/heads/master | <repo_name>RenatoSanchez006/Todo-List<file_sep>/js/index.js
//Add new elements
document.getElementById("submitButton").addEventListener("click", function () {
var input = document.createElement("input");
input.type = "checkbox";
var label = document.createElement("label");
label.textContent = document.getElementById("newTodo").value;
//Element for every user input
var parentDiv = document.createElement("div");
parentDiv.append(input);
parentDiv.append(label);
//Adding element and clearing box
document.getElementById("listOfTodos").appendChild(parentDiv)
document.getElementById("newTodo").value = '';
});
//Uncheck elements
document.getElementById("clearButton").addEventListener("click", function () {
var elements = document.getElementById("listOfTodos").childNodes;
for (var i = 0; i < elements.length; i++) {
elements[i].firstChild.checked = false;
}
});
//Check elements
document.getElementById("markAllButton").addEventListener("click", function () {
var elements = document.getElementById("listOfTodos").childNodes;
for (var i = 0; i < elements.length; i++) {
elements[i].firstChild.checked = true;
}
});
//Deleter elements
document.getElementById("deleteButton").addEventListener("click", function () {
var elements = document.getElementById("listOfTodos");
while (elements.firstChild) {
elements.removeChild(elements.firstChild);
}
});<file_sep>/README.md
HTML, CSS, JavaScript Lab for Web applications class.
Todo List for things to do
| 6c386dc4ab55aae092a436237a3df0622b0e5f0c | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | RenatoSanchez006/Todo-List | 5d249f23cb6480a19b1d5d423d9af74383848409 | 5c385642311b9827033f9ae041064d1f4dcb3ab6 |
refs/heads/master | <repo_name>sabinpark/ECE382_Lab8<file_sep>/code/18_lab8_imp.c
//-------------------------------------------------------------------------------
// Name: <NAME>
// Term: Fall 2014
// MCU: MSP430G2553
// Date: 10 December 2014
// Note: Lab 8: implementation file for the robot maze lab
//-------------------------------------------------------------------------------
#include "msp430g2553.h"
#include "robot_2.h"
/*
* initializes the msp430
*/
void initMSP430() {
IFG1=0; // clear interrupt flag1
WDTCTL=WDTPW+WDTHOLD; // stop WD
BCSCTL1 = CALBC1_8MHZ;
DCOCTL = CALDCO_8MHZ;
P2SEL &= ~BIT6; // Setup P2.6 as GPIO not XIN
P2SEL2 &= ~BIT6;
P2DIR &= ~BIT6;
P2IFG &= ~BIT6; // Clear any interrupt flag
P2IE |= BIT6; // Enable PORT 2 interrupt on pin change
HIGH_2_LOW;
P1DIR |= BIT0 | BIT6; // Enable updates to the LED
LEDS_OFF; // And turn the LED off
TA0CCR0 = 0x8000; // create a 16mS roll-over period
TACTL &= ~TAIFG; // clear flag before enabling interrupts = good practice
TACTL = ID_3 | TASSEL_2 | MC_1; // Use 1:1 presclar off MCLK and enable interrupts
_enable_interrupt();
}
/*
* store the MEM value for the center sensor
*/
unsigned int centerSensor() {
ADC10CTL0 = 0;
ADC10CTL1 = INCH_4 | ADC10DIV_3 ; // Make P1.3 analog input
ADC10CTL0 = SREF_0 | ADC10SHT_3 | ADC10ON | ENC; // Vcc & Vss as reference
ADC10CTL0 |= ADC10SC; // Start a conversion
while(ADC10CTL1 & ADC10BUSY); // Wait for conversion to complete
return ADC10MEM;
}
/*
* store the MEM value for the right sensor
*/
unsigned int rightSensor() {
ADC10CTL0 = 0;
ADC10CTL1 = INCH_5 | ADC10DIV_3 ; // Make P1.3 analog input
ADC10CTL0 = SREF_0 | ADC10SHT_3 | ADC10ON | ENC; // Vcc & Vss as reference
ADC10CTL0 |= ADC10SC; // Start a conversion
while(ADC10CTL1 & ADC10BUSY); // Wait for conversion to complete
return ADC10MEM;
}
/*
* store the MEM value for the left sensor
*/
unsigned int leftSensor() {
ADC10CTL0 = 0;
ADC10CTL1 = INCH_3 | ADC10DIV_3 ; // Make P1.3 analog input
ADC10CTL0 = SREF_0 | ADC10SHT_3 | ADC10ON | ENC; // Vcc & Vss as reference
ADC10CTL0 |= ADC10SC; // Start a conversion
while(ADC10CTL1 & ADC10BUSY); // Wait for conversion to complete
return ADC10MEM;
}
/*
* stops the motors
*/
void stop() {
LEFT_DISABLE;
RIGHT_DISABLE;
LEDS_OFF;
}
/*
* enables the left and right PWMs
*/
void go() {
LEFT_ENABLE;
RIGHT_ENABLE;
}
/*
* moves the robot forward
*/
void moveForward() {
go();
LEFT_OM_HI;
RIGHT_OM_HI;
LEFT_SET_CCW;
RIGHT_SET_CW;
RED_OFF;
GREEN_ON;
}
/*
* moves the robot backward
*/
void moveBackward() {
go();
LEFT_OM_LO;
RIGHT_OM_LO;
// LEFT MOTOR
LEFT_SET_CW;
// RIGHT MOTOR
RIGHT_SET_CCW;
RED_ON; // red LED ON
GREEN_OFF; // green LED OFF
}
/*
* turns the robot CCW
*/
void rotateLeft() {
go();
LEFT_OM_LO;
RIGHT_OM_HI;
// LEFT MOTOR
LEFT_SET_CW;
// RIGHT MOTOR
RIGHT_SET_CW;
RED_ON; // red LED ON
GREEN_OFF; // green LED OFF
}
/*
* turns the robot CW
*/
void rotateRight() {
go();
LEFT_OM_LO;
RIGHT_OM_HI;//RIGHT_OM_LO;
// LEFT MOTOR
LEFT_SET_CCW;
// RIGHT MOTOR
RIGHT_SET_CCW;
GREEN_ON; // green LED ON
RED_OFF; // red LED OFF
}
<file_sep>/README.md
ECE382_Lab8
===========
## *Functionality Update*
|Functionality|Status|Date Completed|Checked by|
|:-:|:-:|:-:|:-:|
| Required | Complete | 11 Dec 14 @ 0700 | Dr. Coulston, Dr. York |
| B | Complete | 11 Dec 14 @ 0700 | Dr. Coulston, Dr. York |
| A | Complete | 11 Dec 14 @ 0700 | Dr. Coulston, Dr. York |
A functionality may be viewd [here](http://youtu.be/e6VjWnEAKvg).
## Overview
Use the previous laboratory assignments (both the robot and the code) to program my robot to autonomously navigate through a maze.
## Requirements
1. Your robot must always start at the home position.
2. Your robot is considered successful only if it finds one of the three exits and moves partially out of the maze.
3. A large portion of your grade depends on which door you exit.
* Door 1: Required Functionality
* Door 2: B Functionality
* Door 3: A Functionality (cannot hit a wall)
* Bonus: Navigate from the A functionality door back to the entrance using the same algorithm (cannot hit a wall)
4. Your robot must solve the maze in less than three minutes.
5. Your robot will be stopped if it touches the wall more than twice.
6. Your robot must use the IR sensors to find its path through the maze.
*NOTE*: Each functionality attempted will have that corresponding door open. We do not have to have the robot sense for gaps or openings in the walls.
## Prelab
#### Pseudo-code
For the prelab, I will simply use Lab 7 code which lit up the LEDs using the sensors. This time, instead of just toggling the LEDs, I will also control the motors based on the IR sensor inputs.
```
// Door 1:
// initially drive forward (slow to moderate) and detect walls that are apx. 5 inches away
// if right sensor is ON
// turn 45 deg. left
// if center sensor voltage is greater than right sensor voltage, turn again
// else if left sensor is ON
// turn 45 deg. right
// if center sensor voltage is greater than left sensor voltage, turn again
// else (if neither the left or right sensors are ON)
// turn 45 deg. right (default)
// drive forward and repeat
// Door 2 and Door 3 [Following a wall method]
// Use right and center sensors (use methods to store the MEM values for each sensor into an int]
// if center sensor reads value higher than cutoff_center...
// turn left
// else if right sensor reads value higher than cutoff_right...
// turn left
// else if right sensor reads too low of a value (meaning the robot is drifting off to the left)...
// right right
// else move forward
```
## Lab
### Required Functionality
I began by copying over the code from lab 7 and retesting the LEDs. As expected, the LEDs lit up when I placed an object in front of the transmitter/receiver pair. Next, I created new main.c and implementation.c files. The implementation.c file was updated with the movement functions used in lab 6.
Although the code worked properly when I tested the LEDs only, when I added the movements from the motors, I was getting very strange results. Instead of turning on and off with the same responsiveness of the LEDs, the motors were erratic in their responses. After trying various things, I eventually was able to get decent responses from the motors (please see the debugging section for details).
I now had to code my maze-solving algorithm. For required functionality, all I had to do was make my robot drive forward until it arrived at the first perpendicular wall and then turn 90 degrees left to exit the maze through door 1.
I started by creating three functions, one for each sensor: right, center, and left. These functions are used to compare the converted packet data from the threshold voltages characterized in lab 7. Below is the method for the center sensor.
```
unsigned int centerSensor() {
ADC10CTL0 = 0;
ADC10CTL1 = INCH_4 | ADC10DIV_3 ; // Make P1.3 analog input
ADC10CTL0 = SREF_0 | ADC10SHT_3 | ADC10ON | ENC; // Vcc & Vss as reference
ADC10CTL0 |= ADC10SC; // Start a conversion
while(ADC10CTL1 & ADC10BUSY); // Wait for conversion to complete
return ADC10MEM;
}
```
Since I had to check for the first corner (NE from the robot's perspective), I had the robot turn left when the center or right sensors were reading in high voltages. To be sure the robot would not hit the left side of the wall, I made another check to turn the robot to the right slightly if the left sensor was activated. In between the left and right walls, I made the robot go forward.
```
while(1) {
c = centerSensor();
r = rightSensor();
l = leftSensor();
int counter = 0;
if((c > centerCutoff || r > rightCutoff) && l < leftCutoff) {
rotateLeft();
_delay_cycles(1000);
} else if(l > leftCutoff) {
rotateRight();
_delay_cycles(1000);
}
else {
stop();
moveForward();
_delay_cycles(1000);
}
moveForward();
}
```
Using these simple checks, my robot passed through the first portion of the maze and cleared door #1.
*Required Functionality Success!*
#### Required Functionality [Debugging]
I had some problems with the motors. The IR sensors were properly detecting voltage changes when used with the LEDs only, but when I started to run the motors and try to toggle the motors' changes using the same threshold voltages, I got very inconsistent results. Even when I figured out the approximate threshold voltage for each of the motors, I still could not properly toggle any changes. It seemed that the extra voltage used to rotate the motors interfered with the IR readings.
The main problem I had with this was that at random times, the motor would infinitely repeat a given movement even if it no longer sensed a high enough voltage which would toggle the appropriate response.
I spent quite a bit of time trying various things to solve this issue, but in the end, I could not figure it out. It is possible that this may be a software issue, but after looking through my code and comparing with other classmates, I concluded that it may actually be a hardware issue.
Having spent too much time on this issue, I decided to call it good and move on to actually coding my robot to move through the maze.
### B Functionality
*NOTE*: I moved straight into A Functionality. Please see below.
#### B Functionality [Debugging]
*NOTE*: I moved straight into A Functionality. Please see below.
### A Functionality
For A functionality, I had to code the robot to go through door #3. This meant the robot would essentially have to account for both the NE and the NW corner. Thus, the robot would somehow have state conditions that would allow it to know when to take a right or left turn at each corner.
But perhaps I could try something else. Another method would be to have the robot hug either the right or left wall. In this way, the robot would simply use either the left or right sensor and ensure that particular sensor will always have something detecting.
I decided to use the wall-hugging method using the right side of the maze (and correspondingly, the right sensor).
Similar to the code from the required functionality, I created various if-statements to check for the few cases my robot would have to navigate through.
Cases:
* Center sensor only
* This situation accounts for when the robot is faced with a wall straight-on and has either side open
* The robot will be told to turn to the left in these cases
* Between the min and max range from the right wall
* I did not want my robot to stray too far off to the left side or too close to the right side
* Between these two extremes, I will tell my robot to go forth and conquer (though somewhat in an S-curve path)
* Close to the right wall
* The robot will sense that it is too close to the right wall and will veer to the left
* Too far from the right wall
* Once the robot has veered too far from the right wall, it will turn right to make sure its right sensor is still tracking a wall
```
while(1) {
c = centerSensor();
r = rightSensor();
if(c > cClose) { // center sense
moveForward();
_delay_cycles(100);
rotateLeft();
_delay_cycles(500);
} else if(r > rFar && r < rClose) { // boundary
//stop();
moveForward();
_delay_cycles(1000);
}
else if(r > rClose) { // right sense
moveForward();
_delay_cycles(500);
rotateLeft();
_delay_cycles(500);
} else if(r < rFar) { // far from the right wall
moveForward();
_delay_cycles(800);
rotateRight();
_delay_cycles(700);
}
moveForward();
}
```
#### A Functionality [Debugging]
After getting required functionality, getting A funcitonality to work was not that difficult. There are, however, a few things I had to work around (literally).
For example, I had to figure out a way for the robot to get around the hair-pin turn located in the middle of the maze. At first, I noticed that the robot would be fine tracking the wall, but when it approaches the tip of the hair-pin turn, it would immediately begin to turn to the right and crash into the edge of the turn. To counter this problem, I recoded the robot to delay a little bit longer while going forward before turning at the hair-pin. This seemed to work for some of the trials, but it was not very reliable.
I then tried a different approach (literally). Instead of having the robot start off perfectly straight-facing the maze, I angled the starting position of the robot 45 degrees to the right. By changing the launch angle, the robot traversed the maze using a different path. The different path allowed the robot to bounce off the wall right before the hair-pin turn and allowed it to make a smooth, rounded turn, completely avoiding the hair-pin. Unfortunately, this was not 100% reliable, but it was better than before.
Another thing I currently have problems with is the robot's consistency. As of now, the robot successfully makes it through the maze about 1 out of ten times. Again, I believe the root of the problem lies with the hardware issues I was having from the required functionality section. However, after all the debugging hours I spent on it, I decided to move on to bigger and better things...
### Bonus Functionality
Incomplete. Needs some tweaking.
#### Bonus Functionality [Debugging]
N/A
## Competition
Jeff 2.0 had his debut today in the ECE Robot Maze Competition. The competition consisted of going through the maze and exiting through Door #3. Though his practice run was a 10.48 seconds the other day, he still managed to pull off a 14.34 seconds for today's competition. I think Jeff 2.0 was a bit nervous and his hardware started to get a bit hot...but regardless, good job, Jeff 2.0!
*UPDATE*: Jeff 2.0 tried the maze again with a slightly tweaked set of new instructions. His new time as of now is 12.24 seconds without touching any walls.
## Documentation
* C2C <NAME> gave me advice to use my `stop()` methods in between other movement calls
<file_sep>/code/18_lab8_main.c
//-------------------------------------------------------------------------------
// Name: <NAME>
// Term: Fall 2014
// MCU: MSP430G2553
// Date: 10 December 2014
// Note: Lab 8: main file the robot maze lab
//-------------------------------------------------------------------------------
#include "msp430g2553.h"
#include "robot_2.h"
// MEM value holders for center, right, and left sensors
unsigned int c, r;
// the threshold values for the sensors
unsigned int rFar = 690; // voltage at which the robot gets too far (right)
unsigned int rClose = 690; // voltage at which the robot gets too close (right)
unsigned int cClose = 562; // voltage at which the robot gets too close (center)
//----------------------------------------------------------------------
// MAIN
//----------------------------------------------------------------------
int main(void) {
initMSP430(); // Setup MSP to process IR and buttons
IFG1=0; // clear interrupt flag1
WDTCTL = WDTPW + WDTHOLD; // disable WDT
BCSCTL1 = CALBC1_8MHZ; // 8MHz clock
DCOCTL = CALDCO_8MHZ;
P1DIR = BIT0 | BIT6; // Set the red and green LEDs as outputs
ADC10AE0 = BIT3 | BIT4 | BIT5; // make P1.3, P1.4, and P1.5 analog inputs
// LEFT MOTOR PWM is OUTPUT and set to the TIMER mode
LEFT_PWN_ENABLE_SET_OUTPUT; // P2.2 is associated with TA1CCR1
LEFT_P2SEL_SET; // P2.2 is associated with TA1CCTL1 // selects the primary peripheral module function
// RIGHT MOTOR PWN is INPUT and set to the TIMER mode
RIGHT_PWN_ENABLE_SET_OUTPUT; // P2.4 is associated with TA1CCR2
RIGHT_P2SEL_SET; // P2.4 is associated with TA1CCTL2
// set the initial direction of the motors (FORWARD)
// LEFT
LEFT_SET_OUTPUT; // set P2DIR BIT1 as an output
LEFT_SET_CCW; // CCW
// RIGHT
RIGHT_SET_OUTPUT; // set P2DIR BIT3 as an output
RIGHT_SET_CW; // CW
// disable the enablers (NO MOVEMENT)
// LEFT
LEFT_ENABLE_SET_OUTPUT; // set P2DIR BIT0 as an output
LEFT_DISABLE; // ensures that the enable is set to 0 (disable)
// RIGHT
RIGHT_ENABLE_SET_OUTPUT; // same as above
RIGHT_DISABLE;
// SETTINGS
TA1CTL = ID_3 | TASSEL_2 | MC_1; // Use 1:8 presclar off MCLK
TA1CCR0 = 100; // set signal period
// LEFT motor
TA1CCR1 = 55;//60;
TA1CCTL1 = OUTMOD_7; // set TACCTL1 to Reset / Set mode
// RIGHT motor
TA1CCR2 = 40;//TA1CCR0-TA1CCR1;
TA1CCTL2 = OUTMOD_7; // set TACCTL1 to Reset / Set mode
// infinite loop
while(1) {
// A FUNCTIONALITY //
c = centerSensor(); // store the center sensor MEM
r = rightSensor(); // store the right sensor MEM
if(c > cClose) { // center sensor is close to a wall in the front
moveForward();
_delay_cycles(100);
rotateLeft();
_delay_cycles(500);
} else if(r > rFar && r < rClose) { // boundary between too far and too close to the right wall
moveForward();
_delay_cycles(1000);
}
else if(r > rClose) { // right sensor too close
rotateLeft();
_delay_cycles(500);
moveForward();
_delay_cycles(500);
rotateLeft();
_delay_cycles(100);
} else if(r < rFar) { // too far from the right wall
moveForward();
_delay_cycles(800);
rotateRight();
_delay_cycles(700);
} else if(r > rFar && r < rClose) {
stop();
moveForward();
_delay_cycles(100);
}
moveForward();
} // end infinite loop
} // end main
<file_sep>/code/robot_2.h
/*
* robot.h
*
* Created on: Dec 5, 2014
* Author: C16Sabin.Park
*/
//-----------------------------------------------------------------
// Page 76 : MSP430 Optimizing C/C++ Compiler v 4.3 User's Guide
//-----------------------------------------------------------------
typedef unsigned char int8;
typedef unsigned short int16;
typedef unsigned long int32;
typedef unsigned long long int64;
#define TRUE 1
#define FALSE 0
#define FORWARD 1
#define STOP 0
#define BACKWARD -1
//-----------------------------------------------------------------
// Function prototypes
//-----------------------------------------------------------------
void initMSP430();
__interrupt void pinChange (void);
__interrupt void timerOverflow (void);
//void leftSensor();
//void centerSensor();
//void rightSensor();
//-----------------------------------------------------------------
// Each PxIES bit selects the interrupt edge for the corresponding I/O pin.
// Bit = 0: The PxIFGx flag is set with a low-to-high transition
// Bit = 1: The PxIFGx flag is set with a high-to-low transition
//-----------------------------------------------------------------
#define IR_PIN (P2IN & BIT6)
#define HIGH_2_LOW P2IES |= BIT6
#define LOW_2_HIGH P2IES &= ~BIT6
/*
#define averageLogic0Pulse 544
#define averageLogic1Pulse 1615
#define averageStartPulse 4340
#define minLogic0Pulse averageLogic0Pulse - 100
#define maxLogic0Pulse averageLogic0Pulse + 100
#define minLogic1Pulse averageLogic1Pulse - 100
#define maxLogic1Pulse averageLogic1Pulse + 100
#define minStartPulse averageStartPulse - 100
#define maxStartPulse averageStartPulse + 100
// constants for the remote control buttons
#define BTN_PWR 0x30DFA857 //
#define BTN_2 0x30DF609F // Forward
#define BTN_4 0x30DF10EF // Rotate Left
#define BTN_5 0x30DF906F // Stop
#define BTN_6 0x30DF50AF // Rotate Right
#define BTN_8 0x30DF30CF // Backward
#define BTN_CH_HI 0x30DF40BF // Increase duty cycle
#define BTN_CH_LO 0x30DFC03F // Decrease duty cycle
#define BTN_1 0x30DFA05F // turn NW
#define BTN_3 0x30DFE01F // turn NE
#define BTN_7 0x30DFD02F // turn SW
#define BTN_9 0x30DFB04F // turn SE
#define BTN_0 0x30DF20DF // continuous CW rotation
#define BTN_DASH 0x30DF6C93 // continuous CCW rotation
#define BTN_OK 0x30DF18E7 //
*/
// constants for motor delays
#define SHORT_DELAY 5000000
#define LONG_DELAY 15000000
#define DELAY_360 9000000 // the delay it takes for (approximately) 360 degrees of rotation
#define DELAY_180 4800000 // for (appx) 180 degrees
#define DELAY_90 2700000 // for (appx) 90 degrees
#define DELAY_45 1400000 // for (appx) 45 degrees
#define DELAY_15 800000 // for (appx) 15 degrees
#define DEG_360 360 // constant to define 360 degrees
// sets the PWN direction bits to output
#define LEFT_PWN_ENABLE_SET_OUTPUT P2DIR |= BIT2
#define RIGHT_PWN_ENABLE_SET_OUTPUT P2DIR |= BIT4
// chooses the proper function for use with the timers
#define LEFT_P2SEL_SET P2SEL |= BIT2
#define RIGHT_P2SEL_SET P2SEL |= BIT4
// left motor enable
#define LEFT_ENABLE_SET_OUTPUT P2DIR |= BIT0 // sets direction pin to output
#define LEFT_ENABLE P2OUT |= BIT0 // enable left motor
#define LEFT_DISABLE P2OUT &= ~BIT0 // disable left motor
// right motor enable
#define RIGHT_ENABLE_SET_OUTPUT P2DIR |= BIT5 // sets direction pin to output
#define RIGHT_ENABLE P2OUT |= BIT5 // enable right motor
#define RIGHT_DISABLE P2OUT &= ~BIT5 // disable right motor
// left motor direction
#define LEFT_SET_OUTPUT P2DIR |= BIT1 // sets direction pin to output
#define LEFT_SET_CW P2OUT &= ~BIT1 // left motor turns clockwise
#define LEFT_SET_CCW P2OUT |= BIT1 // left motor turuns counter-clockwise
// right motor direction
#define RIGHT_SET_OUTPUT P2DIR |= BIT3 // sets direction pin to output
#define RIGHT_SET_CW P2OUT &= ~BIT3 // right motor turns clockwise
#define RIGHT_SET_CCW P2OUT |= BIT3 // right motor turns counter-clockwise
// left motor outmode
#define LEFT_OM_HI TA1CCTL1 = OUTMOD_3;
#define LEFT_OM_LO TA1CCTL1 = OUTMOD_7;
// right motor outmode
#define RIGHT_OM_HI TA1CCTL2 = OUTMOD_3;
#define RIGHT_OM_LO TA1CCTL2 = OUTMOD_7;
#define GREEN_ON P1OUT |= BIT6
#define GREEN_OFF P1OUT &= ~BIT6
#define RED_ON P1OUT |= BIT0
#define RED_OFF P1OUT &= ~BIT0
#define LEDS_ON P1OUT |= BIT0 | BIT6
#define LEDS_OFF P1OUT &= ~(BIT0 | BIT6)
#define LEFT 0
#define CENTER 1
#define RIGHT 2
#define NONE 3
| ca8a6a8df87c72bf25a5eefa1462fa8d9e476eab | [
"Markdown",
"C"
] | 4 | C | sabinpark/ECE382_Lab8 | bf641bb857c5dc53d3ee29246654b58097d4aeae | 38ef4199f04833bc37ba6db8ba397f4e0e883dec |
refs/heads/master | <repo_name>marciobahia/Letmeask<file_sep>/README.md
<div align="center">
<img src="https://github.com/marciobahia/Letmeask/blob/master/src/assets/images/logo.svg">
</div>
## Let Me Ask
[](https://github.com/josepholiveira)
[](#)
[](https://github.com/josepholiveira/letmeask/stargazers)
Let Me Ask is a platform built to let you gather questions from your viewers during your stream and let them vote for which are the best questions for you to answer.
</h4>

<h4 align="center">
## Tecnologies
This project was developed using the following technologies:
- [ReactJS](https://reactjs.org/)
- [Typescript](https://www.typescriptlang.org/)
- [Firebase Authentication](https://firebase.google.com/products/auth)
- [Firebase Realtime Database](https://firebase.google.com/products/realtime-database)
## 💻 Getting started
### Requirements
- You need to install both [Node.js](https://nodejs.org/en/download/) and [Yarn](https://yarnpkg.com/) to run this project.
**Clone the project and access the folder**
```bash
$ git clone https://github.com/marciobahia/Letmeask.git
```
**Follow the steps below**
```bash
**Install the dependencies**
# Access the project folder on your terminal/cmd
$ cd letmeask
# Install the dependencies
$ yarn install
# ou npm install
# Run the application in development mode
$ yarn start
# ou npm run start
# Remember to configure your .env.local following the .env.exemple
```
The app will be available for access on your browser at `http://localhost:3000`
## 📝 License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
---
<<<<<<<
[](https://www.instagram.com/bahiainspetor/)
[](https://www.linkedin.com/in/márcio-sella-bahia-9b73bb19b/)
<file_sep>/.history/src/services/firebase_20210621205120.ts
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "letmeask-5a2c0.firebaseapp.com",
databaseURL: "https://letmeask-5a2c0-default-rtdb.firebaseio.com",
projectId: "letmeask-5a2c0",
storageBucket: "letmeask-5a2c0.appspot.com",
messagingSenderId: "613101567907",
appId: "1:613101567907:web:624f5454bd7c86fae92416"
};
firebase.initializeApp(firebaseConfig);
export const auth = firebase.auth();
export const database = firebase.database();
| d3bc5f66baca218d6dfcca327b71b5581fc76ebf | [
"Markdown",
"TypeScript"
] | 2 | Markdown | marciobahia/Letmeask | e48a04e81892072cd724a2fe06e1706071789383 | eccf64af67b3493d28535a244596ce05f9fc4900 |
refs/heads/master | <file_sep>/**
* Given a string, return its encoding version.
*
* @param {String} str
* @return {String}
*
* @example
* For aabbbc should return 2a3bc
*
*/
function encodeLine(str) {
const arr = [...str];
const answer = [];
let current = [0, ''];
arr.push('');
arr.forEach((e) => {
if (e !== current[1]) {
answer.push((current[0] ? current[0] + 1 : '') + current[1]);
current = [0, e];
} else current[0]++;
});
return answer.join('');
}
module.exports = encodeLine;
<file_sep>const ListNode = require('../extensions/list-node');
/**
* Implement the Queue with a given interface via linked list (use ListNode extension above).
*
* @example
* const queue = new Queue();
*
* queue.enqueue(1); // adds the element to the queue
* queue.enqueue(3); // adds the element to the queue
* queue.dequeue(); // returns the top element from queue and deletes it, returns 1
*
*/
class Queue {
get size() {
let depth = 0;
if (['next'] in this) {
depth = 1;
for (let i = this; i.next !== null; i = i.next, depth++);
}
return depth;
}
enqueue(element) {
let endNode = this;
if (this.size === 0) {
Object.assign(endNode, new ListNode(element));
} else {
for (; endNode.next !== null; endNode = endNode.next);
endNode.next = new ListNode(element);
}
}
dequeue() {
const { value, next } = this;
if (next === null) {
Object.assign(this, null);
} else {
Object.assign(this, new ListNode(next.value));
this.next = next.next;
}
return value;
}
}
module.exports = Queue;
<file_sep>/**
* Given some integer, find the maximal number you can obtain
* by deleting exactly one digit of the given number.
*
* @param {Number} n
* @return {Number}
*
* @example
* For n = 152, the output should be 52
*
*/
function deleteDigit(n) {
const str = n.toString();
const arr = new Array(str.length);
for (let i = 0; i < arr.length; i++) {
arr[i] = str.split('');
arr[i].splice(i, 1);
arr[i] = +arr[i].join('');
}
return Math.max(...arr);
}
module.exports = deleteDigit;
<file_sep>/**
* Given a sorted array, find the index of the element with the given value.
* Time complexity should be O(logN)
*
* @param {Array} array
* @param {Number} value
* @return {Number}
*
* @example
* For ([1, 2, 3], 1) should return 0
* For ([1, 2, 3], 2) should return 1
*
*/
function findIndex(array, value) {
function searchBin(start, end, val) {
let pivot = Math.floor((start + end) / 2);
if (val !== array[pivot]) {
if (val > array[pivot]) pivot = searchBin(pivot, end, val);
else pivot = searchBin(start, pivot, val);
}
return pivot;
}
return searchBin(0, array.length, value);
}
module.exports = findIndex;
<file_sep>/**
* In the popular Minesweeper game you have a board with some mines and those cells
* that don't contain a mine have a number in it that indicates the total number of mines
* in the neighboring cells. Starting off with some arrangement of mines
* we want to create a Minesweeper game setup.
*
* @param {Array<Array>} matrix
* @return {Array<Array>}
*
* @example
* matrix = [
* [true, false, false],
* [false, true, false],
* [false, false, false]
* ]
*
* The result should be following:
* [
* [1, 2, 1],
* [2, 1, 1],
* [1, 1, 1]
* ]
*/
function minesweeper(matrix) {
const maxY = matrix.length;
const maxX = matrix[0].length;
const arr = new Array(maxY);
for (let i = 0; i < maxY; i++) {
arr[i] = new Array(maxX).fill(0);
for (let j = 0; j < maxX; j++) {
if (i - 1 >= 0) {
if (j - 1 >= 0 && matrix[i - 1][j - 1]) arr[i][j]++;
if (matrix[i - 1][j]) arr[i][j]++;
if (j + 1 < maxX && matrix[i - 1][j + 1]) arr[i][j]++;
}
if (i + 1 < maxY) {
if (j - 1 >= 0 && matrix[i + 1][j - 1]) arr[i][j]++;
if (matrix[i + 1][j]) arr[i][j]++;
if (j + 1 < maxX && matrix[i + 1][j + 1]) arr[i][j]++;
}
if (j - 1 >= 0 && matrix[i][j - 1]) arr[i][j]++;
if (j + 1 < maxX && matrix[i][j + 1]) arr[i][j]++;
}
}
return arr;
}
module.exports = minesweeper;
<file_sep>/**
* Given two strings, find the number of common characters between them.
*
* @param {String} s1
* @param {String} s2
* @return {Number}
*
* @example
* For s1 = "aabcc" and s2 = "adcaa", the output should be 3
* Strings have 3 common characters - 2 "a"s and 1 "c".
*/
function getCommonCharacterCount(s1, s2) {
const set = [...new Set(s1 > s2 ? s2 : s1)].sort();
let answer = 0;
const temp = [];
let reg;
for (let i = 0; i < set.length; i++) {
reg = new RegExp(set[i], 'g');
temp[0] = s1.match(reg) !== null ? s1.match(reg).length : 0;
temp[1] = s2.match(reg) !== null ? s2.match(reg).length : 0;
answer += Math.min(...temp);
}
return answer;
}
module.exports = getCommonCharacterCount;
| 48022f89c66ed7b281960ae51f8fd31420225074 | [
"JavaScript"
] | 6 | JavaScript | 4ebula/rs-school-short-track-2021 | a376f4a715a988b6ab139d4ef6b919dd2001b1e8 | 7e320c1f8664780058aae393040c4cf591af7c18 |
refs/heads/master | <file_sep>#pragma once
#include <SDL.h>
#include "EngineModule/Actor.h"
namespace GameModule {
enum class SceneState;
class Button;
class Menu : public EngineModule::Actor{
public:
Menu(std::string nodeName);
void init();
void render() override;
void OnExit() override;
void setState(SceneState val);
SceneState getState();
private:
SDL_Texture* logo;
SDL_Texture* bg;
Button* start;
Button* exit;
Button* yes;
Button* no;
SceneState state;
};
}
<file_sep>#pragma once
#include <SDL.h>
#include <functional>
#include "EngineModule/Actor.h"
namespace GameModule {
class Button : public EngineModule::Actor {
public:
Button(std::string nodeName, std::string spriteName);
void init(std::string spriteName);
void setOnClickCallback(std::function<void()> function);
void OnLButtonDown(int mX, int mY) override;
void render() override;
private:
SDL_Texture* sprite;
std::function<void()> callback;
};
} // namespace GameModule<file_sep>#include "Game.h"
#include <iostream>
#include <SDL_image.h>
#include "EngineModule/Viewport.h"
#include "GameModule/Balancer.h"
#include "GameModule/Weighty.h"
#include "GameModule/Button.h"
#include "GameModule/EStates.h"
using namespace GameModule;
GameModule::Game::Game(std::string name)
: Actor{name}, state{SceneState::NOTHING} {
window = EngineModule::Viewport::getWindow();
renderer = EngineModule::Viewport::getRenderer();
init();
}
void GameModule::Game::init() {
/*
В этой функции определяются все игровые компоненты: задний фон, веса,
кнопки и тд.
*/
SDL_Surface* windowSurface = IMG_Load("Resource\\bg.jpg");
printf("%s \n", IMG_GetError());
bg = SDL_CreateTextureFromSurface(renderer, windowSurface);
SDL_FreeSurface(windowSurface);
balancer = new Balancer{"balancer", this};
addChild(balancer);
Weighty* weighty = new Weighty("weighty1", "gruz1.jpg");
addChild(weighty);
weighty->setTitle(L"Весы");
weighty->setX(100);
weighty->setY(610);
weighty->setWeight(50);
Weighty* weighty2 = new Weighty("weighty2", "gruz1.jpg");
addChild(weighty2);
weighty2->setTitle(L"Хиря2");
weighty2->setX(200);
weighty2->setY(610);
weighty2->setWeight(100.23);
Weighty* weighty3 = new Weighty("weighty3", "gruz1.jpg");
addChild(weighty3);
weighty3->setTitle(L"Хиря3");
weighty3->setX(300);
weighty3->setY(610);
weighty3->setWeight(100.23);
Weighty* cat = new Weighty("cat", "cat.jpg");
addChild(cat);
cat->setTitle(L"Кiт");
cat->setX(400);
cat->setY(610);
cat->setWeight(15);
weights.push_back(weighty);
weights.push_back(weighty2);
weights.push_back(weighty3);
weights.push_back(cat);
menuButton = new Button{"menuButton", "menuButton.png"};
addChild(menuButton);
menuButton->setOnClickCallback([&state=state]() {
state = SceneState::EXIT_TO_MENU;
});
menuButton->setX(1190);
menuButton->setY(10);
}
void GameModule::Game::loop() {}
void Game::OnLButtonUp(int mX, int mY) {
auto childs = getChilds();
for (size_t i = 1; i < childs.size(); ++i) {
if (abs(childs[i - 1]->getX() - childs[i]->getX()) < 3 &&
abs(childs[i - 1]->getY() - childs[i]->getY()) < 3) {
childs[i]->setX(childs[i]->getX() + 30);
childs[i]->setY(childs[i]->getY() + 30);
}
}
}
void GameModule::Game::setState(SceneState state) {
this->state = state;
}
std::vector<Weighty*>& GameModule::Game::getWeights() {
return weights;
}
SceneState GameModule::Game::getState() {
return state;
}
void GameModule::Game::render() {
SDL_Rect screenSize{0, 0, 1280, 720};
SDL_RenderCopy(renderer, bg, &screenSize, NULL);
}
void GameModule::Game::OnExit() {
state = SceneState::EXIT;
}
<file_sep>#pragma once
#include "EngineModule/Actor.h"
#include <SDL.h>
#include <SDL_ttf.h>
namespace GameModule {
class Weighty : public EngineModule::Actor {
public:
Weighty(std::string nodeName, std::string imageName);
void init(std::string imageName);
void render() override;
void onDestroy() override;
void setWeight(float val);
void setTitle(std::wstring title);
float getWeight();
std::wstring getTitle();
void OnLButtonDown(int mX, int mY) override;
void OnLButtonUp(int mX, int mY) override;
void OnMouseMove(int mX,
int mY,
int relX,
int relY,
bool Left,
bool Right,
bool Middle) override;
private:
bool isForward;
SDL_Texture* titleTx;
SDL_Texture* weighTx;
std::wstring title;
SDL_Texture* sprite;
float weight;
};
} // namespace GameModule<file_sep>#pragma once
#include <SDL.h>
#include <vector>
#include "EngineModule/Actor.h"
namespace GameModule {
enum class SceneState;
class Balancer;
class Weighty;
class Button;
class Game : public EngineModule::Actor {
public:
Game(std::string name);
void init();
void loop();
void render();
void OnExit() override;
void OnLButtonUp(int mX, int mY) override;
void setState(SceneState);
std::vector<Weighty*>& getWeights();
SceneState getState();
private:
SceneState state;
Button* menuButton;
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Texture* bg;
Balancer* balancer;
std::vector<Weighty*> weights;
};
} // namespace GameModule<file_sep># Weigher-SDL
Приложение весы на с++(MSVC) с использованием графического движка SDL
<file_sep>#include "Weighty.h"
#include <SDL_image.h>
#include "EngineModule/Viewport.h"
using namespace GameModule;
GameModule::Weighty::Weighty(std::string nodeName, std::string imageName)
: Actor{nodeName} {
isForward = false;
init(imageName);
}
void GameModule::Weighty::init(std::string imageName) {
if (TTF_Init() < 0) {
std::cerr << "[WARNING]: Failed to init TTF: " << TTF_GetError();
}
std::string path = "Resource/" + imageName;
SDL_Surface* weigSurf = IMG_Load(path.c_str());
if (!weigSurf) {
std::cerr << "[WARNING]: Failed to load image: " << imageName;
} else {
sprite = SDL_CreateTextureFromSurface(
EngineModule::Viewport::getRenderer(), weigSurf);
setSizeX(weigSurf->w);
setSizeY(weigSurf->h);
SDL_FreeSurface(weigSurf);
}
setTitle(L"Весы");
setWeight(0);
setX(50);
setY(50);
setSizeX(80);
setSizeY(80);
}
void GameModule::Weighty::render() {
SDL_Rect outline{getX() - 3, getY() - 3, 80 + 6, 80 + 6};
SDL_SetRenderDrawColor(
EngineModule::Viewport::getRenderer(), 80, 80, 80, 255);
SDL_RenderFillRect(EngineModule::Viewport::getRenderer(), &outline);
int W, H;
SDL_QueryTexture(sprite, NULL, NULL, &W, &H);
SDL_Rect srcTX{0, 0, W, H};
SDL_Rect destTX{getX(), getY(), getSizeX(), getSizeY()};
SDL_RenderCopy(
EngineModule::Viewport::getRenderer(), sprite, &srcTX, &destTX);
SDL_QueryTexture(titleTx, NULL, NULL, &W, &H);
SDL_Rect srcTitle{0, 0, W, H};
SDL_Rect dstTitle{getX(), getY() - H - 3, W, H};
SDL_RenderCopy(
EngineModule::Viewport::getRenderer(), titleTx, &srcTitle, &dstTitle);
SDL_QueryTexture(weighTx, NULL, NULL, &W, &H);
SDL_Rect srcWg{ 0, 0, W, H };
SDL_Rect dstWg{ getX(), getY() + getSizeY()+ 3, W, H };
SDL_RenderCopy(
EngineModule::Viewport::getRenderer(), weighTx, &srcWg, &dstWg);
}
void GameModule::Weighty::onDestroy() {}
void GameModule::Weighty::setWeight(float val) {
weight = val;
TTF_Font* font = TTF_OpenFont("Resource/mariad.OTF", 16);
if (!font) {
std::cerr << "[WARNING]: Failed to load font: " << TTF_GetError();
}
int Kg = (int)weight;
int Gr = (int)(weight * 100) % 100;
std::string str = std::to_string(Kg);
str += "." + std::to_string(Gr);
SDL_Surface* wgSurf = TTF_RenderText_Solid(font, str.c_str(), SDL_Color{ 255, 255, 255 });
weighTx = SDL_CreateTextureFromSurface(
EngineModule::Viewport::getRenderer(), wgSurf);
SDL_FreeSurface(wgSurf);
TTF_CloseFont(font);
}
void GameModule::Weighty::setTitle(std::wstring title) {
this->title = title;
TTF_Font* font = TTF_OpenFont("Resource/mariad.OTF", 16);
if (!font) {
std::cerr << "[WARNING]: Failed to load font: " << TTF_GetError();
}
SDL_Surface* titleSurf = TTF_RenderUNICODE_Blended(
font,
reinterpret_cast<Uint16 const*>(title.c_str()),
SDL_Color{255, 255, 255});
titleTx = SDL_CreateTextureFromSurface(
EngineModule::Viewport::getRenderer(), titleSurf);
SDL_FreeSurface(titleSurf);
TTF_CloseFont(font);
}
float GameModule::Weighty::getWeight() {
return weight;
}
std::wstring GameModule::Weighty::getTitle() {
return title;
}
void GameModule::Weighty::OnLButtonDown(int mX, int mY) {
if (getX() < mX && mX < getX() + 80) {
if (getY() < mY && mY < getY() + 80) {
isForward = true;
}
}
}
void GameModule::Weighty::OnLButtonUp(int mX, int mY) {
isForward = false;
}
void GameModule::Weighty::OnMouseMove(
int mX, int mY, int relX, int relY, bool Left, bool Right, bool Middle) {
if (isForward) {
setX(mX - 80 / 2);
setY(mY - 80 / 2);
}
}
<file_sep>#include "Balancer.h"
#include <SDL_image.h>
#include "EngineModule/Viewport.h"
#include "GameModule/Game.h"
#include "GameModule/Weighty.h"
using namespace GameModule;
GameModule::Balancer::Balancer(std::string nodeName, Game* game)
: Actor{nodeName}, game{game} {
weight1 = 0;
weight2 = 0;
init();
}
void GameModule::Balancer::init() {
if (TTF_Init() < 0) {
std::cerr << "[WARNING]: Failed to init TTF: " << TTF_GetError();
}
SDL_Surface* balancerSurf = IMG_Load("Resource/Balancer.png");
balancerTX = SDL_CreateTextureFromSurface(
EngineModule::Viewport::getRenderer(), balancerSurf);
SDL_FreeSurface(balancerSurf);
int screenW;
int screenH;
SDL_GetWindowSize(EngineModule::Viewport::getWindow(), &screenW, &screenH);
setSizeX(balancerSurf->w);
setSizeY(balancerSurf->h);
setX(screenW / 2 - getSizeX() / 2);
setY(screenH / 2 + getSizeY() / 2 - 60);
cupArea = {283, 10, 340, 400};
cup2Area = {655, 10, 340, 400};
initTextureFromWeight();
}
void GameModule::Balancer::render() {
SDL_Rect srcTX{0, 0, getSizeX(), getSizeY()};
SDL_Rect destTX{getX(), getY(), getSizeX(), getSizeY()};
SDL_RenderCopy(
EngineModule::Viewport::getRenderer(), balancerTX, &srcTX, &destTX);
SDL_SetRenderDrawColor(
EngineModule::Viewport::getRenderer(), 230, 10, 10, 255);
SDL_RenderDrawRect(EngineModule::Viewport::getRenderer(), &cupArea);
SDL_RenderDrawRect(EngineModule::Viewport::getRenderer(), &cup2Area);
int W, H;
SDL_QueryTexture(weight1Tx, NULL, NULL, &W, &H);
SDL_Rect srcWg1{0, 0, W, H};
SDL_Rect destWg1{490, 467, W, H};
SDL_RenderCopy(
EngineModule::Viewport::getRenderer(), weight1Tx, &srcWg1, &destWg1);
}
void GameModule::Balancer::OnLButtonUp(int mX, int mY) {
weighCups();
}
void GameModule::Balancer::weighCups() {
std::vector<Weighty*> weights = game->getWeights();
weight1 = 0;
weight2 = 0;
for (auto wg : weights) {
if (!(wg->getX() + wg->getSizeX() < cupArea.x ||
wg->getY() + wg->getSizeY() < cupArea.y ||
wg->getX() > cupArea.x + cupArea.w ||
wg->getY() > cupArea.y + cupArea.h)) {
weight1 += wg->getWeight();
}
if (!(wg->getX() + wg->getSizeX() < cup2Area.x ||
wg->getY() + wg->getSizeY() < cup2Area.y ||
wg->getX() > cup2Area.x + cup2Area.w ||
wg->getY() > cup2Area.y + cup2Area.h)) {
weight2 += wg->getWeight();
}
}
initTextureFromWeight();
}
void GameModule::Balancer::initTextureFromWeight() {
TTF_Font* font = TTF_OpenFont("Resource/mariad.OTF", 40);
if (!font) {
std::cerr << "[WARNING]: Failed to load font: " << TTF_GetError();
}
int Kg = (int)weight1;
int Gr = (int)(weight1 * 100) % 100;
std::string str = std::to_string(Kg);
str += "." + std::to_string(Gr);
if (weight1 < weight2) {
str += " < ";
}else if (weight1 > weight2) {
str += " > ";
}
else {
str += " = ";
}
Kg = (int)weight2;
Gr = (int)(weight2 * 100) % 100;
str += std::to_string(Kg);
str += "." + std::to_string(Gr);
SDL_Surface* weightSurf =
TTF_RenderText_Solid(font, str.c_str(), SDL_Color{0, 0, 0});
weight1Tx = SDL_CreateTextureFromSurface(
EngineModule::Viewport::getRenderer(), weightSurf);
TTF_CloseFont(font);
SDL_FreeSurface(weightSurf);
}
<file_sep>#pragma once
namespace GameModule {
enum class SceneState
{
EXIT, PLAY_GAME, NOTHING, EXIT_TO_MENU, CONFIRM
};
};<file_sep>#pragma once
#include "EngineModule/Actor.h"
#include <SDL.h>
namespace GameModule {
class Weighty;
class Game;
class Balancer : public EngineModule::Actor {
public:
Balancer(std::string nodeName, Game* game);
void init();
void render() override;
void OnLButtonUp(int mX, int mY) override;
void weighCups();
void initTextureFromWeight();
private:
SDL_Texture* balancerTX;
SDL_Renderer* renderer;
Game* game;
float weight1;
float weight2;
char compareSign;
SDL_Texture* weight1Tx;
SDL_Texture* weight2Tx;
SDL_Rect cupArea;
SDL_Rect cup2Area;
};
} // namespace GameModule<file_sep>#include "Button.h"
#include <SDL_image.h>
#include "EngineModule/Viewport.h"
using namespace GameModule;
GameModule::Button::Button(std::string nodeName, std::string spriteName) : Actor{nodeName} {
init(spriteName);
}
void GameModule::Button::init(std::string spriteName) {
std::string path = "Resource/" + spriteName;
SDL_Surface* buttonSurf = IMG_Load(path.c_str());
sprite = SDL_CreateTextureFromSurface(EngineModule::Viewport::getRenderer(),
buttonSurf);
SDL_FreeSurface(buttonSurf);
setX(20);
setY(600);
setSizeX(buttonSurf->w);
setSizeY(buttonSurf->h);
}
void GameModule::Button::setOnClickCallback(std::function<void()> function) {
callback = function;
}
void GameModule::Button::OnLButtonDown(int mX, int mY) {
if (callback != nullptr && getX() < mX && mX < getX() + getSizeX() && getY() < mY && mY < getY() + getSizeY()) {
callback();
}
}
void GameModule::Button::render() {
SDL_Rect srcWg1{0, 0, getSizeX(), getSizeY()};
SDL_Rect destWg1{getX(), getY(), getSizeX(), getSizeY()};
SDL_RenderCopy(
EngineModule::Viewport::getRenderer(), sprite, &srcWg1, &destWg1);
}
<file_sep>#include "TransformComponent.h"
using namespace EngineModule;
void TransformComponent::setX(float val) {
pos.first = val;
}
void EngineModule::TransformComponent::setY(float val) {
pos.second = val;
}
void EngineModule::TransformComponent::setScaleX(float val) {
scale.first = val;
}
void EngineModule::TransformComponent::setScaleY(float val) {
scale.second = val;
}
void EngineModule::TransformComponent::setSizeX(float val) {
size.first = val;
}
void EngineModule::TransformComponent::setSizeY(float val) {
size.second = val;
}
float EngineModule::TransformComponent::getX() {
return pos.first;
}
float EngineModule::TransformComponent::getY() {
return pos.second;
}
float EngineModule::TransformComponent::getScaleX() {
return scale.first;
}
float EngineModule::TransformComponent::getScaleY() {
return scale.second;
}
float EngineModule::TransformComponent::getSizeX() {
return size.first;
}
float EngineModule::TransformComponent::getSizeY() {
return size.second;
}
std::pair<float, float> TransformComponent::getPos() const {
return pos;
}
std::pair<float, float> TransformComponent::getScale() const {
return scale;
}
std::pair<float, float> TransformComponent::getSize() const {
return size;
}
<file_sep>// SDL2 Hello, World!
// This should display a white screen for 2 seconds
// compile with: clang++ main.cpp -o hello_sdl2 -lSDL2
// run with: ./hello_sdl2
#include <stdio.h>
#include "EngineModule/Actor.h"
#include "EngineModule/Root.h"
#include "EngineModule/Viewport.h"
#include "GameModule/Game.h"
#include "GameModule/Menu.h"
#include "GameModule/EStates.h"
using namespace EngineModule;
using namespace GameModule;
#define SCREEN_WIDTH 1280
#define SCREEN_HEIGHT 720
void mainRender(Actor* actor) {
// Если объект не активен, то он и его наследники не рендерятся
if (!actor->getActive()) {
return;
}
actor->render();
for (const auto& child : actor->getChilds()) {
mainRender(child);
}
}
// Обход по всем объектам в дереве
void mainEventLoop(Actor* actor, SDL_Event* e) {
// Если объект не активен, то он и его наследники не реагируют на события
if (!actor->getActive()) {
return;
}
actor->OnEvent(e);
for (const auto& child : actor->getChilds()) {
mainEventLoop(child, e);
}
}
int main(int argc, char* args[]) {
setlocale(LC_ALL, "Russian");
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
std::cerr << "[ERROR]: failed to init SDL\n";
return -1;
}
if (Viewport::init("Balancer", SCREEN_WIDTH, SCREEN_HEIGHT) < 0) {
std::cerr << "[ERROR]: failed to create window\n";
return -1;
}
SDL_Window* window{Viewport::getWindow()};
SDL_Renderer* renderer{Viewport::getRenderer()};
SDL_Event Event;
Root* storage{Root::getRoot()};
Actor* root{storage->getRoot()};
bool quit{};
Menu menu{"menu"};
root->addChild(&menu);
Game game{"game"};
game.setActive(false);
root->addChild(&game);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
while (!quit) {
switch (menu.getState()) {
case SceneState::EXIT: {
quit = true;
break;
}
case SceneState::PLAY_GAME: {
menu.setActive(false);
game.setActive(true);
switch (game.getState()) {
case SceneState::EXIT_TO_MENU: {
menu.setActive(true);
menu.setState(SceneState::NOTHING);
game.setActive(false);
break;
}
case SceneState::EXIT: {
quit = true;
break;
}
}
game.setState(SceneState::NOTHING);
break;
}
}
while (SDL_PollEvent(&Event) != 0) {
mainEventLoop(root, &Event);
}
SDL_RenderClear(renderer);
mainRender(root);
SDL_RenderPresent(renderer);
SDL_Delay(30.3);
}
SDL_Quit();
return 0;
}
<file_sep>#include "Menu.h"
#include "GameModule/Button.h"
#include "EngineModule/Viewport.h"
#include <SDL_image.h>
#include "GameModule/EStates.h"
using namespace GameModule;
GameModule::Menu::Menu(std::string nodeName)
: Actor{nodeName}, state{SceneState::NOTHING} {
init();
}
void GameModule::Menu::init() {
SDL_Surface* windowSurface = IMG_Load("Resource\\bgMenu.jpg");
printf("%s \n", IMG_GetError());
bg = SDL_CreateTextureFromSurface(EngineModule::Viewport::getRenderer(),
windowSurface);
SDL_FreeSurface(windowSurface);
SDL_Surface* logoSurface = IMG_Load("Resource\\logo.png");
printf("%s \n", IMG_GetError());
logo = SDL_CreateTextureFromSurface(EngineModule::Viewport::getRenderer(),
logoSurface);
SDL_FreeSurface(logoSurface);
start = new Button{"start", "start.png"};
addChild(start);
int w, h;
SDL_GetWindowSize(EngineModule::Viewport::getWindow(), &w, &h);
start->setX(w / 5);
start->setY(h / 3);
start->setOnClickCallback([this]() {
this->setState(SceneState::PLAY_GAME);
});
exit = new Button{"exit", "exit.png"};
addChild(exit);
exit->setX(w / 5);
exit->setY(h / 2);
exit->setOnClickCallback([this]() {
this->setState(SceneState::CONFIRM);
});
yes = new Button{"yes", "yes.png"};
addChild(yes);
yes->setX(w / 3);
yes->setY(h / 2);
yes->setOnClickCallback([this]() {
this->setState(SceneState::EXIT);
});
no = new Button{ "no", "no.png" };
addChild(no);
no->setX(w / 2);
no->setY(h / 2);
no->setOnClickCallback([this]() {
this->setState(SceneState::NOTHING);
});
}
void GameModule::Menu::render() {
SDL_Rect screenSize{ 0, 0, 1280, 720 };
SDL_RenderCopy(
EngineModule::Viewport::getRenderer(), bg, &screenSize, NULL);
int w, h;
SDL_QueryTexture(logo, NULL, NULL, &w, &h);
SDL_Rect srcRect{ 0, 0, w, h };
SDL_Rect destRect{ start->getX() - 20, start->getY() - 2*h, w, h };
SDL_RenderCopy(
EngineModule::Viewport::getRenderer(), logo, &screenSize, &destRect);
if (state == SceneState::CONFIRM) {
start->setActive(false);
exit->setActive(false);
yes->setActive(true);
no->setActive(true);
return;
}
start->setActive(true);
exit->setActive(true);
yes->setActive(false);
no->setActive(false);
}
void GameModule::Menu::OnExit() {
state = SceneState::EXIT;
}
void GameModule::Menu::setState(SceneState val) {
state = val;
}
SceneState GameModule::Menu::getState() {
return state;
}
<file_sep>/*
* Documentation
* https://wiki.libsdl.org/SDL_Event
*/
#pragma once
#include <SDL.h>
namespace EngineModule {
class EventComponent {
protected:
EventComponent();
public:
virtual ~EventComponent();
virtual void OnEvent(SDL_Event* Event);
virtual void OnInputFocus();
virtual void OnInputBlur();
virtual void OnKeyDown(SDL_Keycode sym, Uint16 mod);
virtual void OnKeyUp(SDL_Keycode sym, Uint16 mod);
virtual void OnMouseFocus();
virtual void OnMouseBlur();
virtual void OnMouseMove(int mX,
int mY,
int relX,
int relY,
bool Left,
bool Right,
bool Middle);
virtual void OnLButtonDown(int mX, int mY);
virtual void OnLButtonUp(int mX, int mY);
virtual void OnRButtonDown(int mX, int mY);
virtual void OnRButtonUp(int mX, int mY);
virtual void OnMButtonDown(int mX, int mY);
virtual void OnMButtonUp(int mX, int mY);
virtual void OnMinimize();
virtual void OnRestore();
virtual void OnResize(int winId, int w, int h);
virtual void OnExpose();
virtual void OnExit();
virtual void OnUser(Uint8 type, int code, void* data1, void* data2);
};
} // namespace EngineModule<file_sep>#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <SDL.h>
#include "EngineModule/TransformComponent.h"
#include "EngineModule/EventComponent.h"
namespace EngineModule {
class Actor : public TransformComponent, public EventComponent {
protected:
Actor(std::string nodeName);
Actor(const Actor&) = delete;
Actor(const Actor&&) = delete;
public:
virtual void onDestroy();
virtual void render();
~Actor();
void destroy();
void addChild(Actor* newChild);
void removeChild(Actor* child);
Actor* find(std::string name) const;
Actor* find(Actor* actor) const;
void setParent(Actor* newParent);
void setActive(bool val);
bool getActive() const;
Actor* getParent() const;
std::string getName() const;
std::vector<Actor*>& getChilds();
private:
bool isActive;
Actor* parent;
std::string name;
std::vector<Actor*> childs;
};
} // namespace EngineModule<file_sep>#include "Viewport.h"
using namespace EngineModule;
SDL_Window* Viewport::window{};
SDL_Renderer* Viewport::renderer{};
int EngineModule::Viewport::init(std::string windowName, int w, int h) {
if (!window) {
window = SDL_CreateWindow("Balancer",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
w,
h,
SDL_WINDOW_SHOWN);
}
if (!window) {
return -1;
}
if (!renderer) {
renderer = SDL_CreateRenderer(window, -1, 0);
}
}
SDL_Window* Viewport::getWindow() {
return window;
}
SDL_Renderer* EngineModule::Viewport::getRenderer()
{
return renderer;
}
<file_sep>#pragma once
#include <SDL.h>
#include <string>
namespace EngineModule {
class Viewport {
Viewport();
public:
static int init(std::string windowName, int w, int h);
static SDL_Window* getWindow();
static SDL_Renderer* getRenderer();
private:
static SDL_Window* window;
static SDL_Renderer* renderer;
};
} // namespace EngineModule
<file_sep>#include "EventComponent.h"
using namespace EngineModule;
EngineModule::EventComponent::EventComponent() {}
EngineModule::EventComponent::~EventComponent() {}
void EngineModule::EventComponent::OnEvent(SDL_Event* Event) {
switch (Event->type) {
case SDL_KEYDOWN: {
OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod);
break;
}
case SDL_KEYUP: {
OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod);
break;
}
case SDL_MOUSEMOTION: {
OnMouseMove(
Event->motion.x,
Event->motion.y,
Event->motion.xrel,
Event->motion.yrel,
(Event->motion.state & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0,
(Event->motion.state & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0,
(Event->motion.state & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0);
break;
}
case SDL_MOUSEBUTTONDOWN: {
switch (Event->button.button) {
case SDL_BUTTON_LEFT: {
OnLButtonDown(Event->button.x, Event->button.y);
break;
}
case SDL_BUTTON_RIGHT: {
OnRButtonDown(Event->button.x, Event->button.y);
break;
}
case SDL_BUTTON_MIDDLE: {
OnMButtonDown(Event->button.x, Event->button.y);
break;
}
}
break;
}
case SDL_MOUSEBUTTONUP: {
switch (Event->button.button) {
case SDL_BUTTON_LEFT: {
OnLButtonUp(Event->button.x, Event->button.y);
break;
}
case SDL_BUTTON_RIGHT: {
OnRButtonUp(Event->button.x, Event->button.y);
break;
}
case SDL_BUTTON_MIDDLE: {
OnMButtonUp(Event->button.x, Event->button.y);
break;
}
}
break;
}
case SDL_QUIT: {
OnExit();
break;
}
case SDL_SYSWMEVENT: {
// Ignore
break;
}
case SDL_WINDOWEVENT: {
switch (Event->window.event) {
case SDL_WINDOWEVENT_RESIZED:
OnResize(Event->window.windowID,
Event->window.data1,
Event->window.data2);
case SDL_WINDOWEVENT_FOCUS_GAINED: {
OnInputFocus();
}
case SDL_WINDOWEVENT_FOCUS_LOST: {
OnInputBlur();
}
}
break;
}
default: {
OnUser(Event->user.type,
Event->user.code,
Event->user.data1,
Event->user.data2);
break;
}
}
}
void EngineModule::EventComponent::OnInputFocus() {}
void EngineModule::EventComponent::OnInputBlur() {}
void EngineModule::EventComponent::OnKeyDown(SDL_Keycode sym, Uint16 mod) {}
void EngineModule::EventComponent::OnKeyUp(SDL_Keycode sym, Uint16 mod) {}
void EngineModule::EventComponent::OnMouseFocus() {}
void EngineModule::EventComponent::OnMouseBlur() {}
void EngineModule::EventComponent::OnMouseMove(
int mX, int mY, int relX, int relY, bool Left, bool Right, bool Middle) {}
void EngineModule::EventComponent::OnLButtonDown(int mX, int mY) {}
void EngineModule::EventComponent::OnLButtonUp(int mX, int mY) {}
void EngineModule::EventComponent::OnRButtonDown(int mX, int mY) {}
void EngineModule::EventComponent::OnRButtonUp(int mX, int mY) {}
void EngineModule::EventComponent::OnMButtonDown(int mX, int mY) {}
void EngineModule::EventComponent::OnMButtonUp(int mX, int mY) {}
void EngineModule::EventComponent::OnMinimize() {}
void EngineModule::EventComponent::OnRestore() {}
void EngineModule::EventComponent::OnResize(int winId, int w, int h) {}
void EngineModule::EventComponent::OnExpose() {}
void EngineModule::EventComponent::OnExit() {}
void EngineModule::EventComponent::OnUser(Uint8 type,
int code,
void* data1,
void* data2) {}
| bf4a5fbcfbb5ed473adfabba0e7f1557a3623153 | [
"Markdown",
"C++"
] | 19 | C++ | nselyavin/Weigher-SDL | f5dc8862f68c01127fe678ff631bb817b35cdb32 | 0209e9192c3747718a0e9116d65475b11ad2b847 |
refs/heads/master | <repo_name>msdlt/canvas<file_sep>/ebmprimer/ebmprimer.js
/*
* JS to resize H5P in a frame
*/
/*var h5pScript = document.createElement('script');
h5pScript.setAttribute('charset', 'UTF-8');
h5pScript.setAttribute('src', 'https://h5p.org/sites/all/modules/h5p/library/js/h5p-resizer.js');
document.body.appendChild(h5pScript);*/
/* Global variables */
var initCourseId = ENV.COURSE_ID;
//used in Modules page
var moduleNav;
var divCourseHomeContent = document.getElementById('course_home_content');
var divContextModulesContainer = document.getElementById('context_modules_sortable_container');
//var divContextModulesTitle = document.querySelectorAll('.context-modules-title')[0];
var divContent = document.getElementById('content');
var moduleColours = ['#e8ab1e','#91b2c6','#517f96','#1c4f68','#400b42','#293f11','#640D14','#b29295','#002147'];
var delimiter = '.' //The character used to separate your module name and module description
//From: https://stackoverflow.com/questions/4793604/how-to-insert-an-element-after-another-element-in-javascript-without-using-a-lib
function msd_insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
/* Trying plain JS so that it works in the app as well */
function msd_domReady () {
//populate progress bars
msd_showProgressBars();
if(divCourseHomeContent && divContextModulesContainer){
//we're in the modules page as a home page
//first delete any existing nav container
var existingModuleNav = document.getElementById('module_nav');
if(existingModuleNav) {
existingModuleNav.parentNode.removeChild(existingModuleNav);
}
//create our nav container
moduleNav = document.createElement("div");
moduleNav.id = "module_nav";
moduleNav.className = "ou-ModuleCard__box";
moduleNav.innerHTML = '<a id="module_nav_anchor"></a>';
divContent.insertBefore(moduleNav, divContent.childNodes[0]);
//now get modules from api
msd_getSelfThenModules();
} else if(divCourseHomeContent){
//we're in a home page
msd_rewriteModuleLinks();
msd_getSelfThenModules(); //testing
}
}
//Function to work out when the DOM is ready: https://stackoverflow.com/questions/1795089/how-can-i-detect-dom-ready-and-add-a-class-without-jquery/1795167#1795167
// Mozilla, Opera, Webkit
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false);
msd_domReady();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
msd_domReady();
}
});
}
/*
* Get self id
*/
function msd_getSelfThenModules() {
var csrfToken = msd_getCsrfToken();
fetch('/api/v1/users/self',{
method: 'GET',
credentials: 'include',
headers: {
"Accept": "application/json",
"X-CSRF-Token": csrfToken
}
})
.then(msd_status)
.then(msd_json)
.then(function(data) {
msd_getModules(initCourseId, data.id);
})
.catch(function(error) {
console.log('getSelfId Request failed', error);
}
);
}
/*
* Get modules for courseId
*/
function msd_getModules(courseId, userId) {
var csrfToken = msd_getCsrfToken();
fetch('/api/v1/courses/' + courseId + '/modules?include=items&student_id=' + userId,{
method: 'GET',
credentials: 'include',
headers: {
"Accept": "application/json",
"X-CSRF-Token": csrfToken
}
})
.then(msd_status)
.then(msd_json)
.then(function(data) {
console.log(data);
/*var newRow; //store parent row to append to between iterations
//run through each module
data.forEach(function(module, index){
//work out some properties
var moduleFullName = module.name;
var moduleNameParts = moduleFullName.split(delimiter);
var moduleName = moduleNameParts[0];
var moduleDescription = " "; //default to a non-breaking space
if(moduleNameParts.length>1) {
moduleDescription = moduleNameParts[1]; //only update moduleDescription if there's something after the separator
}
//create row for card
if(index == 0 || index == 1 || index == 4 || index == 8) {
newRow = document.createElement("div");
newRow.className = "grid-row center-sm";
moduleNav.appendChild(newRow);
}
var newColumn = document.createElement("div");
//create column wrapper
if(index == 0 || index == 8) {
newColumn.className = "col-xs-12";
} else if (index > 0 && index < 4) {
newColumn.className = "col-xs-12 col-md-4";
} else if (index > 3 && index < 8) {
newColumn.className = "col-xs-12 col-sm-6 col-lg-3";
}
newRow.appendChild(newColumn);
//create module div
var newModule = document.createElement("div");
if(index == 0 || index == 8) {
newModule.innerHTML = ''+
'<div class="ou-ModuleCard" title="' + moduleName + '">'+
' <a href="#module_' + module.id + '">'+
' <div class="ou-ModuleCard__header_hero_short" style="background-color:' + moduleColours[index] + ';" aria-hidden="true">'+
' <h2 class="ou-ModuleCard__header-title ellipsis">' + moduleName + '<span class="ou-ModuleCard__header-subtitle-short ellipsis"> ' + moduleDescription + '</span></h2>'+
' </div>'+
' </a>'+
'</div>';
} else {
newModule.innerHTML = ''+
'<div class="ou-ModuleCard" title="' + moduleName + '">'+
' <a href="#module_' + module.id + '">'+
' <div class="ou-ModuleCard__header_hero" style="background-color:' + moduleColours[index] + ';" aria-hidden="true">'+
' <h2 class="ou-ModuleCard__header-title ellipsis">Mod<span class="visible-lg-inline">ule</span> ' + index + '</h2>'+
' <div class="ou-ModuleCard__header-subtitle ellipsis">' + moduleDescription + '</div>'+
' </div>'+
' </a>'+
'</div>';
}
newColumn.appendChild(newModule);
//now remove then add top buttons to each Canvas module to take back up to menu
var topButtons = document.querySelectorAll(".ou-top_button");
topButtons.forEach(function(topButton) {
topButton.parentNode.removeChild(topButton);
});
var canvasModuleHeaders = document.querySelectorAll(".ig-header");
canvasModuleHeaders.forEach(function(canvasModuleHeader) {
newTopButton = document.createElement("a");
newTopButton.className = "btn ou-top_button";
newTopButton.href = "#module_nav_anchor";
newTopButton.innerHTML = '<i class="icon-arrow-up"></i>Top';
canvasModuleHeader.appendChild(newTopButton);
});
//try and colour in each module
var canvasModuleDiv = document.getElementById('context_module_'+module.id);
canvasModuleDiv.style.borderLeftColor = moduleColours[index];
canvasModuleDiv.style.borderLeftWidth = '10px';
canvasModuleDiv.style.borderLeftStyle = 'solid';
});*/
})
.catch(function(error) {
console.log('msd_getModules request failed', error);
}
);
}
/*
* Function which replaces all <div id="module_x" class="ou-insert-progress-bar">y</div> with graphical progress bars
* x = module number
* y = % complete
*/
function msd_showProgressBars() {
//get all elements with classname ou-insert-progress-bar
var progressBarPlaceholders = document.getElementsByClassName('ou-insert-progress-bar');
Array.prototype.forEach.call(progressBarPlaceholders, function(progressBarPlaceholder) {
var value = progressBarPlaceholder.innerHTML;
var className = progressBarPlaceholder.id;
//UC first letter
var viewName = className.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
//replace underscore with space
viewName = viewName.replace(/_/g, ' ');
//create our new element
var progressBarContainer = document.createElement("div");
progressBarContainer.innerHTML = ''+
'<h4 class="ou-space-before-progress-bar">Current position in ' + viewName + ':</h4>' +
'<div class="ou-ProgressBar ' + className + '" style="width: 100%; height: 15px;" role="progressbar" aria-valuemax="100" aria-valuemin="0" aria-valuenow="'+ value +'">' +
' <div class="ou-ProgressBarBar" style="width: '+ value +'%;" title="'+ value +'%"></div>' +
'</div>';
//insert it after the placeholder using the function msd_insertAfter
msd_insertAfter(progressBarContainer, progressBarPlaceholder);
//now delete the placeholder
progressBarPlaceholder.parentNode.removeChild(progressBarPlaceholder);
});
}
function msd_rewriteModuleLinks() {
/* START rewriting links to go to Modules anchor */
var moduleLinks = document.getElementsByTagName('a'), i;
for (i in moduleLinks) {
var cn = moduleLinks[i].className;
var matchClass = "ou-ModuleLink";
if(cn && cn.match(new RegExp("(^|\\s)" + matchClass + "(\\s|$)"))) {
moduleLinks[i].onclick = function(event) {
var destination = event.currentTarget.href; //attached to the a, even if user clicked something inside the a
var destinationParts = destination.split('/');
j=0;
while (destinationParts[j]!="modules"){
j=j+1;
}
var moduleId = destinationParts[j + 1];
window.location = '/courses/' + initCourseId + "/modules" + "#module_" + moduleId;
return false; //prevent default
}
}
}
}
/* Utility functions */
/*
* Function which returns a promise (and error if rejected) if response status is OK
*/
function msd_status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
/*
* Function which returns json from response
*/
function msd_json(response) {
return response.json()
}
/*
* Function which returns csrf_token from cookie see: https://community.canvaslms.com/thread/22500-mobile-javascript-development
*/
function msd_getCsrfToken() {
var csrfRegex = new RegExp('^_csrf_token=(.*)$');
var csrf;
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
var match = csrfRegex.exec(cookie);
if (match) {
csrf = decodeURIComponent(match[1]);
break;
}
}
return csrf;
}<file_sep>/menu-demo/menu_demo_web.js
/**
* This JavaScript file contains js to create a rh menu in Instructure Canvas
*
* @projectname OU Canvas Menu
* @version 0.1
* @author <NAME>
*
*/
/* Global variables */
var courseId = getCourseId(); //which course are we in
var moduleItemId = getParameterByName('module_item_id'); //used to id active page where data aren't in ENV
var divPageTitle = document.querySelectorAll('.page-title')[0];
/* list of pages to exclude from menu-showing */
/*Note that Conferences, Collaborations, Chat and Attendance pages don't expose ENV.COURSE_ID (although does have ENV.course_id) so menu won't be shown anyway...so no need to exclude */
var dontShowMenuOnTheseElementIds=new Array(
'course_home_content', //Home page
'context_modules', //Modules page
'course_details_tabs' //Settings page
);
var dontShowMenuOnTheseElementClasses=new Array(
'discussion-collections', //Discussions page
'announcements-v2__wrapper', //Announcements page
'ef-main', //Files page
'edit-content' //editing a wiki page
);
/* list of pages where we want menu in right-side-wrapper */
var putMenuInRightSideOnTheseElementIds=new Array(
'discussion_container', //showing a discussion
'quiz_show', //showing a quiz
'assignment_show' //showing an asignment
);
var divContent = document.getElementById('content');
/* Trying plain JS so that it works in the app as well */
function domReady () {
if(divContent && courseId && elementsWithTheseIdsDontExist(dontShowMenuOnTheseElementIds) && elementsWithTheseClassesDontExist(dontShowMenuOnTheseElementClasses)){ //&& courseId==2777 && moduleItemId
getSelfThenModulesForPage();
}
}
/**
* Get self id
*/
function getSelfThenModulesForPage() {
var csrfToken = getCsrfToken();
fetch('/api/v1/users/self',{
method: 'GET',
credentials: 'include',
headers: {
"Accept": "application/json",
"X-CSRF-Token": csrfToken
}
})
.then(status)
.then(json)
.then(function(data) {
getModulesForPage(courseId, data.id);
})
.catch(function(error) {
console.log('getSelfId Request failed', error);
}
);
}
/*
* Do any elements with these ids exist in the document
* @param {string} ids[] - ids to look for
* @returns {boolean}
*/
function elementsWithTheseIdsDontExist(ids) {
for(var i = 0; i < ids.length; i++) {
if(document.getElementById(ids[i])!==null){
return false; //it does exist
}
}
return true;
}
/*
* Do any elements with these classes exist in the document
* @param {string} classes[] - classes to look for
* @returns {boolean}
*/
function elementsWithTheseClassesDontExist(classes) {
for(var i = 0; i < classes.length; i++) {
console.log(classes[i]);
console.log(document.querySelectorAll('.'+classes[i]));
if(document.querySelectorAll('.'+classes[i]).length!==0){
return false; //it does exist
}
}
return true;
}
/*
* Get modules and items for courseId
* @param {number} courseId - ID of course
* @param {number} userId - ID of user - used to return progress info.
* TODO make userId optional
*/
function getModulesForPage(courseId, userId) {
var csrfToken = getCsrfToken();
fetch('/api/v1/courses/' + courseId + '/modules?include=items&student_id=' + userId,{
method: 'GET',
credentials: 'include',
headers: {
"Accept": "application/json",
"X-CSRF-Token": csrfToken
}
})
.then(status)
.then(json)
.then(function(data) {
if(elementsWithTheseIdsDontExist(putMenuInRightSideOnTheseElementIds)) {
/* In most cases, create a new column for the menu: creating a content-wrapper and moving divContent into it*/
var divContentWrapper = document.createElement('div');
divContentWrapper.className = "ou-content-wrapper grid-row";
divContent.classList.add("col-xs-12");
divContent.classList.add("col-sm-9");
divContent.classList.add("col-lg-10");
divContent.classList.add("col-xl-11");
wrap(divContent, divContentWrapper);
//now add divMenuWrapper
var divMenuWrapper = document.createElement('div');
divMenuWrapper.classList.add("ou-menu-wrapper");
divMenuWrapper.classList.add("col-xs-12");
divMenuWrapper.classList.add("col-sm-3");
divMenuWrapper.classList.add("col-lg-2");
divMenuWrapper.classList.add("col-xl-1");
divContentWrapper.appendChild(divMenuWrapper); //add module to content
} else {
/* Where page contains div with id in putMenuInRightSideOnTheseElementIds, append the menu to div#right-side-wrapper */
//TODO use a combination of ENV variables OR div ids and classes to reduce breakages on interface change
var divRightSideWrapper = document.getElementById('right-side-wrapper');
//now add divMenuWrapper
var divMenuWrapper = document.createElement('div');
divMenuWrapper.classList.add("ou-menu-wrapper-in-right-side");
divRightSideWrapper.appendChild(divMenuWrapper); //add module to content
}
//adding click event listener to divMenuWrapper to ensure it is there
//menu items themselves won't exist yet
divMenuWrapper.addEventListener('click',function(e){
if(e.target && (e.target.className.match(/\bou-menu-module-title\b/) || e.target.className.match(/\bou-menu-module-arrow\b/))){
//click on either div with class=ou-module-title or <i> class=ou-module-arrow
var moduleId = e.target.getAttribute('data-module-id');
var targetItemsId = 'ouModuleItemsWrappper_' + moduleId;
var targetItemsElement = document.getElementById(targetItemsId);
targetItemsElement.classList.toggle('is-visible');
var targetArrowId = 'ouModuleTitleArrow_' + moduleId;
var targetArrowElement = document.getElementById(targetArrowId);
if(targetArrowElement.classList.contains('icon-mini-arrow-right')) {
targetArrowElement.classList.remove('icon-mini-arrow-right')
targetArrowElement.classList.add('icon-mini-arrow-down');
} else {
targetArrowElement.classList.remove('icon-mini-arrow-down')
targetArrowElement.classList.add('icon-mini-arrow-right');
}
}
})
//run through each module
data.forEach(function(module, index){
//work out some properties
var moduleName = module.name;
var moduleId = module.id;
//create module div
var newModule = document.createElement('div');
newModule.className = 'ou-module-wrapper';
//div for module name and arrow
var newModuleName = document.createElement('div');
newModuleName.className = 'ou-menu-module-title';
newModuleName.setAttribute('title', moduleName);
newModuleName.setAttribute('data-module-id', moduleId);
//i for arrow
var newModuleArrow = document.createElement('i');
newModuleArrow.classList.add('icon-mini-arrow-right');
newModuleArrow.classList.add('ou-menu-module-arrow');
newModuleArrow.setAttribute('id', 'ouModuleTitleArrow_' + moduleId);
newModuleArrow.setAttribute('data-module-id', moduleId);
newModuleName.appendChild(newModuleArrow);
newModuleName.appendChild(document.createTextNode(moduleName));
newModule.appendChild(newModuleName); //add module name to module wrapper
//newModule.innerHTML = '<div class="ou-menu-module-title" title="' + moduleName + '" data-module-id="' + moduleId + '"><i id="ouModuleTitleArrow_' + moduleId + '" class="icon-mini-arrow-right ou-menu-module-arrow" data-module-id="' + moduleId + '"></i> ' + moduleName + '</div>';
var moduleItemsWrapper = document.createElement('div');
moduleItemsWrapper.className = 'toggle-content';
moduleItemsWrapper.id = 'ouModuleItemsWrappper_'+moduleId;
newModule.appendChild(moduleItemsWrapper); //add module to content
module.items.forEach(function(item, index){
var itemTitle = item.title;
var moduleId = item.module_id;
var itemId = item.id;
var itemType = item.type;
var iconType;
switch(itemType) {
case "Page":
iconType = "icon-document";
break;
case "File":
iconType = "icon-paperclip";
break;
case "Discussion":
iconType = "icon-discussion";
break;
case "Quiz":
iconType = "icon-quiz";
break;
case "Assignment":
iconType = "icon-assignment";
break;
default:
iconType = "icon-document";
}
var newItem = document.createElement('div');
newItem.className = 'ou-menu-item-wrapper';
var itemLink = 'https://yourinstitution.instructure.com/courses/' + courseId + '/modules/items/' + itemId; //construct hopefully app-compatible URL
newItem.innerHTML = '<a class="'+iconType+'" title="'+itemTitle+'" href="'+itemLink+'">'+itemTitle+'</a>';
moduleItemsWrapper.appendChild(newItem); //add item to module
/* Check if this is the live item and leave menu open if it is */
var activateIt = false;
if(ENV.WIKI_PAGE){
//we're in a wiki page
if(item.page_url){
//we're processing a wiki page
if(ENV.WIKI_PAGE.url==item.page_url) {
activateIt = true;
}
}
} else if (ENV.DISCUSSION && ENV.DISCUSSION.TOPIC) {
//we're in a discussion
if(item.content_id){
//we're processing a discussion page
if(ENV.DISCUSSION.TOPIC.ID==item.content_id) {
activateIt = true;
}
}
} else if (ENV.QUIZ) {
//we're in a quiz/survey
if(item.content_id){
//we're processing a quiz/survey page
if(ENV.QUIZ.id==item.content_id) {
activateIt = true;
}
}
} else if (ENV.ASSIGNMENT_ID) {
//we're in an assignment
if(item.content_id){
//we're processing an assignment
if(ENV.ASSIGNMENT_ID==item.content_id) {
activateIt = true;
}
}
} else if (moduleItemId && parseInt(moduleItemId)===parseInt(item.id)) {
//we're in something else but inside a module
activateIt = true;
}
if(activateIt){
/* open relevenat module and highlight active item */
moduleItemsWrapper.classList.add('is-visible');
newItem.classList.add('ou-menu-item-active');
/* change module arrow from right to down */
newModuleArrow.classList.remove('icon-mini-arrow-right')
newModuleArrow.classList.add('icon-mini-arrow-down');
}
});
divMenuWrapper.appendChild(newModule); //add module to menu
});
})
.catch(function(error) {
console.log('getModules request failed', error);
}
);
}
/* Utility functions */
//Function to work out when the DOM is ready: https://stackoverflow.com/questions/1795089/how-can-i-detect-dom-ready-and-add-a-class-without-jquery/1795167#1795167
// Mozilla, Opera, Webkit
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false);
domReady();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
domReady();
}
});
}
/*
* Function which returns a promise (and error if rejected) if response status is OK
*/
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
/*
* Function which returns json from response
*/
function json(response) {
return response.json()
}
/*
* Function which returns csrf_token from cookie see: https://community.canvaslms.com/thread/22500-mobile-javascript-development
*/
function getCsrfToken() {
var csrfRegex = new RegExp('^_csrf_token=(.*)$');
var csrf;
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
var match = csrfRegex.exec(cookie);
if (match) {
csrf = decodeURIComponent(match[1]);
break;
}
}
return csrf;
}
/**
* Function which wraps one element in another div - see: https://stackoverflow.com/questions/6838104/pure-javascript-method-to-wrap-content-in-a-di
* @param {element} toWrap - element to be wrapped
* @param {element} [wrapper] - element to wrap it in - new div if not provided
*/
var wrap = function (toWrap, wrapper) {
wrapper = wrapper || document.createElement('div');
toWrap.parentNode.appendChild(wrapper);
return wrapper.appendChild(toWrap);
};
/**
* Function which gets query string parameters by name - see: https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
* @param {string} name - name of query parameter
* @param {string} [url=window.location.href] - url
*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
/**
* Function which gets the course id either from the ENV or from the URL
* @returns {string} courseId or null
*/
function getCourseId() {
var courseId = ENV.COURSE_ID || ENV.course_id;
if(!courseId){
var urlPartIncludingCourseId = window.location.href.split("courses/")[1];
if(urlPartIncludingCourseId) {
courseId = urlPartIncludingCourseId.split("/")[0];
}
}
return courseId;
}<file_sep>/README.md
# canvas
Code to add a menu to Instructure Canvas sites see: https://learntech.imsu.ox.ac.uk/blog/towards-a-navigation-menu-in-instructure-canvas/
<file_sep>/allmethods/allmethods_web.js
/** Development notes
...Thinking maybe that we look for ENV.COURSE_ID and, if there, we know that we're in a course and so can just wrap div#content and place menu on right of that...
BUT maybe hide on index pages for modules, announcements, discssions, etc where we already have a RH bar...
All Canvas web pages seem to contain:
div#content
div#content-wrapper
Inside these: (child of div#content but maybe with other siblings (in brackets is ENV variable that uniquely tells us we are in the page type) foolowed by how e might get identifier for this page to match up with/modules api feed)
Home: div#course_home_content n/a
Discussions: div.discussion-collections (ENV.openTopics) n/a
Discussion: div#discussion_container (ENV.DISCUSSION) ENV.DISCUSSION.TOPIC.ID/Module | Item | content_id
Announcements: div.announcements-v2__wrapper (ENV.ANNOUNCEMENTS_LOCKED) n/a
Announcement: div#discussion_container (ENV.DISCUSSION) Don't seem to be able to add announcement to module so won't appear in modules api
Assignments: div data-view="assignmentGroups" (ENV.HAS_ASSIGNMENTS) NOTE: Assignments doesn't expose ENV.COURSE_ID so menu won't be shown!
Assignment: div#assignment_show (ENV.ASSIGNMENT_ID) ENV.ASSIGNMENT_ID/Module | Item | content_id
Grades: NOTE: Grades doesn't expose ENV.COURSE_ID so menu won't be shown!
People: NOTE: People doesn't expose ENV.COURSE_ID so menu won't be shown!
Pages: Actually quite useful to have it in Pages!
Files: div.ef-main (ENV.FILES_CONTEXTS) n/a
Syllabus: NOTE: Syllabus doesn't expose ENV.COURSE_ID so menu won't be shown!
Quizzes: Actually quite useful to have it in Quizzes!
Quiz: div#quiz_show (ENV.QUIZ) ENV.QUIZ.id/Module | Item | content_id
Modules: div#context_modules (ENV.MODULE_FILE_DETAILS) n/a
Conferences: NOTE: Conferences doesn't expose ENV.COURSE_ID so menu won't be shown!
Collaborations: NOTE: Collaborations doesn't expose ENV.COURSE_ID so menu won't be shown!
Chat: NOTE: Chat doesn't expose ENV.COURSE_ID (although does have ENV.course_id) so menu won't be shown!
Attendance: NOTE: Attendance doesn't expose ENV.COURSE_ID so menu won't be shown!
Settings: div#course_details_tabs (ENV.SETTINGS) n/a
Things which can be added to a module and may therefore appear in Modules api feed:
Assignment
Quiz
File
Content Page
Discussion
Text header
External URL
External tool
*/
/* Global variables */
var courseId = getCourseId(); //which course are we in
var moduleItemId = getParameterByName('module_item_id'); //where courseId doesn't exist
var divCourseHomeContent = document.getElementById('course_home_content');
var divPageTitle = document.querySelectorAll('.page-title')[0];
var dontShowMenuOnTheseElementIds=new Array(
'course_home_content',
'context_modules',
'course_details_tabs'
);
var dontShowMenuOnTheseElementClasses=new Array(
'discussion-collections',
'announcements-v2__wrapper',
'ef-main'
);
var putMenuInRightSideOnTheseElementIds=new Array(
'discussion_container',
'quiz_show',
'assignment_show'
);
var divContent = document.getElementById('content');
var delimiter = '.' //The character used to separate your module name and module description
//From: https://stackoverflow.com/questions/4793604/how-to-insert-an-element-after-another-element-in-javascript-without-using-a-lib
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
/* Trying plain JS so that it works in the app as well */
function domReady () {
//populate progress bars
showProgressBars();
if(divContent && courseId && courseId==2777 && elementsWithTheseIdsDontExist(dontShowMenuOnTheseElementIds) && elementsWithTheseClassesDontExist(dontShowMenuOnTheseElementClasses)){
//console.log("I'm in a course");
getSelfThenModulesForPage();
} else if(divCourseHomeContent){
//we're in a home page
rewriteModuleLinks();
}
}
//Function to work out when the DOM is ready: https://stackoverflow.com/questions/1795089/how-can-i-detect-dom-ready-and-add-a-class-without-jquery/1795167#1795167
// Mozilla, Opera, Webkit
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false);
domReady();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
domReady();
}
});
}
/**
* Get self id
*/
function getSelfThenModulesForPage() {
var csrfToken = getCsrfToken();
fetch('/api/v1/users/self',{
method: 'GET',
credentials: 'include',
headers: {
"Accept": "application/json",
"X-CSRF-Token": csrfToken
}
})
.then(status)
.then(json)
.then(function(data) {
getModulesForPage(courseId, data.id);
})
.catch(function(error) {
console.log('getSelfId Request failed', error);
}
);
}
/*
* Do any elements with these ids exist in the document
* @param {string} ids[] - ids to look for
* @returns {boolean}
*/
function elementsWithTheseIdsDontExist(ids) {
for(var i = 0; i < ids.length; i++) {
//console.log(ids[i]);
//console.log(document.getElementById(ids[i]));
if(document.getElementById(ids[i])!==null){
return false; //it does exist
}
}
return true;
}
/*
* Do any elements with these classes exist in the document
* @param {string} classes[] - classes to look for
* @returns {boolean}
*/
function elementsWithTheseClassesDontExist(classes) {
for(var i = 0; i < classes.length; i++) {
//console.log(classes[i]);
//console.log(document.querySelectorAll(classes[i])[0]);
if(document.querySelectorAll(classes[i]).length!==0){
return false; //it does exist
}
}
return true;
}
/*
* Get modules and items for courseId
* @param {number} courseId - ID of course
* @param {number} userId - ID of user - used to return progress info.
* TODO make userId optional
*/
function getModulesForPage(courseId, userId) {
var csrfToken = getCsrfToken();
fetch('/api/v1/courses/' + courseId + '/modules?include=items&student_id=' + userId,{
method: 'GET',
credentials: 'include',
headers: {
"Accept": "application/json",
"X-CSRF-Token": csrfToken
}
})
.then(status)
.then(json)
.then(function(data) {
if(elementsWithTheseIdsDontExist(putMenuInRightSideOnTheseElementIds)) {
/* In most cases, create a new column for the menu: creating a content-wrapper and moving divContent into it*/
var divContentWrapper = document.createElement('div');
divContentWrapper.className = "ou-content-wrapper grid-row";
divContent.classList.add("col-xs-12");
divContent.classList.add("col-sm-9");
divContent.classList.add("col-lg-10");
divContent.classList.add("col-xl-11");
wrap(divContent, divContentWrapper);
//now add divMenuWrapper
var divMenuWrapper = document.createElement('div');
divMenuWrapper.classList.add("ou-menu-wrapper");
divMenuWrapper.classList.add("col-xs-12");
divMenuWrapper.classList.add("col-sm-3");
divMenuWrapper.classList.add("col-lg-2");
divMenuWrapper.classList.add("col-xl-1");
divContentWrapper.appendChild(divMenuWrapper); //add module to content
} else {
/* Where page contains div with id in putMenuInRightSideOnTheseElementIds, append the menu to div#right-side-wrapper */
//TODO use a combination of ENV variables OR div ids and classes to reduce breakages on interface change
var divRightSideWrapper = document.getElementById('right-side-wrapper');
//now add divMenuWrapper
var divMenuWrapper = document.createElement('div');
divMenuWrapper.classList.add("ou-menu-wrapper-in-right-side");
divRightSideWrapper.appendChild(divMenuWrapper); //add module to content
}
//adding click event listener to divMenuWrapper to ensure it is there
//menu items themselves won't exist yet
divMenuWrapper.addEventListener('click',function(e){
if(e.target && (e.target.className.match(/\bou-menu-module-title\b/) || e.target.className.match(/\bou-menu-module-arrow\b/))){
//click on either div with class=ou-module-title or <i> class=ou-module-arrow
var moduleId = e.target.getAttribute('data-module-id');
var targetItemsId = 'ouModuleItemsWrappper_' + moduleId;
var targetItemsElement = document.getElementById(targetItemsId);
targetItemsElement.classList.toggle('is-visible');
var targetArrowId = 'ouModuleTitleArrow_' + moduleId;
var targetArrowElement = document.getElementById(targetArrowId);
if(targetArrowElement.classList.contains('icon-mini-arrow-right')) {
targetArrowElement.classList.remove('icon-mini-arrow-right')
targetArrowElement.classList.add('icon-mini-arrow-down');
} else {
targetArrowElement.classList.remove('icon-mini-arrow-down')
targetArrowElement.classList.add('icon-mini-arrow-right');
}
}
})
//run through each module
data.forEach(function(module, index){
//work out some properties
var moduleName = module.name;
var moduleId = module.id;
//create module div
var newModule = document.createElement('div');
newModule.className = 'ou-module-wrapper';
newModule.innerHTML = '<div class="ou-menu-module-title" title="' + moduleName + '" data-module-id="' + moduleId + '"><i id="ouModuleTitleArrow_' + moduleId + '" class="icon-mini-arrow-right ou-menu-module-arrow" data-module-id="' + moduleId + '"></i> ' + moduleName + '</div>';
var moduleItemsWrapper = document.createElement('div');
moduleItemsWrapper.className = 'toggle-content';
moduleItemsWrapper.id = 'ouModuleItemsWrappper_'+moduleId;
newModule.appendChild(moduleItemsWrapper); //add module to content
module.items.forEach(function(item, index){
var itemTitle = item.title;
var moduleId = item.module_id;
var itemId = item.id;
var itemType = item.type;
var iconType;
switch(itemType) {
case "Page":
iconType = "icon-document";
break;
case "File":
iconType = "icon-paperclip";
break;
case "Discussion":
iconType = "icon-discussion";
break;
case "Quiz":
iconType = "icon-quiz";
break;
case "Assignment":
iconType = "icon-assignment";
break;
default:
iconType = "icon-document";
}
var newItem = document.createElement('div');
newItem.className = 'ou-menu-item-wrapper';
var itemLink = 'https://universityofoxford.instructure.com/courses/' + courseId + '/modules/items/' + itemId; //construct hopefully app-compatible URL
newItem.innerHTML = '<a class="'+iconType+'" title="'+itemTitle+'" href="'+itemLink+'">'+itemTitle+'</a>';
moduleItemsWrapper.appendChild(newItem); //add item to module
/* Check if this is the live item and leave menu open if it is */
console.log(moduleItemId);
console.log(item.id);
if(ENV.WIKI_PAGE){
//we're in a wiki page
if(item.page_url){
//we're processing a wiki page
if(ENV.WIKI_PAGE.url==item.page_url) {
moduleItemsWrapper.classList.add('is-visible');
newItem.classList.add('ou-menu-item-active');
}
}
} else if (ENV.DISCUSSION && ENV.DISCUSSION.TOPIC) {
//we're in a discussion
if(item.content_id){
//we're processing a discussion page
if(ENV.DISCUSSION.TOPIC.ID==item.content_id) {
moduleItemsWrapper.classList.add('is-visible');
newItem.classList.add('ou-menu-item-active');
}
}
} else if (ENV.QUIZ) {
//we're in a quiz/survey
if(item.content_id){
//we're processing a quiz/survey page
if(ENV.QUIZ.id==item.content_id) {
moduleItemsWrapper.classList.add('is-visible');
newItem.classList.add('ou-menu-item-active');
}
}
} else if (ENV.ASSIGNMENT_ID) {
//we're in an assignment
if(item.content_id){
//we're processing an assignment
if(ENV.ASSIGNMENT_ID==item.content_id) {
moduleItemsWrapper.classList.add('is-visible');
newItem.classList.add('ou-menu-item-active');
}
}
} else if (moduleItemId && parseInt(moduleItemId)===parseInt(item.id)) {
//we're in something else but inside a module
moduleItemsWrapper.classList.add('is-visible');
newItem.classList.add('ou-menu-item-active');
}
});
divMenuWrapper.appendChild(newModule); //add module to content
});
})
.catch(function(error) {
console.log('getModules request failed', error);
}
);
}
/*
* Function which replaces all <div id="module_x" class="ou-insert-progress-bar">y</div> with graphical progress bars
* x = module number
* y = % complete
*/
function showProgressBars() {
//get all elements with classname ou-insert-progress-bar
var progressBarPlaceholders = document.getElementsByClassName('ou-insert-progress-bar');
Array.prototype.forEach.call(progressBarPlaceholders, function(progressBarPlaceholder) {
var value = progressBarPlaceholder.innerHTML;
var className = progressBarPlaceholder.id;
//UC first letter
var viewName = className.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
//replace underscore with space
viewName = viewName.replace(/_/g, ' ');
//create our new element
var progressBarContainer = document.createElement("div");
progressBarContainer.innerHTML = ''+
'<h4 class="ou-space-before-progress-bar">Current position in ' + viewName + ':</h4>' +
'<div class="ou-ProgressBar ' + className + '" style="width: 100%; height: 15px;" role="progressbar" aria-valuemax="100" aria-valuemin="0" aria-valuenow="'+ value +'">' +
' <div class="ou-ProgressBarBar" style="width: '+ value +'%;" title="'+ value +'%"></div>' +
'</div>';
//insert it after the placeholder using the function insertAfter
insertAfter(progressBarContainer, progressBarPlaceholder);
//now delete the placeholder
progressBarPlaceholder.parentNode.removeChild(progressBarPlaceholder);
});
}
/*
* Rewriting links in the format https://oxforduniversity.instructure.com/courses/[courseId]/modules/[moduleId]/items/first
* which works in the app by taking users to the Modules page and opens the appropriate Module
* However, in the web app, we need to rewrite this to go to the appropriate anchor on the Modules page
*/
function rewriteModuleLinks() {
var moduleLinks = document.getElementsByTagName('a'), i;
for (i in moduleLinks) {
var cn = moduleLinks[i].className;
var matchClass = "ou-ModuleLink";
if(cn && cn.match(new RegExp("(^|\\s)" + matchClass + "(\\s|$)"))) {
moduleLinks[i].onclick = function(event) {
var destination = event.currentTarget.href; //attached to the a, even if user clicked something inside the a
var destinationParts = destination.split('/');
j=0;
while (destinationParts[j]!="modules"){
j=j+1;
}
var moduleId = destinationParts[j + 1];
window.location = "https://oxforduniversity.instructure.com/courses/" + courseId + "/modules" + "#module_" + moduleId;
return false; //prevent default
}
}
}
}
/* Utility functions */
/*
* Function which returns a promise (and error if rejected) if response status is OK
*/
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
/*
* Function which returns json from response
*/
function json(response) {
return response.json()
}
/*
* Function which returns csrf_token from cookie see: https://community.canvaslms.com/thread/22500-mobile-javascript-development
*/
function getCsrfToken() {
var csrfRegex = new RegExp('^_csrf_token=(.*)$');
var csrf;
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
var match = csrfRegex.exec(cookie);
if (match) {
csrf = decodeURIComponent(match[1]);
break;
}
}
return csrf;
}
/**
* Function which wraps one element in another div - see: https://stackoverflow.com/questions/6838104/pure-javascript-method-to-wrap-content-in-a-di
* @param {element} toWrap - element to be wrapped
* @param {element} [wrapper] - element to wrap it in - new div if not provided
*/
var wrap = function (toWrap, wrapper) {
wrapper = wrapper || document.createElement('div');
toWrap.parentNode.appendChild(wrapper);
return wrapper.appendChild(toWrap);
};
/**
* Function which gets query string parameters by name - see: https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
* @param {string} name - name of query parameter
* @param {string} [url=window.location.href] - url
*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
/**
* Function which gets query string parameters by name - see: https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
* @param {string} name - name of query parameter
* @param {string} [url=window.location.href] - url
*/
function getCourseId() {
var courseId = ENV.COURSE_ID || ENV.course_id;
if(!courseId){
var urlPartIncludingCourseId = window.location.href.split("courses/")[1];
if(urlPartIncludingCourseId) {
courseId = urlPartIncludingCourseId.split("/")[0];
}
}
return courseId;
}<file_sep>/testing-lozenge-drop-down/lozenge-test.js
/*
* Add tiles at top of modules tool:
* - Tiles are generated by calling the Canvas api, not by scraping the Modules page as before (should be more reliable as Canvas in upgraded)
* - Added a drop-down arrow which gives you a quick link to the Module item (page, discussion, etc)
* - Tiles will show any images put into a specific folder in the Course’s Files (this defaults to looking for a ’tiles’ folder). If no folder or too few images for the number of Modules, colours are used instead
* - Modules further down the page gain a coloured border to help tie things together
* - Clicking the tile anywhere except the drop-down arrow scrolls you down the Modules page to the appropriate Module.
* - I’ve added a Top button to each module which scrolls you back up to the dashboard view
*/
// TODO - show completion either on links or as e.g 10/12
/* Global variables */
var initCourseId = ENV.COURSE_ID;
var noOfColumnsPerRow = 4; //no of columns per row of tiles at top of Modules page - 1, 2, 3, 4, 6 or 12
var tileImagesFolderName = "tiles";
var moduleNav;
var divCourseHomeContent = document.getElementById('course_home_content');
var divContextModulesContainer = document.getElementById('context_modules_sortable_container');
var tableHomePageTable = document.getElementById('homePageTable');
var divContent = document.getElementById('content');
/* first 9 are Marcy's colors, rest are randomly selected from: https://www.ox.ac.uk/public-affairs/style-guide/digital-style-guide */
var moduleColours = ['#e8ab1e','#91b2c6','#517f96','#1c4f68','#400b42','#293f11','#640D14','#b29295','#002147','#002147','#cf7a30','#a79d96','#f5cf47','#fb8113','#f3f1ee','#aab300','#043946','#be0f34','#a1c4d0','#a1c4d0','#122f53','#0f7361','#3277ae','#872434','#44687d','#517fa4','#177770','#be0f34','#d34836','#70a9d6','#69913b','#d62a2a','#5f9baf','#09332b','#44687d','#721627','#9eceeb','#330d14','#006599','#cf7a30','#a79d96','#be0f34','#001c3d','#ac48bf','#9c4700','#c7302b','#ebc4cb','#1daced'];
var tileImageUrls = [];
//From: https://stackoverflow.com/questions/4793604/how-to-insert-an-element-after-another-element-in-javascript-without-using-a-lib
function msd_insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
/* Wait unril DOM ready before loading tiles */
function msd_domReady () {
if(divCourseHomeContent && divContextModulesContainer){
//we're in the modules page as a home page
//first delete any existing nav container
var existingModuleNav = document.getElementById('module_nav');
if(existingModuleNav) {
existingModuleNav.parentNode.removeChild(existingModuleNav);
}
//create our nav container
moduleNav = document.createElement("div");
moduleNav.id = "module_nav";
moduleNav.className = "ou-ModuleCard__box";
moduleNav.innerHTML = '<a id="module_nav_anchor"></a>';
divContent.insertBefore(moduleNav, divContent.childNodes[0]);
//now get modules from api
//msd_getSelfThenModules();
msd_getTileFolder(initCourseId);
} else if(divCourseHomeContent && tableHomePageTable){
//we're in in a home page which contains a table with id="homePageTable"
//create our nav container
moduleNav = document.createElement("div");
moduleNav.id = "module_nav";
moduleNav.className = "ou-ModuleCard__box";
moduleNav.innerHTML = '<a id="module_nav_anchor"></a>';
//replace table#homePageTable with our moduleNav
tableHomePageTable.parentNode.replaceChild(moduleNav, tableHomePageTable);
//now get modules from api
msd_getTileFolder(initCourseId);
//msd_getSelfThenModules();
}
/* Whichever page I am on, store last page visited via modules (ie chcek that the url contains 'module' - see: https://canvas.instructure.com/doc/api/users.html#method.custom_data.set_data */
//ie PUT to /api/v1/users/:user_id/custom_data(/*scope) where Scope is CourseID?
//then data to post will be something like:
//{
// "data": {
// "item_title": "My item title",
// "item_id": 1234,
// }
//}
//first get id
//then PUT
//On home page, offer last page visited as a link at the top?
}
//Function to work out when the DOM is ready: https://stackoverflow.com/questions/1795089/how-can-i-detect-dom-ready-and-add-a-class-without-jquery/1795167#1795167
// Mozilla, Opera, Webkit
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false);
msd_domReady();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
msd_domReady();
}
});
}
/*
* Get self id - actually only needed to show completion
*/
function msd_getSelfThenModules() {
var csrfToken = msd_getCsrfToken();
fetch('/api/v1/users/self',{
method: 'GET',
credentials: 'include',
headers: {
"Accept": "application/json",
"X-CSRF-Token": csrfToken
}
})
.then(msd_status)
.then(msd_json)
.then(function(data) {
console.log(data);
msd_getTileFolder(initCourseId, data.id);
})
.catch(function(error) {
console.log('getSelfId Request failed', error);
}
);
}
/*
* Get tileImages for courseId
*/
//function msd_getTileFolder(courseId, userId) {
function msd_getTileFolder(courseId) {
var csrfToken = msd_getCsrfToken();
fetch('/api/v1/courses/' + courseId + '/folders',{
method: 'GET',
credentials: 'include',
headers: {
"Accept": "application/json",
"X-CSRF-Token": csrfToken
}
})
.then(msd_status)
.then(msd_json)
.then(function(data) {
console.log(data);
var imagesFolderId;
data.forEach(function(folder){
if(folder.name==tileImagesFolderName){
imagesFolderId = folder.id;
}
});
//msd_getTileImageUrls(courseId, userId, imagesFolderId);
msd_getTileImageUrls(courseId, imagesFolderId);
});
}
//function msd_getTileImageUrls(courseId, userId, imagesFolderId) {
function msd_getTileImageUrls(courseId, imagesFolderId) {
/* temporarily getting file ids here - longer-term, replace with callbacks */
var csrfToken = msd_getCsrfToken();
if(imagesFolderId) {
fetch('/api/v1/folders/' + imagesFolderId + '/files',{
method: 'GET',
credentials: 'include',
headers: {
"Accept": "application/json",
"X-CSRF-Token": csrfToken
}
})
.then(msd_status)
.then(msd_json)
.then(function(data) {
console.log(data);
data.forEach(function(image){
tileImageUrls.push(image.url);
});
msd_getModules(courseId, tileImageUrls);
//msd_getModules(courseId, userId, tileImageUrls);
});
} else {
msd_getModules(courseId);
}
}
/*
* Get modules for courseId
*/
//function msd_getModules(courseId, userId, tileImageUrls) {
function msd_getModules(courseId, tileImageUrls) {
var csrfToken = msd_getCsrfToken();
//fetch('/api/v1/courses/' + courseId + '/modules?include=items&student_id=' + userId,{
fetch('/api/v1/courses/' + courseId + '/modules?include=items',{
method: 'GET',
credentials: 'include',
headers: {
"Accept": "application/json",
"X-CSRF-Token": csrfToken
}
})
.then(msd_status)
.then(msd_json)
.then(function(data) {
console.log(data);
var newRow; //store parent row to append to between iterations
//run through each module
data.forEach(function(module, mindex){
//work out some properties
var moduleName = module.name;
//create row for card
if(mindex % noOfColumnsPerRow === 0) {
newRow = document.createElement("div");
newRow.className = "grid-row center-sm";
moduleNav.appendChild(newRow);
}
var newColumn = document.createElement("div");
// TODO work out classes for noOfColumnsPerRow != 4
//create column wrapper
newColumn.className = "col-xs-12 col-sm-6 col-lg-3";
newRow.appendChild(newColumn);
//create module div
var moduleTile = document.createElement("div");
moduleTile.className = "ou-ModuleCard";
moduleTile.title = moduleName;
var moduleTileLink = document.createElement("a");
if(divContextModulesContainer) {
moduleTileLink.href ="#module_" + module.id;
} else {
moduleTileLink.href = '/courses/' + courseId + '/modules/' + module.id;
}
var moduleTileHeader = document.createElement("div");
moduleTileHeader.className="ou-ModuleCard__header_hero_short";
if(tileImageUrls && tileImageUrls.length > mindex) {
moduleTileHeader.style.backgroundImage = "url(" + tileImageUrls[mindex] + ")";
} else {
moduleTileHeader.style.backgroundColor = moduleColours[mindex];
}
var moduleTileContent = document.createElement("div");
moduleTileContent.className = "ou-ModuleCard__header_content";
var moduleTileActions = document.createElement("div");
moduleTileActions.className = "ou-drop-down-arrow";
moduleTileActions.title = "Click for contents";
var moduleTileArrowButton = document.createElement("a");
moduleTileArrowButton.classList.add("al-trigger");
//moduleTileArrowButton.classList.add("btn");
//moduleTileArrowButton.classList.add("btn-small");
moduleTileArrowButton.href ="#";
var moduleTileArrowIcon = document.createElement("i");
moduleTileArrowIcon.className = "icon-mini-arrow-down";
moduleTileArrowButton.appendChild(moduleTileArrowIcon);
var moduleTileList = document.createElement("ul");
moduleTileList.id = "toolbar-" + module.id + "-0";
moduleTileList.className = "al-options";
moduleTileList.setAttribute("role", "menu");
moduleTileList.tabIndex = 0;
moduleTileList.setAttribute("aria-hidden",true);
moduleTileList.setAttribute("aria-expanded",false);
moduleTileList.setAttribute("aria-activedescendant","toolbar-" + module.id + "-1");
/* Now create drop-down menu */
module.items.forEach(function(item, iindex){
var itemTitle = item.title;
//var moduleId = item.module_id;
var itemId = item.id;
var itemType = item.type;
var iconType;
switch(itemType) {
case "Page":
iconType = "icon-document";
break;
case "File":
iconType = "icon-paperclip";
break;
case "Discussion":
iconType = "icon-discussion";
break;
case "Quiz":
iconType = "icon-quiz";
break;
case "Assignment":
iconType = "icon-assignment";
break;
case "ExternalUrl":
iconType = "icon-link";
break;
default:
iconType = "icon-document";
}
var listItem = document.createElement('li');
listItem.className = 'ou-menu-item-wrapper';
var listItemDest = '/courses/' + courseId + '/modules/items/' + itemId;
var listItemLink = document.createElement("a");
listItemLink.className = iconType;
listItemLink.href = listItemDest;
listItemLink.text = itemTitle;
listItemLink.tabindex = -1;
listItemLink.setAttribute("role", "menuitem");
listItemLink.title = itemTitle;
listItem.appendChild(listItemLink);
moduleTileList.appendChild(listItem);
});
moduleTileActions.appendChild(moduleTileArrowButton);
moduleTileActions.appendChild(moduleTileList);
var moduleTileTitle = document.createElement("div");
moduleTileTitle.classList.add("ou-ModuleCard__header-title");
moduleTileTitle.classList.add("ellipsis");
moduleTileTitle.title = moduleName;
moduleTileTitle.style.color = moduleColours[mindex];
moduleTileTitle.innerHTML = moduleName;
moduleTileContent.appendChild(moduleTileActions);
moduleTileContent.appendChild(moduleTileTitle);
moduleTileLink.appendChild(moduleTileHeader);
moduleTileLink.appendChild(moduleTileContent);
moduleTile.appendChild(moduleTileLink);
newColumn.appendChild(moduleTile);
/* Following only if we are on the Modules page */
if(divContextModulesContainer) {
//now remove then add top buttons to each Canvas module to take back up to menu
var topButtons = document.querySelectorAll(".ou-top_button");
topButtons.forEach(function(topButton) {
topButton.parentNode.removeChild(topButton);
});
var canvasModuleHeaders = document.querySelectorAll(".ig-header");
canvasModuleHeaders.forEach(function(canvasModuleHeader) {
newTopButton = document.createElement("a");
newTopButton.className = "btn ou-top_button";
newTopButton.href = "#module_nav_anchor";
newTopButton.innerHTML = '<i class="icon-arrow-up"></i>Top';
canvasModuleHeader.appendChild(newTopButton);
});
//try and colour in each module
var canvasModuleDiv = document.getElementById('context_module_'+module.id);
canvasModuleDiv.style.borderLeftColor = moduleColours[mindex];
canvasModuleDiv.style.borderLeftWidth = '10px';
canvasModuleDiv.style.borderLeftStyle = 'solid';
}
});
})
.catch(function(error) {
console.log('msd_getModules request failed', error);
}
);
}
/* Utility functions */
/*
* Function which returns a promise (and error if rejected) if response status is OK
*/
function msd_status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
/*
* Function which returns json from response
*/
function msd_json(response) {
return response.json()
}
/*
* Function which returns csrf_token from cookie see: https://community.canvaslms.com/thread/22500-mobile-javascript-development
*/
function msd_getCsrfToken() {
var csrfRegex = new RegExp('^_csrf_token=(.*)$');
var csrf;
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
var match = csrfRegex.exec(cookie);
if (match) {
csrf = decodeURIComponent(match[1]);
break;
}
}
return csrf;
} | 45356f8a3b55335d96f1efc486831f3946eb570e | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | msdlt/canvas | 5c20f32c07e35868ff354bc358f79f597e22c945 | 0addc5851e5727930f83bf23010659be3a860cc7 |
refs/heads/master | <repo_name>WHTaylor/home<file_sep>/bin/follower.py
import time
import curses
# Add an option to pattern match against lines
# For now, just removing this many chars from the beginning
CUT_OFF_THEIR_HEADS = 14
def get_tail_lines(filename, catch_up_N=15):
'''
Create a generator that yields any lines written to 'filename' since last yield
If catch_up_N is a positive number, will yield that many lines from the end
of the existing file.
'''
f = open(filename, "r")
f.seek(0, 2) # Seek to end
if catch_up_N:
fsize = f.tell()
f.seek(max(fsize - 2048, 0), 0) # Seek back a couple KB (hopefully enough)
catch_up_lines = [l[CUT_OFF_THEIR_HEADS:] for l in f.readlines()]
yield catch_up_lines[-catch_up_N:]
while True:
res = []
line = f.readline()[CUT_OFF_THEIR_HEADS:]
while line:
res.append(line)
line = f.readline()[CUT_OFF_THEIR_HEADS:]
yield res
def get_tails(env, system, prefix=""):
if system == "live-ingest":
apps = [prefix + a for a in ["FileWatcher", "LiveIngest", "XMLtoICAT"]]
if env == "local":
log_root = "C:\\FBS\\Logs"
elif env == "dev":
log_root = r"\\icatdevingest\c$\FBS\Logs"
elif env == "prod":
log_root = r"\\icatliveingest\c$\FBS\Logs"
elif system == "schedule":
apps = ["SCHEDULE", "UserOffice"]
if env == "local":
log_root = r"C:/payara/domains/domain1/logs"
elif env == "dev":
print("todo, dev schedule")
exit(1)
elif env == "prod":
print("todo, prod schedule")
exit(1)
return [(app, get_tail_lines(f"{log_root}\\{app}.log")) for app in apps]
tails = get_tails("local", "live-ingest", "Test")
h_height, f_height = 3, 3
def main(stdscr):
curses.curs_set(0)
stdscr.clear()
stdscr.nodelay(True)
scr_height, scr_width = stdscr.getmaxyx()
# Setup a window for each tracked log, in vertical columns
num_cols = len(tails)
col_h_pad = 2
col_width = (scr_width // num_cols - 1) - col_h_pad
windows = []
for i, (app, _) in enumerate(tails):
x = i * (col_width + col_h_pad)
stdscr.insstr(1, x, app) # Title in header
win = curses.newwin(
scr_height - h_height - f_height - 1,
col_width,
h_height,
x)
windows.append(win)
win.scrollok(True)
stdscr.insstr(scr_height - f_height + 1, 1, "q: quit")
stdscr.refresh()
while True:
for i, (_, tail) in enumerate(tails):
lines = next(tail)
if lines:
for line in lines:
windows[i].insertln()
windows[i].insstr(line)
windows[i].refresh()
time.sleep(0.01)
try:
k = stdscr.getkey()
if k == "q": break
except: pass # No key pressed
if __name__ == "__main__":
curses.wrapper(main)
<file_sep>/.bashrc
# Print a random quote
if [[ -r ~/quotes ]]; then
quote=$(shuf -n 1 ~/quotes)
echo "- $quote -"
fi
# Go up n directories
function up {
if [ $# -eq 0 ]; then
cd ..
return 0;
fi;
local n;
if [[ $1 =~ ^[0-9]+$ ]]; then
local old=$PWD;
for ((i=0; i<$1; i++)); do
cd ..;
done;
export OLDPWD=$old;
else
echo "Argument must be a number"
return 1
fi;
}
[[ "rop61488" == $USERNAME ]] && . ~/bash/work/.payara_functions
<file_sep>/.bash_profile
# Never truncate history
export HISTFILESIZE=
export HISTSIZE=
test -f ~/.bash_aliases && . ~/.bash_aliases
test -f ~/.bashrc && . ~/.bashrc
[[ "rop61488" == $USERNAME ]] && . ~/bash/work/.bash_profile
<file_sep>/bash/work/.bash_profile
export APPS_HOME_DIR="/c/Users/rop61488/Documents/Apps"
export PAYARA_DOMAINS_DIR="C:\\payara\\domains"
export DEV_LOGS="\\\\fitbawebdev\\d$\\payara\\domains\\domain1\\logs"
export PROD_LOGS="\\\\fitbaweb1\\d$\\payara\\domains\\domain1\\logs"
export LOCAL_LOGS="$PAYARA_DOMAINS_DIR/domain1/logs"
export ICAT_HOME_DIR="~/projects/isis-icat"
export PATH="$PATH:/c/payara/installations/payara-4.1.2.181/payara41/bin:/usr/local/bin/nunit-3.12/net35"
export CDPATH=".:$APPS_HOME_DIR:$ICAT_HOME_DIR"
alias python="winpty python.exe"
alias nunit="nunit3-console.exe"
alias apps="cd $APPS_HOME_DIR"
alias fbs="cd /c/FBS/Apps"
alias mvnci="mvn clean install -DskipTests -Dmaven.javadoc.skip=true"
alias mvni="mvn install -DskipTests -Dmaven.javadoc.skip=true"
alias bgb='mvnci &> ~/build &'
alias update_wsdl='py $APPS_HOME_DIR/ISISBusApps/Tools/WsdlUpdater/wsdl_updater.py'
alias search_code="grep -rI --exclude={\*.wsdl,Reference.cs,Reference1.cs,\*.html,\*.class,\*.xml,\*.xsd,\*.designer.cs} --exclude-dir={bin,obj,.git}"
alias morning="start_payara 1 & docker start oracleXE"
# Mount main working directory as w. Will change over time
[[ -d /w ]] || subst W: C:/Users/rop61488/projects/work/LiveIngestEndToEndTests
<file_sep>/bin/csdepvis
#!/usr/bin/env python
""" Visualise the dependencies from a .csproj or .sln file """
import argparse
import os
import re
from collections import deque
from pathlib import Path
import xml.etree.ElementTree as ET
# Assumes all tags are from the default xmlns
def get_csproj_refs(cs_proj_path):
tree = ET.parse(str(cs_proj_path))
ns_match = re.search("{(.+)}",tree.getroot().tag)
ns = ns_match.groups()[0]
namespaces = {"xmlns": ns}
def to_name_and_path(projref):
path = Path(projref.attrib['Include'])
name = projref.find("xmlns:Name", namespaces).text
return name, path
projrefs = tree.iterfind(".//xmlns:ProjectReference", namespaces)
return [to_name_and_path(pr) for pr in projrefs]
def get_sln_refs(sln_path):
patt = 'Project\("{[A-Z0-9-]+}"\) = "(.+)", "(.+\.csproj)"'
matches = []
with open(sln_path) as f:
for l in f:
if l == "Global":
break
m = re.search(patt, l)
if m is not None:
matches.append(m)
return [(m.groups()[0], Path(m.groups()[1])) for m in matches]
def resolve_dependencies(root_path):
def get_resolver(path):
ext = os.path.splitext(path)[1]
if ext == ".sln":
return get_sln_refs
elif ext == ".csproj":
return get_csproj_refs
else:
print(f"No resolver for {path}, crashing")
resolved = {}
to_resolve = deque()
def resolve(dep, resolver):
name, path = dep
if name in resolved: return
deps = resolver(path)
resolved[name] = [dep[0] for dep in deps]
for dep in deps:
name, rel_path = dep
to_resolve.append((name, path.parent.joinpath(rel_path)))
resolve((root_path.name, root_path), get_resolver(root_path))
while to_resolve:
name, path = to_resolve.popleft()
resolve((name, path), get_resolver(path))
return resolved
def visualise(dept_tree, name, depth=0):
deps = sorted(dept_tree[name])
lines = [visualise(dept_tree, dep, depth + 1) for dep in deps]
prefix = "|" if depth > 0 else ""
header = prefix + "-" * (depth - 1) + name
splitter = '\n\n' if depth == 0 else '\n'
return splitter.join([header] + lines)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Visualise the dependencies from a .csproj or .sln file')
parser.add_argument('file', help='the .sln or .csproj file')
args = parser.parse_args()
root_path = Path(args.file)
dept_tree = resolve_dependencies(root_path)
print()
print(visualise(dept_tree, root_path.name))
<file_sep>/.bash_aliases
alias tailf="tail -f"
alias ll="ls -alF"
function mkcd { mkdir -p $1; cd $1; }
alias scs='grep -r --include \*.cs'
alias freeze-req='pip freeze > requirements.txt'
alias g=git
complete -o bashdefault -o default -o nospace -F __git_wrap__git_main g
| a275f508b545ea4b1e07e06c1b8ba308fc4b919f | [
"Python",
"Shell"
] | 6 | Python | WHTaylor/home | 7556457f87bca3052088c2067a3870b9c6cf0c3d | f1942ab25ff853f56838899db196b93722445e4f |
refs/heads/master | <repo_name>SIW22/Kaleidos<file_sep>/README.md
# Kaleidos
## Wireframes









## User Stories
- Users are greeted with a splash page with branding id;
- Before loading the site, users may login or register a new account.
- Users can add images and descriptions of virtually anything.
- Once added, items added can be edited or deleted.
- 1 user may have numerous collections of items, which can be sorted by category.
---
LOGO:
- clicking on logo will lead back to home page
SPLASH PAGE:
- root route
- logo and app name
- slogan of our app
- create account
INDEX PAGE:
- include navigation
- *browse by*: all, category, type
USERS:
- login/registration
- session tied to login
- logout
## DB Models and ERD
### ERD:

### MODELS:
- collection / products
- users
### SCHEMA ATTRIBUTES:
USER:
- full name: String,
- username: String,
- email: String,
- password: <PASSWORD>
PRODUCT:
- Category: String,
- Item name: String,
- description: String,
- image: data
## Technologies Used
- HTML
- CSS
- MongoDB
- Express
- JavaScript
- DOM Manipulation
- jQuery/Vanilla JS
- Session
- Mongo-Connect
- Multiparty
- Cloudinary
- Dotenv
## BONUS/PLANNED FEATURES:
- add sort by category function
- login / registration options
- display and add images
## CRUD
- full functionality for all users
- Create new items
- View created items
- Edit items
- Delete items
<file_sep>/server.js
const express = require('express');
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();
const cloudinary = require('cloudinary');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
/* ---------------- CONFIGS ---------------- */
// dotenv
require('dotenv').config();
// start port
const port = process.env.PORT || 4000;
const app = express();
console.log('The value of test = ', process.env.NEW_TEST);
/* ---------------- CONTROLLERS ---------------- */
const productsController = require('./controllers/productsController');
const authController = require('./controllers/authController');
/* -------------- SET VIEW ENGINE -------------- */
app.set('view engine', 'ejs');
// Static
app.use(express.static('views/partials'))
app.use(express.static('public'));
/* ---------------- MIDDLEWARE ---------------- */
// Express Session
app.use(session({
store: new MongoStore({
url: process.env.MONGODB_URI || 'mongodb://localhost:27017/trending',
}),
secret: process.env.SESSION_SECRET, // how we verify we created this cookie
resave: false,
saveUninitialized: false,
}));
// Method Override
app.use(methodOverride('_method'));
// BodyParser
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
/* ---------------- ROUTES ---------------- */
// GET Root Route
app.get('/', (req, res) => {
res.render('index', {
title: 'Home'
});
});
// Products Route
app.use('/products', productsController);
// Auth Route
app.use('/auth', authController);
/* ---------------- EVENT LISTENER ---------------- */
app.listen(port, () => console.log(`Server is running on port ${port}`)); | 73832e94cdd6c88d3b529fd56b1edf0c22ee084e | [
"Markdown",
"JavaScript"
] | 2 | Markdown | SIW22/Kaleidos | 08210bf048ed31fe8d81d917d2e6dfeb95586da7 | 331b275f967bda55ac5373ae013f1aac3394e3c5 |
refs/heads/master | <repo_name>SabeerShaikh/Android<file_sep>/app/src/main/java/com/example/assignment/AssignmentFragment.java
package com.example.assignment;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.example.assignment.Adapter.AssignmentDemoAdapter;
import com.example.assignment.DB.AppDatabase;
import com.example.assignment.Interfaces.MainView;
import com.example.assignment.Presenter.MainPresenterImpl;
import com.example.assignment.Util.API;
import com.example.assignment.dataModel.AssignmentModel;
import java.util.List;
import java.util.Objects;
/**
* Created by <NAME> on 12/04/2019.
*/
public class AssignmentFragment extends Fragment implements MainView, SwipeRefreshLayout.OnRefreshListener {
private final String LOADING_TAG = "MainActivity_LOADING";
private final String CONTENT_TAG = "MainActivity_CONTENT";
private final String STATE_TAG = "MainActivity_KeyForLayoutManagerState";
private LinearLayoutManager linearLayoutManager;
private AssignmentDemoAdapter mAssignmenAdapter;
private List<AssignmentModel> assignmentModelsList;
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private MainPresenterImpl mMainPresenter;
private boolean wasLoadingState = false;
private boolean wasRestoringState = false;
private Parcelable savedRecyclerLayoutState;
private SharedPreferences sharedpreferences;
private AppDatabase mDatabase;
private AssignmentActivity listener;
// This event fires 1st, before creation of fragment or any views
// The onAttach method is called when the Fragment instance is associated with an Activity.
// This does not mean the Activity is fully initialized.
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Activity){
this.listener = (AssignmentActivity) context;
}
}
// This event fires 2nd, before views are created for the fragment
// The onCreate method is called when the Fragment instance is being created, or re-created.
// Use onCreate for any standard setup that does not require the activity to be fully created
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getting all savedInstanceState data
if (savedInstanceState != null) {
wasLoadingState = savedInstanceState.getBoolean(LOADING_TAG, false);
wasRestoringState = savedInstanceState.getBoolean(CONTENT_TAG, false);
savedRecyclerLayoutState = savedInstanceState.getParcelable(STATE_TAG);
}
}
private void OfflineLoadData() {
// Creates the databases and initializes it.
mDatabase = Room.databaseBuilder(listener.getApplicationContext(), AppDatabase.class, "production")
.build();
//create thread for fetching recodes from database
//Fetching all recodes from database.
Runnable runnable = new Runnable() {
@Override
public void run() {
//Fetching all recodes from database.
assignmentModelsList = mDatabase.databaseInterface().getAllItems();
mAssignmenAdapter = new AssignmentDemoAdapter(assignmentModelsList);
mRecyclerView.setAdapter(mAssignmenAdapter);
setRecyclerViewCache();
if (savedRecyclerLayoutState != null) {
Objects.requireNonNull(mRecyclerView.getLayoutManager()).onRestoreInstanceState(savedRecyclerLayoutState);
}
savedRecyclerLayoutState = null;
}
};
Thread newThread = new Thread(runnable);
newThread.start();
}
// The onCreateView method is called when Fragment should create its View object hierarchy,
// either dynamically or via XML layout inflation.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
return inflater.inflate(R.layout.assignment_fragment_layout, parent, false);
}
// This event is triggered soon after onCreateView().
// onViewCreated() is only called if the view returned from onCreateView() is non-null.
// Any view setup should occur here. E.g., view lookups and attaching view listeners.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init(view);
//if network is not available
if (!isInternetOn(listener)) {
OfflineLoadData();
listener.setTitle(sharedpreferences.getString("ActivityTitle", ""));
}
}
private void init(View view) {
//Initialisation of shared preference
sharedpreferences = listener.getSharedPreferences(API.MyPREFERENCES, Context.MODE_PRIVATE);
mSwipeRefreshLayout = view.findViewById(R.id.swipe_layout);
mRecyclerView = view.findViewById(R.id.recycler_view);
linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
// Setup refresh listener which triggers new data loading
mSwipeRefreshLayout.setOnRefreshListener(this);
// Configure the refreshing colors
mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
@Override
public void onStart() {
super.onStart();
mMainPresenter = new MainPresenterImpl(this);
if (wasLoadingState) {
// it was loading already so restart fetching anyway
mMainPresenter.getDataForList(listener.getApplicationContext(), false);
} else {
// it was not loading now it wither restores cached data or fetch from network
mMainPresenter.getDataForList(listener.getApplicationContext(), wasRestoringState);
}
}
@Override
public void onRefresh() {
//force refresh
if (isInternetOn(getActivity()))
mMainPresenter.getDataForList(listener.getApplicationContext(), false);
else
hideProgress();
}
//set the recycler view cache for fast loading images
private void setRecyclerViewCache() {
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setItemViewCacheSize(20);
mRecyclerView.setDrawingCacheEnabled(true);
mRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
}
@Override
public void onGetDataSuccess(List<AssignmentModel> list) {
mAssignmenAdapter = new AssignmentDemoAdapter(list);
mRecyclerView.setAdapter(mAssignmenAdapter);
setRecyclerViewCache();
if (savedRecyclerLayoutState != null) {
Objects.requireNonNull(mRecyclerView.getLayoutManager()).onRestoreInstanceState(savedRecyclerLayoutState);
}
savedRecyclerLayoutState = null;
}
@Override
public void onGetDataFailure(String message) {
Toast.makeText(listener.getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
@Override
public void showProgress() {
hideProgress();
mSwipeRefreshLayout.setRefreshing(true);
}
@Override
public void hideProgress() {
if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
@Override
public void setMainTitle() {
listener.setTitle(sharedpreferences.getString("ActivityTitle", ""));
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (mAssignmenAdapter != null && mAssignmenAdapter.getItemCount() != 0) {
// for data restoring purpose
outState.putBoolean(CONTENT_TAG, true);
} else {
outState.putBoolean(CONTENT_TAG, false);
}
if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
// saving the loading state
outState.putBoolean(LOADING_TAG, true);
} else {
outState.putBoolean(LOADING_TAG, false);
}
outState.putParcelable(STATE_TAG, linearLayoutManager.onSaveInstanceState());
super.onSaveInstanceState(outState);
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
boolean isRestoringVal = false;
boolean isLoadingState = false;
if (savedInstanceState != null) {
isRestoringVal = savedInstanceState.getBoolean(CONTENT_TAG, false);
isLoadingState = savedInstanceState.getBoolean(LOADING_TAG, false);
}
if (isLoadingState) {
// it was loading already so restart fetching anyway
mMainPresenter.getDataForList(listener.getApplicationContext(), false);
} else {
// it was not loading then, now it whether restores cached data or fetch from network
mMainPresenter.getDataForList(listener.getApplicationContext(), isRestoringVal);
}
assert savedInstanceState != null;
savedRecyclerLayoutState = savedInstanceState.getParcelable(STATE_TAG);
}
}
@Override
public void onStop() {
mMainPresenter.onDestroy();
super.onStop();
}
// This method is called when the fragment is no longer connected to the Activity
// Any references saved in onAttach should be nulled out here to prevent memory leaks.
@Override
public void onDetach() {
super.onDetach();
this.listener = null;
}
private boolean isInternetOn(Context context) {
// get Connectivity Manager object to check connection
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
if (Build.VERSION.SDK_INT < 23) {
final NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null) {
return (ni.isConnected() && (ni.getType() == ConnectivityManager.TYPE_WIFI || ni.getType() == ConnectivityManager.TYPE_MOBILE));
}
} else {
final Network n = cm.getActiveNetwork();
if (n != null) {
final NetworkCapabilities nc = cm.getNetworkCapabilities(n);
return (nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI));
}
}
}
return false;
}
}
<file_sep>/app/src/main/java/com/example/assignment/Adapter/AssignmentDemoAdapter.java
package com.example.assignment.Adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import com.example.assignment.R;
import com.example.assignment.dataModel.AssignmentModel;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by <NAME> on 11/28/19.
*/
public class AssignmentDemoAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private List<AssignmentModel> mDatalist;
public AssignmentDemoAdapter(List<AssignmentModel> list) {
this.mDatalist = list;
}
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.testdemo_raw, parent, false);
return new ItemViewHolder(view);
}
@Override
public void onBindViewHolder(final ItemViewHolder holder, int position) {
AssignmentModel assignmentModel = mDatalist.get(position);
holder.testTitle.setText(assignmentModel.getmTilte());
holder.testDescription.setText(assignmentModel.getmDecription());
//holder.imageView.setText(eq.getMagnitude() + "!");
Picasso.get()
.load(assignmentModel.getImageHref())
.fit()
.into(holder.imageView, new com.squareup.picasso.Callback() {
@Override
public void onSuccess() {
//Success image already loaded into the view
}
@Override
public void onError(Exception e) {
//Error placeholder image already loaded into the view, do further handling of this situation here
holder.imageView.setImageResource(R.drawable.ic_launcher);
}
});
}
@Override
public int getItemCount() {
return mDatalist.size();
}
}
<file_sep>/app/src/main/java/com/example/assignment/Interfaces/MainPresenter.java
package com.example.assignment.Interfaces;
import android.content.Context;
/**
* Created by <NAME> on 11/28/19.
*/
public interface MainPresenter {
void getDataForList(Context context, boolean isRestoring);
void onDestroy();
}
<file_sep>/app/src/main/java/com/example/assignment/AssignmentActivity.java
package com.example.assignment;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
/**
* Created by <NAME> on 11/28/19.
*/
public class AssignmentActivity extends AppCompatActivity {
private String TAG_ASSIGNMENT_FRAGMENT = "AssignmentFragment";
private AssignmentFragment mAssignmentFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assignment);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
mAssignmentFragment = new AssignmentFragment();
transaction.replace(R.id.title_fragment, mAssignmentFragment).commit();
}
}
<file_sep>/app/src/main/java/com/example/assignment/Presenter/MainInteractorImpl.java
package com.example.assignment.Presenter;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import androidx.room.Room;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.assignment.DB.AppDatabase;
import com.example.assignment.Interfaces.GetDataListener;
import com.example.assignment.Interfaces.MainInteractor;
import com.example.assignment.R;
import com.example.assignment.Util.API;
import com.example.assignment.dataModel.AssignmentDataManager;
import com.example.assignment.dataModel.AssignmentModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by <NAME> on 11/28/19.
*/
public class MainInteractorImpl implements MainInteractor {
private final String REQUEST_TAG = "Demo-Network-Call";
private GetDataListener mGetDatalistener;
private RequestQueue mRequestQueue;
private AppDatabase mDatabase;
private SharedPreferences sharedpreferences;
private Context mContext;
//Response from the Server
private final Response.Listener<String> onEQLoaded = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
List<AssignmentModel> assignmentModelsList = new ArrayList<>();
JSONObject jsonObject;
JSONArray jsonArray = null;
String mainTitle;
try {
jsonObject = new JSONObject(response);
mainTitle = jsonObject.getString("title");
jsonArray = jsonObject.getJSONArray("rows");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("ActivityTitle", mainTitle);
editor.apply();
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject jsonObject1;
//Fetching data and adding data into model arraylist and storing in room database
assert jsonArray != null;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject1 = jsonArray.getJSONObject(i);
String title = jsonObject1.getString("title");
String description = jsonObject1.getString("description");
String imageHref = jsonObject1.getString("imageHref");
if ((title != null) && (description != null) && (imageHref != null) &&
!title.contains("null") && !description.contains("null") && !imageHref.contains("null")) {
AssignmentModel assignmentModel = new AssignmentModel(title, description
, imageHref);
//adding to room database
addToDB(assignmentModel);
assignmentModelsList.add(assignmentModel);
}
}
mGetDatalistener.onSuccess(mContext.getString(R.string.success), assignmentModelsList);
} catch (JSONException ex) {
mGetDatalistener.onFailure(ex.toString());
}
}
};
MainInteractorImpl(GetDataListener mGetDatalistener) {
this.mGetDatalistener = mGetDatalistener;
}
@Override
public void provideData(Context context, boolean isRestoring) {
//providing data on screen orientation
boolean shouldLoadFromNetwork;
if (isRestoring) {
List<AssignmentModel> existingData = AssignmentDataManager.getInstance().getLatestData();
if (existingData != null && !existingData.isEmpty()) {
// we have cached copy of data for restoring purpose
shouldLoadFromNetwork = false;
mGetDatalistener.onSuccess(context.getString(R.string.restore), existingData);
} else {
shouldLoadFromNetwork = true;
}
} else {
shouldLoadFromNetwork = true;
}
if (shouldLoadFromNetwork) {
if (isInternetOn(context)) {
this.initNetworkCall(context);
} else {
mGetDatalistener.onFailure("No internet connection.");
}
}
}
private final Response.ErrorListener onEQError = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mGetDatalistener.onFailure(error.toString());
}
};
private void initNetworkCall(Context context) {
cancelAllRequests();
mContext = context;
sharedpreferences = context.getSharedPreferences(API.MyPREFERENCES, Context.MODE_PRIVATE);
mDatabase = Room.databaseBuilder(context, AppDatabase.class, "production")
.build();
mRequestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.GET, API.ASS_URL, onEQLoaded, onEQError);
request.setRetryPolicy(new DefaultRetryPolicy(
10000, /* 10 sec timeout policy */
0, /*no retry*/
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
request.setTag(REQUEST_TAG);
mRequestQueue.add(request);
}
private void cancelAllRequests() {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(REQUEST_TAG);
}
}
@Override
public void onDestroy() {
cancelAllRequests();
}
private void addToDB(final AssignmentModel assignmentModel) {
//Inserting data in room data
AsyncTask.execute(new Runnable() {
@Override
public void run() {
mDatabase.databaseInterface().insertAll(assignmentModel);
}
});
}
private boolean isInternetOn(Context context) {
// get Connectivity Manager object to check connection
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
if (Build.VERSION.SDK_INT < 23) {
final NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null) {
return (ni.isConnected() && (ni.getType() == ConnectivityManager.TYPE_WIFI || ni.getType() == ConnectivityManager.TYPE_MOBILE));
}
} else {
final Network network = cm.getActiveNetwork();
if (network != null) {
final NetworkCapabilities nc = cm.getNetworkCapabilities(network);
assert nc != null;
return (nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI));
}
}
}
return false;
}
}
<file_sep>/app/src/main/java/com/example/assignment/Interfaces/MainView.java
package com.example.assignment.Interfaces;
import android.os.Bundle;
import com.example.assignment.dataModel.AssignmentModel;
import java.util.List;
/**
* Created by <NAME> on 11/28/19.
*/
public interface MainView {
void onGetDataSuccess(List<AssignmentModel> list);
void onGetDataFailure(String message);
void showProgress();
void hideProgress();
void setMainTitle();
void onRestoreInstanceState(Bundle savedInstanceState);
}
<file_sep>/app/src/main/java/com/example/assignment/dataModel/AssignmentModel.java
package com.example.assignment.dataModel;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
/**
* Created by <NAME> on 11/28/19.
*/
@Entity
public class AssignmentModel {
/* @PrimaryKey(autoGenerate = true)
private int id;*/
@PrimaryKey
@NonNull
@ColumnInfo(name = "title")
private String title;
@ColumnInfo(name = "description")
private String description;
@ColumnInfo(name = "imageHref")
private String imageHref;
public AssignmentModel(String title, String description, String imageHref) {
this.title = title;
this.description = description;
this.imageHref = imageHref;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getImageHref() {
return imageHref;
}
public String getmTilte() {
return title;
}
public String getmDecription() {
return description;
}
}
<file_sep>/app/src/main/java/com/example/assignment/Presenter/MainPresenterImpl.java
package com.example.assignment.Presenter;
import android.content.Context;
import com.example.assignment.Interfaces.GetDataListener;
import com.example.assignment.Interfaces.MainInteractor;
import com.example.assignment.Interfaces.MainPresenter;
import com.example.assignment.Interfaces.MainView;
import com.example.assignment.dataModel.AssignmentDataManager;
import com.example.assignment.dataModel.AssignmentModel;
import java.util.List;
/**
* Created by <NAME> on 11/28/19.
*/
public class MainPresenterImpl implements MainPresenter, GetDataListener {
private MainView mMainView;
private MainInteractor mInteractor;
public MainPresenterImpl(MainView mMainView) {
this.mMainView = mMainView;
this.mInteractor = new MainInteractorImpl(this);
}
public MainView getMainView() {
return mMainView;
}
@Override
public void getDataForList(Context context, boolean isRestoring) {
// get this done by the interactor
mMainView.showProgress();
mInteractor.provideData(context, isRestoring);
}
@Override
public void onDestroy() {
mInteractor.onDestroy();
if (mMainView != null) {
mMainView.hideProgress();
mMainView = null;
}
}
@Override
public void onSuccess(String title, List<AssignmentModel> list) {
// updating cache copy of data for restoring purpose
AssignmentDataManager.getInstance().setLatestData(list);
if (mMainView != null) {
mMainView.setMainTitle();
mMainView.hideProgress();
mMainView.onGetDataSuccess(list);
}
}
@Override
public void onFailure(String message) {
if (mMainView != null) {
mMainView.hideProgress();
mMainView.onGetDataFailure(message);
}
}
}
<file_sep>/app/src/main/java/com/example/assignment/Interfaces/GetDataListener.java
package com.example.assignment.Interfaces;
import com.example.assignment.dataModel.AssignmentModel;
import java.util.List;
/**
* Created by <NAME> on 11/28/19.
*/
public interface GetDataListener {
void onSuccess(String message, List<AssignmentModel> list);
void onFailure(String message);
}
<file_sep>/app/src/main/java/com/example/assignment/Interfaces/MainInteractor.java
package com.example.assignment.Interfaces;
import android.content.Context;
/**
* Created by <NAME> on 11/28/19.
*/
public interface MainInteractor {
void provideData(Context context, boolean isRestoring);
void onDestroy();
}
| 27bfdcee4099b61e5aa7b339c0e2d5830017a896 | [
"Java"
] | 10 | Java | SabeerShaikh/Android | 59c9910df9357d1f43e3b2335556885aaed620f6 | 76feb8d30f616ab8073c04481fd2bb437cc123a3 |
refs/heads/master | <file_sep>import { renderPolygon, renderLinePath } from "../lib/render-poly.js";
import { fireEvent } from "../lib/utilities.js";
customElements.define("wc-star-generator",
class extends HTMLElement {
constructor() {
super();
this.bind(this);
}
bind(element) {
element.attachEvents = element.attachEvents.bind(element);
element.cacheDom = element.cacheDom.bind(element);
element.render = element.render.bind(element);
element.generate = element.generate.bind(element);
element.finish = element.finish.bind(element);
}
connectedCallback() {
this.render();
this.cacheDom();
this.attachEvents();
this.generate();
}
render() {
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = `
<link rel="stylesheet" href="css/system.css">
<style>
:host { display: grid; grid-template-columns: [form] 200px [output] auto; }
fieldset { padding: 0px; margin-bottom: 0.5rem; }
#form { grid-column: form; }
#output { grid-column: output; border: 1px solid black; background-image: var(--checker); background-size:20px 20px;
background-position: 0 0, 0 10px, 10px -10px, 10px 0px; }
#finish { display: var(--finish-display, block); }
.button-container { display: flex; }
</style>
<div id="form">
<fieldset>
<label for="spike-count">Spikes:</label>
<input id="spike-count" type="phone" value="5" />
</fieldset>
<fieldset>
<label for="inner-radius">Inner Radius:</label>
<input id="inner-radius" value="10" />
</fieldset>
<fieldset>
<label for="outer-radius">Outer Radius:</label>
<input id="outer-radius" value="25" />
</fieldset>
<fieldset>
<label for="rotation">Rotation:</label>
<input id="rotation" value="0" />
</fieldset>
<fieldset>
<label for="stroke">Stroke:</label>
<input id="stroke" value="black" />
</fieldset>
<fieldset>
<label for="stroke-width">Stroke Width:</label>
<input id="stroke-width" value="1" />
</fieldset>
<fieldset>
<label for="fill">Fill:</label>
<input id="fill" value="transparent" />
</fieldset>
<fieldset>
<label for="render-type">Render Type:</label>
<select id="render-type">
<option value="polygon">Polygon</option>
<option value="path">Path</option>
</select>
</fieldset>
<div class="button-container">
<button id="finish">Finish</button>
</div>
</div>
<div id="output"></div>
`
}
cacheDom() {
this.dom = {
spikeCount: this.shadowRoot.querySelector("#spike-count"),
innerRadius: this.shadowRoot.querySelector("#inner-radius"),
outerRadius: this.shadowRoot.querySelector("#outer-radius"),
rotation: this.shadowRoot.querySelector("#rotation"),
stroke: this.shadowRoot.querySelector("#stroke"),
strokeWidth: this.shadowRoot.querySelector("#stroke-width"),
fill: this.shadowRoot.querySelector("#fill"),
renderType: this.shadowRoot.querySelector("#render-type"),
finish: this.shadowRoot.querySelector("#finish"),
output: this.shadowRoot.querySelector("#output")
};
}
attachEvents() {
this.dom.spikeCount.addEventListener("input", this.generate);
this.dom.innerRadius.addEventListener("input", this.generate);
this.dom.outerRadius.addEventListener("input", this.generate);
this.dom.rotation.addEventListener("input", this.generate);
this.dom.stroke.addEventListener("input", this.generate);
this.dom.strokeWidth.addEventListener("input", this.generate);
this.dom.fill.addEventListener("input", this.generate);
this.dom.renderType.addEventListener("change", this.generate);
this.dom.finish.addEventListener("click", this.finish);
}
generate() {
const spikeCount = parseInt(this.dom.spikeCount.value, 10);
const anglePerSpike = 2 * Math.PI / spikeCount;
const anglePerHalfSpike = anglePerSpike / 2;
const innerRadius = parseFloat(this.dom.innerRadius.value);
const outerRadius = parseFloat(this.dom.outerRadius.value);
const rotation = parseFloat(this.dom.rotation.value) * Math.PI / 180;
const stroke = this.dom.stroke.value;
const strokeWidth = parseFloat(this.dom.strokeWidth.value);
const fill = this.dom.fill.value;
const renderType = this.dom.renderType.value;
const polarPoints = []
let currentTheta = rotation;
for (let i = 0; i < spikeCount; i++) {
polarPoints.push([innerRadius, currentTheta]);
currentTheta += anglePerHalfSpike;
polarPoints.push([outerRadius, currentTheta]);
currentTheta += anglePerHalfSpike;
}
const normalizedPoints = polarPoints.map(([r, theta]) => [r * Math.cos(theta) + outerRadius, r * Math.sin(theta) + outerRadius]);
const svg = renderType === "polygon"
? renderPolygon(outerRadius * 2, outerRadius * 2, normalizedPoints, fill, stroke, strokeWidth)
: renderLinePath(outerRadius * 2, outerRadius * 2, normalizedPoints, fill, stroke, strokeWidth);
this.dom.output.innerHTML = "";
this.dom.output.appendChild(svg);
}
finish() {
const svg = this.dom.output.querySelector("svg");
fireEvent(this, "star-generated", svg ? svg.innerHTML : null);
}
}
)
<file_sep># svg-pad
https://ndesmic.github.io/svg-pad/
A text-based SVG editor for the web.
# Instructions
- Disk icon - *Download* the svg file
- Box + arrow - *Export* the svg file as a png (this is done with a custom canvas renderer such that it will not run into security issues)
- Eye - *Preview* as a png. Canvas renderer is highly experimental, incomplete and may not produce what you expect.
- Line - Adds a sample ```line```.
- Box - Add a sample ```rect```.
- Circle - Add a sample ```circle```.
- Oval - Add a sample ```ellipse```.
- Triangle - Add a sample ```polygon```.
- Squiggle - Add a sample ```path```.
- T - Add a sample ```text```.
- Curly Brackets - *Pretty print* the current code
- Checker box - Sets the *background*.
- Settings - Unused
- Wire box - Save to *dropbox*
All work is saved automatically in local storage so as long as you don't empty cache you should be okay.
Use the tabs at the bottom to switch between CSS and SVG.
If you haven't visited in a while it's advised that you clear all service worker caches just in case.
<file_sep>-add filter debug system
-saving combined CSS+SVG
-combined CSS+SVG
-saving by context
-CSS
-SVG
-pretty print by context
-CSS
-SVG
-shortcut keys
-ctrl + s
-ctrl + alt + s
-undo
-dropbox icon
-clip UI
-g UI
-font UI
-glyph
-reset button
-background for SVG workspace
-background for CSS workspace
===================================
-bake CSS into SVG
===================================
Tools:
Pills
Lightbulbs
Hearts
Squircles
Spiral
Wave
Lightning bolt
ECG
Gems (3D raster)
===================================
- Relative to Absolute
- Absolute to Relative
- Flip X
- Flip Y
- Translate X
- Translate Y
- Arbitrary rotation
- Scale
- Transform baking<file_sep>export class Dropbox {
constructor(appName = "", appKey = ""){
this.appName = appName;
this.appKey = appKey;
this.bind(this);
this.checkToken();
}
bind(dropbox){
dropbox.checkToken = this.checkToken.bind(dropbox);
dropbox.authorize = this.authorize.bind(dropbox);
dropbox.isAuthorized = this.isAuthorized.bind(dropbox);
dropbox.download = this.download.bind(dropbox);
dropbox.upload = this.upload.bind(dropbox);
}
authorize(){
window.location.href = `https://www.dropbox.com/oauth2/authorize?response_type=token&client_id=${this.appKey}&redirect_uri=${window.location.href}`;
}
isAuthorized(){
return localStorage.getItem(`${this.appName}-access_token`) && localStorage.getItem(`${this.appName}-uid`);
}
checkToken(){
const params = new URLSearchParams(window.location.hash.substr(1));
if(params.has("access_token")){
this.token = params.get("access_token");
this.uid = params.get("uid");
localStorage.setItem(`${this.appName}-access_token`, this.token);
localStorage.setItem(`${this.appName}-uid`, this.uid);
//cleanup hash
window.location.href.replace(/access_token=.*?&/, "");
window.location.href.replace(/uid=.*?&/, "");
window.location.href.replace(/token_type=.*?&/, "");
window.location.href.replace(/account_id=.*?&/, "");
}else{
this.token = localStorage.getItem(`${this.appName}-access_token`);
this.uid = localStorage.getItem(`${this.appName}-uid`);
}
}
download(path){
const arg = {
path : path
};
return fetch("https://content.dropboxapi.com/2/files/download", {
headers : new Headers({
"Authorization" : `Bearer ${this.token}`,
"Dropbox-API-Arg" : JSON.stringify(arg)
}),
method : "POST"
});
}
upload(content, options){
if(options.mode){
options.mode = { ".tag" : options.mode };
}
if(options.path[0] !== "/"){
options.path = "/" + options.path;
}
if(typeof(content) === "string"){
content = stringToArrayBuffer(content);
}
return fetch("https://content.dropboxapi.com/2/files/upload", {
headers : new Headers({
"Authorization" : `Bearer ${this.token}`,
"Dropbox-API-Arg" : JSON.stringify(options),
"Content-Type" : "application/octet-stream"
}),
method : "POST",
body : content
});
}
stringToArrayBuffer(string){
const arrayBuffer = new ArrayBuffer(string.length);
const uInt8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < string.length; i++) {
uInt8Array[i] = string.charCodeAt(i);
}
return arrayBuffer;
}
}
<file_sep>export function flipAcrossX(instruction, origin){
switch(instruction.type){
case "verticalLineAbsolute":
case "verticalLineRelative":
return { type: instruction.type, points: [origin - (instruction.points[0] - origin)] }
case "moveAbsolute":
case "moveRelative":
case "lineAbsolute":
return { type: instruction.type, points: [instruction.points[0], origin - (instruction.points[1] - origin)] };
case "lineRelative":
case "horizontalLineAbsolute":
case "horizontalLineRelative":
case "closePath":
return { type: instruction.type, points: instruction.points };
case "cubicCurveAbsolute":
case "cubicCurveRelative":
return { type: instruction.type, points: [
instruction.points[0],
origin - (instruction.points[1] - origin),
instruction.points[2],
origin - (instruction.points[3] - origin),
instruction.points[4],
origin - (instruction.points[5] - origin),
]};
case "S":
case "s":
case "Q":
case "q":
case "T":
case "t":
case "A":
case "a":
}
}<file_sep>const Tabs = (function() {
const defaults = {
root : null, //required
onChange : ()=>{},
hash : null
};
function create(options){
const tabs = {};
tabs.options = Object.assign({}, defaults, options);
bind(tabs);
tabs.init();
return tabs;
}
function bind(tabs){
tabs.init = init.bind(tabs);
tabs.cacheDom = cacheDom.bind(tabs);
tabs.attachEvents = attachEvents.bind(tabs);
tabs.tabClick = tabClick.bind(tabs);
tabs.showTab = showTab.bind(tabs);
tabs.updateHash = updateHash.bind(tabs);
tabs.hashChanged = hashChanged.bind(tabs);
}
function init(){
this.cacheDom();
this.attachEvents();
if(this.options.hash){
this.showTab(Util.getHashValue(tabs.options.hash) || 0);
}else{
this.showTab(0);
}
}
function cacheDom(){
this.dom = {};
this.dom.root = this.options.root;
this.dom.tabs = Array.from(this.dom.root.querySelectorAll(".tab"));
this.dom.tabContents = Array.from(this.dom.root.querySelectorAll(".tab-content"));
}
function attachEvents(){
this.dom.tabs.forEach(x => x.addEventListener("click", this.tabClick));
window.addEventListener("hashchange", this.hashChanged);
}
function tabClick(e){
var tabName = e.currentTarget.dataset.tab;
this.showTab(tabName);
}
function showTab(tabName){
this.dom.tabContents.forEach(x => x.classList.remove("selected"));
this.dom.tabs.forEach(x => x.classList.remove("selected"));
if(typeof(tabName) === "number"){
tabName = this.dom.tabContents[tabName].dataset.tab;
}
this.dom.tabContents.filter(x => x.dataset.tab === tabName)[0].classList.add("selected");
this.dom.tabs.filter(x => x.dataset.tab === tabName)[0].classList.add("selected");
this.updateHash(tabName);
this.options.onChange(tabName);
}
function updateHash(tabName){
if(this.options.hash){
var hash = getHashValue(this.options.hash);
if(hash){
window.location.href = window.location.href.replace(this.options.hash + "=" + hash, this.options.hash + "=" + tabName);
}else if(window.location.hash.length > 0){
window.location.href = window.location.href + "&" + this.options.hash + "=" + tabName;
}else{
window.location.href = window.location.href + "#" + this.options.hash + "=" + tabName;
}
}
}
function hashChanged(){
var hash = getHashValue(this.options.hash);
this.showTab(hash);
}
function getHashValue(key){
var map = getQueryMap(window.location.hash);
return map[key];
}
function getQueryMap(queryString){
var map = {};
var andSplit = queryString.split("&");
for(var i = 0; i < andSplit.length; i++){
var equalSplit = andSplit[i].split("=");
map[equalSplit[0]] = equalSplit[1];
}
return map;
}
return {
create : create
};
})();
<file_sep>import { makeAbsolute } from "../../../js/lib/svg-path/make-absolute.js";
describe("make-absolute", () => {
describe("makeAbsolute", () => {
[
{
input : [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "moveAbsolute", points: [20, 20] }
],
expectedValue : [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "moveAbsolute", points: [20, 20] }
]
},
{
input: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "moveRelative", points: [10, 10] }
],
expectedValue: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "moveAbsolute", points: [20, 20] }
]
},
{
input: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "lineAbsolute", points: [20, 20] }
],
expectedValue: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "lineAbsolute", points: [20, 20] }
]
},
{
input: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "lineRelative", points: [10, 10] }
],
expectedValue: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "lineAbsolute", points: [20, 20] }
]
},
{
input: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "horizontalLineAbsolute", points: [20] }
],
expectedValue: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "horizontalLineAbsolute", points: [20] }
]
},
{
input: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "horizontalLineRelative", points: [10] }
],
expectedValue: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "horizontalLineAbsolute", points: [20] }
]
},
{
input: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "verticalLineAbsolute", points: [20] }
],
expectedValue: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "verticalLineAbsolute", points: [20] }
]
},
{
input: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "verticalLineRelative", points: [10] }
],
expectedValue: [
{ type: "moveAbsolute", points: [10, 10] },
{ type: "verticalLineAbsolute", points: [20] }
]
}
]
.forEach(test => {
it(`should make ${test.input[1].type} absolute`, () => {
const result = makeAbsolute(test.input);
expect(result).toEqual(test.expectedValue);
});
})
});
});<file_sep>const svgns = "http://www.w3.org/2000/svg";
export function renderPolygon(height, width, points, fill, stroke, strokeWidth){
const svg = document.createElementNS(svgns, "svg");
svg.setAttributeNS(null, "height", height);
svg.setAttributeNS(null, "width", width);
const polygon = document.createElementNS(svgns, "polygon");
polygon.setAttributeNS(null, "points", points.map(p => p.join(",")).join(" "));
polygon.setAttributeNS(null, "fill", fill);
polygon.setAttributeNS(null, "stroke", stroke);
polygon.setAttributeNS(null, "stroke-width", strokeWidth);
svg.appendChild(polygon);
return svg;
}
export function renderLinePath(height, width, points, fill, stroke, strokeWidth) {
const svg = document.createElementNS(svgns, "svg");
svg.setAttributeNS(null, "height", height);
svg.setAttributeNS(null, "width", width);
const path = document.createElementNS(svgns, "path");
path.setAttributeNS(null, "d", `M${points[0][0]},${points[0][1]} ` + points.slice(1).map(([x, y]) => `L${x},${y}`).join(" ") + "Z");
path.setAttributeNS(null, "fill", fill);
path.setAttributeNS(null, "stroke", stroke);
path.setAttributeNS(null, "stroke-width", strokeWidth);
svg.appendChild(path);
return svg;
}
export function renderPath(height, width, instructions, fill, stroke, strokeWidth) {
const svg = document.createElementNS(svgns, "svg");
svg.setAttributeNS(null, "height", height);
svg.setAttributeNS(null, "width", width);
const path = document.createElementNS(svgns, "path");
path.setAttributeNS(null, "d", instructions.map(([op, ...args]) => op + args.join(" ")).join(" "));
path.setAttributeNS(null, "fill", fill);
path.setAttributeNS(null, "stroke", stroke);
path.setAttributeNS(null, "stroke-width", strokeWidth);
svg.appendChild(path);
return svg;
}<file_sep>export function stringEndsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
export function download(url, fileName){
const link = document.createElement("a");
link.href = url;
link.download = fileName;
link.click();
}
export function createDocument(cssUrl, svg){
return `
<!doctype html>
<html>
<head>
<title>svg</title>
<link rel="stylesheet" href="${cssUrl}" />
</head>
<body>
${svg}
</body>
</html>`;
}
export function normalizeFileName(fileName){
fileName = fileName || "new_svg.svg";
const dotSplit = fileName.split(".");
if(dotSplit.length == 0 || dotSplit[dotSplit.length - 1] != "svg"){
fileName += ".svg";
}
return fileName;
}
export function arrayTakeBy(array, count){
const result = [];
for(let i = 0; i < array.length; i += count){
const tuple = [];
for(let j = 0; j < count; j++){
tuple.push(array[i + j]);
}
result.push(tuple);
}
return result;
}
export function parseSvgPoints(pointsString) {
return arrayTakeBy(pointsString.split(/[,\s]/)
.map(term => term.trim())
.filter(term => term != ""), 2);
}
const domParser = new DOMParser();
export function parseXml(xmlString) {
return domParser.parseFromString(xmlString, "text/xml");
}
export function fireEvent(element, eventName, payload = null) {
const event = new CustomEvent(eventName, { detail: payload });
return element.dispatchEvent(event);
}<file_sep>export class InstructionSimplifier {
constructor() {
this.bind(this);
}
bind(instructionSimplifier) {
instructionSimplifier.simplifyInstructions = this.simplifyInstructions.bind(instructionSimplifier);
instructionSimplifier.simplifyInstruction = this.simplifyInstruction.bind(instructionSimplifier);
instructionSimplifier.moveAbsolute = this.moveAbsolute.bind(instructionSimplifier);
instructionSimplifier.moveRelative = this.moveRelative.bind(instructionSimplifier);
instructionSimplifier.lineAbsolute = this.lineAbsolute.bind(instructionSimplifier);
instructionSimplifier.lineRelative = this.lineRelative.bind(instructionSimplifier);
instructionSimplifier.horizontalLineAbsolute = this.horizontalLineAbsolute.bind(instructionSimplifier);
instructionSimplifier.horizontalLineRelative = this.horizontalLineRelative.bind(instructionSimplifier);
instructionSimplifier.verticalLineAbsolute = this.verticalLineAbsolute.bind(instructionSimplifier);
instructionSimplifier.verticalLineRelative = this.verticalLineRelative.bind(instructionSimplifier);
instructionSimplifier.cubicCurveAbsolute = this.cubicCurveAbsolute.bind(instructionSimplifier);
instructionSimplifier.cubicCurveRelative = this.cubicCurveRelative.bind(instructionSimplifier);
}
simplifyInstructions(pathInstructions) {
const simplifiedInstructions = [];
this.currentPoint = {
x: 0,
y: 0
};
for (var i = 0; i < pathInstructions.length; i++) {
simplifiedInstructions.push(...[].concat(this.simplifyInstruction(pathInstructions, i)));
}
return simplifiedInstructions;
}
simplifyInstruction(instructions, index) {
const instruction = instructions[index];
return this[instruction.type](instructions, index, ...instruction.points);
}
moveAbsolute(instructions, index, x, y) {
this.currentPoint = {
x,
y
};
return instructions[index];
}
moveRelative(instructions, index, dx, dy) {
var instruction = instructions[index];
return {
type: "moveAbsolute",
points: [this.currentPoint.x + dx, this.currentPoint.y + dy]
};
}
lineAbsolute(instructions, index, x, y) {
let last = this.currentPoint;
this.currentPoint = {
x,
y
};
return {
type: "lineAbsolute",
points: [x, y]
};
}
lineRelative(instructions, index, dx, dy) {
var instruction = instructions[index];
return {
type: "lineAbsolute",
points: [this.currentPoint.x, this.currentPoint.y, this.currentPoint.x + dx, this.currentPoint.y + dy]
};
}
horizontalLineAbsolute(instructions, index, x) {
var instruction = instructions[index];
return {
type: "lineAbsolute",
points: [this.currentPoint.x, this.currentPoint.y, x, this.currentPoint.y]
};
}
horizontalLineRelative(instructions, index, dx) {
var instruction = instructions[index];
return {
type: "lineAbsolute",
points: [this.currentPoint.x, this.currentPoint.y, this.currentPoint.x + dx, this.currentPoint.y]
};
}
verticalLineAbsolute(instructions, index, y) {
var instruction = instructions[index];
return {
type: "lineAbsolute",
points: [this.currentPoint.x, this.currentPoint.y, this.currentPoint.x, y]
};
}
verticalLineRelative(instructions, index, dy) {
var instruction = instructions[index];
return {
type: "lineAbsolute",
points: [this.currentPoint.x, this.currentPoint.y, this.currentPoint.x, this.currentPoint.y + dy]
};
}
cubicCurveAbsolute(instructions, index, startCX, startCY, endCX, endCY, x, y) {
this.currentPoint = {
x: x,
y: y
};
return instructions[index];
}
cubicCurveRelative(instructions, index, startCX, startCY, endCX, endCY, dx, dy) {
var instruction = instructions[index];
return {
type: "cubicCurveAbsolute",
points: [startCX, startCY, endCX, endCY, this.currentPoint.x + dx, this.currentPoint.y + dy]
};
}
cubicCurveShortAbsolute(instructions, index, endCX, endCY, x, y) {
var instruction = instructions[index];
return {
type: "cubicCurveAbsolute",
points: [startCX, startCY, endCX, endCY, this.currentPoint.x + dx, this.currentPoint.y + dy]
};
}
closePath(instructions, index){
return instructions[index];
}
}<file_sep>import { SvgPathParser } from "../../../js/lib/svg-path/svg-path-parser.js";
describe("svg-path-parser", () => {
it("should tokenize path", () => {
const svgPathParser = new SvgPathParser();
const result = svgPathParser.tokenizePath("C-0.171767888,10.638723 -0.238720425,11.6876357 0.617810306,11.6411804");
expect(result).toEqual([
"C",
"-0.171767888",
"10.638723",
"-0.238720425",
"11.6876357",
"0.617810306",
"11.6411804"
]);
});
it("should parse M", () => {
const svgPathParser = new SvgPathParser();
const result = svgPathParser.parsePath("M0.61319289,10.4895769");
expect(result[0]).toEqual({
points: [0.61319289, 10.4895769],
type: "moveAbsolute"
});
});
it("should parse C", () => {
const svgPathParser = new SvgPathParser();
const result = svgPathParser.parsePath("C-0.171767888,10.638723 -0.238720425,11.6876357 0.617810306,11.6411804");
expect(result[0]).toEqual({
points: [-0.171767888, 10.638723, -0.238720425, 11.6876357, 0.617810306, 11.6411804],
type: "cubicCurveAbsolute"
});
});
});<file_sep>export function empty(node){
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
}<file_sep>class SpNav extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
const details = Array.from(this.querySelectorAll("details"));
details.forEach(d =>{
d.addEventListener("click", e => {
details.filter(d => d !== e.target).forEach(d => d.removeAttribute("open"));
});
});
}
}
customElements.define("sp-nav", SpNav);
<file_sep>import { renderPolygon, renderLinePath } from "../lib/render-poly.js";
import { fireEvent } from "../lib/utilities.js";
customElements.define("wc-polygon-generator",
class extends HTMLElement {
constructor(){
super();
this.bind(this);
}
bind(element){
element.attachEvents = element.attachEvents.bind(element);
element.render = element.render.bind(element);
element.cacheDom = element.cacheDom.bind(element);
element.generate = element.generate.bind(element);
element.finish = element.finish.bind(element);
}
connectedCallback(){
this.render();
this.cacheDom();
this.attachEvents();
this.generate();
}
render(){
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = `
<link rel="stylesheet" href="css/system.css">
<style>
:host { display: grid; grid-template-columns: [form] 50% [output] 50%; }
fieldset { padding: 0px; margin-bottom: 0.5rem; }
#form { grid-column: form; }
#output { grid-column: output; border: 1px solid black; background-image: var(--checker); background-size:20px 20px;
background-position: 0 0, 0 10px, 10px -10px, 10px 0px; }
.button-container { display: flex; }
</style>
<div id="form">
<fieldset>
<label for="side-count">Sides:</label>
<input id="side-count" type="phone" value="3" />
</fieldset>
<fieldset>
<label for="radius">Radius:</label>
<input id="radius" value="25" />
</fieldset>
<fieldset>
<label for="rotation">Rotation:</label>
<input id="rotation" value="0" />
</fieldset>
<fieldset>
<label for="stroke">Stroke:</label>
<input id="stroke" value="black" />
</fieldset>
<fieldset>
<label for="stroke-width">Stroke Width:</label>
<input id="stroke-width" value="1" />
</fieldset>
<fieldset>
<label for="fill">Fill:</label>
<input id="fill" value="transparent" />
</fieldset>
<fieldset>
<label for="render-type">Render Type:</label>
<select id="render-type">
<option value="polygon">Polygon</option>
<option value="path">Path</option>
</select>
</fieldset>
<div class="button-container">
<button id="finish">Finish</button>
</div>
</div>
<div id="output"></div>
`
}
cacheDom(){
this.dom = {
sideCount : this.shadowRoot.querySelector("#side-count"),
radius : this.shadowRoot.querySelector("#radius"),
rotation: this.shadowRoot.querySelector("#rotation"),
stroke: this.shadowRoot.querySelector("#stroke"),
strokeWidth: this.shadowRoot.querySelector("#stroke-width"),
fill: this.shadowRoot.querySelector("#fill"),
renderType: this.shadowRoot.querySelector("#render-type"),
finish: this.shadowRoot.querySelector("#finish"),
output: this.shadowRoot.querySelector("#output")
};
}
attachEvents(){
this.dom.sideCount.addEventListener("input", this.generate);
this.dom.radius.addEventListener("input", this.generate);
this.dom.rotation.addEventListener("input", this.generate);
this.dom.stroke.addEventListener("input", this.generate);
this.dom.strokeWidth.addEventListener("input", this.generate);
this.dom.fill.addEventListener("input", this.generate);
this.dom.renderType.addEventListener("change", this.generate);
this.dom.finish.addEventListener("click", this.finish);
}
generate(){
const sideCount = parseInt(this.dom.sideCount.value, 10);
const anglePerSide = 2 * Math.PI / sideCount;
const radius = parseFloat(this.dom.radius.value);
const rotation = parseFloat(this.dom.rotation.value) * Math.PI/180;
const stroke = this.dom.stroke.value;
const strokeWidth = parseFloat(this.dom.strokeWidth.value);
const fill = this.dom.fill.value;
const renderType = this.dom.renderType.value;
const polarPoints = [];
let currentTheta = rotation;
for(let i = 0; i < sideCount; i++){
polarPoints.push([radius, currentTheta]);
currentTheta += anglePerSide;
}
const normalizedPoints = polarPoints.map(([r,theta]) => [r * Math.cos(theta) + radius, r * Math.sin(theta) + radius]);
const svg = renderType === "polygon"
? renderPolygon(radius * 2, radius * 2, normalizedPoints, fill, stroke, strokeWidth)
: renderLinePath(radius * 2, radius * 2, normalizedPoints, fill, stroke, strokeWidth);
this.dom.output.innerHTML = "";
this.dom.output.appendChild(svg);
}
finish(){
const svg = this.dom.output.querySelector("svg");
fireEvent(this, "polygon-generated", svg ? svg.innerHTML : null);
}
}
)
<file_sep>import { flipAcrossX } from "../../../js/lib/svg-path/path-transformer.js";
describe("path-transformer", () => {
describe("flipAcrossX", () => {
[
{
input: { type: "moveAbsolute", points: [10, 10] },
origin: 5,
expectedValue: { type: "moveAbsolute", points: [10, 0]}
},
{
input: { type: "moveAbsolute", points: [10, 10] },
origin: 7,
expectedValue: { type: "moveAbsolute", points: [10, 4] }
},
{
input: { type: "moveAbsolute", points: [10, -10] },
origin: 7,
expectedValue: { type: "moveAbsolute", points: [10, 24] }
},
{
input: { type: "moveRelative", points: [10, 10] },
origin: 5,
expectedValue: { type: "moveRelative", points: [10, 0] }
},
{
input: { type: "moveRelative", points: [10, 10] },
origin: 15,
expectedValue: { type: "moveRelative", points: [10, 20] }
},
{
input: { type: "lineAbsolute", points: [10, 10] },
origin: 5,
expectedValue: { type: "lineAbsolute", points: [10, 0] }
},
{
input: { type: "lineRelative", points: [10, 10] },
origin: 5,
expectedValue: { type: "lineRelative", points: [10, 0] }
},
{
input: { type: "horizontalLineAbsolute", points: [10] },
origin: 5,
expectedValue: { type: "horizontalLineAbsolute", points: [10] }
},
{
input: { type: "horizontalLineRelative", points: [10] },
origin: 5,
expectedValue: { type: "horizontalLineRelative", points: [10] }
},
{
input: { type: "verticalLineAbsolute", points: [10] },
origin: 5,
expectedValue: { type: "verticalLineAbsolute", points: [0] }
},
{
input: { type: "verticalLineRelative", points: [10] },
origin: 5,
expectedValue: { type: "verticalLineRelative", points: [0] }
},
{
input: { type: "cubicCurveAbsolute", points: [10, 10, 5, 5, 15, 15] },
origin: 5,
expectedValue: { type: "cubicCurveAbsolute", points: [10, 0, 5, 5, 15, -5] }
},
{
input: { type: "cubicCurveRelative", points: [10, 10, 5, 5, 15, 15] },
origin: 5,
expectedValue: { type: "cubicCurveRelative", points: [10, 0, 5, 5, 15, -5] }
},
].forEach(x =>
it(`should flip [${JSON.stringify(x.input)}] around ${x.origin}`, () => {
expect(flipAcrossX(x.input, x.origin)).toEqual(x.expectedValue);
}));
});
});<file_sep>customElements.define("wc-svg-canvas",
class svgcanvas extends HTMLElement {
static get observedAttributes(){
return [];
}
constructor(){
super();
this.bind(this);
}
bind(element){
element.render = element.render.bind(element);
element.cacheDom = element.cacheDom.bind(element);
}
connectedCallback(){
this.render();
this.cacheDom();
}
render(){
this.attachShadow({ mode: "open" });
}
update(svg, css){
const styleSheet = new CSSStyleSheet();
styleSheet.replaceSync(css);
this.shadowRoot.adoptedStyleSheets = [styleSheet];
this.shadowRoot.innerHTML = svg;
}
cacheDom(){
this.dom = {};
}
}
)
<file_sep>"use strict";
var Keyboard = (function(){
var keyMapper = { //unfinished
13 : "enter",
16 : "shift",
17 : "ctrl",
18 : "alt",
27 : "esc",
32 : "space",
37 : "left",
38 : "up",
39 : "right",
40 : "down",
49 : "one",
50 : "two",
51 : "three",
52 : "four",
53 : "five",
65 : "six",
67 : "seven",
68 : "eight",
69 : "nine",
192 : "tilde"
};
var keyName = {
"enter" : 13,
"shift" : 16,
"ctrl" : 17,
"alt" : 18,
"esc" : 27,
"space" : 32,
"left" : 37,
"up" : 38,
"right" : 39,
"down" : 40,
"one" : 49,
"two" : 50,
"three" : 51,
"four" : 52,
"five" : 53,
"six" : 54,
"seven" : 55,
"eight" : 56,
"nine" : 57,
"tilde" : 192
}
var pressedKeys = {};
var unhandledKeys = {};
var handlers = {};
document.addEventListener("keydown", function(e){
var key = keyMapper[e.which];
var stroke = mapStroke(e);
pressedKeys[key] = true;
if(handlers[stroke]){
handlers[stroke]();
}else{
unhandledKeys[key] = true;
}
}, true);
document.addEventListener("keyup", function(e){
var key = keyMapper[e.which];
pressedKeys[key] = false;
unhandledKeys[key] = false;
}, true);
function mapStroke(e){
var key = keyMapper[e.which];
var stroke = key;
if(e.shiftKey && key != "shift"){
stroke = "shift+" + stroke;
}
if(e.altKey && key != "alt"){
stroke = "alt+" + stroke;
}
if(e.ctrlKey && key != "ctrl"){
stroke = "ctrl+" + stroke;
}
return stroke;
}
function isAnyPressed(){
for(var key in pressedKeys){
if(pressedKeys[key]){
return true;
}
}
return false;
}
function register(key, handler){
handlers[key] = handler;
}
return {
pressedKeys: pressedKeys,
unhandledKeys : unhandledKeys,
isAnyKeyPressed: isAnyPressed,
register : register
};
})();<file_sep>export function makeAbsolute(instructions) {
const absoluteInstructions = [];
let currentPoint = [0, 0];
for (let instruction of instructions) {
let absoluteInstruction;
switch (instruction.type) {
case "moveRelative": {
absoluteInstruction = {
type: "moveAbsolute",
points: [currentPoint[0] + instruction.points[0], currentPoint[1] + instruction.points[1]]
};
currentPoint = [absoluteInstruction.points[0], absoluteInstruction.points[1]];
break;
}
case "lineRelative": {
absoluteInstruction = {
type: "lineAbsolute",
points: [currentPoint[0] + instruction.points[0], currentPoint[1] + instruction.points[1]]
};
currentPoint = [absoluteInstruction.points[0], absoluteInstruction.points[1]];
break;
}
case "moveAbsolute": {
absoluteInstruction = {
type: "moveAbsolute",
points: [...instruction.points]
}
currentPoint = [absoluteInstruction.points[0], absoluteInstruction.points[1]];
break;
}
case "lineAbsolute": {
absoluteInstruction = {
type: "lineAbsolute",
points: [...instruction.points]
}
currentPoint = [absoluteInstruction.points[0], absoluteInstruction.points[1]];
break;
}
case "horizontalLineRelative": {
absoluteInstruction = {
type: "horizontalLineAbsolute",
points: [currentPoint[0] + instruction.points[0]]
};
currentPoint = [absoluteInstruction.points[0], currentPoint[1]];
break;
}
case "horizontalLineAbsolute": {
absoluteInstruction = {
type: "horizontalLineAbsolute",
points: [instruction.points[0]]
}
currentPoint = [absoluteInstruction.points[0], currentPoint[1]];
break;
}
case "verticalLineRelative": {
absoluteInstruction = {
type: "verticalLineAbsolute",
points: [currentPoint[1] + instruction.points[0]]
};
currentPoint = [currentPoint[0], absoluteInstruction.points[0]];
break;
}
case "verticalLineAbsolute": {
absoluteInstruction = {
type: "verticalLineAbsolute",
points: [instruction.points[0]]
};
currentPoint = [currentPoint[0], absoluteInstruction.points[0]];
break;
}
case "cubicCurveRelative": {
absoluteInstruction = {
type: "cubicCurveAbsolute",
points: [currentPoint[0] + instruction.points[0], currentPoint[1] + instruction.points[1], currentPoint[0] + instruction.points[2], currentPoint[1] + instruction.points[3], currentPoint[0] + instruction.points[4], currentPoint[1] + instruction.points[5]]
};
currentPoint = [absoluteInstruction.points[4], absoluteInstruction.points[5]];
break;
}
case "cubicCurveAbsolute": {
absoluteInstruction = {
type: "cubicCurveAbsolute",
points: [...instruction.points]
};
currentPoint = [absoluteInstruction.points[4], absoluteInstruction.points[5]];
break;
}
case "smoothCurveRelative": {
absoluteInstruction = {
type: "smoothCurveAbsolute",
points: [currentPoint[0] + instruction.points[0], currentPoint[1] + instruction.points[1], currentPoint[0] + instruction.points[2], currentPoint[1] + instruction.points[3]],
}
currentPoint = [absoluteInstruction.points[2], absoluteInstruction.points[3]];
break;
}
case "smoothCurveAbsolute": {
absoluteInstruction = {
type: "smoothCurveAbsolute",
points: [...instruction.points]
};
currentPoint = [absoluteInstruction.points[2], absoluteInstruction.points[3]];
break;
}
case "quadraticCurveRelative": {
absoluteInstruction = {
type: "quadraticCurveAbsolute",
points: [currentPoint[0] + instruction.points[0], currentPoint[1] + instruction.points[1], currentPoint[0] + instruction.points[2], currentPoint[1] + instruction.points[3]],
}
currentPoint = [absoluteInstruction.points[2], absoluteInstruction.points[3]];
break;
}
case "quadraticCurveAbsolute": {
absoluteInstruction = {
type: "quadraticCurveAbsolute",
points: [...instruction.points]
};
currentPoint = [absoluteInstruction.points[2], absoluteInstruction.points[3]];
break;
}
case "smoothQuadraticRelative": {
absoluteInstruction = {
type: "smoothQuadraticAbsolute",
points: [currentPoint[0] + instruction.points[0], currentPoint[1] + instruction.points[1]],
}
currentPoint = [absoluteInstruction.points[0], absoluteInstruction.points[1]];
break;
}
case "smoothQuadraticAbsolute": {
absoluteInstruction = {
type: "smoothQuadraticAbsolute",
points: [...instruction.points]
};
currentPoint = [absoluteInstruction.points[0], absoluteInstruction.points[1]];
break;
}
case "arcRelative": {
absoluteInstruction = {
type: "arcAbsolute",
points: [instruction.points[0], instruction.points[1], instruction.points[2], instruction.points[3], instruction.points[4], currentPoint[0] + instruction.points[5], currentPoint[1] + instruction.points[6]],
}
currentPoint = [absoluteInstruction.points[0], absoluteInstruction.points[1]];
break;
}
case "arcAbsolute": {
absoluteInstruction = {
type: "arcAbsolute",
points: [...instruction.points]
};
currentPoint = [absoluteInstruction.points[0], absoluteInstruction.points[1]];
break;
}
case "closePath":
//currentPoint = startingPoint
break;
}
absoluteInstructions.push(absoluteInstruction);
}
return absoluteInstructions;
}<file_sep>import { SvgPathParser } from "../../js/lib/svg-path/svg-path-parser.js";
import { InstructionSimplifier } from "../../js/lib/svg-path/instruction-simplifier.js";
import { flipAcrossX } from "../../js/lib/svg-path/path-transformer.js";
import { CanvasRenderer } from "../../js/lib/svg-path/canvas-renderer.js";
const pathParser = new SvgPathParser();
const instructionSimplifier = new InstructionSimplifier();
Array.from(document.querySelectorAll("section"))
.forEach(section => {
const path = section.querySelector("svg path");
const data = path.getAttribute("d");
const instructions = pathParser.parsePath(data);
const simplifiedInstructions = instructionSimplifier.simplifyInstructions(instructions);
const invertedInstructions = simplifiedInstructions.map(i => flipAcrossX(i, 10));
const canvasRenderer = new CanvasRenderer();
canvasRenderer.canvas.width = 20;
canvasRenderer.canvas.height = 20;
canvasRenderer.drawInstructionList(invertedInstructions, { fillColor: "#000", strokeWidth: 0 });
section.appendChild(canvasRenderer.canvas);
});<file_sep>customElements.define("service-worker",
class extends HTMLElement {
static get observedAttributes() {
return ["url", "scope"];
}
constructor(){
super();
this.attrs = {};
this.installServiceWorker();
}
async installServiceWorker(){
if("serviceWorker" in navigator){
try {
const serviceWorker = await navigator.serviceWorker.register(this.url, {scope: this.scope});
this.serviceWorkerInstalled(serviceWorker);
}catch(ex){
this.serviceWorkerInstallFailed(ex);
}
}
}
serviceWorkerInstalled(registration){
console.log("App Service registration successful with scope:", registration.scope);
}
serviceWorkerInstallFailed(error){
console.error("App Service failed to install", error);
}
attributeChangedCallback(name, oldValue, newValue) {
this.attrs[name] = newValue;
}
get url(){
return this.attrs.url || "service-worker.js";
}
set url(value){
this.attrs.url = value;
}
get scope(){
return this.attrs.scope || "./";
}
set scope(value){
this.attrs.scope = value;
}
});
<file_sep>import { parseSvgPoints, parseXml } from "./utilities.js";
import { CanvasRenderer } from "./svg-path/canvas-renderer.js";
import { InstructionSimplifier } from "./svg-path/instruction-simplifier.js";
import { SvgPathParser } from "./svg-path/svg-path-parser.js";
function getAsClipPath(element) {
return {
id: element.id,
elements: element.childNodes
};
}
function getAttrs(element, attributeNames = []) {
const attrs = {
stroke: getAttr(element, "stroke"),
strokeWidth: getAttr(element, "stroke-width"),
fill: getAttr(element, "fill"),
clipPath: getUrlAttr(element, "clip-path")
};
for (let attrName of attributeNames) {
attrs[attrName] = getAttr(element, attrName);
}
return attrs;
}
function getAttr(element, name, defaultValue = null) {
const attr = element.attributes[name]
if (attr) {
return attr.value;
}
if (element.style && element.style[name]) {
return element.style[name];
}
return defaultValue;
}
function getUrlAttr(element, name) {
return getAttr(element, name, "")
.replace(/url\(/, "")
.replace(")", "")
.replace(/^#/, "");
}
function getFont(element) {
const family = getAttr(element, "font-family", "Times New Roman");
const weight = getAttr(element, "font-weight");
const style = getAttr(element, "font-style");
let size = getAttr(element, "font-size", "16px");
if (!isNaN(size)) {
size = size + "px";
}
return [style, weight, size, family]
.filter(x => x)
.map(x => x.trim())
.join(" ");
}
function setContext(context, attrs) {
context.lineWidth = attrs.strokeWidth;
context.strokeStyle = attrs.stroke;
context.fillStyle = attrs.fill;
}
function setCanvasAttributes(canvas, svgElement){
const height = getAttr(svgElement, "height", 2000);
const width = getAttr(svgElement, "width", 2000);
canvas.setAttribute("height", height);
canvas.setAttribute("width", width);
}
function strokeAndFill(attrs, scope) {
if (attrs.fill) {
scope.context.fill();
}
if (attrs.stroke) {
scope.context.stroke();
}
}
function normalizeTextCoordinates(attrs, width){
switch(attrs["text-anchor"]){
case "middle" :
return { ...attrs, ...{ x: (parseFloat(attrs.x) - width/2) } };
case "end" :
return { ...attrs, ...{ x: (parseFloat(attrs.x) - width) } };
default:
return attrs;
}
}
export class SvgToCanvas {
constructor(canvas) {
this.canvas = canvas || document.createElement("canvas");
this.bind(this);
this.svgPathParser = new SvgPathParser();
this.instructionSimplifier = new InstructionSimplifier();
this.canvasRenderer = new CanvasRenderer(this.canvas);
}
bind(svgToCanvas) {
svgToCanvas.render = this.render.bind(svgToCanvas);
svgToCanvas.drawAtomic = this.drawAtomic.bind(svgToCanvas);
svgToCanvas.drawElement = this.drawElement.bind(svgToCanvas);
svgToCanvas.drawContainer = this.drawContainer.bind(svgToCanvas);
svgToCanvas.drawPath = this.drawPath.bind(svgToCanvas);
svgToCanvas.drawText = this.drawText.bind(svgToCanvas);
svgToCanvas.drawLine = this.drawLine.bind(svgToCanvas);
svgToCanvas.drawRectangle = this.drawRectangle.bind(svgToCanvas);
svgToCanvas.drawPolygon = this.drawPolygon.bind(svgToCanvas);
svgToCanvas.drawEllipse = this.drawEllipse.bind(svgToCanvas);
svgToCanvas.drawCircle = this.drawCircle.bind(svgToCanvas);
svgToCanvas.drawOval = this.drawOval.bind(svgToCanvas);
svgToCanvas.clip = this.clip.bind(svgToCanvas);
}
render(svgText) {
const svgDoc = parseXml(svgText);
const svgElement = svgDoc.childNodes[0];
const context = this.canvasRenderer.context;
const canvas = context.canvas;
setCanvasAttributes(canvas, svgElement);
this.drawElement(svgElement, {
document: svgDoc,
context: context,
defs: {
clipPaths: {}
}
});
return canvas;
}
drawElement(element, scope) {
switch (element.nodeName) {
case "defs":
case "svg":
case "g":
this.drawAtomic(this.drawContainer, element, scope);
break;
case "text":
this.drawAtomic(this.drawText, element, scope);
break;
case "line":
this.drawAtomic(this.drawLine, element, scope);
break;
case "polyline":
this.drawAtomic(this.drawPolyline, element, scope);
break;
case "polygon":
this.drawAtomic(this.drawPolygon, element, scope)
break;
case "path":
this.drawAtomic(this.drawPath, element, scope);
break;
case "rect":
this.drawAtomic(this.drawRectangle, element, scope);
break;
case "circle":
this.drawAtomic(this.drawCircle, element, scope);
break;
case "ellipse":
this.drawAtomic(this.drawEllipse, element, scope);
break;
case "clipPath":
const clipPath = getAsClipPath(element);
scope.defs.clipPaths[clipPath.id] = clipPath.elements;
break;
case "title":
case "#text":
return; //no-op, non-visual content
default:
console.error("No implementation for element: " + element.nodeName)
}
}
drawAtomic(drawFunc, element, scope) {
const clipPath = getUrlAttr(element, "clip-path");
scope.context.save();
if (clipPath) {
this.clip(scope.defs.clipPaths[clipPath], scope);
}
drawFunc.call(this, element, scope);
scope.context.restore();
}
clip(clipPath, scope) {
scope.context.beginPath();
for (let element of clipPath) {
this.drawElement(element, scope);
}
scope.context.clip();
}
drawContainer(element, scope) {
const attrs = getAttrs(element);
if (attrs.clipPath) {
this.clip(scope.defs.clipPaths[attrs.clipPath], scope);
}
for (var i = 0; i < element.childNodes.length; i++) {
var el = element.childNodes[i];
this.drawElement(el, scope);
}
}
drawRectangle(element, scope) {
const attrs = getAttrs(element, ["x", "y", "height", "width"]);
setContext(scope.context, attrs);
scope.context.rect(attrs.x, attrs.y, attrs.width, attrs.height);
strokeAndFill(attrs, scope);
}
drawPolyline(element, scope) {
const attrs = getAttrs(element, ["points"]);
const points = parseSvgPoints(attrs.points);
setContext(scope.context, attrs);
scope.context.beginPath();
scope.context.moveTo(points[0][0], points[0][1]);
for (let i = 1; i < points.length; i++) {
scope.context.lineTo(points[i][0], points[i][1]);
}
scope.context.stroke();
}
drawPolygon(element, scope) {
const attrs = getAttrs(element, ["points"]);
const points = parseSvgPoints(attrs.points);
setContext(scope.context, attrs);
scope.context.beginPath();
scope.context.moveTo(points[0][0], points[0][1]);
for (let i = 1; i < points.length; i++) {
scope.context.lineTo(points[i][0], points[i][1]);
}
scope.context.closePath();
strokeAndFill(attrs, scope);
}
drawCircle(element, scope) {
const attrs = getAttrs(element, ["cx", "cy", "r"]);
setContext(scope.context, attrs);
scope.context.beginPath();
scope.context.arc(attrs.cx, attrs.cy, attrs.r, 0, Math.PI * 2, true);
scope.context.closePath();
strokeAndFill(attrs, scope);
}
drawEllipse(element, scope) {
const attrs = getAttrs(element, ["cx", "cy", "rx", "ry"]);
setContext(scope.context, attrs);
drawOval(attrs.cx, attrs.cy, attrs.rx, attrs.ry, scope);
strokeAndFill(attrs, scope);
}
drawOval(cx, cy, rx, ry, scope) {
scope.context.beginPath();
scope.context.translate(cx - rx, cy - ry);
scope.context.scale(rx, ry);
scope.context.arc(1, 1, 1, 0, 2 * Math.PI, false);
}
drawLine(element, scope) {
const attrs = getAttrs(element, ["x1", "x2", "y1", "y2"]);
setContext(scope.context, attrs);
scope.context.beginPath();
scope.context.moveTo(attrs.x1, attrs.y1);
scope.context.lineTo(attrs.x2, attrs.y2);
strokeAndFill(attrs, scope);
}
drawText(element, scope) {
const attrs = getAttrs(element, ["x", "y", "text-anchor"]);
const font = getFont(element);
scope.context.font = font;
const textContent = element.textContent;
const width = scope.context.measureText(textContent).width;
const transformedAttrs = normalizeTextCoordinates(attrs, width);
scope.context.fillText(textContent, transformedAttrs.x, transformedAttrs.y);
if (attrs.stroke) {
context.strokeText(textContent, transformedAttrs.x, transformedAttrs.y);
}
}
drawPath(element, scope) {
const attrs = getAttrs(element, ["d"]);
const instructionList = this.instructionSimplifier.simplifyInstructions(this.svgPathParser.parsePath(attrs.d));
this.canvasRenderer.drawInstructionList(instructionList, {
stroke: attrs.stroke || "#000",
strokeWidth: attrs.strokeWidth,
fillColor: attrs.fill
});
}
} | 19a6b21eed0d7274e78807aa948ff105b76c912a | [
"JavaScript",
"Text",
"Markdown"
] | 21 | JavaScript | Somnid/svg-pad | 92f21a8593bdf02f98b1d1dd5cac4f45355662ab | 8e1cc1b03cc3587c4f62b57ae46f1098bfa8517f |
refs/heads/master | <repo_name>anandvarkeyphilips/PackageTrack<file_sep>/src/main/java/com/jits/shipping/constants/AppConstants.java
package com.jits.shipping.constants;
/**
* Created by <NAME> on 6/1/2018.
*/
public class AppConstants {
public static final String[] validShipMethods = {"GRD","AIR","RAL"};
}
<file_sep>/src/main/java/com/jits/shipping/entity/Package.java
package com.jits.shipping.entity;
import java.util.Comparator;
/**
* Created by <NAME> on 5/31/2018.
*/
public class Package {
private String id;
private String shipMethod;
private String fromZip;
private String toZip;
private Float weight;
private int height;
private int width;
private int depth;
private String other;
private String hazards;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getShipMethod() {
return shipMethod;
}
public void setShipMethod(String shipMethod) {
this.shipMethod = shipMethod;
}
public String getFromZip() {
return fromZip;
}
public void setFromZip(String fromZip) {
this.fromZip = fromZip;
}
public String getToZip() {
return toZip;
}
public void setToZip(String toZip) {
this.toZip = toZip;
}
public Float getWeight() {
return weight;
}
public void setWeight(Float weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getDepth() {
return depth;
}
public void setDepth(int depth) {
this.depth = depth;
}
public String getOther() {
return other;
}
public void setOther(String other) {
this.other = other;
}
public String getHazards() {
return hazards;
}
public void setHazards(String hazards) {
this.hazards = hazards;
}
public static Comparator<Package> idComparator = new Comparator<Package>() {
@Override
public int compare(Package p1, Package p2) {
return (int) (p1.getId().compareTo(p2.getId()));
}
};
}
<file_sep>/src/test/java/com/jits/shipping/helper/PackageHandlerHelperTest.java
package com.jits.shipping.helper;
import com.jits.shipping.exceptions.ValidationException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Created by <NAME> on 5/31/2018.
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class PackageHandlerHelperTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Autowired
private PackageHandlerHelper packageHandlerHelper;
//Format ID|GRD|FROMZIP|TOZIP|WEIGHT|HEIGHT|WIDTH|DEPTH|OTHER|HAZARD
//Valid Example 012345678901234567|GRD|12345|67890|12345|67890|12345|67890|OTHER|HAZARD
@Test
public void addNewPackageTestSuccessful() throws Exception {
packageHandlerHelper.validateAndAddPackage("012345678901234567|GRD|12345|67890|12345|67890|12345|67890|OTHER|HAZARD");
}
@Test
public void addNewPackageTestInvalidShipMethod() throws Exception {
exception.expect(ValidationException.class);
exception.expectMessage("Invalid Shipment Method");
packageHandlerHelper.validateAndAddPackage("012345678901234567|GRC|12345|67890|12345|67890|12345|67890|OTHER|HAZARD");
}
@Test
public void addNewPackageTestInvalidFromZipCode() throws Exception {
exception.expect(ValidationException.class);
exception.expectMessage("Invalid From Zip Code");
packageHandlerHelper.validateAndAddPackage("012345678901234567|GRD|wrong|67890|12345|67890|12345|67890|OTHER|HAZARD");
}
@Test
public void addNewPackageTestInvalidToZipCode() throws Exception {
exception.expect(ValidationException.class);
exception.expectMessage("Invalid To Zip Code");
packageHandlerHelper.validateAndAddPackage("012345678901234567|GRD|12345|wrong|12345|67890|12345|67890|OTHER|HAZARD");
}
@Test
public void addNewPackageTestCorrectWeight() throws Exception {
packageHandlerHelper.validateAndAddPackage("012345678901234567|GRD|12345|67890|30.0|67890|12345|67890|OTHER|HAZARD");
}
@Test
public void addNewPackageTestInvalidWeight() throws Exception {
exception.expect(ValidationException.class);
exception.expectMessage("Invalid Weight");
packageHandlerHelper.validateAndAddPackage("012345678901234567|GRD|12345|67890|abc|67890|12345|67890|OTHER|HAZARD");
}
@Test
public void addNewPackageTestInvalidHeight() throws Exception {
exception.expect(ValidationException.class);
exception.expectMessage("Invalid Height");
packageHandlerHelper.validateAndAddPackage("012345678901234567|GRD|12345|67890|0.20|wrng|12345|67890|OTHER|HAZARD");
}
@Test
public void addNewPackageTestInvalidDataExtra() throws Exception {
exception.expect(ValidationException.class);
exception.expectMessage("The Barcode is having invalid number of details");
packageHandlerHelper.validateAndAddPackage("012345678901234567|GRD|12345|67890|0.20|wrng|12345|67890|OTHER|HAZARD|EXTRA");
}
}<file_sep>/src/main/java/com/jits/shipping/helper/InformationLookupHelper.java
package com.jits.shipping.helper;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* Created by 1509967 on 6/4/2018.
*/
@Component
public class InformationLookupHelper {
private Map<String, String> statesToDistributionCentreMap = new HashMap<>();
{
statesToDistributionCentreMap.put("AL", "DC2");
statesToDistributionCentreMap.put("AK", "DC3");
statesToDistributionCentreMap.put("AZ", "DC3");
statesToDistributionCentreMap.put("AR", "DC1");
statesToDistributionCentreMap.put("CA", "DC3");
statesToDistributionCentreMap.put("CO", "DC3");
statesToDistributionCentreMap.put("CT", "DC1");
statesToDistributionCentreMap.put("DE", "DC1");
statesToDistributionCentreMap.put("DC", "DC1");
statesToDistributionCentreMap.put("FL", "DC1");
statesToDistributionCentreMap.put("GA", "DC1");
statesToDistributionCentreMap.put("HI", "NA");
statesToDistributionCentreMap.put("ID", "DC3");
statesToDistributionCentreMap.put("IL", "DC2");
statesToDistributionCentreMap.put("IN", "DC2");
statesToDistributionCentreMap.put("IA", "DC2");
statesToDistributionCentreMap.put("KS", "DC3");
statesToDistributionCentreMap.put("KY", "DC2");
statesToDistributionCentreMap.put("LA", "DC2");
statesToDistributionCentreMap.put("ME", "DC1");
statesToDistributionCentreMap.put("MD", "DC1");
statesToDistributionCentreMap.put("MA", "DC1");
statesToDistributionCentreMap.put("MI", "DC2");
statesToDistributionCentreMap.put("MN", "DC2");
statesToDistributionCentreMap.put("MS", "DC2");
statesToDistributionCentreMap.put("MO", "DC2");
statesToDistributionCentreMap.put("MT", "DC3");
statesToDistributionCentreMap.put("NE", "DC3");
statesToDistributionCentreMap.put("NV", "DC3");
statesToDistributionCentreMap.put("NH", "DC1");
statesToDistributionCentreMap.put("NJ", "DC1");
statesToDistributionCentreMap.put("NM", "DC3");
statesToDistributionCentreMap.put("NY", "DC1");
statesToDistributionCentreMap.put("NC", "DC1");
statesToDistributionCentreMap.put("ND", "DC3");
statesToDistributionCentreMap.put("OH", "DC1");
statesToDistributionCentreMap.put("OK", "DC3");
statesToDistributionCentreMap.put("OR", "DC3");
statesToDistributionCentreMap.put("PA", "DC1");
statesToDistributionCentreMap.put("RI", "DC1");
statesToDistributionCentreMap.put("SC", "DC1");
statesToDistributionCentreMap.put("SD", "DC3");
statesToDistributionCentreMap.put("TN", "DC1");
statesToDistributionCentreMap.put("TX", "DC3");
statesToDistributionCentreMap.put("UT", "DC3");
statesToDistributionCentreMap.put("VT", "DC1");
statesToDistributionCentreMap.put("VA", "DC1");
statesToDistributionCentreMap.put("WA", "DC2");
statesToDistributionCentreMap.put("WV", "DC1");
statesToDistributionCentreMap.put("WI", "DC2");
statesToDistributionCentreMap.put("WY", "DC3");
}
public String getDistributionCentre(String stateCode) {
return statesToDistributionCentreMap.get(stateCode);
}
}
| c5e14028d18e5f247aebf0e9fd2bdd94356ef262 | [
"Java"
] | 4 | Java | anandvarkeyphilips/PackageTrack | 694f99d9225b26c683c36433a4db67081660b853 | b741d6dad8b6ffa7e903f159a05f006ec33e9549 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.